Q: Frame 1:26 - What does q unify with? We have:
(run* q
  (fresh (x)
    (==
      `(,x)
      q)))

In this case  `(,x) is a list where the refrence to the variable x isn't quoted.
Does q unifies with a single element list?
Is the result (_0) because q unifies with the fresh variable x (even if it's in a list) or because it doesn't unify with anything at all? Or would in that case the result have been ()?

A:
Does q unify with a single element list?

Yes. (== (list x) q) is the same as (== q (list x)). Both q and x are fresh before the execution of this unification goal (and q does not occur in (list x)). Afterwards, it is recorded in the substitution that the value of q is (list x). No  value for x is recorded.

Is the result (_0) because q unifies with the fresh variable x (even if it's in a list) or because it doesn't unify with anything at all? Or would in that case the result have been ()?

No, q does not unify with x, but rather with a list containing x.
When the final value of the whole run* expression is returned, the variables are "reified", replaced with their values. x has no value to be replaced with, so it is printed as _0, inside a list as it happens, which list is the value associated with q.
The value of (run* q ...) is a list of all valid assignments to q, as usual. There is only one such association, for the variable q and the value (list x).
So ( (_0) )  should be printed as the value of the (run* q ...) expression -- a list of one value for q, which is a list containing an uninstantiated x, represented as a value _0.


Q: jQuery slider not adding active slide class I'm having an issue with a slider I've put together (with navigation to each slide). The issue being that the .active-slide class is not being added correctly to the next slide. I've had this working in CodePen - http://codepen.io/davelivesey/pen/mEBkAa - but as soon as I transplant that into my project it breaks, the main issue being the .active-slide class is no longer added to the next slide.
I've added a $(document).ready( ... around it, but this doesn't fix it. There are no conflicts with any other code I've written and both the CodePen and the project use the same version of jQuery (2.2.4).
Here's the code that's not working in the project. I've removed some of the CSS for the sake of brevity!
HTML

I'm slide one.

I'm slide two.

I'm slide three.

CSS(SASS)
#slider {
  width: 100%;
  height: 600px;
  position: relative;
  background-color: rgb(240,240,240);

  .slide {
    width: 100%;
    height: 600px;
    position: absolute;
    top: 0;
    display: none;
  }
}

.slide.active-slide {
  display: block;
}

#slider-nav ul {
  list-style: none;
  text-align: center;

    li {
      display: inline-block;
      margin-right: 5px;

      a span {
        display: inline-block;
        width: 10px; height: 10px;
        border-radius: 10px;
        border: 1px solid rgb(130,130,130);
    }
  }

  li.active a span {
    background-color: rgb(180,180,180);
  }
}

jQuery:
$(document).ready( function() {

    var $slides  = $('#slider .slide'),
        $navWrap = $('#slider-nav ul');

    function nextSlide() {
        var $next = $('#slider-nav ul li.active').next();
        if ($next.length === 0){
            $next = $('#slider-nav ul li:first-of-type');
        }
        $next.click();
    }
    function slideTransition(index) {

        $('#slider .slide.active-slide').delay(6000).fadeOut(500, function() {
            $(this).removeClass('active-slide');
        });

        $('#slider .slide:eq(' + index + ')').fadeIn(500, function() {
            $(this).addClass('active-slide');
        });
    }

    $slides.each( function(index) {
        $navWrap.append('

');
    });

    var timer = setInterval(nextSlide, 6000);
    $('#slider .slide:first').addClass('active-slide').fadeIn(200);
    $('#slider-nav ul li').click(function() {
        clearInterval(timer);
        $(this).siblings('.active').removeClass('active');
        $(this).addClass('active');
        var index = $(this).index('li');
        slideTransition(index);
        timer = setInterval(nextSlide, 6000);
        return false;
    });

    $('#slider-nav ul li:first-of-type').click();

});


Q: Conditionally add class to image by jquery This JS replace image file name default.jpg to hqdefault.jpg from all images below. But now I'm trying to add class to Image, if Image src has img.youtube.com link on images by extending this JS.
JS:
$('#selector img').attr('src',function(i,e){
    return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
});

HTML:

Means, If image src has Youtube image then add a class .video to parent image.

A: Try:
$('#selector img').each(function(i) {
    var self = $(this);
    var src = self.attr('src');
    if (src.match(/img.youtube.com/)) {
        self.attr('src', src.replace("/default.jpg","/hqdefault.jpg"));
        self.addClass('video');
    }
});

A: You can add a condition before replacing and add video class.
$('#selector img').attr('src',function(i,e){
    if($(this).attr('src').search('img.youtube.com') > 0){
         $(this).addClass('video');
    }
    return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
});


Q: BIML: Issues about Datatype-Handling on ODBC-Source Columns with varchar > 255 I'm just getting into BIML and have written some Scripts to creat a few DTSX-Packages. In general the most things are working. But one thing makes me crazy.
I have an ODBC-Source (PostgreSQL). From there I'm getting data out of a table using an ODBC-Source. The table has a text-Column (Name of the column is "description"). I cast this column to varchar(4000) in the query in the ODBC-Source (I know that there will be truncation, but it's ok). If I do this manually in Visual Studio the Advanced Editor of the ODBC-Source is showing "Unicode string [DT_WSTR]" with a Length of 4000 both for the External and the Output-Column. So there everything is fine. But if I do the same things with BIML and generate the SSIS-Package the External-Column will still say "Unicode string [DT_WSTR]" with a Length of 4000, but the Output-Column is telling "Unicode text stream [DT_NTEXT]". So the mapping done by BIML differs from the Mapping done by SSIS (manually). This is causing two things (warnings):

*

*A Warning that metadata has changed and should be synced

*And a Warning that the Source uses LOB-Columns and is set to Row by Row-Fetch..

Both warnings are not cool. But the second one also causes a drasticaly degredation in Performance! If I set the cast to varchar(255) the Mapping is fine (External- and Output-Column is then "Unicode string [DT_WSTR]" with a Length of 255). But as soon as I go higher, like varchar(256) it's again treated as [DT_NTEXT] in the Output.
Is there anything I can do about this? I invested days in the Evaluation of BIML and find many things an increase in Quality of Life, but this issue is killing it. It defeats the purpose of BIML if I have to correct the Errors of BIML manually after every Build.
Does anyone know how I can solve this Issue? A correct automatic Mapping between External- and Output-Columns would be great, but at least the option to define the Mapping myself would be ok.
Any Help is appreciated!
Greetings
Marco
Edit As requested a Minimal Example for better understanding:

*

*The column in the ODBC Source (Postegres) has the type "text" (Columnname: description)

*I select it in a ODBC-Source with this Query (DirectInput):
SELECT description::varchar(4000) from mySourceTable

*The ODBC-Source in Biml looks like this:
<OdbcSource Name="mySource" Connection="mySourceConnection"> <DirectInput>SELECT description::varchar(4000) from mySourceTable</DirectInput></OdbcSource>

*If I now generate the dtsx-Package the ODBC-Source throws the above mentioned warnings with the above mentioned Datatypes for External and Output-Column

A: As mentioned in the comment before I got an answer from another direction:
You have to use DataflowOverrides in the ODBC-Source in BIML. For my example you have to do something like this:
`<OdbcSource Name="mySource" Connection="mySourceConnection">
  <DirectInput>SELECT description::varchar(4000) from mySourceTable</DirectInput>
  <DataflowOverrides>
    <OutputPath OutputPathName="Output">
      <Columns>
        <Column ColumnName="description" SsisDataTypeOverride="DT_WSTR" DataType="String" Length="4000" />
      </Columns>
    </OutputPath>
    <OutputPath OutputPathName="Error">
      <Columns>
        <Column ColumnName="description" SsisDataTypeOverride="DT_WSTR" DataType="String" Length="4000" />
      </Columns>
    </OutputPath>
  </DataflowOverrides>
</OdbcSource>`

You won't have to do the Overrides for all columns, only for the ones you have mapping-Issues with.
Hope this solution can help anyone who passes by.
Cheers


Q: Can we create a link with dynamic ID in SPA model I am developing a single page application using ReactJS. My whole application is running in Single Page. Now, I need one page that accept the used ID from the URL and show the result based on the user ID.
Is this possible in SPA model or I have to move the my website to MPA model?
I tried some answers and am not clear about it
for ex: https://stackoverflow.com/questions/id/101
I have to get the ID 101 and show the result based on the id in the page.

A: yes sure this is possible.
Let me give you some background over this. If you are building SPA with multiple pages, you would like to use a client-side routing in otder to display differen page based on the browser url. As I know defacto solution for routing in react is react-router but there are many other to chose from. See this link. Unfortunately, I won't be able to completely explain how to use react-router solution, but here is a brief example.
Inside your main component (like App.jsx) add routing:
// 1. do proper imports
import { BrowserRouter } from "react-router-dom";

// 2. wrap your application inside of BrowserRouter component

class App extends React.Component {
// your code

    render() {
        return (
            <BrowserRouter>
                {/* your app code */}

                {/* Add routing */}
                <Route path="/" exact component={Dashboard} />
                <Route path="/questions/id/:id" component={Question} />

                {/* your app code */}
            <BrowserRouter>
        )
    }
}

You should see now that when your browser url matches /questions/id/:id component Question should be mounted to the page. Inside this component, you can fetch id that was passed in. It will be inside this.props.match.param.id property
class Question extends React.Component {
// your code

    render() {
        const id = this.props.match.param.id;

        return (

                Page with { id } was opened

        )
    }
}

Sure you would like to familiarise yourself with react-router docs.

A: ReactJs don't include a router. But the most popular package to do this is React-router.
The official documentation references other good packages


Q: How to retrieve current server FQDN in a java class I need to compose a dynamic URL based on current host running the web application.
I have a backgrund process launched on startup via ServletContextListener.
This thread has to send emails to customers with a registration ticket. In the email text I need to print the complete URL to my webapp and the servlet. Lets say those emails like "click here to confirm your subscription or copy&paste blabla...."
How my I obtain the FQDN of my running webapp?
It's not a servlet so I cannot relay on a HttpServletRequest instance and the server has many virtual hosts.
Here is where I launch the thread:
public class Initializer implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        Log.addItem("SYSTEM START");

        PasswordRecoveryListener pwlisten = new PasswordRecoveryListener(1000 * 60 * 1);
        pwlisten.start();
    }
}

In arg0.getServletContext().getContextPath() I found nothing but the path.
I looked for the hostname in the Context (where I have other constants) but without success.


Q: prototype function error : is not a function I tried to encapsulate a javascript object and declared some prototype function. But there were some errors.
Here is my code:
const editor_theme = require('./editor-theme.js')

let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}')
defaultTheme.setTitlebarColor('888888')
console.log(defaultTheme.getTitlebarColor())

//main.js

