Q: JQuery interfering with lxml parsing I am trying to scrape a website which was probably written poorly, so when you initially perform a GET request on their page, it responds with 5 entries in a mixture of html, javascript, jquery because it's the visual part of the page, and if you want to get more entries, you click a button, which internally performs a POST request on the same page along with the "pagination value" which is like the page you want, like if you want entries 6 to 10, you give a value of "2" to pagination value and if you want entries 11 to 15, you give a value of "3", and it does this asynchronously and appends the data to the end of the previous result set.
Sending/receiving is not a problem, in fact, when I try to scrape the page using lxml, I can easily get values for the first 5 entries, however, when I have to get the second set of data, I provide pagination value of "2" and I expect xml data back, because xml/html would be easy to parse, but here's my problem:
They return a weird combination of jquery AND html. It goes something like this:
$(".entry:last").after("

some data

");

When you inspect their website, this works flawlessly, the last 5 entries that just got downloaded asynchronously via AJAX, gets added sequentially to the first 5 entries, I looked into the "after" method of Jquery and I can confirm that it just appends the 5 entries after the 5th element.
When I initially scraped their data, the root element was a html tag, so I could parse it using lxml, but the response that they provide the moment I have to parse the result of this pagination is this weird mix of Jquery and html.
Also I can assure you that there is only one "after" method, and everything else is html, so basically 2 lines of Jquery, the first line and the last line, so I assumed I would just blindly remove the first and last line and then parse it again, but the response object that I get from the requests library, which I use to perform the POST operation, returns it as one long line of data, so I cannot do any readLine() on it, to seperate the first line from the second line from the last line, it's all just one line to me. So I would like pointers on how I would solve something like this.
Thanks :D

A: So if I understand correctly, the question is "How do I extract HTML embedded in javascript code".
The quick and dirty solution is to use a regular expression to extract the HTML. This is going to be a little finicky because of quoting but it's not too bad, you need a regular expression which can match a string with escaped quotes, this one will do the trick for doublequotes, it will match anything between doublequotes which is not a double quote, or is a quoted double quote:
"((?:[^"]+|\\")+)"

You can then use that to create a regular expression which will extract the contents of the html string from it's jquery wrapping:
import re

mixed_js_html = r'$(".entry:last").after("

some data

");')

m = re.search(r'after\("((?:[^"]+|\\")+)"\)', mixed_js_html):
html_code = m.group(1)
html_code = html_code.replace('\\"', '"') # unescape quotes
print(html_code)
#

some data


Q: accessing current redux state in monaco editor action run function I have a monaco editor instance, and I add an action for the Ctrl+S Keys.
const addActions = (editor: editor.IStandaloneCodeEditor) => {
        editor.addAction({
            id: "save-element-action",
            label: "Save Element",
            keybindings: [KeyMod.CtrlCmd | KeyCode.KEY_S],
            precondition: undefined,
            keybindingContext: undefined,
            contextMenuGroupId: "navigation",
            contextMenuOrder: 1.5,

            // @param editor The editor instance is passed in as a convinience
            run: function (ed) {
                // TODO: saveElement is called but doesnt work yet because expressionEditorState is empty (Closure??)
                saveElement();
            },
        });
    };

in the saveElement function i want to access some state from my redux store
    const saveElement = (editor?: editor.ICodeEditor) => {
        if (expressionEditorState.elementContent === undefined || expressionEditorState.elementContent === "") {
            dispatch(createErrorAction("No content for element"));
            return;
        }

        dispatch(createSaveElementAction(user, expressionEditorState.elementContent, expressionEditorState.elementMetaData));
    };

the expressionEditorState is the same as the initial state (so empty).
The setup of the state is down with a custom hook and the useSelector hook.
How can i access the current state of redux in the run function of a monaco action?

A: if anyone is following up...
the solution is to use thunks (see redux-thunks). so i rewrote saveElement as thunk and just dispatch it.
dispatch(saveElement())


Q: How to specify different buld dirrectories for qmake? I use qmake. I have the following project structure:
/
|_SFMLWidgets
| |_...
| |_View.h
| |_View.cpp
| \_...
|
|_MapEditor
| |_...
| |_View.h
| |_View.cpp
| \_...
|
\_main.cpp

This views do different things. When I try to compile project I get compilation errors:
overriding recipe for target 'debug/View.o'
ignoring old recipe for target 'debug/View.o'

It happens because both views are builded in same directory. Is there any way to specify different build dirrectories?
I want something like:
/
|_debug
  |_SFMLWidgets
  | |_...
  | |_View.o
  | \_...
  |
  |_MapEditor
  | |_...
  | |_View.o
  | \_...
  |
  |_main.o
  \_main.exe

My .pro file

A: You can put each of SFMLwidgets and MapEditor in separate subdirs qmake project files. Shared configuration of the two subprojects can go into a pri file.


Q: Prove that $\lambda_{gh}=\lambda_h\lambda_g$ Let $G$ be a group; Consider the mapping of $G$ into itself, $\lambda_g$, defined for $g \in G$ by $\lambda_g(x)=gx$. Prove that $\lambda_{gh}=\lambda_h\lambda_g$.
This is question on page $74$ of I. N. Herstein.
If I look at  $\lambda_{gh}(x)=ghx=g(hx)=\lambda_g(\lambda_h(x))$. But this is not what the question says to prove. Is there something wrong with the question?? Or my approach??
Thank you!!

A: Here is the problem statement from Herstein's Topics in Algebra, 2nd ed:

As you can see, Herstein defines function application on the right ($x\lambda_g$ means $(x)\lambda_g$) and so you get the reverse order of composition.
Your answer can be readily adapted to this convention:
$$(x)\lambda_{gh}=(gh)x=g(hx)=(hx)\lambda_g = ((x)\lambda_h)\lambda_g= (x)(\lambda_h\circ\lambda_g)$$

A: In seeing $\lambda_g\lambda_h$ you may think that is a multiplication. But, ask yourself: where we are? What kind of multiplication is defined here?
$\lambda_g\in Aut(G)$ and $Aut(G)$ is a group wrt the composition, i.e. we are working in the group $(Aut(G),\circ)$.
Hence when we write $\lambda_g\lambda_h$ we mean exactly $\lambda_g\circ\lambda_h$! And this is exactly what you wrote in the end:
$\lambda_{gh}(x)=(gh)x=g(hx)=g\lambda_h(x)=\lambda_g(\lambda_h(x))=(\lambda_g\circ\lambda_h)(x)$. Since this holds $\forall x\in G$, we can conclude that $\lambda_{gh}=\lambda_g\circ\lambda_h$.


Q: Bitlocker on non-TPM board: how to change startup option?
When I initially encrypted my OS drive, and BitLocker asked me how I wanted to unlock my drive at startup, I chose "Enter a password".
Now I'm wondering if I can change that to USB drive. I've been searching around without any results.
I've tried right-click on drive > "Manage BitLocker" > "Backup recovery key to usb drive"
Then left the usb drive in the machine in the hopes that it would read the text file. This doesn't seem to work.
Any ideas?

A: You can add different types of key to the bitlocker volume. The Windows GUI is limited.
Also the terminology is somewhat confusing and ambiguous. (External Key file, recovery key, recovery file, recovery key within a recovery txt file. Just be aware of the different key-commands and double check your expectations.)
Please open this in a new tab, it may provide some insights.
Manage-bde -protectors C: -add /?

You will have to update the command to your needs. Please understand the difference between a recovery .txt document with numbers and an actual key file. (*.bek) ("External Key file")
manage-bde -protectors C: -add -StartupKey F:

F: is USB drive.
If the system detects the USB stick, it will not ask for a password and simply boot.
Side note
You might want to enable legacy usb in the bios if your USB stick is not detected at all. You can check if you ask for the F8 boot menu. The USB stick should be listed there.
You may delete the password protector after you have successfully booted up from your USB stick in several ports. (Test is; hubs may misbehave.)


Q: Не выходит установить bluebird bcrypt-as-promised npm i --save bluebird bcrypt-as-promised
Вбиваю эту команду и выдает эти ошибки

A: Вам РусскимАнглийским языком написало, что не найден Python в C:\Program Files (x86)\Python36-32\python.EXE
Попробуйте установить Python на компьютер и запустить команду снова

A: Пайтон 3х не подходил, поставил версию ниже и все заработало.
Можно закрывать


Q: Scrollbar in mIRC window Is it possible to remove or hide (hide to allow mouse wheeling) a scroll bar within a custom mIRC window.  The verticle scrollbar to be specific.
If you look to the very right of the picture you see the scrollbar.
Is there a way to remove it?

A: Yes, it can be removed.
I put together this AHK script that will hide the scrollbar in mIRC, and will keep it hidden even after resizing the window, as well as minimizing and restoring the window.
Load this up in autohotkey and it will start working once you click on a channel or anything in the switchbar.
~LButton::
MouseGetPos, , , , OutputVarControl
if (OutputVarControl = "mIRC_SwitchBar1" or OutputVarControl = "ScrollBar1")
{
WinWait, ahk_class mIRC
Control, Style, Hide, ScrollBar1
ControlGetPos, x,, Width,, mIRC_Channel1
ControlMove, mIRC_Channel1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Query1
ControlMove, mIRC_Query1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Status1
ControlMove, mIRC_Status1, ,, (Width + 18)
ControlGetPos, x,y, Width,Height, ListBox1
ControlMove, ListBox1, (x - 18),, ,
}
else if (OutputVarControl = "MSTaskListWClass1")
{
sleep, 500
if WinActive("ahk_class mIRC"){
WinWait, ahk_class mIRC
Control, Style, Hide, ScrollBar1
WinGetPos, X, Y, W, H, ahk_class mIRC
WinMove, ahk_class mIRC, , , , (W + 18),,
WinGetPos, X, Y, W, H, ahk_class mIRC
WinMove, ahk_class mIRC, , , , (W - 18),,
ControlGetPos, x,, Width,, mIRC_Channel1
ControlMove, mIRC_Channel1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Query1
ControlMove, mIRC_Query1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Status1
ControlMove, mIRC_Status1, ,, (Width + 18)
ControlGetPos, x,y, Width,Height, ListBox1
ControlMove, ListBox1, (x - 18),, ,
}
}
return

Assumes you use mIRC with one window maximized at a time inside the mIRC client like this. But you can have as many channels/query windows open, the script can handle switching between them.

A: No, The scroll-bar at the main custom window, can not be removed.


Q: A method to evaluate rounding errors I'd like to learn to evaluate how much there is error if I compute algebraic expressions and round my intermediate steps. For example, I had data of length of couples height as (167,183), (165,165), (167,178), (163,173), (178,180), (165,173). I computed the Pearson correlation of those data points to be $$\frac{\frac{85}{5}}{\sqrt{\frac{287}{10}}\sqrt{41}}.$$
But if I make a table to compute the correlation which has say columns $x,y,x-\bar{x},y-\bar{y},(x_i-x)(y_i-y), (x_i-x)^2,(y_i-y)^2$ and for every point I round the result for example to four decimals, what can I say the error $\epsilon$ of the correlation coefficient? Or if $\epsilon$ should be for example less than $0.01$, how many digits should I take to the intermediate results. I would like to see some tutorial/lecture notes/book to evaluate errors. Also, if person's height is 167 in this data, the height $h$ actually satisfies the inequality $166.5<h<167.5$ so I'd like to learn how much that affects on the correlation.

