text:
Q: How can I convert these flowchart GOTO statements to Python? I have some flowcharts which are representing the algorithm of finding peak and troughs of a time series.
I tried to convert them to Python, but I don't know how to fix the "GOTO" things.
def minzo(trough,peak, i,x,r,p,sp):
    f=-1
    i=i+1
    if i == (len(ts) - 1):
        endzo1 = endzo()
    else:
        if x[i] < trough:
            trough=x[i]
        else:
            if x[i]-trough>=r:
                p=p+1
                sp.append(trough)
                peak=ts[i]
                maxzo1=maxzo()
    return trough,peak,i,x,r,p,sp

x = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sp = []
r = 1
trough = x[0]
peak = x[0]
i = -1

while i<len(x):
    i = i + 1
    if i == (len(x)-1):
        GOTO ENDZO???
    else:
        if x[i]>peak:
            peak=x[i]
            if peak-trough>=r:
                sp.append(trough)
                GOTO MAXZO

        else:
            if x[i]<trough:
                trough=x[i]
                if peak-trough>=r:
                    sp.append(peak)
                    GOTO MINZO

The flowcharts are below:
Start

GOTOs

A: Is this correct?
def endzo(x, trough, peak, i, p, f, l, r, s, n):
    n = p + 1
    if abs(f) == 1:
        if f == 1:
            s[n] = peak
        else:
            s[n] = trough
    else:
        s[n] = (trough + peak) / 2

    return x, trough, peak, i, p, f, l, r, s, n

def maxzo(x, trough, peak, i, p, f, l, r, s, n):
    f = f + 1
    while i < len(x):
        i = i + 1
        if i == (len(x) - 1):
            x, trough, peak, i, p, f, l, r, s, n = endzo(x, trough, peak, i, p, f, l, r, s, n)
        else:
            if x[i] > peak:
                peak = x[i]
            else:
                if peak - x[i] >= r:
                    p = p + 1
                    s[p] = peak
                    trough = x[i]
                    x, trough, peak, i, p, f, l, r, s, n = minzo(x, trough, peak, i, p, f, l, r, s, n)
        return x, trough, peak, i, p, f, l, r, s, n

def minzo(x, trough, peak, i, p, f, l, r, s, n):
    f = -1
    while i < len(x):
        i = i + 1
        if i == (len(x) - 1):
            x, trough, peak, i, p, f, l, r, s, n = endzo(x, trough, peak, i, p, f, l, r, s, n)
        else:
            if x[i] < trough:
                trough = x[i]
            else:
                if x[i] - trough >= r:
                    p = p + 1
                    s[p] = trough
                    peak = x[i]
                    x, trough, peak, i, p, f, l, r, s, n = maxzo(x, trough, peak, i, p, f, l, r, s, n)
        return x, trough, peak, i, p, f, l, r, s, n

x = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
trough = x[0]
peak = x[0]
i = -1
p = 0
f = 0
l = len(x) - 1
r = 1
s = []
n = 0

while i <= l:
    i = i + 1
    if i == l:
        x, trough, peak, i, p, f, l, r, s, n = endzo(x, trough, peak, i, p, f, l, r, s, n)
    else:
        if x[i] > peak:
            peak = x[i]
            if peak - trough >= r:
                s[p] = trough
                x, trough, peak, i, p, f, l, r, s, n = maxzo(x, trough, peak, i, p, f, l, r, s, n)

        else:
            if x[i] < trough:
                trough = x[i]
                if peak - trough >= r:
                    s[p] = peak
                    x, trough, peak, i, p, f, l, r, s, n = minzo(x, trough, peak, i, p, f, l, r, s, n)

print(s)


text:
Q: Call SoapClient constructor with WSDL from a variable instead of a URL Is it possible to call the PHP SoapClient constructor, which takes a URL as an argument, with the contents of a string instead.
In my example I have a manipulated DOMDocument containing WSDL which I would write into a string with saveXML().
The idea is to not touch the filesystem if possible. I have tried php://memory but tests on retrieving the stream content with functions like file_get_contents result in empty strings as I suspect the stream context has disappeared. Is there another way?

A: Yes it is possible to instantiate the SoapClient class with a variable containing your WSDL string, all without touching the filesystem.  Since the SoapClient requires a URI parameter, we will create a Data URI and pass it in:
$wsdlstring  = <<<WSDL
<?xml version="1.0" encoding="utf-8"?>
<definitions name="SoapArrayTest"
                  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
                  xmlns:tns="http://test-uri/"
                  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
                  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
                  xmlns="http://schemas.xmlsoap.org/wsdl/"
                  targetNamespace="http://test-uri/"
  >
  <types>
    <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://test-uri/">
      <complexType name="Baz">
        <sequence>
          <element name="fruit" type="tns:StringArray"/>
          <element name="vegetables" type="tns:StringArray"/>
        </sequence>
      </complexType>
      <element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="BazElement" type="tns:Baz"/>
      <complexType name="StringArray">
        <sequence>
          <element name="item" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
        </sequence>
      </complexType>
      <element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="StringArrayElement" type="tns:StringArray"/>
    </schema>
  </types>
  <message name="fooRequest">
  </message>
  <message name="fooResponse">
    <part name="result" type="tns:Baz"/>
  </message>
  <portType name="TestPortType">
    <operation name="foo">
      <input message="tns:fooRequest"/>
      <output message="tns:fooResponse"/>
    </operation>
  </portType>
  <binding  name="TestBinding" type="tns:TestPortType">
    <soap:binding  style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation  name="foo">
      <soap:operation  soapAction="#foo" style="rpc"/>
      <input />
      <output >
        <soap:body  parts="result" use="literal" namespace="http://test-uri/" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
      </output>
    </operation>
  </binding>
  <service  name="TestService">
    <port  name="TestPort" binding="tns:TestBinding">
      <soap:address location="http://example.com"/>
    </port>
  </service>
</definitions>
WSDL;

$doc = new DOMDocument();
$doc->loadXML($wsdlstring);
$data = $doc->saveXML();
$wsdl = 'data://text/plain;base64,'.base64_encode($data);
$soapclient = new SoapClient($wsdl);
var_dump($soapclient->__getFunctions());

redpajama_set_name: RedPajamaStackExchange


text:
Q: Drupal 8 - Generate carousel from custom content type I begin to work on D8 few days ago. I want to build a website as you can do it with Wordpress + ACF using D8 and its Content type.
Steps are similar : creating a specific page > add custom fields > display them how we want in the page.
I managed to display some content by reaching the value in the big D8 datas :
// example for a h1 tag

{{ node.field_accueil_slide_titre.value }}

Using node or content main Object/array. By the way it's already difficult and quite stupid to have to delve the node/content array to guess the ".value", ".uri" or ".title" that are needed when we want specific things. Is that the good way to do ? I can't find a doc or listing about it.
My point is that I now want to make something as a "foreach loop" on the field that contains images but I can't find a way to reach images in a clean array.
And if I try to display the field to delve my chrome tab crash..
{% for images in content.field_accueil_image_slide %}

This do not works for example.
Do I have to generate a new block just for the carousel generation ?

A: first step:
you have to create a new content-type with a field pictures and the setting unlimited (you can upload as many pictures as you want for your carousel).
second step:
create a new template for this content-type. in your template you can loop through the uploaded pictures.
for example: (my field in the contenttype is field_carousell_picture).
i use owl-carousel. i have included the owl-carousel java-script and call it with the style tag.

        {% for i in 0..content.field_carousell_picture|length %}
         {%if content.field_carousell_picture[i]['#item'].entity.uri.value != "" and content.field_carousell_picture[i]['#item'].entity.uri.value is not empty %}

                {{ content.field_carousell_picture[i]}}

         {%endif%}
        {%endfor%}

third step: you can watch your node and see your carousel or include it to  a page.


text:
Q: C++ only create an instance of a class if a condition on the template type is met I'm searching for a way to only instantiate a class if a condition on the template type is met. I would like to do this within the class during run-/ and compile-time and not terminate the program, but throw an exception.
I'm working on a class where the template type needs to have a time component. Ideally, the type is derived from a class that only defines the time as a member. That way, doing something like the following should be safe:
#include <type_traits>
#include <stdexcept>

class Time
{
  public:
    double t;
};

class A : Time
{

};

template<class T>
class B
{
    T data;

    void do_someting()
    {
      data.t = 12.34;
    }
};

B<A> some_instance;

I found this C++ templates that accept only certain types
So the following would do the check, but static_assert only checks during compile time.
template<class T>
class B
{
    static_assert(std::is_base_of<Time, T>::value, "T must inherit from Time Class");
    T data;

    void do_someting()
    {
      data.t = 12.34;
    }
};

Would it be safe to do the following or is there a cleaner way of archiving this?
Edit: Changed due to Timos input.
template<class T>
class B
{
  B()
  {
    if(std::is_base_of<Time, T>::value)
    {
      throw std::invalid_argument( "T must inherit from Time Class" );
    }
  }

    T data;

    void do_someting()
    {
      data.t = 12.34;
    }
};

A: I'm a bit confused with what you try to achieve.  From my understanding, you want to prevent B from being used with classes which don't inherit from Time.
For this, the solution with the static_assert is the best solution. One of the strengths of C++ is that you can cause compilation errors when a precondition gets violated. In weakly typed languages as Javascript, PHP, Bash ... this would cause a run-time error, which requires you to have a test case for that piece of code.
The other solution with the exception doesn't add any benefits, as the if-statement will be evaluated at compile time and effectively be if (true) or if (false).
So by writing the second solution, you actually need more time to debug the code as you have to launch your executable, run a test case which uses this code and check the behavior with the debugger. All of which could be prevented with the static_assert.

A: Use std::enable_if which is exactly for this purpose. It will lead to compile time error if condition is not met.
#include <type_traits>
#include <stdexcept>

class Time
{
  public:
    double t;
};

class A : Time
{

};

class C
{

};

template<class T, class _T=typename std::enable_if<std::is_base_of<Time, T>::value, T>::type >
class B
{
    T data;

    void do_someting()
    {
      data.t = 12.34;
    }
};

B<A> some_instance;
//B<C> other_instance; // error

A: The idea is good but implementation is wrong. This should go like this:
templacte <T, Base>
class ThrowIfNotBaseOf {
    void checkIt() {
        if(!std::is_base_of<Base, T>::value) {
            throw std::invalid_argument( "T must inherit from Time Class" );
        }
    }

public:
    TypeCheckThrow() { // default constructor
        checkIt();
    }

    TypeCheckThrow(const TypeCheckThrow<T, Base> &) { // copy constructor
        checkIt();
    }

    TypeCheckThrow(TypeCheckThrow<T, Base> &&) { // move constructor
        checkIt();
    }
};

template<class T>
class B
{
    ThrowIfNotBaseOf<T, Time> typeCheckThrow;

    T data;

    void do_someting()
    {
      data.t = 12.34;
    }
};

I'm agree that this requirement is a bit strange. Maybe you should describe what you are trying to solve instead asking how to fix your idea of solution. I'm suspecting XY Problem.


