text:
Q: Refresh a tab and not the ReactJs Ajax page I am currently experiencing a problem. I use ReactJs and Ajax but the problem is that on the same page I have 4 tabs. Each tab is a page.
To summarize I have a page that matters 4.
Except that in one of its tabs I have to delete a credit card so once I select the card and I click on the delete button I want it refreshes that my tab but he raffrachi the main page and my tab n ' is more open. So I thought about putting a location.reload () but it refreshed the whole page and does not solve my problem because the active tab closes.
I give you the code and some pictures for understanding.
Before refresh:
enter image description here
After refresh:
enter image description here
While I want it refreshes only tab "means of payment" here is my code:
handleCardDelete = () => {
var numCard = $('input[name=rbCard]:checked').val();
console.log(this.state.token);
 $.ajax({
    url: 'http://API.....,

    dataType: 'json',

    type: 'DELETE',

    headers: {
        'Authorization' : 'Bearer ' + this.state.token
    },

    complete: function(){
        alert("carte supprimée avec succès");
        window.location.reload();
    },

});

};
My ReactJs Tab:
<Button animated='fade' onClick={this.handleAddCardSubmit}>
        <Button.Content visible>
            Ajouter une carte
        </Button.Content>
        <Button.Content hidden>
            <Icon name='add' />
        </Button.Content>
    </Button>

    <Button animated='fade' onClick={this.handleCardDelete}>
        <Button.Content visible>
            Supprimer la carte
        </Button.Content>
        <Button.Content hidden>
            <Icon name='delete' />
        </Button.Content>

My ReactJs "Home" Page:

handleItemClick = (e, { name }) => {
    this.setState({activeItem: name});
    if(name === 'Profil'){
      this.setState({fluxActif: <MonProfil/>});
    }
    if(name === 'MoyenDePaiement'){
          this.setState({fluxActif: <MoyenDePaiement/>});
      }
  };
  componentWillMount(){
    const token = localStorage.token;
    this.setState({token});

  };
  render() {

    return (

        <Menu className="MonCompteMenu">

Mon Compte

        </Menu>
        <Grid>
          <Grid.Column width={3}>
            <Menu fluid vertical tabular>
              <Menu.Item  name='Profil' active={this.state.activeItem === 'Profil'} onClick={this.handleItemClick} >
Mon Profil

              </Menu.Item>
              <Menu.Item  name='MoyenDePaiement' active={this.state.activeItem === 'MoyenDePaiement'} onClick={this.handleItemClick} >
Moyen de paiement

              </Menu.Item>
            </Menu>
          </Grid.Column>

          <Grid.Column stretched width={13}>
            <Segment >
              {this.state.fluxActif}
            </Segment>
          </Grid.Column>
        </Grid>

    )
  }
}

I continue my research. I thank you in advance.

A: you shouldn't use setState() twice like this!!, and don'y put components in state!
refactor your code like this, maybe will solve your problem
handleItemClick = (e, { name }) => {
    const { activeItem } = this.state;
    if(activeItem === name) return;
    this.setState({activeItem: name, });
  };

render() {
   const { activeItem } = this.state
   const ActiveTab = activeItem === 'Profil' ? MonProfil : MoyenDePaiement
   return (
      ......
       <Segment >
          <ActiveTab />
        </Segment>

   )
}


text:
Q: Why is the derivative of $e^x$ equal to $e^x$? I know that for the exponential function $e^x$ that the derivative will equal $e^x$ itself. But why? And also what is the significance of that?
Is that what gives $e$ its power? The rate of change of $e$ as it grows to the power of $x$, is $e^x$ itself. I get that the function doesn't produce $e^x$, that merely the rate at which its changes between $e^x$ and $h$ as $h \to 0$. But the intuition as to why and what is the significance to math eludes me. Mind you, I understand the math behind it, just not the intuition. For example, I understand this entire post https://mathinsight.org/exploring_derivative_exponential_function but why
I understand the math behind this post Could you explain why $\frac{d}{dx} e^x = e^x$ "intuitively"?. But I'm looking for an analogy.

A: Note $\ln e^x =x$.  Use the chain rule:  $\ln'(e^x)\cdot (e^x)'=1\implies \frac1{e^x}\cdot (e^x)'=1\implies (e^x)'=e^x$.

A: Without knowing anything about $e$, one could pose the question - is there a function $f(x)$ such that the derivative of the function evaluated at any point $x$ is equal to $f(x)$. The function that satisfies this property happens to be $\alpha e^x$.
$${d \over dx}f(x) = f(x)$$
$$\implies {df(x) \over f(x)} = dx$$
$$\implies ln(f(x)) = x + c$$
$$ \implies f(x) = \alpha e^x$$
Another way to look at it could be: (i) if the rate of change of a function is constant, the function is linear. (ii) if the rate of change is polynomial, the function is a polynomial (of a higher order than the derivative), and (iii) if the rate of rate change is exponential, the function is exponential.
$$ {d \over dx}f(x) = ae^x$$
$$ \implies df(x) = ae^x dx$$
$$ \implies f(x) = ae^x + c$$

A: I find cosine and sine very natural and significant in mathematics, and they can be represented by Euler's formula:

$$ e^{i\theta}  = \cos(\theta) + i\sin(\theta)$$

And from this we know the derivatives of these natural pair of functions easily thanks to derivative of $e^z$ being itself:

$$\frac{d}{d\theta}e^{i\theta}  = \frac{d}{d\theta}\cos(\theta) + i\frac{d}{d\theta}\sin(\theta)$$
$$ ie^{i\theta} = -\sin{(\theta)} + i\cos(\theta) = \frac{d}{d\theta}\cos(\theta) + i\frac{d}{d\theta}\sin(\theta)$$

so

$$ \frac{d}{d\theta}\cos(\theta) = -\sin{(\theta)} \tag 1$$
$$ \frac{d}{d\theta}\sin(\theta) = \cos(\theta) \tag 2$$

Perhaps it was the necessity of (1) and (2) that fueled nature to mandate

$$ \frac{d}{dz}e^z = e^z$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do i loop thorugh all double positions to save all frames to hard disk? I'm using FrameGrabber.cs and I added its dll as reference: JockerSoft.Media.dll and Interop.qedit.
Now in Form1 code in the constructor I'm trying to retrieve all the frames in their position and save each frame to a new bitmap file on the hard disk but I can't figure out how to do it.
I don't know how to loop through all frames/double[] position I also wanted to see get information about how many frames there are I could get the framerate which is 17.8....
I want to get a list/array of all frames and then save each frame to hard disk and then do another manipulations on the frames.
This is the site i got the example from. Tried to look there and on source code but couldn't figure out how to do it.
** I also have a trackBar1 in the designer I wanted to be able to scroll through all frames which also doesn't work good.
This is my Form1 code which doesn't work good I can get only one frame.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ExtractFrames.Properties;
using ExtractFrames;
using JockerSoft.Media;
using JockerSoft;
using Interop.qedit;
using Interop;
using System.Runtime.InteropServices;