A: You might look up "interval arithmetic".


Q: Flashlight app (How to set screen brightness to Max?) I am working on a flashlight android app, which has an option for screen light(Max Brightness). How can I set an activity brightness to max with a button press?

A: This site has some information about the topic: http://www.tutorialforandroid.com/2009/01/changing-screen-brightness.html
The part what you need:
IHardwareService hardware = IHardwareService.Stub.asInterface(ServiceManager.getService("hardware"));
if (hardware != null)
        hardware.setScreenBacklight(brightness);

I didn't test it but it should work
UPDATE:
Alternate solution:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1.0f;
getWindow().setAttributes(params);


Q: StringBuilder, add Tab between Values I have a small problem:
I have a List of fields, with 3 Values. I want to build my String with these three Values,
delimited by a "TAB"..
Code:
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
    stringBuilder.Append(field).Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();

The Tab is only between the 3rd and 2nd Value (Between 1st and 2nd is a Space ?!)
So I tried this:
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
    stringBuilder.Append(field + "\t").Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();

Then I have 2 Tabs between 3rd and 2nd, one Tab between 1st and 2nd and also a Space
between 1st and 2nd..
(The Space is always there, how to avoid that?)
So what I have to do? Need only (without spaces..) a Tab between these Values..

A: I think you are confusing with tab char and sapces.
Are you expecting fixed no of white spaces to be added in the end of every word?
\t -> is just a tab char
The following is generated by the code given by you.
Java    StackOverflow   Banyan
Javasun StackOverflow   Banyan

The above two lines have same tab char b/w the 1st & 2nd Word.
if you type one more char in the end of "Javasun" it will extend like the following
Javaasunk   StackOverflow   Banyan

A: try
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
    stringBuilder.Append(field.Trim()).Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();

Basically I would just use return string.Join ( "\t", fields ); .

A: I would have thought you would want
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
    stringBuilder.Append(field);
    stringBuilder.Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();

A: Instead of looping, you can use string.Join:
StringBuilder stringBuilder = new StringBuilder();

stringBuilder.AppendLine(string.Join("\t", fields));

Note that you can pass in the string directly to AppendLine as well.