module.exports = {
    Editor_Theme: function (data) {
        var _themeData = JSON.parse(data)

        var _titlebar_color = _themeData.titlebar_color
        var _background_color = _themeData.background_color

        const Func = function() { }

        Func.prototype = {
            getTitlebarColor : function () {
                return _titlebar_color
            },
            getBackgroundColor : function () {
                return _background_color
            },
            setTitlebarColor : function (titlebarColor) {
                _titlebar_color = titlebarColor || _titlebar_color
            }
        }

        Object.freeze(Func)
        Object.freeze(Func.prototype)

        return Func
    }

}

//editor-theme.js

The error log is it:

Uncaught TypeError: defaultTheme.setTitlebarColor is not a function

A: Your constructor now returns another constructor function, not an object. Return an instance of that constructor instead:

// module.exports = {
let moduleExports = {

  Editor_Theme: function(data) {

    var _themeData = JSON.parse(data)

    var _titlebar_color = _themeData.titlebar_color
    var _background_color = _themeData.background_color

    const Func = function() {}

    Func.prototype = {
      getTitlebarColor: function() {
        return _titlebar_color
      },
      getBackgroundColor: function() {
        return _background_color
      },
      setTitlebarColor: function(titlebarColor) {
        _titlebar_color = titlebarColor || _titlebar_color
      }
    }

    Object.freeze(Func)
    Object.freeze(Func.prototype)

    return new Func() //Instantiate constructor
  }

}

// const editor_theme = require('./editor-theme.js')
const editor_theme = moduleExports

let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}')
defaultTheme.setTitlebarColor('888888')
console.log(defaultTheme.getTitlebarColor())

Or even better, just Object.create an object with a custom prototype:

// module.exports = {
let moduleExports = {

  Editor_Theme: function(data) {

    var _themeData = JSON.parse(data)

    var _titlebar_color = _themeData.titlebar_color
    var _background_color = _themeData.background_color

    const prototype = {
      getTitlebarColor: function() {
        return _titlebar_color
      },
      getBackgroundColor: function() {
        return _background_color
      },
      setTitlebarColor: function(titlebarColor) {
        _titlebar_color = titlebarColor || _titlebar_color
      }
    }

    Object.freeze(prototype)

    return Object.create(prototype) //Object with custom prototype
  }

}

// const editor_theme = require('./editor-theme.js')
const editor_theme = moduleExports

let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}')
defaultTheme.setTitlebarColor('888888')
console.log(defaultTheme.getTitlebarColor())


Q: Emacs does not react when I press C-. (dot/period) I am learning Agda and when I type C-cC-. there is no reaction in my Emacs. I can type either C-c. or C-cM-. and then I will be told that these bindings are not defined. But when I try to type C-cC-. the mini-buffer only shows C-c and it seems that Emacs is waiting for the next key binding. So how should I fix this problem?
I am using a MacOS. Any help will be appreciated.


Q: ZOOM-IN & ZOOM-OUT 2D graphics C# i have  to ZOOM-IN & ZOOM-OUT specific portion of  2D-graphics like (line, Rectangle, circle) which i have drawn on winform.
I am not used any picture box, panel.
I crated simple program to draw circle & on button click try to zoom
but it showing error "parameter is not valid"
in method Drawing() @ Line- DeviceContexct.Transform = mainViewTransform;
public Graphics DeviceContexct;
  public Matrix mainViewTransform = new Matrix();

    private void ScalingCircle_Paint( object sender, PaintEventArgs e )
            {
                Pen myPen = new Pen(Color.Blue, 1);
                e.Graphics.DrawRectangle(myPen, 50, 50, 100, 100);
                mainViewTransform.Scale(3, 2);
                DeviceContexct = e.Graphics;
            }
     private void Drawing(Graphics gr)
            {
                Pen myPen2 = new Pen(Color.Red, 1);
                DeviceContexct.Transform = mainViewTransform;
                DeviceContexct.DrawRectangle(myPen2, 50, 50, 100, 100);
            }
       private void button1_Click( object sender, EventArgs e )
            {
                Drawing(DeviceContexct);

            }

A: I prefer to draw into Bitmaps with System.Drawing.Graphics object.
Then you can use your graphics object with "go.DrawImage(...)" to draw the bitmap directly into your winforms and actually give it a scale.
https://msdn.microsoft.com/en-us//library/ms142040(v=vs.110).aspx

A: I got the solution, thanks for your help.
I only need to call refresh/invalidate etc on button click.
public partial class ScalingCircle : Form
{
    public Graphics DeviceContexct;
    // current transformation matrix of main view (offset & scaling)
    public Matrix mainViewTransform = new Matrix();

    public int scale = 1;

    public ScalingCircle()
    {
        InitializeComponent();
        DeviceContexct = Graphics.FromHwnd(this.Handle);
        DeviceContexct = this.CreateGraphics();
    }

    public void ScalingCircle_Paint(object sender, PaintEventArgs e)
    {
        DeviceContexct = e.Graphics;
        DeviceContexct.PageUnit = GraphicsUnit.Pixel;
        DeviceContexct.Transform = mainViewTransform;
        ScalingCircle1(scale);
    }

    private void ScalingCircle1(int x )
    {
        Pen myPen2 = new Pen(Color.Black, 1);
        DeviceContexct.Transform = mainViewTransform;

        Rectangle myRectangle = new Rectangle(50, 50, 100 * x, 100 * x);
        DeviceContexct.FillRectangle(new SolidBrush(Color.BurlyWood), myRectangle);
    }

    private void ScalingCircle_Load( object sender, EventArgs e )
    {
        this.ResizeRedraw = true;
      }

    private void button1_Click( object sender, EventArgs e )
    {
        scale += 5;
        this.Refresh();
    }

    private void button2_Click( object sender, EventArgs e )
    {
        if (scale > 1)
        {
            scale -= 5;
            this.Refresh();
        }
    }
}

A: You can use transformations for that. The graphics object you use for painting things has a Transformation property of type System.Drawing.Drawing2D.Matrix.
Graphics also has the ScaleTransform method.
I haven't used it myself, but that is how microsofts Chart does it.
https://msdn.microsoft.com/de-de/library/system.drawing.drawing2d.matrix(v=vs.110).aspx
https://msdn.microsoft.com/de-de/library/system.drawing.graphics.scaletransform(v=vs.110).aspx


Q: End processing a stream using event-stream I am reading a large JSON file using JSONStream and I want to call a method when the whole stream is processed.
var JSONStream = require('JSONStream'), es = require('event-stream');

es.pipeline(
  fs.createReadStream('file.json'),
  JSONStream.parse(['features', true]),
  es.map(function (data) {
    console.log("Added data");
  })
);

How can I do that?

A: I used 'event-stream' for processing of ~200kB files contain JSONs inside and got the issue when 'end' Event was never called when using 'event-stream', if I put .on('end') after event-stream pipes. But when I put it Before pipes - everything works just ok!
stream.on('end',function () {
            console.log("This is the End, my friend");
     }).on('error',function (err) {
                console.error(err);
     }).pipe(es.split())
       .pipe(es.map(function (line, cb) {
                //Do anything you want here with JSON of line
                return cb();
            }));

nodejs,  event-stream

A: Sorted. Save the read stream in a variable and pipe an on('end', function) on that read stream.


Q: python getting many to many from model mixin returning None I have a model:
class Employee(models.Model, MyMixin):
    full_name = models.CharField(max_length=255)
    items = models.ManyToManyField(Item, blank=True)

and a mixin class:
class MyMixin(object):

    def my_m2m(self, field):
        field_value = getattr(self, field)
        print(field_value)
        // do something with many to many field

emp = Employee()
emp.my_m2m("items")

It gives me the result like employee.Item.None while printing emp.my_m2m("items")
 on console.
If I do emp.items.all() it gives me the result but I cant get it by name.
Why is it not giving the list of item associated with it ?
Am I missing anything ?

A: As you say, adding .all() gives the result, so you need to add that to your dynamic lookup:
field_value = getattr(self, field).all()


Q: Where does Identity Server 4 stores client's code verifier I have setup Identity Server 4 with EF & Angular client (OIDC JS library) with Authorization Code with PKCE grant. I see the code challenge & method being passed in the /authorize url. As per specification, auth server stores code challenged passed by client on auth server to be verified later when client sends code verifier.
Where does identity server 4 stores the code challenge in database?

A: It depends on how it is implemented, one common way is to store them in a database table called PersistedGrants. The Authorization Codes are also stored in this table, however they are deleted as as soon as they are used.
The image shows what it can look like in this table.

The Code_challenge is stored together with the access-code in the database and you can see the code where they pack it all together and then store it as an encrypted blob in the database.

*

*AuthorizeResponseGenerator.cs (look at the end of the file)

The authorization code is stored in the database as the image below shows:

The actual payload is encrypted and protected, at it looks like this:
{
  "PersistentGrantDataContainerVersion": 1,
  "DataProtected": true,
  "Payload": "CfDJ8OFLAj3iVVVHvhgvjcKB19Z7-Hms4IIQobGgGl7VnJQCtKiB-Inr3h-mcWCxxD8dJ4QNTbuVeywbT6ROsaf13EpaIQDWtLgbnSPvCDTLQeWTO_vP0UtDwJ7TTCc5aTvKEp_9hX9S1b3l685bmBMlTIcZFqGGM2VfK0qasWCqKSQcTxeN6cgJygZEQNMgAG4ipqr..."
}


Q: c++ syntax using inheritance I'm having trouble with the syntax of an inherited classes and constructors and methodes in them.
I want to implement a class date and a child class date_ISO that would set a given day, month, year in a specific order and through a method write it into string.
I thing my base class date works fine, but I'm having problems with the derived date_ISO
How do I use correct syntax to inherite a constructor like Date, and how do I implement and execute it?
code for class Date:
#ifndef DATE_HPP
#define DATE_HPP
#include <sstream>
#include <string>
#include <iostream>

class Date
{

    private:
    short day;
    short month;
    short year;

    public:
    std::string getDD(short day);
    std::string getMM(short month);
    std::string getYear(short year);

    Date(short day, short month, short year);

    virtual std::string format() =0;
    virtual ~Date() =0;

};

        std::string Date::getDD(short day)
    {
        std::stringstream s_day;

        if(day < 10)
        {
        s_day << '0' << day;
        }
        return s_day.str();
    }

    std::string Date::getMM(short month)
    {
        std::stringstream s_month;
        if(month < 10)
        {
        s_month << '0' << month;
        }
        return s_month.str();
    }

    std::string Date::getYear(short year)
    {
        std::stringstream s_year;
        s_year << year;
        return s_year.str();
    }

    Date::Date(short day, short month, short year) : day(day), month(month), year(year){}

#endif