namespace ExtractFrames
{
    public partial class Form1 : Form
    {
        double x;
        string sf;
        double[] streamDouble ;
        string strVideoFile;
        public Form1()
        {
            InitializeComponent();
            sf = @"d:\Frames\";
            strVideoFile = @"d:\My Movie.wmv";
            for (int x = 0; x < 40; x++)
            {
                streamDouble = new double[x];
                SaveFramesFromVideo(strVideoFile, streamDouble, sf + x.ToString("D6") + ".bmp");
            }
            //getFrameRate();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private  void getFrameRate()
        {
            // Get framerate
            MediaDet md = new MediaDet();
            md.Filename = strVideoFile;
            //md.CurrentStream = 0;                     // choose the video stream
            x = md.FrameRate;
            double i = md.StreamLength;

        }

        public static void SaveFramesFromVideo(string videoFile, double[] positions, string outputBitmapFiles)
        {
            if (videoFile == null)
                throw new ArgumentNullException("videoFile");

            double streamLength;

            IMediaDet mediaDet = null;
            try
            {
                _AMMediaType mediaType;
                if (openVideoStream(videoFile, out mediaDet, out mediaType))
                {
                    streamLength = mediaDet.StreamLength;
                    Size target = getVideoSize(mediaType);
                    int iteration = 0;
                    foreach (double position in positions)
                    {
                        iteration++;
                        string outputBitmapFile = string.Format(outputBitmapFiles, iteration);
                        mediaDet.WriteBitmapBits(position, target.Width, target.Height, outputBitmapFile);
                    }
                    return;
                }
            }
            catch (COMException ex)
            {
                throw new InvalidVideoFileException();
            }
            finally
            {
                if (mediaDet != null)
                    Marshal.ReleaseComObject(mediaDet);
            }

            throw new InvalidVideoFileException("No video stream was found");
        }

        private static Size getVideoSize(_AMMediaType mediaType)
        {
            WinStructs.VIDEOINFOHEADER videoInfo = (WinStructs.VIDEOINFOHEADER)Marshal.PtrToStructure(mediaType.pbFormat, typeof(WinStructs.VIDEOINFOHEADER));

            return new Size(videoInfo.bmiHeader.biWidth, videoInfo.bmiHeader.biHeight);
        }

        private static Size scaleToFit(Size target, Size original)
        {
            if (target.Height * original.Width > target.Width * original.Height)
                target.Height = target.Width * original.Height / original.Width;
            else
                target.Width = target.Height * original.Width / original.Height;

            return target;
        }
        private static Size scaleToFitSmart(Size target, Size original)
        {
            target = scaleToFit(target, original);

            if (target.Width > original.Width || target.Height > original.Height)
                return original;

            return target;
        }

        private static bool openVideoStream(string videoFile, out IMediaDet mediaDet, out _AMMediaType aMMediaType)
        {
            mediaDet = new MediaDet();

            //loads file
            mediaDet.Filename = videoFile;

            //gets # of streams
            int streamsNumber = mediaDet.OutputStreams;

            //finds a video stream
            for (int i = 0; i < streamsNumber; i++)
            {
                mediaDet.CurrentStream = i;
                _AMMediaType mediaType = mediaDet.StreamMediaType;

                if (mediaType.majortype == JockerSoft.Media.MayorTypes.MEDIATYPE_Video)
                {
                    //video stream found
                    aMMediaType = mediaType;
                    return true;
                }
            }

            //no video stream found
            Marshal.ReleaseComObject(mediaDet);
            mediaDet = null;
            aMMediaType = new _AMMediaType();
            return false;
        }

    }

}

A: The SaveFramesFromVideo() method expects a double array filled with the percentage position in the file in seconds - since you don't know how this relates to the length of the video you cannot use the frame rate alone. You can however save a frame at each full percentage into the file:
var streamDouble = new double[1];
for (int x = 0; x < 100; x++)
{
    streamDouble[0] = x;
    SaveFramesFromVideo(strVideoFile, streamDouble, sf + x.ToString("D6") + ".bmp");
}

If you just need that for WMV files you could also use AsfMojo instead - a complete solution would then look like this:
AsfFile asfFile = new AsfFile(@"D:\samples\sample.wmv");
AsfFileProperties fileProperties = asfFile.GetAsfObject<AsfFileProperties>();
TimeSpan duration = TimeSpan.FromTicks((long)fileProperties.PlayDuration) - TimeSpan.FromMilliseconds(fileProperties.Preroll);

var streamProps = asfFile.GetAsfObjects<AsfExtendedStreamProperties>()
                         .SingleOrDefault(x => x.StreamNumber == asfFile.PacketConfiguration.AsfVideoStreamId);

double timePerFrame = streamProps.AvgTimePerFrame / (double) 10000000 ;

double offset = 0;
while (offset < duration.TotalSeconds)
{
    using (var bitmap = AsfImage.FromFile(@"D:\samples\sample.wmv").AtOffset(offset))
    {
        if(bitmap!=null)
            bitmap.Save(string.Format(@"d:\Frames\{0}.jpg", offset.ToString("N")), ImageFormat.Jpeg);
    }
    offset += timePerFrame;
}


text:
Q: Use awk to display devices with disk usage above 10%, and print the column headings as well The below command displays devices with file system usage above 10%. However it is  not displaying the column headings. This is the command I use:
df -Ph | awk '+$5 >= 10 {print}'

I want output like this
Filesystem                      Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup00-LogVol00   9.7G  1.9G  7.4G  21% /
/dev/mapper/VolGroup00-LogVol     5.0G  665M  4.1G  14% /app
server:/data                      5.0G  546M  4.3G  12% /data

A: you can do this using two conditions for awk to print the line: either disk usage is above 10%, either the first parameter is "Filesystem":
df -Ph | awk '(+$5 >= 10 || $1=="Filesystem") {print}'

edit as suggested by Jotne you can write this shorter like this (print is default action):
df -Ph | awk '+$5>=10 || $1=="Filesystem"'

A: Print if we are looking at the first line or the fifth field is greater than or equal to 10.
df -Ph | awk 'NR==1 || +$5 >= 10'

Awk's default action is to print the line so block can be omitted.


text:
Q: SQL Syntax Highlighting not working When I open *.sql file with Visual Studio 2012 Update 3, I'm not getting sql syntax highlighting, all text is in white (dark theme is used). I remember I was testing some RedGate SQL addons but all of this is uninstalled now. I'm sure Visual Studio reinstallation will solve this, but is there maybe an easier solution ?

A: I solved problem by reinstalling SQL Server Data Tools from here http://msdn.microsoft.com/en-us/data/tools.aspx


text:
Q: TypeORM get one side of a many to many relationship I have got two entities: User and Organisation. These entities have a Many-to-Many relationship with each other. (A user can belong to multiple organisations and an organisation has multiple users.)
I have an endpoint /organisation/:id/members this endpoint should return only the users belonging to the organisation of :id.
I have created a query as follows:
    const members = await getConnection()
      .createQueryBuilder(Organisation, 'org')
      .where('org.id = :orgId', { orgId })
      .innerJoinAndSelect('org.members', 'member')
      .select('member')
      .getMany();

This returns an empty array, except when getRawMany is used. Then it returns the following:
[
  {
    "member_id": 1,
    "member_email": "example@example.com",
    "member_firstName": "John",
    "member_middleName": "",
    "member_lastName": "Doe"
  }
]

I would like to know how I get getMany() to return User entities.
Update:
I have the following example which does work. However, it requires the user to give the joinTable a name.
await getConnection()
      .createQueryBuilder(User, 'user')
      .innerJoinAndSelect(
        'organisation_members',
        'member',
        'member.userId = user.id',
      )
      .where('member.organisationId = :orgId', { orgId })
      .getMany();

A: NEW ANSWER:
My entities were setup incorrectly. I specified my ManyToMany relationship like this (incorrect!):
@ManyToMany(type => User)
members: User[];

Because this is a bi-directionaly relationship, I must specify on what field the user has the relationship towards the organisations:

@ManyToMany(
  type => User,
  user => user.organisations,
)
  members: User[];

And my User entity has:
@ManyToMany(
  type => Organisation,
  org => org.members,
)
organisations: Organisation[];

Use the TypeORM Query Relation Builder to get all members.
Updated once again:
return getConnection()
      .createQueryBuilder()
      .relation(Organisation, 'members')
      .of(orgId)
      .loadMany();


text:
Q: Is there a deep reason why a non-relativistic Lagrangian does not have higher order derivatives? In classical mechanics non-relativistic Lagrangians rely only on the coordinates and their first derivatives to describe a physical system.
Is there a deep reason why particle acceleration etc does not make an appearance as a Lagrangian argument?


text:
Q: При открытии попапа профиля невозможно изменить данные при открытии попапа профиля в консоли ошибка. Скрин http://joxi.ru/1A5YdBpS46gDVA
не могу изменить профиль. При сабмите ошибка http://joxi.ru/Dr8YZBESKLQzpm и ничего не изменяется
Еще заметил ошибки:
При открытии попапа профиля нужно вставлять в его инпуты данные пользователя, которые отображены сейчас на сайте, чтобы можно было их отредактировать сразу и обновить.
export default class UserInfo {
  constructor({ nameAuthor, infoAuthor }) {
    this._nameAuthor = nameAuthor;
    this._infoAuthor = infoAuthor;
  }

  getUserInfo() {
    this._userInfoValues = {
      nameAuthor: this._nameAuthor.textContent,
      infoAuthor: this._infoAuthor.textContent,
    };
    return this._userInfoValues;
  }

  setUserInfo(newData) {
    this._nameAuthor.textContent = newData.nameAuthor;
    this._infoAuthor.textContent = newData.infoAuthor;
    }
}

