Q: Python Decorator for printing every line executed by a function I want to, for debugging purposes, print out something pertaining to each and every line executed in a python method.
For example if there was some assignment in the line, i want to print what value was assigned for that variable, and if there was a function call, i want to print out the value returned by the function, etc.
So, for example if i were to use a decorator, applied on function/method such as :
@some_decorator
def testing() :
    a = 10
    b = 20
    c = a + b
    e = test_function()

the function testing when called, should print the following :
a = 10
b = 20
c = 30
e = some_value

Is there some way to achieve this? More fundamentally, i want to know whether i can write a code that can go through some other code line by line, check what type of an instruction it is, etc. Or maybe like we can get a dictionary for finding out all the variables in a class, can i get a dictionary like datastructure for getting every instruction in a function, which is as good a metaprogram can get.
Hence, I am particularly looking a solution using decorators, as I am curious if one can have a decorator that can go through an entire function line by line, and decorate it line by line,
but any and all solutions are welcome.
Thanks in advance.

A: How about something like this? Would this work for you?
Debug Context:
import sys

class debug_context():
    """ Debug context to trace any function calls inside the context """

    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print('Entering Debug Decorated func')
        # Set the trace function to the trace_calls function
        # So all events are now traced
        sys.settrace(self.trace_calls)

    def __exit__(self, *args, **kwargs):
        # Stop tracing all events
        sys.settrace = None

    def trace_calls(self, frame, event, arg):
        # We want to only trace our call to the decorated function
        if event != 'call':
            return
        elif frame.f_code.co_name != self.name:
            return
        # return the trace function to use when you go into that
        # function call
        return self.trace_lines

    def trace_lines(self, frame, event, arg):
        # If you want to print local variables each line
        # keep the check for the event 'line'
        # If you want to print local variables only on return
        # check only for the 'return' event
        if event not in ['line', 'return']:
            return
        co = frame.f_code
        func_name = co.co_name
        line_no = frame.f_lineno
        filename = co.co_filename
        local_vars = frame.f_locals
        print ('  {0} {1} {2} locals: {3}'.format(func_name,
                                                  event,
                                                  line_no,
                                                  local_vars))

Debug Decorator:
def debug_decorator(func):
    """ Debug decorator to call the function within the debug context """
    def decorated_func(*args, **kwargs):
        with debug_context(func.__name__):
            return_value = func(*args, **kwargs)
        return return_value
    return decorated_func

Usage
@debug_decorator
def testing() :
    a = 10
    b = 20
    c = a + b

testing()

Output
###########################################################
#output:
#   Entering Debug Decorated func
#     testing line 44 locals: {}
#     testing line 45 locals: {'a': 10}
#     testing line 46 locals: {'a': 10, 'b': 20}
#     testing return 46 locals: {'a': 10, 'b': 20, 'c': 30}
###########################################################