A: Sub WarningWindow(ByVal content As String)
    Dim sw As New StringWriter()
    Dim hw As New HtmlTextWriter(sw)
    Dim gridHTML As String = sw.ToString().Replace("""", "'").Replace(System.Environment.NewLine, "")
    Dim sb As New StringBuilder()
    Dim a As String = "Welcomeback"
    'GridView1.RenderControl(hw)
    sb.Append("<script type = 'text/javascript'>")
    sb.Append("window.onload = new function(){")
    sb.Append("var printWin = window.open('', '', 'left=0")
    sb.Append(",top=0,width=1400,height=500,resize=yes,scrollbars =yes');")
    sb.Append("printWin.document.write(""")
    sb.Append("<INPUT Type=Button Name=Close Size=40  Value='Clsose(GSS)' onclick='self.close()'; / > ")
    sb.Append("</br><INPUT Type=Button Name=fu Size=40  Value='Alert' onclick=javascript:window.alert('" & a & "'); / > ")
    sb.Append("<INPUT Type=Text Name=gss Size=40  Value=300 ; / > ")
    sb.Append(" <P>")
    sb.Append(content)
    sb.Append(""");")
    sb.Append("printWin.focus();")
    sb.Append("printWin.show;};")
    sb.Append("</script>")
    ClientScript.RegisterStartupScript(Me.GetType(), "suvesh", sb.ToString())
End Sub


Q: Font size confusion in LaTeX I am a beginner in LaTeX and I am not able to resolve the problem. Hopefully, I will get the help here.
I have the following code:
 \documentclass[12pt]{article}
 \usepackage{newtxtext,newtxmath}
 \usepackage{authblk}
 \renewcommand{\Authfont}{\fontsize{12}{14.4pt}\selectfont}
 \renewcommand{\Affilfont}{\fontsize{10}{12}\selectfont}
 \begin{document}
\title{\textbf{Preparation of Papers for IEEE Sponsored Conferences \& Symposia}}
\author{Navdeep Singh\textsuperscript{a}, Lakhwinder Kaur \textsuperscript{b}, Kuldeep Singh \textsuperscript{c}}
\affil[a,b]{Dept. of Computer Science \& Engg., Punjabi University, Patiala, 147001, Punjab}
\affil[c]{Bharat Electronics Ltd, Ghaziabad, U.P, India}
\date{}
\maketitle
\end{document}

and it gives the following output:

Here as we can observe the superscript on the last author's name contains an unwanted '1'. I am not able to find out what is the mistake in my code. Please help me locate it.
Another question I would like to ask is based on the following 2 commands
\documentclass[12pt]{article}
\renewcommand{\Authfont}{\fontsize{12}{14.4pt}\selectfont}

Both the commands say that the font size is 12pt then why is the font size of title and authors different? I know they both belong to different packages but a given font size of 12pt should remain the same? Isn't it right?
What if I am told by the journal to use a font size of 12pt, how can I be sure which one is right to use. Please advise me.

A: You should set the footnotemarker with the optional argument of \author:
 \documentclass[12pt]{article}
 \usepackage{newtxtext,newtxmath,lipsum}
 \usepackage{authblk}
 \renewcommand{\Affilfont}{\footnotesize}
 \renewcommand{\Authfont}{\normalsize}
 \renewcommand\Authands{, }
 \begin{document}
\title{\textbf{Preparation of Papers for IEEE Sponsored Conferences \& Symposia}}
\author[a]{Navdeep Singh}
\author[b]{Lakhwinder Kaur}
\author[c]{Kuldeep Singh}
\affil[a,b]{Dept. of Computer Science \& Engg., Punjabi University, Patiala, 147001, Punjab}
\affil[c]{Bharat Electronics Ltd, Ghaziabad, U.P, India}
\date{}
\maketitle

\lipsum
\end{document}

The title is larger than 12pt.


Q: Working with array as table and employee hours and salaries I need help with an array that shows a list of employees, their hours, their wage and then totals the pay for each employee and then totals the hours for all employee's hours, wages and total employee pay. I have code so far as:
import java.util .*;
public class Employee
{
    public static void main(String[] args)
{
String wages[][] =
    {
        {"Emp", " " , "Hours", " ", "Wages", " ", "Total Pay"},
        {"Bobby", " ", "45", " ", "35"},
        {"Rick", " ", "15", " ",  "33"},
        {"Mike", " ", "66", " ", "50"},
        {"Jayme", " ", "15", " ",  "45"},
        {"Total", " ", " ", " ", " ", " "}
    };
  for (int i = 0; i < wages.length; i++)
  {
for (int j = 0; j < wages[i].length; j++)
{
    System.out.print(wages[i][j]);
}
System.out.println();

 }
          Integer H1 = Integer.valueOf(wages[1][2]);
          Integer H2 = Integer.valueOf(wages[2][2]);
          Integer H3 = Integer.valueOf(wages[3][2]);
          Integer H4 = Integer.valueOf(wages[4][2]);

          int sumH = 0;

          sumH = H1 + H2 + H3 + H4;

  System.out.println();
  System.out.println("The Sum of All Employee Hours is: " + sumH);

          Integer W1 = Integer.valueOf(wages[1][4]);
          Integer W2 = Integer.valueOf(wages[2][4]);
          Integer W3 = Integer.valueOf(wages[3][4]);
          Integer W4 = Integer.valueOf(wages[4][4]);

          double over = 0;
          double  totalPay1 = 0;

          if (H1 <= 40)
          {
        totalPay1 = W1 * H1;
          }
            else
              {

                 totalPay1 = (W1 * H1)  + ((H1- 40 ) * (W1 * 1.5));
               }

        double  totalPay2 = 0;

          if (H2 <= 40)
          {
        totalPay2 = W2 * H2;
          }
            else
              {

                 totalPay2 = (W2 * H2)  + ((H2) * (W2 * 1.5));
               }

        double  totalPay3 = 0;

          if (H3 <= 40)
          {
        totalPay3 = W3 * H3;
          }
            else
              {

                 totalPay3 = (W3 * H3)  + ((H3) * (W3 * 1.5));
               }

        double  totalPay4 = 0;

          if (H4 <= 40)
          {
        totalPay4 = W4 * H4;
          }
            else
              {

                 totalPay4 = (W4 * H4)  + ((H4) * (W4 * 1.5));
               }

      double grandTotal = 0;

      grandTotal = totalPay1 + totalPay2 + totalPay3 + totalPay4;

      System.out.printf("The total number of Pay is $%.2f.%n", grandTotal);

      //Bobby's totalPay1

          double bobbyTotal = (double) 0;

          bobbyTotal = totalPay1;

          System.out.printf("Bobby's total pay is $%.2f.%n", bobbyTotal);

        //Ricks Total
          double rickTotal = (double) 0;

          rickTotal = totalPay2;

          System.out.printf("Rick's total pay is $%.2f.%n", rickTotal);

            //Mikes Total
          double mikeTotal = (double) 0;

          mikeTotal = totalPay3;

          System.out.printf("Mike's total pay is $%.2f.%n", mikeTotal);

            //Jaymes Total
          double jaymeTotal = (double) 0;

          jaymeTotal = totalPay4;

          System.out.printf("Jayme's total pay is $%.2f.%n", jaymeTotal);
   }

 }

I need to be able to print the totals for each employee as the last column in the array [x][6]
I was able to print them out but I want it to look more like a a table. Along with that my formulas might be off because I don't think it's factoring in overtime right. I think there might be something wrong with my IF ELSE  statement.
The array should print out like
Emp   Hours   Wage   Total
Bobby  45       35          $1662.50
Rick      15       33          $495.00
Mike     66        50          $3,950.00
Jayme   15       45         $675.00
Total      141    163         $6,782.50

What I've got is:
Emp Hours Wages Total Pay
Bobby 45 35
Rick 15 33
Mike 66 50
Jayme 15 45
Total

The Sum of All Employee Hours is: 141
The total number of Pay is $11257.50.
Bobby's total pay is $1837.50.
Rick's total pay is $495.00.
Mike's total pay is $8250.00.
Jayme's total pay is $675.00

A: Using a class rather than a String[]
We identified that each employee has name, hours, wage, total values, instead of representing this in a String[], we can use a class
class Employee{

   private String name;
   private int hours;
   private int wage;
   private int total;

   public Employee(String name, int hours, int wage){
       this.name = name;
       this.hours = hours;
       this.wage = wage;
       this.total = hours * wage;
   }

   public String getName(){
       return name;
   }

   public int getHours(){
       return hours;
   }

   public int getWage(){
       return wage;
   }

   public int getTotal(){
      return total;
   }

   public String toString(){
       return String.format("%s %d %d %d", name, hours, wage, total);
   }
}

Now we have defined how an Employee looks like, so now we can use Employee
Putting the Employee into a List
public class EmployeeData{
    public static void main(String[] args){
       List<Employee> employees = new ArrayList<Employee>();

       Employee bobby = new Employee("Bobby", 45, 35);
       Employee rick = new Employee("Rick", 15, 33);
       Employee mike = new Employee("Mike", 66, 50);
       Employee jayme = new Employee("Jayme", 15, 45);

       employees.add(bobby);
       employees.add(rick);
       employees.add(mike);
       employees.add(jayme);

       //Now we have added all the employees, so we can just run through them
       System.out.println("Employee Hours Wage Total");
       for(Employee employee: employees){
          System.out.println(employee.toString());
       }
    }
}

Now you don't have to calculate everything many times, but just run through the list once, if you want to change the total, then you can calculate it inside here
public Employee(String name, int hours, int wage){
    this.name = name;
    this.hours = hours;
    this.wage = wage;
    this.total = hours * wage;
}


Q: What does Google Earth Engine's image.unmix() differentiate from other implementations? I want to realize a project with spectrally unmixed Landsat imagery. However, I find no satisfying information on the respective GEE function, image.unmix().
I processed a few scenes with the exact same three endmembers both in GEE and with the help of RSToolbox package's mesma() function in R. The results differ largely, with mesma() looking quite more promising.
I cannot compare to the widely used ENVI function right now, but it seems that there is strong differences in implementations.
I am not even sure if they all three could classify as Multiple Endmember Spectral Mixture Analysis (MESMA) or if I'm comparing apples with oranges here.
The GEE help file linked at the top quotes:

For more flexible methods, see the Array Transformations page

I fear, I don't quite understand what Array Transformations are capable of and how they are used. How would I build my own unmix() with these and would it enhance my results?
Can anybody could shed light on potential differences and the exact functionality of the GEE implementation?


Q: WSDL UNKNOWN for input/output I've recently started developing a SOAP web service but running through some issues I can't resolve. So I've built a PHP client to test out the service. When I invoke __getFunctions using soapclient through my php script, I receive the following
array(1) { [0]=> string(31) "UNKNOWN doOrder(UNKNOWN $order)" }

Why are my input and output data types unknown?
WSDL:
<?xml version="1.0"?>
<definitions name="PlaceOrders"
         targetNamespace="urn:PlaceOrders"
         xmlns:tns="urn:PlaceOrders"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
         xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
         xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
         xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
         xmlns="http://schemas.xmlsoap.org/wsdl/">
<types>
<xsd:schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:Orders">
  <xsd:element name="orderXML" type="xsd:base64Binary" />
  <xsd:element name="orderResponse" type="xsd:string" />
</xsd:schema>
</types>

<message name="doOrder">
<part name="order" type="tns:orderXML" />
</message>

<message name="doOrderResponse">
<part name="return" type="tns:orderResponse" />
</message>

<portType name="OrderPort">
  <operation name="doOrder">
    <input message="tns:doOrder" />
    <output message="tns:doOrderResponse" />
  </operation>
</portType>

<binding name="OrderBinding" type="tns:OrderPort">
  <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="doOrder">
  <soap:operation soapAction="urn:OrderAction" />
  <input>
    <soap:body use="encoded" namespace="urn:Orders" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
  </input>
  <output>
    <soap:body use="literal" namespace="urn:Orders" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
  </output>
</operation>
</binding>

<service name="OrderService">
<port name="OrderPort" binding="tns:OrderBinding">
  <soap:address location="[MYLINK]" />
</port>
</service>

</definitions>

SOAP Client:
ini_set('display_errors',1);
ini_set('soap.wsdl_cache_enabled', 0);
$client = new SoapClient([MYLINK]);
var_dump($client->__getFunctions());


Q: JPA/Hibernate How to add duplicate values to a List<> with a @OneToMany mapping I am getting an error every time I try to add duplicate products to the Client class.
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "uk_8opk6otadh2pkvi9bghguwp89"
  Detail: Key (products_id)=(500010) already exists.

My entities
@Entity
public class Client {
    @Id
    private String id;

    @OneToMany
    private List<Product> products;
}

@Entity
public class Product {
    @Id
    private String id;

    private Boolean foreign;
    private Integer price;
}

When I call .save() hibernate is trying to re-save an already existing Product. I believe this is due to the how it cascades things.
public Client addNewProduct(Client client, Product newProduct) {
    List<Product> products = client.getProducts();
    products.add(newProduct);
    client.setProducts(products);
    return clientRepository.save(client);
}

I just want to be able to add duplicates to a List<>. I believe this is & should be a uni-directional relationship.

A: This does not work with your current relationship, I don't understand why you would want to add duplicates, but if you have to, then you'd have to create a new entity for that. One example would be something like this:
@Entity
public class ProductBatch {

  @Id
  private String id;

  @OneToOne
  private Product product;

  private Integer count;

  // getter & setter
}

and then you change your Client like this:
@Entity
public class Client {

    @Id
    private String id;

    @OneToMany
    private List<ProductBatch> products;
}

this makes something like this possible for your addNewProduct function:
public Client addNewProduct(Client client, Product newProduct) {
    List<ProductBatch> products = client.getProducts();
    boolean exists = false;
    for(ProductBatch product : products) {
        if(product.getProduct().equals(newProduct)) {
            product.setCount(product.getCount() + 1);
            exists = true;
        }
    }
    if(!exists) {
        BatchProduct product = new BatchProduct();
        product.setProduct(newProduct);
        product.setCount(0);
        products.add(product);
    }
    client.setProducts(products);
    return clientRepository.save(client);
}

A: That has nothing to do with JPA or Hibernate. A constraint is a Database constraint and it is right. If a Foreign Key is already part of the table, trying to add it again, violates this constraint. An ID is unique and it should stay that way. So adding duplicates (at least with the same ID) will not work.


Q: Numeros aleatorios sin repeticion asignando valores de una pestaña a parte Éste es un codigo el cual coge de una lista de números de otra pestaña una celda aleatoria de tal celda a tal celda, el problema es que vuelve a repetirse los mismos numeros y necesitaria que fueses sólo una vez asignados.
  for( var contador = rango_min; contador <= numcouriers;contador++){

    if(SpreadsheetApp.getActiveSheet().getRange("V5!D"+ contador).getValue()!=" - "){
      const valor = SpreadsheetApp.getActiveSheet().getRange("V5!D"+ contador).getValue();
        if(valor.slice(0,1) === "8" || valor.slice(0,1) === "9" || valor.slice(0,2) === "10"|| valor.slice(0,2) === "11"|| valor.slice(0,2) === "12"){

        var cell = sheet.getRange("E" + contadorlu);
        var value = Math.floor((Math.random()*(rango_max - rango_min)) + rango_min);
        cell.setValue(value);

       }
       else if(valor.slice(0,2) === "13" || valor.slice(0,2) === "14" || valor.slice(0,2) === "15"|| valor.slice(0,2) === "16"|| valor.slice(0,2) === "17" || valor.slice(0,2) === "18" || valor.slice(0,2) === "19" || valor.slice(0,2) === "20"){

        var cell = sheet.getRange("E" + contadorlu);
        var value = Math.floor((Math.random()*(rango_max - rango_min)) + rango_min);
        cell.setValue(value)
       }
    }
      else if(SpreadsheetApp.getActiveSheet().getRange("V5!D"+ contador).getValue()==" - "){
      var cell = sheet.getRange("E" + contadorlu);
      cell.setValue("-");

     }
      contadorlu = contadorlu + 1;
   }

Mi idea era meter el valor escogido en un array y borrarlo de la celda y al finalizar escribir todos de nuevo en la pestaña que escoge los numeros pero aunque me los borre os números si que me vuelve a repetir.
Alguna idea por favor?
Gracias


Q: Javascript ! and !! differences
Possible Duplicate:
What is the !! operator in JavaScript?

What is the difference between these two operators? Does !! have special meaning, or does it simply mean you are doing two '!' operations. I know there are "Truth" and "Truthy" concepts in Javascript, but I'm not sure if !! is meant for "Truth"

A: !! is just double !
!true // -> false
!!true // -> true

!! is a common way to cast something to boolean value
!!{}  // -> true
!!null // -> false

A: Writing !! is a common way of converting a "truthy" or "falsey" variable into a genuine boolean value.
For example:
var foo = null;

if (!!foo === true) {
    // Code if foo was "truthy"
}

After the first ! is applied to foo, the value returned is true. Notting that value again makes it false, meaning the code inside the if block is not entered.


Q: O que é Mineração de Dados? Bom, o título diz tudo:

O que é Mineração de Dados?

A: Mineração de dados ou do inglês Data Mining
Desde que a informação passou a ser tão importante para a tomada de decisão os dados passaram a ser armazenados em grandes escalas. E com o volume de dados armazenados crescendo diariamente, começou a aparecer o questionamento. O que fazer com tantos dados armazenados? As técnicas tradicionais de exploração de dados não são mais adequadas para tratar a grande maioria dos repositórios. Com a finalidade de responder a esta questão, foi proposta, no final da década de 80, a Mineração de
Dados, do inglês Data Mining.
A Mineração de Dados é uma das tecnologias mais promissoras da atualidade. Um dos fatores deste sucesso é o fato de dezenas, e muitas vezes centenas de milhões de reais serem gastos pelas companhias na coleta dos dados e, no entanto, nenhuma informação útil é identificada. Em seu trabalho, Han (2006) em seu livro refere-se a essa situação como "rico em dados, pobre em informação". Além da iniciativa privada, o setor público e o terceiro setor (ONGt’s) também podem se beneficiar com a Mineração de Dados.
Mineração de dados não é apenas usado pelo Bitcoin, mas Segundo Witten e Bramer podem ser utilizados em algumas das áreas de forma satisfatória, como:

*

*Retenção de clientes: identificação de perfis para determinados
produtos, venda cruzada;

*Bancos: identificar padrões para auxiliar no gerenciamento de
relacionamento com o cliente;

*Cartão de Crédito: identificar segmentos de mercado, identificar
padrões de rotatividade;

*Cobrança: detecção de fraudes;

*Telemarketing: acesso facilitado aos dados do cliente;

*Medicina: indicação de diagnósticos mais precisos;

*Segurança: na detecção de atividades terroristas e criminais;

*Tomada de Decisão: filtrar as informações relevantes, fornecer
indicadores de probabilidade.

*Um supermercado melhore a disposição de seus produtos nas
prateleiras, através do padrão de consumo de seus clientes;

Mas mineração de dados funciona na prática?
A mineração de dados é utilizado em grandes quantidades de dados e usa análises matemática para derivar anomalias, padrões e correlações, captando apenas o que é relevante, através de uma educação prévia da ferramenta. As empresas utilizam esta tecnologia para suportar a tomada de decisões e proporcionar vantagens estratégicas. Usando uma ampla variedade de técnicas, você pode utilizar estas informações para aumentar as receitas, reduzir custos, melhorar o relacionamento com os clientes, reduzir riscos e entre outros.
O mais importante para qualquer projeto que decida usar a mineração de dados é definir claramente qual será o problema solucionado.
Segundo o site do SAS Institute

Mineração de dados é definido como uma disciplina combinada,
  representa uma variedade de métodos ou técnicas utilizadas em
  diferentes capacidades analíticas que abordam uma gama de necessidades
  organizacionais, respondem diferentes tipos de perguntas e usam
  diferentes níveis de regras para se chegar a uma decisão.

E ainda definem várias tipo de modelagem, como: Modelagem descritiva, Modelagem preditiva e Modelagem prescritiva.
Um dos padrões mais difundidos para se trabalhar com mineração de dados é o CRISP-DM (Cross-Industry Standard Processo of Data Mining), devido à vasta literatura disponível e por atualmente ser considerado o padrão de maior aceitação, segundo HAN (2006).
Como afirma Olson et al. (2008) em seu livro, o processo CRISP-DM consiste de seis fases organizadas de maneira cíclica, conforme mostra a figura abaixo. Além disto, apesar de ser composto por fases, o fluxo não é unidirecional, podendo ir e voltar entre as fases.

As fases do processo CRISP-DM, são:

*

*Entendimento dos Negócios: Nessa etapa, o foco é entender qual o
objetivo que se deseja atingir com a mineração de dados. O
entendimento do negócio irá ajudar nas próximas etapas.

*Entendimento dos Dados: As fontes fornecedoras dos dados podem vir
de diversos locais e possuírem diversos formatos. Segundo Olson et
al, após definir os objetivos, é necessário conhecer os dados
visando: Descrever de forma clara o problema; Identificar os dados
relevantes para o problema em questão; Certificar-se de que as
variáveis relevantes para o projeto não são interdependentes.
Normalmente as técnicas de agrupamento e de exploração visual também
são utilizadas nesta etapa.

*Preparação dos Dados: Devido às diversas origens possíveis, é comum que os dados não estejam preparados para que os métodos de Mineração de Dados sejam aplicados diretamente. Dependendo da qualidade desses dados, algumas ações podem ser necessárias. Este processo de limpeza dos dados geralmente envolve filtrar, combinar e preencher valores vazios.

*Modelagem: É nesta fase que as técnicas (algoritmos) de mineração serão aplicadas. A escolha da(s) técnica(s) depende dos objetivos desejados.
Mineração de Dados: Conceitos, Tarefas, Métodos e Ferramentas 5

*Avaliação: Considerada uma fase crítica do processo de mineração, nesta etapa é necessária a participação de especialistas nos dados, conhecedores do negócio e tomadores de decisão. Diversas ferramentas gráficas são utilizadas para a visualização e análise dos resultados (modelos). Testes e validações, visando obter a confiabilidade nos modelos, devem ser executados (cross validation, suplied test set, use training set, percentage split) e indicadores para auxiliar a análise dos resultados precisam ser obtidos (matriz de confusão, índice de correção
e incorreção de instâncias mineradas, estatística kappa, erro médio absoluto, erro relativo médio, precisão, F-measure, dentre outros).

*Distribuição: Após executado o modelo com os dados reais e completos é necessário que os envolvidos conheçam os resultados.

Obs.: Resposta baseada nos livros citados. Todos o conhecimento
  repassados tem como base as afirmações e conhecimento dos altores
  sobre tema


Q: Efficient iteration through AD Group Membership I'm just going to five straight in with what I have, the scenario is a little too complex to explain off the mark.
XML config:
  <Groups>
    <Group priority="1" name="testGroup1" profile="testProfile1"/>
    <Group priority="2" name="testGroup2" profile="testProfile2"/>
    <Group priority="3" name="testGroup3" profile="testProfile3"/>
    <Group priority="4" name="testGroup4" profile="testProfile4"/>
  </Groups>

Powershell:
$userProfileHash = [ordered]@{}
# Itterate through groups
foreach ($group in ($homeNode.ApplicationMethod | ? {$_.id -eq "adgroup"}).Groups.Group | Sort-Object $_.priority) {
  # Get group members, Itterate through them
  Get-ADGroupMember -Identity $group.name | ForEach-Object {
    # Add to ordered hash
    try {
      $userProfileHash.Add($($_.samaccountname),$group.profile)
    } catch {#don't want to see errors, there may be many}
  }
}

Now I'll to to explain:
To protect against a user being a member of more than 1 of the defined groups. I sort the groups by priority (in the foreach expression) and then use the hashtable rule that the key must be unique.
This ensures that each user is only added once and that they will be assigned the profile of the group they appeared in first.
I don't really like this approach, but it was the quickest of the approaches I tried: 5 Seconds with 1100 test users.
Question:
How can I speed up this code?
(there may be tens of thousands of users when this is in production)

A: Hash table operations are very efficient, and if you're getting a lot of errors due to duplicate adds you might be better off eliminating the error handling.  If you sort the priorities in descending order then you can do this:
$userProfileHash[$_.samaccountname] = $group.profile

and eliminate the Try/Catch.  Duplicate memberships will just get overwritten and the last entry written for each user will be the highest priority group profile they belong to.
Edit: the original command I posted used the += operator.  That's not correct for this application, and I've corrected the code.


Q: Javascript files getting included multiple times For some reason my javascript files are getting included in my source 12 times.  Other members of my team, using the same source, do not have this problem.
Any ideas what could cause this?

A: Have you made sure that you are precompiling all of your assets?
Try using:
bundle exec rake assets:precompile


Q: Cancelling a background worker without worker.CancellationPending check? I have a Validator class which has a Validate function, This validate function loops over bunch of file and validates them. User can cancel the validate process.
For cancelling the back ground worker I need ta reference of the background worker instance in Validtor class (for cancelling the validation process) and call CancellationPending on it.
But the problem is  Validator class can't have reference to background worker because there are times when we call the "Validate" function synchronously and Validator class does not have to know this.
So far  I have tried replacing  backgroundworker.CancellationPending check with some flag e.g. IsCanceled which do not seems to work.

A: You have two options:

*

*Make two overloads of the Validate method. One that is synchronous and one that is asynchronous and cancellable.

*Change your Validate method so that the calling code is responsible for looping over the files (consider an iterator method, using yield)

I'd go with option 1 as it is a smaller change.


Q: How to use std::chrono::milliseconds as a default parameter Scenario
I have a C++ function which intakes a parameter as std::chrono::milliseconds. It is basically a timeout value. And, it is a default parameter set to some value by default.
Code
#include <iostream>
#include <chrono>

void Fun(const std::chrono::milliseconds someTimeout = std::chrono::milliseconds(100)) {
    if (someTimeout > 0) {
        std::cout << "someNumberInMillis is: " << someNumberInMillis.count() << std::endl;
    }
}

int main() {
    unsigned int someValue = 500;
    Fun(std::chrono::milliseconds(someValue))
}

Issue
All of above is okay but, when I call Fun with a value then fails to compile and I get the following error:

No viable conversion from 'bool' to 'std::chrono::milliseconds' (aka
  'duration >')

Question:
What am I doing wrong here? I want the caller of Fun to be explicitly aware that it is using std::chrono::milliseconds when it invokes Fun. But the compiler doesn't seem to allow using std::chrono::milliseconds as a parameter?
How use std::chrono::milliseconds as a default parameter?
Environment
Compiler used is clang on macOS High Sierra

A: With the other syntax errors fixed, this compiles without warnings in GCC 9:
#include <iostream>
#include <chrono>

void Fun(const std::chrono::milliseconds someNumberInMillis
                                         = std::chrono::milliseconds(100))
{
    if (someNumberInMillis > std::chrono::milliseconds{0}) {
        std::cout << "someNumberInMillis is: " << someNumberInMillis.count()
                  << std::endl;
    }
}

int main()
{
    unsigned int someValue = 500;
    Fun(std::chrono::milliseconds(someValue));
}


Q: disconnected set in Zariski topology Suppose that $V$ is a nonempty affine algebraic set. If $k[V]$ is the direct sum of two non-zero ideals, prove that V is disconnected in the Zariski topology.
I am preparing for the midterm, and I stuck on this problem.
If $k[V]=\frac{k[A^n]}{I(V)}=A+B$ sum of ideals then how can I connect that with connectedness of set $V$?
Thank you!


Q: use gruntjs in root file my file tree
|-  root
|-- gruntfile.js
|-- package.json
|-- lib (jQuery & other)
|-- webapp
|---- App-1
|------- src(app src)
|---------- js
|---------- css
|---------- images
|------- package.json(use to require other modules)
|---- App-2
|------- src(app src)
|---------- js
|---------- css
|---------- images
|------- package.json(use to require other modules)
... ...
|---- App-n

In my file system,most app use a same task.Make gruntfile in every "App" file is not easy.
so,how can i use a gruntfile on "root",and use it on my "App" file?
thanks~:)

A: Unless all your apps are going to be exactly the same, use a new gruntfile for each app. I'm guessing each of your apps will all be different as you've duplicated the src folder within each in anticipation.
I don't recommend a global dependency setup. As time goes on, each of your apps will diverge and the amount of your apps will increase. When it comes time to upgrade jQuery or any other dependency in your root/lib folder... you will be forced to upgrade every single app.
The small convenience now is totally not worth it later.
Instead, just install everything locally and then you can upgrade each app as needed without breaking the other apps. If you come across duplicate code in your apps, consider moving it into a module. Create your module just like another app, then type npm link to make it installable. Then in each of your apps do npm link mymodule to install your module to the node_modules/mymodule folder. Here is an example file tree:
my file tree
|-  root
|-- devmodules
|---- mymodule
|------ index.js
|------ package.json
|-- webapps
|---- App-1
|------- src(app src)
|---------- js
|---------- css
|---------- images
|------- node_modules (jQuery & other)
|------- Gruntfile.js
|------- package.json(use to require other modules)
|---- App-2
|------- src(app src)
|---------- js
|---------- css
|---------- images
|------- node_modules (jQuery & other)
|------- Gruntfile.js
|------- package.json(use to require other modules)
... ...
|---- App-n


Q: Difference between reading PORT and PIN What is the difference between reading PORTA and PINA?
What is the relation between a port and its pins?I'm really confused!!!
sample of reading PORT:(reading pin is not useful here)
Assembly
f=1MHZ
ATmega8
I need to complement PORTB every 1ms.(Dutycycle=50%)
    LDI R16,$FF
    OUT DDRB,R16
    MAIN: LDI R16,00
    DELAY:CPI R16,200
    BREQ LOOP
    INC R16
    RJMP DELAY
    loop:IN R17,PORTB
    COM R17
    OUT PORTB,R17
    OUT R17,PORTB
    RJMP MAIN

A: I agree with DrFriedParts answer completely, however, I do want to add that, you can indeed read PORT to find out whether the port/pin is configured as OUTPUT high or low (when DDR = 1, port/pin configured as output) or whether the internal pullup resistor is activated (when DDR = 0, port/pin configured as input). In this way a port port can be used (in a rather silly way) as general storage or to pass information about the state of the output/input pullups, as in the following scenario
Perhaps one part of your program writes something to ports or activates/deactivates pullups, and the other part of the program reads PORT to find out how it is configured. Reading PORT immediately after writing PORT does not make sense: having written to PORT, you know what the value of PORT is.

A: PORT is the OUTPUT buffer, PIN is the INPUT buffer.
When you want to set the pin to a "high" or "low" voltage, write to the PORT register.
When you want to know what voltage is currently presented to a pin, read the PIN register.
The bits of these registers represent the corresponding pins of the general-purpose input/output port.
Here is a simplified schematic of the electronics inside the AVR connected to a single pin (go here for complete datasheets).
This circuit block is repeated for each pin. Eight of these form a port (port A, for example).

Starting at the left-most square (which represents the physical connection to the outside world), you can see three paths:

*

*The upper-most path is the software selectable pull-up resistor

*The middle path is used when the pin is configured as an output

*The lowest path is used when the pin is configured as an input
It should be noted that some or all of this circuitry can be bypassed when the pin is shared with an internal peripheral. For example, the Analog-to-Digital Converter (ADC).

A: For your purposes, reading from PORT actually makes sense: The pins in question are output pins, and you simply want to read the last value you wrote, toggle it, and write it back. So you’re using the port register as a byte of externally observable RAM.
On the other hand, for this particular app, you could simply just keep the value in a register and wouldn’t even have to read back the PORT register.


Q: Aggregate by name and average value per day in SQL I have data of the following format in a table (I have only shown values for two hours, but in reality I have values for all 24 hours):
Name    Availability           Date             ItemID
--------------------------------------------------------
S1          75        2014-11-11 19:00:00.000   1124023
S1          80        2014-11-11 20:00:00.000   1124023
S2          60        2014-11-11 19:00:00.000   1124010
S2          50        2014-11-11 20:00:00.000   1124010

I would like to get the average availability for the entire day in the following format in a view:
Name    Availability       Date     ItemID
--------------------------------------------------------
S1         77.5         2014-11-11  1124023
S2          55          2014-11-11  1124010

It's okay if Date in the output shows up as 2014-11-11 0:00:00.000 as well.
I tried the following, but it doesn't work. Any help would be greatly appreciated.
SELECT Name, AVG(Availability), CAST(FLOOR(CAST(Date AS FLOAT)) AS DATETIME) AS Expr1, ItemID
    FROM dbo.ServiceAvailability
    GROUP BY CAST(FLOOR(CAST(Date AS FLOAT)) AS DATETIME)

A: Your current query is very close, you are missing a few columns in your GROUP BY clause. I'd also suggest a shorter way to get the date without time.
SELECT
  Name,
  AVG(cast(Availability as decimal(10, 2))),
  CAST([Date] as date) AS Expr1,
  ItemID
FROM dbo.ServiceAvailability
GROUP BY Name, CAST([Date] as date), ItemID

See Demo. Since you are using SQL Server 2014, you can just cast your datetime column as a date - which drops the time portion.  I'd also suggest casting your Availability column to something other than an int so you get a decimal.
Since you are using an aggregate function any columns in the SELECT list that aren't being aggregated need to be included in the GROUP BY clause, so you need to include Name and ItemID.


Q: Why the Callout option makes plotting performance poor Bug introduced in 11.0 and fixed in 11.1

The Callout option is a new option for plotting, but the performance is very poor, see bellow testing case.
num = 1000;
list = N@Sin@Range[num];
list2 = ReplacePart[list,num->Callout[Last@list,Last@list]];

GraphicsRow[{ListLinePlot@list // Timing,
ListLinePlot@list2 // Timing}, ImageSize -> Large]

output shows as:

it spends more times running time when data plotting option Callout is used. I just wonder why?


Q: Silverlight 4.0 - image cropping with mouse events I have a task to build image cropping functionality in Silverlight 4.0 application. What I need to do is to have user on the left button mouse click select area to remain after cropping is applied and then call some other event (button click maybe) to apply that cropping itself.
I did develop similar functionality for rotation. I am pretty sure it is possible to do for cropping as well but that task is probably rare at this point for I can't find tutorials on the topic in the net.
If you guys can get me a snippet to begin with or point to some good tutorial about Silverlight 4.0 image cropping, I would appreciate it.
Thanks!

A: As far as cropping images are concerned you can use the WriteableBitmapEx library on codeplex.
Now you just need to draw a rectangle on a canvas containing the image to describe the crop region.


Q: TIdTCPServer gets stuck when connecting the second time I am using TIdTCPClient to get a file list all works well but when i close the client application and open it again i don't receive any event on TCPServer onExecute though the TIdTCPClient successfully connects to it and i am not able to send the file list.
What am i doing wrong ?
Some code :
procedure TTaifun.csConnected(Sender: TObject);
begin
  cs.IOHandler.WriteLn('FILE_LIST|NOW'); //Sending a request to server for the files
  fname := cs.IOHandler.ReadLn(nil); //Got the file names
  files := ExplodeString(fname,'|'); // Parse the files
end;

procedure TTaifun.svExecute(AContext: TIdContext);
var
  cmds, flist: TStringList;
  i: Integer;
  tmp: string;
  FS : TFileStream;
begin
  CSection.Enter; //Enter critical section
  cmds := ExplodeString(AContext.Connection.IOHandler.ReadLn(nil), '|');
  try
    if cmds[0] = 'FILE_LIST' then //Check command received
    begin
      flist := TStringList.Create;
      flist.LoadFromFile(MyPath + 'files.dat');
      tmp := '';
      for i := 0 to flist.Count - 1 do
      begin
          tmp := tmp + flist[i] + ',' + GetFileSize(flist[i]) + ',' +
          BoolToStr(FileExists(MyPath + 'Thumbs\' +
          ChangeFileExt(ExtractFileName(flist[i]), '.thb')),true) + '|'; //Do some parsing
      end;
      AContext.Connection.IOHandler.WriteLn(tmp); //Send the string
    end
 finally
  CSection.Leave; //Leave critical section
 end;
end;

A: You are not protecting your critical section from exceptions.  When the client disconnects, an exception will be raised by either ReadLn() or WriteLn() (depending on timing) to terminate the thread for that client.  The next time the OnExecute event is called for a different thread, the critical section will still be locked and cannot be re-entered again, deadlocking your code.  Add a try/finally to your code to guard against that, eg:
procedure TTaifun.svExecute(AContext: TIdContext);
var
  ...
begin
  CSection.Enter; //Enter critical section
  try
    ...
  finally
    CSection.Leave; //Leave critical section
  end;
end;

With that said, why are you using a critical section to begin with?  The code you showed is thread-safe by itself, it does not need to be protected from concurrent access:
procedure TTaifun.svExecute(AContext: TIdContext);
var
  cmds, flist: TStringList;
  i: Integer;
  tmp: string;
begin
  cmds := ExplodeString(AContext.Connection.IOHandler.ReadLn, '|');
  if cmds[0] = 'FILE_LIST' then //Check command received
  begin
    tmp := '';
    flist := TStringList.Create;
    try
      flist.LoadFromFile(MyPath + 'files.dat');
      for i := 0 to flist.Count - 1 do
      begin
        tmp := tmp + flist[i] + ',' + GetFileSize(flist[i]) + ',' +
          BoolToStr(FileExists(MyPath + 'Thumbs\' +
          ChangeFileExt(ExtractFileName(flist[i]), '.thb')),true) + '|'; //Do some parsing
      end;
    finally
      flist.Free;
    end;
    AContext.Connection.IOHandler.WriteLn(tmp); //Send the string
  end;
end;

Alternatively:
procedure TTaifun.svExecute(AContext: TIdContext);
var
  cmds, flist: TStringList;
  i: Integer;
begin
  cmds := ExplodeString(AContext.Connection.IOHandler.ReadLn, '|');
  if cmds[0] = 'FILE_LIST' then //Check command received
  begin
    flist := TStringList.Create;
    try
      flist.LoadFromFile(MyPath + 'files.dat');
      for i := 0 to flist.Count - 1 do
      begin
        flist[i] := flist[i] + ',' + GetFileSize(flist[i]) + ',' +
          BoolToStr(FileExists(MyPath + 'Thumbs\' +
          ChangeFileExt(ExtractFileName(flist[i]), '.thb')),true); //Do some parsing
      end;
      flist.Delimiter := '|';
      flist.StrictDelimiter := True;
      AContext.Connection.IOHandler.WriteLn(flist.DelimitedText); //Send the string
    finally
      flist.Free;
    end;
  end;
end;


Q: Why no type mismatch in call to CoCreateInstance function in the Windows API? I'm trying to translate this example of calling the WMI/COM using winapi from C++ to Rust, but there's something I don't understand in the original code. Here's a function call in the C++ code:
hres = CoCreateInstance(
        CLSID_WbemLocator,
        0,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator, (LPVOID *) &pLoc);

What puzzles me is the type of the first and fourth arguments. Take the fourth argument, for example. If we look at the definition of CoCreateInstance, the fourth argument is of type REFIID which in turn is defined as a *IID where an IID is defined as a GUID. So the fourth argument should be a pointer to a GUID object.
But if you look at what I think is the definition of IID_IWbemLocator, it's defined as a GUID (using the DEFINE_GUID macro). So it looks like we're passing a GUID as an argument when really we should be passing a pointer to a GUID. Why does this code compile?
By comparison, in Rust I have to pass a reference to IID_IWbemLocator.
Apologies if the answer is really simple, I'm pretty unfamiliar with both C++ and the Winapi.

A:
the third argument is of type REFIID which in turn is defined as a *IID where an IID is defined as a GUID. So the third argument should be a pointer to a GUID object.

The documentation you linked is incorrect. I suspect it was written for C.
In C++, REFIID and REFCLSID are defined as IID references in Windows headers, like so:
#ifdef __cplusplus
#define REFIID const IID &
#else
#define REFIID const IID * __MIDL_CONST
#endif

#ifdef __cplusplus
#define REFCLSID const IID &
#else
#define REFCLSID const IID * __MIDL_CONST
#endif


Q: replacing elements in a vector of vectors C++ i have a vector of vector that contain just periods
(".") so far and I want to replace certain coordinates on the grid with a symbol that I am taking in from an input file. I am using the replace method but keep getting this error

" error: no matching function for call to replace(std::basic_string, std::allocator >&, std::basic_string, std::allocator >&, const char [2], const char*)"

I am not sure what that error means. I appreciate any and all help. Thanks in advance
here is my code
 #include <vector>
 #include <string>
 #include <fstream>
 #include <iostream>
 #include <algorithm>

using namespace std;

int main()
{
string locationfilename, filenames,symbol;
int numRows, numCols, startRow, startCol, endRow, endCol, possRow, possCol, id;

cout<< "Enter Locations Filename"<<endl;
cin>>locationfilename;
cout<< "Enter Names Filename"<<endl;
cin>>filenames;

ifstream locations(locationfilename.c_str());
ifstream names(filenames.c_str());

locations>>numRows>>numCols>>startRow>>startCol>>endRow>>endCol;

vector <string> rows(numCols,".");
vector< vector<string> > grid(numRows,rows);

locations>>possRow>>possCol>>symbol>>id;
while(!locations.fail())
{

    if(possRow>numRows || possCol>numCols)
    {
        cout<<id<< " out of bounds-ignoring"<<endl;
    }
    else
    {
    replace(grid.at(possRow).front(),grid.at(possRow).back(),".",symbol.c_str());
    }

locations>>possRow>>possCol>>symbol>>id;
}

}

A: As pointed by Chris, the parameters you passed in std::replace are not the correct ones. std::replace expects iterators for its first two parameters but you are passing references.
You can use begin() and end() to get the iterators:
std::replace(grid.at(possRow).begin(), grid.at(possRow).end(), ".", symbol.c_str());


Q: Running header: chapter and section in same line (KOMA) I would like to have the chapter’s and section’s name appearing in the same line, one coming from the left, the other from the right end.
My solution works perfectly fine as long as the chapters and sections aren’t too long.
If this is the cause they are overlaid.
I am looking for a solution to put the section’s name in a second line if its name is too long, so it would interfere with the chapter’s name.
I am aware of Chapter title in header too long but I don’t want to use \chapter[<short title>]{<long title>} or \section[<short title>]{<long title>} since I don’t want to change the appearance in the table of contents.
Consider the following MWE:

\documentclass[
twoside=false,
open=right,
]{scrbook}
\usepackage{ragged2e}
\usepackage[
headsepline,
autooneside=false,
automark,
draft=false,
    ]{scrlayer-scrpage}
\pagestyle{scrheadings}
\clearscrheadfoot
\rofoot{\bfseries\thepage}
\automark*[subsection]{}
\addtokomafont{pageheadfoot}{\normalfont\footnotesize\sffamily}
\lohead{\RaggedRight\leftmark}
\rohead{\RaggedLeft\rightmark}

\begin{document}
\chapter{Normal chapter title in a common document}
\clearpage
\section{No problem here}
\clearpage
\section{Very big problem here since the section title is too long for the line}
\end{document}

A: You can have a short text in the header and a long text in the table of contents. You only need the option headings=optiontohead:
\documentclass[
twoside=false,
open=right,
headings=optiontohead
]{scrbook}
\usepackage{ragged2e}
\usepackage[
headsepline,
autooneside=false,
automark,
draft=false,
    ]{scrlayer-scrpage}
\pagestyle{scrheadings}
\clearscrheadfoot
\rofoot{\bfseries\thepage}
\automark*[subsection]{}
\addtokomafont{pageheadfoot}{\normalfont\footnotesize\sffamily}
\lohead{\RaggedRight\leftmark}
\rohead{\RaggedLeft\rightmark}

\begin{document}
\tableofcontents
\chapter{Normal chapter title in a common document}
\clearpage
\section{No problem here}
\clearpage
\section[short for head]{Very big problem here since the section title is too long for the line}
\end{document}

A: Here is how to calculate if it fits and then taking the decision whether to break it up. The 2em is to keep some space between the two parts.
\rohead{\sechead}
\newlength{\chaplength}
\newlength{\seclength}
\newcommand{\sechead}{%
     \settowidth{\chaplength}{\leftmark}%
     \settowidth{\seclength}{\rightmark}%
     \ifdim \dimexpr\chaplength+\seclength+2em>\textwidth
     \parbox{\dimexpr \textwidth-2em-\chaplength}{\RaggedLeft\rightmark}
     \else\RaggedLeft\rightmark\fi}


Q: How to control enumitem's description list via leftmargin and labelwidth keys I am trying to learn how to use enumitem's keys to adjust a description list.  In this case, I would like to have my list items and description text both left aligned, but the description text should all start at the same horizontal position.
What I have below comes pretty close, but it seems that the setting of \labelwidth is being ignored, and that there is some other thing I need to add to get the correct value of leftmargin.
The tabular version produces that output I want, but would prefer to use the description list from enumitem.
\documentclass{article}
\usepackage{enumitem}
\usepackage{calc}

\newcommand*{\LongDescription}{This is a  long sentence to check that when it gets wrapped it is indented properly on the next line, but doesn't seem to when used in the list.}%
\newcommand*{\ShortDescription}{A very short description.}%

\begin{document}
\newcommand*{\LargestItem}{The Largest Named Item}%
\newlength{\MaxWidth}%
\settowidth{\MaxWidth}{\LargestItem}%
\newlength{\MaxWidthPlusLabelSep}%
\setlength{\MaxWidthPlusLabelSep}{\labelsep+\MaxWidth}%

\begin{description} [leftmargin=\MaxWidthPlusLabelSep,labelwidth=\MaxWidth]
\item Small Name:
    \ShortDescription
\item The Largest Named Item: \LongDescription
\item Larger Name:
    \ShortDescription
\end{description}

\hrule\medskip

I want something like this, but should be able to do this with a list:

\bigskip
\begin{tabular}{l@{ }p{\linewidth-\MaxWidthPlusLabelSep}}
Small Name:
    &\ShortDescription\\\\
    The Largest Named Item:
    &\LongDescription\\\\
    Larger Name:
    &\ShortDescription
\end{tabular}
\end{document}

I have tried the solutions on how to Change hanging indent in description list
and How to align long labels in a list to the left margin?
but have not been able to adapt them to what I want.

A: \newenvironment{mydesc}[1]
  {\settowidth{\dimen0}{#1}%
   \renewcommand{\descriptionlabel}[1]{##1\hfill}%
   \begin{description}[leftmargin=\dimexpr\dimen0+\labelsep\relax,labelwidth=\dimen0 ]}
  {\end{description}}

\begin{mydesc}{The Largest Named Item}
\item[Small Name]
    \ShortDescription
\item[The Largest Named Item] \LongDescription
\item [Larger Name]
    \ShortDescription
\end{mydesc}

If enumitem version 3 is not available, it's possible to use a solution provided in the LaTeX Companion:
\newenvironment{mydesc}[1]
  {\list{}{\renewcommand\makelabel[1]{##1\hfil}%
     \settowidth\labelwidth{\makelabel{#1}}%
     \setlength\leftmargin{\dimexpr\labelwidth+\labelsep\relax}}}
  {\endlist}

A: With version 3.3 it's:
\begin{description}[
  leftmargin=!,     % let enumitem do the dirty job
  labelwidth=\widthof{\bfseries The Largest Named Item}]

You have to put the format of the label (here, something similar to widest would be useful, so I've added it to my todo list)


Q: Soap Request as String convert it into java object I'm getting a SOAP request as string, from which I want to extract a Java object. Is it possible? If yes, then how? What API can be used for this?

A:
I'm getting a SOAP request as string, from which I want to extract a
  Java object. Is it possible?

Yes.

If yes, then how?

You need to convert the String into something that JAXB can unmarshal.  Examples include a StringReader or XMLStreamReader.

What API can be used for this?

Since a SOAP message contains more information than what corresponds to the domain model I would recommend using JAXB with a StAX XMLStreamReader.  You use StAX to parser the String.  Then you advance the XMLStreamReader to the element that contains the content you wish to unmarshal.  Then you unmarshal the XMLStreamReader at that point.

*

*http://blog.bdoughan.com/2012/08/handle-middle-of-xml-document-with-jaxb.html


Q: PostgreSQL using constants in foreign key The syntax for Foreign Key, as described in official documentation, includes set of column from table A referencing set of column from table B.
Is it possible to use Constant in foreign key declaration?
The problem is, I have table DICTIONARIES which contains all dictionary values, discriminated by TYPE. I know it's not good design, but unfortunatelly, I have not much to say, as the DB admin wants to 'minimize the number of tables'...
Is it possible to achieve something like that:
CREATE TABLE PERSON (
  id integer primary key,
  country_id integer,
  ...
  FOREIGN KEY ('COUNTRY', country_id) REFERENCES DICTIONARIES(TYPE, ID)
)

It would effectively solve the issue. I'm aware I can add column to the table person, which will has only one possible value 'COUNTRY', or I could write a trigger, but I'd prefer to avoid that to keep design cleaner.

A: A foreign key constraint is from one table's columns to another's columns, so, no.
Of course the database should have a table COUNTRY(country_id). Commenters have pointed out that your admin is imposing an anti-pattern.
Good, you are aware that you can define a column and set it to the value you want and make the foreign key on that. That is an idiom used for avoiding triggers in constraining some subtyping schemes.
You may be able to compute a 'COUNTRY' column depending on your DBMS, at least.
Your question is essentially this one, see the end of the question & the comments & answers.
(Lots of functionality would be trivial to implement. Perhaps the difficulty (besides ignorance of consumers) is that arbitrary constraints become quickly expensive computationally. That might just get vendors aggravation. Also, optimization in SQL is impeded by its differences from the relatonal model.)

A: For Posrgres not having computed (or constant) columns, you can force them to a fixed value column, using DEFAULT plus (maybe) a check. This may be ugly, but it works:
CREATE TABLE dictionaries
  ( id integer primary key
  , typename varchar NOT NULL CHECK ( typename IN ('person' ,'animal' ,'plant' ))
  , content varchar NOT NULL
  -- ...
  , UNIQUE (typename, id)
  , UNIQUE (typename, content)
  );

CREATE TABLE person
  ( id integer primary key
  , typename varchar NOT NULL DEFAULT 'person' CHECK( typename IN ('person' ))
  , species_id integer
  -- ...
  , FOREIGN KEY (typename, species_id) REFERENCES dictionaries(typename, id) -- DEFERRABLE INITIALLY DEFERRED
);

INSERT INTO dictionaries( id, typename, content) VALUES
 ( 1 , 'person' , 'Bob')
,( 2 , 'person' , 'Alice')
,( 11 , 'animal' , 'monkey')
,( 12 , 'animal' , 'cat')
,( 13 , 'animal' , 'dog')
,( 21 , 'plant' , 'cabbage')
        ;
SELECT * FROM dictionaries;

        -- this should succeed
INSERT INTO person( id, species_id) VALUES
 ( 1,1 )
,( 2,2 )
        ;
        -- this should fail
INSERT INTO person( id, species_id) VALUES
 ( 3,11 )
,( 4,12 )
        ;


Q: CocoaPodspec unresolved identifier error I am trying to create my own framework by CocoaPodspec.
I need some help to resolve the issue.
And I got an error after run command pod lib lint --no-clean --verbose interminal :
error: use of unresolved identifier 'GlobalLoaderView'

This is Podspec file content :
Pod::Spec.new do |s|
  s.platform = :ios
  s.ios.deployment_target = '11.0'
  s.name = "HalBase"
  s.swift_version = '4.0'
  s.summary = "This is example"
  s.requires_arc = true
  s.version = "1.0"
  s.license = { :type => "MIT", :file => "LICENSE" }
  s.author = { "ntancnit@gmail.com" => "ntancnit@gmail.com" }
  s.homepage = "https://github.com/ntancnit/HalBase"
  s.source = { :git => "https://github.com/ntancnit/HalBase.git", :tag => "#{s.version}"}
  s.ios.framework = "UIKit"
  s.ios.framework = "CoreLocation"
  s.ios.framework = "Foundation"
  s.dependency 'RxSwift', '~> 4.0.0'
  s.dependency 'RxCocoa', '~> 4.0.0'
  s.dependency 'RxDataSources', '~> 3.0'
  s.dependency 'Action'
  s.dependency 'Alamofire', '~> 4.0'
  s.dependency 'AlamofireImage', '~> 3.0'
  s.dependency 'ObjectMapper', '~> 3.0'
  s.dependency 'IQKeyboardManagerSwift', '~> 5.0.0'
  s.dependency 'SVProgressHUD'
  s.dependency 'PureLayout'
  s.dependency 'KeychainAccess'
  s.source_files = "HalBase/**/*.{swift,h,m}"
  s.resources = "HalBase/**/*.{png,jpeg,jpg,storyboard,xib,plist,swift}"
end

GlobalLoaderView is my custome class inhered from UIControl.
I am using swift 4, Xcode 9.4
Thank you!


Q: Point on a finite grid graph Suppose we are on a finite 2D grid of points from $(-a,-b)$ to $(a,b)$. In the beginning, we are at the point $(0,0)$ inside the grid. How many points are there that have distance $k$ between $(0,0)$?

A: Are you asking how many vertices have distance exactly $k$ from $(0,0)$?
If so, the answer is $4k$ for any $k$ which is at least one, and less than or equal to $\min\{a,b\}$.
You can check this inductively.
Look at how the vertices at distance 2 in the grid branch out from those at distance 1.
The three red vertices in quadrant 1 ($x \geq 0$ and $y \geq 0$) are all adjacent to the two blue vertices in quadrant 1. A similar pattern holds in all four quadrants.

So let our inductive hypothesis be that the number of vertices at distance $k$ from (0,0) in any single quadrant is $k+1$. (This is true for $k=1$, so we have a base case).
Now let's prove it for distance $k+1$.
Let's first assume we are in the first quadrant. Each vertex at distance $k$ (of which there are k+1 by assumption) has exactly 1 neighbour, directly above it, at distance $k+1$.
But, there is also one extra neighbour. The vertex at distance $k$ on the x-axis has a neighbour at distance $k+1$ directly to the right (see the figure below, the 'extra' neighbour to the right has a little + next to it).
Thus in quadrant 1, there are $k+2$ vertices at distance $k+1$ from (0,0).
This proof works for the other quadrants by 'rotating' the argument, as shown in the figure below.
This completes the proof by induction that each quadrant contains $k+1$ vertices at distance $k$ from $(0,0)$.
Note that the vertices on the axes get double-counted, as they lie in two quadrants.
We know each quadrant has $k+1$ vertices at distance $k$, and there are 4 quadrants, with 4 vertices double-counted, so the total number of vertices at distance $k$ is
$4(k+1) - 4 = 4k$.


Q: How to take screen shot of a web page in PHP and show it in model popup and submit it into database function screenshot(){
       html2canvas(document.body).then(function(canvas) {

         //document.body.appendChild(canvas);

         // Get base64URL
         var base64URL = canvas.toDataURL('').replace( 'image/octet-stream');

         // AJAX request
      $.ajax({
            url: 'screen_shot.php',
            type: 'post',
            data: {image: base64URL},

            success: function(data){
               alert('Upload successfully');
            }
         });
       });
    }

A: 1) You can use HTML5 & javaScript to take screenshots. This will work for sure. check more details
here
(function (exports) {
    function urlsToAbsolute(nodeList) {
        if (!nodeList.length) {
            return [];
        }
        var attrName = 'href';
        if (nodeList[0].__proto__ === HTMLImageElement.prototype
        || nodeList[0].__proto__ === HTMLScriptElement.prototype) {
            attrName = 'src';
        }
        nodeList = [].map.call(nodeList, function (el, i) {
            var attr = el.getAttribute(attrName);
            if (!attr) {
                return;
            }
            var absURL = /^(https?|data):/i.test(attr);
            if (absURL) {
                return el;
            } else {
                return el;
            }
        });
        return nodeList;
    }

    function screenshotPage() {
        urlsToAbsolute(document.images);
        urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
        var screenshot = document.documentElement.cloneNode(true);
        var b = document.createElement('base');
        b.href = document.location.protocol + '//' + location.host;
        var head = screenshot.querySelector('head');
        head.insertBefore(b, head.firstChild);
        screenshot.style.pointerEvents = 'none';
        screenshot.style.overflow = 'hidden';
        screenshot.style.webkitUserSelect = 'none';
        screenshot.style.mozUserSelect = 'none';
        screenshot.style.msUserSelect = 'none';
        screenshot.style.oUserSelect = 'none';
        screenshot.style.userSelect = 'none';
        screenshot.dataset.scrollX = window.scrollX;
        screenshot.dataset.scrollY = window.scrollY;
        var script = document.createElement('script');
        script.textContent = '(' + addOnPageLoad_.toString() + ')();';
        screenshot.querySelector('body').appendChild(script);
        var blob = new Blob([screenshot.outerHTML], {
            type: 'text/html'
        });
        return blob;
    }

    function addOnPageLoad_() {
        window.addEventListener('DOMContentLoaded', function (e) {
            var scrollX = document.documentElement.dataset.scrollX || 0;
            var scrollY = document.documentElement.dataset.scrollY || 0;
            window.scrollTo(scrollX, scrollY);
        });
    }

    function generate() {
        window.URL = window.URL || window.webkitURL;
        window.open(window.URL.createObjectURL(screenshotPage()));
    }
    exports.screenshotPage = screenshotPage;
    exports.generate = generate;
})(window);

2) You can also use html2canvas below is the simple example of how to implement.
JS
  html2canvas(document.querySelector("#capture")).then(canvas => {
        document.body.appendChild(canvas)
    });

HTML

Hello world!

download & include in the head section
//*

//*


Q: Linear version of Gronwall's inequality, proof I am reading a proof of the following theorem:
Assume $\phi$ is a continuous function in $[0,T]$ that satisfies $$\phi(t) = \alpha + \int_0^t (\beta \phi(s) + \gamma)ds, \hspace{0.5mm} t\in [0,T], $$ where $\alpha, \gamma \in \mathbb{R}$ and $\beta > 0$. Then $$\phi(t) \leq \alpha e^{\beta t} + \frac{\gamma}{\beta}(e^{\beta t} - 1), \hspace{0.5mm} t\in [0,T]. $$
The proof begins by setting $$\psi(t) = \alpha + \int_0^t (\beta \phi(s) + \gamma)ds,  $$ in order to obtain $$\psi'(t) \leq \beta \psi(t) + \gamma \implies \psi'(t) - \beta \psi(t) \leq \gamma \implies  \left(e^{-\beta t} \psi(t) \right)' \leq \gamma e^{-\beta t}. $$
After this, it says that this implies that $e^{-\beta t} \psi(t) - \psi(0) \leq \frac{\gamma}{\beta}(1-e^{-\beta t}), $ and this is what confuses me.
I think that $$\left(e^{-\beta t} \psi(t) \right)' \leq \gamma e^{-\beta t} \implies e^{-\beta t} \psi(t) \leq -\frac{\gamma}{\beta}e^{-\beta t}, $$ but does subtracting $\psi(0) = \alpha$ on the left-hand side somehow correspond to adding $\gamma / \beta$ on the right-hand side? I don't see how it would.
UPDATE
Could it be that I have to integrate $\gamma e^{-\beta t} $ from $0$ to $t$? Because then that would be $\frac{\gamma}{\beta}(1-e^{-\beta t})$. But then I am still confused about what allows us to subtract $\psi(0)$ from the left-hand side.


Q: Differences between query using LINQ and IQueryable interface directly? Using Entity Framework 4, and given:
ObjectSet<Thing> AllThings = Context.CreateObjectSet<Thing>;

public IQueryable<Thing> ByNameA(String name)
{
    IQueryable<Thing> query =  from o in AllThings
                               where o.Name == name
                               select o;
    return query;
}

public IQueryable<Thing> ByNameB(String name)
{
    return AllThings.Where((o) => o.Name == name);
}

Both return IQueryable<> instances, and thus the query doesn't hit the server until something like ToList() is called, right? Is it purely readability that is the difference, or are the using fundamentally different technologies on the back-end?

A: These compile to nearly identical code.
The first syntax translates directly, by the compiler, into methods with the names provided in the second syntax.
The main difference between these two methods is really just that you're using a different syntax, and that you're assigning to a temporary variable (query) instead of just returning the result directly.  However, they are, for all practical purposes, identical.


Q: Why is the time derivative of the magnetic field finite? One step in finding the interface conditions for electromagnetic waves involves recognizing that as $\vec{A}\rightarrow 0$, $\int_{\vec{A}}\frac{d\vec{B}}{dt}d\vec{A}=0$.  Specifically, we usually treat $A$ as a rectangle with one side begin driven to zero. This is justified as $\frac{d\vec{B}}{dt}$ is finite.
Of course, this does not hold generally. $\vec{B}$ could, for instance, be a delta function ($B = \delta(z)t$). It doesn't seem as though this is explicitly prohibited by Maxwell's equations. Do the interface conditions solely come about because, for practical purposes, we're only interested in smooth solutions?

A: Physically $dB/dt$ is finite.
But one might be interested in a case where $dB/dt$ is large enough that it cannot be neglected on the distance scale associated with an interface, such as for example the size of atoms. This can happen with X-rays, or with other wavelengths at high enough intensity. And then indeed the 'standard' continuity results do not apply.


Q: Filling content from bottom and right to left order Inside my page I have div which I want to populate with some content like it's on image. How can I do this without shrinking div content and populate inside div from bottom to up?

A: Best approach for this layout would be the Flexbox Technique
You can wrap the rows in the reverse order using wrap-reverse

$(document).ready(function() {
  $('.create').on('click', function() {
    $('.container').append('

');
  })
});
.container {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  background: #6CC4DA;
  -webkit-flex-wrap: wrap-reverse;
  -ms-flex-wrap: wrap-reverse;
  flex-wrap: wrap-reverse;
  align-items: baseline;
  align-content: flex-start;
  height: 280px;
  width: 770px;
}
.circle {
  background: #C78DEF;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  margin: 5px;
}

<button class="create">Create a circle</button>

JSfiddle

A: You can flip horizontal parent div and flip horizontal back each child block:

$(document).ready(function() {
  $(document).on('click', 'button', function() {
    var
      items = $('.content-item').size(),
      space = document.createTextNode(' ');
    $('.container').append($('
' + (items + 1) + '
')).append(space);
  });
});
.container {
  width: 400px;
  height: 200px;
  background: cyan;
  transform: ScaleY(-1);
}
.content-item {
  display: inline-block;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin: 5px;
  text-align: center;
  line-height: 50px;
  background: purple;
  color: #fff;
  transform: ScaleY(-1);
}

<button>Increase population</button>

1

2

3

4

5

6

7


Q: meteorjs -- Problems with the accounts-twitch package & OAuth2 Today, I started a new project (IRC Bot, etc.) to be used with Twitch.TV's chat servers.
I wanted to use the accounts-twitch package that I found on Atmosphere, and had to manually install it (editing the package.js file) due to a deprecated dependency on accounts-oauth2-helper.
After getting it to properly install, my app crashes on startup now.  It tosses the following error before dying, and I don't know how to fix it:
[[[[[ ~/projects/wasdbot ]]]]]

=> Started MongoDB.
=> Starting your app...

W20140605-15:22:42.283(-4)? (STDERR)
W20140605-15:22:42.350(-4)? (STDERR) /home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/fibers/future.js:173
W20140605-15:22:42.350(-4)? (STDERR)                        throw(ex);
W20140605-15:22:42.350(-4)? (STDERR)                              ^
W20140605-15:22:42.351(-4)? (STDERR) TypeError: Cannot call method 'registerService' of undefined
W20140605-15:22:42.351(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:2)
W20140605-15:22:42.351(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:82)
W20140605-15:22:42.351(-4)? (STDERR)     at packages/accounts-twitch.js:123:4
W20140605-15:22:42.351(-4)? (STDERR)     at packages/accounts-twitch.js:130:3
W20140605-15:22:42.352(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:155:10
W20140605-15:22:42.352(-4)? (STDERR)     at Array.forEach (native)
W20140605-15:22:42.352(-4)? (STDERR)     at Function._.each._.forEach (/home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/underscore/underscore.js:79:11)
W20140605-15:22:42.352(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:82:5
=> Exited with code: 8
W20140605-15:22:43.456(-4)? (STDERR)
W20140605-15:22:43.457(-4)? (STDERR) /home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/fibers/future.js:173
W20140605-15:22:43.457(-4)? (STDERR)                        throw(ex);
W20140605-15:22:43.458(-4)? (STDERR)                              ^
W20140605-15:22:43.463(-4)? (STDERR) TypeError: Cannot call method 'registerService' of undefined
W20140605-15:22:43.463(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:2)
W20140605-15:22:43.464(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:82)
W20140605-15:22:43.464(-4)? (STDERR)     at packages/accounts-twitch.js:123:4
W20140605-15:22:43.464(-4)? (STDERR)     at packages/accounts-twitch.js:130:3
W20140605-15:22:43.465(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:155:10
W20140605-15:22:43.465(-4)? (STDERR)     at Array.forEach (native)
W20140605-15:22:43.465(-4)? (STDERR)     at Function._.each._.forEach (/home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/underscore/underscore.js:79:11)
W20140605-15:22:43.466(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:82:5
=> Exited with code: 8
W20140605-15:22:44.622(-4)? (STDERR)
W20140605-15:22:44.624(-4)? (STDERR) /home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/fibers/future.js:173
W20140605-15:22:44.625(-4)? (STDERR)                        throw(ex);
W20140605-15:22:44.625(-4)? (STDERR)                              ^
W20140605-15:22:44.628(-4)? (STDERR) TypeError: Cannot call method 'registerService' of undefined
W20140605-15:22:44.629(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:2)
W20140605-15:22:44.629(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:82)
W20140605-15:22:44.630(-4)? (STDERR)     at packages/accounts-twitch.js:123:4
W20140605-15:22:44.630(-4)? (STDERR)     at packages/accounts-twitch.js:130:3
W20140605-15:22:44.630(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:155:10
W20140605-15:22:44.631(-4)? (STDERR)     at Array.forEach (native)
W20140605-15:22:44.631(-4)? (STDERR)     at Function._.each._.forEach (/home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/underscore/underscore.js:79:11)
W20140605-15:22:44.631(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:82:5
=> Exited with code: 8
=> Your application is crashing. Waiting for file change.

Seems like the problem is this call to Accounts.oauth.registerService, in twitch_server.js, but I don't really know how to go about fixing it.
I also can't seem to find anything about this oauth stuff in their API docs, anywhere, or maybe I'm looking in the wrong place, or maybe I'm missing a package that I should have included?
All I added to my project is accounts-twitch, accounts-ui, and coffeescript, as of right now.  I haven't written any code yet, just trying to fire up Meteor.
Any help would be amazing.  I really appreciate everyone's time beforehand.


Q: Mule ESB + RabbitMQ reliability and up-time: how to re-create a deleted exchange automatically at runtime I've got a Large mule application that receives on multiple queues and publishes to at least one exchange. I'm manually QA'ing the application by deleting the queues and exchanges to see if mule will retry to connect (and also shut down rabbit altogether)
This question is for when an exchange is deleted. The messages go into a locked anonymous queue named something like: amq.gen-gFs6-7sP2nw1ntgobO6cBg
I'm looking for a way to reconnect the exchange and still pass through the messages. Is this even possible?
I've set options like
exchangeDurable="true"
queueDurable="true"
Is there any other things (or rabbit configs) that I need to do or would be beneficial to me?
Next Test: Shutdown RabbitMQ in the middle of processing.
Code:

<mule xmlns:jdbc-ee="http://www.mulesoft.org/schema/mule/ee/jdbc"
xmlns:vm="http://www.mulesoft.org/schema/mule/vm"
xmlns:http="http://www.mulesoft.org/schema/mule/http"
xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:amqp="http://www.mulesoft.org/schema/mule/amqp"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.4.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml"
xmlns:file="http://www.mulesoft.org/schema/mule/file"
xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/jdbc http://www.mulesoft.org/schema/mule/ee/jdbc/current/mule-jdbc-ee.xsd
http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd
http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/amqp http://www.mulesoft.org/schema/mule/amqp/current/mule-amqp.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd"
xmlns:context="http://www.springframework.org/schema/context">

<amqp:connector name="amqpAutoAckLocalhostConnector"
      host="${config.status_reporting.host}"
      port="${config.status_reporting.port}"
      virtualHost="${config.status_reporting.virtual_host}"
      username="${config.status_reporting.username}"
      password="${config.status_reporting.password}"
      requestedHeartbeat="${config.status_reporting.requestedHeartbeat}"
      doc:name="AMQP Connector for Status Messages"/>

<flow name="send_status" doc:name="send_status">
    <vm:inbound-endpoint path="send_status" exchange-pattern="one-way" responseTimeout="10000" doc:name="VM" />
    <logger message="starting send status" level="DEBUG" doc:name="Logger"/>

    <!-- some code here has been removed for stackoverflow question -->

    <flow-ref name="cwm_send" doc:name="flow ref"/>
</flow>

<flow name="cwm_send" doc:name="cwm_send">
    <amqp:outbound-endpoint exchangeName="${config.status_reporting.exchange_name}"
                      exchangeType="topic"
                      exchangeDurable="${config.status_reporting.exchange_is_durable}"
                      routingKey="${config.status_reporting.routing_key}"
                      connector-ref="amqpAutoAckLocalhostConnector" doc:name="AMQP Out" queueDurable="true" responseTimeout="10000"/>
</flow>

<flow name="send_ingest_status" doc:name="send_ingest_status">
    <vm:inbound-endpoint exchange-pattern="request-response" responseTimeout="10000" doc:name="VM" path="send_ingest_status"/>
    <vm:outbound-endpoint path="send_status" exchange-pattern="one-way" doc:name="Send Status">
        <set-payload value="#[[
            'status_code': 'foo',
            'status_descr': 'test description.',
            'status_final': '0',
            'version': '1.0']]"/>
    </vm:outbound-endpoint>

</flow>
</mule>

Thank you.

A: This problem also seems to occur when an exchange is declared only in an outbound endpoint. There is an open bug concerning this in the Mulesoft JIRA, and you can vote for it to help them prioritize it.
I took a look at the source code, and the problem seems to be that there is simply no code to declare exchanges when an outbound endpoint is started.  In your case, you'd probably want the code to run at the time the message is sent, or maybe at the time the exchange is deleted.  This timing wouldn't be covered by the aforementioned bug, but you might open a new issue describing the use case and the desired functionality.  And a pull request would probably be even better! ;)


Q: Comportamiento inesperado con ( user-threads | fibers | coroutines ) Estoy probando libcoro, una librería muy simple y de bajo nivel que proporciona coroutines mas o menos portables. Supuestamente, es válida para sistemas en producción.
Mi código es el siguiente:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

#include "coro.h"

// Argumentos pasados a los 'thread's.
struct Arg {
  const char *message;
  coro_context coro;
  struct coro_stack stack;
};

// Datos de cada 'thread'.
// Args[0] es el 'thread' principal, en el que empezamos y que controla
// al resto.
struct Arg Args[4] = {
  { NULL, { 0 }, { 0 } },
  { "Mensaje 1", { 0 }, { 0 } },
  { "Mensaje 2", { 0 }, { 0 } },
  { "Mensaje 3", { 0 }, { 0 } }
};
// Selector del 'thread' actual; usado al planificar.
volatile int idx;

// 'cuerpo' de los 'thread's.
void body( struct Arg * );
// Manejador de la interrupcion SIGALRM.
void handler( int );

int main( void ) {
  // Reservamos la memória a usar como pila por cada 'thread',
  // y los inicializamos.
  for( idx = 1; idx < 4; ++idx ) {
    coro_stack_alloc( &( Args[idx].stack ), 0 );
    coro_create( &( Args[idx].coro ),
                 (coro_func)&body,
                 (void *)&Args[idx],
                 Args[idx].stack.sptr,
                 Args[idx].stack.ssze );
  }

  signal( SIGALRM, &handler );
  idx = 4;
  coro_create( &( Args[0].coro ), NULL, NULL, NULL, 0 );

  // Planificador.
  // Los ejecutamos en secuencia, del último al primero.
  while( --idx ) {
    printf( "Dentro del bucle. idx = %d\n", idx );
    alarm( 1 );
    coro_transfer( &( Args[0].coro ), &( Args[idx].coro ) );
  }

  printf( "Fuera del bucle. idx = %d\n", idx );
  return 0;
}

void body( struct Arg *arg ) {
  printf( "%s.\n", arg->message );
  while( 1 );
  coro_transfer( &( arg->coro ), &( Args[0].coro ) );
  printf( "Saliendo de body. idx = %d", idx );
}

void handler( int sig ) {
  (void)sig;
  coro_transfer( &( Args[idx].coro ), &( Args[0].coro ) );
}

En un código similar que usé de esqueleto, que no usaba alarm( ) ni signal( ), ni el while( 1 ) (sin forzar por tanto el cambio de tarea en el manejador de interrupciones), producía la siguiente salida:

Dentro del bucle. idx = 3
  Mensaje 3.
  Dentro del bucle. idx = 2
  Mensaje 2.
  Dentro del bucle. idx = 1
  Mensaje 1.
  Fuera del bucle. idx = 0

La salida esperada del código mostrado es la misma; los mensajes en pantalla deberían ser idénticos; no obstante, se muestra lo siguiente:

Dentro del bucle. idx = 3
  Mensaje 3.
  Dentro del bucle. idx = 2
  Mensaje 2.

Ahí se detiene, y el uso de la CPU se pone al 100%; es decir, se detiene en el while( 1 ) dentro de la función body( ); da la impresión de que no entra en la función manejadóra de la interrupción.
Estoy seguro de que el fallo está en mi lógica de funcionamiento, pero no doy con la tecla. Es raro que interrumpa el while( 1 ) 2 veces y luego deje de Hacerlo. Mi sentido común dicta que, o no lo interrumpiría nunca, o lo haría siempre.

A: Vale, ya está. Error por mi parte, al no leer correctamente la documentación de libcoro.
La librería ofrece varios backends, para usar uno u otro dependiendo de la plataforma, el sistema operativo, o por si alguno directamente no funciona.
Estaba haciendo las pruebas con el backend CORO_ASM, supuestamente de los mas rápidos en Linux. La última modificación de libcoro fué en 2016, así que asumí, erroneamente, que ese backend funcionaria en sistemas modernos.
Los he probado todos, y, en mi plataforma (Linux, x64), tan solo funciona con CORO_CONTEXT. Por los síntomas, parece que hay alguna incompatibilidad con el manejo de señales.
Ya lo avisa en la documentación:

-DCORO_ASM
Hand coded assembly, known to work only on a few architectures/ABI: GCC + arm7/x86/IA32/amd64/x86_64 + GNU/Linux and a
  few BSDs.
  Fastest choice, if it works.

La mas rápida ... si funciona.


Q: Show ajaxloader on the time of $.getJson call i want to show ajaxloader icon on the time of executing $.getJSON.
it should disappear after $.getJSON completes.
$.getJSON("url",
    function(data){
      ........
      ........
      });

A: Try this pattern:
$("#someAnimatedGif").show();
$.getJSON("url", function (data) {
    $("#someAnimatedGif").hide();
});

The animated gif will initially be hidden, and you can use JQuery to hide/show it.
The key is to show it right before you execute the Ajax call, and hide it again when the callback returns.