text:
Q: Handshakes with different people Jerry is shaking hands with a group of people. There are $n \geq 2$ people there. Any person can shake any number of the other peoples' hands, including zero, but any two people can only shake each other's hands once. Shaking hands is a mutual event between exactly two people.
Prove or disprove the claim that there must always be at least two people who shook the same number of hands as each other.
I have two theories for this problem: this is a problem that involves the pigeonhole principle, with there being n-1 holes. Or that it is a problem that involves derangements. I am mainly not sure how to approach the problem.

A: Go with the pigeon hole proinciple. Each of the $n$ people will have shaken between $0$ and $n-1$ other peoples hands. If someone has shaken $n-1$ hands then they have shaken everyone elses hand & so there cannot be someone who has shaken $0$ hands.


text:
Q: compiler error: operator "*"and"+" cannot be applied i asked like this question yesterday but i didnt get good answer about it
in the code below why i cant use * and + in last line?and whats the way to solve that?thanks
    private void bigzarb(int u,int v)
    {
        double n;
        int x=0;
        int y;
        int w=0;
        int z;
        string[] i = textBox7.Text.Split(',');
        int[] nums = new int[i.Length];
        for (int counter = 0; counter < i.Length; counter++)
        {
            nums[counter] = Convert.ToInt32(i[counter]);
        }

        u = nums[0];
        double firstdigits =Math.Floor(Math.Log10(u) + 1);
         v = nums[1];
        double seconddigits = Math.Floor(Math.Log10(v) + 1);
        if (firstdigits >= seconddigits)
        {
            n = firstdigits;

        }
        else
        {
            n = seconddigits;

        }
        if (u == 0 || v == 0)
        {
            MessageBox.Show("the Multiply is 0");
        }
        string threshold = textBox9.Text;
        int intthreshold = Convert.ToInt32(threshold);
        int intn = Convert.ToInt32(n);
        if (intn <= intthreshold)
        {

            double uv = u * v;
            string struv = uv.ToString();
            MessageBox.Show(struv);

        }
        else
        {
           int m  =Convert.ToInt32(Math.Floor(n / 2));

            x = u % 10 ^ m;
            y = u / 10 ^ m;
            w = v % 10 ^ m;
            z = v / 10 ^ m;

            bigzarb(x, w) *( 10 ^ m) +(bigzarb(x,w)+bigzarb(w,y))*10^m +bigzarb(y,z);///compiler gives error operator "*"and"+" cannot be applied to operands of type'void'and'int'

///and compiler gives error operator "*"and"+" cannot be applied to operands of type 'void' and 'void'
        }

    }

A: Well, there are a few things wrong here:

*

*You're trying to use the results of calling a method, but that method has no return value... so there's no result to multiply. This is what the compiler is complaining about.

*I suspect you think that ^ performs a "power" operation - it's actually a bitwise xor

*Your final statement doesn't actually do anything with the results of the calculation

Given that your method doesn't return anything, what values do you think are going to be used in an expression such as bigzarb(x, w) *( 10 ^ m)?

A: Your method bigzarb has a void signature, which you are using in a calulation.

A: Jon Skeet has answered this question, but I though I would be more explicit to explain exactly what is happening on this line...
bigzarb(x, w) *( 10 ^ m) + (bigzarb(x,w)+bigzarb(w,y))*10^m +bigzarb(y,z);

Let's break it into sections
The first statement is
bigzarb(x, w)

But as you'll see from Jon's answer - you are not returning a value from this method...
private void bigzarb(int u,int v)
Now let's replace that bit with it's actual value now we've explained it:
[void] *( 10 ^ m) + (bigzarb(x,w)+bigzarb(w,y))*10^m +bigzarb(y,z);

The same goes for all of the other calls to bigzarb - so let's replace those too...
[void] * ( 10 ^ m) + ([void] + [void]) * 10 ^ m + [void];

So your problem is, in order to use mathematical operators, you need numbers on each side - but you don't have numbers because your method is void.
You could change your method to return a number - but be aware of recursion... when you call this method, it calls itself three times and each of those calls will result in a further three calls to the method. Not good!

A: this is because
rerturn type  of  function gzarb(x, w) is void  so you can't do any operatin on a void pointer.
and in the last line ,you are using output of gzarb in a runing calculation.


text:
Q: Three.js shadows grainly/artifacty on animated object I'm trying to get soft shadows to look nice on this animated mesh test
https://codesandbox.io/s/zen-black-et9cs?file=/src/App.js
No amount of playing with the shadow mapSize or shadowBias appears to fix this strange grainyness/artifacting I see on the animated mesh shadow.

Does anyone have any thoughts on what to try to improve these shadows?

A: This call is causing it:
softShadows({
  frustum: 3.75, // Frustum width (default: 3.75) must be a float
  size: 0.005, // World size (default: 0.005) must be a float
  near: 9.5, // Near plane (default: 9.5) must be a float
  samples: 17, // Samples (default: 17) must be a int
  rings: 11, // Rings (default: 11) must be a int
});

A: How I ended up improving this a bit was messing with the softShadows drei parameters - mainly lowering the "size" parameter. It's not perfect, but it's better.
softShadows({
  frustum: 3.75, // Frustum width (default: 3.75) must be a float
  size: 0.002, // World size (default: 0.005) must be a float
  near: 9.5, // Near plane (default: 9.5) must be a float
  samples: 17, // Samples (default: 17) must be a int
  rings: 11, // Rings (default: 11) must be a int
});


text:
Q: C++ Powershell not executing command properly? So, I have a quick bit of code that should give me the drive serials that are currently installed on the system, however, when I run this, powershell gets an error. I'm not entirely sure what's wrong here, as when I type the command on powershell it works fine. Here is some of the code :
std::string exec(const char* cmd) {
    std::array<char, 128> buffer;
    std::string result;
    std::shared_ptr<FILE> pipe(_popen(cmd, "r"), _pclose);
    if (!pipe) throw std::runtime_error("_popen() failed!");
    while (!feof(pipe.get())) {
        if (fgets(buffer.data(), 128, pipe.get()) != NULL)
            result += buffer.data();
    }
    return result;
};

Later I call this:
std::string test = exec("powershell -ExecutionPolicy Bypass get-ciminstance Win32_LogicalDisk | % VolumeSerialNumber");

If this works correctly, I should have a string with multiple serial numbers on it (as I have multiple drives), however I don't. I get this powershell error that is printed into my console.
'%' is not recognized as an internal or external command,
operable program or batch file.

Anyone have any ideas on how to fix this? I tried adding a \ before the % but that didn't work either. Any help is greatly appreciated!

A: _popen spawns cmd.exe to run your command.

The _popen function creates a pipe. It then asynchronously executes a spawned copy of the command processor, and uses command as the command line.

Thus the | is being interpreted by cmd, which tries to run % as a command.
Thus the output coming out of cmd:

'%' is not recognized as an internal or external command,
operable program or batch file.

To fix it, I believe quoting the powershell program in the command should be enough.
exec("powershell -ExecutionPolicy Bypass \"get-ciminstance Win32_LogicalDisk | % VolumeSerialNumber\"");


text:
Q: Why won't this image show up? Using NSData and initWithData NSURL* urlEx = [NSURL URLWithString:@"Pacific_Map.png"];
NSData* mapExIMGData = [[NSData alloc] initWithContentsOfURL: urlEx];

UIImage* imgEx = [[UIImage alloc] initWithData:mapExIMGData];

mapImageViewEx.image = imgEx;

If I replace mapImageViewEx.image = imgEx; with mapImageViewEx.image = [UIImage imageNamed:@"Pacific_Map.png"]; it works, but I do not want to use imageNamed.

A: That's because imageNamed knows where to scan for the file, but initWithContentsOfURL expects the full path. use
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"Pacific_Map" ofType:@"png"];
NSURL* urlEx = [NSURL fileURLWithPath:imagePath];
NSData* mapExIMGData = [[NSData alloc] initWithContentsOfURL: urlEx];

UIImage* imgEx = [[UIImage alloc] initWithData:mapExIMGData];

mapImageViewEx.image = imgEx;

A: What's wrong with using imageNamed?  Anyway, you could use initWithContentsofPath.
+ (UIImage *)imageWithContentsOfFile:(NSString *)path

Tell us more about what you are trying to accomplish.  Good luck,
James
EDIT:  Sorry, I assumed Pacific_Map.png was just a placeholder path.  Like someone else posted, you need to indicate the full path if you're not going to use imageNamed.


text:
Q: TypeError: normalize() argument 2 must be str, not Series with a dataframe of strings I have a dataframe that contains news for each day and I try to analyze the intensity of the feeling for the day, it is to say if the general feeling of the day from the news is positive, negative or neutral. Here is the df_news dataframe :
    Date    name
0   2017-10-20  Gucci debuts art installation at its Ginza sto...
1   2018-08-01  Gucci Joins Paris Fashion Week for Its Spring ...
2   2018-04-20  Gucci launches its new creative hub Gucci ArtL...
3   2017-10-20  Gucci to launch homeware line Gucci Decor - CP...
4   2017-12-07  GUCCI opens new store at Miami Design District...
5   2018-01-12  Gucci opens Gucci Garden in Florence - LUXUO
6   2018-02-26  GUCCI's wild experiment with the Fall Winter 2...
7   2018-08-09  Gucci Revamped London Flagship Store | The Imp...
8   2018-08-01  Alessandro Michele Announces new Gucci Home co...
9   2017-10-20  Before He Picks Up the CFDA's International Aw...

I tried to get the intensity of the feeling with the following code he uses SentimentIntensityAnalyzer de nltk.sentiment.vader  :
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import unicodedata
sid = SentimentIntensityAnalyzer()
for date, row in df_news.T.iteritems():
    try:
        sentence = unicodedata.normalize('NFKD', df_news.loc[date, 'name']).encode('ascii','ignore')
        #print((sentence))
        ss = sid.polarity_scores(str(sentence))
        df_news.set_value(date, 'compound', ss['compound'])
        df_news.set_value(date, 'neg', ss['neg'])
        df_news.set_value(date, 'neu', ss['neu'])
        df_news.set_value(date, 'pos', ss['pos'])
    except TypeError:
        print(df_news.loc[date, 'name'])
        print(date)

However I get a TypeError for certain dates. Thanks to try catch you do not take it into account and draw the following table :
    name    compound    neg neu pos
Date
2017-10-20  Gucci debuts art installation at its Ginza sto...
2018-08-01  Gucci Joins Paris Fashion Week for Its Spring ...
2018-04-20  Gucci launches its new creative hub Gucci ArtL...   0.4404  0   0.756   0.244
2017-10-20  Gucci to launch homeware line Gucci Decor - CP...
2017-12-07  GUCCI opens new store at Miami Design District...   0   0   1   0
2018-01-12  Gucci opens Gucci Garden in Florence - LUXUO    0   0   1   0
2018-02-26  GUCCI's wild experiment with the Fall Winter 2...   0   0   1   0
2018-08-09  Gucci Revamped London Flagship Store | The Imp...   0.3182  0   0.602   0.398
2018-08-01  Alessandro Michele Announces new Gucci Home co...
2017-10-20  Before He Picks Up the CFDA's International Aw...

But when I delete try catch to understand why it failed, I get the following error :
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-2e9dbfc62bce> in <module>
      4 for date, row in df_news.T.iteritems():
      5 #    try:
----> 6     sentence = unicodedata.normalize('NFKD', df_news.loc[date, 'name']).encode('ascii','ignore')
      7     #print((sentence))
      8     ss = sid.polarity_scores(str(sentence))