code for class Date_iso:
#ifndef DATEISO_HPP
#define DATEISO_HPP
#include "Date.hpp"
#include <sstream>
#include <string>
#include <iostream>

class DateISO : public Date
{
    public:
    std::string format();
    DateISO(short day, short month, short year);
};

    std::string DateISO::format()
    {
        std::stringstream ss;
        ss << this->getYear() << this->getMM() << this->getDD();
        return ss.str();
    }

    DateISO::DateISO(short day, short month, short year){}

    Date::~DateISO()
    {
    }

#endif

Followup question:
I have written a small code with the tips i got here and I don't use it properly. I'm trying to have a polymorphic pointer that would help create a few objects of the derived class but firstly I wanted to check what happends when I create a simple objekt of the derived class. It doesnt compile and I get a "undefined referance" error to all my get methods.
I add the new code (old code no longer relevant but is still there for comparison).
code for class Date:
#ifndef DATE_HPP
#define DATE_HPP
#include <sstream>
#include <string>
#include <iostream>

class Date
{

    private:
    short day;
    short month;
    short year;

    public:
    std::string getTT(short day);
    std::string getMM(short month);
    std::string getYear(short year);

    Date(short day, short month, short year);

    virtual std::string format() =0;
    virtual ~Date() =0;

};

        std::string Date::getTT(short day)
    {
        std::stringstream s_day;
        this->day = day;
        if(day < 10)
        {
        s_day << '0' << day;
        } else {
        s_day << day;
        }
        return s_day.str();

    }

    std::string Date::getMM(short month)
    {
        std::stringstream s_month;
        this->month = month;
        if(month < 10)
        {
        s_month << '0' << month;
        } else {
        s_month << month;
        }
        return s_month.str();
    }

    std::string Date::getYear(short year)
    {
        this->year = year;
        std::stringstream s_year;
        s_year << year;
        return s_year.str();
    }

    Date::Date(short day, short month, short year) : day(day), month(month), year(year)//prueft die Attribute
    {
        //some code
    }

#endif

code for class dateISO:
#ifndef DateISO_HPP
#define DATEISO_HPP
#include "Date.hpp"
#include <sstream>
#include <string>
#include <iostream>

class DateISO : public Date
{
    public:
    std::string getTT();
    std::string getMM();
    std::string getYear();

    std::string format();
    DateISO(short day, short month, short year);
    ~DateISO();
};

    std::string DateISO::format()
    {
        std::stringstream ss;
        ss << DateISO::getYear() << DateISO::getMM() << DateISO::getTT();
        return ss.str();
    }

    DateISO::DateISO(short day, short month, short year) : Date(day, month, year){}

    DateISO::~DateISO()
    {
        //some code
    }

#endif

and code for the test main:
#include "DateISO.hpp"
//#include "DateDE.hpp"
#include "Date.hpp"
#include <sstream>
#include <string>
#include <iostream>

int main()
{
    DateISO date_iso(5,9,2017);
    std::cout << date_iso.format();

return 0;
}

How do I use a polymorphic pointer to create and manage objekts?
what is wrong with the object that I created (that gives me an error)?
I am sorry for the long question and am thankful for any help.

A: You already know how to use a constructor initializer list as you do it in the Date constructor.
You "call" a parent class constructor just the same way. In your case
DateISO::DateISO(short day, short month, short year)
    : Date(day, month, year)  // "Call" the parent constructor
{}

A: In addition to Some Programmer Dude's answer, it is also possible to inherit a constructor with 'using' like so:
class DateISO : public Date
{
    using Date::Date;
};

This will redeclare all the base classes constructors in the child class, and all arguments will be forwarded to the base constructor, so this probably wouldn't be suitable if your base class had multiple constructors and you only wanted to inherit one of them, nor if your child class has additional members which must be initialised, but for your case where all members are in the base class and the child class only adds methods this should be okay. See the section on 'Inheriting Constructors' for more information.


Q: Method for converting float to integer after checking I am trying to perform multiple operations on two numbers (say A and B). These two numbers are getting inputted via a single string. So I am converting them into Double values and performing an operation on them.
The poblem is that the output is always double. I would like to have the answer to be an integer answer if the result is an integer, say, 2 instead of 2.0.
Cases:

*

