text:
Q: Plot and imagesc (from Matlab) with PSTricks I'd like to plot with PSTricks some data from Matlab.
I usually plot these data using the imagesc and the colorbar in Matlab, but I'd rather do it in LaTeX...
Here is the picture I want to plot in LaTeX :

It's actually plotting 2 vectors (time and velocity) and 1 array (the color), but I can't figure how to do it...
Is there a special PSTricks package to do it ? If it could read the 3 data files, I'd be simple...
If it's just a couple of commands, it's good too...
Edit : providing data files
Here are the data (all are .csv files):

*

*time is an 175x1 matrix

*velocity is an 14112x1 matrix

*tension is ans 14112x175 matrix...
I compressed them in a zip file
The data are quite huge, but an example with 10 points is good too..

A: It uses the data file from Malipivo and the pstricks-add.tex from http://texnik.dante.de/tex/generic/pstricks-add/. Run it with
latex --shell-escape <file>
dvips <file>
ps2pdf -dNOSAFER <file>.ps

shell-escape is needed to run from within the document the external texlua which creates on the fly the data file with PSTricks structure. The data files must be ibn the same directory as this document:
\documentclass{article}
\usepackage{pstricks-add}
\usepackage{filecontents}
\begin{filecontents*}{data.lua}
local c=0 -- a counter of data
print("Cashing 3 files...")
time="time.csv" -- 175
speed="speed.csv"
tension="tension.csv"
local times={}
for time in io.lines(time) do table.insert(times,time) end
local speeds={}
for speed in io.lines(speed) do table.insert(speeds,speed) end
local tensions={}
for tension in io.lines(tension) do table.insert(tensions,tension) end
topst=io.open("image.data","w")
topst:write("/contourdata [")
print("Processing "..#tensions.." lines...")
for tension=1,200 do -- #tensions or 300
  c=0
  topst:write("[\n")
  for mdata in string.gmatch(tensions[tension],"[^,]+") do
    c=c+1
    writeme=speeds[tension].." "..times[c].." "..mdata.."\n"
    topst:write(writeme)
  end
topst:write("]")
end -- for tension

topst:write("] def\n")
\end{filecontents*}

\begin{document}
\immediate\write18{texlua data.lua}
\psset{xunit=1mm,yunit=2.5}
\begin{pspicture}(0,1)(70,3.5)
\pstContour[colored,colorOffset=100 add]{image.data}
\psaxes[labelFontSize=\footnotesize,mathLabel=false,Dx=10,Dy=0.5,Oy=1,
        ticksize=-5pt 0](0,1)(70,3.5)
\multido{\rA=1.0+0.01,\iA=383+1}{250}{\psline[linecolor={[wave]\iA}](70,\rA)(75,\rA)}
\psaxes[xAxis=false,Oy=-100,Dy=3,dy=0.5,ticksize=0 4pt,ylabelPos=right](75,1)(75,3.5)
\end{pspicture}
\end{document}

A:
Partial solution

I've downloaded and unzipped your ZIP file. In that folder I created a standalone Lua script (mal-preprocess.lua) which processes those three data sets.
The output is one file suitable for PSTricks (toimage-pst.data) and one file (toimage.data) for PGFplots. I don't know how to set the graph properly in PSTricks and I'm reaching limits in PGFplots/pdflatex, therefore an enclosed example is limited from #tensions (number of lines; line 33 in the Lua code) to the first 200 entries.
I run in that folder:
texlua mal-preprocess.lua

These are skeletons of the TeX files, we run:
latex mal-contour.tex
dvips mal-contour.dvi
ps2pdf mal-contour.ps

and
lualatex mal-contour-pgfplots.tex

I enclose the Lua code, those two TeX files and a preview of the snippet from PGFplots (I'm having some difficulties with ps2pdf). The mal-preprocess.lua file is:
-- I am mal-preprocess.lua...
-- I take 3 data sets and prepare data set for PSTricks...

--local pstricks=0 -- 0 (pgfplots) or 1 (pstricks)
local c=0 -- a counter of data

-- Cashing files...
print("Cashing 3 files...")
time="time.csv" -- 175
speed="speed.csv"
tension="tension.csv"
local times={}
for time in io.lines(time) do
table.insert(times,time)
end -- for time
local speeds={}
for speed in io.lines(speed) do
table.insert(speeds,speed)
end -- for speed
local tensions={}
for tension in io.lines(tension) do
table.insert(tensions,tension)
end -- for tension

-- The core...
whereto=io.open("../toimage.data","w")
topst=io.open("../toimage-pst.data","w")
topst:write("/contourdata [")

print("Processing "..#tensions.." lines...")
-- Load all lines...
--local temp=""
for tension=1,200 do -- #tensions or 300
c=0
topst:write("[\n")
-- Parse that one line...
for mdata in string.gmatch(tensions[tension],"[^,]+") do
  c=c+1
  writeme=speeds[tension].." "..times[c].." "..mdata.."\n"
  whereto:write(writeme)
  topst:write(writeme)
end -- for mdata

topst:write("]")
whereto:write("\n")
end -- for tension

topst:write("] def\n")

This is the mal-contour.tex file:
% run: latex mal-contour.tex
% -> ps; ->pdf
\documentclass{article}
\usepackage{pstricks-add}
\begin{document}
\psset{unit=0.1cm}
\begin{pspicture}[showgrid](0,1)(4775,3.5)
\pstContour[colored]{toimage-pst.data}
\end{pspicture}
\end{document}

The second file is the mal-contour-pgfplots.tex file:
% run: lualatex engine mal-contour-pgfplots.tex
\documentclass[a4paper]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\begin{document}
\begin{tikzpicture}
\begin{axis}[view={0}{90},colorbar,grid=none]
\addplot3[surf,shader=interp,mesh/cols=175] file {toimage.data};
\end{axis}
\end{tikzpicture}
\end{document}

I believe that GNUplot is a better tool for manipulating huge data sets. I would recommend to use PNG file at the TeX level instead of a vector form as there are so many elements in it. This is a fast test (mal-test.plt) for GNUplot, I enclose the code and a preview of mal-test.png which can be loaded by the \includegraphics command from the graphicx package.
set terminal png
set output "mal-test.png"
unset key

set title ""
set xlabel ""
set ylabel ""

set xrange [ 0.0000 : 84.30000 ] noreverse nowriteback
set yrange [ 1.0000 : 3.50000 ] noreverse nowriteback
set zrange [ -100.0000 : -85.00000 ] noreverse nowriteback

splot "toimage.data"

Update: A note on the data transformation

You can picture your three files as here (one file consists the first row, the second file consists the first column and the last file consists the cells/data set):
- A B C D
X 1 2 3 4
Y 5 6 7 8
Z 9 0 1 2

We transform them to this form by repeating the labels from the first row and from the first column (however, the file size of data changed significantly from 96200+12390248+1199=12487647 to 48643360 bytes - toimage.data - that's the reason we usually don't save data in this form):
X A 1
X B 2
X C 3
X D 4

Y A 5
Y B 6
Y C 7
Y D 8

Z A 9
Z B 0
Z C 1
Z D 2


text:
Q: why does while(*s++ == *t++) not work to compare two strings I'm implementing strcmp(char *s, char *t) which returns <0 if s<t, 0 if s==t, and >0 if s>t by comparing the fist value that is different between the two strings.
implementing by separating the postfix increment and relational equals operators works:
for (; *s==*t; s++, t++)
    if (*s=='\0')
        return 0;
return *s - *t;

however, grouping the postfix increment and relational equals operators doesn't work (like so):
while (*s++ == *t++)
    if (*s=='\0')
        return 0;
return *s - *t;

The latter always returns 0. I thought this could be because we're incrementing the pointers too soon, but even with a difference in the two string occurring at index 5 out of 10 still produces the same result.
Example input:
strcomp("hello world", "hello xorld");
return value:
0
My hunch is this is because of operator precedence but I'm not positive and if so, I cannot exactly pinpoint why.
Thank you for your time!

A: Because in the for loop, the increment (s++, t++ in your case) is not called if the condition (*s==*t in your case) is false. But in your while loop, the increment is called in that case too, so for strcomp("hello world", "hello xorld"), both pointers end up pointing at os in the strings.

A: Since you always increment s and t in the test, you should refer to s[-1] for the termination in case of equal strings and s[-1] and t[-1] in case they differ.
Also note that the order is determined by the comparison as unsigned char.
Here is a modified version:
int strcmp(const char *s, const char *t) {
    while (*s++ == *t++) {
        if (s[-1] == '\0')
            return 0;
    }
    return (unsigned char)s[-1] - (unsigned char)t[-1];
}

Following the comments from LL chux, here is a fully conforming implementation for perverse architectures with non two's complement representation and/or CHAR_MAX > INT_MAX:
int strcmp(const char *s0, const char *t0) {
    const unsigned char *s = (const unsigned char *)s0;
    const unsigned char *t = (const unsigned char *)t0;

    while (*s++ == *t++) {
        if (s[-1] == '\0')
            return 0;
    }
    return (s[-1] > t[-1]) - (s[-1] < t[-1]);
}

A: Everyone is giving the right advice, but are still hardwired to inlining those increment operators within the comparison expression and doing weird off by 1 stuff.
The following just feels simpler and easier to read. No pointer is ever incremented or decremented to an invalid address.
while ((*s == *t) && *s)
{
    s++;
    t++;
}
return *s - *t;

A: For completeness in addition to what was already well answered about the wrong offset during subtraction:
*s - *t; is incorrect when *s, *t is negative.
The standard C library specifies that string functions compare as if char was unsigned char.  Thus  code that subtracts  via a char * gives the wrong answer when the characters are negative.

For all functions in this subclause, each character shall be interpreted as if it had the type unsigned char (and therefore every possible object representation is valid and has a different value).
  C17dr § 7.24.1 3

int strcmp(const char *s, const char *t) {
  const unsigned char *us = (const unsigned char *) s;
  const unsigned char *ut = (const unsigned char *) t;
  while (*us == *ut && *us) {
    us++;
    ut++;
  }
  return (*us > *ut) - (*us < *ut);
}

This code also addresses obscure concerns of non-2's complement access of -0 and char range exceeding int.

redpajama_set_name: RedPajamaStackExchange


text:
Q: This error does NOT occur if I use a non-class/prototype method: Origin file:// is not allowed by Access-Control-Allow-Origin I had come across this CORS issue but was able to overcome it using jsonp and callback=? like suggested below:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
I also have '--allow-file-access-from-files' turned on for Chrome and I have hosted this on Google app engine and also loaded it via Firefox.
However, I started using classes in javascript (via CoffeeScript) and it gives me this error when I use the class method. Please note that I am able to overcome this issue by not using the class/instance method below:
Issue:
I am trying to show a few locations on a google map. I call the google fusion table api to get my data and display it. It works fine when I call the dataHandler() method like a regular method and not as as class method. When I call it like a class method, I get this error locally: "Origin file:// is not allowed by Access-Control-Allow-Origin." I am trying locally on Chrome. When I deploy/host it on the google app engine, I get this error on the same line '400 (Bad Request) '
Thanks
var myMap = new MyMap();
google.load('visualization', '1.0', {"callback":myMap.initialize});

class MyMap
initialize: -> //Javascript equivalent: MyMap.prototype.initialize = function() {
  ...
  jqxhr = $.get(encodeURI(url), @dataHandler, "jsonp") // Does not work.

  //Javascript equivalent: jqxhr = $.get(encodeURI(url), this.dataHandler, "jsonp");

  jqxhr = $.get(encodeURI(url), dataHandler, "jsonp") // This works without the @

  //Javascript equivalent: jqxhr = $.get(encodeURI(url), dataHandler, "jsonp");

dataHandler: (d) -> // Does not work. Javascript equivalent: MyMap.prototype.dataHandler = function(d) {

dataHandler= (d) -> // This works. Javascript equivalent: dataHandler = function(d) {

Local Error:

XMLHttpRequest cannot load
  https://www.googleapis.com/fusiontables/v1/query?key=AIzaSyDjfc6i-&sql=SELECT%20Lat,%20Lng%20from%201Stisvr...&callback=?. Origin file:// is not allowed by Access-Control-Allow-Origin.

Hosted/Server Error:

GET https://www.googleapis.com/fusiontables/v1/query?key=AIzaSyDjfc6i-&sql=SELECT%20Lat,%20Lng%20from%201Stisvr...&callback=? 400 (Bad Request)

A: Use some proxy like charles instead of accessing file from filesystem.


text:
Q: AMP split array in src bind I am trying to build a binding in an amp-list. What I need to do is extract the first entry in the array. For instance my json array looks like this:
"Ids": [
    "123",
    "456"
]
The amp-binding is looking like this:
[src]="'http://any.com?id=' + {{Ids}}"
I want this to end up like:
src="http://any.com?id=123
But is looks like this without any manipulation
src="http://any.com?id=123,456
Looking at the white listed functions, I wondering if I should use Array to String for this.


text:
Q: Add separator when fetching values from XML in SQL I have following XML code snippet and I am trying to read it in tabular format using SQL Server.
declare @ProductXML varchar(max);
set @ProductXML = '<hashtable>   <entry>
    <string>host</string>
    <string-array>
      <string>csdfs</string>
    </string-array>
  </entry>
 <entry> <string>dom</string><map-array>
      <map>
        <entry>
          <string>thirdlevelentrey</string>
          <vector>
            <string>1in</string>
            <string>2in</string>
            <string>3in</string>
            <string>4in</string>
            <string>5in</string>
          </vector>
        </entry>
      </map>
    </map-array></entry>
</hashtable>'

DECLARE @xml xml

SELECT @xml = CAST(CAST(@ProductXML AS VARBINARY(MAX)) AS XML)

SELECT
    x.Rec.query('./string').value('.', 'nvarchar(50)') AS 'Product Name',
    x.Rec.query('./vector/string').value('.', 'nvarchar(50)') AS 'Product TLDs'
FROM
    @xml.nodes('/hashtable/entry/map-array/map/entry') AS x(Rec)

I am facing the issue with second column Product TLDs. In under the vector multiple rows value merged in single text. I want them with separator or delimited text so I could recognize them later when I use.
If someone can help me to place a separator or deliminator such as  1in|2in|3in and so on...
or can it be possible to in a child table considering thirdlevelentry as a table.

A: You could use
SUBSTRING(
x.Rec.query('for $string in ./vector/string/text()
            return  concat("|", $string)
').value('.', 'nvarchar(50)'),
2,50) AS [Product TLDs]

This returns
1in |2in |3in |4in |5in

So injects some additional spaces. If the values you are concatenating won't contain any spaces you could use
REPLACE(
x.Rec.query('for $string in ./vector/string/text()
            return string($string)
').value('.', 'nvarchar(50)'),
' ','|') AS [Product TLDs]

Which returns
1in|2in|3in|4in|5in

A: If your values within <vector><string> don't contain blanks there's a very easy solution:
SELECT
    x.Rec.query('./string').value('.', 'nvarchar(50)') AS 'Product Name',
    x.Rec.query('data(./vector/string)').value('.', 'nvarchar(50)') AS 'Product TLDs'
FROM
    @xml.nodes('/hashtable/entry/map-array/map/entry') AS x(Rec);

The XQuery function .data() will return all content with a blank as separator. I have no idea, why they did not add a second parameter to sepcify the separator...
If your strings contain blanks Martin Smith's FLWOR approach is great!


text:
Q: HTML Select Value Exposure by Locker Service in Lightning Component I am trying to access the value of a  tag within a controller. I have tried component.find("selectId").getElement().value but the value field does not seem to be exposed for selects. The above works for determine the value of other  forms. This is not being done within another component.
Test Component:
<aura:component >

    Select Label

             <select aura:id="select-01" name="select-01" class="slds-select" onchange="{!c.onSelectChange}">
                <option>Option One</option>
                <option>Option Two</option>
                <option>Option Three</option>
            </select>

</aura:component>

Testing Controller:
onSelectChange : function(component, event, helper) {
console.log("Input Selected");
var selected = component.find("select-01").getElement();
debugger;
}

I'm not sure if this is because I'm looking for the wrong thing, or is Locker Services just totally locking down selects.

A: If you peek in the Locker source code here you can see the whitelisted attributes:
https://github.com/forcedotcom/aura/blob/master/aura-impl/src/main/resources/aura/locker/SecureElement.js
So you are right, value has not been whitelisted for <select> elements. (Hey SalesForce, maybe you should get on that!) However selected and value have been whitelisted for <option> elements. So you might instead be able to do something like this:
var selected = component.find("select-01").getElement()
    .children.find(function(option){return option.selected});

And now you'll end up with the option DOM node. Pardon if there are any flaws in my JS.


text:
Q: Finding max of difference + element for an array We have an array consisting of each entry as a tuple of two integers. Let the array be A = [(a1, b1), (a2, b2), .... , (an, bn)]. Now we have multiple queries where we are given an integer x, we need to find the maximum value of ai + |x - bi| for 1 <= i <= n.
I understand this can be easily achieved in O(n) time complexity for each query but I am looking for something faster than that, probably O(log n) for each query. I can preprocess the array in O(n) time, but the queries should be done faster than O(n).
Any kind of help would be appreciated.

A: It seems to be way too easy to over-think this.
For n = 1, the function is v-shaped with a minimum of a1 at b1, with slopes of -1 and 1, respectively - let's call these values ac and bc (for combined).
For an additional pair (ai, bi), one of the pairs may dominate the other (|bc - bi| ≤ |ac - ai), which may then be ignored.
Otherwise, the falling slope of the combination will be from the pair with the larger b, the rising slope from the other.
The minimum will be between the individual b, closer to the b of the pair with the larger a, the distance being half the difference between the (absolute value of the) "coordinate" differences, the minimum value that amount higher.
The main catch is that neither needs to be an integer - the only alternative being exactly in the middle between two integers.
(Ending up with the falling slope from max ai + bi, and the rising slope of max ai - bi.)


text:
Q: Pass data to router-outlet - problem when multiply routers with names I have problem with pass data to router outlet.
Usually I do something like below:
<router-outlet (activate)="setConfig($event)"></router-outlet>

and
setConfig(component: { [key: string]: any }) {
   component.data = this.data;
}

and it works perfect.
But problem is when I have multiply router-outlet with empty path and name. So in routing.module I have:
  {
    path: 'test',
    component: TestComponent,
    children: [
      {
        path: '',
        loadChildren: () => loadRemoteModule({
          remoteName: 'test1',
          remoteEntry: `/c/test1/remoteEntry.js`,
          exposedModule: 'Test1Module',
        }).then(m => m.Test1Module)
      },
      {
        path: '',
        outlet: 'test2',
        loadChildren: () => loadRemoteModule({
          remoteName: 'test2',
          remoteEntry: `/c/test2/remoteEntry.js`,
          exposedModule: 'Test2Module',
        }).then(m => m.Test2Module)
      }
    ]
  },

and in component:
<router-outlet (activate)="setConfig($event)"></router-outlet>
<router-outlet (activate)="setConfig($event)" name="test2"></router-outlet>

In this case I can't set component.data = this.data, because when I console.log component inside setConfig it isn't my component from child route as I expected, it is "ɵEmptyOutletComponent", and I don't know how to pass data to this component in this case.
Test1 and Test2 are microfrontends, there are independents projects and there arent't part of project where Test Component is.

A:
when I console.log component inside setConfig it isn't my component from child route as I expected, it is "ɵEmptyOutletComponent"

That's because there is no component provided in the children route:
children: [
      {
        path: '',
        loadChildren: () => loadRemoteModule({
          remoteName: 'test1',
          remoteEntry: `/c/test1/remoteEntry.js`,
          exposedModule: 'Test1Module',
        }).then(m => m.Test1Module),
        // component: myComponent   <======= MISSING HERE
      }
]

Of course you don't need to provide one since you only want to lazy load the module.
Instead of assigning the data to the component via activate EventEmitter, you should create a service that can store the data. This way, any of your components can have access to it.

share-data.service.ts  (which stores the data)
import { Injectable } from '@angular/core';

import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class ShareDataService {

  // This is the data to be shared by components which
  // includes Test component, Test1 component, Test2 component, etc.
  // BehaviorSubject is better then Subject because it will
  // send the last known value even if the subscriber subscribe late.

  public data = new BehaviorSubject<string>('');

  constructor() {}
}

test.component.ts ( which assigns new value to the data)
import { Component } from '@angular/core';
import { ShareDataService } from './share-data.service';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css'],
})
export class TestComponent implements OnInit {
  constructor(private readonly _serv: ShareDataService) {}

  public ngOnInit() {

    // We want to broadcast the new value to the
    // service so all other component can be notify
    // if they are subscribed to the share-data service.

    this._serv.data.next('new data!');
  }
}

test1.component.ts (which fetches the new value from the data)
import { Component, OnInit } from '@angular/core';
import { ShareDataService } from './share-data.service';

@Component({
  selector: 'app-test1',
  templateUrl: './test1.component.html',
  styleUrls: ['./test1.component.css'],
})
export class Test1Component implements OnInit {
  private _myData: string;

  constructor(private readonly _serv: ShareDataService) {}

  public ngOnInit() {

    // We pull data from the service and assign the value to the _myData.
    // The subscribe part is to make sure we pull the latest value.

    this._serv.data.subscribe(data => this._myData = data);
  }
}


text:
Q: Why is this linearly dependent when matrix is reduced and variables all equal 0? This set of vectors: {(9,9,0),(2,0,1),(3,5,-4),(12,12,-1)} is said to be linearly dependent by multiple sources however I don't understand why. When I put the numbers into a matrix and reduce it I get :
1 0 0
0 1 0
0 0 1
0 0 0
,
so
x=0,
y=0,
z=0. I thought when the variables are all equal to zero the set is linearly independent, so I would like to know why the set is actually linearly dependent.

A: You reduced your problem to the problem to show that $(1,0,0),(0,1,0),(0,0,1)$ and $(0,0,0)$ are linearly dependent. The easy way to do this is to consider
$$
\begin{pmatrix} 0 \\ 0 \\ 0 \end{pmatrix}
= x \begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}
+ y \begin{pmatrix} 0 \\ 1 \\ 0 \end{pmatrix}
+ z \begin{pmatrix} 0 \\ 0 \\ 1 \end{pmatrix}
+ w \begin{pmatrix} 0 \\ 0 \\ 0 \end{pmatrix}
$$
and note that if $x=y=z = 0$, the equation holds for any value of $w$, which implies these 4 vectors are linearly dependent.

As a side note, if you have a set of vectors $V = \{v_i\}_{i=1}^m \subset \mathbb{R}^n$ with $m > n$, then $V$ will always be linearly dependent. (In your case, $n=3$ and $m=4$.) Easy way to see this is that it is possible with $n$ linearly independent vectors to generate any vector in $\mathbb{R}^n$, by taking the standard basis, so all vectors $v_i$ are generated as linear combinations of at most $n$ linearly independent vectors, and so cannot contain more than $n$ linearly independent vectors.


text:
Q: How to convert single String column to multiple columns based on delimiter in Apache Spark I have a data frame with a string column and I want to create multiple columns out of it.
Here is my input data and pagename is my string column

I want to create multiple columns from it. The format of the string is the same - col1:value1 col2:value2 col3:value3 ... colN:valueN . In the output, I need multiple columns - col1 to colN with values as rows for each column. Here is the output -

How can I do this in spark? Scala or Python both is fine for me. Below code creates the input dataframe -
scala> val df = spark.sql(s"""select 1 as id, "a:100 b:500 c:200" as pagename union select 2 as id, "a:101 b:501 c:201" as pagename """)
df: org.apache.spark.sql.DataFrame = [id: int, pagename: string]

scala> df.show(false)
+---+-----------------+
|id |pagename         |
+---+-----------------+
|2  |a:101 b:501 c:201|
|1  |a:100 b:500 c:200|
+---+-----------------+

scala> df.printSchema
root
 |-- id: integer (nullable = false)
 |-- pagename: string (nullable = false)

Note - The example shows only 3 columns here but in general I have more than 100 columns that I expect to deal with.

A: You can use str_to_map, explode the resulting map and pivot:
val df2 = df.select(
    col("id"),
    expr("explode(str_to_map(pagename, ' ', ':'))")
).groupBy("id").pivot("key").agg(first("value"))

df2.show
+---+---+---+---+
| id|  a|  b|  c|
+---+---+---+---+
|  1|100|500|200|
|  2|101|501|201|
+---+---+---+---+

A: So two options immediately come to mind
Delimiters
You've got some obvious delimiters that you can split on. For this use the split function
    from pyspark.sql import functions as F

    delimiter = ":"

    df = df.withColumn(
        "split_column",
        F.split(F.col("pagename"), delimiter)
    )

    # "split_column" is now an array, so we need to pull items out the array
    df = df.withColumn(
        "a",
        F.col("split_column").getItem(0)
    )

Not ideal, as you'll still need to do some string manipulation to remove the whitespace and then do the int converter - but this is easily applied to multiple columns.
Regex
As the format is pretty fixed, you can do the same thing with a regex.
    import re

    regex_pattern = r"a\:() b\:() c\:()"
    match_groups = ["a", "b", "c"]

    for i in range(re.compile(regex_pattern).groups):
        df = df.withColumn(
            match_groups[i],
            F.regexp_extract(F.col(pagename), regex_pattern, i + 1),
        )

CAVEAT: Check that Regex before you try and run anything (as I don't have an editor handy)


text:
Q: Finding and counting if there are the correct number of vowels in a sentence I've been looking around the site and can't find an answer to my question. I need to be able to look through a given amount of strings and count the amount of vowels in the word. If the amount of vowels match the numbers entered before, then print YES. If one word doesn't have the right amount of vowels, print NO. I tried using a String array then going through each word in the array to look for the vowels, increment the vowel check (vocheck) for every vowel it finds, then check if vocheck equals the appropriate number. But, when I check to see if the vocheck for loop works, it just keeps vocheck as 0. What's wrong?
import java.util.*;
public class verses {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int lines = input.nextInt();
        int[] arr = new int[lines];
        int vowels = 0;
        boolean vcheck = true;
        int vocheck = 0;
        for(int i = 0; i < lines; i++){
            arr[i] = input.nextInt();
        }
        String[] word = new String[lines];
        for(int x = 0; x < word.length; x++){
            word[x] = input.nextLine();
        }
        word[word.length-1] = input.nextLine();

        for(int m = 0; m < lines; m++){
            for(int y = 0; y < word[y].length(); y++){
                if(word[m].charAt(y) == 'a'
                        || word[m].equals('e')
                        || word[m].equals('i')
                        || word[m].equals('o')
                        || word[m].equals('u')
                        || word[m].equals('y')){
                    vocheck++;
                }
            }
            if(vocheck != arr[m]){
                vcheck = false;
            }
        }

        if(vcheck == true){
            System.out.println("YES");
        }else{
            System.out.println("NO");
        }

    }

}

This is what a sample input would look like
3
2 2 3
intel
code
challenge
This should print YES because there are three words, the first has 2 vowels, the second has 2 vowels, and the third has 3 vowels

A: Remove these word[m].equals('e') and use like you used first time
word[m].charAt(y) == 'a'.
And
for(int y = 0; y < word[y].length(); y++) //use word[m]
public class Test {
public static void main(String[] args) {
    int[] arr = {2, 3, 2};
    boolean vcheck = true;

    String[] word = {"ch ale", "fa jio", "gt eyu"};//new String[lines];

    int vocheck = 0;
    for(int m = 0; m < 3; m++){
        vocheck = 0;
        for(int y = 0; y < word[m].length(); y++){
            if(word[m].charAt(y) == 'a'
                    || word[m].charAt(y) == 'e'
                    || word[m].charAt(y) == 'i'
                    || word[m].charAt(y) == 'o'
                    || word[m].charAt(y) == 'u')
            {
                vocheck++;
            }
        }
        System.out.println(vocheck);
        if(vocheck != arr[m]){
            vcheck = false;
            break;
        }
    }

    if(vcheck == true){
        System.out.println("YES");
    }else{
        System.out.println("NO");
    }

}

}
Try it

A: You can do something like this:
for(int i = 0; i < lines; i++){
    if(word[i].toLowerCase().replaceAll("[^aeiouy]", "").length() == arr[i]){
        System.out.println("Word " + word[i] + " has " + arr[i] + " vowels");
    }else{
        System.out.println("Word " + word[i] + " DOESN'T HAVE " + arr[i] + " vowels");
    }
}

What this word[i].toLowerCase().replaceAll("[^aeiouy]", "").length() does is to change all letters in the word to lowercase (toLowerCase()), replace all non-vowels characters from it (replaceAll("[^aeiouy]", "")) and get the number of remaining characters (length()), the number of vowels.

A: There are multiple problems here:

*

*Add input.nextLine(); before reading words. This is necessary otherwise first entry in array word would be rest of the part of the previous line.

*word[word.length-1] = input.nextLine(); is not necessary

*vocheck must be initialized for each iteration of the loop

*for(int y = 0; y < word[y].length(); y++){ should be for(int y = 0; y < word[m].length(); y++){. Notice y is changed to m.

*Also other conditions are not consistent. They shouldn't be like word[m].equals('e') but like word[m].charAt(y) == 'e'
import java.util.*;public class verses {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int lines = input.nextInt();
    int[] arr = new int[lines];
    int vowels = 0;
    boolean vcheck = true;
    int vocheck = 0;
    for(int i = 0; i < lines; i++){
        arr[i] = input.nextInt();
    }
    input.nextLine();
    String[] word = new String[lines];
    for(int x = 0; x < word.length; x++){
        word[x] = input.nextLine();
    }
    //word[word.length-1] = input.nextLine();

    for(int m = 0; m < lines; m++){
        vocheck = 0;
        for(int y = 0; y < word[m].length(); y++){
            if(word[m].charAt(y) == 'a'
                    || word[m].charAt(y) == 'e'
                    || word[m].charAt(y) == 'i'
                    || word[m].charAt(y) == 'o'
                    || word[m].charAt(y) == 'u'
                    || word[m].charAt(y) == 'y'){
                vocheck++;
            }
        }
        if(vocheck != arr[m]){
            vcheck = false;
        }

    }
    if(vcheck == true){
        System.out.println("YES");
    }else{
        System.out.println("NO");
    }
}

}

A: Why don't you try some regex :)
public static void main(String[] args) throws InterruptedException {
    String s = "4 2 2 3 2 intel code challenge aa";
    s = s.replaceAll("(?i)[^\\daeiou ]", ""); // replace all consonants with empty String.
    String[] arr = s.split("\\s+"); // Split based on space.
    int count = 0;
    System.out.println(Arrays.toString(arr));
    for (int i = 1; i <= arr.length / 2; i++) {
    // Check for equality of String lengths and input values
        if (Integer.parseInt(arr[i]) == arr[arr.length / 2 + i].length()) {
            count++;
        } else {
            System.out.println("NO");
            return;
        }
    }
    // Check if counts of String are same as number of Strings
    if (count != Integer.parseInt(arr[0])) {
        System.out.println("NO");
    } else {
        System.out.println("YES");
    }

}

O/P :
[4, 2, 2, 3, 2, ie, oe, aee, aa]
YES


text:
Q: Version of zmq jar I have zmq.jar built by someone else long time ago. How can I find out which version it corresponds to?
Not much in the MANIFEST:
$ cat MANIFEST.MF
Manifest-Version: 1.0
Created-By: 1.6.0_14 (Sun Microsystems Inc.)

Here's the contents. Would someone be able to tell whether it's 2.x or 3.x?
$ jar tvf zmq.jar
     0 Thu Feb 02 14:59:52 EST 2012 META-INF/
    71 Thu Feb 02 14:59:52 EST 2012 META-INF/MANIFEST.MF
  2429 Wed Feb 01 14:24:32 EST 2012 org/zeromq/App.class
  4320 Tue Jan 24 14:40:32 EST 2012 org/zeromq/EmbeddedLibraryTools.class
  2392 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZContext.class
  3536 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZFrame.class
   920 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZMQ$Context.class
  2401 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZMQ$Error.class
  3232 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZMQ$Poller.class
  5613 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZMQ$Socket.class
  2484 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZMQ.class
   771 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZMQException.class
  1468 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZMQForwarder.class
  1663 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZMQQueue.class
   424 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZMQStreamer.class
  9771 Tue Jan 24 14:40:32 EST 2012 org/zeromq/ZMsg.class

A: Just ask for the version!
import org.zeromq.ZMQ;

public class ZMQVersion {

   public static void main (String[] args) {
      System.out.println(
        String.format("Version string: %s, Version int: %d",
          ZMQ.getVersionString(),
          ZMQ.getFullVersion()));
   }
}


text:
Q: Running Rails on a private server The issue I'm having is a bit hard to explain.. I Recently took it upon myself to learn Rails. I've got a server (a computer with ubuntu 12.04 running at my house) And own a domain with Hover.com, and use no-IP as a dynDNS service between the two of them.  Now the issue I'm running into is the rails project (a simple hello page to start) works off my no-IP domain, but when I go to my actual domain (with the no-IP domain as a forwarding address) I get a blank page, Looking at the source I see that it's been put into a frameset, and is empty.
I am relatively new to DNS but an hour of searching I believe my issue is with how my DNS records are set up (CNAME vs A), but sadly don't know the details on one compared to the other.
Anyone have any idea how to fix this issue so I can view my rails apps on my domain instead of being forced to view it from no-IP, or straight from my IP:3000?


text:
Q: Sign In with TweetSharp by using ID and Password TwitterService service = new TwitterService("CONSUMER KEY", "CONSUMER SECRET");
service.AuthenticateWith("TOKEN KEY", "TOKEN SECRET");

var retweets = service.ListRetweetsByMe();

So I can use this script to get all retweets but from which user?
I think I should first authorize with correct credentials. So how can I do it?
User should put his/her ID and PW to sign in.

A: you need to use oauth:
TwitterClientInfo client = new TwitterClientInfo();
        client.ConsumerKey = "ConsumerKey";
        client.ConsumerSecret = "ConsumerSecret";
        twitterService = new TwitterService(client);
        requestToken = twitterService.GetRequestToken();
        Uri urlAuth = twitterService.GetAuthorizationUri(requestToken);

you can send the user to that url with a webbrowser control or how you want...well and then you need to receive the pin with a textbox or something...i answer thinking that you are talking about a desktop app.


text:
Q: Yup Validation For AutoComplete in Material UI I have an autocomplete that should be required if either of the two fields is true.
My problem is that when I click submit, it outputs An unhandled error was caught during validation in <Formik validationSchema /> TypeError: You cannot concat() schema's of different types: string and object
  category: string().when(['new', 'exist'], {
    is: false,
    then: object({
      id: string(),
      name: string(),
    })
      .nullable()
      .required('field is required'),
  }),
  new: bool().nullable(),
  exist: bool().nullable(),

A: If I'm reading the error message correctly, then it seems that the string() you have immediately after category:  should be replaced with object() instead, i.e.:
  category: object().when(['new', 'exist'], {
    is: false,
    then: object({
      id: string(),
      name: string(),
    })
      .nullable()
      .required('field is required'),
  }),
  new: bool().nullable(),
  exist: bool().nullable(),


text:
Q: Search Filter space not recognized I am passing in a search filter with a category that has a space in it. It returns the correct result if there is no space.
So, if Person2 is passed as Person 2 below then it gives the wrong result:
string filter =
    String.Format("\"category <> 'Person' AND category <> 'Person2', subject: testsubject\"");

List<QueryOption> options = new List<QueryOption>
{
    new QueryOption("$search", filter)
};

var messages = graphClient.Me
    .MailFolders
    .Inbox
    .Messages
    .Request(options)
    .Select("id, Categories, Subject")
    .Top(500)
    .GetAsync()
    .Result;

A: The $search query parameter using Keyword Query Language (KQL). According to the documentation, phrases need to be double-quoted:

Free text KQL queries are case-insensitive but the operators must be in uppercase. You can construct KQL queries by using one or more of the following as free-text expressions:

*

*A word (includes one or more characters without spaces or punctuation)

*A phrase (includes two or more words together, separated by spaces; however, the words must be enclosed in double quotation marks)

Try enclosing your category strings in double-quotes:
string filter = "\"category <> \\\"Person\\\" AND category <> \\\"Person 2\\\", subject: testsubject\""

Note that in order to send the quote through the API it needs to be escaped (\"). In order to have C# include the escaped sequence in the string, the escape character must ALSO be escaped (\\ + \").  This is why you end up with the odd-looking triple slash (\\\").


text:
Q: Wordpress - If first post add the class selected Somehow in my custom posts-blog-page in wordpress I want to be able to add the class "selected" on the first-post.
What I am doing is the following:
                    <?php if (have_posts()) : ?>
                    <?php $postcount = 0; ?>
                    <?php while (have_posts()) : the_post(); ?>
                    <?php $postcount++; ?>

                    <?php if ($postCount == 0) { ?>
                        <li class="selected" data-date="<?php the_time('F jS, Y'); ?>">
                            <a class="news-box" href="<?php the_permalink(); ?>" target="_self">
                                <?php the_post_thumbnail(); ?>

<?php the_title(); ?>

<?php the_excerpt(__('Continue reading »','example')); ?>

By <?php the_author_link(); ?>

                    <?php  } else { ?>
                        <li data-date="<?php the_time('F jS, Y'); ?>">
                            <a class="news-box" href="<?php the_permalink(); ?>" target="_self">
                                <?php the_post_thumbnail(); ?>

<?php the_title(); ?>

<?php the_excerpt(__('Continue reading »','example')); ?>

By <?php the_author_link(); ?>

                    <?php } ?>
                    <?php endwhile; ?>
                    <?php endif; ?>

However this applies the class "selected" on all li's.
Any ideas?

A: There's a lot of duplication there, just to display the class if $postcount == 0
Also, it shouldn't evaluate to true, since you $postcount++ too early.
Try this:
<?php if (have_posts()) : ?>
    <?php $postcount = 0; ?>
    <?php while (have_posts()) : the_post(); ?>

        <li class="class="<?php if($postcount == 0) { echo 'selected'; } ?>" data-date="<?php the_time('F jS, Y'); ?>">
            <a class="news-box" href="<?php the_permalink(); ?>" target="_self">
                <?php the_post_thumbnail(); ?>

<?php the_title(); ?>

<?php the_excerpt(__('Continue reading »','example')); ?>

By <?php the_author_link(); ?>

        <?php $postcount++; ?>

    <?php endwhile; ?>
<?php endif; ?>

A: Theres useless code there. Try this
<?php if (have_posts()) {
    $postcount = 0;
    while (have_posts()) : the_post();
        if ($postcount == 0) { ?>
             <li class="selected" data-date="<?php the_time('F jS, Y'); ?>">
        <?php } else { ?>
             <li data-date="<?php the_time('F jS, Y'); ?>">
        <?php } ?>
        <a class="news-box" href="<?php the_permalink(); ?>" target="_self">
        <?php the_post_thumbnail(); ?>

<?php the_title(); ?>

<?php the_excerpt(__('Continue reading »','example')); ?>

By <?php the_author_link(); ?>

    <?php
      $postcount++;
      endwhile;
    ?>


text:
Q: Retrofit works but callback doesn't call success or failure methods - Android I try to make a service that will connect to server using retrofit. But whenever I try to connect, it doesn't reach the callback success or failure methods. It does get the result but then it stopped before reaching success or failure methods so it makes my app not responding.
I've done successfully using retrofit before but I didn't use service, and now I need to do this inside a service and it won't work. Please help me.
Thanks in advance.
Here is my service class:
public class ConnectionService extends Service implements Messaging,UserManagement, Callback<Response>{

public final IBinder myBinder = new MyBinder();
public final RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint(Api.API_URL)
        .setClient(new OkClient(new OkHttpClient()))
        .setLogLevel(RestAdapter.LogLevel.FULL)
        .build();
private String jsonResponse = "";
private final Object object = new Object();
private Gson gson = new Gson();

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent intent) {
    return myBinder;
}

@Override
public boolean getInbox(String token, long limit, long page) {
    return false;
}

@Override
public boolean getMessage(String token, int id_member, long limit, long page) {
    return false;
}

@Override
public boolean sendMessage(String token, int id_teman, String message) {
    return false;
}

@Override
public boolean hideMessage(String token, long id_message) {
    return false;
}

@Override
public boolean getToyotaMessage(String token, long limit, long page) {
    return false;
}

@Override
public void showNotification(String message) {

}

@Override
public boolean Signup(String fullname, String email, String password) {

    return false;
}

@Override
public Me Login(String email, String password) {
    Me me = new Me(email,password);
    Api.Login login = restAdapter.create(Api.Login.class);
    login.fetch(me,this);
    try{
        synchronized (object){
            object.wait();
            if(jsonResponse != null && !jsonResponse.equals("")){
                Type tipe = new TypeToken<ApiResponse<Me>>(){}.getType();
                ApiResponse<Me> apiResponse = gson.fromJson(jsonResponse,tipe);
                Metadata metadata = apiResponse.metadata;
                if(metadata.code==200){
                    return apiResponse.data.get(0);
                }
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
}

@Override
public void success(Response response, Response response2) {
    synchronized (object){
        jsonResponse = Utils.convertResultToString(response);
        Log.d(ConnectionService.class.getSimpleName(),"Success. Response: "+jsonResponse);
        object.notifyAll();
    }
}

@Override
public void failure(RetrofitError retrofitError) {
    synchronized (object){
        jsonResponse = null;
        object.notifyAll();
    }
}

public class MyBinder extends Binder{
    public ConnectionService getInstance(){
        return ConnectionService.this;
    }
}
}

The connection happens inside function Login.
Here's my Api Login interface:
public class Api {

public interface Signup{

    @POST(Methods.SIGNUP)
    void fetch(
            @Body Me me,
            Callback<Response> callback
    );
}
public interface Login{
    @POST(Methods.LOGIN)
    void fetch(
            @Body Me me,
            Callback<Response> callback
    );
}
}

And here's inside my mainActivity that calls Login method inside my service:
public class MainActivity extends ActionBarActivity {

public boolean isLoggedin = false;
public Me me = null;

public ConnectionService myService;
public ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        Log.d(MainActivity.class.getSimpleName(),"On Service Connected");
        myService = ((ConnectionService.MyBinder)iBinder).getInstance();
        login();
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        Log.d(MainActivity.class.getSimpleName(),"On Service Connected");
        myService = null;
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

private void login(){
    if(myService != null) {
        me = myService.Login(Settings.EMAIL, Settings.cred);
        if (me != null) {
            Log.d(MainActivity.class.getSimpleName(), "full name: " + me.fullname);
            isLoggedin = true;
        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onStart() {
    super.onStart();
    if(myService == null){
        bindService(new Intent(this,ConnectionService.class),serviceConnection, Context.BIND_AUTO_CREATE);
        //startActivity(new Intent(this,ConnectionService.class));
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if(myService != null){
        unbindService(serviceConnection);
        //stopService(new Intent(this,ConnectionService.class));
    }
}
}

Response that I get after on Service Connected:
05-25 14:31:42.954    7006-7006/com.subkhansarif.connecionmodule D/MainActivity﹕ On Service Connected
05-25 14:31:42.993    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ ---> HTTP POST http://103.247.10.71/imsave/v3/account/login
05-25 14:31:42.993    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ Content-Type: application/json; charset=UTF-8
05-25 14:31:42.993    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ Content-Length: 57
05-25 14:31:42.993    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ {"email":"a@a.a","password":"a","id_member":0,"points":0}
05-25 14:31:42.993    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ ---> END HTTP (57-byte body)
05-25 14:31:43.180    7006-7020/com.subkhansarif.connecionmodule W/dalvikvm﹕ VFY: unable to find class referenced in signature (Ljava/nio/file/Path;)
05-25 14:31:43.180    7006-7020/com.subkhansarif.connecionmodule W/dalvikvm﹕ VFY: unable to find class referenced in signature ([Ljava/nio/file/OpenOption;)
05-25 14:31:43.188    7006-7020/com.subkhansarif.connecionmodule I/dalvikvm﹕ Could not find method java.nio.file.Files.newOutputStream, referenced from method okio.Okio.sink
05-25 14:31:43.188    7006-7020/com.subkhansarif.connecionmodule W/dalvikvm﹕ VFY: unable to resolve static method 19323: Ljava/nio/file/Files;.newOutputStream (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/OutputStream;
05-25 14:31:43.188    7006-7020/com.subkhansarif.connecionmodule D/dalvikvm﹕ VFY: replacing opcode 0x71 at 0x000a
05-25 14:31:43.188    7006-7020/com.subkhansarif.connecionmodule W/dalvikvm﹕ VFY: unable to find class referenced in signature (Ljava/nio/file/Path;)
05-25 14:31:43.188    7006-7020/com.subkhansarif.connecionmodule W/dalvikvm﹕ VFY: unable to find class referenced in signature ([Ljava/nio/file/OpenOption;)
05-25 14:31:43.188    7006-7020/com.subkhansarif.connecionmodule I/dalvikvm﹕ Could not find method java.nio.file.Files.newInputStream, referenced from method okio.Okio.source
05-25 14:31:43.188    7006-7020/com.subkhansarif.connecionmodule W/dalvikvm﹕ VFY: unable to resolve static method 19322: Ljava/nio/file/Files;.newInputStream (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/InputStream;
05-25 14:31:43.188    7006-7020/com.subkhansarif.connecionmodule D/dalvikvm﹕ VFY: replacing opcode 0x71 at 0x000a
05-25 14:31:43.813    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ <--- HTTP 200 http://103.247.10.71/imsave/v3/account/login (820ms)
05-25 14:31:43.813    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ Date: Mon, 25 May 2015 07:31:43 GMT
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ Server: Apache/2.4.10 (Unix) OpenSSL/1.0.1j PHP/5.6.3 mod_perl/2.0.8-dev Perl/v5.16.3
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ X-Powered-By: PHP/5.6.3
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ Content-Length: 750
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ Content-Type: application/json
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ X-Cache: MISS from webcache.cnrglab.itb.ac.id
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ X-Cache-Lookup: MISS from webcache.cnrglab.itb.ac.id:3128
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ X-Cache: MISS from webcache-ng.cnrglab.itb.ac.id
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ X-Cache-Lookup: MISS from webcache-ng.cnrglab.itb.ac.id:3128
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ Via: 1.1 webcache.cnrglab.itb.ac.id (squid/3.5.4-20150510-r13825), 1.1 webcache-ng.cnrglab.itb.ac.id (squid/3.5.3)
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ Connection: keep-alive
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ OkHttp-Selected-Protocol: http/1.1
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ OkHttp-Sent-Millis: 1432539103202
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ OkHttp-Received-Millis: 1432539103816
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ {"metadata":{"code":200,"message":"OK","timestamp":"2015-05-25 14:31:43"},"data":[{"image":{"href":"http:\/\/103.247.10.71\/imsave\/assets\/member_image\/174","mime_type":""},"id_member":174,"fullname":"a","email":"a@a.a","phone":"4","birthday":null,"gender":null,"address":null,"city":null,"province":null,"country":"INDONESIA","zip":null,"latitude":null,"longitude":null,"location":null,"device":"EMAIL","login_method":"FB","points":20,"level":"1","badges":[],"created":"2015-05-22 19:29:34","token":"Un87jGj8DB6Q1Jhf08Acct1nsewQC0dwnlEG1YOFzVvAFNQFWrS8UTwn73dK3rgqMV7OTWttSZ4xMVdJm6Sh0oE8rRSvj9V543UYZorSowqbrEUNKM4KbJSCBL7UU30Y6UW6joZHUpSl3N9NzeyKXrnzcvt6yt5Fo2MHqLplaiHe5R2F6Aq42NDej6lRzqxYtkGU65fh"}],"pagination":{"page":1,"limit":1,"size":1}}
05-25 14:31:43.821    7006-7020/com.subkhansarif.connecionmodule D/Retrofit﹕ <--- END HTTP (750-byte body)

as seen in response above, it ends up after connection gets the result and never invoke success or failure methods.

A: In my case the problem was Android Studio Emulator . in real android device onFailure or onResponse always called .
also add timeout to OkHttp :
    val httpClient = OkHttpClient.Builder()
        .readTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .build()

A: Well you shouldn't tell the main thread to wait. That's bad practice and is the reason you're seeing the ANR. Instead do it in a thread, though the point of the async call is that you don't need to wait.
If you really wanted to make a blocking call, why not rename your interface methods to return objects rather than void. Then you can follow the synchronous approach and you won't need your service extending Callback (which I'm not a big fan of btw).


text:
Q: Having Azure Joined devices have local administrator access to only a specific device only Good afternoon, I am fairly new to Azure AD in general; I know my way around but I am stumped on something for a client of ours.
We have a client who has devices joined to Azure AD. They wish to create local administrator accounts on specific computers that only specific people can access and only that administrative account can be used on that workstation for administrative rights (just like a regular device local admin account)
For example:
CON-01 (PC name) should have a local admin account that's in Azure AD named JohnDoe_adm@contoso.com that can do elevated admin privileges' but this JohnDoe_adm@contoso.com account should not be allowed to have local administrative rights on CON-02. And vice versa. JaneDoe_adm@contoso.com should only have local administrative rights to CON-02 but her login can't be used on CON-01 for elevated permissions.
Devices will not be connected to the local AD frequently for policy updates (and we want to avoid VPN connection to the local AD DC). Client strictly wants these devices joined via Azure AD Joined but to have administrative accounts managed through Azure AD.
The clients accounts are synchronized in Azure with their local AD.
I saw that with a premium license for Azure you can add local administrators group on Azure AD joined devices but doing so will allow that user to have local administrative access on all devices that are joined and we are trying to prevent that.
Would it be possible to create a group called CONOTSO/CON-01 Local Administrators in Azure AD; and add JohnDoe_adm@contoso.com to this group and go onto CON-01 and manually apply CONOTSO/CON-01 Local Administrators group under Administrators in lusrmgr.msc on the workstation CON-01 ?
Or any suggestions to make this process easier to achieve what I am looking for?
Any advice is appreciated! Thanks!

A: You can do that, just not in the GUI.  :-)
On an individual computer you can use "Net Group Administrators /Add AzureAD\JohnDoe_adm" to give that account admin rights to the machine.
You'll have to do that for each machine.

A: •   Yes, you can create an Azure AD user, for example in this scenario, johndoe_adm@contoso.com as a member of the local administrators' group on Azure AD joined devices. For that purpose, you will have to create a policy under 'Endpoint Protection' in Intune management portal for 'local user/group membership' for managing local admins of Windows 10/11 client devices. Please follow the below snapshots for more information: -

As shown in the above policy, you can create a policy for 'local user group membership'. In it, you can create a profile for Windows 10/11 by selecting the appropriate option and selecting the correct local users' group to be managed through it as shown below: -

Once the above options have been selected, then you can have the option of selecting Azure AD users or groups in the respective selected local administrators group so that the Azure AD users can be a member of local administrators' group on client system as below: -

Thus, in this way, you can add an Azure AD user/group as a member of local administrators' group on the Azure AD joined and Intune MDM managed and complaint system by assigning this policy on the said device groups.
•   Also, please note that as you are saying that a particular Azure AD user, i.e., ABC should be a member of a local administrators' group on an Azure AD joined device, viz., XYZ which is readily possible as per stated above but you also want that this user ABC should not be a member of another Azure AD joined device's local administrators' group, then for this purpose, you will have to create a separate Azure AD user for every Azure AD joined device and create one profile likewise for every Azure AD user/group as well as for every device that is going to be a part of the local administrators' group on the client system which can be very hectic and time consuming given the options available in Intune MDM.
Thus, I would suggest you create a single Azure AD user for the purpose of adding it in the local administrators' group on every Azure AD joined and Intune MDM managed Windows 10/11 device and further create a profile as shown above and deploy it on all the Windows 10/11 devices to be managed through Intune and required accordingly. Also, do keep the credentials of that Azure AD user with yourself only to maintain a level of confidentiality.
For more detailed information on the above, kindly refer the below link: -
https://www.anoopcnair.com/manage-local-admins-using-intune-group-mgmt/#:~:text=The%20local%20user%20group%20management,or%20Windows%2011%20local%20group.


text:
Q: Radio buttons not passing value in Firefox with jQuery I have this review site, with a form for users to enter their reviews, example: http://www.thecrowder.com/index.php/userreviews/sites/99_Designs (click on 'submit review')
I'm using a jQuery star rating plugin  and it's working fine in Chrome. However, there's some problem with Firefox and IE - it doesn't recognize the value being sent and I get an error that the 'rating' variable is missing.
If I remove the ':checked" in the jquery, I don't get an error but obviously also get '0' as the rating. Is there a different way that I should write this for the other browsers?
The review form:

    Site reviewed:
    <input readonly type="text" id="site" value="<?php echo ucwords($cleanSitename); ?>" class="required">

        Name:
         <input type="text" id="name" class="required" >

        Review:
        <textarea id="messageUser" class="required" ></textarea>

        Rate this site:

                <input type="radio" value="1" class="star" name="rate"/>
                <input type="radio" value="2" class="star" name="rate"/>
                <input type="radio" value="3" class="star" name="rate"/>
                <input type="radio" value="4" class="star" name="rate"/>
                <input type="radio" value="5" class="star" name="rate"/>

<button id="submitReview2">Submit</button>

jQuery:
$('#submitReview2').click(function() {
    var profile = $('#site').val();
    var name = $('#name').val();
    var message = $('#messageUser').val();
    var rating = $("input:radio[name=rate]:checked").val();
  }

BTW, I'm using codeigniter if it makes any difference.
Thanks

A: Try this to get the number of stars selected:
var rating = $(".star-rating-control .star-rating-on").length;


text:
Q: How to deserialize a C struct into a Rust struct Let's say that there exists a kernel header like this in C:
typedef struct {
  uint32_t type;
  uint32_t length;
  uint32_t extra;
  uint32_t flags;

  uint32_t reserved0;
  uint32_t reserved1;

  uint32_t magic;
  uint32_t crc32;
} zbi_header_t;

That is, the fist bytes of the kernel image are this struct.
In order to parse this header into Rust, I'd have something like this:
#[derive(Debug)]
#[repr(C)]
pub struct ZbiHeader {
    zbi_type: u32,
    length: u32,
    extra: u32,
    flags: u32,
    reserved0: u32,
    reserved1: u32,
    magic: u32,
    crc32: u32,
}

notice that I added a repr(C).
What is the best Rust way to transform a slice &[u8] of size sizeof(zbi_header_t) into this struct?
Can I take a byte array and deserialize it into a struct? talks about alignment issues but would we have it here?
In this particular case where all values are uint32_t I think the compiler wouldn't do any paddings, but I don't know if this is guaranteed and also I'm thinking about what if there was an u8 in the middle. It could be that the compiler always disables the paddings for this file? By the way, the header is from https://fuchsia.googlesource.com/fuchsia/+/6d0df1b8f7cbadf04553501f995156b224dd6347/zircon/system/public/zircon/boot/image.h#102 but I couldn't find any rules saying it should ignore paddings, etc.

A: There are multiple ways to go about doing this. The easiest way is if the byte slice is known to be well aligned.
let header:&ZbiHeader = unsafe{ &*slice.as_ptr().cast() };

Things get a little more complicated if the byte slice is unaligned. In that case, you have to use ptr::read_unaligned instead.
let header:ZbiHeader = unsafe{ slice.as_ptr().cast().read_unaligned() };

I believe the struct you have shown does not have any padding, and has the same memory representation as an [u32;8]. Look here for more about the C's struct layout. If your struct did have padding it wouldn't be initialized, so you shouldn't use an &[u8] you should use a &[MaybeUninit<u8>] instead. Or if possible, pass around the struct itself or a pointer to it instead of a byte array.

A: Padding won't be an issue - since you have #[repr(C)], the representation of the Rust ZbiHeader will match the representation of the  C zbi_header_t, padding and all.
As for the alignment issues, it entirely depends on how you get your &[u8] byte slice. If you know for a fact that it's a zbi_header_t casted to a byte pointer, then the pointer should be well aligned. If you're just grabbing a random &[u8] slice, ex from a file input buffer, then you'd have to worry.


text:
Q: OS X - forwarding external port to local loopback address I have an HTTP service bound to port 8000 that I want to access from another computing on the network, but I can't seem to connect using the external IP address of the machine (e.g. 192.168.0.105). I've checked the OS X firewall isn't running, so I'm assuming the issue is the service is only bound to the IP address 127.0.0.1, and not the external IP address.
What would be the easiest way to temporarily forward external connections on port 8000 to 127.0.0.1:8000?

A: easiest and quickest way to make locally bound ports available to the public interface without reconfiguring the underlying service is to create a ssh port forwarding and make it available globally (by default it only listens locally)
Because it's the same machine, you will have to use different ports. On the Mac where the service runs, start
ssh -v -g -L 8001:localhost:8000 localhost
-v for verbose, so you see the incoming connections
-g to make it available on the public interface
-L port:targethost:targetport well, you know that already :-)
in case you have more than one active interface on the machine, extend the -L statement to include the adress you want to bind it to.

A: Use ipfw, it likes iptables in linux.
I guess you are using ssh port forwarding a service to your local.
ipfw add fwd 127.0.0.1,8000 tcp from any to 192.168.0.105 dst-port 8000

The other machine on the network is able to access the service via 192.168.0.105:8000

A: If I understand correctly, Squid might work. Also, try the computer name rather than IP, or some other service (ping, VNC, FTP, etc)

A: First, make sure you're going after the right problem.  You can check what IPs the web server is listening on with the netstat command:
$ netstat -an | grep LISTEN
tcp46      0      0  *.8000                 *.*                    LISTEN
tcp4       0      0  *.88                   *.*                    LISTEN
tcp6       0      0  *.88                   *.*                    LISTEN
tcp4       0      0  127.0.0.1.631          *.*                    LISTEN
tcp6       0      0  ::1.631                *.*                    LISTEN

In the first line of this example, the "*.8000" means that something (presumably the web server) is listening on port 8000 on all bound IPs.  On the other hand, the last two lines mean something is listening on port 631 on the IPv4 and IPv6 loopbacks (127.0.0.1 and ::).  If you see "127.0.0.1:8000" when you run the command, that means you're on the right track in your diagnosis.
If this is the problem, it's probably best to solve it by getting the web server bound to all IPs, rather than trying to work around it with a forwarder.  Check your Apache config file(s) (the default on OS X is /etc/apache2/httpd.conf, plus everything "Include"ed from it) for "Listen" directives.  If you see
Listen 127.0.0.1:8000

change it to
Listen 8000


text:
Q: Programming library for (fast) signature based matching? I've been given an assignment to build an application that will perform signature based matching on some network traffic (at layer 7). Matching will be performed in real-time and it needs to be fast in order for the system to keep it's responsiveness at all times.
At first I thought about using regular expressions as signatures and pcre as a library for matching. But it seems this is too slow. There will be a few thousand signatures for matching.
Since I don't have a lot of experience in signature based content matching I am asking:

*

*Should I use regular expressions as signatures and find some faster library?

*Is there any other library (free or commercial) for signature based matching that is fast?

A: To build an efficient RE matcher, one compiles it into a finite state machine with accept and not-accept states.
When you have more than one RE, you can easily form their disjunction, and compile that into an FSA, with not-accept states, and states marked according to which RE accepted.
So with a few thousand REs, you compute one huge disjunction and build the FSA for that set.
Most standard lexing engines (e.g., FLEX) do exactly this, using one RE per token, and will tell you which token.   So you ought to be able to use FLEX as a starting place.


text:
Q: Round Robin scheduling in java I'm trying to implement Round Robin scheduling algorithm. But the code I have done so far only consider the burst time. I also need to consider the arrival time of the process too. I have a time_chart array which I'm using to store the number of the process which is currently executing. But if no process is currently executing (that is if selected process has finished executing and next process has not arrived.), value 0 should be inserted into the time_chart array.
I have stored burst time and arrival time in a 2D array as:
//proc[][0] is the AT array
//proc[][1] is the BT array

and Time Quantum in variable q. Below is my code:
int time_chart[] = new int[total_time];
int sel_proc = 1;
int current_q = 0;

for (int k = 0; k < total_time; k++) {

    //Assign selected process to current time in the Chart
    time_chart[k] = sel_proc;

    //Decrement Remaining Time of selected process by 1 since it has been assigned the CPU for 1 unit of time
    proc[sel_proc - 1][1]--;

    //Updating value of sel_proc for next iteration
    current_q++;

    if (current_q == q || proc[sel_proc - 1][1] == 0)//If Time slice has expired or the current process has completed execution
    {
        current_q = 0;
        //This will select the next valid value for sel_proc
        for (int j = 1; j <= n; j++) {
            sel_proc++;
            if (sel_proc == (n + 1)) {
                sel_proc = 1;
            }
            if (proc[sel_proc - 1][1] != 0) {
                break;
            }
        }
    }
}

// print timeline for testing
for (i = 0; i < total_time; i++) {
System.out.println("Time " + i + ": " + time_chart[i]);
}

currently it will select the next process even though it has not arrived yet. Therefore, I need to check if the next process has arrived or not. I tried using proc[sel_proc][0] <= k to check this but it didn't seem to work. By that I mean I didn't get any output. I can't think of another way to check if the next process has arrived or not. How can I check this and put value 0 into the array if the next process has not arrived?

A: Although you can accomplish this using only arrays you may find the logic easier if you create a class structure to store the process information and use two Queues. The first Queue being a list of processes ordered by arrival time and the second Queue the processes that are currently being executed.
You can model you process something along these lines
private static class Process {
    public final int id;
    public final int burstTime;
    public final int arrivalTime;
    public int executionTime;

    public Process(int id, int burstTime, int arrivalTime) {
        super();
        this.id = id;
        this.burstTime = burstTime;
        this.arrivalTime = arrivalTime;
    }
}

Then create a Queue call unscheduled processes (Or what ever seems appropriate) and add the processes to that queue ordered by arrival time. Queue<Process> = new LinkedList<>()
Now during your loop every time you just check the head of the queue and see if the process' arrival time is equal or greater than the current time. If it is remove it from the queue and add it to the head of scheduler queue. LinkedList<Process> = new LinkedList<>()
You always remove the head process from the scheduler queue and update the execution time of the process. Make sure not to go beyond burst time, ie execution time is always increased by the quantum OR burstTime - executionTime, depending on which is smaller. After the update, if the execution time is less then the burstTime, add the process back to the scheduler queue.
Remember the the current time will not be increased by quantum, if the remaining time on the process was less than the quantum.

A: This problem is much simpler if rather than a single int tracking the currently running process, you use a list of all. A good choice is to keep an ordered list where the running process is at the head, and the others follow in the order they should run in the future. Then you can always get the next process to run by rotating the list. It's simple to update the list for each quantum. A Java collection that makes all these options easy is called a Deque.
Something like this:
Deque<Integer> running = new ArrayDeque<>();
for (int quantum = 0; quantum < totalDuration; ++quantum) {
  // Add new arrivals to the list of running processes.
  // Note that if the processes are pre-sorted by arrival time,
  // this loop can be made more efficient. This assumes no sorting.
  for (int process = 1; process <= processCount; ++process) {
    if (arrivalTime[process] == quantum)
      running.addLast(process); // Use addFirst if new procs should run immediately.
  }
  if (running.isEmpty())
    timeChart[quantum] = 0; // Nothing to run
  else {
    // Select the process now at the head.
    int selectedProcess = running.getFirst();

    // Decrement the running process's burst time. If it's done, remove
    // it from the running list.
    if (--burstTime[selectedProcess] == 0)
      running.removeFirst();

    // Record the run for this quantum.
    timeChart[quantum] = selectedProcess;

    // Rotate the previous head to the tail of the list for next quantum.
    if (running.size() > 1)
      running.addLast(running.removeFirst());
  }
}

Note I've used more rational names and Java conventions. Your choice of names and data types is a bit hideous. As others have said, it would be still better to group arrival and burst times for a process in a class.

A: Actually, you should see whether the arrival time of the process is less than or equal the next upcoming time. So, you should check proc[sel_proc][0] <= k + 1. In particular, the only change that you should make is your if which instead of
if (proc[sel_proc - 1][1] != 0) {
    break;
}

should become: (if the remaining burst time is not zero and its arrival time is before or equal the next time, i.e. k + 1)
if (proc[sel_proc - 1][1] != 0 && proc[sel_proc][0] <= k + 1) {
        break;
}

More importantly, make sure that your last valid time unit is total_time - 1 and not total_time itself. Furthermore, are your arrival times 0-based or 1-based, these are corner cases that you have to be careful about.

A: What do you plan to schedule with your algorithm. I have never heard of anyone that does time slicing, except when implementing an operating system.
Time slicing works at an OS level because the OS can choose which (of the eligible) processes/threads it wants to run on the CPU, and because the OS can basically stop a thread at any instruction and flush CPU registries to cache. This principle will only work in code, if each task can be broken down to very small units of work ('CPU' instructions). That way if you have 100 tasks consisting of 100 units each, and a 4 processor cores, you can implement your own time slicing algorithm (but I would not recommend it).
Traditionally, if you have multiple concurrent tasks, you would use a threadpool with thread count equal to the number of CPU cores (or more it the tasks have IO), and you would simply queue the tasks as they arrive, and let the OS worry about time slicing.


text:
Q: How can I prevent a base constructor from being called by an inheritor in C#? I've got a (poorly written) base class that I want to wrap in a proxy object. The base class resembles the following:
public class BaseClass : SomeOtherBase
{
   public BaseClass() {}

   public BaseClass(int someValue) {}

   //...more code, not important here
}

and, my proxy resembles:
public BaseClassProxy : BaseClass
{
  public BaseClassProxy(bool fakeOut){}
}

Without the "fakeOut" constructor, the base constructor is expected to be called. However, with it, I expected it to not be called. Either way, I either need a way to not call any base class constructors, or some other way to effectively proxy this (evil) class.

A: There is a way to create an object without calling any instance constructors.
Before you proceed, be very sure you want to do it this way. 99% of the time this is the wrong solution.
This is how you do it:
FormatterServices.GetUninitializedObject(typeof(MyClass));

Call it in place of the object's constructor. It will create and return you an instance without calling any constructors or field initializers.
When you deserialize an object in WCF, it uses this method to create the object. When this happens, constructors and even field initializers are not run.

A: At least 1 ctor has to be called. The only way around it I see is containment. Have the class inside or referencing the other class.

A: I don't believe you can get around calling the constructor.  But you could do something like this:
public class BaseClass : SomeOtherBase
{
   public BaseClass() {}

   protected virtual void Setup()
   {
   }
}

public BaseClassProxy : BaseClass
{
   bool _fakeOut;
   protected BaseClassProxy(bool fakeOut)
   {
        _fakeOut = fakeOut;
        Setup();
   }

   public override void Setup()
   {
       if(_fakeOut)
       {
            base.Setup();
       }
       //Your other constructor code
   }
}

A: If what you want is to not call either of the two base class constructors, this cannot be done.
C# class constructors must call base class constructors. If you don't call one explicitly, base( ) is implied. In your example, if you do not specify which base class constructor to call, it is the same as:
public BaseClassProxy : BaseClass
{
    public BaseClassProxy() : base() { }
}

If you prefer to use the other base class constructor, you can use:
public BaseClassProxy : BaseClass
{
    public BaseClassProxy() : base(someIntValue) { }
}

Either way, one of the two will be called, explicitly or implicitly.

A: If you do not explicitly call any constructor in the base class, the parameterless constructor will be called implicitly. There's no way around it, you cannot instantiate a class without a constructor being called.

A: I am affraid that not base calling constructor isn't option.

A: When you create a BaseClassProxy object it NEEDS to create a instance of it's base class, so you need to call the base class constructor, what you can doo is choose wich one to call, like:
public BaseClassProxy (bool fakeOut) : base (10) {}

To call the second constructor instead of the first one

A: I ended up doing something like this:
public class BaseClassProxy : BaseClass
{
   public BaseClass BaseClass { get; private set; }

   public virtual int MethodINeedToOverride(){}
   public virtual string PropertyINeedToOverride() { get; protected set; }
}

This got me around some of the bad practices of the base class.

A: constructors are public by nature. do not use a constructor and use another for construction and make it private.so you would create an instance with no paramtersand call that function for constructing your object instance.

A: All right, here is an ugly solution to the problem of one class inheriting the constructors of another class that I didn't want to allow some of them to work. I was hoping to avoid using this in my class but here it is:
Here is my class constructor:
public MyClass();
{
   throw new Exception("Error: Must call constructor with parameters.");
}

OK now you were warned that it was ugly. No complaints please!
I wanted to force at least the minimal parameters from my main constructor without it allowing the inherited base constructor with no parameters.
I also believe that if you create a constructor and do not put the : base() after it that it will not call the base class constructor. And if you create constructors for all of the ones in the base class and provide the same exact parameters for them in the main class, that it will not pass through. But this can be tedious if you have a lot of constructors in the base class!

A: It is possible to create an object without calling the parameterless constructor (see answer above). But I use code like this to create a base class and an inherited class, in which I can choose whether to execute the base class's init.
public class MyClass_Base
{
    public MyClass_Base()
    {
        /// Don't call the InitClass() when the object is inherited
        /// !!! CAUTION: The inherited constructor must call InitClass() itself when init is needed !!!
        if (this.GetType().IsSubclassOf(typeof(MyClass_Base)) == false)
        {
            this.InitClass();
        }
    }

    protected void InitClass()
    {
        // The init stuff
    }
}

public class MyClass : MyClass_Base
{
    public MyClass(bool callBaseClassInit)
    {
        if(callBaseClassInit == true)
            base.InitClass();
    }
}

A: Here is my solution to the problem
using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(new Child().Test);
    }

    public class Child : Parent {
        public Child() : base(false) {
            //No Parent Constructor called
        }
    }
    public class Parent {
        public int Test {get;set;}
        public Parent()
        {
            Test = 5;
        }
        public Parent(bool NoBase){
            //Don't do anything
        }
    }
}

A simple elegant solution. You can change it according to your need.

A: Another simple solution from me:
class parent
{
    public parent()
    {
        //code for all children

        if (this.GetType() == typeof(child1))
        {
            //code only for objects of class "child1"
        }
        else
        {
            //code for objects of other child classes
        }
    }
}

class child1 : parent
{
    public child1()
    {}
}

// class child2: parent ... child3 : parent ... e.t.c


text:
Q: Appropriate to use repeated function calls to loop through something (i.e. a list) in Python? Lets say I have the following Python script:
def pop_and_loop():
    my_list.pop(0)
    my_func()

def my_func():
    #do something with list item [0]
    if my_list[0] finished_with:
        pop_and_loop()
    #continued actions if not finished with
    if my_list[0] finished_with:
        pop_and_loop()

my_list = [#list containing 100 items]
my_func()

Is this an appropriate setup? Because, am I not leaving each function call open in a way because its having to hold a marker at the position where I have left the function to go to another, so theoretically it is waiting for me to come back, but I'm never coming back to that one. Does this create problems and is there a different way you're meant to do this?
EDIT: My actual script is more complicated than this, with loads of different functions that I need to call to whilst processing each item in the main list. Essentially my question is whether I need to convert this setup into an actual loop. Bearing in mind that I will need to refresh the main list to refill it again and then loop through the same again. So how would I keep looping that? Should I instead have:
my_list = []

def my_func(item):
    #do something with list item
    if item finished_with:
        return output
    elif item_finished_now:
        return output

while not len(my_list):
    while #there are items to fill the list with:
        #fill list

        for x in my_list:
            output = my_func(x)
            #deal with output and list popping here
    #sleep loop waiting for there to be things to put into the list again
    time.sleep(60)

A: Yours is simply an example of recursion.
Both the question and answer are borderline opinion-based, but in most cases you would prefer an iterative solution (loops) over recursion unless the recursive solution has a clear benefit of either being simpler or being easier to comprehend in code and in reasoning.
For various reasons, Python does not have any recursion optimizations such as tail call and creates a new stack frame for each new level (or function call). That, and more, are reasons an iterative solution would generally be faster and why the overhead of extra recursive calls in Python is rather large - it takes more memory for the stack and spends more time creating those frames. On top of all, there is a limit to the recursion depth, and most recursive algorithms can be converted to an iterative solution in an easy fashion.
Your specific example is simple enough to convert like so:
while my_list:
    while my_list[0] != "finished":
        # do stuff
    my_list.pop(0)

On a side note, please don't pop(0) and use a collections.deque instead as it's O(1) instead of O(N).


text:
Q: Vue CLI dynamic import from project module I know it is possible to imports component from a bundled webpack file like this
import {componentA, componentB} from '../component.bundle';

Is it possible to achieve this same as a dynamic import, like this.
const url = '${window.location.origin}/assets/default/js/bundle/vue_data.bundle.js';
        this.getAxiosInstance().get(url).then(response => {
                const {Add, Edit, Filter, View} =  () => import(response.data);
        });

If yes, please how? Thank you

A: Yes, using dynamic imports:

To dynamically import a module, the import keyword may be called as a function. When used this way, it returns a promise.

I'm assuming from your url example that your import is in the assets directory of your project (i.e. src > assets) and not actually on an external domain.  In that case, you don't need axios.  You would do it like this:
const path = 'assets/default/js/bundle/vue_data.bundle.js';
import('@/' + path).then(module => {
  const {Add, Edit, Filter, View} = module;
});

You need to hardcode the @/ portion or there will be issues, e.g. if you tried to do import(path) with const path = '@/assets/default/js/bundle/vue_data.bundle.js'


text:
Q: Movable stall along roads What do we call the movable food stalls set up on roadsides  more common in India? I usually refer to them as a cart or a food-stall.

A: Do you have a link or a picture to describe what you mean?  If it's on wheels we'd probably call it a food cart or possibly a food truck.
Without wheels it would be a food stand, or possibly a food stall, depending on how they are organized.


text:
Q: How to set EST Date as it is in DateTimePicker jquery without any conversion I have a python server which is return an EST time (for e.g 1420473600), when I am trying to set the same timestamp in my jquery Date Time Picker, it is not giving me an proper timing. Its showing an IST Time.
My code is as below.
//startTime and endTime are EST time stamps that I receive from Server.
$( "#datepicker" ).datetimepicker({
    minDate:new Date(startTime*1000),
    maxDate:new Date(endTime*1000)
});

The datetimepicker converts is automatically to IST, I want to display the exact date as it is coming from Server without any conversion.

A: Try to add the "locale:'en'" option to the datetimepicker.


text:
Q: Verificar campo de formulario antes de enviar petición - Django Soy nuevo en Django, y estaba realizando una app para control de stock y ventas. El problema que tengo, es que al crear una venta, necesita verificar que haya stock disponible, y en caso de que no haya, enviar un mensaje de error o similar, pero no consigo hacerlo.
models.py
class Producto(models.Model):
    nombre = models.CharField(max_length=100)
    stock = models.IntegerField()
    precio_venta = models.FloatField()
    precio_stock = models.FloatField()

class Venta(models.Model):
    producto = models.ForeignKey(Producto, on_delete=models.CASCADE)
    cantidad = models.FloatField()
    fecha = models.DateTimeField('dia vendido',auto_now=True)

views.py
def new_venta(request):
    form = NewVentaForm()
    return render(request,'ventas/form_venta.html', {'form':form})

forms.py
class NewVentaForm(forms.ModelForm):

    class Meta:
        model = Venta
        fields = ['producto','cantidad']

Tambien quisiera saber si es posible hacerlo con clases genéricas, gracias.

A: Una opción podría ser que dentro de la función new_venta(), se verifique el stock del producto que se quiera, para ello yo crearía una función adicional que se encargue de ver el stock de un producto en particular
def ver_stock(nombre_producto): #recibe el nombre del producto
    producto = Producto.objects.get(nombre = nombre_producto) #recoge el producto encontrado
    if producto.stock > 0: #comprueba que el stock sea mayor que 0
        return True # si es así retorna True
    else:
        return False #de no cumplir retorna False

Esta función podría recibir el id, también que sería lo más apropiado, en lugar de recibir como parámetro el nombre.

La función anterior se podría usar a la hora de llamar a la función new_venta(), pero esta vista además de recibir el request debe de recibir el atributo en cuestión, es decir, en este caso el nombre del producto:
 def new_venta(request, nombre_producto): #recibe la request y el nombre del producto
    if ver_stock(nombre_producto) == True:
        form = NewVentaForm()
        return render(request,'ventas/form_venta.html', {'form':form})
    else:
        return HttpResponseNotFound('
Lo sentimos no hay stock de este producto:(
')

Recuerda que para mandar algún campo adicional a tu vista dentro de las url debe de ir:
url(r'^venta/(?P<nombre_producto>\d+)/$',new_venta, name='ventas'),

Dentro de la template cuando llamas a la url, debes de indicarle el atributo que recibe:
Venta


text:
Q: EJB @PersistenceContext EntityManager Throws NullPointerException I'm having a problem with injecting EntityManager by using @PersistenceContext. I try to inject EntityManager in EJB class with @PersistenceContext and I always get NullPointerException.
Here is EJB class:
@Stateless
public class BookEJB {

public BookEJB(){

}

@PersistenceContext(unitName = "BookWebStorePU")
private EntityManager em;

public Book createBook(Book book) throws Exception {
    System.out.println("EM: " + em);
    em.persist(book);
    return book;
}

public Book findBookByIsbn10(String isbn10){
    Book book = new Book();
    em.find(Book.class, isbn10);
    return book;
}
//Other methods here
}

Here's Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="BookWebStorePU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<validation-mode>NONE</validation-mode>
<properties>
  <property name="javax.persistence.schema-generation.database.action" value="create"/>
  <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
  <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/BookWebStoreDB"/>
  <property name="javax.persistence.jdbc.user" value="bookwebstoreadmin"/>
  <property name="javax.persistence.jdbc.password" value="password"/>
  <!-- Let EclipseLink create database schemas automatically -->
  <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
  <property name="eclipselink.ddl-generation.output-mode" value="database"/>
</properties>

Here's my test file:
public class BookDaoTests {

private BookEJB bookDao;
private Book newBook;

@Before
public void init() {

    newBook = new Book();
    newBook.setName("Flying Cow");
    newBook.setDescription("Super cool story about flying cow");
    newBook.setAuthor("Me");
    newBook.setIsbn10("0123456789");
    newBook.setIllustrations(true);
    newBook.setPublishYear(2013);
    newBook.setNumberOfPages(1567);
    newBook.setQuantity(58);

    bookDao = new BookEJB();

}

@Test
public void createBook() throws Exception{
    bookDao.createBook(newBook);
    Assert.assertEquals("Book was created!", bookDao.findBookByIsbn10("0123456789"), newBook);
}

}

So when I run that test file I get following error:
Testcase: createBook(com.mysite.bookstore.tests.BookDaoTests): Caused an ERROR
null
java.lang.NullPointerException
at com.mysite.bookwebstore.beans.BookEJB.createBook(BookEJB.java:27)
at com.mysite.bookstore.tests.BookDaoTests.createBook(BookDaoTests.java:46)

EM: null

I use following technologies:

*

*Glassfish 4

*JavaEE 7

*JSF

*EclipseLink 2.1

*Java DB

I hope we can find some solution for this problem. I have been tackling now 3 days of this problem and searched and tested solutions from Google and from Stackoverflow but none of the solutions helped/worked. To make sure that the EntityManager was really null, I debugged test file and saw that indeed it gives null. So how can I solve this problem?

A: The EntityManager instance, is injected when the EJB is deployed in the Container.
If you take a look at the lifecycle of enterprise bean, you will see clearly when dependency injection occurs.
When the Container sees the @Persistencecontext annotation it will inject a container-managed EntityManager.
The problem is that the code executed in this test is not managed by the Container, therefore, no one inject the necessary dependencies.
bookDao = new BookEJB();

When you run the test, the BookEJB class is just a simple POJO, the @Stateless and @PersistenceContext annotations are simply ignored.
You have several alternatives in order to test your EJB, take a look at this link.


text:
Q: Making manually mounted LUKS volume visible in Nautilus In Unity under Ubuntu, when I mounted a volume under /media, then it was shown in Nautilus, as if it was mounted by gvfs.
Now I'm running GNOME 3.20.1, which mounts its drives under /run/media/[user]. When I mounted my LUKS volume using /etc/crypttab and /etc/fstab under /mnt, it disappeared from "Other locations" submenu in Nautilus. Even, when I mounted it under /run/media/[user], it still stayed that way.
How to replicate the pre-udisks2 behavior of this?

A: It turns out that adding x-gvfs-show to the mount options does the job.


text:
Q: Week start and end dates within a month in Spark 2.4 Requirement: find out week start date and end date, but only within the given month date.
Input df:
df = spark.createDataFrame([('1', '2022-07-01'), ('2', '2022-07-30'), ('3', '2022-07-31')], ["id", "date"])
df.createOrReplaceTempView("date_table")

# +---+----------+
# | id|      date|
# +---+----------+
# | 1 |2022-07-01|
# | 2 |2022-07-30|
# | 3 |2022-07-31|
# +---+----------+

Expected output:
+---+----------+-----------+-----------+
| id|      date|week_start | week_end  |
+---+----------+-----------+-----------+
| 1 |2022-07-01|2022-07-01 |2022-07-02 |
| 2 |2022-07-30|2022-07-24 |2022-07-30 |
| 3 |2022-07-31|2022-07-31 |2022-07-31 |
+---+----------+-----------+-----------+

The below query does not work, as it goes out of the boundaries of the given month (row id 1 and 3).
spark.sql(""" select id,date,date_sub(date,dayofweek-1) as week_start,
                date_add(date, 7-dayofweek) as week_end FROM
                (select id,date,dayofweek(date) as dayofweek
                FROM date_table) T""")

A: In order to get the expected output, together with what you already have, you could use greatest and least, providing the start and end of month respectively.
SELECT id,
       date,
       greatest(date_sub(date, dayofweek-1), trunc(date, 'MM')) as week_start,
       least(date_add(date, 7-dayofweek), last_day(date)) as week_end
FROM
    (SELECT id, date, dayofweek(date) as dayofweek
     FROM date_table) T

Full example:
df = spark.createDataFrame([('1', '2022-07-01'), ('2', '2022-07-30'), ('3', '2022-07-31')], ["id", "date"])
df.createOrReplaceTempView("date_table")

df = spark.sql(
    """
    SELECT id,
           date,
           greatest(date_sub(date, dayofweek-1), trunc(date, 'MM')) as week_start,
           least(date_add(date, 7-dayofweek), last_day(date)) as week_end
    FROM
        (SELECT id, date, dayofweek(date) as dayofweek
         FROM date_table) T
    """
)
df.show()
# +---+----------+----------+----------+
# | id|      date|week_start|  week_end|
# +---+----------+----------+----------+
# |  1|2022-07-01|2022-07-01|2022-07-02|
# |  2|2022-07-30|2022-07-24|2022-07-30|
# |  3|2022-07-31|2022-07-31|2022-07-31|
# +---+----------+----------+----------+


text:
Q: How can I execute a one liner (without Terminal) in IDEA I'd like to execute a short series of commands in IDEA. realistically the actual commands don't matter, but here it is
git add --all . && git stash && ( git svn dcommit || git svn rebase && git svn dcommit ) && git stash pop

is it possible to make this an "external tool"? without writing an actual .sh script? or perhaps is there some other way? I don't want to keep running it in the terminal, I'd rather click a button (or shortcut it) or find some way to make it execute after commit.


text: Q: How should I cite a reference from another document? How should I cite a reference from another document? Now I am using the xcite package, then \externalcitedocument{docname}, and with the help of \cite{}, I cite the reference that I need. But the problem is that my document compiles with error. It's an error, not a warning. The auxiliary files also exist but still I get this error.


text:
Q: send list through ajax but model is empty in controller action I have model of list in which I get list of two parameters. Data send from view is correct but in controller action it is null
        var model = {
                "IdeaFinancials": ideaFinancials
           };
        model = JSON.stringify({ 'model': model });
        $.ajax({

                url: '@Url.Action("TeamMapping", "Team")',
                type: 'Post',
            contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: model,
                success: function (res) {
                $('#result').html('"PassThings()" successfully called.');
                 },
                failure: function (response) {
                $('#result').html(response);

            });

In Controller Acton
[HttpPost]
        public JsonResult TeamMapping (IEnumerable<UsersTeamMapping> model)
        {
            var mo = _roleServices.GetRolesList();
           return Json(mo, JsonRequestBehavior.AllowGet);
        }

But model is still empty

A:         var model = {
                "IdeaFinancials": ideaFinancials
           };
        $.ajax({

                url: '@Url.Action("TeamMapping", "Team")',
                type: 'Post',
            contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: JSON.stringify(model),
                success: function (res) {
                $('#result').html('"PassThings()" successfully called.');
                 },
                failure: function (response) {
                $('#result').html(response);

            });

inside the UsersTeamMapping must contain the IdeaFinancials attributes check if it contains
Class C#
public class UsersTeamMapping
    {
        public List<string> IdeaFinancials { get; set; }
    }

[HttpPost]
public JsonResult TeamMapping (UsersTeamMapping model)
{
  var mo = _roleServices.GetRolesList();
  return Json(mo, JsonRequestBehavior.AllowGet);
}