 export const authorProfileInput = document.querySelector('.form__input_info_name-author');

export const authorJobProfileInput = document.querySelector('.form__input_info_name-author-job');```


text:
Q: Uunderstand the limits of the ? operator if say I had a function that would ultimately come true could I do something like this?
somefunction(data) ? cout << "This is true" << endl : cout << this false << endl;

or am I little off? or is this impossible with such said operand? or could I call a different function? Ultimately, I a trying to figure out the limitations of this functions and other uses that aren't apparent in the c++ tutorial site.
std::cout<< (somefunction(data) ? "This is true" : anotherfunction (data) <

or other cases that people can think of...

A: I would look at Wikipedia. Basically it's syntax is
condition ? trueOutput : falseOutput;

Also you can nest them. You can output any value, but the condition has to be a boolean.
So in your case it would be:
cout << (someFunction(data) ? "True" : "False") << endl;

You can then nest this even!
cout << (someFunction(data) ? "True" : (newTernary(data) ? "False, but true" : (finalTernary(data) ? "False, false, and finally true" : "Always false:("))) << endl;

A: Not quite an "answer", but bear in mind that nearly always, using ternary operators for anything beyond the most simple things is "bad".
Reasonable usage is something like:
cout << "There are " << count << " item" << ((count != 1) ? "s":"")
     << " in your basket";

But if your ternary operators are nested, then you want to use if/else type constructs instead. People will want to read the the code without pulling their hair out in the future!
Of course, the initial statement can be done without ternary operators, assuming the result is a bool [and if it isn't, you could make it to a bool with a static_cast<bool>(someFunction(data))].
cout << "This is " << boolalpha << someFunction(data) << endl;

A: The "limitation" is that the three arguments have to be expressions, and there are rules about their types.  In your case, that all works out since cout << foo is an expression. Although you need to replace this false with "this is false".
But as others have pointed out, it is better to use the bare strings as your expressions.  I might have written
std::cout << "This is " << (somefunction(data) ? "true" : "false") << ".\n";


text:
Q: Javascript: closures? eventlistener won't add I seem to have a problem, and I suspect it's a problem with closures. I got 3 buttons, and when I run this code only the last button gets an eventlistener. This is why I suspect a closures problem. I tried all sorts of things as create other functions but the didn't help me. In the function addListeners i have 3 console.logs with information and they display the RIGHT information. So in addeventlisteners I have the right DIV, with the right information but it doesn't add a listener. Could anyone help me out here? I have no idea what I'm doing wrong.
function CheckAiringShows(slug,lastwatched,Length) {
var nmb = lastwatched.number;
var nxnmb = nmb +1;
$.ajax({
    type: "GET",
    url: "https://api-v2launch.trakt.tv/calendars/all/shows/"+strDate+"/30",
    headers: {
        "Content-Type": "application/json",
        "trakt-api-version": "2",
        "trakt-api-key": "a16246673f04042fca0fbc80eddd2b8b742524f62deaf11a6d0daf97f053005f"
    },
    success : function(response)
    {
        response.forEach(function (object, index) {
            if(slug == object.show.ids.slug){
                var airdate = new Date(object.first_aired).format("dddd, mmmm dS 'at' HH:MM:ss");

                var nextnumber = "s"+object.episode.season+"e"+object.episode.number;
                document.getElementsByClassName("airingshow")[0].innerHTML += ""+object.show.title+": "+nextnumber+" "+airdate+"<input type='submit' class='calendar' id='"+object.episode.ids.trakt+"' value='Add to calendar!'/>";

                var calend = document.getElementById(object.episode.ids.trakt);
                addListeners(calend,object,Length);
            }
        });

    }
});
}
function addListeners(item,object,length){
    console.log(item);
    console.log(object);
    console.log(length);
          // this line didn't work out at all, nothing got an eventlistener this way.
          // return function(){item.addEventListener('click', function(){makeApiCall(object,length)})};
    item.addEventListener('click', function(){makeApiCall(object,length)});
}

A: It's because you are replacing the innerHTML in every iteration, effectively destroying previously created DOM elements and replacing them.
Here's a few solutions:

*

*First generate the entire HTML, then change the innerHTML and attach handlers.

*Attach a single handler on the container and handle bubbling events on the children you want (event delegation).

*Construct the DOM using the DOM API (e.g. document.createElement(...), container.appendChild(...)).

Event delegation is usually more simple if the content of a container is dynamic, because you do not have to worry about adding handlers on newly added elements.

$('#dynamic-container')
  .on('click', 'button', function () {
    alert('You clicked on a button!');
  })
  //cliking dynamically added button will also work
  .append('<button>dynamic button</button>');

  <button>static button</button>


text:
Q: How to write a cell array to csv in Matlab while keeping the structure of the cell array for the strings I am trying to write out a cell aray to a csv file in Matlab. data{1,:} is equal to headers and data{2,:} has the data (2x23).
The data in the cell array has a mixture of strings and numbers.
One of the cells in the array has a very long string/comment and when I try to write it out to a csv, the string gets broken up into a number of pieces and printed out over 3 cells in the csv file. This pushes all of the other information out of sync with it's associated header.
This is what I'm currently trying:
 fid = fopen('test.csv', 'w') ;
fprintf(fid, '%s,\t', csvdata{1,1:end}) ;
fprintf(fid,'\n,%f, %f, %f,%f, %f, %s,%s, %f, %f,%s, %f, %s,%s, %f, %s,%s, %s, %s,%s, %s,%s,%s,%s',csvdata{2,:});
fclose all

A: You should enclose your strings with double quotes (") to ensure that the commas within the strings are treated as literal commas rather that delimiters
fprintf(fid,'\n,%f, %f, %f,%f, %f, "%s","%s", %f, %f,"%s", %f, "%s","%s", %f, "%s","%s", "%s", "%s","%s", "%s","%s","%s","%s"',csvdata{2,:});


text:
Q: How do I explicitly call an exception-throwing method in C++? I have a simple class:
class A {
 public:
  bool f(int* status = nullptr) noexcept {
    if (status) *status = 1;
    return true;
  }
  void f() {
    throw std::make_pair<int, bool>(1, true);
  }
};

int main() {
  A a;
  a.f(); // <- Ambiguity is here! I want to call 'void f()'
}

I want to resolve ambiguity of a method call in favour of the exception-throwing method by any means.
The rationale behind such interface:

*

*To have the noexcept(true) and noexcept(false) interface,

*To allow optionally get extra information via a pointer in the noexcept(false) variant - while the noexcept(true) variant will always pack this information inside an exception.

Is it possible at all? Suggestions for a better interface are also welcome.

A: I agree with other users' suggestions to simply remove the default argument.
A strong argument in favour of such a design is that it would be in line with the new C++17 filesystem library, whose functions typically offer callers the choice between exceptions and error reference parameters.
See for example std::filesystem::file_size, which has two overloads, one of them being noexcept:

std::uintmax_t file_size( const std::filesystem::path& p );

std::uintmax_t file_size( const std::filesystem::path& p,
                          std::error_code& ec ) noexcept;

The idea behind this design (which is originally from Boost.Filesystem) is almost identical to yours, except of the default argument. Remove it and you do it like a brand new component of the standard library, which obviously can be expected not to have a completely broken design.

A: Having functions with this kind of signatures is obviously a bad design as you've found out. The real solutions are to have different names for them or to lose the default argument and were presented already in other answers.
However if you are stuck with an interface you can't change or just for the fun of it here is how you can explicitly call void f():
The trick is to use function pointer casting to resolve the ambiguity:
a.f(); // <- ambiguity is here! I want to call 'void f()'

(a.*(static_cast<void (A::*)()>(&A::f)))(); // yep... that's the syntax... yeah...

Ok, so it works, but don't ever write code like this!
There are ways to make it more readable.
Use a pointer:
// create a method pointer:
auto f_void = static_cast<void (A::*)()>(&A::f);

// the call is much much better, but still not as simple as `a.f()`
(a.*f_void)();

Create a lambda or a free function
auto f_void = [] (A& a)
{
    auto f_void = static_cast<void (A::*)()>(&A::f);
    (a.*f_void)();
};

// or

void f_void(A& a)
{
    auto f_void = static_cast<void (A::*)()>(&A::f);
    (a.*f_void)();
};

f_void(a);

I don't know if this is necessary better. The call syntax is definitely simpler, but it might be confusing as we are switching from a method call syntax to a free function call syntax.

A: Both versions f have different meanings.
They should have two different name, as:

*

*f for the throwing one, because using it means that your are confident on success, and failure would be an exception in the program.

*try_f() or tryF() for the error-return based one, because using it means that failure of the call is an expected outcome.

Two different meanings should be reflected in the design with two different name.

A: In C++14 it's ambiguous because noexcept is not part of the function signature. With that said...
You have a very strange interface. Although f(int* status = nullptr) is labelled noexcept, because it has a twin that does throw a exception, you are not really giving the caller a logical exception guarantee. It seems you simultaneously want f to always succeed while throwing an exception if the precondition is not met (status has a valid value, i.e not nullptr). But if f throws, what state is the object in? You see, your code is very hard to reason about.
I recommend you take a look at std::optional instead. It'll signal to the reader what you are actually trying to do.

A: C++ already has a type specifically used as an argument to disambiguate between throwing and non-throwing variants of a function: std::nothrow_t. You can use that.
#include <new>

class A {
 public:
  bool f(std::nothrow_t, int* status = nullptr) noexcept {
    if (status) *status = 1;
    return true;
  }
  void f() {
    throw std::make_pair<int, bool>(1, true);
  }
};

int main() {
  A a;
  a.f(); // Calls 'void f()'
  a.f(std::nothrow); // Calls 'void f(std::nothrow_t, int*)'
}

Though I would still prefer an interface where the name distinguishes the variants, or possibly one where the distinction isn't necessary.

A: Because it seems fundamentally obvious to me, I may be missing something or may not fully understand your question. However, I think this does exactly what you want:
#include <utility>

class A {
 public:
  bool f(int* status) noexcept {
    if (status) *status = 1;
    return true;
  }
  void f() {
    throw std::make_pair<int, bool>(1, true);
  }
};

int main() {
  A a;
  a.f(); // <- now calls 'void f()'
  a.f(nullptr);  // calls 'bool f(int *)'
}

I simply removed the default argument from the noexcept variant. It's still possible to call the noexcept variant by passing nullptr as an argument, which seems a perfectly fine way of indicating that you want to call that particular variant of the function - after all, there's going to have to be some syntactic marker indicating which variant you want to call!

A: Here's a purely compile-time method.
It may be useful if your compiler happens to have trouble optimizing away function pointer calls.
#include <utility>

class A {
 public:
  bool f(int* status = nullptr) noexcept {
    if (status) *status = 1;
    return true;
  }
  void f() {
    throw std::make_pair<int, bool>(1, true);
  }
};

template<void (A::*F)()>
struct NullaryFunction {
  static void invoke(A &obj) {
    return (obj.*F)();
  }
};

int main() {
  A a;
  // a.f(); // <- Ambiguity is here! I want to call 'void f()'
  NullaryFunction<&A::f>::invoke(a);
}

A: So you are trying to throw an exception if the code is unprepared for an error return?
Then, how about
class ret
{
    bool success;
    mutable bool checked;
    int code;
public:
    ret(bool success, int code) : success(success), checked(false), code(code) { }
    ~ret() { if(!checked) if(!success) throw code; }

    operator void *() const { checked = true; return reinterpret_cast<void *>(success); }
    bool operator!() const { checked = true; return !success; }

    int code() const { return code; }
};

This is still an Abomination unto Nuggan though.
By removing the if(!success) check in the destructor, you can make the code throw whenever a return code is not looked at.


text:
Q: Add and remove from array in single query I want to make a query in which i want to know either the user like or unlike my status, now i want to make it on single query so that I will not call the DB 2 times from my NODEJS server, do any have solution of my problem.
For Add We are using
    collection.update({ _id: id },
        { $pull: {
            'user_id': 'xxxx-xxxx-xxxx-xxxx' }
        }
    );
For Remove We are using
collection.update({ _id: id },
    { $push: {
        'user_id': 'xxxx-xxxx-xxxx-xxxx' }
    }
);

Now I want to use both of them in one query like if apply present in fruit array remove it if not add it.

A: MongoDB does not allow both a $pull and $push or any other operation to update the same "path" ( therefore single array ) in a single statement. This is mainly to do with the logic handling server side where the update operations are never considered to be ordered in a statement.
Example:
{
   "responses": [
       { "user": "Tom", "status": "like" },
       { "user": "Sarah", "status": "unlike" }
   ]
}

Not that it would make much sense, but you cannot do this:
db.collection.update(
    {},
    {
        "$pull": { "responses": { "user": "Tom", "status": "like" },
        "$push": { "responses": { "user": "Tom", "status": "unlike" }
    }
)

As the single operation here contains both $push and $pull on the "same path" as "responses". Regardless of you you contruct the statement, neither is required to execute in any order at all.
While we could "match" the position for "Tom" and change his "status" to "unlike" instead, a better model is to do this:
{
    "likes": ["Tom"],
    "unlikes": ["Sarah"],
    "likesTotal": 1,
    "unlikesTotal": 1,
    "totalScore": 0
}

What this means if I want to change the "vote" for "Tom" then you make a construct like this, with the help of Bulk operations to enable a single request and response:
var bulk = db.collection.initializeOrderedBulkOp();

// Cast "Tom's" unlike where they had a "like" already
bulk.find({
    "likes": "Tom",
    "unlikes": { "$ne": "Tom" }
}).updateOne({
    "$pull": { "likes": "Tom" },
    "$push": { "unlikes": "Tom" },
    "$inc": {
        "likesTotal": -1,
        "unlikesTotal": 1
    }
]);

// Cast "Tom's" new vote where nothing was there at all
bulk.find({
    "unlikes": { "$ne": "Tom" },
    "likes": { "$ne": "Tom" }
}).updateOne({
    "$push": { "unlikes": "Tom" },
    "$inc": {
        "unlikesTotal": 1,
        "totalScore": -1
    }
});

bulk.execute();

This produces a really nice pattern. Not only is each update operation here basically "atomic" in that by acting on separate document properties each modifier is allowed to execute without conflict. But also as a "Bulk" operation, the request for "both" update operations that meet all possible conditions here are sent in a single request and received in a single response.
Of course your "client" logic should also be aware of the current status for who has "liked/disliked" on a particular item, but enforcing this in the general API is good practice.
It keeps arrays in check, and also keeps useful counters in check for general data and general querying purposes, without the need to "calculate" lengths of arrays or matching types.


text:
Q: Issue when setting Game Screen upon BACK button pressed I have 3 game screens, saying A, B and C, each extending the Screen class. The game normally goes from A to B, and B to C, triggered by click events.
For quick debug purpose, I put the following codes in ScreenC 's render method, so that when BACKSPACE or BACK key are pressed I can go back to ScreenB from ScreenC, and it works fine.
if (Gdx.input.isKeyPressed(Input.Keys.BACK) || Gdx.input.isKeyPressed(Input.Keys.BACKSPACE)) {
        game.setScreen(new ScreenB(game));
        dispose();
}

Now I want to go back from ScreenB to ScreenA, so I put the following in ScreenB's render method, and it works fine, too.
if (Gdx.input.isKeyPressed(Input.Keys.BACK) || Gdx.input.isKeyPressed(Input.Keys.BACKSPACE)) {
    game.setScreen(new ScreenA(game));
    dispose();
}

However, the problem is, now if I press BACKSPACE or BACK key on ScreenC, I will go back to ScreenA directly. Seems to me the keyPressed event propagated to ScreenB from ScreenC, so that ScreenB detected the event then set to ScreenA directly. I am wondering if this is the expected behavior and how do I avoid this? Thanks!

A: Try this
Gdx.input.isKeyJustPressed(Input.Keys.Back)
and the state isn't maintained just a single consumed event.
isKeyPressed is more for character movement i.e. "a" to move left etc


text:
Q: Data Base Model - Huge (over 1 million lines) text files I have to work on a project involving huge amount of data stored in a raw text file. Each field is delimited by its size, ie, field 1 is from position 0 to 3, etc.. (not CSV file)
The file contains over a million lines.
I need to store it into a database. I checked several posts about what would be the best way to go about it, and it seems like the technology choice matters less than the algorithm. I'm open to Php, Perl or Python. Feel free to suggest anything.
Now, the file structure in itself is a bit tricky. Here is an example:
A880780093vvd47aa8db20d4133e6f587cf046054e8316000212093659D11001
C880780093d47aa8db20d4133e6f587cf046054e831600021209365907000 0711012012C
A880780093vvcaacb22bfb091127f9c9e14175d858ee25000212093681O11001
C880780093caacb22bfb091127f9c9e14175d858ee2500021209368107000 0611012012ADI
D880780093caacb22bfb091127f9c9e14175d858ee250002120936810700011012012HK00210Z
A880780093vvb92f937a3fd1268c1478deb174a1bfca86000212093750S11041
C880780093b92f937a3fd1268c1478deb174a1bfca8600021209375007000 3911012012PB
C880780093b92f937a3fd1268c1478deb174a1bfca8600021209375007000 3911012012B 1002
E880780093212093750b92f937a3fd1268c1478deb174a1bfca8600007000110120120100000127000000000000
C880780093b92f937a3fd1268c1478deb174a1bfca8600021209375007000 3911012012B

Basically, there are 6 types of lines, from A to F; line A is the header of the block. Lines B and C have the exact same length and fields. Line D is a possible complement to line C, meaning that it is attached to a line C but not required; also meaning there cannot be a line D without a line C. Lines E and F are independent lines, only attached to line A. (all lines are part of a block, so they could all be "attached" to a line A, or a virtual block ID)
How would I go about to create a model that would allow me to:
- modify some data on some lines based on some criteria (ie, if 5th char of line C is 4, then 10th becomes 7)
- keep track of the modified ones (ie, I want to be able to link them to their original selves)
- Be able to rebuild the original text file, deleting the original lines and replacing them by their modified version
- Be able to insert new lines in the block: if line C has 7th char = 0 then I add below it a D line.
- keep the line order intact. (if one line is inserted, it moves the order for the following line by  1 rank ahead)
I thought about using a parent_id foreign key in all 5 line tables (one per each line type, since they do not have the same fields); thus resolving the line ordering issue, but I am stuck at rebuilding the modified file version. I also thought about dividing the file into blocks (starting by a line A), then linking lines to block ID...
Any suggestion would be greatly appreciated!
Thanks a lot in advance!

A: Go through the file line by line and use a stack. Something along the lines:
<?php

// You'd have to implement the database yourself!
$db = new Database();
$db->startTransaction();

$stack = array();
$fh    = fopen("my-file", "r");
$i     = 0;
while (($buffer = fgets($handle, 4096)) !== false) {
  if (!isset($buffer[0])) {
    continue;
  }

  switch ($buffer[0]) {
    case "A":
      // Do something ...
      break;

    case "C":
      // Do something ...
      break;

    case "C":
      if ($stack[$i] != "C") {
        trigger_error("Line D without preceding line C");
      }
      // Do something ...
      break;

     // More stuff ...
  }

  $stack[$i++] = $buffer;
  $db->insert("INSERT INTO table (line) VALUES ($buffer)");
}

$db->commitTransaction();

?>

Of course there are better solutions than the ugly switch, but it's quick'n'dirty. Your database design answer is impossible to answer because we have no clue about the requirements. All in all consider posting your work and ask specific questions regarding a small piece of a big problem and not asking to solve big problems.


text:
Q: Simplest way to display each hour of the day in Ruby I have a calendar screen where I want to display the hours of the day like this:
12:00am

1:00am

2:00am

..

4:00pm

5:00pm

etc.

Being a total Ruby noob, I was wondering if anyone could help me figure out the simplest way to display this.

A: #!/usr/bin/env ruby

# without using actual `Date` objects ...

p ["12:00am"] + (1..11).map {|h| "#{h}:00am"}.to_a +
  ["12:00pm"] + (1..11).map {|h| "#{h}:00pm"}.to_a

["12:00am", "1:00am", "2:00am", "3:00am", "4:00am", "5:00am", "6:00am",
"7:00am", "8:00am", "9:00am", "10:00am", "11:00am", "12:00pm", "1:00pm",
"2:00pm", "3:00pm", "4:00pm", "5:00pm", "6:00pm", "7:00pm", "8:00pm",
"9:00pm", "10:00pm", "11:00pm"]

Or using actual DateTime objects and %I:%M%p as format:
#!/usr/bin/env ruby

require "Date"

for hour in 0..23 do
  d = DateTime.new(2010, 1, 1, hour, 0, 0)
  p d.strftime("%I:%M%p")
end

Which would print:
"12:00AM"
"01:00AM"
"02:00AM"
"03:00AM"
"04:00AM"
"05:00AM"
"06:00AM"
"07:00AM"
"08:00AM"
"09:00AM"
"10:00AM"
"11:00AM"
"12:00PM"
"01:00PM"
"02:00PM"
"03:00PM"
"04:00PM"
"05:00PM"
"06:00PM"
"07:00PM"
"08:00PM"
"09:00PM"
"10:00PM"
"11:00PM"

A: You could generate these like this:
array = ['12:00am'] + (1..11).map {|h| "#{h}:00am"} + ['12:00pm'] + (1..11).map {|h| "#{h}:00pm"}

or simply write out the array (this is more efficient):
array = ["12:00am", "1:00am", "2:00am", "3:00am", "4:00am", "5:00am", "6:00am", "7:00am", "8:00am", "9:00am", "10:00am", "11:00am", "12:00pm", "1:00pm", "2:00pm", "3:00pm", "4:00pm", "5:00pm", "6:00pm", "7:00pm", "8:00pm", "9:00pm", "10:00pm", "11:00pm"]

You can then print these however you want, eg.
array.each do |el|
    puts el
end


text:
Q: POST Dynamic Values in Array in multipart/form-data in c# In my Xamarin App, the form is Dynamic, means the Form is been Fetch from API and then I Get the Entry Value from Dynamic Form in ViewModel.
Sending data to backend with static values.
var fields = "[{\"name\": \"firstName\", \"value\": \"Hannah\"}, {\"name\": \"lastName\", \"value\": \"Arendt\"}, {\"name\": \"email\", \"value\": \"example@mail.com\"}]";

Content.Add(new StringContent(fields), "fields");

Now, as I'm getting Form dynamically.
foreach (var item in Value.ToList())
{
    item.name;
    item.Value;
}

Just want to replace name and value with dynamic data (item.name and item.Value).
var fields = [{"name": item.name, "value": item.Value}];

Content.Add(new StringContent(fields), "fields");

A: I think it will be useful.
you need to add: using Newtonsoft.Json;
var values = Value.ToList().Select(item => new { item.name, item.value }).ToList();

var fields = JsonConvert.SerializeObject(values);


text:
Q: Periodic background task on iOS Is there anyway to run background task on iOS? Like periodically checking some system condition of the phone and report on the widget?
Also, I found that if the iPhone is shut down, then those background task cannot execute again when the phone restart.

A: The short answer: No.
The long answer is more nuanced, but you shouldn't do it anyway. You can schedule your application for background refresh, but that is unreliable (app will not be run on constant intervals), and if user swipes the app in task switcher, the app will not run at all in the background. Another hacky way is to have a server send a silent push to wake the app more reliably. However this is still not guaranteed to succeed; if user swipes the app in task switcher, your app will not run.
In either case, you cannot trigger widget updates from your app. Widget lifetime is managed by the operating system. Instead, implement widgetPerformUpdate(completionHandler:) and perform your widget updates there. However, as above, this is not a periodic operation.


text:
Q: Can we use JasperReports with AngularJS? I have been looking for a reporting tool for AngularJS and have been without luck.
I wanted to know if we can use JasperReports with AngularJS. I stumbled upon this and this link. But they didn't help much.
Any help would be great!
PS: In case JasperReports cannot be used with AngularJS, are there any reporting platforms for AngularJS?

A: Short answer: No, long answer: No, Jasper Reports is based on Java, so you'll need to setup a Java server (or a Jasper Reports Server) that renders to HTML and then use that HTML output in an Iframe or inlined in your code using some server side technology, speaking of which, depeding of your server side technology you may also find a Jasper Reports implementation for your particular server side technology.

A: Please have a look for Visualize.js. Maybe it would be useful for your case.


text:
Q: Floating point number answer difference between c++ and calculator I am calculating a floating point number by formula: number=1/(n-2.001)
Where n is any integer from 1 to infinite.
But it give me different answer in laptop and scientific calculator.
C++ calculation : 0.333444
Calculator answer: 0.3334444815

I have to get all digits in c++. How i get this.

A: Decimal equivalent of 1/3 is 0.33333333333333….
An infinite length number would require infinite memory to store, and we typically have 4 or 8 bytes. Therefore, Floating point numbers store only a certain number of significant digits, and the rest are lost.

NOTE : When outputting floating point numbers, cout has a default precision of 6 and it truncates anything after that.

The precision of a floating point number defines how many significant digits it can represent without information loss.

*

*Therefore in your case only 6 decimals points are outputted and rest are turncated

*To change the Precision of floating-point data types in C++ check this


text:
Q: Magento 2 - what database tables are involved in front end design and blocks I am working on Magento 2 (ver. 2.4.3-p1) with theme Porto.
I have 2 instances of Megento. One is with database having all the product and site data and other is blank site (with no product / site data) but only frontend design implemented.
I want to merge both databases into one so the design and code becomes on 1 instance.
My questions is, which tables from "design instance" should be copied to "database instance" (having all the product and site data). I know the frontend files structure but need to know database tables involved in front end design.
Any help is highly appreciated


text:
Q: Определение структуры внутри union без имени, как маршалировать? Я немного не понял как мне маршалировать такое объединение:
typedef union _LARGE_INTEGER {
    struct {
        DWORD LowPart;
        LONG HighPart;
    } DUMMYSTRUCTNAME;
    struct {
        DWORD LowPart;
        LONG HighPart;
    } u;
    LONGLONG QuadPart;
} LARGE_INTEGER;

При том раскладе что DUMMYSTRUCTNAME не имеет значения, т.е. он пуст.
Правильно ли я сделал?
[StructLayout(LayoutKind.Explicit)]
public struct LargeInteger
{
    [StructLayout(LayoutKind.Sequential)]
    public struct DummyStruct
    {
        public uint LowPart { get; set; }
        public long HighPart { get; set; }
    }

    [FieldOffset(0)] public DummyStruct DummyStructField;
    [FieldOffset(0)] public DummyStruct u;
    [FieldOffset(0)] public long QuadPart;
}


text:
Q: Calling a function defined in a directive's scope from a controller EDIT: I created a Plnkr
http://plnkr.co/edit/yuvtrPs3csAQZW7OF06O
I'm not sure if this has anything to do, but I noticed the console's log shows:

Event tracked Multipane Show Preview Toolbar undefined undefined

Premise: I'm creating a new question following the "probably forgotten" question at the link:

AngularJS: How do I call a function defined in a directive's scope from a controller?

Since I got one answer there, I informed him of the new question in case he wants to complete his answer here.
Also, I know there are similar questions, but I can't find a solution suitable for my case.
I need to call a function which belongs to the $scope of a ng-directive used in my Angular application.
Following the tutorial at:

http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

I set up the following code as example.
Let's say the directive is defined like this: (concretely the directive -- simplified here -- is the one defined by the plugin: www.ixtendo.com/polyglot-language-switcher-2/#angularjs )
Note: there is not parent-child relation between the directive and the controller which I want to make access the directive's controller's function. This is why I use $rootScope
.directive('my-directive', ['$document', '$timeout', '$rootScope', function ($document, $timeout, $rootScope) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            // ....
        },
        controller: ['$scope', '$rootScope', function ($scope, $rootScope) {

            var myFunction= function () {
                // do something...
            };

            $scope.$on('openLanguageSelectionPopup', function (){
                console.log("event triggered"); // NOT triggered!
                myFunction();
            });
        }
    };
}]);

I need to call myFunction from my controller (called mainController) which is the controller of the view where my directive is placed. I defined it as:
.controller('mainController',
function ($scope, $rootScope){
    $rootScope.$emit('openLanguageSelectionPopup');
    // this is event should be received by any $rootScope.$on(...) in ANY controller
})

I modified the directive's controller itself but unsuccessfully
In fact the event (openLanguageSelectionPopup) is not triggered (console.log is not printed).
I am also sure that both the $on and the $emit are reached at some point (I tried with console.log(...) ).
I understand the problem may be in directive's scope definition as proposed as solution in the following answer:

Calling a method in a controller defined in a directive from a javascript function

However, if this is the problem, I can't understand what the accepted answer can bring to my specific case.
Also, I don't understand where I should put $rootScope: in the directive's controller function or in the directive's definition function (in my example I added it in both).

A: You emit and broadcast your stuff in the controller.
But the directive doesn't exist.
Atleast i think that's happening.
Because if i wrap your broadcast in a timeout they receive it.
Also your plunkr is missing somethings
You forgot to add the script to the index.html
And you call your directive in the html like this  but it should be


text:
Q: Как сделать такой border? Подскажите как реализовать такую рамку, чтобы оставался пробел под заголовком.

A: Пример (+ данного решения: работает на любом фоне (градиент, изображение))

body {
  background: #291923;
}

fieldset {
  border-color: #fff;
  border-style: solid;
  border-width: 1px;
  padding: 15px;
  color: #fff;
}

legend {
  text-align: center;
  color: #fff;
}
<fieldset>
  <legend align="center">Заголовок</legend>

Text

</fieldset>

Пример с градиентом

body {
  height: 100vh;
  background: linear-gradient(135deg, rgba(255,0,0,1) 0%,rgba(109,0,25,1) 100%);
}

fieldset {
  border-color: #fff;
  border-style: solid;
  border-width: 1px;
  padding: 15px;
  color: #fff;
}

legend {
  text-align: center;
  color: #fff;
}
<fieldset>
  <legend align="center">Заголовок</legend>

Text

</fieldset>

A: Один из способов

.boby {
  background: white;
  padding-top: 30px;
}

.cell {
  height: 100px;
  border: 1px solid red;
  position: relative;
}

h1 {
  position: absolute;
  left: 50%;
  top: -40px;
  transform: translateX(-50%);
  background: white;
  padding: 0 30px;
}

TЕКСТ

A: вышло так

.home {
  border:2px solid red;
  position:relative;
}
.home h2{
 position:absolute;
 top:-35px;
 background:white;
 left:50%;
 margin-left:-60px;
 width:90px;
 text-align:center;
}

TEXT

text text text text text

A: Не совсем то, что тебе надо, наверное
https://jsfiddle.net/6fqLsj9s/
https://jsfiddle.net/6fqLsj9s/1/
HTML

TEXT

CSS:
.cover-block:before,
.cover-block:after {
    content:                  '';

    z-index:                  2;

  display:           inline-block;
    position:                absolute;

    border-style:           solid;

    top:                          0px;
}

.cover-block:before {
    left:                       0px;

    border-width:           50px 0px 50px 25px;
    border-color:           transparent transparent transparent black;
}

.cover-block:after {
    right:                      0px;

    border-width:           50px 25px 50px 0px;
    border-color:           transparent black transparent;
}

P.S.
Вот вариант с одним уголком-границей
https://jsfiddle.net/6fqLsj9s/2/
Я наложил :after на :before, при этом :after на 1 пиксель меньше чем :before, а имеет цвет заднего фона, что дает иллюзию уголка.
Как сделать 2 уголка пока не знаю.
body {
  background: white;
}

.cover-block {
  position: relative;

  width: 300px;
  height: 100px;

  border: 1px solid orange;
  border-left: none;

  text-align: center;
  line-height: 100px;

  color: black;
  font-size: 20px;
  font-family: calibri;
 }

.cover-block:before,
.cover-block:after {
    content:                  '';

  display:           block;
    position:                absolute;

    border-style:           solid;

  left:               0px;
}

.cover-block:before {
    top:                          0px;
    border-width:           50px 0px 50px 25px;
    border-color:           transparent transparent transparent orange;
}

.cover-block:after {
  top:                1px;
    border-width:           49px 0px 49px 24px;
    border-color:           transparent transparent transparent white;
}

P.P.S.
2 уголка легко делается, если использовать не 1 div, а 3

TEXT

и к каждому уголку применить код (чуть модифицированный), который я привел для одноуголкового примера.
P.P.P.S
Уф - получилось, как описал выше: https://jsfiddle.net/6fqLsj9s/3/
Пришлось ввести дополнительные блоки (2 штучки)
HTML:

TEXT

CSS:
body {
  background: white;
}

.cover-block {
  position: relative;

  width: 300px;
  height: 100px;

  border: 1px solid orange;
  border-left: none;
  border-right: none;

  text-align: center;
  line-height: 100px;

  color: black;
  font-size: 20px;
  font-family: calibri;
 }

 .left,
 .right {
   position: absolute;
   top: 0px;

   width: 0px;
   height: 100%;
 }

.left {
  left: 0px;
}

.right {
  right: 0px;
}

.left:before,
.left:after,
.right:before,
.right:after {
    content:                  '';

  display:           block;
    position:                absolute;

    border-style:           solid;
}

.left:before,
.left:after {
  left:               0px;
}

.left:before {
    top:                          0px;
    border-width:           50px 0px 50px 25px;
    border-color:           transparent transparent transparent orange;
}

.left:after {
  top:                1px;
    border-width:           49px 0px 49px 24px;
    border-color:           transparent transparent transparent white;
}

.right:before,
.right:after {
  right:               0px;
}

.right:before {
    top:                          0px;
    border-width:           50px 25px 50px 0px;
    border-color:           transparent orange transparent transparent;
}

.right:after {
  top:                1px;
    border-width:           49px 24px 49px 0px;
    border-color:           transparent white transparent transparent;
}


text:
Q: RegEx/Javascript: How to get the parameter from URL? Hi i have this kind of URLs
www.example.com/registration/star/xx223x/xxxx67x/xx
www.example.com/registration/star-mega/x45xx/xxxrfxx/xx
www.example.com/registration/manager/xxx34xx/xx
www.example.com/registration/pro/xxxxx/xxx

How can i using javascript and RegEx get the parameter after /registration/ and before the next / into variable? (star, star-mega, manager, pro)

A: How about the following regex: www\.example\.com\/registration\/([^\/]+)? see http://regex101.com/r/xS8zZ6

A: To expand on the awesome answer by Uri Y, here is how you use it in JavaScript:
var url = 'www.example.com/registration/star-mega/x45xx/xxxrfxx/xx';
var result = url.match('\/registration\/([^\/]+)');
alert(result[1]);

JSFiddle Here.


text:
Q: How to set focus to a control in a Windows Forms application? In a Windows Forms application, when do I write the code to set the focus to a control both while the application is launched and subsequently after I call a function?
For instance, if I have a DropDownList, a TextBox and four buttons and I want the Focus to be set to the DropDownList, where do I write my code?
To set the focus to a particular control on application launch, I can set the tab index to that DropDown (with a minimum value, under the assumption TabStop property is set to True).
Now, if the user completes an operation (say, any of the Click Button Events) and then I update the DropDown and after that if I want to set the focus...I can do it as
MyDropDownList.Focus()

QUESTION
NB: The question is more about where, not how?

A: By far the simplest solution is to set the TabIndex property correctly so that your 'MyDropDownList' control has the lowest index.  The next approach is to do it in the constructor.  But you have to use Select(), the Focus() method cannot work yet because the control doesn't become visible until later.
Public Sub New()
    InitializeComponent()
    MyDropDownList.Select()
End Sub

Works in the Load event as well.  Focus() starts working in the Shown event.

A: When the parent window is activated (that is, when it receives the "Activated" event), set the focus to the child control where you want the focus located.
private void Form_AddAppID_Activated(object sender, EventArgs e)
{
    textID.Focus();
}

Note that the tab order has nothing to do with where the focus starts. Instead, the tab order is used to decide how the focus gets transferred when the user hits the tab key.


text:
Q: C++ template parameters as arguments to assembler macros in an asm block (gcc/gas) I am attempting to use an integer template argument in some asm macros, but I'm running into a substitution problem.  Below is a (very) simplified version of what I'm doing:
template<int X> void delay() {
    asm __volatile__(
        "  .macro fl_delay dtime, reg=r0    \n\t"
        "    .if (\\dtime > 0)              \n\t"
        "      .set dcycle, (\\dtime / 3)   \n\t"
        "      .set dwork, (dcycle * 3)     \n\t"
        "      .set drem, (\\dtime - dwork) \n\t"
        "      .rept (drem)                 \n\t"
        "        nop                        \n\t"
        "      .endr                        \n\t"
        "      .if dcycle >= 0              \n\t"
        "        mov \\reg, #dcycle         \n\t"
        "        loop_\\@:                  \n\t"
        "        sub \\reg, #1              \n\t"
        "        bne loop_\\@               \n\t"
        "      .endif                       \n\t"
        "    .endif                         \n\t"
        "  .endm                            \n\t"
        "  fl_delay %[X], r0                \n\t"
        : [X] "I" (X)
        :
        : "r0");
}

The macro basically allows for me to do cycle count accurate delays.  So, for example, if in my asm code I write:
"  fl_delay 13, r0"

it will delay for exactly 13 cycles (using register r0 for the loop counter).  This part works fantastically well in a bunch of testing.  The problem comes when I want to make the argument to my macro depend on a template argument (The X, above).  If I (elsewhere) write delay<13>(); the asm for the generated function looks like:
; fl_delay macro definition here
fl_delay #13, r0

The problem is, gnu as's expression parser doesn't like the #.  I suspect the problem is the bit in the macro where, say, I do .set dcycle, (\\dtime / 3).  The \\dtime will get replaced with #13 making that line .set dcycle, (#13 / 3) (which I have been able to verify by putting that exact line in some test code, the as error message is the same).
So, I have one of two questions that I need to find an answer to:

*

*Is there a way for me to get the int value from a template parameter into the asm block without the leading #?  (I've tried a bunch of asm constraints but they all put the leading # in there)

*If I can't do the above, is there a way for me to strip the leading character of an as .macro argument value?  I've done a bunch of digging but haven't been able to find anything along those lines.

I don't believe there is a way for me to abuse the C preprocessor to do this, as that runs and does its substitutions before any template/C++ parsing is done.
(What I'm writing is some code that has very strict timing requirements, depending on a piece of hardware being talked to - the protocol is pretty much the same for different types of the hardware, the timing is just different.  Because I'm running on hardware with pretty low clock speeds (16-48Mhz), sometimes the delay will be 0-3 clocks, which is short enough to mean that I can't do it in asm, which is why I'm using .macros - because then when there needs to be a delay of 0 (because of the combination of clock speed and hardware timings) nothing gets emitted, if i need a delay of 1, then a single nop gets emitted, etc...)
EDIT:  I have a potential solution, it is ugly, so I'm going to leave the question up here in case folks have another option.  There's a limit to how large my delays can be, so I can basically do something along the following:
template<int X> void delay() {
    switch(X) {
      case 0: asm __volatile__ (".set X, 0\n\t"); break;
      case 1: asm __volatile__ (".set X, 1\n\t"); break;
      case 2: asm __volatile__ (".set X, 2\n\t"); break;
      case 3: asm __volatile__ (".set X, 3\n\t"); break;
      case 4: asm __volatile__ (".set X, 4\n\t"); break;
      case 5: asm __volatile__ (".set X, 5\n\t"); break;
      case 6: asm __volatile__ (".set X, 6\n\t"); break;
    }
    asm __volatile__(
        "  .macro fl_delay dtime, reg=r0    \n\t"
        "    .if (\\dtime > 0)              \n\t"
        "      .set dcycle, (\\dtime / 3)   \n\t"
        "      .set dwork, (dcycle * 3)     \n\t"
        "      .set drem, (\\dtime - dwork) \n\t"
        "      .rept (drem)                 \n\t"
        "        nop                        \n\t"
        "      .endr                        \n\t"
        "      .if dcycle >= 0              \n\t"
        "        mov \\reg, #dcycle         \n\t"
        "        loop_\\@:                  \n\t"
        "        sub \\reg, #1              \n\t"
        "        bne loop_\\@               \n\t"
        "      .endif                       \n\t"
        "    .endif                         \n\t"
        "  .endm                            \n\t"
        "  fl_delay X, r0                \n\t"
        :
        :
        : "r0");
}

void loop() { delay<5>(); }

Which means that for the delay<5>(); instantiation, there's a .set X, 5 that gets emitted just before the rest of my asm block.  It'll be ugly (my delays could be up to 120 cycles) but it will work.


text:
Q: Doubts of security: Mysqli vs PDO i've started to create my website, but now i have few doubts. I've searched, that MySqli object oriented is good to use because you can prepare the queries, use bind_param and execute. The MySqli from my website looks like this: PHP MySQLI Prevent SQL Injection
But, this is good enough? My website need a good code like this to become more secure for SQL Injection, but it makes me immune for DDoS and defaces?
Backing to the topic: Mysqli is equal to PDO in secure and performance?

A: There is no difference in security, but only in usability.
Mysqli is unusable as is, leaving PDO the only choice.


text:
Q: Why is my nginx routing my react app static files to my index.html I want to host a demo app on a subroute of my domain. When I place the app in the root of the domain and use the following configuration, it works:
server {
   server_name domain.com www.domain.com;
   root /var/www/my-app/build;
   index index.html index.htm;
   location / {
       try_files $uri /index.html =404;
   }
}

But when i move it to a subroute using the following configuration, it correctly fetches the initial index.html but then routes the static file requests (for css, js, images...) to index.html as well.
server {
        listen 80;
        server_name domain.com www.domain.com;

        location / {
        }
        location /demo-apps/my-app{
                root /var/www/my-app/build;
                try_files $uri /index.html =404;
        }
}

And I don't understand why. Here's a screen capture of the request which succeeds but returns the index.html file instad of the js file:

And here's the folder structure on the server:

As I understand it, the request from the first screen capture should match the $uri condition in the second location block and return the corresponding js file but, clearly, I'm wrong. What do I need to change for this to work?
Before anyone asks, yes, I did restart nginx.

A: The path to the file is constructed by concatenating the value of root with the value of $uri. So a request for /demo-apps/my-app/css/foo.css will be looked for at /var/www/my-app/build/demo-apps/my-app/css/foo.css, which is the wrong place.
You can use alias instead (see this document), for example:
location /demo-apps/my-app {
    alias /var/www/my-app/build;
    try_files $uri /demo-apps/my-app/index.html;
}

However, using alias and try_files together can be problematic. See this long term issue.

Or use a regular expression location (see this dcoument) to extract the latter part of the URI, for example:
location ~ ^/demo-apps/my-app(/.*)?$ {
    root /var/www/my-app/build;
    try_files $1 /index.html =404;
}


text:
Q: xcode после обновления пропали кнопки в приложении Подскажите, обновлял xcode до последний версии и как следстви пришлось обновить OS X Yosemite до версии 10,10. Запустил приложение в новом xcode и пропали кнопки на главной странице в xcode. Но если запустить приложение в симуляторе или на девайсе то они там есть и нормально работают. Они остались в приложении, но вот в левом столбце они стали полупрозрачные, как их вернуть?

A: В файле сториборда на панели Interface Builder Document уберите галочку для поля Size Classes.


text:
Q: How to determine different parts of the meal from a column of timings in python I want to get the parts of the meal ("breakfast", "lunch", "dinner") from a column of timings (9:30am-12noon,3pm-12midnight)
following is a sample of dataframe column:-
0                                10am – 1am
1                           12noon – 1:30am
2                              9:30am – 1am
3         12noon – 3:30pm, 7pm – 12midnight
4        11am – 3:30pm, 6:30pm – 12midnight
                       ...
170                           11:40am – 4am
171                            7pm – 1:30am
172                            12noon – 1am
173                            6pm – 3:30am
174                              9am – 10pm

I want to replace respective timings with respective part/parts of the meal
for example, if 11am - 3:30pm then replace it with ["breakfast","lunch"]  if 9am:10pm then replace it with ["breakfast","lunch","dinner"] and so on.

A: My solution:
import re

def parse_time(t):
    t = t.strip()
    hours = int(re.findall('^[0-9]+', t)[0])
    m = re.findall(':([0-9]+)', t)
    if len(m) > 0:
        minutes = int(m[0])
    else:
        minutes = 0
    afternoon = re.search('(pm)|(midnight)', t)
    if afternoon:
        hours += 12
    return (hours, minutes)

def get_parts(s):
    x = re.split('–|-', s)
    start, end = x[0].strip(), x[1].strip()
    start_hours, start_minutes = parse_time(start)
    end_hours, end_minutes = parse_time(end)
    parts = []
    if start_hours < 11: # or whenever you think breakfast ends
        parts.append("breakfast")
    if 12 < start_hours < 15 or 12 < end_hours < 15:
        parts.append("lunch")
    if end_hours > 17:
        parts.append("dinner")
    return parts

def get_all_parts(data):
    x = [set(get_parts(s)) for s in data.split(",")]
    return set.union(*x)

print(get_all_parts("10am-3:30pm"))
print(get_all_parts("11am - 3:30pm, 6:30pm - 12midnight"))
print(get_all_parts("10am - 11am, 5pm-7pm"))


text:
Q: How i can add function to already exist function I have function.php in plugin. (This plugin works with the theme).
In already exist function.php have
add_action( 'wp_ajax_nopriv_tmp_register', 'tmp_register' );
add_action( 'wp_ajax_tmp_register', 'tmp_register' );

function tmp_register() {

...bla bla

}

How i can add some my_own function to this already exists function?
Im try already by
if( !function_exists('tmp_register') )

add_filter('tmp_register', 'my_register', 10, 1);

if( !function_exists('tmp_register') ) {
    function my_register(){

        $usermobile          = trim( sanitize_text_field( wp_kses( $_POST['usermobile'], $allowed_html ) ));

        update_user_meta( $user_id, 'user_mobile_meta_value', $usermobile );

}

}

A: You need to remove the hook and then add with the function you want.
In your theme's functions.php
remove_action( 'wp_ajax_nopriv_tmp_register', 'tmp_register' );
remove_action( 'wp_ajax_tmp_register', 'tmp_register' );
add_action( 'wp_ajax_nopriv_tmp_register', 'your_own_tmp_register' );
add_action( 'wp_ajax_tmp_register', 'your_own_tmp_register' );
function your_own_tmp_register(){
/*do what you need*/
}


text:
Q: Given that the Fourier coefficients of the function prove that the function is continuous Here is the problem:
Given that the Fourier coefficients of the function $f(x)$ are:
$a_n=0$ , $b_n= \frac{1}{n!}$

*

*Prove or disprove that $f(x)$ is continuous

*Find the function explicitly

*What are the Fourier coefficients of $f'(x)$


text:
Q: nodejs array.push(...). array empty Почему получаю в результате пустой список?
Промежуточные выводы дают заполненные объекты, но такое чувство, что где то создается временный объект (массив) в который и пушится значение, а переданный в параметрах не заполняется.
Код:
var needle = require('needle');
var cheerio = require('cheerio');

function scrap(src_arr, res_arr){
    for(word of src_arr){
        var url = "https://wooordhunt.ru/word/" + word;
        console.debug(url)

        needle.get(url, function(err, res){
            if (err) throw err;

            var $ = cheerio.load(res.body);
            res_arr.push({
                word: $("#wd_title>h1").text().toLowerCase(),
                transcription_us: $("#us_tr_sound>span").text(),
                transcription_uk: $("#uk_tr_sound>span").text(),
                translation: $(".t_inline_en").text(),
            });
        });
    }
}

var src_words = ["about", "add", "afternon", "again"]
var result = [];
scrap(src_words, result)
console.log(result.length);

Результат:
https://wooordhunt.ru/word/about
https://wooordhunt.ru/word/add
https://wooordhunt.ru/word/afternon
https://wooordhunt.ru/word/again
0

A: var needle = require('needle');
var cheerio = require('cheerio');
function a_get(url, res_arr){
    return new Promise(function(resolve, reject){
            needle.get(url, function(err, res){
            if (err) throw err;

            var $ = cheerio.load(res.body);
            resolve(res_arr.push({
                word: $("#wd_title>h1").text().toLowerCase(),
                transcription_us: $("#us_tr_sound>span").text(),
                transcription_uk: $("#uk_tr_sound>span").text(),
                translation: $(".t_inline_en").text(),
            }));
        });
    });
}

async function scrap(src_arr, res_arr){
    for(word of src_arr){
        var url = "https://wooordhunt.ru/word/" + word;
        console.debug(url)
        await a_get(url, res_arr);

    }
}

var src_words = ["about", "add", "afternon", "again"]
var result = [];
scrap(src_words, result).then(res => console.log(result.length));

Все дело в асинхронности. ТЫ выводишь  длину массива до того, как выполнится get запрос. Промисы и async/await(по сути то же,что и промис, просто синтаксический сахар) помогли решить твою проблему


text:
Q: inf of a finite set I often see the notation
$$\inf \{x_1,..,.x_n\}$$
or
$$\inf\{s,t\}$$
Is this considered appropriate notation or is it considered better to use $\min$ in these cases?

A: Using $\mathrm{inf}$ is not incorrect, but may cause a moments pause when someone reads it.  Using $\mathrm{min}$ will not cause this pause.  Your goal should always be to communicate as effectively as possible so go with $\mathrm{min}$ unless you have a specific and compelling reason not to.

A: It depends on the order you have on the set. Even with finite sets, an infimum can differ from a minimum. The infimum is the greatest lower bound while the minimum is an infimum belonging to the original set.
Take the set $\{0,1,2\}$ with the partial order $\prec$ defined by : $0\prec 1$ and $0\prec 2$. Then
$$ \inf \{1,2\} = 0 $$
but $\min\{1,2\}$ does not even exist.

A: Whichever you use it is okay, but there is a difference.
For min the result must be an element of the set while for inf that doesn't have to be the case.
$\inf \{ i\mid i = 1/2 ^ n\} = 0$
while $0$ is not part of the set
$\min \{ i\mid i = 1/2 ^ n\}$ is undefined because what is the lowest value in the set?

A: um.there is no distinction between them,but I prefer min.


text:
Q: Are palindromic triples of roots of any interest in algebraic group E6? Consider the 72 roots of the algebraic group E6 in their most symmetric coordinatization (in 9-space), as given in the section "Roots of E6" here:
https://en.wikipedia.org/wiki/E6_(mathematics)
From these roots, we can clearly form ordered palindromic triples of roots RiRjRk where Ri is the same root as Rk.
Are such ordered palindromic triples of roots of any particular interest in E6 or structures derived from E6?
If so, where and why?
Thanks for whatever time you can afford to spend considering this question.


text:
Q: Set a Kubernetes Secret with data from an external Key Vault I'm using ArgoCD (a GitOps tool) to deploy my Helm project in a Kubernetes cluster.  My cluster is configured to connect to my external key vault, so once my application is deployed to my cluster, it can fetch an access token and grab any secret it needs in the vault.  My project also has a use case in which is spins up a new pod within my cluster to run some batch process, and this pod uses a imagePullSecret to connect to my private registry that contains an image for this pod.
If this imagePullSecret is present in my cluster and in the same namespace as my project, this process works.  However, I'm trying to keep my project IaC as cluster agnostic as possible.  Basically, should I spin up a new Kubernetes cluster, I can deploy my project to this cluster without any manual changes needed, and the project has everything it needs to run.
What I want to do is add a yaml file in my template folder that defines a secret in the cluster (which will be my imagePullSecret) so that I know that secret will always be there.  Since this secret is project dependent, assume that the IaC code to deploy the cluster will not do this task.  Of course, to be secure, I don't want to have the actual secret data in the file itself.
As my cluster is already seamlessly connected to an external Key Vault, I'm wondering if there's a way to fetch this information from the vault at the time of deployment.  So the secret yaml would look like:
kind: Secret
apiVersion: v1
metadata:
  name: superSecretData
  namespace: projectNameSpace
  # Maybe some connection annotation needed here?
type: dockerconfigjson
data:
  secretData: <Data from Key Vault>

I saw there was some small project for this, but I wanted to know if there is a more...standard way to do it.  When searching online for a solution, there are many to set secrets in a Pod, but I want to actually create a Kubernetes secret in my namespace.  My GitOps tool may be able to do this, and may be a solution to this problem, but if I can avoid this middleman situation (KV -> ArgoCD -> k8s secret -> project instead of just KV -> k8s secret -> project) I would like to go that route


text:
Q: jquery.dataTables with hidden columns crash my JQuery I am using the datatables library in an AdminLTE. I use a small JQuery code to bring the data to an edit modal.
$(document).ready(function () {
/* =========================================================
      EDITAR ALERGENOS
==========================================================*/
$(".btn-warning").click(function (e) {
    e.preventDefault();
    $('#alergenoEditModal').modal('show');
    // capturamos la informacion de la fila
    var alergeno = e.currentTarget.parentElement.parentNode;
    var nombre_ES = alergeno.children[1].innerHTML;
    var nombre_CA = alergeno.children[2].innerHTML;
    var nombre_EN = alergeno.children[3].innerHTML;
    var nombre_DE = alergeno.children[4].innerHTML;

    $('#edit_nombre_ES').val(nombre_ES);
    $('#edit_nombre_CA').val(nombre_CA);
    $('#edit_nombre_EN').val(nombre_EN);
    $('#edit_nombre_DE').val(nombre_DE);

});

});

Everything works until the moment when the columns are hidden to be responsive. At that moment the action does not respond to me.
In full screen we press the yellow edit button.

And the modal appears with the data to edit. All right.

However, when the screen is reduced and the buttons are hidden ...

We press the blue button to bring up the yellow edit button ... ... and it doesn't work

I don't understand where the problem is.

A: You have to use event delegation for dynamically added elements. Try this -
$(document).ready(function () {

    $(document).on('click', ".btn-warning", function (e) {
        e.preventDefault();
        $('#alergenoEditModal').modal('show');
        // capturamos la informacion de la fila
        var alergeno = e.currentTarget.parentElement.parentNode;
        var nombre_ES = alergeno.children[1].innerHTML;
        var nombre_CA = alergeno.children[2].innerHTML;
        var nombre_EN = alergeno.children[3].innerHTML;
        var nombre_DE = alergeno.children[4].innerHTML;

        $('#edit_nombre_ES').val(nombre_ES);
        $('#edit_nombre_CA').val(nombre_CA);
        $('#edit_nombre_EN').val(nombre_EN);
        $('#edit_nombre_DE').val(nombre_DE);

    });

});


text:
Q: Converting iPhone app to Universal, XCode 5.1 and Storyboards. Bug? I just updated my XCode to 5.1.
My application is targeting iOS 7 and it has 1 single storyboard that it is targeting iPhone only.
Now I need to convert my app from iPhone only to Universal.
When changing the devices from iPhone to Universal I get prompt to if I want to copy the storyboard or not. I click on copy. After selecting Copy I get a new folder called iPad that it is empty and I continue to only have 1 Storyboard (the iPhone one).
However, the iPad section of the application is now referencing a storyboard called "Main-iPad" which does not exist. I believe this storyboard should've been created automatically.
If I run the app in the iPad emulator, the app runs but the console outputs this:
NSMainNibFile and UIMainStoryboardFile are both set. NSMainNibFile ignored.

If I chose not to copy, then the iPad folder does not get created and I continue with 1 storyboard and the ipad is referencing the iPhone storyboard (the only storyboard I have).
I can replicate this with a single view brand new project as well.
Also, XCode 5.1 does not seem to let me duplicate my storyboard or change the type of an existing storyboard from iPhone to iPad.
Any suggestions?

A: Yep - it's a bug under iOS7. To fix the error message go into the .plist and delete the line that specifies the iPad xib name. You'll just then have to copy the iPhone storyboard and rename iPad-Main.


text:
Q: Bind image load errors in the  Is there a way to bind to the load() event of an image after changing it's src? is 2 years old
How to remove future broken image using jquery has not been answered successfully
NOTE: I am fully aware of how to handle the image failing to load AS it is loading - I could add a placeholder image and then assign the onerror handler in the same loop I am assigning the actual src like this DEMO
I am trying to EITHER run down a page of images and handle already failed images (not optimal) OR
have jQuery bind all img.onerror in given selector before the page is loading (Better solution)
So I thought of ON in the head:
DEMO
$("figure img").on("error",function () {
  console.log("error")
  $(this).parents(".content-holder").removeClass("p-alt");
  $(this).parents("figure").remove();
});

but that does not work - nothing removed and nothing in the console.
I have looked at naturalWidth, but that is not supported by all browsers

A: how can you bind an event to an element that doesn't exist at that point? $("figure img") does not select anything as those elements don't exist on the page yet.


text:
Q: What is a semaphore wait? I got the following error in my MariaDB 10.x hostname.err log:
InnoDB: ###### Diagnostic info printed to the standard error stream
InnoDB: Error: semaphore wait has lasted > 600 seconds
InnoDB: We intentionally crash the server, because it appears to be hung.

Can someone please explain (as simply as possible ;-D) what a "semaphore wait" is within the context of MySQL/MariaDB?
All I could gather from Mr. Google is that they are "related to internal synchronization between threads in mysqld"

A: Semaphores throttle access to a resource.  If it's not available a process has to wait until it is.  Very long waits can signal that you have a deadlock situation and something needs to be killed to break it up.
https://stackoverflow.com/questions/2332765/lock-mutex-semaphore-whats-the-difference

A lock allows only one thread to enter the part that's locked and the
  lock is not shared with any other processes.
A mutex is the same as a lock but it can be system wide (shared by
  multiple processes).
A semaphore does the same as a mutex but allows x number of threads to
  enter, this can be used for example to limit the number of cpu, io or
  ram intensive tasks running at the same time.


text:
Q: Empty POST method I am totally new in PHP and i have problem with posting data. I try to post data and write it in txt file. I already increase my post max size in php.ini. I use XAMPP
<form action="forms/save_news.php" method="post" role="form">

        <input type="text" name="date" class="form-control" id="date" placeholder="Дата" data-rule="minlen:10" data-msg="Моля въведете дата" />

        <input type="text" class="form-control" name="title" id="title" placeholder="Заглавние"/>

        <textarea class="form-control" name="data" rows="5" data-rule="required" data-msg="Моля въведете съдържание" placeholder="Новина"></textarea>

<button type="submit">Запиши</button>

</form>

And my PHP code is:
<?php
if(isset($_POST['date'])) {
   $date = $_POST['date'];
   $fp = fopen('data.txt', 'a');
   fwrite($fp, $date);
   fclose($fp);
}
?>

A: My first guess would be a permission issue.  What I would do to troubleshoot this is to turn on error reporting in your PHP script.  Try the following code:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (isset($_POST('date')) {
  $date = filter_var($$_POST['date'], FILTER_SANITIZE_STRING);
  $fp = fopen('data.txt', 'a');
  fwrite($fp, $date);
  fclose($fp);
}
?>

Post another request from your form and see what appears in the browser.  The errors that are reported should tell you where the problem is, but if you aren't positive how to fix the errors.
Now, all that said, be sure to never trust data sent from a web form.  For simply testing purposes, you can do what you are doing, but I would not recommend getting into the habit since it can breed complacency.  Note the change I made to the line that assigns the value of the form field to the $date variable.  It uses a filter_var function to sanitize the string.  There are plenty of combinations, and it is best to understand exactly how you are going to use the data, eventually to choose the correct filter(s).

A: You may consider an extra check. For example, if $_POST['date'] contained an empty string, it would pass isset() and would still append this to the Text file.
PHP Version is also a consideration here.
Try:
<?php
if(isset($_POST['date']) && !empty($_POST['date'])) {
  $date = $_POST['date'];
  if (is_writable('date.txt'){
    $fp = fopen('date.txt', 'a');
    if(fwrite($fp, $date) === FALSE){
      echo "Cannot write to file";
      exit;
    }
    fclose($fp);
  } else {
    echo "The file is not writable.";
  }
}
?>

Also, this script assumes that date.txt and save_news.php reside in the same folder path. Is date.txt in forms folder? If it is not you will want to ensure that the script can reach the file and there are proper permissions for XAMPP and PHP to Read, Write to this file.
If date.txt is elsewhere, maybe in the parent, use:
$fp = fopen('../date.txt', 'a');

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled open_basedir further restrictions may apply.

https://www.php.net/manual/en/function.fopen.php


text:
Q: How to implement luabidi so that I can use luacode in XeLaTeX I would like to use the following luacode (follow-up from this post):
\usepackage{luacode}
\begin{luacode*}

function replace_punc ( buff )
   if string.find ( buff , "\\gla" ) then
      buff = string.gsub ( buff , " (``)" ,
             "\\nogloss{%1} @ " )
      buff = string.gsub ( buff, "([:.,;'!?]+)( )" ,
          " @ \\nogloss{%1}%2" )

   end
   return ( buff )
end

luatexbase.add_to_callback ( "process_input_buffer", replace_punc, "replace_punc" )
\end{luacode*}

Its purpose is to automate \nogloss.
It works with LuaLaTeX, but my whole document is set up with polyglossia, which is incompatible with LuaLaTeX. @alanmunn mentioned that the above code could work with XeLaTeX if I use the luabidi package. I have played around with luabidi without success.
I would like the above code to work in XeLaTex with the following MWE:
\documentclass{book}

\usepackage{expex}
\usepackage{polyglossia}
\usepackage{fontenc}
\setdefaultlanguage{english}
\setotherlanguage{hebrew}
\newfontfamily\hebrewfont[Script=Hebrew]{FrankRuehl}
\newfontfamily\englishfont{Linux Libertine O}

\lingset{everygla=\Large,glwordalign=center}

\begin{document}
\begin{hebrew}

\begingl
  \gla "שלום {קוראים לי} דוד." //
  \glb shalom \textenglish{korim li} david//
  \glc Hello \textenglish{my name is} David//
\endgl

\begingl
  \gla "מה נשמע דוד?" //
  \glb ma nishma david //
  \glc what \textenglish{is heard} David //
\endgl

\begingl
  \gla "יום טוב!" //
  \glb yom tov //
  \glc day good //
\endgl

\end{hebrew}
\end{document}

A: Your question doesn't make much sense. The luacode will work only in luatex. There is absolutly no chance to get it working with xelatex.
Your document compiles for me with lualatex if I add some code to get \luatexpardir and \luatextextdir (see https://tex.stackexchange.com/a/273303/2388).  I also had to change the font.
But I have no idea how good the bidi code works with lualatex as I can't read hebrew.
\directlua{
tex.enableprimitives("luatex",tex.extraprimitives("omega","luatex"))
}

\documentclass{book}

\usepackage{expex}
\usepackage{polyglossia}
\usepackage{fontenc}
\setdefaultlanguage{english}
\setotherlanguage{hebrew}
\newfontfamily\hebrewfont[Script=Hebrew]{EzraSIL}
\newfontfamily\englishfont{Linux Libertine O}

\lingset{everygla=\Large,glwordalign=center}

\begin{document}
\begin{hebrew}

\begingl
  \gla "שלום {קוראים לי} דוד." //
  \glb shalom \textenglish{korim li} david//
  \glc Hello \textenglish{my name is} David//
\endgl

\begingl
  \gla "מה נשמע דוד?" //
  \glb ma nishma david //
  \glc what \textenglish{is heard} David //
\endgl

\begingl
  \gla "יום טוב!" //
  \glb yom tov //
  \glc day good //
\endgl

\end{hebrew}
\end{document}


text:
Q: How to execute command and use it's result in sed correctly? I have a config file in JSON format with following block
"device" :
{
    "name"       : "MyPi",
    "type"       : "ws2801",
    "output"     : "/dev/spidev0.0",
    "rate"       : 250000,
    "colorOrder" : "rgb"
},

I use sed (non GNU version on OS X) to replace the string values with sed expression like this:
sed -i '' '1h;1!H;$!d;x;s#\("device" :[^}]*"colorOrder"[ ]*: \)"[^"]*"#\1"grb"#' hyperion.config.json
Now I want to replace "output": line with the result of ls /dev/tty.usbmodem* with this command:
sed -i '' -e '1h;1!H;$!d;x;s#\("device" :[^}]*"output"[ ]*: \)"[^"]*"#\1"$(ls /dev/tty.usbmodem*)"#' hyperion.config.json
However ls is not executed and I get "output"     : "$(ls /dev/tty.usbmodem*)",
I tried replacing single quotes with double quotes with escaping inside the expression, that didn't work.
So how can I replace the value of the output (inside the "device" block) with the output of ls command?

A: Add quotes like in the example below.
Replace:
'xxx"$(ls /dev/tty.usbmodem*)"xxx'

by:
'xxx"'"$(ls /dev/tty.usbmodem*)"'"xxx'

A: replace the part (inside the single quotes)
$(ls /dev/tty.usbmodem*)

by
'"$(ls /dev/tty.usbmodem*)"'

hence exiting the single quote part and entering a double quote for the command, then reentering single quote.


text:
Q: How to save to a ImageField from an ftp download in Django Currently I am saving a file to a loal directory from a ftp server. But I want to move to using ImageFields to make things more manageable.
here is the current code snippet
file_handle = open(savePathDir +'/' +  fname, "wb")
nvcftp.retrbinary("RETR " + fname, _download_cb)
file_handle.close()
return savePathDir +'/' +  fname

Here is my first attempt at matching. I am returning the path just for compatibilities sake for now. Later I will access the stored files properly through the model.
new_image = CameraImage(video_channel = videochannel,timestamp = file_timestamp)
file_handle = new_image.image.open()
nvcftp.retrbinary("RETR " + fname, _download_cb)
file_handle.close()
new_image.save()
return new_image.path()

Is this correct?
I am confused about what order I should deal with the file_handle and the ImageField "image"

A: You are missing _download_cb, so I'm not using it.
Refs The File Object of Django. Try
# retrieve file from ftp to memory,
# consider using cStringIO or tempfile modules for your actual usage

from StringIO import StringIO
from django.core.files.base import ContentFile
s = StringIO()
nvcftp.retrbinary("RETR " + fname, s.write)
s.seek(0)
# feed the fetched file to Django image field
new_image.image.save(fname, ContentFile(s.read()))
s.close()

# Or
from django.core.files.base import File
s = StringIO()
nvcftp.retrbinary("RETR " + fname, s.write)
s.size = s.tell()
new_image.image.save(fname, File(s))