TypeError: normalize() argument 2 must be str, not Series

Then I thought that the problem was with the lines that were not string but for example with the first :
>>>type(df_news['name'][0])
str

To get the data
doc_data = {
  "size": 10,
  "query": {
    "bool": {
      "must" : [
       {"term":{"text":"gucci"}}
     ]
    }
  }
 }

docs = create_doc("https://elastic:rKzWu2WbXI@db.luxurynsight.com/luxurynsight_v2/news/_search",doc_data)

information_df = pd.DataFrame.from_dict(docs.json()["hits"]["hits"])

# Reading the JSON file
df_news = pd.read_json('data.json')

# Converting the element wise _source feature datatype to dictionary
df_news._source = df_news._source.apply(lambda x: dict(x))

# Creating name column
df_news['name'] = df_news._source.apply(lambda x: x['name'])

# Creating createdAt column
df_news['createdAt'] = df_news._source.apply(lambda x: x['createdAt'])

df_news['createdAt'] =  pd.to_datetime(df_news['createdAt'], unit='ms')

df_news['createdAt'] = pd.DatetimeIndex(df_news.createdAt).normalize()
#df_news.createdAt.dt.normalize()

df_news['Date'] = df_news['createdAt']

df_news = df_news[['name','Date']]
df_news = df_news.set_index('Date')
information_df._source = information_df.apply(lambda x: dict(x))
df_news.reset_index()

It should give back :
    Date    name
0   2017-10-20  Gucci debuts art installation at its Ginza sto...
1   2018-08-01  Gucci Joins Paris Fashion Week for Its Spring ...
2   2018-04-20  Gucci launches its new creative hub Gucci ArtL...
3   2017-10-20  Gucci to launch homeware line Gucci Decor - CP...
4   2017-12-07  GUCCI opens new store at Miami Design District...
5   2018-01-12  Gucci opens Gucci Garden in Florence - LUXUO
6   2018-02-26  GUCCI's wild experiment with the Fall Winter 2...
7   2018-08-09  Gucci Revamped London Flagship Store | The Imp...
8   2018-08-01  Alessandro Michele Announces new Gucci Home co...
9   2017-10-20  Before He Picks Up the CFDA's International Aw...

Edit :
I grouped the articles that appears the same days and put in lists the articles
# get date out of the index to column
df_news = df_news.reset_index()
# optional
df_news['Date'] = pd.to_datetime(df_news['Date'])
# groupby and output group rows as list
df_news = df_news.groupby('Date')['name'].apply(list)
df_news.head()