*A= 2 and B= 2 (input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result => 4

*A= 2.0 and B= 2.0 (input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result => 4.0
I looked it up and it wasn't much help. As such questions either deal with conversion or precision. Links to any similar/helping questions that I might have missed will work too. I know how to convert from float to int, but looking for optimum way to check if a number can be represented in int or not. And get result accordingly.
Thank you

A: You can try and use % operator to decide if the two doubles produce a perfect division and use integer casting like below.
double num1 = 20.0;
double num2 = 5.0;

if (num1%num2 == 0) {
    System.out.println((long) (num1/num2));
} else {
    System.out.println(num1/num2);
}


Q: Change div value based on  option Using this great plugin
http://exodecreations.com/jQuery/jqDropDown.html
My Jquery code:
jQuery(function() {
  jQuery('#list4').jqDropDown({
    optionChanged: function(){
      jQuery("#firmos").html('My New Text');
    },
    direction: 'up',
    defaultStyle: false,
    containerName: 'theContainer',
    toggleBtnName: 'awesomeToggleClass',
    optionListName: 'thisListIsRocking',
    effect: 'fade',
    effectSpeed: 300
  });
});

My php code:
<form action="#">
  <select id="list4" name="invoices">
    <option>Aspen</option>
    <option>Tokyo</option>
    <option>Cannes</option>
    <option>Capetown</option>
    <option>Paris</option>
    <option>Nice</option>
    <option>Geneva</option>
  </select>
</form>

Based on the option selected i would like the div with id #firmos to change its value.
My current example changes the div text to a single value but i will need a different value for each option..
Any efficient ideas? The list of cities will be around 50.. maybe define an attribute within each <option> ?

A: I believe this may work.
jQuery("#firmos").html($(this).val());

In your document ready function it would look like this.
jQuery(function() {
  jQuery('#list4').jqDropDown({
    optionChanged: function(){
      jQuery("#firmos").html($(this).val());
    },
    direction: 'up',
    defaultStyle: false,
    containerName: 'theContainer',
    toggleBtnName: 'awesomeToggleClass',
    optionListName: 'thisListIsRocking',
    effect: 'fade',
    effectSpeed: 300
  });
});

Edited
Actually if you want to redisplay the option in another element this control has a parameter called place holder
you could do this.
jQuery(function() {
  jQuery('#list4').jqDropDown({
    placeholder: '#firmos',
    direction: 'up',
    defaultStyle: false,
    containerName: 'theContainer',
    toggleBtnName: 'awesomeToggleClass',
    optionListName: 'thisListIsRocking',
    effect: 'fade',
    effectSpeed: 300
  });
});

Edited Again
If you want a custom value you can do something like this
jQuery(function() {
  jQuery('#list4').jqDropDown({
    optionChanged: function(){
      jQuery("#firmos").html((function (currentElement) {
        switch (currentElement.val())
        {
          case "someval":
            return "somethingSpecial1";
            break;
          case "someval2":
            return "somethingSpecial2";
            break;
          /// more case statements.
        }
      })($(this)));
    },
    direction: 'up',
    defaultStyle: false,
    containerName: 'theContainer',
    toggleBtnName: 'awesomeToggleClass',
    optionListName: 'thisListIsRocking',
    effect: 'fade',
    effectSpeed: 300
  });
});

A: Well, I looked that this plugin just replicates a select element in a list <li> and seems not possible to get the exact changed value from the select because it doesn't change if you see the DOM (that makes me assume that the onchange event from that plugin is used just to trigger something when your list changes).
So, it seems you need to do some tricky thing to get the selected value implementing an onchange event recreation.
Like this:
Live Demo: http://jsfiddle.net/oscarj24/nuRKE/
$(function () {

    var firmos = $('#firmos');

    $('#list4').jqDropDown({
        direction: 'up',
        defaultStyle: false,
        containerName: 'theContainer',
        toggleBtnName: 'awesomeToggleClass',
        optionListName: 'thisListIsRocking',
        effect: 'fade',
        effectSpeed: 300
    });

    //This will be your new 'onchange' event when using 'jqDropDown' plugin.
    $('ul .ddOption').on('click', function(e){
        var selected = $.trim($(e.target).text());
        switch (selected)
        {
          case 'Aspen':
            firmos.html('You selected Aspen.');
            break;
          case 'Tokyo':
            firmos.html('You selected Tokyo.');
            break;
          //Do the same for other options.
        }

    });
});


Q: Problem with SSD MobileNet V2 FPNLite 320x320 conversion for Coral AI TPU I'm trying to run Tensorflow model lite on Rasperry PI with Coral TPU.
Model is SSD Mobile Net 2. It works fine on PC after conversion either fully quantized or with float I/O.
However when I run it on Coral TPU I got a lot of wrong result. Usually it is false positive class 0 (mapped to person).
Could somebody help me, I run out ideas how to fix it?
Tensorflow version: 2.5.0
Tensorflow Lite version: 2.5.0
Steps I did:

*

*Download the model: http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz

*I changed input resize layer to 320x320, but the result is the same as original 300x300.

*I converted saved model to tf lite friendly format:

python3 object_detection/export_tflite_graph_tf2.py --pipeline_config_path /home/pawel/proj/net_models/ssd_mobilenet_v2_320x320_coco17_tpu-8-init/pipeline.config --trained_checkpoint_dir /home/pawel/proj/net_models/ssd_mobilenet_v2_320x320_coco17_tpu-8-init/checkpoint --output_directory /home/pawel/proj/net_models/ssd_mobilenet_v2_320x320_coco17_tpu-8-fixed-input

*Model convertion to TF Lite format, model_path points to the previous step output, I tried quantize True/False and the commented part of the code below:

 converter = tf.lite.TFLiteConverter.from_saved_model(model_path)
    if quantize:
        # converter.optimizations = [tf.lite.Optimize.DEFAULT]
        # converter.representative_dataset = representative_data_gen
        # converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
        # converter.inference_input_type = tf.uint8
        # converter.inference_output_type = tf.uint8

        converter.representative_dataset = representative_data_gen
        converter.optimizations = [tf.lite.Optimize.DEFAULT]
        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8, tf.lite.OpsSet.SELECT_TF_OPS]
        converter.inference_input_type = tf.uint8
        converter.inference_output_type = tf.uint8
        converter.allow_custom_ops = True

        print(converter.experimental_new_quantizer)  # outputs True
        print(converter.experimental_new_converter)  # outputs True
    else:
        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
        converter.optimizations = []

    tflite_model = converter.convert()

    with open(lite_model_path, 'wb') as f:
        f.write(tflite_model)

Data provider, used code from step 5:
def representative_data_gen():
    from cocodataset import CocoDataSet
    coco = CocoDataSet(input_size, input_size)
    images = coco.get_calibration_dataset(500)
    for img in images:
        yield [img]

*Repressentative data set - Coco 2017 valuation data - 500 samples.

 class CocoDataSet:
  ...
    def get_calibration_dataset(self, limit: int):
        with open(self.annotation_file, 'r') as f:
            annotations = json.load(f)
        image_info = annotations['images']
        random.shuffle(image_info)
        image_info = image_info[:limit]
        image_paths = []
        for img in image_info:
            image_path = self.image_dir + img['file_name']
            image_paths.append(image_path)

        print(f"{limit} images will be returned")
        images = []
        fl = True
        for i, path in enumerate(image_paths):
            print(f"Loading {i}/{len(image_paths)}:" + path)
            image = cv.imread(path)
            image = cv.cvtColor(image, cv.COLOR_BGR2RGB)

            tensor = np.zeros((self.input_height, self.input_width, 3), dtype=np.uint8)
            _, _, channel = tensor.shape

            h, w, _ = image.shape
            scale = min(self.input_width / w, self.input_height / h)
            w, h = int(w * scale), int(h * scale)
            image = cv.resize(image.copy(), (w, h), interpolation=cv.INTER_LINEAR)

            reshaped = image
            margin_x = (self.input_width - w) // 2
            margin_y = (self.input_height - h) // 2
            tensor[margin_y:h + margin_y, margin_x:w + margin_x] = reshaped

            tensor = np.expand_dims(tensor, axis=0)

            tensor = tensor.astype(np.float32) - 127.5
            tensor = tensor * 0.007843

            images.append(tensor)

        return images

*Coral AI compilation:

edgetpu_compiler ssd_mobilenet_v2_coral.tflite

*Inference with Coral AI (Rpi). It works fine with SSD2 Mobile Net provided in Coral AI SDK.

   x, y, scale = self.set_image_input(self.interpreter, region)

   self.interpreter.invoke()

   detection_boxes = self.get_output_tensor(self.interpreter, 0)
   detection_classes = self.get_output_tensor(self.interpreter, 1, np.int)
   detection_scores = self.get_output_tensor(self.interpreter, 2)
   count = self.get_output_tensor(self.interpreter, 3, np.int)

8.Input image, scaled and centered:
def set_image_input(self, interpreter: tflite.Interpreter, image: np.ndarray) -> (int, int, float):
        self.did = self.did + 1
        width, height = (self.input_height, self.input_width)
        stretch = False
        if stretch:
            h, w, _ = (self.input_height, self.input_width, 1)
        else:
            h, w, _ = image.shape

        cv.imwrite(f"{self.logs_dir}/image{self.did}.png", image)
        scale = min(width / w, height / h)
        w, h = int(w * scale), int(h * scale)
        tensor = self.input_tensor(interpreter)
        tensor.fill(0)
        _, _, channel = tensor.shape

        image = cv.resize(image.copy(), (w, h), interpolation=cv.INTER_LINEAR)

        reshaped = image
        if tensor.dtype == np.float32:
            reshaped = reshaped * (1.0/255) - 1
        margin_x = (self.input_width - w) // 2
        margin_y = (self.input_height - h) // 2
        tensor[margin_y:h + margin_y, margin_x:w + margin_x] = reshaped

        return margin_x, margin_y, scale

*Getting output tensor:

 def get_output_tensor(self, interpreter: tflite.Interpreter, index: int, result_type=np.float):
    output_details = interpreter.get_output_details()[index]
    quantization = output_details['quantization']
    dtype = output_details['dtype']
    tf_index = output_details['index']
    tensor = np.squeeze(interpreter.get_tensor(tf_index))
    if quantization != (0, 0):
        input_scale, input_zero_point = quantization
        tensor = (tensor.astype(np.float32) - input_zero_point) * input_scale
    if tensor.dtype != result_type:
        tensor = tensor.astype(result_type)
    return tensor

What I noticed that the results differs a little when I run the conversion a couple of times - the representative data is randomly obtained from the set. The differences are much more visible on Coral AI compiled model, that that I run on PC.

A: The accuracy quantized SSD model is slightly lowered than the float model, you can probably try the efficient-det model: https://www.tensorflow.org/lite/api_docs/python/tflite_model_maker/object_detector

A: It looks that the newest update of Coral compiler and RaspberryPI runtime solved the issue.
RPI runtime after update: 2.5.0.post1
Edge CPU compiler after update: 16.0.384591198
Some example detections (class, score):
Coral:
[(0, 0), (1, 0.7210485935211182), (0, 0), (1, 0.6919153332710266), (1, 0.7428985834121704), (1, 0.8485066890716553), (24, 0.6919153332710266)]

TF Lite - CPU:
[(0, 0), (1, 0.7210485935211182), (0, 0), (1, 0.6919153332710266), (1, 0.7356152534484863), (1, 0.8412233591079712), (24, 0.7028403282165527)]

TF CPU:
[(0, 0), (1, 0.75359964), (0, 0), (1, 0.7409908), (1, 0.7797077), (1, 0.8114069), (24, 0.750371)]


Q: Upgrading Ghost Broke My Website My ghost blog was running fine and i've just tried to upgrade it using the guide posted here. I am using Digital Ocean as the web host by the way.
After upgrade it's showing some problems, I've looked at the error log and it's showing a bunch of errors like this:
2015/09/07 13:22:50 [error] 3987#0: *23 connect() failed (111: Connection refused) while connecting to upstream, client: (IP HIDDEN), server: my-ghost-blog.com, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:2368/favicon.ico", host: "HOST HIDDEN", referrer: "http://URL HIDDEN/"

I've removed IPs and what not

A: Since nobody has answered it I might as well post what worked for me. I was able to start the blog manually with npm start it was just the service ghost start that reported [OK] but didn't actually start it.
First I was able to find the error in /var/log/nginx/errors.log
2016/02/08 21:18:27 [error] 601#0: *2086 connect() failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: my-ghost-blog.com, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:xxxx/favicon.ico", host: "mydomain.com", referrer: "http://example.com/path-to-post/"
I had to recursively change the owner of /ghost directory like this:
chown -R ghost:ghost ghost/*

I executed it from /var/www
thanks to @BrettDeWoody for his post


Q: redirect to a action that expects value in other controller I have a controller StepOfIdea,and this controller has a action like this :
 StepOfIdeaRepository objStepOfIdearepository=new StepOfIdeaRepository();
        public ActionResult Index(int ideaId)
        {
            return View(objStepOfIdearepository.FindBy(i=>i.IdeaId==ideaId));
        }

So i have another controller named idea and this controller has a view named index
@model IEnumerable<DomainClass.Idea>

@{
    ViewBag.Title = "Index";
}

لیست

    @if (User.IsInRole("User"))
    {

            @Html.ActionLink("ایده جدید", "Create", new {step = 1})

    }

        @if (User.IsInRole("Admin"))
        {

            @Html.DisplayNameFor(model => model.User.Name)

        }

            @Html.DisplayNameFor(model => model.IdeaPersion)

            @Html.DisplayNameFor(model => model.IdeaEnglish)

            @Html.DisplayNameFor(model => model.IdeaResult)

            @Html.DisplayNameFor(model => model.Date)

@foreach (var item in Model) {

         @if (User.IsInRole("Admin"))
        {

            @Html.DisplayFor(modelItem => item.User.Name) @Html.DisplayFor(modelItem => item.User.Name)

        }

            @Html.DisplayFor(modelItem => item.IdeaPersion)

            @Html.DisplayFor(modelItem => item.IdeaEnglish)

            @Html.DisplayFor(modelItem => item.IdeaResult)

            @Html.DisplayFor(modelItem => item.Date)

            @Html.RenderAction("ویرایش","index", stepofidea, new { id=item.Id }) |

            @Html.ActionLink("ویرایش", "Edit", new { id=item.Id }) |
            @Html.ActionLink("نمایش", "Edit", new { id=item.Id }) |
            @Html.ActionLink("حذف", "Delete", new { id=item.Id })

}

In this line
    @Html.RenderAction("ویرایش","index", ????, new { id=item.Id }) |

I want to redirect to index action of  stepOfIdea controller and pass a value .But the above line doesn't work .

A: I think you confused some terms in translation to English, and what you are actually looking for is to create an Link that also passes a variable.
You can do this very simply, by:
@Html.ActionLink("ویرایش", "Index", "StepOfIdea", new { id = item.Id }, null)

This will create the HTML:
ویرایش


Q: Why does content size of UITableView Change I have a UITableView that I am loading my data in 3 blocks. I load the latest 10 records and when user pulls up using the UIRefreshControl, I load the preceding 10 and show the last row from the previous block. I store the previous content size right before I load the new set from database
previousContentSizeHeight = tableView.contentSize.height

and then when data comes and update my array, I use previous to calculate the new content size of table
let difference = tableView.contentSize.height -
     previousContentSizeHeight - MinimumCellHeight

self.messageTableView.setContentOffset(CGPoint(x: 0, y: difference), animated: false)

This works for the most part. It behaves correctly after the viewDidAppear when loading the first set and when loading the 2nd set, but in the third set it starts changing in content size. It gets decreased! My understanding is if I am adding data to it (not deleting anything), the content size should only grow.
I have in multiple places in my code readings of the table content size like this event:
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    print("tableView.contentSize.height is: \(tableView.contentSize.height)")
}

as I am scrolling up and down, I see the number decrease and sometimes increase and decrease
Why does content size changes in size!?
NOTE: I want to stick to using the content offset. I have more luck with it than IndexPath.
UPDATE #1
@Sohil R. Memon: I tried your suggestion. Per screenshot, I added a print statement and as you can see the viewDidLayoutSubviews is still not executing. i tried inside the endDisplaying with self.messageTableView and just tableView

A: Once the cell are displayed and didEndDisplaying is called, there are more things to process and when you scroll cellForItem calls again and that gives you different sizes.
In order to get the exact contentSize of UITableView once all the cells are displayed, you can get it from below method. Just write the below method in your UIViewController class.
override func viewDidLayoutSubviews() {
    print(tableView.contentSize.height) //Exact Content Size of UITableView
}

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    tableView.layoutIfNeeded()
}

Hope this helps!


Q: Connect to sftp server with host key fingerprint using python 3.0 on Windows I am trying to connect to an sftp server using python on Windows. I cannot connect to the server without a hostkey. A lot of options, especially with pysftp ask for hostkey files which apparently aren't generated on Windows.
From what I can see is that I have 3 options:
1) [Most preferred] use a string to generate the required key through python code. But that's always producing errors - some of the code using StringIO doesn't work on Python 3 and the possible workarounds don't seem to work for me. Apparently I am not able to decode the key properly and I have no idea how to check for that. I have tried to generate PKey but I am not sure what I am doing wrong.
2) get the right format of known_hosts file (I have no idea what it should look like and couldn't find any samples online) - and put or add the hostkey there. That way I'd (hopefully) be able to use cnopts to connect to the server.
3) This is a fallback option, if the above two don't work: use python to call powershell script that does the work - I have been successful at this but would like to pass arguments from python script to powershell and then get results/status from powershell back to python.
The most relevant options that I have tried out:
Python - pysftp / paramiko - Verify host key using its fingerprint
Embedding public key as string in Paramiko Application
Using python pysftp package, getting a "SSHException: Bad host key from server" error
What I'd like is a sample string (that would look like the actual thing) and the steps around creating a key from it. Or a sample file that I can use to just plugin the details and run the code.


Q: Not able to update reducer state in redux On change of select I want to save the value in reducer. But How can I pass the value into state.
below is the code I am using.
container/header/index.js
const changeCloud = () => {
  return ('hello');
}

const mapStateToProps = () => ({
  cloud: changeCloud(),
  menuItems: menuItems,
})

const mapDispatchToProps = (dispatch) => ({
  setCloud: () => {
    dispatch(setCloud('sf'));
  },
})

const Header = connect(
  mapStateToProps,
  mapDispatchToProps
)(HeaderPresentational);

component/header/index.js
setCloudClick(evt) {
    this.setState({
      value: evt.target.value,
    }, function () {
      this.props.setCloud('this.state.value');
    });
  }

render(){
    return(
    <select onChange={this.setCloudClick} value={this.state.value}>
        <option value="zscaler.net">zscaler.net</option>
        <option value="zscalerOne.net">zscalerOne.net</option>
        <option value="zscaler.net">ZscalerTwo.net</option>
        <option value="Zscaler Private Access">Zscaler Private Access</option>
    </select>
);
}

reducer.js
function reducer(state, action) {
  switch (action.type) {
    case 'SET_CLOUD' :
      alert(action.text);
      return state;
    default :
      return state;
  }
}
export default reducer;

A: From the callback, you need to pass the value and not the string
setCloudClick(evt) {
    this.setState({
      value: evt.target.value,
    }, function () {
      this.props.setCloud(this.state.value);  // pass this.state.value here
    });
  }

However, when you are storing value in store, you need not store it locally. You can dispatch the value like
index.js
setCloudClick(evt) {
    this.setState({
      value: evt.target.value,
    }, function () {
      this.props.setCloud(this.state.value);
    });
  }

render(){
    return(
         <select onChange={this.setCloudClick} value={this.state.value}>
            <option value="zscaler.net">zscaler.net</option>
            <option value="zscalerOne.net">zscalerOne.net</option>
            <option value="zscaler.net">ZscalerTwo.net</option>
            <option value="Zscaler Private Access">Zscaler Private Access</option>
        </select>
    );
}

container/header/index.js
const changeCloud = () => {
  return ('hello');
}

const mapStateToProps = () => ({
  cloud: changeCloud(),
  menuItems: menuItems,
})

const mapDispatchToProps = (dispatch) => ({
  setCloud: (value) => {
    dispatch(setCloud(value));
  },
})

const Header = connect(
  mapStateToProps,
  mapDispatchToProps
)(HeaderPresentational);


Q: How to show html form using shortcode in wordpress? I want to show html form using shortcode. Here is my code:
add_shortcode('sms_order_form', 'sms_order_form_html');

function sms_order_form_html(){?>
'<form>

        0<input type="range" id="range" value="0" min="0" max="100"/>100
        0

</form>
<?php } ?>

But this doesn't print the form. but if I replace the HTML form by echo 'hello'; it prints hello. Is there any way to show any HTML using shortcode.
N.B.: shortcode is placed using elementor.

A: Shortcode should return a string:
<?php
add_shortcode( 'sms_order_form', 'sms_order_form_html' );

function sms_order_form_html() {
    ob_start();

    ?>
    <form>

            0<input type="range" id="range" value="0" min="0" max="100"/>100
            0

    </form>
    <?php

    return ob_get_clean();
}

A: Shortcode functions need to return the output in form of a string as opposed to outputting HTML right away. You can use output buffering to return your code like so:
add_shortcode('sms_order_form', 'sms_order_form_html');

function sms_order_form_html() {
  ob_start();
?>
<form>

        0<input type="range" id="range" value="0" min="0" max="100"/>100
        0

</form>
<?php
  return ob_get_clean(); // clear the output buffer, and return as string
}


Q: How does google chrome launch desktop apps? i don't really know the terminology so im going to start with an example.
If I click a magnet link, Google chrome asks if i want to launch a torrent client. I click ok and chrome launches that app and the app does some stuff based on the link.
now is there anyway to see how the app gets the info from chrome? and how chrome starts the app?

A: It depends exactly on the OS, but in general, another desktop program can register a specific protocol, or URI scheme, to open up a program. Then, when Chrome doesn't know how to deal with a protocol, it'll just hand it over to the OS to deal with.
In Windows for example, they're configured by putting something into the system registry under a specific key (https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx).
Most applications will setup themselves as a default for the particular protocol when installed.

A: Chrome is a "desktop" program. It can open any program exposed from the operating system.
A link can contain a specific protocol instead of http://, the OS can have a map that ties protocols directly to installed programs. Chrome is not communicating with the app at any point. It only tells the os to open a resource at a given url with a given program.


Q: Podio: "Item has been deleted" on PUT, but can retrieve item via GET For some items I have the following problem:
I can retrieve them via GET https://api.podio.com/item/$itemId (meaning the item is not deleted). But when I want to update the item via PUT https://api.podio.com/item/$itemId, it results in a HTTP 410 with the following body:
{
    "error_parameters": {},
    "error_detail": null,
    "error_propagate": false,
    "request": {
        "url": "http://api.podio.com/item/$itemId",
        "query_string": "",
        "method": "PUT"
    },
    "error_description": "Item has been deleted",
    "error": "gone"
}

Is there any wrong assumption on my side, or why do I get this error?


Q: insert table with onclick JS function I want a onclick button that when you press it, it shows up a pre-compilated table.
I've tried to use the table as a text or a paragraph in teh script and obviusly it did'nt work. I can't figure out how to do it. can you help me?

A: The easy way is to add the table with a 'hide' class, like:
<button id='toggleTable'>
  show/hide table
</button>
<table class='hide' id='tableTarget'>
...
</table>

The js:

document.addEventListener('DOMContentLoaded', () => {
  document
    .querySelector('#toggleTable')
    .addEventListener(
      'click',
      () => {
        document
          .querySelector('#tableTarget')
          .classList
          .toggle('hide')
      },
      false
    )
  },
  false
)

the css:
.hide {
  display: none !important;
}

if you use any frontend framework should be easier. But this is with plain html/js/css. And IE9 is not supported with this solution. If you need it, you have to change a little bit the js code.
Good Luck!


Q: My django objects get affected when I commit changes in heroku with git My django admin panel objects get affected when I commit changes in git for my heroku website.
I commit changes to my heroku website from following command in terminal -
git add .
git commit -am "make it better"
git push heroku master
enter code here

before committing when I add new model:

after committing changes it disappeared:

Is there any solution for that committing changes does not affect these objects in django admin panel ?


Q: reverse geocoding to find exact organization/building/landmark name that location When I search  about an  organization in google maps,along with map location, there is side  pop up where  other  details like adress,ph no etc show  up.
I  know  the python coding to find cordinates  for an address.
but  I  am notable to find  the a way to extract name of  the  organization from the  address.
Is there a way to program( python preferred) to  find the organization/building/landmark name for  which I only have the address ?
Note : Through web scraping I can find the address of the organization from its web-site but  how do  I find the name of organization if I  have only its address or cordinates
Eg : search 'Ajanta Chemical Industries' on google map and you get below address
Office & Factory 812/ E-9, 10 11 & 12, Samtel Zone, Phase- III, RIICO Industrial Area, Bhiwadi, Rajasthan 301019
Question - If I  have above address , is  there a programmable  way to  find that its for 'Ajanta Chemical Industries'  ?


Q: how to convert unsigned char array to QByteArray in Qt? unsigned char x[] = {0x7E,0x00,0x00,0x0F };
I want to push it to QByteArray but the QByteArray when finds '\0' stops copying.

A: Which Qt version are you using? 4.7 has QByteArray(const char*, size) which should work and QByteArray::fromRawData(const char*, int size) which also should work.

A: QByteArray test("\xa4\x00\x00", 3);


Q: Case insensitive matching python I want to match items from one list in another without worrying about case sensitivity.
mylist1 = ['fbH_q1ba8', 'fHh_Q1ba9', 'fbh_q1bA10','hoot']
mylist2 = ['FBH_q1ba8', 'trick','FBH_q1ba9', 'FBH_q1ba10','maj','joe','civic']

I was doing this before:
for item in mylist2:
    if item in mylist1:
        print "true"
    else:
        print "false"

But this fails because it is not case sensitive.
I am aware of re.match("TeSt", "Test", re.IGNORECASE) but how can I apply that to my example?

A: Normalize the case with str.lower():
for item in mylist2:
    print item.lower() in mylist1

The in containment operator already returns True or False, easiest just to print that:
>>> mylist1 = ['fbh_q1ba8', 'fhh_q1ba9', 'fbh_q1ba10','hoot']
>>> mylist2 = ['FBH_q1ba8', 'trick','FBH_q1ba9', 'FBH_q1ba10','maj','joe','civic']
>>> for item in mylist2:
...     print item.lower() in mylist1
...
True
False
False
True
False
False
False

If mylist1 contains mixed case values, you'll need to make the loop explicit; use a generator expression to produce lowercased values; testing against this ensures only as many elements are lowercased as needed to find a match:
for item in mylist2:
    print item.lower() in (element.lower() for element in mylist1)

Demo
>>> mylist1 = ['fbH_q1ba8', 'fHh_Q1ba9', 'fbh_q1bA10','hoot']
>>> for item in mylist2:
...     print item.lower() in (element.lower() for element in mylist1)
...
True
False
False
True
False
False
False

Another approach is to use any():
for item in mylist2:
    print any(item.lower() == element.lower() for element in mylist1)

any() also short-circuits; as soon as a True value has been found (a matching element is found), the generator expression iteration is stopped early. This does have to lowercase item each iteration, so is slightly less efficient.
Another demo:
>>> for item in mylist2:
...     print any(item.lower() == element.lower() for element in mylist1)
...
True
False
False
True
False
False
False

A: Why not just do:
for item in mylist2:
    if item.lower() in [j.lower() for j in mylist1]:
        print "true"
    else:
        print "false"

This uses .lower() to make the comparison which gives the desired result.

A: The other answers are correct. But they dont account for mixed cases in both lists. Just in case you need that:
mylist1 = ['fbh_q1ba8', 'fbh_q1ba9', 'fbh_q1ba10','hoot']
mylist2 = ['FBH_q1ba8', 'trick','FBH_q1ba9', 'FBH_q1ba10','maj','joe','civic']

for item in mylist2:
    found = "false"
    for item2 in mylist1:
        if item.lower() == item2.lower():
            found = "true"
    print found


Q: Reading and using data from user files in Javascript (web application), without uploading them I'd like to have a way for a webpage -which is generated dynamically by my server- to read all the files in a specific user folder, manipulate them using javascript, within the web browser, and using them to show to the user some results (specific correlations between the data, dependent on the context and sometimes some graphs, drawn using these correlations).
Communication with the server about these data is neither required nor desired. Actually, since all the manipulations needed can be done via javascript and the files can be huge, for now I absolutely don't want that their content is uploaded to the server. Therefore there are no security risks (at least none that I can see).
Server side, I'm only interested to save the name of the folder, so that the user (who is registered) doesn't need to select the files one by one or to select them again every time a new page is dynamically created.
For now, the only hopes to find a solution that I have been able to gather are about using the Chrome FileSystem API (but I'd prefer a general solution, not dependent on a specific browser) or creating an extension that the user should install to use this feature when visiting the website (which, for me, is maybe even worse than relying on a specific browser).
So I wonder if there is a way to implement this feature using only pure javascript and HTML5 and using neither extensions nor browser dependent solutions.

A: Due to security reasons, JavaScript running in the browser should not be used to access the filesystem directly. But definitely you can access it using Node's fs module (but that's on the server side).
Another way is, if you let the user pick files using the <input type="file"> tag then you can use the File API to fetch the contents. But I think that is not what you are looking for.
Recommended reading: https://en.wikipedia.org/wiki/JavaScript#Security


Q: How to set the Priority for feature file inside include tag How to set the priority for feature file(s) to run in the TestNG.xml file with include tag.
I have added the "priority" attribute inside the include tag as follows:
<test name="DESKTOP Chrome" enabled="true">
<parameter name="platform" value="desktop" />
<parameter name="driver.name" value="chromeDriver" />
<parameter name="webdriver.chrome.driver" value="driver/chromedriver.exe" />
<parameter name="chrome.additional.capabilities" value="{'chromeOptions':{'useAutomationExtension':false}}"/>
    <groups>
        <run>
            <include name="@aLoginMenuDesktop" priority="1"/>
            <include name="@ViewPrimaryNavigationMenuDesktop" priority="2"/>
            <include name="@PortfolioOverview" priority="3"/>
            <include name="@FooterDesktop" priority="4"/>
            <include name="@zSignOutMenuDesktop" priority="5"/>
        </run>
    </groups>

    <classes>
        <class name="com.qmetry.qaf.automation.step.client.gherkin.GherkinScenarioFactory" />
    </classes>
</test>

But during the execution it throws the below error.

Caused by: org.xml.sax.SAXParseException; lineNumber: 17;
  columnNumber: 54; Attribute "priority" must be declared for element
  type "include".   at
  com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown
  Source)

A: I removed the priority inside the tag and make it run by default instead,
I just found out that the priority by default (alphabetical) is not based on the tag name of the feature file (@faturefile) that is being called
But, it is based from the filename of the feature file (teststep.feature)


Q: How to set a breakpoint on clicking a 3rd party button? I'm trying to debug a 3rd party widget (+1 button to be exact). Specifically, I'd like to set a breakpoint in Chrome that stops when a button in the widget is clicked.
I would like to break on the 3rd party code that handles to click event. Is there a Chrome extension (or something else I haven't thought of) to help me find the right place in the code to break on?

A: You can make use of Chrome's Developer Tools; no extension is required.
I made a +1 button example here: http://jsfiddle.net/rPnAe/.
If you go to that fiddle and then open Developer Tools (F12), then go to Scripts and expand Event Listener Breakpoints and lastly expand 'Mouse' and tick the 'click' checkbox, then whenever you click somewhere (which includes an event listener), the debugger will now break at the line of code which contains the listener function.


Q: JS Script not loading on Firefox and Safari My web page does not seem to load a JS file into it on Firefox, Safari and most mobile browsers, but it works on Chrome (and other chromium based browsers).
https://paxco.in/wallet.html Is the page
I have the script tage <script type="text/javascript" scr="./js/web3.min.js"></script> But it does not show in the sources when I use dev tools, and I get errors when I reference functions from the file as according to the browser it is non-existent.
EDIT: Fixed Linking script,
Now I can't reference the /js/web3.min.js file in my other scripts

A: You have an unclosed tag somewhere on your page.
This results in the browser not being able to parse the DOM properly, resulting in your script tag not being "rendered".
Chrome has some better error handling for cases like that, which makes it work in that browser.

Also, there's a typo:
scr="./js/web3.min.js"
Should be
src="./js/web3.min.js"


Q: Hide buttons when printing I have a page which contains at the bottom 3 buttons with the following coding:

    function printpage() {
        //Get the print button and put it into a variable
        var printButton = document.getElementById("printpagebutton");
        //Set the print button visibility to 'hidden'
        printButton.style.visibility = 'hidden';
        //Print the page content
        window.print()
        printButton.style.visibility = 'visible';
    }
#options {
 align-content:center;
 align-items:center;
    text-align: center;
}

<input type="submit" value="post news" >
<input id="printpagebutton" type="button" value="print news" onclick="printpage()"/>
<input type="button" value="re-enter the news">

I managed to hide the print button while printing but i couldn't with the others.
I've searched the internet for the solution, and most questions were answered by adding the display:none; in css, but i end up with 3 hidden buttons on the screen.
I only want the buttons hidden while printing
Answer might be simple, my knowledge in web developing is acient.
Thank you in advance.

A: You can use a css media query to target print:
@media print {
  .hide-print {
    display: none;
  }
}

A: You can use CSS @media queries. For instance:

@media print {
  #printPageButton {
    display: none;
  }
}
<button id="printPageButton" onClick="window.print();">Print</button>

The styles defined within the @media print block will only be applied when printing the page. You can test it by clicking the print button in the snippet; you'll get a blank page.

A: Assign an id to the other 2 buttons. For the POST NEWS button you can set id to postnews and RE-ENTER THE NEWS to reenterthenews; Then do this
function printpage() {

    //Get the print button and put it into a variable
    var printButton = document.getElementById("printpagebutton");
    var postButton = document.getElementById("postnews");
    var reenterButton = document.getElementById("reenterthenews");

    //Set the button visibility to 'hidden'
    printButton.style.visibility = 'hidden';
    postButton.style.visibility = 'hidden';
    reenterButton.style.visibility = 'hidden';

    //Print the page content
    window.print()

    //Restore button visibility
    printButton.style.visibility = 'visible';
    postButton.style.visibility = 'visible';
    reenterButton.style.visibility = 'visible';

}

HTML

<input type="submit" id="postnews" value="post news" >
<input id="printpagebutton" type="button" value="print news" onclick="printpage()"/>
<input type="button" id="reenterthenews" value="re-enter the news">


Q: Using Teradata macros from Entity Framework? Is it possible to use Teradata Macros directly from Entity Framework? I tried the model designer and guessed they would show up under stored procedures which they don't. Does the Teradata .Net provider support macros at all?
Or, do I have to manually write the SQL sentences to execute the macros?


Q: SQL query to update all subpages of a specific uid in TYPO3 I'm looking to find an SQL query to update my TYPO3 table (pages) to add a specific fe_group for all pages under a specific uid in the page tree.
Example: UPDATE pages SET fe_group = 16 WHERE pid = 84;
This will add my fe_group to all pages under my specific uid in the page tree but only for the first level under. I need to reach the infinite levels.
TYPO3 v6.2 and above
Thanks!

A: If you want to apply usergroup access rights to all subpages of a page, there is a built in function the page properties already: Extend to Subpages.
This works in all TYPO3 versions you mentioned:

If you really want to do it with an SQL query, you need to create a small PHP script to recursively change the access rights.


Q: Convert websites into mobile website format I would like to display other we pages in my mobile webapp, but some web pages will be too cumbersome for use on a tiny mobile device screen. So implement some kind of google mobilizer feature. Is there any API available in PHP so that i can use that to convert these pages into mobile compatible

A: No. You'll have to do it manually. You should look into responsive CSS layouts. These will adjust the content of the page as the width of the browser changes. So same page will work in a full browser window and mobile.
Look at

*

*http://www.columnal.com/

*http://lessframework.com/

*http://speckyboy.com/2011/11/17/15-responsive-css-frameworks-worth-considering/

A: I got it, we can use skweezer API for this. If you want to see your website in mobile compatible format try this
http://www.skweezer.com/s.aspx?q=www.example.com

Replace www.example.com with your website URL.
For more details, visit http://company.skweezer.com/


Q: Estimation time to read an article In ASP MVC How can I estimate time to read an article  like docs.asp.net website
docs.asp.net
At the top of all articles, it says you need xxx minutes to read. I think they are using an algorithm to estimate time
How can I do that!
Thanks in advance

A: The words read per minute average is about 250-300, once you know this you just need to:

*

*Get the article word count.

*Divide this number by 275 (more or less).

*Round the result to get a integer number of minutes.

A: According to a study conducted in 2012, the average reading speed of an adult for text in English is: 228±30 words, 313±38 syllables, and  987±118 characters per minute.
You can therefore calculate an average time to read a particular article by counting one of these factors and dividing by that average speed. Syllables per minute is probably the most accurate, but for computers, words and characters are easier to count.
Study Citation:
Standardized Assessment of Reading Performance: The New International Reading Speed Texts IReST by
Susanne Trauzettel-Klosinski; Klaus Dietz; the IReST Study Group, published in Investigative Ophthalmology & Visual Science August 2012, Vol.53, 5452-5461

A: A nice solution here, on how
to get an estimated read time of any article or blog post  https://stackoverflow.com/a/63820743/12490386
here's an easy one

*

*Divide your total word count by 200.

*You’ll get a decimal number, in this case, 4.69. The first part of your decimal number is your minute. In this case, it’s 4.

*Take the second part — the decimal points — and multiply that by 0.60. Those are your seconds. Round up or down as necessary to get a whole second. In this case, 0.69 x 0.60 = 0.414. We’ll round that to 41 seconds.

*The result? 938 words = a 4 minute, 41 second read.


Q: How to make vs2010 auto generate method stubs at the end of file I try to auto generate method stub using visual studio's View.ShowSmartTag functionality

When I choose this option, Method8 will be placed right after Method2 but I want to place it after all methods, Method7 in this case.
Is there any settings for this?

A: After researching I found that I couldn't do that


Q: How to extract the hidden value in imacros I want to extract the verification code in attribute value, what the code? i dont understand in this problem
Look this

A: I hope it helps, And not too late.
TAG POS=1 TYPE=INPUT:HIDDEN ATTR=NAME:_RequestVerificationToken* EXTRACT=TXT


Q: Error JAVAC0000: error: package com.google.android.gms... does not exist So I just got a new MAC, and I have so many errors when running my project. I haven't worked on the project for about a year now, and this happens:
Image here
I have tried cleaning, rebuilding etc.. nothing seems to work. Tips?
I am using Visual Studio Community 2019 for Mac Version 8.3.3 (build 8)


Q: How to create a value in enum with '&' I need to create a enum value something like this' DESIGN & BUILD'. I am writing an importer service and that imports the types like above. I need to compare it with ones in the Db.
Is it possible to create enum values like above? Moreover, I think we could also do it by taking a regex expression that yields only text but not any sort of symbols, I mean we only get 'DESIGNBUILD'.

A: You can't. Enum value names have to be valid C# identifiers, and that excludes &. I suggest you use DescriptionAttribute or something similar to provide more flexible metadata for the enum values.
While you could use a regular expression to perform the mapping, I believe you'll end up with a more flexible result if you use metadata. You can then easily build a Dictionary<string, YourAttributeType> and vice versa.


Q: ajax unpload image and showing img thumb I am trying to work on an application form that fill information and submit to server, but in the images part i am having a problem. i want to show the user a thumb of the selected img. and that can just happen with uploading the img to the server and give it the path and refresh the control when getting back the url of the img.
I am not using the ajaxupload toolkit or anything, all whtat i am using is a input type file, and c# for the code behind and ajax functions.
i am calling the ajax function with javascript but what should i pass as parameter so i can catch it from the server side, save it and how to return back the url of the saved img . i red lots of articles, most of them uses PHP, or ajaxupload packages, nd i think i can be done without that..surely i dont need a post back at all
regards

A: I don't think you can send file on server using AJAX, 'cause you don't have access to file system via JavaScript. I don't believe what you're trying to do is possible without Flash or Silverlight. Try SWFUpload, for instance. I was using it on my previous project, and it worked fine for me.
EDIT:
And about returning the URL. SWFUpload lets you to send some parameters along with file. So you could generate GUID (on the server side, then just insert it in JavaScript for SWFUpload as an additonal post parameter) and once SWFUpload finished with uploading image, save it on the server using posted GUID as a name of file. After that you can make AJAX request from JavaScript using the same GUID and ask for uploaded image. Hope this helps.


Q: java.lang.ClassNotFoundException: com.liferay.portal.jsonwebservice.JSONWebServiceServlet in Liferay? hai iam new to json web services in liferay i got the following error! i have added JSONWebServiceServlet in web.xml. do i have to add any jar file to classpath?
05:51:36,250 ERROR [PortalClassLoaderServlet:76] java.lang.ClassNotFoundException: com.liferay.portal.jsonwebservice.JSONWebServiceServlet
java.lang.ClassNotFoundException: com.liferay.portal.jsonwebservice.JSONWebServiceServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
    at com.liferay.portal.kernel.servlet.PortalClassLoaderServlet.portalInit(PortalClassLoaderServlet.java:70)
    at com.liferay.portal.kernel.util.PortalLifecycleUtil.register(PortalLifecycleUtil.java:52)
    at com.liferay.portal.kernel.servlet.PortalClassLoaderServlet.init(PortalClassLoaderServlet.java:44)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1173)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4350)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4659)
    at org.apache.catalina.startup.HostConfig.checkResources(HostConfig.java:1244)
    at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1342)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:303)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1337)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1601)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1610)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1590)
    at java.lang.Thread.run(Unknown Source)

in web.xml i have written like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>pdfportlet-portlet</display-name>

    <jsp-config>
        <taglib>
            <taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri>
            <taglib-location>/WEB-INF/tld/liferay-portlet.tld</taglib-location>
        </taglib>
    </jsp-config>
    <servlet>
           <servlet-name>JSON Web Service Servlet</servlet-name>
           <servlet-class>com.liferay.portal.kernel.servlet.PortalClassLoaderServlet</servlet-class>
           <init-param>
               <param-name>servlet-class</param-name>
               <param-value>com.liferay.portal.jsonwebservice.JSONWebServiceServlet</param-value>
           </init-param>
           <load-on-startup>0</load-on-startup>
       </servlet>
      <servlet-mapping>
          <servlet-name>JSON Web Service Servlet</servlet-name>
          <url-pattern>/api/jsonws/*</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
          <servlet-name>JSON Web Service Servlet</servlet-name>
          <url-pattern>/api/secure/jsonws/*</url-pattern>
      </servlet-mapping>

</web-app>

A:  configure the servlet like this: some sysntax error i think. its working fine now.
   <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>student-portlet</display-name>
    <servlet>
    <servlet-name>JSON Web Service Servlet</servlet-name>
    <servlet-class>
    com.liferay.portal.kernel.servlet.PortalClassLoaderServlet
    </servlet-class>
    <init-param>
    <param-name>servlet-class</param-name>
    <param-value>com.liferay.portal.servlet.JSONServlet</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>JSON Web Service Servlet</servlet-name>
    <url-pattern>/api/jsonws/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>JSON Web Service Servlet</servlet-name>
    <url-pattern>/api/secure/jsonws/*</url-pattern>
    </servlet-mapping>
        <jsp-config>
        <taglib>
          <taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri>
          <taglib-location>/WEB-INF/tld/liferay-portlet.tld</taglib-location>
        </taglib>
        </jsp-config>
    </web-app>


Q: How get get the entered values from input box and not the content of Value attribute I have some input fields with pre-populated values. After editing the values of this field if the save button is pressed in my script tag I want to take the edited value in the field and send it to my controller using ajax. The problem I faced is when I am picking the value of my input field using

var name = document.getElementById('iusername').value;

I am getting the value in value attribute and not the one resulted after edit.


Q: Truncated If Statement C++ (Turning letters to numbers) I am trying to change a series of letters into numbers with C++ and have started by making this code.
However, it appears that the math that calculates the digit1 variable is never getting executed.
Any thoughts?
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int qtyofnumbers, num, digit1, counter;
    char letters, upperlower;

    cout << "Enter a letter: ";
    cin >> letters;

    for (counter = 0; counter < 8; counter++)
    {
        if (counter == 3)
            cout << "-";

        num = static_cast<int>(letters) - static_cast<int>('A');

        if (0 <= num && num < 26)
            digit1 = (num / 3) + 2;

        if (((num / 3 == 6 ) || (num / 3 == 7)) && (num % 3 == 0))
            digit1 = digit1-1;

        if (digit1 > 9)
            digit1 = 9;

        cin >> letters;
    }

    cout << digit1;

    return 0;
}

A: My guess is that the problem is in your input. Are you entering capital letters or lowercase letters? Their ASCII codes are different. So, you probably want to change the code from
num= static_cast<int>(letters)-static_cast<int>('A');

to something like
if (num >= 'a')
    num = letters - 'a';
else
    num = letters - 'A';

Also, as mentioned by @jtbandes, use the curly braces { and }. Whitespace does not determine scope in C++. Even if it's for only one line of code after your if-statement, it'll save you headaches in the future.

A: Is the static cast necessary? I recommend using a string stream or just traversing the string character by character using .at() and relying on the ascii values for conversion. http://web.cs.mun.ca/~michael/c/ascii-table.html.


Q: Where can I set path to make.exe on Windows? When I try run make from cmd-console on Windows, it runs Turbo Delphi's make.exe but I need MSYS's make.exe. There is no mention about Turbo Delphi in %path% variable, maybe I can change it to MSYS in registry?

A: The path is in the registry but usually you edit through this interface:

*

*Go to Control Panel -> System -> System settings -> Environment Variables.

*Scroll down in system variables until you find PATH.

*Click edit and change accordingly.

*BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e. c:\path;c:\path2

*Launch a new console for the settings to take effect.

A: Or you can just run this PowerShell command to append extra folder to the existing path:
$env:Path += ";C:\temp\terraform"

A: To add a PERSISTENT path (eg one that's permanent), you can do this one-liner in PowerShell (adjust the last c:\apps\terraform part)
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value  (((Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path) + ";c:\apps\terraform" )

Alternatively, you can jump directly to the Environment Variables dialog by RUNning/CMD/PowerShell this:
rundll32.exe sysdm.cpl,EditEnvironmentVariables

A: Here I'm providing solution to setup Terraform environment variable in windows for beginners.

*

*Download the terraform ZIP file from Terraform site.

*Extract the .exe from the ZIP file to a folder eg C:\Apps\Terraform
copy this path location like C:\Apps\terraform\

*Add the folder location to your PATH variable, eg: Control Panel -> System -> System settings -> Environment Variables
In System Variables, select Path > edit > new > Enter the location of the Terraform .exe, eg C:\Apps\Terraform then click OK

*Open a new CMD/PowerShell and the Terraform command should work

A: I had issues for a whilst not getting Terraform commands to run unless I was in the directory of the exe, even though I set the path correctly.
For anyone else finding this issue, I fixed it by moving the environment variable higher than others!

A: Why don't you create a bat file makedos.bat containing the following line?
c:\DOS\make.exe %1 %2 %5

and put it in C:\DOS (or C:\Windowsè or make sure that it is in your %path%)
You can run from cmd, SET and it displays all environment variables, including PATH.
In registry you can find environment variables under:

*

*HKEY_CURRENT_USER\Environment

*HKEY_CURRENT_USER\Volatile Environment

*HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment

A: just copy it to system32 call make1 or whatever if the name conflicts.


Q: How to catch ajax error response? when i have an ajax error response with jquery i have the following log:
jquery.js:8630 OPTIONS http://10.0.1.108:8000/api/v1.0/auth/ net::ERR_CONNECTION_REFUSED
Object {readyState: 0, status: 0, statusText: "error"}

In my object i have a property statusText: 'error', but no properties with 'net::ERR_CONNECTION_REFUSED'.
I tried to log the responseText as see here Get server response with AJAX error? but my object didn't have this property;
Do you know how i can get it in javascript please? Thank.

A: You can't.
Many errors, including most (if not all) status: 0 errors, are not exposed to JavaScript.
They indicate network or same origin policy errors and exposing the details to JavaScript could leak information. For example, if it was possible to distinguish between "Connection Refused", "Post doesn't speak HTTP" and "No Access-Control-Allow-Origin header", then it would be trivial to write a page that would quietly map out all the webservers on the visitor's corporate network. That information could then be used for phishing attacks.


Q: sum of specific key for multiple similar keys in array of object - JavaScript I have an array of objects like the following:
[
    {
        'Product': 'P1',
        'Price': 150,
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 100,
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 200,
        'Location': 2,
    },
    {
        'Product': 'P2',
        'Price': 10,
        'Location': 1,
    },
    {
        'Product': 'P2',
        'Price': 130,
        'Location': 1,
    },
    {
        'Product': 'P3',
        'Price': 40,
        'Location': 1,
    }
]

I need to add up all the prices for objects with the same product and same location.  For the example above the result would be:
[
   {
        'Product': 'P1',
        'Price': 250, // price is the sum of both similar in location and product
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 200,
        'Location': 2, // same product but different location
    },
    {
        'Product': 'P2',
        'Price': 140, //sum of same
        'Location': 1,
    },
    {
        'Product': 'P3',
        'Price': 40,
        'Location': 1,
    },
]

I have searched several similar issues, but those were dealing with only one key to check for, I have different keys (product and location - may be more than 2 in the future) to identify as different.

A:

const input = [
    {
        'Product': 'P1',
        'Price': 150,
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 100,
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 200,
        'Location': 2,
    },
    {
        'Product': 'P2',
        'Price': 10,
        'Location': 1,
    },
    {
        'Product': 'P2',
        'Price': 130,
        'Location': 1,
    },
    {
        'Product': 'P3',
        'Price': 40,
        'Location': 1,
    }
]

const output = []
input.forEach(item => {
  const index = output.findIndex(o => o.Product === item.Product && o.Location === item.Location);
  if (index === -1) {
    output.push(item);
  } else {
    output[index].Price += item.Price;
  }
});
console.log(output);

Without arrow function
input.forEach(function(item) {
  const index = output.findIndex(function(o) { return o.Product === item.Product && o.Location === item.Location});
  if (index === -1) {
    output.push(item);
  } else {
    output[index].Price += item.Price;
  }
});

A: You can use reduce() to do that,

obj = [
   {
        'Product': 'P1',
        'Price': 250, // price is the sum of both similar in location and product
        'Location': 1,
    },
    {
        'Product': 'P1',
        'Price': 200,
        'Location': 2, // same product but different location
    },
    {
        'Product': 'P2',
        'Price': 140, //sum of same
        'Location': 1,
    },
    {
        'Product': 'P3',
        'Price': 40,
        'Location': 1,
    },
]

res = obj.reduce((prev, curr) => {
  index = prev.findIndex(item => item.Product=== curr.Product && item.Location === curr.Location);
  if(index > -1) {
    prev[index].Price += curr.Price;
  } else {
    prev.push(curr);
  }
  return prev;
}, []);

console.log(res);

A: Modifying @William's answer (Accepted) for my use case as it was to be run on the platform which was not supporting ES6 features (findIndex and arrow function), this can be done without findIndex as below;

var input = [{
    'Product': 'P1',
    'Price': 150,
    'Location': 1,
  },
  {
    'Product': 'P1',
    'Price': 100,
    'Location': 1,
  },
  {
    'Product': 'P1',
    'Price': 200,
    'Location': 2,
  },
  {
    'Product': 'P2',
    'Price': 10,
    'Location': 1,
  },
  {
    'Product': 'P2',
    'Price': 130,
    'Location': 1,
  },
  {
    'Product': 'P3',
    'Price': 40,
    'Location': 1,
  }
]

var output = []
input.forEach(function(item) {
  var index = output.indexOf(output.filter(function(o) {
    return o.Product === item.Product && o.Location === item.Location
  })[0]); // note the [0] index here
  if (index === -1) {
    output.push(item);
  } else {
    output[index].Price += item.Price;
  }
});
console.log(output);


Q: Why is gmailr not working in docker build process? I'm using the gmailr package for sending emails from a r script.
Locally it's all working fine, but when I try to run this during a docker build step in google cloud I'm getting an error.
I implemented it in the following way described here.
So basically, locally the part of my code for sending emails looks like this:
gm_auth_configure(path  = "credentials.json")
gm_auth(email = TRUE, cache = "secret")
gm_send_message(buy_email)

Please note, that I renamed the .secret folder to secret, because I want to deploy my script with docker in gcloud and didn't want to get any unexpected errors due to the dot in the folder name.
This is the code, which I'm now trying to run in the cloud:
setwd("/home/rstudio/")
gm_auth_configure(path  = "credentials.json")
options(
  gargle_oauth_cache = "secret",
  gargle_oauth_email = "email.which.was.used.to.get.secret@gmail.com"
)
gm_auth(email = "email.which.was.used.to.get.secret@gmail.com")

When running this code in a docker build process, I'm receiving the following error:
Error in gmailr_POST(c("messages", "send"), user_id, class = "gmail_message",  :
  Gmail API error: 403
  Request had insufficient authentication scopes.
Calls: gm_send_message -> gmailr_POST -> gmailr_query

I can reproduce the error locally, when I do not check the
following box.
Therefore my first assumption is, that the secret folder is not beeing pushed correctly in the docker build process and that the authentication tries to authenticate again, but in a non interactive-session the box can't be checked and the error is thrown.
This is the part of the Dockerfile.txt, where I'm pushing the files and running the script:
#2 ADD FILES TO LOCAL
COPY . /home/rstudio/

WORKDIR /home/rstudio

#3 RUN R SCRIPT
CMD Rscript /home/rstudio/run_script.R

and this is the folder, which contains all files / folders beeing pushed to the cloud.
My second assumption is, that I have to somehow specify the scope to use google platform for my docker image, but unfortunately I'm no sure where to do that.
I'd really appreciate any help! Thanks in advance!

A: For anyone experiencing the same problem, I was finally able to find a solution.
The problem is that GCE auth is set by the "gargle" package, instead of using the "normal user OAuth flow".
To temporarily disable GCE auth, I'm using the following piece of code now:
library(gargle)
cred_funs_clear()

cred_funs_add(credentials_user_oauth2 = credentials_user_oauth2)

gm_auth_configure(path  = "credentials.json")
options(
  gargle_oauth_cache = "secret",
  gargle_oauth_email = "sp500tr.cloud@gmail.com"
)
gm_auth(email = "email.which.was.used.for.credentials.com")

cred_funs_set_default()

For further references see also here.


Q: Asking for name again if the first name input doesn't match the second name input I would like to make a program that asks the user his name two times. If the two names are the same regardless of the case, it will print success. If the two names are not the same, it will ask the user again to input another set of names (2 names) and if it is now the same it will also print success.
public static void main(String args[]) throws IOException {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter name: ");
    String one = input.readLine();
    System.out.println("Enter name: ");
    String two = input.readLine();

    if (one.equalsIgnoreCase(two)) {
        System.out.print("Success");
    }
    else {
        System.out.println("Enter name: ");
        input.readLine();
        System.out.println("Eneter name: ");
        input.readLine();
    }
}

The part that checks if the two names are the same is fine. The part that I am confused is the code where it will ask for another set of 2 names
else {
    System.out.println("Enter name: ");
    input.readLine();
    System.out.println("Eneter name: ");
    input.readLine();
}

Example output:
Enter name:
Mark Andrew
Enter name:
Mark Andrew
Success

Enter name:
Mark Andrew
Enter name:
John Paul
Enter name:
Mark Andrew
Enter name:
Mark Andrew
//this is the part that I am confused. It doesn't print success//

I am open to opinions and suggestions.
Thanks

A: In the else part, you are not checking again if the names are the same or not. That's why it's not showing Success the next time when you gave the same names. Using a loop would be better if we want to take inputs until the same names are entered.
public static void main(String args[]) throws IOException {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    boolean areNamesEqual = false;
    while(!areNamesEqual) {
        System.out.println("Enter name: ");
        String one = input.readLine();
        System.out.println("Re-enter name: ");
        String two = input.readLine();
        if (one.equalsIgnoreCase(two)) {
            areNamesEqual = true;
        }
    }
    System.out.print("Success");
}


Q: PHP foreach() loop $string = "The complete archive of The New York Times can now be searched from NYTimes.com " //the actual input is unknown, it would be read from textarea

$size = the longest word length from the string

I assigned and initialized array in for loop, for example array1, array2 ....arrayN, here is how i did
for ($i = 1; $i <= $size; $i++) {
    ${"array" . $i} = array();
}

so the $string would be divided in the length of the word
$array1 = [""];
$array2 = ["of", "be", ...]
$array3 = ["the", "can", "now", ...] and so on

So, my question is how to assign in simple for loop or foreach loop $string value to $array1, $array2, $array3 ....., since the input text or the size of the longest word is unknown

A: I'd probably start with $words = explode(' ', $string)
then sort the string by word length
usort($words, function($word1, $word2) {
    if (strlen($word1) == strlen($word2)) {
        return 0;
    }
    return (strlen($word1) < strlen($word2)) ? -1 : 1;
});

$longestWordSize = strlen(last($words));

Loop over the words and place in their respective buckets.
Rather than separate variables for each length array, you should consider something like
$sortedWords = array(
    1 => array('a', 'I'),
    2 => array('to', 'be', 'or', 'is'),
    3 => array('not', 'the'),
);

by looping over the words you don't need to know the maximum word length.
The final solution is as simple as
foreach ($words as $word) {
    $wordLength = strlen($word);
    $sortedWords[ $wordLength ][] = $word;
}

A: You could use something like this:
$words = explode(" ", $string);
foreach ($words as $w) {
    array_push(${"array" . strlen($w)}, $w);
}

This splits up $string into an array of $words and then evaluates each word for length and pushes that word to the appropriate array.

A: you can use explode().

$string = "The complete archive of The New York Times can now be searched           from NYTimes.com " ;

$arr=explode(" ",$string);
$count=count($arr);

$big=0;
 for ($i = 0; $i < $count; $i++) {
     $p=strlen($arr[$i]);
if($big<$p){ $big_val=$arr[$i]; $big=$p;}

     }
echo $big_val;

A: Just use the word length as the index and append [] each word:
foreach(explode(' ', $string) as $word) {
    $array[strlen($word)][] = $word;
}

To remove duplicates $array = array_map('array_unique', $array);.
Yields:
Array
(
    [3] => Array
        (
            [0] => The
            [2] => New
            [3] => can
            [4] => now
        )

    [8] => Array
        (
            [0] => complete
            [1] => searched
        )

    [7] => Array
        (
            [0] => archive
        )

    [2] => Array
        (
            [0] => of
            [1] => be
        )

    [4] => Array
        (
            [0] => York
        )

    [5] => Array
        (
            [0] => Times
        )
)

If you want to re-index the main array use array_values() and to re-index the subarrays use array_map() with array_values().


Q: Getting the size of single document in Mongodb? I am new to MongoDB and am trying to retrieve the size of a single document from a database.
The database is named "enron"
The collection is named "email"
I tried:
Object.bsonsize(db.email.findOne())

I also tried:
Object.bsonsize(db.enron.findOne())

But it only returns 0.
How can I get the size of a document?
Thank you!

A: Here is the related question How to get the size of a single document in MongoDB?