Q: IF-statement depending on notebook.page.label (gtk#) I am realtively new to C# and am trying to have an action in my toolbar that will act depending on which page in a notebook that I am currently "viewing".
Here is what I am trying to do:
protected void OnRefreshActionActivated (object sender, EventArgs e)
{

    if (mynotebook.CurrentPage.Equals == pgMyNotebookPage)
    {
        lblMsg.Text = "You are viewing the first page";
    }
    else
    {
        lblMsg.Text = "You are viewing the second page";
    }

}

However I can't seem to get this to work. Any pointers?
Regards,
Christian

A: I solved this by creating a messagedialog that showed me the output of mynotebook.CurrentPage. It turned out that each page was assigned a number starting with 0.
This is the working code:
protected void OnRefreshActionActivated (object sender, EventArgs e)
{
    if (nbMain.CurrentPage == 0)
    {
            lblMsg.Text = "You are viewing the first page.";

    }
    else
    {
           lblMsg.Text = "You are viewing the first page.";

    }

}


Q: WebKit gradient from an image Does anyone know if there is a tool that will take an image (.png, .gif, etc) and output the gradient that the image contains?
I really want to recreate this image  in css. Looks like a mix of linear and radial gradients and is beyond my css skills

A: Getting the gradient from a random image is going to be tough for any image processor.  You would probably have better luck by getting the pixel data for the image, finding the top and bottom pixel, pulling the color data out of them, then using these values to create your gradient.

A: Get started with this tool
http://gradients.glrzad.com/ and then read about radial gradients here to make it radial http://hacks.mozilla.org/2009/11/css-gradients-firefox-36/
You can get this far with that tool:
-webkit-gradient(
    linear,
    left bottom,
    left top,
    color-stop(0, rgb(68,214,254)),
    color-stop(0.49, rgb(53,150,230)),
    color-stop(0.51, rgb(123,180,236)),
    color-stop(1, rgb(255,255,255))
)
-moz-linear-gradient(
    center bottom,
    rgb(68,214,254) 0%,
    rgb(53,150,230) 49%,
    rgb(123,180,236) 51%,
    rgb(255,255,255) 100%
)

Then make it radial, mozilla only here
-moz-radial-gradient(right bottom,
   ellipse,
   #44D6FE 0%,
   #3596E6 49%,
   #7BB4EC 51%,
   #FFFFFF 100%) repeat scroll 0 0 transparent

and here is an image of what it looks like

A: Your example is an overlap of two radial gradients. There is a white to mid-blue stop to opaque radial gradient centered above the button with a mid-opacity; on top of simple blue to white radial gradient centered to the bottom right.


Q: Replace input field error message text based on input field label name So I have this account creation form for a company. Here's what it looks like:

I am going to explain first how a feature in this system works.

*

*After company creation, a table will be shown, listing all the companies I created.

*In the Action column of this table, there's an action button that once I click it, I will be logged in into a specific company I chose, acting as the user logged inside that company.

*Inside, there's more like the same layout and I can create a sub-company called "Operator".

*So there's a "Create Operator" button and once clicked, I will be redirected to the same form layout above (except that the "Company Name" label is changed to "Operator Name").

*Alright, so I am using Yii2 php framework and basically, each input field is an attribute in a db table and in my model, there's a function called public function attributeLabels() where each of these attributes are assigned to a specific label.

*For example, first input field's db table attribute name is company_name so inside this function it is assigned as company_name => "Company Name" and this label is passed to the view which is this form. So whenever there are error messages, this label is used.

*Regardless if I am creating a company or operator, the error message is always "Company Name should not be blank". What I need to accomplish is when I create an operator, the error message should be "Operator Name should not be blank."
I hope you get my problem. So I tweaked some javascript/jQuery but I am still having problems.
// For changing Operator Name error message
var operatorNameLabel = $('.field-company-company_name label').attr('for','company-company_name').text();
var companyNameErrorDiv = $(".field-company-company_name p");
var operatorNameMsg = 'Operator Name should not be blank.';

$('#submit-button').click(function() {
    // Change Operator Name error message
    if (operatorNameLabel == "Operator Name") {
        companyNameErrorDiv.html("
Operator Name should not be blank
");
        //companyNameErrorDiv.text(operatorNameMsg);
    }
});

$('#content-offset').click(function () {
    if (operatorNameLabel == "Operator Name") {
        companyNameErrorDiv.html("
Operator Name should not be blank
");
        //companyNameErrorDiv.text(operatorNameMsg);
    }
});

My problem in my current code is that :

*

*when I leave the operator name input field blank then click into a blank space outside the input field, the error message is still "Company Name should not be blank."

*but then when I click back to the input field, that's the time the error message changes to "Operator Name should not be blank."

*What really happens is that when I click at the operator name input field, then single click outside or at any other input fields, the error message remains "Company Name should not be blank.",

*but when I do a second click, the the error message changes.

*There's a problem when I click back to the operator name input field for it keeps on getting back to the "Company Name should not be blank" error message, when clicked.
I hope you get my problem.
EDIT:
Yii2 generated html looks like this:

    Operator Name

        <input type="text" id="company-company_name" class="form-control" name="Company[company_name]" required="required">

Company Name cannot be blank.

A: Try adding required attribute to input element, data-* at label element; css :invalid, :after pseudo element, content property of label to display message when input is invalid.

input:invalid + label:after {
  content: " " attr(data-name) " should not be blank";
  color: red;
}
<input type="text" name="company_name" required />

<input type="text" name="login_name" required />

<input type="email" name="email" required />

<input type="password" name="password" required />

<input type="password" name="password_confirm" required />


Q: Python - Create a Bar Chart of Average Estimated Salary by c_rating, but do a facet_wrap by gender My data set is Churn_Modeling:
RowNumber     CustomerId     Surname    CreditScore     Geography   Gender  Age Tenure    Balance   NumOfProducts   HasCrCard   IsActiveMember  EstimatedSalary Exited
        1       15634602    Hargrave            619       France    Female  42       2          0               1           1                1        101348.88     1
        2       15647311        Hill            608       Spain     Female  41       1   83807.86               1           0                1        112542.58     0
        3       15619304        Onio            502       France    Female  42       8   159660.8               3           1                0        113931.57     1
        4       15701354        Boni            699       France    Female  39       1          0               2           0                0         93826.63     0
        5       15737888    Mitchell            850       Spain     Female  43       2  125510.82               1           1                1          79084.1     0
        6       15574012         Chu            645       Spain     Male    44       8  113755.78               2           1                0        149756.71     1

I created a column called c_rating with the following ranges: (<500 -="very poor",  500-600="poor",  601-660="fair", 661-780="good",  and >= 780 – "excellent") with code:
from plotnine import *
from dfply import *
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import datetime as dt

a_churn = pd.read_csv("Churn_Modeling.csv")

a_churn['c_rating'] = pd.cut(a_churn['CreditScore'], bins=[0,500,600,660,780,1000],labels = ['very poor', 'poor', 'fair', 'good', 'excellent'])

a_churn

I am trying to create a Bar Chart of Average Estimated Salary by c_rating, but do a facet_wrap by gender.
(a_churn >>
  group_by(X.c_rating) >>
  summarise(avg_est_salary = X.EstimatedSalary.mean()) >>
  ggplot(mapping=aes(x=avg_est_salary,y = 'c_rating')) +geom_bar(stat = "identity"))

However I get the error c_rating is not defined.

A: Is this what you are trying to do?
from plotnine import ggplot, aes, geom_bar, facet_wrap
import pandas as pd

a_churn = pd.read_csv('Churn_Modeling.csv')
a_churn['c_rating'] = pd.cut(a_churn['CreditScore'], bins=[0,500,600,660,780,1000],labels = ['very poor', 'poor', 'fair', 'good', 'excellent'])

p = ggplot(a_churn) + aes(x='c_rating', y='EstimatedSalary') + geom_bar(stat='identity', alpha=0.8) + facet_wrap('Gender')
print(p)


Q: Twig impossible to invoke a method on a string variable After updating "twig/twig" to "v2.4.4" I have an error when calling macro function.
Impossible to invoke a method ("widget_prototype") on a string variable (":ERP/timesheets:_form_part.html.twig").

My macro:
{% macro widget_prototype(widget, remove_text) %}
{% if widget.vars.prototype is defined %}
    {% set form = widget.vars.prototype %}
    {% set name = widget.vars.prototype.vars.name %}
{% else %}
    {% set form = widget %}
    {% set name = widget.vars.full_name %}
{% endif %}

Calling macro part:
{% include ':ERP/timesheets:_data_content_supply_from_widget.html.twig' with {form:form, name:name} %}

{% endmacro %}

            <div id="post_supplies"
             data-prototype="{{ _self.widget_prototype(form.supplies, 'remove'|trans({}, 'common'))|escape }}"
             style="margin-bottom: 5px">
            {% for widget in form.supplies.children %}
                {{ _self.widget_prototype(widget, 'remove'|trans({}, 'common')) }}
            {% endfor %}
        </div>

How to correctly call macro? Tried calling without _self and I have the error: Unknown "widget_prototype" function.

A: DarkBee's answer is good, but if your macro is in the same twig file that's calling it then you will still need to import it like so:
{% import _self as my_macros %}
{{ my_macros.widget_prototype(...) }}

Seems a bit counter-intuitive but that's how it is.

A: You need to import the macro, not include it
{% import "my_macro.twig" as my_macro %}
{{ my_macro.function(arg1) }}


Q: Specifying matplotlib scatter size in plot units I would like to specify my scatter dot size not using points or pixels but rather using plot units. Take for instance the following:
import matplotlib.pyplot as plt
x = [0]
y = [0]
plt.scatter(x,y)
plt.show()

This produces a plot as follows:

What if, say, I wanted my marker to have a radius of exactly 0.002 plot units? I understand the s parameter indicates the area of the marker size in points. Is there a way to directly provide it in plot units? If not what is the best way to convert from plot units to points so I can pass it into the s parameter?
I have also seen some other questions which propose using a PatchCollection and simply plotting a circle with a specified radius. I would prefer not to use this approach. I'd like to avoid extensively rewriting existing code and instead use the s parameter along with plt.scatter.
Edit
I tried using the code from this question which apparently allows you to control the marker size based on plot units. However I couldn't really get it to work for my basic case:
import matplotlib.pyplot as plt
import numpy as np

class scatter():
    def __init__(self,x,y,ax,size=1,**kwargs):
        self.n = len(x)
        self.ax = ax
        self.ax.figure.canvas.draw()
        self.size_data=size
        self.size = size
        self.sc = ax.scatter(x,y,s=self.size,**kwargs)
        self._resize()
        self.cid = ax.figure.canvas.mpl_connect('draw_event', self._resize)

    def _resize(self,event=None):
        ppd=72./self.ax.figure.dpi
        trans = self.ax.transData.transform
        s =  ((trans((1,self.size_data))-trans((0,0)))*ppd)[1]
        if s != self.size:
            self.sc.set_sizes(s**2*np.ones(self.n))
            self.size = s
            self._redraw_later()

    def _redraw_later(self):
        self.timer = self.ax.figure.canvas.new_timer(interval=10)
        self.timer.single_shot = True
        self.timer.add_callback(lambda : self.ax.figure.canvas.draw_idle())
        self.timer.start()

x = [0]
y = [0]
fig = plt.figure()
ax = fig.gca()
size = 3.14*0.002**2
scatter(x, y, ax, size = 0.002, edgecolors = 'black')
ax.set_ylim(-0.004, 0.004)
ax.set_xlim(-0.004, 0.004)
ax.scatter(x,y)
ax.grid()
plt.show()

The above outputs the following figure:

Which does not look like it has a size of 0.002 as I indicated in scatter(x, y, ax, size = 0.002, edgecolors = 'black'). I'm not sure what I'm doing wrong here.


Q: Details of socket using socket ID This question may sound basic one . Are there any functions in c or Java where I can get the socket details like , port , address , buffer size using only socket identifier ?

A: Some minimal information available with me is posted below.
I don't know much of Java. But as far as 'C' is concerned, you can use the getsockopt function to get the buffer sizes (send buffer and recv buffer) of the socket.
It appears getsockname helps you in getting the ip & port to which the socket is bound to.

A: In c in the function accept:
csock = accept(sock, (struct sockaddr*)&csin, &recsize);

*

*sock is the socket server(int)

*csock is the socket client (int)

*recsize is the size

*csin is a struct with client's details

*

*csin.sin_addr is the client's address

*csin.sin_port is the client's port

From a socket ID try this:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>

f()
{
   int s;
   struct sockaddr_in sa;
   int sa_len;
   .
   .
   .
      /* We must put the length in a variable.              */
   sa_len = sizeof(sa);
      /* Ask getsockname to fill in this socket's local     */
      /* address.                                           */
   if (getsockname(s, &sa, &sa_len) == -1) {
      perror("getsockname() failed");
      return -1;
   }

  /* Print it. The IP address is often zero beacuase    */
  /* sockets are seldom bound to a specific local       */
  /* interface.                                         */
   printf("Local IP address is: %s\n", inet_ntoa(sa.sin_add r));
   printf("Local port is: %d\n", (int) ntohs(sa.sin_port));
   .
   .
   .
}


Q: How to enable colors with Win32-OpenSSH and Putty? Summary
There seems to be a bug in Win32-OpenSSH that prevents colors to be shown in certain terminal emulators such as PuTTY and mintty.
Win32-OpenSSH seems to replace the color escape sequence "\033[32m\033[40mtest" by "\033[0;39;24;27;32;40;mtest" and the problem seems to be the last semicolon before the m. Removing this semicolon, the colors are displayed correctly.
Details
I installed Win32-OpenSSH-Win64 (version 0.0.24.0) according to https://github.com/PowerShell/Win32-OpenSSH/wiki/Install-Win32-OpenSSH.
I set
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\OpenSSH\DefaultShell="C:\Program Files\GIT\bin\bash.exe"

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\OpenSSH\DefaultShellCommandOption="-c"

Logging into my machine with
ssh localhost

I do not get color output with PUTTY, and not with "Git Bash for Windows" but I do get colors with the native "cmd.exe" and with "Bash on Ubuntu on Subsystem for Linux" connecting to the same local server.
The problem seems to be related to unusual escape sequences. Logging all session output in PuTTY shows escape sequences that are terminated by a semicolon: "\033[0;39;24;27;32;40;mtest" and PUTTY does not seem to be able to handle them. Escape sequences without the final semicolon, e.g., "\033[0;39;24;27;32;40mtest" are handled correctly by PUTTY.
Those unusal escape sequences seem to be introduced by Win32-OpenSSH. In contrast, the Bitvise SSH Server produces the escape sequence "\033[32m\033[40mtest".


Q: How can I add additional columns during BULK INSERT without modifying source file I have a BULK INSERT into a table but I need to add data that is not in my csv for the last column in each row of the table.
For example, if my csv file contains 10 columns but the database table contains 11 columns, how can I add data for the last column? Modifying the csv file itself is not an option
Is this possible with BULK INSERT?
Here is my script:
BULK INSERT [Data_GPS].[dbo].[Data_z]
    FROM 'C:\TEMP\SQL\Bulk insert\dane.csv'
    WITH
    (
    FIRSTROW = 2,
    FIELDTERMINATOR = ';',
    ROWTERMINATOR = '\n',
    ERRORFILE = 'C:\TEMP\SQL\Bulk insert\errors.txt',
    TABLOCK
    )

A: Sure.  Just use OPENROWSET(BULK ...) instead of BULK INSERT and you can add whatever extra columns you want. EG
select *
from openrowset(bulk 'C:\TEMP\dane.csv', format='CSV')


Q: Get string between two sets of characters in shell I pipe the following string "version": "1.0.0", to sed and I'm trying to get 1.0.0 out of it. I want to get it by the rule: get string between : " and ",.
I've been trying the following:
sed -e '/:\ \"/,/\ ",/p'
sed -e 's/:\ \"\(.*\)\",/\1/'

The first one does nothing and the last one returns "version"1.0.0, which is close, but no cigar. What am I missing?

A: You need to match complete input by using .* on either side of your search pattern to be able to replace full line with just the captured group's back-reference.
This sed should work:
s='"version": "1.0.0",'

sed 's/.*: "\([^"]*\)",.*/\1/' <<< "$s"
1.0.0

Or even this one:
sed 's/.*: "\(.*\)",.*/\1/' <<< "$s"
1.0.0

A: Another approach, using grep with lookahead/lookbehind:
$ grep -oP '(?<=: ")[^"]*(?=")' <<< '"version": "1.0.0",'
1.0.0

or shorter, using \K to exclude : " from the matched string:
$ grep -oP ': "\K[^"]+' <<< '"version": "1.0.0",'
1.0.0


Q: Storing Documents on Azure with custom metadata i am trying to find the best way to implement a small site allowing the user to upload a file and then search on it.
i used azure search with blob storage.
the file is stored on the blob storage and is then gets indexed by azure search indexer - so far so good.
the problem is that i would like to add to each document some custom data like file id and other business data, this data is not part of the document. is there a way to achieve this?
some one, suggested i use cosmos db, though i am not sure its the best way to go when it comes to documents.
Thanks

A: If you would like to keep using blob storage, you can store metadata with the blobs - just add custom metadata to your blobs, add corresponding fields to the search index, and the blob indexer will pick up the metadata.


Q: How to enable SSL usage when using local XML autodiscover file? I use the Redemption library and I encountered a problem I can not solve by myself.
In my project, I use a local XML file to login to the Exchange server (Autodiscover service is disabled on the server and can not be enabled). For this purpose, I create an Outlook Autodiscover "PreferLocalXml" registry key value and a domain name value defining the path to the local XML file. Redemption works correctly, but for some reason it does not use SSL when sending requests to the server.
Is it possible to force SSL usage in this case? However, using Autodiscover (without local XML file) works fine (SSL is used). Thank you in advance for your help.
I tried setting RDOSession.ConnectEncryptData to true, but it did not work.

A: But PreferLocalXml is supposed to point to a local file, not a web server, so SSL would not apply - the file is accesses using the file API.


Q: Trigger to run TeamCity based on file existence I want to run TeamCity processes based on file existance.
I have two TeamCity processes (Dev and Prod):

*

*Dev should be run if there is DevParam file in repo (or in specified location).

*Prod should be run if there is ProdParam file.

I want to run exactly one process after each push to repository.
This files will be added and removed like:

*

*[0] Repository has DevParam file

*[1] Pushed, there is still DevParam file -> Dev process should be run

*[2] Pushed, removed DevParam file and added ProdParam -> Prod process should be run

*[3] Pushed, there is still ProdParam -> Prod should be run

I tried to create Trigger with rules, but I failed (rule like +:DevParam run also on file removal).
Git recognizes addind and removing this files as Moving with Rename, so it may be relevant.

A: file management is not a normal process. I strongly advise you to use the branch flow. For your example, use develop branch(DevParam) for an all your developers and master branch for a prod
Try to use the follows advice.
The developers are coding in the dev branch. Each developer working only this branch.
You should create the build configuration with the trigger to your dev branch. After each new commit, the configuration will be triggered.
If you decided that the code in the dev branch is ready to production, you just merged all to the master. And now you can also trigger the same configuration only for a master branch.
For more information about gitflow-workflow read this


Q: Intel Compiler /QxCORE-AVX2 switch and compatibility with AMD Excavator/RyZen For some unknown reason Intel decided to does not support AVX2 via typical /arch: option. /arch: recognizes only following instructions IA32,SSE,SSE2,SSE3,AVX. So if you want to compile for AVX2 you are basically forced to activate /QxCORE-AVX2 switch. The problem with this option is that it injects check code. That code at runtime checks if your cpu is compatible with selected intructions. If CPU is not compatible then this message pops-up.
Please verify that both the operating system and the processor support Intel(R)
MOVBE, F16C, FMA, BMI, LZCNT and AVX2 instructions.
Now I'm worried that the same message may pop-up on AMD Excavator and RyZen CPU due to not being GenuineIntel. Unfortunately I do not have access to any AMD cpu so I can't check that on real cpu. To make your life easier I've compiled this simple code with activated /QxCORE-AVX2 option.
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    double a, b, c;
    a = 3.0;
    b = 2.0;
    c = 1.0;

    a = a*b + c;

    printf("a=%1.1f",a);

    return 0;
}

and here is decompiled asm code: http://codepad.org/KL4Vq978
My question to people who understand asm code is do you see anything what may block execution of this code on latest AMD cpus? If yes will this http://www.softpedia.com/get/Programming/Patchers/Intel-Compiler-Patcher.shtml help?

A: It turns out that /arch:CORE-AVX2 is recognized and compiled executable contains FMA instructions! I really do not understand why this option is not listed in Visual Studio and in ICL /help ?!?
Dropbox menu in Visual Studio (NO AVX2!)
http://i.cubeupload.com/c1xidV.png
ICL /help
http://i.cubeupload.com/y2Cre6.png

A: The Ryzen supports these instruction sets, but the code will not run on AMD processors because it checks if the processor is "GenuineIntel". There has been a long discussion and legal battle about this issue. See http://www.agner.org/optimize/blog/read.php?i=49


Q: Is there a jQuery event that fires when all effects are done running The title explains the question, otherwise is there way to call a function when all the effects on a page are done running?

A: You could nest your animations like this
$('#Div1').slideDown('fast', function(){
   $('#Div2').slideUp('fast');
});

And do them sequentially...
You could also do something like this:
var animations = 0;
checkAnimation(1);
$('#Div1').slideDown('fast', function(){
   checkAnimation(-1);
});

checkAnimation(count){
   animations += count;
   if(count == 0)
      //animations complete
   }
   else {
       //still animating
   }
}

Hope this helps.

A: You might be able to make use of .queue to get the functionality you are after.  If the length of the queue was 0 you would know that all animations on the object are finished.
Documentation


Q: Solve the complex system : Find $x$ and $y$ where :
\begin{cases}
ix-(1+i)y=3 \\
(2+i)x+iy=4 & \text{}
\end{cases}
I have used the rectangular form of complex number by expressing $x=(a,b)$ and $y=(c,d)$ and reaching in a system with 4 equations and 4 unknowns in this form :
\begin{cases}
-b=3+c+-d \\
a=d+c \\
2a=4+d+c \\
2b=-c-a \\
\end{cases}
where we get the right answer $x=(\frac{7}{3}, \frac{-4}{3})$ and $y=(\frac{1}{3},2)$
I would like to know if there is any simpler approach with some more clever manipulations cause my solving method is a bit long.

A: Just express $x$ as function of $y$ from both equations.
Then set the two expressions to be equal. Then find $y$.
By using this approach I get:
$y=1/3 + 2i$
$x=(7-4i)/3$
So it seems your result is correct.

A: Use the Cramer rule, evaluating the $2\times2$ determinants in complex numbers.
$$\Delta=\left|\begin{array}&i&-(1+i)\\2+i&i\end{array}\right|=3i$$
and so on.


Q: Angular + TypeScript + AMD = duplication? I've been developing in Angular for a few months and am now investigating whether it's worth moving to TypeScript for my development. One of the issues I'm having is the duplication when using external modules and injecting services. For example I have this (simplified) code:
///<reference path="../../../../typings/tsd.d.ts" />

// imports for strong typing
import audioModel = require('app/plugins/audio/audio.model');

export class AudioController {

    public model: audioModel;

    static $inject = ['$scope', '$q', 'AudioModel'];
    constructor(protected $scope, protected $q, protected AudioModel:audioModel) {
        this.model = new AudioModel();
    }

}

The AudioModel is an Angular factory defined in the external module 'audio.model.ts', so it seems to me that I'm injecting it twice - once using Angular, and again using the TypeScript import to get strong typing.
Is there a better way to both use Angular dependency injection and strong typing in an AMD project?

A:
Is there a better way to both use Angular dependency injection and strong typing in an AMD project

This was an issue with angular 1.x dependency injection. The Angular module system was independent of the traditional Browser module systems in existance (e.g. AMD).
So you do need to import it twice. Once the Type, next the DI.


Q: How to integrate a maven project with parent pom as module? I'd like to use a parent maven project/aggregator to build my project and a dependency which I have in my source root as git submodule, e.g.
aggregator pom.xml
 - dependency pom.xml
 - project pom.xml

I naively adapted this layout from GNU C/C++ projects, like coreutils which simply checkout dependencies as submodules and updated them to a compatible commit together with the project state/commit.
The thing with maven is that there's a parent directive in pom.xml of the dependency and removing it would definitely require to modify the dependency which is not the intention of this setup. So, the same question asked a very different way is: Is a parent directive in a pom definitely preventing a project from being used as a maven module?. Can the warning Some problems were encountered while building the effective model or [dependency] 'parent.relativePath' of POM [dependency] points at [aggreator] instead of org.sonatype.oss:oss-parent, please verify your project structure be ignored?
I'm aware about the fact that this isn't the intended workflow of maven (with the local cache in mind) and that it could be easily achieved by making dependency not a maven module, but just a git submodule and write a two-line build script invoking mvn in the source root and the dependency subdirectory.
I tried using the reactor plugin, but it simply doesn't build anything which isn't included in module declaration (both the make and the make-dependents target) (error Couldn't find project [dependency] in reactor; make sure you specified the correct group:artifactId).
I'm using maven 3.3.1.

A:
Is a parent directive in a pom definitely preventing a project from being used as a maven module

No. In the end a parent is simply used to inherit stuff and it can refer to any parent. In a multimodule project parents and children point to each other (child refers to a parent, parent defines child as a module).
On the other hand: you might wonder why it is a problem that any project is used as a module. The writer of the aggregator pom probably had a reason for it.

Can the warning Some problems were encountered while building the effective model or [dependency] 'parent.relativePath' of POM [dependency] points at [aggreator] instead of org.sonatype.oss:oss-parent, please verify your project structure be ignored?

It shouldn't be ignored, it must be set correctly, i.e. use <relativePath></relativePath> (empty String) in the parent.


Q: "... the day you find out why." The Apocryphal Twain suggests that the oft-quoted aphorism :

The two most important days of your life are the day you were born and the day you find out why.

is not, actually, attributable to Mark Twain, though, indeed, it does sound very much like many other of his pithy sayings. The true source of the saying is not my question, however. I am interested in what I think to be the clever design of it.
One could say that 'you were born' is in elipsis and that the statement 'the day you find out why' depends on the notional understanding of the words not present.

The two most important days of your life are the day you were born and the day you find out why you were born.

But the whole of the saying strikes deeper than that, I would say.
'... the day you find out why' is  not just about finding out why I, in particular, was born, It is about finding out why anyone is born. It is about finding out why anything happens.
It is about finding out why.
That is to say, it is about the whole of why.
As children can ask, why such-and-such. And then they pick up on the answer and ask 'Why so-and-so'. And why the next ... and the next.
They want to know the whole of why.
So my question is - what part of speech is 'why' when it means the whole of why ?

The day I found out why.

When the word 'why' means 'the reason that everything is the way it is' ... then what part of speech is it ?

A:
The two most important days of your life are the day you were born and the day you find out why.

This should be understood as
The two most important days of your life are {the day [that] you were born} and {the day [that] you find out why [you were born]}.
You ask

When the word 'why' means 'the reason that everything is the way it is' ... then what part of speech is it?

but this has a problem: it never means that. The following will demonstrate that the nearest it could mean (but does not) is "...the day you find out the answer to the why/the enigma of birth."
Why is either

*

*an adverb = for what reason:

1883   D. C. Murray Hearts ix   Why don't you learn Italian?
Or

*an interjection

1893   M. Pemberton Iron Pirate i   Mary looked up suddenly..and said,..‘Why, I believe I've been asleep!’
Or

*a noun = reason:

1832   R. Southey Ess. II. 415   The reader who may not be..acquainted with the when, and the how, and the why of the surrender.
or

*(OED) A question beginning with (or consisting of) the word ‘why?’; a question as to the reason of something; hence, a problem, an enigma.

1866   A. Steinmetz Weathercasts 20   She could supply the ready ‘because’ to many of the old philosopher's ‘whys’.
I can find no example of the noun “why” appearing in the singular without a determiner, and this indicates that the noun "why" is countable. Your example has no determiner: it appears to be an adverb.
If it did mean “the question of why we were born” or “the question of why anyone is born, then it would be a noun and it would be
The two most important days of your life are {the day [that] you were born} and the day [that] you find out the why.


Q: SQL Server queries xls file worked yesterday(I swear), now refuses to. 0.o Hey all, the following select statement used to correctly query an Excel spreadsheet on a 64bit SQL Server 2008 R2, and now provides me with an error.
SELECT
     MPNCode, Supplier, Stock , Price, Manufacturer, [Description]
FROM
     OPENROWSET('Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0 Xml;Database=C:\inetpub\wwwroot\nCompass\Products\Import\SupplierProducts.xls;HDR=YES',
                'SELECT * FROM [Sheet1$]') WHERE MPNCode IS NOT NULL

The error I get is.

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked
  server "(null)" returned message
  "Unspecified error".
  Msg 7303, Level 16, State 1, Line 1
  Cannot initialize the data source object of OLE DB provider
  "Microsoft.ACE.OLEDB.12.0" for linked
  server "(null)".

I've tried restarting everything and googled the thing to death - somehow something has happened that is preventing this from working.
The file-path/file-name is correct because when I change the path I get a different error message.
Ad-hoc connections are enabled from the surface manager - after this I'm stumped at what the issue could be.
Any help will be very much appreciated.

A: Is the linked spreadsheet opened on the desktop?  What happens if you create a new sheet in the same folder and try to open it instead?

A: I think SQL Server needs to access to TEMP folders to copy or create some files.
If the folder does not exist or ther SQL Service account does not have enough permission to access the folders, you'll get the exception.
Run Procmon.exe on the server and execute the query again. You can see what's happening and where the SQL Server wants to access.


Q: package ‘RMySQL’ is available as a source package but not as a binary I am receiving the above error when I try to install this package. Reading this question install RMySQL for Mac I read the install guide.
Here's what is said:
During installation, RMySQL looks for the MySQL headers and libraries
in the system directories.  If these are not installed in system-wide
directories (or if you want to use an alternate MySQL distribution),
you may specify which MySQL directory(ies) to use through one of the
following:

   1. The shell variables PKG_CPPFLAGS and PKG_LIBS (using Bourne shell)

       export PKG_CPPFLAGS="-I<include-dir>"
       export PKG_LIBS="-L<library-dir> -lmysqlclient"

       For instance, on some 64 systems (e.g., Linux) you may need to set

       export PKG_CPPFALGS="-I/usr/include/mysql"
       export PKG_LIBS="-L/usr/lib64/mysql -lmysqlclient"

I have browsed my computer, I don't believe that those directories exist.
I have installed XAMPP previously on my Mac and wondered if the directories needed are in there somewhere since XAMPP uses MySQL?
Can I just download the directories somewhere?
How can I find if they are already on my computer?
export PKG_CPPFALGS="-I/usr/include/mysql"
export PKG_LIBS="-L/usr/lib64/mysql -lmysqlclient"

I'm at a loss for what to do next?

A: If you don't mind installing another MySQL server via Homebrew, I have posted the complete solution in another thread: Installing RMySQL in mavericks

But in your case, I do find those directories in XAMPP that contain the same necessary MySQL header and library files as those installed via Homebrew.
So you can set the environment variables and build in the Terminal way:
% export PKG_CPPFALGS="-I/Applications/XAMPP/xamppfiles/include"
% export PKG_LIBS="-L/Applications/XAMPP/xamppfiles/lib -lmysqlclient"
## RMySQL_x.x-x.tar is the source package you have manually downloaded
% R CMD INSTALL RMySQL_x.x-x.tar

or in the RStudio way:
> Sys.setenv(PKG_CPPFLAGS = "-I/Applications/XAMPP/xamppfiles/include")
> Sys.setenv(PKG_LIBS = "-L/Applications/XAMPP/xamppfiles/lib -lmysqlclient")
## It will automatically download the source package in the remote repo
> install.packages("RMySQL", type = "source")


Q: How to chain api calls with AngularJS I'm new to angualrJS and web development in general. I have a controller named FavoritesCtrl that makes an api call and returns an object.
My controller looks like this:
controllers.controller('FavoritesCtrl', function($scope, $http) {
  $http.jsonp('https://api...=JSON_CALLBACK').then(function (scooby){
    $scope.list=scooby.data;
  });
});

I access the returned data in my html with this:

product_id: {{ favorite.product_id }}

I need to send that {{ favorite.product.id  }} back as a parameter in another api call so I can generate an affiliate link, but I don't know the most angular way to do it.
Should I attempt to send the second call in the FavoritesCtrl or would it make sense to put it in a new controller?
I can get the proper affiliate link back with something like this:
controllers.controller('FavoritesCtrl', function($scope, $http) {
  $http.jsonp('https://api...=JSON_CALLBACK').then(function (scooby){
    $scope.list=scooby.data;

    var length = scooby.data.favorites.length;
    var i;

    for (i=0;i<length;i+=1){
      var getProductId = scooby.data.favorites[i].product_id;
      $http.jsonp('https://api...+getProductId+'&callback=JSON_CALLBACK').then(function (fred){
      console.log(fred.data.link);
    });
  });
});

But I can't figure out a good way to display this on my page with the associated item. Any suggestions will be greatly appreciated.
Thank You!

A: You're on the right track.  I think in your for loop in the controller, just put $scope.list.favorites[i].affiliateLink = [whatever the returned value of the specific affiliate link should be];
Then in the HTML, it would just interpolate as {{favorite.affiliateLink}}

A: You probably want to use ng-click and this will call another method in your controller:

{{favorite.product_id}}

in your controller :
$scope.doSomething = function (prodId) {
  // Do whatever you want here
};

A: You can accomplish this in a more elegant way using a tool that you already have - promises. Promises are there to help you chain events like this.
A simple example would be:
get('story.json').then(function(response) {
  return JSON.parse(response);
}).then(function(response) {
  console.log("Yey JSON!", response);
});

A very good introduction to promises can be found here [1].
[1] http://www.html5rocks.com/en/tutorials/es6/promises/


Q: Log with Python logging in Robot Framework I use robot framework 3.0 under Python 2.7.8. Robot framework's documentation (http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#programmatic-logging-apis) states that

In addition to the new public logging API, Robot Framework offers a built-in support to Python's standard logging module. This works so that all messages that are received by the root logger of the module are automatically propagated to Robot Framework's log file.

I made a short library file to test this:
from logging import debug, error, info, warn

def try_logging():
    info("This is merely a humble info message.")
    debug("Most users never saw me.")
    warn("I warn you about something.")
    error("Something bad happened.")

My test case is:
*** Test Cases ***
Logtest
    Try logging

When I run it it is a PASSED case, but nothing logged into the HTML log. The test execution log has the suit and the case and the keyword as it should but when I expand them nothing is logged but the "Start / End / Elapsed" line.
How could I forward the Python logger messages to Robot? As you can see the so called automatic propagation is not working automatically. My goal is to write a library that can be run with or without Robot Fw.
Ty for your help in advance.

A: After hours of code digging I managed to find the answer. I think it is worth sharing as it may be help you if you have some similar issue.
In my case I had some unused libraries imported. One of them was a class that was instantiated when Robot Framework imported the library file. This object had some logger settings that messed up the defaults, that is why I got no result in the robot log.
Without it I got the expected results and automatic propagation worked fine.


Q: How to detect if a JS variable is undefined? // mystring contains dynamic text. Sometimes can be
// null
var a = mystring.split(" ");
var proc = a[0] + " " + a[1];

If a does not contain text, after split proc is undefined. If I try to assing its value to a textbox the result is "undefined":
mytextbox.val(proc);

So I need a way to make that proc has always a value, at least an empty string.

A: You can just use
(mystring || " ")

which will evaluate to mystring if it is not null, or " " if it is.
Or, you can just put an if statement around the whole thing:
if (mystring != null) {
    // stuff
} else {
    var proc = "";
}

A: var proc = "";
if (mystring !== null) { // omit this if you're sure it's a string
    var a = mystring.split(" ");
    if (a.length > 1) {
        proc = a[0] + " " + a[1];
    }
}

I'm quite sure your proc is not undefined, but the string " undefined".


Q: .NET application closes without error on using library methods I have a C++ DLL Library. I'm testing the DLL with a C# Project with NET Framework 4.0. In the C++ DLL I'm using some libraries, like POCO, Boost, ODBC, SQLite, SOCI...
It was doing great until I decided to replace the SOCI interface with the POCO one to reduce the number of libraries loaded in the library.
I compiled the PocoData, PocoDataODBC and added them, together with the headers, into the project. The project compiles OK, creates the DLL, and the DLL passes the Dependency Walker tests.
But something strange happens when using the DLL from the .NET Project. The app just closes when executing the DLL methods that contains the Poco::Data part to connect with the database.
There is no exception or error thrown. Not even "application just crashed" from windows. It just stop running and the Visual Studio returns to normal just like if it ended correctly.
I isolated the error and it's enought with any use or call inside the PocoData library to do this error. I can use the library until it tries to use a method that has any call to this. For example:
Session session("ODBC", conn);

Or even this alone:
Poco::Data::RecordSet rs();

So every time the C# calls a method that contains anything from the Poco::Data in the DLL it fails.
Any idea what can be happening?

Windows events log something when the app makes the error, I don't know if it's relevant. It raises two events, the first one is a system hour change between same value (strange), type: Kernel-General.
The second one (about 10 seconds later) is Service Control Manager level Information:

Service Windows Error Reporting Service entered in running state.


Q: explicit formulae of heat kernel on graphs I have just discovered this article about heat kernels on graphs. It has been written by a respected theoretical physicist, but seemingly never made it into a peer-reviewed journal. On the other hand, the paper offers formulae of some interest, given how little is known about discrete heat kernels even in simple graph configurations; but it has virtually never been quoted. Is anybody aware of this paper? Are its results known to be correct/uncorrect?


Q: Code executes differently on Windows and Android I'm coding a simple game called Jotto. A player tries to guess a secret five letter word; each letter is unique. After each 5-letter guess word you're told how many letters in the guess are also in the secret word. It's my first attempt at cross-platform development with Delphi. I've developed Windows apps in Delphi, and a little bit for Android with Flutter.
All the code executes as expected on Windows (32 bit), but not on Android (64 bit, SDK 25.2.5). No exceptions are raised, but the calculated number of correct guesses each turn are incorrect and unpredictable (i.e., the calculated result of total below is what's off). Running the code through the debugger shows local variables are incorrect sometimes, too.
Here are the relevant functions:
function TJotto.OccurrencesOfChar(const aWord, aChar: string): integer;
var
  i: integer;
begin
  result := 0;
  for i := 1 to Length(aWord) do
    if aWord[i] = aChar then
      inc(result);
end;

and
function TJotto.MakeGuess(aGuessWord: string): string;
var
  i: integer;
  total: integer;
  wordToDisplay: string;
begin
  total := 0; // number of matches
  wordToDisplay := aGuessWord;
  // save copy of guess before deleting duplicate letters
  // because guess will be displayed
  // did user solve puzzle?
  if aGuessWord = FSecretWord then
    Exit('You did it! The word was ' + aGuessWord);
  // make sure all letters in aGuessWord are different
  // otherwise a guess like 'vexed' will say an E is present in FSecretWord twice
  for i := 5 downto 1 do
    if OccurrencesOfChar(aGuessWord, aGuessWord[i]) > 1 then
      Delete(aGuessWord, i, 1);
  // go through each letter in aGuessWord to see if it's in FSecretWord
  // keep a running total number of matches
  for i := 1 to Length(aGuessWord) do
    total := total + OccurrencesOfChar(FSecretWord, aGuessWord[i]);

  result := wordToDisplay + #9 + total.ToString;
end;

A: Note: Previous to Delphi 10.4 the mobile compilers used by default 0-based indexing for strings. See Zero-based strings.
Use the Low() and High() intrinsic functions to iterate strings.
The irregularities you are seeing is because of indexing outside of the boundries of the string. When debugging, use overflow and range checking on to detect these kind of errors.
Your code will look like this:
function TJotto.OccurrencesOfChar(const aWord, aChar: string): integer;
var
  i: integer;
begin
  result := 0;
  for i := Low(aWord) to High(aWord) do
    if aWord[i] = aChar then
      inc(result);
end;

and
function TJotto.MakeGuess(aGuessWord: string): string;
var
  i: integer;
  total: integer;
  wordToDisplay: string;
begin
  total := 0; // number of matches
  wordToDisplay := aGuessWord;
  // save copy of guess before deleting duplicate letters
  // because guess will be displayed
  // did user solve puzzle?
  if aGuessWord = FSecretWord then
    Exit('You did it! The word was ' + aGuessWord);
  // make sure all letters in aGuessWord are different
  // otherwise a guess like 'vexed' will say an E is present in FSecretWord twice
  for i := High(aGuessWord) downto Low(aGuessWord) do
    if OccurrencesOfChar(aGuessWord, aGuessWord[i]) > 1 then
      Delete(aGuessWord, i+1-Low(aGuessWord), 1); // Delete uses one-based array indexing even in platforms where the strings are zero-based.
  // go through each letter in aGuessWord to see if it's in FSecretWord
  // keep a running total number of matches
  for i := Low(aGuessWord) to High(aGuessWord) do
    total := total + OccurrencesOfChar(FSecretWord, aGuessWord[i]);

  result := wordToDisplay + #9 + total.ToString;
end;


Q: Knockout.js How should I add computed value to observaleArray? I need to add to observableArray computed values, my current code is look like this:
   self.prices = ko.observableArray();
   .....
   var pax = $("select#ticketsnumber option:selected").val();
        var irt;
        if ($("input[name='isrt']").is(":checked")) {
            irt = 1;
        } else {
            irt = 0;
        }
    $.each(self.prices(), function (price) {
            price.FinalPrice = ko.computed(function() {
               return prices.Price * irt * parseInt(pax);
        });
    });

But I do not have any idea how should I call binding of this computed value (currently this way - ) as well as this just seemed like computed value has not been added - binding result show 0.
Data model:
  public class PriceItem
        {
            ...
            public string Price { get; set; }
           ...
            public int FinalPrice { get; set; }
        }

This is the way how I retrieve data to self.prices:
self.getprices = function () {
            var destinationtypefrom = $("select#optionsfrom option:selected").attr("name");
            var destinationtypeto = $("select#optionsto option:selected").attr("name");
            var fromcode = $("select#optionsfrom").val();
            var tocode = $("select#optionsto").val();
            var json = { desttypefrom: destinationtypefrom, desttypeto: destinationtypeto, codefrom: fromcode, codeto: tocode, 'DepartureDate': $("#departure").val(), 'ReturnDate': $("#return").val() };
            $.ajax({
                url: "/Home/GetFlights",
                data: json,
                type: "post",
                cache: false,
                success: function (result) {
                    if (result.Error == null) {
                        self.prices(result);
                        ko.mapping.fromJS(result, {}, self.prices);
                    } else {
                        $("#modalerror").on("show.bs.modal", function () {
                            var modal = $(this);
                            modal.find("#errormsg").text(result.Error);
                        });
                    }
                },
                error: function (xhr) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });
        }

A: The main problem is that your $.each is wrong by assuming the first argument to be the actual element in the prices array. In fact, the first argument is the index, the second argument is the actual price you want to augment.
Also, you seem to have a typo in the computed function calculation, it's price.Price instead of prices.Price.
Try this:
$.each(self.prices(), function (index, price) {
    price.FinalPrice = ko.computed(function() {
        return price.Price * irt * parseInt(pax);
    });
});

And in your HTML, something like:

See Fiddle


Q: Unable to uninstall Chromium from Ubuntu I am unable to uninstall Chromium browser from Ubuntu 18.04.3.
I tried to uninstall it through Ubuntu software and also through commands but didn't work in my case
Command I used:
sudo apt-get remove chromium --purge

Output:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'chromium' is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.

A: The app name is wrong. It is chromium-browser
sudo apt remove chromium-browser --purge


Q: Proof Fermat's Little Theorem I'm trying to follow the proof for here https://primes.utm.edu/notes/proofs/FermatsLittleTheorem.html?fbclid=IwAR2WAws38n6M--Dx4cOWc8QToKG9sJf1JL9V_9MDATTG4UIx2yNyvpF2M7Q
I'm a bit confused by the part
Suppose that ra and sa are the same modulo p, then we have $r = s (mod p)$, so the p-1 multiples of a above are distinct and nonzero;
why do we have $r = s\ (mod\ p)$ ?

A: $p\mid ra-sa=(r-s)a$. Since $p$ is prime and by hypothesis $p\nmid a$, it must hold $p\mid r-s$.

A: If $p$ is a prime number then $\mathbb{Z}_p$ has a cancellation property, you can see the Saucy's proof. Although, in general it's not true, for example in $\mathbb{Z}_6$: $2\cdot3 = 2\cdot0 =0$ but $3 \not =0$.


Q: Swift code that will print a string of all the characters of a new word typed in a UITextView as they are being typed I need help with swift code or function that will run in the body of UITextView function textViewDidChange that will print a string of all the letters of a new Word     as  they are being typed in a UITextView control. So if I have a UITextView control on my user interface named txtTextView and it has no text in it when the application starts running if I then type letter "o" then letter "o" will be printed in the console out put screen. After I have typed "or" then "or" will be printed. After I have typed "orange" then "orange" will be printed. If after typing orange I press space bar and start typing "ma" then "ma" will be printed and after I have typed "orange mango" then "mango" will be printed. Hope I have conveyed the idea. Basically I would like the code to print all the letters of every new word as they are being typed in the UITextView. Many thanks for your help.
func textViewDidChange( textView: UITextView ) {
 // code for this place
}

A: Just create an outlet to your textField, add the UITextViewDelegate and set the delegate. After that just override the textViewDidChange method. Code example below
@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    textView.delegate = self
}

@IBAction func textField_EditingChanged(sender: UITextField) {
    // Will print out each letter that is typed
    print(sender.text!.characters.last!)

    // Will print out the word
    print(sender.text!)
}

func textViewDidChange(textView: UITextView) {
    // Will print out each letter that is typed
    print(textView.text!.characters.last!)

    // Will print out the word
    print(textView.text!)
}


Q: AS3 Assign Class to XML Loaded element I need to load a set of images with from XML and assign  Interactivity to them
first I load the XML
import flash.display.Loader;
import flash.net.URLRequest;
    var loader:Loader      = new URLLoader();
    var request:URLRequest = new URLRequest("myXML.xml");
    loader.load(request);

loader.addEventListener(Event.Complete, proessFile);
function processFile(e:Event):void
{
 var loadedXML:XML = (e.target.data);
}

//load set of images from XML file

for (var i:uint = 0; i < loadedXML.image.length(); i++)
{
    var imgLoader:Loader      = new Loader();
    var imgRequest:URLRequest = new URLRequest (loadedXML.img[i].attribute("filepath"));
    imgLoader.load(imgRequest);
    addChild(imgLoader);
}

here I  need to make every single image draggable. Is it possible to change it into another data type, b/c I can't work with Loader?
I've tried assign them .name property, but I was unable to call them later.
I don't know If I'm clear enough, but essentially I need to work with every single loaded image as new object. Is it possible to assign variable to every single image?
Any suggestion for thework flow here would be much appreciated.

A: Because you add them to the stage, you could try naming them and then calling them via the stage's getChildByName method.
Or you could build an array of loaders or, better yet, movieClips. Something like:
import flash.display.Loader;
import flash.net.URLRequest;
var loader:Loader      = new URLLoader();
var request:URLRequest = new URLRequest("myXML.xml");
loader.load(request);

var images:Array = new Array();

loader.addEventListener(Event.Complete, proessFile);
function processFile(e:Event):void
{
 var loadedXML:XML = (e.target.data);
}

//load set of images from XML file

for (var i:uint = 0; i < loadedXML.image.length(); i++)
{
    // create a new movie clip
    var tmpMovieClip:MovieClip = new MovieClip();
    var imgLoader:Loader      = new Loader();
    var imgRequest:URLRequest = new URLRequest (loadedXML.img[i].attribute("filepath"));
    imgLoader.load(imgRequest);
    // add the loader to the movie clip's display list
    tmpMovieClip.addChild(imgLoader);
    // add the movieclip to the previously declared array
    images.push(tmpMovieClip);
}

This way, you can call and use any element of the Array when you need them. If you don't need the MoviClips, you could just add the Loader instances into the Array.

A: I'm afraid I am having trouble understanding some your questions.

Is it possible to change it into another data type, b/c I can't work with Loader?

First, what data type would you like to change it to. Second, why can't you work with Loader?

I've tried assign them .name property, but I was unable to call them later.

Why did you want to call them and how did you try to?

I need to work with every single loaded image as new object.

Each loader object encapsulates a single image object. The image is actually inside the Loader (on the .content property).

evilpenguin describes how you can store references to the loader objects inside an array so that you can access them later. That is the correct basic approach. The real question is: "What exactly are you trying to do?"
You say:

here I need to make every single image draggable.

If it is that simple, then add events directly to the loader (which encapsulates the image).
for each(var image:XML in loadedXML.image)
{
    var imgLoader:Loader = new Loader();
    var imgRequest:URLRequest = new URLRequest(image.@filepath);
    imgLoader.load(imgRequest);
    addChild(imgLoader);

    // NOTE: you may want to wait until it is done loading
    // before you add drag and drop behaviour although
    // that isn't strictly necessary
    makeDraggable(imgLoader);
}

function makeDraggable(loader:Loader):void
{
    loader.addEventListener(MouseEvent.MOUSE_DOWN, startDrag);
    loader.addEventListener(MouseEvent.MOUSE_UP, stopDrag);

    // NOTE: I'll leave it up to you to decide
    // how you want to implement drag and drop
}

Note: I've also changed your loop to use E4X which is a much nice way of dealing with XML in Actionscript.

A: To create a 'copy' of your images simply do the following.
private function contentLoaderInfo_completeHandler(event:Event):void
{
    var loaderInfo:LoaderInfo = event.target as LoaderInfo;
    var originalBitmap:Bitmap = loaderInfo.content as Bitmap;
    var newBitmap:Bitmap = new Bitmap(originalBitmap.bitmapData.clone());
    images.push(addChild(newBitmap));
}

This way you are completely detached from the loader object and can dispose of them completely. Obviously as evilpenguin suggested you could then instead add them to Sprites or MovieClips and then add these to the stage (the Bitmap class is not a DisplayObjectContainer and so you can not add extra children to them).


Q: Formatting CDATA string shows unexpected character I have this string entry:
<string name="title_label">[<![CDATA[Title]]> %s</string>

and I format it this way:
String titleLabel = getString(R.string.title_label);
Spanned title = Html.fromHtml(String.format(titleLabel, "My Title"));

However, it shows:
[Title My Title
instead of:
Title My Title
Why is it showing the '[' character in the beginning?

A: Try changing it to :
<string name="title_label"><![CDATA[Title]]> %s</string>

A: Dude, you have 3 opening and 2 closing square brackets there in your XML :)
Happens to the best of us :)


Q: Where is the line for an acceptable question? Take a look at this question: What is a plain English explanation of "Big O" notation?
The question itself is very simple, and I have nothing against this question. I am just asking this because I don't want to put up any unacceptable questions on stackoverflow.  I am wondering why this question was not downvoted due to "lack of research" or "lack of effort in formatting the question." To me, it seems like a "please give me the answer" kind of question, which do receive a lot of downvotes and get closed on stackoverflow. And there are a lot of other examples of questions like this that have received many upvotes/stayed open.
Where is the line between a question that is acceptable and a question that is unacceptable?

A: Big O is a foundational programming concept.  A plain-English explanation on SO seems sensible.   Wikipedia can be very obtuse sometimes.
Questions that seem similar to this but get closed are, all too often, just someone who's too lazy to look it up himself.  Those are not hard to spot.
Questions that do not demonstrate a good-faith effort at solving the problem themselves do not do well.  These include questions that ask the community to solve the problem for them, and questions that can be easily answered by searching online.

A: There are two completely different issues here.  There is the issue of whether or not a particular question should be open or closed.  That, while there can certainly be debate or discussion on the topic, is a question that should have an objective answer based on clear metrics.
Then there is the question of how to vote on a question.  That is entirely subjective, and entirely at the whim of each individual voter.  Anyone can decide whether to upvote or downvote a question for any reason they want (barring a few exceptions for voting fraud).  While there are a number of common reasons that people tend to up or down vote, thus allowing the potential of explaining the likely reason some posts are voted on as they were, at the end of the day nobody is bound to vote in a particular direction.  A vote can never, by definition, be wrong.  The result is that sometimes you can't explain the voting on a question; it can be inconsistent, confusing, unstable, etc.  You just need to learn to deal with that.


Q: Replace the first word of every line in a file with the line number If I have a file like this:
foo bar
bar foo
5 foo
bar 5

and I want to change the file to look like this:
1 bar
2 foo
3 foo
4 5

How can I go about doing this?

A: How about Awk?
$ awk '{$1 = FNR} 1' file
1 bar
2 foo
3 foo
4 5


Q: Stop Camera from rotating around a rotating parent I have a rolling marble and would like my camera to follow it. My problem is that my camera is also rotating around my object as it is rotating.
Here's my code.
-(void) setupCameraOnMarble:(SCNNode*)marble
{
    [cameraNode removeFromParentNode];

    [marble addChildNode:cameraNode];

    SCNLookAtConstraint *marbleStare = [SCNLookAtConstraint lookAtConstraintWithTarget:marble];

    marbleStare.gimbalLockEnabled = YES;

    cameraNode.constraints = @[marbleStare];
}

I'm thinking that a transform constraint should work but I don't understand how it works.

A: Are you sure you need to make cameraNode a child of marble?
Because according to SKNode docs: when a node’s coordinate system is scaled or rotated, this transformation is applied both to the node’s own content and to that of its descendants see SKNode
So i assume you need to un-child camera from marble. And to achive that followint the object behavior from camera, you may update camera coordinates somewhere in the code, that moves the marble

A: I have un-childed my camera to my sphere and made my class a SCNSceneRendererDelegate protocol and added this to the rendering loop:

-(void) renderer:(id)renderer updateAtTime:(NSTimeInterval)time
{
[cameraNode setPosition: SCNVector3Make(marbleNode.presentationNode.position.x, marbleNode.presentationNode.position.y + 5, marbleNode.presentationNode.position.z + 10)];
}

If I log the coordinates of the marble.presentationNode they are changing but my camera still doesn't move!


Q: Stripe multiple subscriptions at checkout best method? I am using Stripe and have a site (node, express, react) where customers purchase subscriptions. They can purchase multiple subscriptions at a time and those subscriptions can have varying intervals. So, each subscription is created separately on the back end during checkout. Basically, the back end receives an array of subscription criteria for the customer's cart and sets up each one as its own subscription, returning an array of subscription objects.
Here is the possible issue I am realizing. Let's say there are 5 subscriptions in a customer's cart it is possible that 3 subscriptions are created successfully and that 2 fail due to insufficient funds, or other reasons. Now you have a partially completed checkout, the card has already been charged for 3 subscriptions and you need new payment details for the remaining 2 subscriptions. Plus, you have to handle letting the user know and altering the cart to reflect that only some of the cart has been purchased which I'm not sure what the expected UI/UX for something like that is. Anyone have any ideas on how to handle this better with Stripe to charge all or none or something similar.


Q: Как узнать значение строки? String PA;

Scanner in = new Scanner(System.in, "Cp866");

PA = in.nextLine();

Не могу узнать значение PA если при вводе я нажму Enter ничего не введя.
Пробовал if(PA == "") out.print("=="); if(PA == null) out.print("=="); Задавать null при объявлении.
Решил проблему проверкой строки isEmpty().

A: Дело в том, что вы сравниваете строки по ссылке. Выражение вида str=="" для строки которую считали из консоли, будет давать всегда false
Для желаемого результата нужно использовать, либо метод equals, либо isEmpty


Q: how to use json response in wpf application My wpf application is communicating with php web api. First I post some data to web api and recieved json resonse. At server side php script just prepared an array and json_encode(arrayName)is sent to client. At my client side I am using following code
using (WebResponse jsonResponse = request.GetResponse())
            {
                // Do something with response
                StreamReader streamReader = new StreamReader(jsonResponse.GetResponseStream());
                String responseData = streamReader.ReadToEnd();

                MessageBox.Show(responseData);
            }

in the message box I am able to see all the data sent by server. Now I don't have any idea how to assign this data to local variables? Kindly guide me.
http://i.imgur.com/1Qzds8G.png
EDIT
Response shown in message box is :-
[{"response":"true","user_id":"250","username":"sapan108"}]'

After Googling I created following class :-
public class UserData
{
    public string response { get; set; }
    public string error { get; set; }
    public int user_id { get; set; }
    public string username { get; set; }
}

Now How to assign json response to these variables.
Note: Due to less reputation unable to post image directly. Sorry for inconvenience.

A: 1) You should create class to represent json data (http://json2csharp.com/)
public class RootObject
{
    public string response { get; set; }
    public string user_id { get; set; }
    public string username { get; set; }
    public string current_balance { get; set; }
    public string message { get; set; }
    public string outh_token { get; set; }
    public List<string> lastFiveSpinNumbers { get; set; }
}

2) You should deserialize json data into class (the easiest way is to using Json.NET library - http://www.newtonsoft.com/json)
using (WebResponse jsonResponse = request.GetResponse())
{
    // Do something with response
    StreamReader streamReader = new StreamReader(jsonResponse.GetResponseStream());
    String responseData = streamReader.ReadToEnd();
    var myData = JsonConvert.DeserializeObject<List<RootObject>>(responseData);
    // process your data
    foreach (var rootObject in myData)
    {
        string response = rootObject.response;
        // ...
    }
}


Q: How to pass custom props to drawer screens in React Navigation 5? Here's my Drawer Navigation config:
  return (
    <NavigationContainer theme={navigationTheme}>
      <Drawer.Navigator
        drawerContent={(props) => (
          <DrawerContent {...props} />
        )}
      >
        <Drawer.Screen name="Home" component={HomeScreen} />
        <Drawer.Screen name="About" component={AboutScreen} />
      </Drawer.Navigator>
    </NavigationContainer>
  );

and in my DrawerContent component:
export default function DrawerContent({ state, navigation, ...props }) {
  return (
    <DrawerContentScrollView {...props}>
        <Drawer.Section>
          {state.routes.map((route) => (
            <DrawerItem
              key={route.key}
              label={route.name}
              onPress={() => navigation.navigate(route.name)}
            />
          ))}
        </Drawer.Section>
      </View>
    </DrawerContentScrollView>
  );
}

I want to add an icon prop to my DrawerItem component inside the DrawerContent component. I tried doing this:
<Drawer.Screen name="Home" icon="home" component={HomeScreen} />

and in my DrawerContent
{state.routes.map((route) => (
    <DrawerItem
        key={route.key}
        icon={({ color, size }) => (
        <MaterialCommunityIcons name="home" icon={route.icon} color={color} size={size} />
        )}
        label={route.name}
        onPress={() => navigation.navigate(route.name)}
    />
))}

But the route.icon property is undefined. Any idea on this?

A: Fixed it using options prop on Screen.
In my Drawer Navigator:
<Drawer.Navigator>
  <Drawer.Screen
    name="Home"
    component={HomeScreen}
    options={{ icon: 'home' }}
  />
</Drawer.Navigator>

and to access it in the custom DrawerContent component:
export default function DrawerContent({ state, navigation, ...props }) {

    const getIcon = (key) => props.descriptors[key].options.icon;

    return (
        <DrawerContentScrollView {...props}>
            <Drawer.Section>
            {state.routes.map((route) => (
                <DrawerItem
                key={route.key}
                label={route.name}
                icon={({ color, size }) => (
                    <MaterialCommunityIcons
                        name={getIcon(route.key)}
                        color={color}
                        size={size}
                    />
                )}
                onPress={() => navigation.navigate(route.name)}
                />
            ))}
            </Drawer.Section>
        </View>
        </DrawerContentScrollView>
    );
}


Q: setTimeout(fn,0) triggering before styles have been applied When I want to yield execution of my javascript and allow the browser to apply styles etc. before I continue, I tend to use the common technique of setTimeout with a delay of 0 to have a callback queued at the end of the event loop. However, I came across a situation where this doesn't seem to be working reliably.
In the snippet below, I have an active class that applies a transition to the chaser element.
When I hover over a target div, I want to remove the active class from the chaser element, move the chaser to a new location, then reapply the active class. The effect should be that the o should immediately vanish, and then fade in its new location. Instead, both the opacity and top have the transition applied, so the o slides from position to position, most of the time.
If I increase the inner timeout's delay to 10, it starts to behave as I originally intended. If I set it to 5, then it sometimes does and sometimes doesn't.
I would have expected any setTimeout to have queued my callback until after the style updates have been applied, but there's a clear race condition here. Am I missing something? Is there a way to guarantee the order of updates?
I'm on Chrome 56 on macOS and Windows, haven't tested other browsers yet.
(I know I can achieve this in other ways such as applying the transition to only the opacity property - please consider this a contrived example to demonstrate the particular question about ordering style updates).

var targets = document.querySelectorAll('.target');
var chaser = document.querySelector('#chaser');
for (var i = 0; i < targets.length; i++) {
  targets[i].addEventListener('mouseenter', function(event) {
    chaser.className = '';
    setTimeout(function() {
      // at this point, I'm expecting no transition
      // to be active on the element
      chaser.style.top = event.target.offsetTop + "px";

      setTimeout(function() {
        // at this point, I'm expecting the element to
        // have finished moving to its new position

        chaser.className = 'active';
      }, 0);
    }, 0);
  });
}
#chaser {
  position: absolute;
  opacity: 0;
}
#chaser.active {
  transition: all 1s;
  opacity: 1;
}
.target {
  height: 30px;
  width: 30px;
  margin: 10px;
  background: #ddd;
}

o

x

x

x

x

x

A: What you need to listen for is transitionend event before doing anything else. You can read up on MDN about transitionend event. Btw, setTimeout should never be used to guarantee timing.
EDIT: This is for reference after clarification from OP. Whenever a style change occurs to an element, there is either a reflow and/or repaint. You can read more about them here. If the second setTimeout is ran before the first reflow, then you get the sliding effect. The reason why 10ms will lead to the desired effect is because .active class is added after the offsetTop property has been adjusted (leading to transition property applied after the element has changed it's offsetTop). Usually, there are 60fps (i.e: ~16ms per frame) which means that you have a 16 ms window to do anything before the new styles are applied. This is why a small delay of 5ms will sometimes lead different results.
TL:DR - The browser asks JS and CSS every 16ms for any updates, and calculates what to draw. If you miss the 16ms window, you can have completely different results.

A: You are calling a setTimeout() timing method inside another setTimeout() timing method.
My thought is, why not call the both setTimeout() method separately like so:
The first setTimeout() method should execute first, then at end of execution, it should call the second setTimeout() method.

A: Here is a working script for moving the chaser:
function _( id ) { return document.getElementById( id ); }

window.addEventListener( 'load', function() {

 var targets = document.querySelectorAll('.target');
  var chaser = document.querySelector('#chaser');

 setTopPosition( targets );

function setTopPosition( targets ) {
    for (var i = 0; i < targets.length; i++) {
        targets[i].addEventListener('mouseenter', function(event) {

            chaser.className = '';
            _( 'status' ).innerText = chaser.className; // to inspect the active class

           setTimeout(function() {
               /* at this point, I'm expecting no transition // to be active on the element */

              chaser.style.top = event.target.offsetTop + "px";
      }, 0);

          // check if charser.className == ''
          if ( chaser.className == '') {
              setClassName();
          } else {
              alert( 0 );
          }

       }); // addEventListener
    } // for
} //function setTopPosition( targets )

function setClassName() {
    setTimeout(function() {

         /* at this point, I'm expecting the element to have finished moving to its new position */

        chaser.className = 'active';
        _( 'status' ).innerText = chaser.className;
         }, 0);
} // function setClassName()

});

HTML:

o

x

x

x

x

x

status

CSS:
#chaser { position: absolute; opacity: 0; }
#chaser.active { transition: all 1s; opacity: 1; }
.target { height: 30px; width: 30px; margin: 10px; background: #ddd; }


Q: How do I send data from a Component to another Component in Angular? I'm very new to Angular, and I'm really struggling to find a concise answer to this problem. I have a Form Component Here:
(I'm excluding the directives and imports as they're not really relevant)
export class JournalFormComponent implements OnInit {

  public entries: EntriesService;

  constructor(entries: EntriesService) {
    this.entries = entries;
  }

  ngOnInit(): void {
  }

}

The EntriesService service just stores an array of entries:
export class Entry {
  constructor (
    public num: number,
    public name: string,
    public description: string,
    public text: string
  )  { }
}

The Form Component template renders a <h2> and a <app-input> Component for each entry in the EntriesService, which works. That looks like this:
<div *ngFor="let entry of entries.entries">
  <h2> {{ entry.num }}. {{ entry.name }} </h2>
  <app-input id="{{entry.num}}"></app-input>
</div>

Here's the <app-input> Input Component:
@Component({
  selector: 'app-input',
  template: `
    <textarea #box
      (keyup.enter)="update(box.value)"
      (blur)="update(box.value)">
    </textarea>
    `
})
export class InputComponent {
  private value = '';

  update(value: string) {
    this.value = value;
  }

  getValue () {
    return this.value;
  }
}

The InputComponent stores the user's text perfectly, but I don't know how to pass that data to the Form Component's EntriesService to update the Entry in order to Export it or Save it later. How is this done?
I think I'm phrasing this question well, but I'm not sure. If you need clarification I'll provide it.
Not sure if it matters, but I'm using Angular 9.1.11

A: There are many ways to update the data from one component to another.

*

*component to component using service or subjects

*parent~child component data exchange using Input() and Output() decorators. Or by using @ViweChild() interactions.
and many more

But please do check the angular docs https://angular.io/guide/component-interaction .
Use the below simple code, u might need to include modules like FormsModule. and import Input(), Output etc
@Component({
  selector: 'app-journal-form',
  template: `
    <div *ngFor="let entry of entries.entries; let i=index">
      <h2> {{ entry.num }}. {{ entry.name }} </h2>
      <app-input id="{{entry.num}}" [entry]="entry" [arrayIndex]="i" (updateEntry)="updateEntry($event)" ></app-input>

    </div>`
})
export class JournalFormComponent implements OnInit {
  constructor(private entries: EntriesService) {
    this.entries = entries;
  }

  ngOnInit(): void {
  }

  updateEntry(event){
    console.log(event);
    this.entries[event.arrayIndex] = event.entry;
  }

}

@Component({
  selector: 'app-input',
  template: `
    <textarea [(ngModel)]="name"
      (keyup.enter)="update()"
      (blur)="update()">
    </textarea>
    `
})
export class InputComponent {
  @Input() entry: any;
  @Input() arrayIndex: number;
  @Output() updateEntry: EventEmitter<any> = new EventEmitter();
  name:string;
  constructor() {
    console.log(entry);
    this.name = entry.name;
  }

  update(){
    this.entry.name = this.name;
    this.updateEntry.emit({entry: this.entry, arrayIndex});
  }

}

A: Output event will help in this situation.
<div *ngFor="let entry of entries.entries">
  <h2> {{ entry.num }}. {{ entry.name }} </h2>
  <app-input id="{{entry.num}}" (entryChange) = "entry.text = $event"></app-input>
</div>

app-input component
export class InputComponent {
  private value = '';
  @Output() entryChange = new EventEmitter<string>();
  update(value: string) {
    this.value = value;
   this.entryChange.emit(value);
  }
}

Instead of entry.text = $event you can also pass it to any save function, like saveEntry($event);


Q: Is selected option selected if attribute is in DOM or not To create a Dual Listbox like Bootstraps I needed to remove the default gray color of selected option. The only way to remove this gray color was to change the selected state of the element to false. No other trick worked to remove the gray background color of selected option.
Now if I do so, the attribute selected still remains in DOM but seems to be false. I thought if we have an element like:
<option value="1" selected>1: Lorem ipsum</option>

if selected is there it means always option selected true as it is the same as:
<option value="1" selected="selected">1: Lorem ipsum</option>

or
<option value="1" selected="true">1: Lorem ipsum</option>

but this seems not to be like so. Could anyone shed some light on this for me?
I've created a fiddle https://jsfiddle.net/npm6tn0m/ trying to demonstrate the scenario. Where the css
option[selected] {
   background-color: orange;
}

only works for the selected option which is set to false but still has the selected attribute in DOM. Cause this may vary across different browsers here is an image from what I see in OSX Chrome browser:

All code like in the fiddle also here on SO:

var elements = document.querySelectorAll('.special option');
for(var i=0; i < elements.length; i++) {
    elements[i].selected = false;
}

setTimeout(function(){
  var elements = document.querySelectorAll('option');
 for(var i=0; i < elements.length; i++) {
     console.log('Value = ' + elements[i].value + ' selected: '+ elements[i].selected);
 }
}, 1000);
option[selected] {
   background-color: orange;
}
<select class="special" multiple>
  <option value="1" selected>1: Lorem ipsum</option>
  <option value="2"  >2: dolor sit amet</option>
</select>

<select multiple>
  <option value="3"  selected>3: Lorem ipsum</option>
  <option value="4"  >4: dolor sit amet</option>
</select>

A:
I thought if we have an element like:
<option value="1" selected>1: Lorem ipsum</option>

if selected is there it means always option selected true as it is the same as:
<option value="1" selected="selected">1: Lorem ipsum</option>

...
but this seems not to be like so. Could anyone shed some light on this for me?

You're correct about how boolean attributes work, just not about what the selected boolean attribute represents. :-)
The selected attribute represents the default selected state, not the current selected state. It's like an input's value attribute in that way; the default (used in case of form reset, for instance), not the current value.
Just as the current value of an input is not represented in the DOM, similarly the current value of a option's selectedness is not represented in the DOM.

A: Different browser may treat this attribute differently. According to the MSDN documentation (for Internet Explorer):

To select an item in HTML, it is not
  necessary to set the value of the
  SELECTED attribute to true. The mere
  presence of the SELECTED attribute set
  its value to true.

In firefox and Safari this does work:
<option selected='false' />

From what I can tell by looking at the official WC3 standard for HTML5, the supported case is only:
<option selected='selected' />

You will either need to selectively emit the attribute, or use selected='false' or use javascript to control which item is initially selected.


Q: Generate only continuous combinations of a list of numbers I have a list in python [1, 2, 3, 4, 5, 6]. I want to generate all possible combinations of length 2, 3, 4 and 5. I have used itertools.combinations to generate the combinations but it doesn't generate continuous combinations only. For example, length 2 combinations should be only [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]. Is there any faster way to generate than the following code?
for start, end in combinations(range(len(lst)), 2):
    if end - start <= 4 and end-start >= 1:
        print(lst[start:end+1])

A: You don't need combinations at all. What you want looks more like a sliding window.
for i in range(2, 6):
    for j in range(len(lst) - i + 1):
        print(lst[j:j + i])

A: You can loop over the list as following:
a = [1,2,3,4,5,6]
for i in range(2, len(a)):
    for j in range(len(a)-i + 1):
        print(a[j:j+i])
    print()

The trick here is that a[j:j+i] returns the list from j, up until j+i.
Putting this into a function form:
def continuous(lst, length):
     slices = []
     for j in range(len(lst)-length + 1):
         slices.append(a[j:j+length])
     return slices

A: You can loop through the list in the following method
lst = [1, 2, 3, 4, 5 ,6]

def continuous(lst, length):
    result = []
    for i in range (0, len(lst)-length):
        entry = []
        for j in range (0, length):
            entry.append(lst[i+j])
        result.append(entry)
    return result

print(continuous(lst, 2))

or if you are just looking to print it line by line
def continuous(lst, length):
    for i in range (0, len(lst)-length):
        entry = []
        for j in range (0, length):
            entry.append(lst[i+j])
        print(entry)


Q: How to turn a Rails app with Devise into an OAuth provider? I have a Rails application with admin accounts using Devise for authentication. I am creating a second application and would like to authenticate using the first application instead of duplicating admin accounts in the second application. So my idea is to turn the first application into an OAuth provider so that the second app can simply act as an OAuth client using something like OmniAuth. Have you done this before? Is there a plugin which adds the ability to Devise to be able to act as an OAuth provider? What do I need to change/add in order to turn the app into an OAuth provider?

A: Use Doorkeeper gem. Its easy to introduce OAuth 2 provider functionality to your application. It can be also integrated with Devise.
Doorkeeper also provides a configuration option to auto-approve and skip the authorization step. This is useful when working with a set of trusted applications, so that you don't confuse your users by requiring them to "authorize" your company's trusted app.
# in config/initializers/doorkeeper.rb
Doorkeeper.configure do
  # ...other config options...

  skip_authorization do
    true
  end

end


Q: Can I detect the integrity of the picture in the PDF file use Itextsharp There are some pdf files.And there are pictures in PDF that are incomplete.Can i Check if PDF has incomplete pictures use ITextsharp?
The Sample Pdf
The bad pdf looks like this

Thanks a lot!


Q: How can I remotely log someone off from my Google (Chrome) account? I have a friend who used to use Safari and (about a year ago) I used to use Google Chrome on her laptop because I didn't have my own at the time.
I completely forgot that it was even syncing the entire time, until today I saw that she's surfing from my account. :P
How can I log her off my account?

A: Change your Google account password to something she doesn't know.
It won't cause her to become logged off, but should prevent her from logging back into it next time she opens Chrome.


Q: Есть ли в Blender что-то типа режима Hidden Line? Есть ли в режимах Viewport Blender'а что-то типа max'овского Hidden Line - аналог Wireframe, но со скрытием невидимых (находящихся за другими полигонами) граней?

A: У конкретного объекта можно включать отображение сетки на панели object:

Это включает сетку, которую видно только спереди:

A: В 2.8 есть такой режим:

Включается выключением X-ray в режиме wireframe.


Q: How i can receive variable from another thread in Jmeter in the first thread, I received JSON (format - {"id":6054,"name":"Jmeter created chat","description":"jmeter created test"})
I want to use it in the second thread variable '6054'
I use BeanShell Assertion with code:
${__setProperty(("id":"(.+?)"), ${chat_id)};
but it, of course, doesn't work, please tell me the right way..
many thanks

A: *

*It won't work because your __setProperty() function call doesn't make sense at all and it's syntactically incorrect

*Since JMeter 3.1 you're supposed to use JSR223 Test Elements and Groovy language for scripting

So

*

*Remove your Beanshell Assertion

*Add JSR223 PostProcessor as a child of the request which returns the above response

*Put the following code into "Script" area:
props.put('chat_id', new groovy.json.JsonSlurper().parse(prev.getResponseData()).id as String)

*In 2nd Thread Group access the value using __P() function as:
${__P(chat_id,)}

Demo:

More information regarding what these prev and props guys mean can be found in the Top 8 JMeter Java Classes You Should Be Using with Groovy article

P.S. You may find Inter-Thread Communication Plugin easier to use


Q: How to change default value in counter-increment? I think the code is counting the "Rank" header as a row and assigning 1 to it. How can I change the first number of the counter-increment? I would like the table to start from 0 so that the "Rank" header is assigned 0 and the next row is 1, and so on and so forth.
http://oi59.tinypic.com/5bsabc.jpg

CSS File
tr.odd {background-color: #FFFFFF}
tr.even {background-color: #F2F2F2}

table {
    counter-reset: rowNumber;
}

table tr {
    counter-increment: rowNumber;
}

table tr td:first-child::before {
    content: counter(rowNumber);
    min-width: 1em;
    text-align: center;
}

JSP File
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="<c:url value='/css/egovframework/leaderboard.css'/>" />
<form id="listForm" name="listForm" method="post">
    <input type="hidden" name="id"/>
</form>

Leaderboard

        <colgroup>
        <col style="width:50px">
        <col style="width:500px">
        <col style="width:150px">
        <col style="width:100px">
        </colgroup>

            Rank
            Name
            Points
            Wins

        <c:forEach var="item" items="${leaderboard}" varStatus="loopStatus">

                <c:out value="${item.playersLastName}"/>, <c:out value="${item.playersFirstName}"/>

                <c:out value="${item.playersPoints}"/>

                <c:out value="${item.playersWins}"/>

        </c:forEach>

A: CSS counter's default value is always 0 and that's not the problem in your case. The problem is that you are incrementing the value to 1 when the first tr is encountered itself.
There are multiple ways in which you can solve this:

*

*Assign the initial value of the counter as -1 during counter-reset property. This means that when the first tr is encountered the counter value increments from -1 to 0 and so it looks as though the header row is not numbered.

tr.odd {
  background-color: #FFFFFF
}
tr.even {
  background-color: #F2F2F2
}
table {
  counter-reset: rowNumber -1;
}
table tr {
  counter-increment: rowNumber;
}
table tr td:first-child::before {
  content: counter(rowNumber);
  min-width: 1em;
  text-align: center;
}

    Rank
    Name
    Points
    Wins

*Increment counter value only from the second tr that is encountered. This can be done using the + (adjacent sibling selector) or ~ (general sibling selector) or nth-child(n+2). Using one of these would mean the selector would be matched only by the second and subsequent tr within the table.

tr.odd {
  background-color: #FFFFFF
}
tr.even {
  background-color: #F2F2F2
}
table {
  counter-reset: rowNumber;
}
table tr + tr {
  counter-increment: rowNumber;
}
table tr td:first-child::before {
  content: counter(rowNumber);
  min-width: 1em;
  text-align: center;
}

    Rank
    Name
    Points
    Wins

*Best and recommended solution: Wrap the headers inside a thead, the contents inside tbody and modify the selector within which the counter is incremented. This is recommended because it gives a proper structure to the table and doesn't look hackish.

tr.odd {
  background-color: #FFFFFF
}
tr.even {
  background-color: #F2F2F2
}
table {
  counter-reset: rowNumber;
}
table tbody tr {
  counter-increment: rowNumber;
}
table tr td:first-child::before {
  content: counter(rowNumber);
  min-width: 1em;
  text-align: center;
}

      Rank
      Name
      Points
      Wins


Q: Fedora liveUSB how to boot to ram? I use Linux Mint mostly as OS. I wanted to try to use Fedora more. I wanted to boot liveUSB to ram, familiar toram option to pass to the kernel (although it is not kernel parameter, it AFAIK is passed further down the line of boot sequence) had not worked. I've tried web search and to my surprise most relevant (IMO) result for booting to ram was this post w/out any answers: https://forums.fedoraforum.org/showthread.php?324932-Fedora-33-boot-live-to-ram

the option rd.live.ram doesn't seem to work any more. Any idea how to
boot live image to ram?

Is it definite - no boot to ram support for recent versions? Any historic reasons why has it been dropped? It was of particular surprise to me as I've found about swap to ram in Fedora, which I don't recall reading about for Linux Mint / Ubuntu.

A: I've just downloaded the XFCE spin for Fedora 35 ( Fedora-Xfce-Live-x86_64-35-1.2.iso ) and the option is there however it looks like there's a bug and using the option (rd.live.ram=1) leads to a dead system under VirtualBox:

Maybe it only affects the XFCE spin. I've filed a bug report: https://bugzilla.redhat.com/show_bug.cgi?id=2035641


Q: I have to create a CI CD pipeline to integrate repos in azure to linux server My azure repos contains all the folders , and changes will be made by the users in the azure repos.
I want to create CI CD pipeline in azure repos to integrate azure repos and the linux server. Whenever some changes done in the azure repos should reflect in the linux server.
I want to know, how to implement the above scenerio.

A: According to your description, you can try to install a new self-hosted agent in your Linux server.
And then in your CI pipeline, you can use the git clone command to clone the repo in your Linux server.
You can also use the copy files task to copy the folder of the repo the to the UNC path.


Q: snowpack: reference files outside of project folder Our team develops a bunch of JavaScript browser apps. These apps share functionality (core) and Web Components (shared). The folder structure is:
/apps
     /app-1
     /app-2
     ...
/core
/shared

Each folder contains a src folder.
Considering using snowpack in the folder app-1 I want to reference js files in /core/src or /shared/src both for development (using snowpack dev) and packaging (using snowpack build)

*

*is this possible?

*are there best practices how to achieve this?

*are there examples for such a situation (or a similar one)

What I tried:
Step 1: I used paths like this: ../../core/src/router.js. This didn't work, maybe because the resources were outside of the webroot of the test server (snowpack dev).
Step 2: I created two symlinks:
apps/app-1/src/@core   -> ../../../core/src
apps/app-1/src/@shared -> ../../../shared/src

Now the local server found all the resources. The build process however found only those files, that were direct children of core/src or shared/src, but not any file within a subfolder as e.g. shared/src/component/filter.js.
Any ideas or thoughts?
Appendix
The snowpack.config.json of app-1:
{
    "devOptions": {
        "port": 8082,
        "open": "none"
    },
    "mount": {
        "public": "/",
        "src": "/_dist_"
    },
    "plugins": [
        "@snowpack/plugin-babel",
        "@snowpack/plugin-dotenv",
        "@snowpack/plugin-sass"
    ]
}

Example for import in app-1/src/handler:
import { loadRoute } from '../@core/router'    // works fine
import '../@shared/component/filter'           // does not work
// or:
import { loadRoute } from '../@core/router.js' // works fine, too
import '../@shared/component/filter.js'        // does not work neither

A: You can solve your problem just adding:
  workspaceRoot: '..',

to your snowpack.config.js file.
Basically it tells snowpack to process everything from the parent folder (..) through it's pipeline. It will pick up dependencies and process everything.
In your case, you could import files from shared in app-1 by using relative paths, and without creating any symlinks:
import something from '../shared/something';

You can find more about workspaceRoot property in snowpack's documentation.

A: You should be able to specify a relative path to the folder in your mount object as another key:
{
  "mount": {
    "../../shared": "/_dist_"
  }
}

this should serve your files from the shared directory from the /_dist_ folder.