It gives me back :
Date
2017-10-20    [Gucci debuts art installation at its Ginza st...
2017-12-07    [GUCCI opens new store at Miami Design Distric...
2018-01-12       [Gucci opens Gucci Garden in Florence - LUXUO]
2018-02-26    [GUCCI's wild experiment with the Fall Winter ...
2018-04-20    [Gucci launches its new creative hub Gucci Art...
2018-08-01    [Gucci Joins Paris Fashion Week for Its Spring...
2018-08-09    [Gucci Revamped London Flagship Store | The Im...
Name: name, dtype: object

Therefore when I try to apply Stael's answer :
sentence = df_news.loc[date, 'name'].apply(lambda x: unicodedata.normalize('NFKD', x).encode('ascii','ignore'))

That is to say to normalize to each item in the series
I get the following error :
---------------------------------------------------------------------------
IndexingError                             Traceback (most recent call last)
<ipython-input-173-1bc93a0a065c> in <module>
      5     try:
      6         #sentence = unicodedata.normalize('NFKD', df_news.loc[date, 'name']).encode('ascii','ignore')
----> 7         sentence = df_news.loc[date, 'name'].apply(lambda x: unicodedata.normalize('NFKD', x).encode('ascii','ignore'))
      8         ss = sid.polarity_scores(str(sentence))
      9         df_news.set_value(date, 'compound', ss['compound'])

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1470             except (KeyError, IndexError):
   1471                 pass
-> 1472             return self._getitem_tuple(key)
   1473         else:
   1474             # we by definition only have the 0th axis

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
    873
    874         # no multi-index, so validate all of the indexers
--> 875         self._has_valid_tuple(tup)
    876
    877         # ugly hack for GH #836

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
    218         for i, k in enumerate(key):
    219             if i >= self.obj.ndim:
--> 220                 raise IndexingError('Too many indexers')
    221             try:
    222                 self._validate_key(k, i)

IndexingError: Too many indexers

And when I try to only take Date in the Index I got sentence = df_news.loc[date].aply(x: ... :
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-176-308d1f6c6644> in <module>
      5     try:
      6         #sentence = unicodedata.normalize('NFKD', df_news.loc[date, 'name']).encode('ascii','ignore')
----> 7         sentence = df_news.loc[date].apply(lambda x: unicodedata.normalize('NFKD', x).encode('ascii','ignore'))
      8         ss = sid.polarity_scores(str(sentence))
      9         df_news.set_value(date, 'compound', ss['compound'])

AttributeError: 'list' object has no attribute 'apply'

A: it looks to me like it is this line:
sentence = unicodedata.normalize('NFKD', df_news.loc[date, 'name']).encode('ascii','ignore')

you're trying to call normalise on each item in the series df.news.loc[...]
but pandas doesn't apply the function across the series for you - I think what you want to do is something like this:
sentence = df_news.loc[date, 'name'].apply(lambda x: unicodedata.normalize('NFKD', x).encode('ascii','ignore')

which is the pandas way of applying a function (normalize) to each item in a series.

Edit:
Theory 2 - when you call df_news.loc[date, 'name'] you are selecting the item where index==date and column=='name' - but it looks from your question that some of the date's are duplicated in your index, which means that sometimes instead of getting a single record where you can call unicodedata.normalize on it, you are getting a series, which causes your error.
you'll notice that the records that didn't fill when you used the 'try: except:` clause are records which have duplicated dates.
you need to handle that in some way, perhaps by using row out of iteritems rather than date, but that's for you to figure out.

A: seeing as you have moved on to a 3rd error on the one post I thought I'll have one more go at this.
First and foremost I feel like you don't understand a lot of your own code. errors like AttributeError: 'list' object has no attribute 'apply' imply to me that you don't know what your variable are when you are operating on them, so I think you need to work more slowly and carefully to understand what each bit of your code is doing before you move on to the next section.
That said, your problem isn't as complicated as you have made it - you are trying to apply these two lines of code
    sentence = unicodedata.normalize('NFKD', df_news.loc[date, 'name']).encode('ascii','ignore')

    ss = sid.polarity_scores(str(sentence))

to every entry in the column 'name' in your dataframe, which is not that hard.
you could do it as easily as this:
scores = []
for entry in df['name']:
    sentence = unicodedata.normalize('NFKD', entry).encode('ascii','ignore')
    scores.append(sid.polarity_scores(str(sentence)))

that will give you a list of the score dictionaries you were calling ss
you can apply those as columns in your dataframe like this:
df['new_column'] = [i['example_key'] for i in scores]

it's not the best or most efficient way of doing it, but it is a pretty simple way for you to achieve what it looks like you're trying to do.
Good luck.

if you have previously grouped by day, and listed your strings (btw I don't think you should do that) then you need another layer of iteration
scores = []
for sentence_list in df['name']:
    for entry in sentence_list:
        sentence = unicodedata.normalize('NFKD', entry).encode('ascii','ignore')
        scores.append(sid.polarity_scores(str(sentence)))


text:
Q: How to generate key prefix for "unstable" types I use a mocking framework that exposes a method for generating mock record ids. The utility method uses getKeyPrefix() to mock an Id. This works for most object types but doesn't work for __Share records.
I'm not sure how to mock these Ids because even though they are "unstable" salesforce somehow can validate the id when setting it and throws an error
Folder__Share testFolderShare1 = new Folder__Share(
    Id = TestUtils.generateId(Folder__Share.SObjectType)
);

System.TypeException: Invalid id value for this SObject type: 02f000000000007AAA

How can I generate the key prefix for unstable types?
Util for generating Id:
private static Integer seed = 1;
public static Id generateId(SObjectType objectType) {
    String result = String.valueOf(seed++);
    String prefix = objectType.getDescribe().getKeyPrefix();
    if (prefix == null && objectType.getDescribe().getAssociateEntityType() == 'Share') {
        prefix = '02c';
    }
    return prefix + '0'.repeat(12 - result.length()) + result;
}


text:
Q: Why doesn't this simple program work? I'm trying to sort out everything concerning the way Unicode works in Windows console applications. Why doesn't this simple program work?
#include <iostream>

int wmain(int argc, const wchar_t* const argv[])
{
    for (int i = 1; i < argc; ++i)
        std::wcout << argv[i] << std::endl;

    return 0;
}

Compiled with
>cl /EHsc /D _UNICODE /D UNICODE /Zc:wchar_t test.cpp

the program produces
> test.exe 1 2 3 abc абв
1
2
3
abc

Where is the fifth argument? I have to mention that абв fits into both my GetACP() and GetConsoleCP() & GetConsoleOutputCP() code pages (1251, 866 & 866). It's interesting that the program works (in a way) with the characters outside of those code pages:
> test.exe Sæter
Sцter

But:
> test.exe абв Sæter

A: I think this is because wcout converts to narrow characters.
See this other question about this topic.
Another good link.


text:
Q: Systemd write to file after killing service I have my Python script, which is started via systemd .service file (mine is called skriptaRFM.service). In my Python script I write some values in files and when I kill service I want to write in those files some lines. I read on forums about Kill functions in service files but I don't know which one is the right one for me. I have except function in my script but it won't execute it if I stop service.
Can anyone tell me what can I do? Thank you :)


text:
Q: ¿Como puedo hacer que las coordenadas de dibujo de un cuadrado sea la misma de un circulo? decidì mejorar un poco un antiguo juego, y me encontrè este problema:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
let width=70,height=70;
let radio=(width+height)/Math.PI;
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.arc(30,30,radio,0,(Math.PI/180)*360,0);
ctx.strokeRect(30,30,width,height);
ctx.stroke();
</script>

</body>
</html>

El circulo no se dibuja en la misma posicion que el cuadrado.
Resultado esperado:

Y al momento de ver la coliciòn de un circulo con un cuadrado los calculos se me rompen.

A: El cuadrado y el círculo no son concéntricos porque la función arc toma como posición el centro mientras que strokeRect la esquina superior izquierda.
Aprovechando para implementar funciones que dibujen a partir del centro queda así:

function cuadrado(center, size){
    halfSize = { x: size.x / 2, y: size.y / 2 }
    topLeftCorner = { x: center.x - halfSize.x, y: center.y - halfSize.y }
    ctx.strokeRect(topLeftCorner.x, topLeftCorner.y, size.x, size.y)
}

function circulo(center, radius){
    ctx.arc(center.x, center.y, radius, 0, Math.PI * 2)
}

var c = document.getElementById("myCanvas")
var ctx = c.getContext("2d")
let centro = { x: 50, y: 50 }
let tamaño = { x: 50, y: 50 }
let diámetro = Math.sqrt(tamaño.x * tamaño.x + tamaño.y * tamaño.y)

ctx.moveTo(0,0)
ctx.lineTo(200,100)
sqrt2 = Math.sqrt(2)
cuadrado(centro, tamaño)
circulo(centro, diámetro/2)
ctx.stroke()
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">Your browser does not support the HTML canvas tag.</canvas>

A:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="120" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
let width = 70, height = 70;
let dia = Math.sqrt( width * width + height * height );
ctx.arc( 30 + width/2, 30 + height/2,  dia/2, 0, (Math.PI/180) *360, 0 );
ctx.strokeRect( 30, 30, width, height );
ctx.stroke();
</script>

</body>
</html>

En dia, obtenemos el diámetro en base al teorema de Pitágoras, que nos devuelve la hipotenusa del triángulo formado por los lados del cuadrado.
Dado que para el dibujo del circulo, se toma como referencia su centro, ubicamos este sumandole la mitad del lado a la posición del cuadrado.

A: Solamente hice modificaciones los siguientes cálculos:
let radio = (width + height) / 3 + 4;

ctx.arc(65, 65, radio, 0, (Math.PI / 180) * 360, 0);

Y obtienes el resultado esperado, ejemplo:

var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
let width = 70, height = 70;
let radio = (width + height) / 3 + 4;
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.arc(65, 65, radio, 0, (Math.PI / 180) * 360, 0);
ctx.strokeRect(30, 30, width, height);
ctx.stroke();
<canvas id="myCanvas" width="200" height="120" style="border:1px solid #d3d3d3;">
  Your browser does not support the HTML canvas tag.
</canvas>


text:
Q: Azure Functions and SharePoint Online - Newtonsoft.Json issue when calling ClientContex's "CreateSiteAsync" function I'd like my Azure Function to be triggered on Azure Queue events, and use the event data when communicating with SharePoint Online. The first SharePoint task would be to provision new sites based on the incoming Queue data.
The complete code is added to the bottom of this post.
I've set up a new Visual Studio 2019 Azure Function v1 function, and installed Microsoft.NET.Sdk.Functions v1.0.24, Newtonsoft.Json v11.0.2 and SharePointPnPCoreOnline v3.15.1911.
After fighting the very infamous Could not load file or assembly 'Newtonsoft.Json, Version=11.0.2, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. error message, I came across this blog post suggesting I should use binding redirects. I've set up my project according to the blog post, but still struggle with the above error message. Here's a larger portion of the error message:

[15.11.2019 07:54:02] Something went wrong: System.ArgumentException: IDX12729: Unable to decode the header '[PII
  is hidden]' as Base64Url encoded string. jwtEncodedString: '[PII is
  hidden]'. ---> System.TypeInitializationException: The type
  initializer for 'System.IdentityModel.Tokens.Jwt.JsonExtensions' threw
  an exception. ---> System.IO.FileNotFoundException: Could not load
  file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral,
  PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The
  system cannot find the file specified. --->
  System.IO.FileNotFoundException: Could not load file or assembly
  'Newtonsoft.Json, Version=11.0.2, Culture=neutral,
  PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The
  system cannot find the file specified. [15.11.2019 07:54:02]    at
  System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String
  codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint,
  StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean
  throwOnFileNotFound, Boolean forIntrospection, Boolean
  suppressSecurityChecks) [15.11.2019 07:54:02]    at
  System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String
  codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint,
  StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean
  throwOnFileNotFound, Boolean forIntrospection, Boolean
  suppressSecurityChecks) [15.11.2019 07:54:02]    at
  System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName
  assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly,
  StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean
  throwOnFileNotFound, Boolean forIntrospection, Boolean
  suppressSecurityChecks) [15.11.2019 07:54:02]    at
  System.Reflection.Assembly.Load(AssemblyName assemblyRef) [15.11.2019
  07:54:02]    at
  FunctionApp5.Application.AssemblyBindingRedirectHelper.<>c__DisplayClass2_0.b__0(Object
  sender, ResolveEventArgs args) [15.11.2019 07:54:02]    at
  System.AppDomain.OnAssemblyResolveEvent(RuntimeAssembly assembly,
  String assemblyFullName) [15.11.2019 07:54:02]    --- End of inner
  exception stack trace --- [15.11.2019 07:54:02]    at
  System.IdentityModel.Tokens.Jwt.JsonExtensions..cctor() [15.11.2019
  07:54:02]    --- End of inner exception stack trace --- [15.11.2019
  07:54:02]    at
  System.IdentityModel.Tokens.Jwt.JsonExtensions.DeserializeJwtHeader(String
  jsonString) [15.11.2019 07:54:02]    at
  System.IdentityModel.Tokens.Jwt.JwtSecurityToken.Decode(String[]
  tokenParts, String rawData)

I noticed that the error message first referst to the version 10.0.0.0 of Newtonsoft.JSON, and then referst to the version 11.0.2. So it looks to me like the bindings redirect actually kicks in, but that the runtime can't find version 11.0.2 even though it's installed.
Extract from the debug log:
RedirectAssembly()
Authenticate to SharePoint
Creating SharePoint site
Binding Newtonsoft.Json to version 11.0.2

Another thing I've noticed, is that the actual bindings seems to be performed after my business code (i.e ClientContext's CreateSiteAsync function, that creates the actual site) have executed. I base this statements off the fact that when reading through the debug output, the line that says Binding Newtonsoft.Json to version 11.0.2 comes after the line Creating SharePoint site. So I'm thinking that if I find some way of running the actual binding redirects before the business code is run, maybe things will work.
Any help in debugging this issue will be greatly appreciated.
The code
class "AssemblyBindingRedirectHelper"
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Text;

namespace FunctionApp5.Application
{
    public static class AssemblyBindingRedirectHelper
    {

        public static void ConfigureBindingRedirects()
        {
            var redirects = GetBindingRedirects();
            redirects.ForEach(RedirectAssembly);
        }

        private static List<BindingRedirect> GetBindingRedirects()
        {
            var result = new List<BindingRedirect>();
            var bindingRedirectListJson = Environment.GetEnvironmentVariable("BindingRedirects");
            using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(bindingRedirectListJson)))
            {
                var serializer = new DataContractJsonSerializer(typeof(List<BindingRedirect>));
                result = (List<BindingRedirect>)serializer.ReadObject(memoryStream);
            }
            return result;
        }

        private static void RedirectAssembly(BindingRedirect bindingRedirect)
        {

            Debug.WriteLine("RedirectAssembly() ");
            ResolveEventHandler handler = null;
            handler = (sender, args) =>
            {
                var requestedAssembly = new AssemblyName(args.Name);
                if (requestedAssembly.Name != bindingRedirect.ShortName)
                {
                    return null;
                }
                var targetPublicKeyToken = new AssemblyName("x, PublicKeyToken=" + bindingRedirect.PublicKeyToken).GetPublicKeyToken();
                requestedAssembly.SetPublicKeyToken(targetPublicKeyToken);
                requestedAssembly.Version = new Version(bindingRedirect.RedirectToVersion);
                requestedAssembly.CultureInfo = CultureInfo.InvariantCulture;
                AppDomain.CurrentDomain.AssemblyResolve -= handler;

                Debug.WriteLine("Binding " + bindingRedirect.ShortName + " to version " + bindingRedirect.RedirectToVersion);

                return Assembly.Load(requestedAssembly);
            };
            AppDomain.CurrentDomain.AssemblyResolve += handler;
        }

        public class BindingRedirect
        {
            public string ShortName { get; set; }
            public string PublicKeyToken { get; set; }
            public string RedirectToVersion { get; set; }
        }
    }
}

class "ApplicationHelper"
using System;
using System.Diagnostics;

public static class ApplicationHelper
{
    private static bool IsStarted = false;
    private static object _syncLock = new object();

    public static void Startup()
    {
        if (!IsStarted)
        {
            lock (_syncLock)
            {
                if (!IsStarted)
                {
                    FunctionApp5.Application.AssemblyBindingRedirectHelper.ConfigureBindingRedirects();
                    IsStarted = true;
                }
            }
        }
    }
}

The business logic class
I made a small modification to the code, based on this pattern, but I believe the effect should be pretty much the same.
using System;
using System.Diagnostics;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core.Sites;

namespace FunctionAppBootstrapping
{

    public static class Bootstrapping
    {
        public static void Init()
        {
            ApplicationHelper.Startup();
        }
    }

    public static class Function1
    {

        [FunctionName("Function1")]
        public static async void Run([QueueTrigger("queue001", Connection = "")]string myQueueItem, TraceWriter log)
        {
            Bootstrapping.Init();
            log.Info($"C# Queue trigger function processed: {myQueueItem}");

            var azureClientId = "myID";
            var azureClientSecret = "mySecret";
            string siteUrl = "https://<mytenant>.sharepoint.com";

            Debug.WriteLine("Authenticate to SharePoint " + System.Threading.Thread.CurrentThread.Name);
            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, azureClientId, azureClientSecret))
            {
                var url = siteUrl + "/sites/" + myQueueItem;

                CommunicationSiteCollectionCreationInformation communicationSiteInfo = new CommunicationSiteCollectionCreationInformation
                {
                    Title = "My new site name",
                    Url = url,
                    SiteDesign = CommunicationSiteDesign.Blank,
                    Description = "My description",
                    Owner = "akeho@devmiljo.no"
                };

                try
                {
                    Debug.WriteLine("Creating SharePoint site");
                    var createCommSite = await cc.CreateSiteAsync(communicationSiteInfo);
                    log.Info($"Successfully created the page {url}. Return value: {createCommSite}");
                }
                catch (Exception e)
                {
                    log.Error($"Something went wrong: {e.ToString()}");
                }
            };

        }
    }
}


text:
Q: Per hour Holt-Winter time series prediction (forecasting) I am fairly new to the R package and I am dealing with time series. I have to build a prediction model for forecasting clicks for the future. The time interval for prediction needs to be hourly.
My example time series:
 DateTime            Clicks

(06/23/13 00:00:00)  757
(06/23/13 01:00:00)  714
(06/23/13 02:00:00)  776
(06/23/13 03:00:00)  870
(06/23/13 04:00:00) 1263
(06/23/13 05:00:00) 1457
(06/23/13 06:00:00) 1621
(06/23/13 07:00:00) 1606
(06/23/13 08:00:00) 1779
(06/23/13 09:00:00) 1832
(06/23/13 10:00:00) 1808
(06/23/13 11:00:00) 1789
(06/23/13 12:00:00) 1907
(06/23/13 13:00:00) 2021
(06/23/13 14:00:00) 2018
(06/23/13 15:00:00) 1836
(06/23/13 16:00:00) 1627
(06/23/13 17:00:00) 1331
(06/23/13 18:00:00) 1059
(06/23/13 19:00:00)  817
(06/23/13 20:00:00)  761
(06/23/13 21:00:00)  781
(06/23/13 22:00:00)  752
(06/23/13 23:00:00)  725
(06/24/13 00:00:00)  708
(06/24/13 01:00:00)  718
(06/24/13 02:00:00)  791
(06/24/13 03:00:00)  857
(06/24/13 04:00:00) 1094
(06/24/13 05:00:00) 1247
(06/24/13 06:00:00) 1316
(06/24/13 07:00:00) 1401
(06/24/13 08:00:00) 1575
(06/24/13 09:00:00) 1604
(06/24/13 10:00:00) 1774
(06/24/13 11:00:00) 1865
(06/24/13 12:00:00) 1964
(06/24/13 13:00:00) 2002
(06/24/13 14:00:00) 2043
(06/24/13 15:00:00) 2030
(06/24/13 16:00:00) 1733
(06/24/13 17:00:00) 1420
(06/24/13 18:00:00) 1075
(06/24/13 19:00:00)  831
(06/24/13 20:00:00)  789
(06/24/13 21:00:00)  791
(06/24/13 22:00:00)  715
(06/24/13 23:00:00)  683
(06/25/13 00:00:00)  802
(06/25/13 01:00:00)  811
(06/25/13 02:00:00)  838
(06/25/13 03:00:00)  851
(06/25/13 04:00:00) 1064
(06/25/13 05:00:00) 1191
(06/25/13 06:00:00) 1242
(06/25/13 07:00:00) 1233
(06/25/13 08:00:00) 1452
(06/25/13 09:00:00) 1501
(06/25/13 10:00:00) 1718
(06/25/13 11:00:00) 1861
(06/25/13 12:00:00) 1896
(06/25/13 13:00:00) 2073
(06/25/13 14:00:00) 2279
(06/25/13 15:00:00) 2239
(06/25/13 16:00:00) 2018
(06/25/13 17:00:00) 1550
(06/25/13 18:00:00) 1182
(06/25/13 19:00:00) 1063
(06/25/13 20:00:00)  973
(06/25/13 21:00:00) 1027
(06/25/13 22:00:00)  961
(06/25/13 23:00:00)  890
(06/26/13 00:00:00)  894
(06/26/13 01:00:00)  835
(06/26/13 02:00:00)  852
(06/26/13 03:00:00)  893
(06/26/13 04:00:00) 1111
(06/26/13 05:00:00) 1239
(06/26/13 06:00:00) 1263
(06/26/13 07:00:00) 1260
(06/26/13 08:00:00) 1451
(06/26/13 09:00:00) 1556
(06/26/13 10:00:00) 1733
(06/26/13 11:00:00) 1981
(06/26/13 12:00:00) 2063
(06/26/13 13:00:00) 2150
(06/26/13 14:00:00) 2278
(06/26/13 15:00:00) 2188
(06/26/13 16:00:00) 1980
(06/26/13 17:00:00) 1611
(06/26/13 18:00:00) 1381
(06/26/13 19:00:00) 1211
(06/26/13 20:00:00) 1129
(06/26/13 21:00:00) 1092
(06/26/13 22:00:00) 1009
(06/26/13 23:00:00)  973
(06/27/13 00:00:00)  865
(06/27/13 01:00:00)  805
(06/27/13 02:00:00)  840
(06/27/13 03:00:00)  813
(06/27/13 04:00:00) 1010
(06/27/13 05:00:00) 1201
(06/27/13 06:00:00) 1329
(06/27/13 07:00:00) 1343
(06/27/13 08:00:00) 1532
(06/27/13 09:00:00) 1612
(06/27/13 10:00:00) 1768
(06/27/13 11:00:00) 1977
(06/27/13 12:00:00) 2089
(06/27/13 13:00:00) 2247
(06/27/13 14:00:00) 2270
(06/27/13 15:00:00) 2275
(06/27/13 16:00:00) 2155
(06/27/13 17:00:00) 1639
(06/27/13 18:00:00) 1315
(06/27/13 19:00:00) 1099
(06/27/13 20:00:00) 1052
(06/27/13 21:00:00) 1099
(06/27/13 22:00:00)  965
(06/27/13 23:00:00)  961
(06/28/13 00:00:00)  765
(06/28/13 01:00:00)  830
(06/28/13 02:00:00)  874
(06/28/13 03:00:00)  845
(06/28/13 04:00:00) 1011
(06/28/13 05:00:00) 1160
(06/28/13 06:00:00) 1232
(06/28/13 07:00:00) 1310
(06/28/13 08:00:00) 1467
(06/28/13 09:00:00) 1639
(06/28/13 10:00:00) 1704
(06/28/13 11:00:00) 3704
(06/28/13 12:00:00) 7350
(06/28/13 13:00:00) 7629
(06/28/13 14:00:00) 7570
(06/28/13 15:00:00) 7276
(06/28/13 16:00:00) 7189
(06/28/13 17:00:00) 7139
(06/28/13 18:00:00) 7167
(06/28/13 19:00:00) 6871
(06/28/13 20:00:00) 6575
(06/28/13 21:00:00) 6112
(06/28/13 22:00:00) 5276
(06/28/13 23:00:00) 4407
(06/29/13 00:00:00) 3741
(06/29/13 01:00:00) 3427
(06/29/13 02:00:00) 3311
(06/29/13 03:00:00) 3096
(06/29/13 04:00:00) 3010
(06/29/13 05:00:00) 3301
(06/29/13 06:00:00) 3783
(06/29/13 07:00:00) 4578
(06/29/13 08:00:00) 5599
(06/29/13 09:00:00) 6590
(06/29/13 10:00:00) 6998
(06/29/13 11:00:00) 7323
(06/29/13 12:00:00) 7282
(06/29/13 13:00:00) 7009
(06/29/13 14:00:00) 6636
(06/29/13 15:00:00) 6407
(06/29/13 16:00:00) 6386
(06/29/13 17:00:00) 6505
(06/29/13 18:00:00) 3104
(06/29/13 19:00:00)  939
(06/29/13 20:00:00)  915
(06/29/13 21:00:00)  955
(06/29/13 22:00:00)  968
(06/29/13 23:00:00)  870
(06/30/13 00:00:00) 3504
(06/30/13 01:00:00) 3122
(06/30/13 02:00:00) 2874
(06/30/13 03:00:00) 2613
(06/30/13 04:00:00) 2905
(06/30/13 05:00:00) 2806
(06/30/13 06:00:00) 3244
(06/30/13 07:00:00) 3789
(06/30/13 08:00:00) 5015
(06/30/13 09:00:00) 6031
(06/30/13 10:00:00) 6841
(06/30/13 11:00:00) 7014
(06/30/13 12:00:00) 7265
(06/30/13 13:00:00) 7460
(06/30/13 14:00:00) 7275
(06/30/13 15:00:00) 7531
(06/30/13 16:00:00) 7013
(06/30/13 17:00:00) 6637
(06/30/13 18:00:00) 5770
(06/30/13 19:00:00) 5593
(06/30/13 20:00:00) 6524
(06/30/13 21:00:00) 5081
(06/30/13 22:00:00) 1131
(06/30/13 23:00:00)  949

This is a time series for a whole week on a hourly basis. Considering this data I need to predict using Holt-Winters the number of clicks that will be obtained for the next hour i.e. (06/28/13 00:00:00). I am trying to figure it out but am getting really confused. I will be thankful if someone can point me to the right direction.
EDIT:
I am using the Holt-Winters predict module as follows:
search_fit <- HoltWinters(z)
p = predict(search_fit,24)

But the problem is that the HOLT-WINTERS is not detecting any trend in the prediction. is it normal? Because there is a big change starting 06/28/13.
Following are my predicted values:
Time Series:
Start = c(15887, 1)
End = c(15887, 24)
Frequency = 24
            fit
 [1,]  927.6462
 [2,]  935.2716
 [3,] 1006.5636
 [4,] 1066.4182
 [5,] 1295.5852
 [6,] 1442.9397
 [7,] 1508.1693
 [8,] 1590.9613
 [9,] 1762.5033
[10,] 1789.1287
[11,] 1958.1083
[12,] 2049.1711
[13,] 2054.7757
[14,] 2168.1302
[15,] 2163.1514
[16,] 1979.5268
[17,] 1772.7355
[18,] 1483.0484
[19,] 1220.1946
[20,]  987.2366
[21,]  938.1745
[22,]  965.5915
[23,]  940.4669
[24,]  911.0089

and this is the prediction plot.

The trend component shows no variation. There is something I might be doing wrong while using the predict method of Holt-Winters.

A: Here are some suggestions/things to try:
One reason you are not seeing HoltWinters pick up a trend could be that the change you are referring to (on 6/28/13 in your data) is manifesting itself in the level component. The clicks have changed materially starting from noon on 6/28.
One note: HoltWinters() will spit out the Smoothing parameters (alpha, beta, gamma). It will give you the slope b. If beta is 0, that only means that the trend does not change over the time series. It started with a slope b, and continues to be at the same slope.
Things to try
Try this:
 > library(forecast)
 > accuracy(search_fit)

Also a good idea to check the auto-correlations:
 > acf(search_fit$residuals, lag.max=24)

A few general comments that might help your analysis

*

*In addition to HoltWinters (exponential smoothing), you might want to look into ARIMA methods.
As Rob Hyndman states at the start of Chapter 8 of his textbook:

Exponential smoothing and ARIMA models are the two most
  widely-used approaches to time series forecasting, and provide
  complementary approaches to the problem. While exponential
  smoothing models were based on a description of trend and
  seasonality in the data, ARIMA models aim to describe the
  autocorrelations in the data.

*

*As a quick starting reference I find 1.Avril Coghlan's Little Book of R for Time series
to be a great primer. Also, 2. Time Series Analysis with R - Part I  is great, with a little more technical detail.

*As and when you find the time, reading Prof. Rob Hyndman's book Forecasting Principles and Practice online is well worth the time, for anyone who's going to be doing Time Series analysis.

*Be sure to try the forecast package as well. Especially its auto.arima() function is an incredible time saver.
Hope this helps.

A: Try auto.arima or ets for automated time series
See code here
http://rpubs.com/newajay/timeseries


text:
Q: How to make Ionic CLI show what files are generated when running `ionic g page MyPage`? It currently doesn't show up. This is what I want to see:
$ ionic g page About
√ Create www/app/about/about.html
√ Create www/app/about/about.js
√ Create www/app/about/about.scss

Currently using a Mac with OSX, using iTerm.


text:
Q: Localized messages in Pentaho reports I am currently trying to put a localized message in a Pentaho report. The message has one parameter which is to be inserted into the message's localized text like
All approved disconnects of ${company} in ${region}
How do I do that using Pentaho Report Designer? I've tried a resource-message. It correctly accesses a localized text defined in a resource bundle inlined with the report file but I cannot get it to substitute the placeholder for the parameter. How do I connect the message to parameters of the report?

A: Are you connecting the message to parameters or a field? A resource-message should be fine. You need to replace your curly braces to parentheses.
For example, in my translations file.
REPORT_DATE=Report Date: $(report date, date, MMMM yyyy)


text:
Q: CSS Aspect Ratio - set width of child element based on dynamic parent height To begin, let me explain what I know exists and have tried variations of:

*

*The typical aspect ratio hack, which manages the height of an
element based on a width.

*Stackoverflow answers, where the
height is determined by an image, which then dictates the width of
the container.

What I'm interested in is pure CSS solutions, with whatever hacky, new-fangled, experimental properties you can think of, that achieves the following results:

The height of the card is based on content (in this case a title and a paragraph). We'll call that h. Another element within the card should be that same h height (based on the content of a sibling), and whatever that h amount is, it should also be the width of that element (to create a square).
Edit (2019-28-02): I apologize for not being clear on this next point but, in order to get the text to wrap, the area where the text sits should have a maximum width. Marc Bellêtre's solution is admittedly pretty close as of today.
This question is very similar to an older question which did not receive any responses. The difference is that the parent, in this case, is not receiving any explicit height values. The height of the parent card is purely determined by the text inside of it. I can imagine that if that question has not received any responses/solutions that this may fare no different, especially since this is slightly more difficult. However, new technologies have come around since then (ie.: flexbox/grid), that might be helpful.
Please, no JavaScript solutions. I'm very aware of how to achieve this using it.
Sometimes when I load this code, the box isn't even square. The big problem is it doesn't respect the height: 100% at all but then it will be square after fiddling with resizing the browser or content. Updating the ratio makes the box grow unexpectedly large.

.card {
  background: #ddd;
  display: inline-flex;
}

.aspect-ratio {
  border: 1px solid;
  padding: 1em;
  aspect-ratio: 1 / 1;
  background: #ccc;
}

.content {
  padding: 1em;
  flex: 1 1 200px;
}

h3,
p {
  margin: 0;
}

(h)

Title

The more I type, the taller this box gets (h)

A: You can achieve this using an image with a 1:1 aspect ratio and the flex property.

section {
  display: flex;
}

.square {
  display: grid;
  background-color: lightgrey;
}

img {
  height: 100%;
  width: auto;
  max-width: 200px;
  visibility: hidden;
}

.text {
  padding-left: 1rem;
}

Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vulputate lectus nec ligula fermentum suscipit. Nam lobortis turpis sed augue interdum maximus.

EDIT JULY 2021:
For some reason the previous solution was not working anymore without adding display: grid to the pixel container.
There is still a bug I didn't manage to fix causing the element to have sometimes a wrong aspect ratio before resizing the window.
Also this solution has a major drawback as it breaks as soon as the text wraps into a number of lines making its height too big. The square then grows in width as it is based on the height, reducing the width left for the text which grows again in height... Ending up up in some kind of infinite loop.
This can be avoided using a max-width on the image, but obviously this would break the aspect ratio.
Anyway this more a hack than a real solution to the question but I couldn't find a better way to achieve this without using Javascript.


text:
Q: How to scroll to certain row in QML TreeView In TreeView, selecting a row by clicking it.
But I want to focus the row in TreeView by indicating the row QModelIndex and roleName.
I found similar function in ListView:
positionViewAtIndex(int index, PositionMode mode)

How to do this in TreeView?

A: Try to use hidden variable __listView.
__listView.positionViewAtIndex(row, mode)


text:
Q: Dilworth's Theorem is equivalent to Hall's I have been told that Dilworth's Theorem implies Hall's Theorem.
I don't seem to be able to show this implication, especially because I haven't done any graph theory in a while!
Any help?
If possible, I would like a graph theory proof (and not using systems of distinct representative).
I believe the main idea is to order the bipartite graph $G = X \cup Y$ by letting $x<y$ if and only if $x \in X$, $y\in Y$ and there is an edge between $x$ and $y$. Now if I could show that I can assume the longest anti-chain in $G$ contains the whole of $X$, I am done. But I am not sure this is true!
I tried to apply Hall's Condition to a possibly "larger" anti-chain which does not contain some elements of X and show this is not possible, but I was unsuccessful.

A: More generally, you can show that, dilworth theorem implies that in bipartite graphs, maximum matching is equal to minimum vertex cover, and vice versa.
As a hint, one way is easy: the complement of a minimum vertex cover is an anti chain. I leave the other side to you!


text:
Q: How to change the background color of list items/elements in a nav bar using JQuery? I am just learning the JQuery and for the sake of testing my self I was creating a simple webpage having a nav-bar consists of list elements, and a header and footer. I want to change the background colors of the list elements of nav-bar whenever I click any item.
I have tried using the $(id-name) selector and .click() method to change the background color, but it just changes the background color of text, not the whole element containing the padding, width/height and borders etc.
Here is my HTML Code:

ELEMENT 1

ELEMENT 2

ELEMENT 3

ELEMENT 4

This is Text 1

This is text 2

This is text 3

This is text 4

Here is my CSS Code:
body{
    font-family: Helvetica;
    margin: 0;
    padding: 0;
}

#body{
    background-color: #fcfcfc;
    width: 75%;
    float: left;;
    height: 450;
}

#nav{
    background-color: #e1e4e6;
    width: 25%;
    float: left;
    height: 440px;
}

ul{
    list-style: none;
}

ul li a{
    text-decoration: none;
    padding: 20px;
    color: white;
    background-color: black;
    margin-bottom: 100px;
    font-style: italic;
}

ul li{
    margin-top: 40px;
}

Here is my JQuery Code:
$(document).ready(function(){
    $("#text1").css("background-color", "#38ceff");

    console.log("enter in script");

    $("#t1").click(function(){
        $("li").eq(0).css("background-color", "#505152");
        $("li").eq(1).css("background-color", "black");
        $("li").eq(2).css("background-color", "black");
        $("li").eq(3).css("background-color", "black");

        $("#text1").show();
        $("#text2").hide();
        $("#text3").hide();
        $("#text4").hide();
    });

    $("#t2").click(function(){
        $("li").eq(0).css("background-color", "black");
        $("li").eq(1).css("background-color", "#505152");
        $("li").eq(2).css("background-color", "black");
        $("li").eq(3).css("background-color", "black");

        $("#text1").hide();
        $("#text2").show();
        $("#text3").hide();
        $("#text4").hide();
    });

    $("#t3").click(function(){
        $("li").eq(0).css("background-color", "black");
        $("li").eq(1).css("background-color", "black");
        $("li").eq(2).css("background-color", "#505152");
        $("li").eq(3).css("background-color", "black");

        $("#text1").hide();
        $("#text2").hide();
        $("#text3").show();
        $("#text4").hide();
    });

    $("#t4").click(function(){
        $("li").eq(0).css("background-color", "black");
        $("li").eq(1).css("background-color", "black");
        $("li").eq(2).css("background-color", "black");
        $("li").eq(3).css("background-color", "#505152");

        $("#text1").hide();
        $("#text2").hide();
        $("#text3").hide();
        $("#text4").show();
    });
});

Any help would be greatly appreciated.

A:

$(function(){
    $("#text1").css("background-color", "#38ceff");

    console.log("enter in script");

    $("#t1").click(function(){
        $("li a").eq(0).css("background-color", "#505152");
  $("li a").eq(1).css("background-color", "black");
        $("li a").eq(2).css("background-color", "black");
        $("li a").eq(3).css("background-color", "black");

        $("#text1").show();
        $("#text2").hide();
        $("#text3").hide();
        $("#text4").hide();
    });

    $("#t2").click(function(){
        $("li a").eq(0).css("background-color", "black");
        $("li a").eq(1).css("background-color", "#505152");
        $("li a").eq(2).css("background-color", "black");
        $("li a").eq(3).css("background-color", "black");

        $("#text1").hide();
        $("#text2").show();
        $("#text3").hide();
        $("#text4").hide();
    });

    $("#t3").click(function(){
        $("li a").eq(0).css("background-color", "black");
        $("li a").eq(1).css("background-color", "black");
        $("li a").eq(2).css("background-color", "#505152");
        $("li a").eq(3).css("background-color", "black");

        $("#text1").hide();
        $("#text2").hide();
        $("#text3").show();
        $("#text4").hide();
    });

    $("#t4").click(function(){
        $("li a").eq(0).css("background-color", "black");
        $("li a").eq(1).css("background-color", "black");
        $("li a").eq(2).css("background-color", "black");
        $("li a").eq(3).css("background-color", "#505152");

        $("#text1").hide();
        $("#text2").hide();
        $("#text3").hide();
        $("#text4").show();
    });
});
body{
    font-family: Helvetica;
    margin: 0;
    padding: 0;
}

#body{
    background-color: #fcfcfc;
    width: 75%;
    float: left;;
    height: 450;
}

#nav{
    background-color: #e1e4e6;
    width: 25%;
    float: left;
    height: 440px;
}

ul{
    list-style: none;
}

ul li a{
    text-decoration: none;
    padding: 20px;
    color: white;
    background-color: black;
    margin-bottom: 100px;
    font-style: italic;
}

ul li{
    margin-top: 40px;
}

ELEMENT 1

ELEMENT 2

ELEMENT 3

ELEMENT 4

This is Text 1

This is text 2

This is text 3

This is text 4

Here is your javascript
 $("#text1").css("background-color", "#38ceff");

console.log("enter in script");

$("#t1").click(function(){
    $("li a").eq(0).css("background-color", "#505152");
    $("li a").eq(1).css("background-color", "black");
    $("li a").eq(2).css("background-color", "black");
    $("li a").eq(3).css("background-color", "black");

    $("#text1").show();
    $("#text2").hide();
    $("#text3").hide();
    $("#text4").hide();
});

$("#t2").click(function(){
    $("li a").eq(0).css("background-color", "black");
    $("li a").eq(1).css("background-color", "#505152");
    $("li a").eq(2).css("background-color", "black");
    $("li a").eq(3).css("background-color", "black");

    $("#text1").hide();
    $("#text2").show();
    $("#text3").hide();
    $("#text4").hide();
});

$("#t3").click(function(){
    $("li a").eq(0).css("background-color", "black");
    $("li a").eq(1).css("background-color", "black");
    $("li a").eq(2).css("background-color", "#505152");
    $("li a").eq(3).css("background-color", "black");

    $("#text1").hide();
    $("#text2").hide();
    $("#text3").show();
    $("#text4").hide();
});

$("#t4").click(function(){
    $("li a").eq(0).css("background-color", "black");
    $("li a").eq(1).css("background-color", "black");
    $("li a").eq(2).css("background-color", "black");
    $("li a").eq(3).css("background-color", "#505152");

    $("#text1").hide();
    $("#text2").hide();
    $("#text3").hide();
    $("#text4").show();
});

});

A:

$(document).ready(function() {
  $('#nav li a').on('click', function(){
    $('li a.orange').removeClass('orange');
    $(this).addClass('orange');
});
});
body {
  font-family: Helvetica;
  margin: 0;
  padding: 0;
}

#body {
  background-color: #fcfcfc;
  width: 75%;
  float: left;
  ;
  height: 450;
}

#nav {
  background-color: #e1e4e6;
  width: 25%;
  float: left;
  height: 440px;
}

.orange {
  background-color: #ffa500;
}

ul {
  list-style: none;
}

ul li a {
  text-decoration: none;
  padding: 20px;
  color: white;
  background-color: black;
  margin-bottom: 100px;
  font-style: italic;
}

ul li {
  margin-top: 40px;
}

.orange {
  background-color: #ffa500;
}

ELEMENT 1

ELEMENT 2

ELEMENT 3

ELEMENT 4

This is Text 1

This is text 2

This is text 3

This is text 4

how about doing it like this. this should get you started.

A: you don't select the
 element, you select the  tag inside the
.
change this code:
$("li").eq(2).css("background-color", "#505152");

to this code:
$("li a").eq(2).css("background-color", "#505152");


text:
Q: Workaround for showing font size > 1000px? Firefox limits font display to a size of 1000px. Users of my application with large displays may need font sizes > 1000px. Anyone aware of a work around?
I've tried using different units (rem, em, %) and changing the body font size in %.

A: Use css transforms instead, like:
transform:scale(200%,200%);


text:
Q: Redirect .php extension requests to same url without .php I've migrated a website. The previous website was built in php, so all the links in search have a php extension. The pages on the new website were built with static NuxtJS and do not.
All the resources I've found are for hiding .php from urls, but how can I use the .htaccess file to 301 redirect all .php urls to ones without them.
Take this:
https://example.com/about.php

and turn it into this:
https://example.com/about

before it hits the server and gives the visitor a 500 or 404 error?

A: Found something that works well enough
RewriteCond %{REQUEST_URI} .php$
RewriteRule ^(.*).php$ /$1 [R=301,L]

This turns
https://example.com/about.php

into
https://example.com/about/

I'd prefer if the redirect did not contain the ' / ' at the end, but I suppose this fixes the breaking changes for now.
I placed this rewrite before the non-www and https redirects that I currently have.


text:
Q: Why does painting in a timer cause application to become unresponsive I include Application.DoEvents() in 3 different places. Don´t know why this simple app is freezing.
Any idea?
It runs very well in my VM running Visual Studio 2010 in Windows 7. I move it to a Visual Studio 2019 in my host machine running Windows 10. It runs very well, but as soon I click inside it - to close the windows - it hangs the Windows control. Mouse is blocked in Visual Studio region, and I have to open Task Manager and kill the process to close the app.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Kaledoscópio
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();

            tmrStep.Tick += tmrStep_Tick;
            tmrStep.Start();
            Application.DoEvents();
        }

        private void tmrStep_Tick(object sender, EventArgs e)
        {
            Graphics g = frmMain.ActiveForm.CreateGraphics();

            Random randomColor = new Random();
            Color defaultColor = Color.FromArgb(randomColor.Next(255), randomColor.Next(255), randomColor.Next(255));
            Pen defaultPen = new Pen(defaultColor, 2);

            int intHeight = (int)g.VisibleClipBounds.Height;
            int intWidth = (int)g.VisibleClipBounds.Width;

            int intMiddleHeight = intHeight / 2;
            int intMiddleWidth = intWidth / 2;

            Point posTopLeft = new Point(0, 0);
            Point posTopRight = new Point(intWidth, 0);
            Point posBottomLeft = new Point(0, intHeight);
            Point posBottomRight = new Point(intWidth, intHeight);
            Point posMiddle = new Point(intMiddleWidth, intMiddleHeight);
            Point posMiddleTop = new Point(intMiddleWidth, 0);
            Point posMiddleLeft = new Point(0, intMiddleHeight);
            Point posMiddleRight = new Point(intWidth, intMiddleHeight);
            Point posMiddleBottom = new Point(intMiddleWidth, intHeight);

            int defaultStep = randomColor.Next(3, 10);

            int b1;
            for(b1 = 0; b1<=intMiddleWidth; b1+=defaultStep)
            {
                g.DrawLine(defaultPen, posTopLeft.X + b1, posTopLeft.Y, posMiddle.X - b1, posMiddle.Y);
                g.DrawLine(defaultPen, posTopRight.X - b1, posTopRight.Y, posMiddle.X + b1, posMiddle.Y);
                g.DrawLine(defaultPen, posMiddle.X - b1, posMiddle.Y, posBottomLeft.X + b1, posBottomLeft.Y);
                g.DrawLine(defaultPen, posMiddle.X + b1, posMiddle.Y, posBottomRight.X - b1, posBottomRight.Y);
                Application.DoEvents();
            }

            int b2;
            for( b2=0; b2<=intMiddleHeight; b2+=defaultStep)
            {
                g.DrawLine(defaultPen, posMiddleTop.X, posMiddleTop.Y + b2, posMiddleLeft.X, posMiddleLeft.Y - b2);
                g.DrawLine(defaultPen, posMiddleTop.X, posMiddleTop.Y + b2, posMiddleRight.X, posMiddleRight.Y - b2);
                g.DrawLine(defaultPen, posMiddleRight.X, posMiddleRight.Y + b2, posMiddleBottom.X, posMiddleBottom.Y - b2);
                g.DrawLine(defaultPen, posMiddleLeft.X, posMiddleLeft.Y + b2, posMiddleBottom.X, posMiddleBottom.Y - b2);
                Application.DoEvents();
            }

            Application.DoEvents();
        }
    }
}

A: For what it's worth, I was able to reproduce the hanging behavior using the code you posted. The program did eventually respond to closing the window, but it took a very long time. I did not spend any time trying to figure out exactly what caused the program to hang, because the code you have now is so horribly incorrect, so far from the right way to use the Windows Forms API, that I didn't see any point.
Problems in the code you posted include:

*

*Calling CreateGraphics(). A correctly written Winforms program should never need this.

*Calling DoEvents(). Ditto.

*Creating a new Random object every time you want to pick a new random number. See e.g. Random number generator only generating one random number

*Failing to dispose the Pen object you create. This can lead to exhausting of GDI handles, which might be the cause of the apparent hang (and would explain why the program eventually does come back…if and when the finalizer thread catches up with all the undisposed Pen objects, the handles can be reclaimed and the program can proceed normally, for a little while longer until it runs out of handles again).

*Using the static Form.ActiveForm property to get the form to draw into. This is wrong for at least two reasons: 1) it could draw into a window you don't intend to, and 2) there might not even be an active form, causing the property to return null, which then will lead to an exception.

All of the above can be solved easily, just by following the correct guidelines for writing Windows Forms programs:

*

*Only ever draw in a Paint event handler or in the OnPaint() override. Call Invalidate() to cause the Paint event to be raised.

*DoEvents() often is a crutch used by people who put long-running code into the UI thread, when that long-running code belongs in a different thread. Your code doesn't run long enough to block the UI thread for significant amounts of time, so it's not clear why that's even in your code. It can just be removed.

*Create a single Random object once, and reuse it each time you want a new random number.

*Dispose the Pen object. Use the using statement to do this safely and reliably.

*Just use the current Form instance to decide what form to affect (in a correct version of the code, this means calling Invalidate() on the current instance, rather than calling CreateGraphics(), but the same principle applies regardless).

Here is a version of the code you posted that is correct. As a happy benefit, it also runs a lot faster. It can actually keep up with the 100ms interval that's the default for the System.Windows.Forms.Timer class.
private readonly Random randomColor = new Random();

public Form1()
{
    InitializeComponent();
    tmrStep.Tick += tmrStep_Tick;
    tmrStep.Start();
}

private void tmrStep_Tick(object sender, EventArgs e)
{
    Invalidate();
}

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Graphics g = e.Graphics;

    Color defaultColor = Color.FromArgb(randomColor.Next(255), randomColor.Next(255), randomColor.Next(255));
    using (Pen defaultPen = new Pen(defaultColor, 2))
    {
        int intHeight = this.ClientSize.Height;
        int intWidth = this.ClientSize.Width;

        int intMiddleHeight = intHeight / 2;
        int intMiddleWidth = intWidth / 2;

        Point posTopLeft = new Point(0, 0);
        Point posTopRight = new Point(intWidth, 0);
        Point posBottomLeft = new Point(0, intHeight);
        Point posBottomRight = new Point(intWidth, intHeight);
        Point posMiddle = new Point(intMiddleWidth, intMiddleHeight);
        Point posMiddleTop = new Point(intMiddleWidth, 0);
        Point posMiddleLeft = new Point(0, intMiddleHeight);
        Point posMiddleRight = new Point(intWidth, intMiddleHeight);
        Point posMiddleBottom = new Point(intMiddleWidth, intHeight);

        int defaultStep = randomColor.Next(3, 10);

        int b1;
        for (b1 = 0; b1 <= intMiddleWidth; b1 += defaultStep)
        {
            g.DrawLine(defaultPen, posTopLeft.X + b1, posTopLeft.Y, posMiddle.X - b1, posMiddle.Y);
            g.DrawLine(defaultPen, posTopRight.X - b1, posTopRight.Y, posMiddle.X + b1, posMiddle.Y);
            g.DrawLine(defaultPen, posMiddle.X - b1, posMiddle.Y, posBottomLeft.X + b1, posBottomLeft.Y);
            g.DrawLine(defaultPen, posMiddle.X + b1, posMiddle.Y, posBottomRight.X - b1, posBottomRight.Y);
        }

        int b2;
        for (b2 = 0; b2 <= intMiddleHeight; b2 += defaultStep)
        {
            g.DrawLine(defaultPen, posMiddleTop.X, posMiddleTop.Y + b2, posMiddleLeft.X, posMiddleLeft.Y - b2);
            g.DrawLine(defaultPen, posMiddleTop.X, posMiddleTop.Y + b2, posMiddleRight.X, posMiddleRight.Y - b2);
            g.DrawLine(defaultPen, posMiddleRight.X, posMiddleRight.Y + b2, posMiddleBottom.X, posMiddleBottom.Y - b2);
            g.DrawLine(defaultPen, posMiddleLeft.X, posMiddleLeft.Y + b2, posMiddleBottom.X, posMiddleBottom.Y - b2);
        }
    }
}


text:
Q: How to observer child vue finish render I am working on a chat tool using vue single file components.I am facing a problem,root .vue has child .vue and grandchild .vue, I want to observer children's rendering,to get the root div's height,to change scrollbar position,
i used the $nextTick() http://rc.vuejs.org/api/#vm-nextTick,but it cant observer children's render,so ,is there any way can I try? thanks a lot.

A: You can use parent child communication of vue to get to know when you child has rendered. Vue provided following event interface:

*

*Listen to an event using $on(eventName)

*Trigger an event using
$emit(eventName)

A parent component can listen to the events emitted from a child component using v-on directly in the template where the child component is used.
So you can emit a event in your child component's lifecycle hook like following:
mounted () {
  this.$emit('childRendered')
}

In parent component, you can listen to this event or create a method, like following:
this.$on('childRendered', function () {
  // change scrollbar position
})

An example of parent child communication: fiddle

A: This is just for everyone to easily see the workaround that was mentioned by Saurabh in his comment to his answer. I also used the updated lifecycle to wait for the DOM to finish rendering and patching before manipulating it again.
Since updated does not guarantee that all child components have also been re-rendered, use vm.$nextTick inside of updated.
updated: function () {
  this.$nextTick(function () {
    // Code that will run only after the
    // entire view has been re-rendered
  })
}


text:
Q: On Android, any library i can use freely to convert images to 8 bit? I am struggling to find a good library, free to use even commercially, where i could convert an image to 8 bit gray.
I did try using OpenCV, but in the end it add up a lot to the weight of the apk, which is a constraint unfortunatly!
The image file i am trying to convert is a Android.Graphics.Bitmap.
Thanks in advance!


text:
Q: C# - NHibernate unable to cast NHibernate.Collection.Generic.PersistentGenericSet to System.Collections.Generic.IList For some reason, NHibernate is telling me it can't convert NHibernate.Collection.Generic.PersistentGenericSet[Ingredient] to System.Collection.Generic.IList[Ingredient], when I try to get the data from the database. This is a simplfied version of my class mapping/implementation:
public class Product {
    protected Product() { };

    public virtual Name { get; set; }
    public virtual IList<Ingredient> {
        get { return new List<Ingredient>(ingredients).AsReadOnly(); }
        protected set { ingredients = value; }
    }

    private IList<Ingredient> ingredients = new List<Ingredient>();
}

--
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="LanchesAdmin.Core.Domain.Product, LanchesAdmin.Core" table="product" >
        <id name="ID" generator="identity">
            <column name="id" not-null="true" />
        </id>

        <property name="Name" column="name" length="64" not-null="true" />

        <set name="Ingredients" table="ingredient" fetch="join" lazy="true" inverse="true">
            <key column="product_id" />
            <one-to-many class="LanchesAdmin.Core.Domain.Ingredient, LanchesAdmin.Core" />
        </set>
    </class>
</hibernate-mapping>

I've seen several related questions, but they all tell me to use IList, and that's exactly what I'm doing.

A: The reason is that you are using a set. And PersistentGenericSet<T> simply doesn't implement the IList<T> interface.
I think you should simply make the property of type IEnumerable<Ingredient>.
This solves two problems:

*

*You get rid of the error you mentioned

*The API of your class directly communicates that consumers of your class aren't allowed to add ingredients via that property.

A: Do you want a list, bag or set? Your domain model contains a IList<T> but you've mapped it as a <set>.
Either change your mapping to a <bag> or <list> or change your domain model to use a ISet<T>.

A: Either change type of the property to ISet from IList.
Or change mapping from <set> to <list>.


text:
Q: How to stretch in width a WPF user control to its window? I have a Window with my user control and I would like to make usercontrol width equals window width. How to do that?
The user control is a horizontal menu and contains a grid with three columns:
<ColumnDefinition Name="LeftSideMenu" Width="433"/>
<ColumnDefinition Name="Middle" Width="*"/>
<ColumnDefinition Name="RightSideMenu" Width="90"/>

That is the reason I want the window width, to stretch the user control to 100% width, with the second column relative.
EDIT:
I am using a grid, there is the code for Window:
<Window x:Class="TCI.Indexer.UI.Operacao"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles"
    Title=" " MinHeight="550" MinWidth="675" Loaded="Load" ResizeMode="NoResize" WindowStyle="None" WindowStartupLocation="CenterScreen" WindowState="Maximized" Focusable="True"
    x:Name="windowOperacao">
    <Canvas x:Name="canv">
        <Grid>
            <tci:Status x:Name="ucStatus"/> <!-- the control which I want to stretch in width -->
        </Grid>
    </Canvas>
</Window>

A: Is the Canvas crucial in your window? If not, try removing it and keep the Grid as the main panel. Canvas has no size unless specified, while a Grid normally takes up all available space. Inside the Canvas, the Grid will have no available space.

A: You need to make sure your usercontrol hasn't set it's width in the usercontrol's xaml file. Just delete the Width="..." from it and you're good to go!
EDIT: This is the code I tested it with:
SOUserAnswerTest.xaml:
<UserControl x:Class="WpfApplication1.SOAnswerTest"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Name="LeftSideMenu" Width="100"/>
            <ColumnDefinition Name="Middle" Width="*"/>
            <ColumnDefinition Name="RightSideMenu" Width="90"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0">a</TextBlock>
        <TextBlock Grid.Column="1">b</TextBlock>
        <TextBlock Grid.Column="2">c</TextBlock>
    </Grid>
</UserControl>

Window1.xaml:
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="Window1" Height="300" Width="415">
    <Grid>

        <local:SOAnswerTest Grid.Column="0" Grid.Row="5" Grid.ColumnSpan="2"/>
    </Grid>
</Window>

A: Does setting the HorizontalAlignment to Stretch, and the Width to Auto on the user control achieve the desired results?

A: The Canvas in WPF doesn't provide much automatic layout support. I try to steer clear of them for this reason (HorizontalAlignment and VerticalAlignment don't work as expected), but I got your code to work with these minor modifications (binding the Width and Height of the control to the canvas's ActualWidth/ActualHeight).
<Window x:Class="TCI.Indexer.UI.Operacao"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles"
Title=" " MinHeight="550" MinWidth="675" Loaded="Load"
ResizeMode="NoResize" WindowStyle="None" WindowStartupLocation="CenterScreen"
WindowState="Maximized" Focusable="True" x:Name="windowOperacao">

<Canvas x:Name="canv">
    <Grid>
        <tci:Status x:Name="ucStatus" Width="{Binding ElementName=canv
                                                    , Path=ActualWidth}"
                                      Height="{Binding ElementName=canv
                                                    , Path=ActualHeight}"/>
        <!-- the control which I want to stretch in width -->
    </Grid>
</Canvas>

The Canvas is the problem here. If you're not actually utilizing the features the canvas offers in terms of layout or Z-Order "squashing" (think of the flatten command in PhotoShop), I would consider using a control like a Grid instead so you don't end up having to learn the quirks of a control that works differently than you have come to expect with WPF.

A: What container are you adding the UserControl to? Generally when you add controls to a Grid, they will stretch to fill the available space (unless their row/column is constrained to a certain width).

A: Instead use Width and Height in user controls, use MinHeight and MinWidth.
Then you can configure the UC well, and will be able to stretch inside other window.
Well, as Im seeing in WPF Microsoft made a re-thinking about windows properties and behaviors, but so far, I didn't miss anything from olds windows forms, in WPF the controls are there, but in a new point of view.

A: This worked for me.
don't assign any width or height to the UserControl and define row and column definition in the parent window.
<UserControl x:Class="MySampleApp.myUC"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
        >
   <Grid>

    </Grid>
</UserControl>

 <Window xmlns:MySampleApp="clr-namespace:MySampleApp"  x:Class="MySampleApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="auto" Width="auto" MinWidth="1000" >
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <MySampleApp:myUC Grid.Column="0" Grid.Row="0" />
</Grid>


text:
Q: Meaning of "makeshift dias"? What is the meaning of makeshift dias in this passage?

He had invited over a hundred guests, including members of the press. He addressed everyone from a makeshift dias.

A: The correct spelling is "dais".
According to Wikipedia:

A dais is any raised platform located either inside or outside of a room or enclosure, often for dignified occupancy, as at the front of a lecture hall or  sanctuary.

Makeshift means cobbled together out of whatever is available. For example, you can make a table out of an upturned bucket with a flat piece of wood on top.


text:
Q: OP rejected my edit and resubmitted it under their name Recently I stumbled upon an answer which had a small bug (incorrect variable name) pointed out in the comments. To achieve better reader experience, I edited this comment into the answer.
The OP of the answer rejected my edit claiming it was incorrect and subsequently made the exact same edit under their name. I understand they may have made a mistake when reviewing my proposal, but I believe they should have accepted my proposal instead of creating their own.
I'm not too worried about the situation, but misattributions such as this one result in no reputation gains for the editors, which is problematic especially for users with lower reputation trying to get privileges by meaningful activities.
I believe there should be a policy in place encouraging re-acceptance of rejected edits instead of submitting them again from a different account.

A: There's not really anything to do given the situation. It looks like it's a one-off mistake given I don't see anything similar in this user's history.
It looks like OP could not have overriden their own rejection. It would just say "You voted on this suggested edit to your post as noted below. No further action is required." (I'm not even able to override any reviews I did as a moderator.)
And not even a moderator can reverse the edit decision at this point, because of the subsequent edit. You can't suggest the edit again because the improvement was already made to the post. OP caused themselves slightly more work by not accepting the edit and didn't really get anything as a result (e.g. no rep was gained, no progress towards badges was made).

A: Code edits that change anything but non-functional whitespace are generally not appropriate. Changing what code does is contrary to the poster's intent. (What exact rejection reason did you actually get? Because one automated one is, contrary to the poster's intent.) Rejecting it is appropriate & sends proper feedback. Approving it does not accomplish that & suggests that the edit is OK. But it is OK for the poster to make that edit, changing the post question/answer, per the author's (new) intent.
From the Stack Overflow FAQ:
When should I make edits to code?

A: Sometimes people make mistakes, realise they did so and change their minds. It happens. Best move on unless there's some kind of pattern of a user doing this repeatedly.
Note that editing code by anyone other than the OP (original poster) is generally discouraged though. The comment suggesting the change was not made by the OP so you should really just leave things alone. What if the comment was wrong?


text:
Q: "Unable to resolve host "" No address associated with hostname" I have Ios App and put my back end in hosting called arvixe my main problem that if connect my app to internet throw Vodafone Egypt it stop for running and give me this Error
Unable to resolve host "" No address associated with host name
Although my App work correctly if i open it from any Connection provider I have this problem with the same error in my Android version
after i called customer support of arvixe  they said that we didn't block any internet providers in Egypt
and Vodafone customer support said if my Sim card work correctly with fb ,inst ,or YouTube that meaning that no problem from my side

A: You have two solutions:
1. Change the end of your computer to be
8.8.8.8
8.8.4.4
2. If you are using mobile app, install the app from the play store with name DNS changer and use Google DNS; this will solve your issue.


text:
Q: How to describe nested request body in OpenAPI (Swagger) syntax? I need to describe REST (json) api with OpenAPI (Swagger) syntax. I have stuck at the point when I need to describe nested request body. Please suggest how to make it, lets use as example the next nested request body:
{
   "pauses" : [
     {"name" : "PAUSING_AUTO"},
     {"name" : "NO_PAUSE_CRITERIA","Min" : 15},
     {"name" : "PREVENTED_PAUSE","Min" : 5},
     {"name" : "REVERT_TO_RUN"},
     {"name" : "RUNNING"}
    ]
}

A: The following description would do:
pauses:
    type: "array"
    items:
      type: "object"
      required:
        - name
      properties:
        name:
          type: "string"
        Min:
          type: "integer"


text:
Q: Nullable Double Type-Hint I'm writing a neural net, and have the following definition of a Node:
(defrecord Node [^double input-sum ^double last-output])

input-sum is the running sum of it's input; pre-activation. last-output is it's activated value.
My original thought was to create an initial node like (->Node 0 nil). My rational was it didn't make any sense to give the last-output a real value before it had ever been activated.
Unfortunately, creating the above Node yields a NPE; apparently because it's attempting to cast the nil as a double:
(->Node 0 nil)
NullPointerException   clojure.lang.RT.doubleCast (RT.java:1298)

If I remove the type-hint on last-output, it works fine.
I'm trying to get into the habit of type-hinting what I can. Is there a way to provide the type-hint on last-output, but also indicate that nil is an acceptable value?

A: If you really need to typehint with a primitive type, and using object type Double is not an option (like for performance related reason), the common practice (as far as i know) is to create your own custom constructor function:
user> (defrecord Node [^double input-sum ^double last-output])
user.Node

user> (defn make-node [^Double input-sum ^Double last-output]
        (->Node (or input-sum 0) (or last-output 0)))
#'user/make-node

user> (make-node nil 0)
#user.Node{:input-sum 0.0, :last-output 0.0}

user> (make-node 10 nil)
#user.Node{:input-sum 10.0, :last-output 0.0}

user> (make-node 1 2)
#user.Node{:input-sum 1.0, :last-output 2.0}

the approach is used for all the cases, where you need some sophisticated logic for the entity construction.
update
If you really need both a primitive value and the way to distinguish value from "no value", you could use NaN for that:
user> (defn make-node [^Double input-sum ^Double last-output]
        (->Node (or input-sum Double/NaN) (or last-output Double/NaN)))
#'user/make-node

user> (make-node 1 nil)
#user.Node{:input-sum 1.0, :last-output NaN}

so, it is value, and also is the primitive analogue of nil.

A: ^double is type hint for Java primitive double type. Try ^Double.