text:
Q: How to batch extract images from a PDF TL/DR Version: How do I extract the image out of the Type B file below. Note that there are around 600 such files so I would prefer some sort of batch operation.
Type A Type B

Details: I'm redesigning my company's online catalog an need top extract the design images from ~2000 PDFs which either Type A (where I can export the images using Acrobat XI Tools - Document Processing - Extract All Images) or of Type B.
I don't know how these were designed or the cause for the difference (the PDF creation was contracted out to some now defunct company 2 yrs ago).
As noted above I can batch process (Acrobat XI Action Wizard) all Type A files but that still leaves me with ~600 Type B files for which I am clueless.
Any ideas?

A: This can be done with pdfimages (poppler utils):
http://cgit.freedesktop.org/poppler/poppler/tree/utils


text:
Q: Rolling Average Prediciton for Future 30 Days in DAX I am working on a forecasting graph that will be pulling in data from SQL through power query. The graph will have slicers and filters available to the user to analyze different populations. I am currently being asked to provide a rolling average for each day of the next month but will update daily as more data becomes available. I need 30 days of rolling average that occur after the current date. Using the prior days rolling average calculation. This has to be completed in dax to allow the filters and slicers to work appropriately. The rolling average looks 14 days back.
Any ideas on how to best proceed would be greatly appreciated.
Below is a table of data to show how this looks in excel:

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to intercept and change data passing from DB to ListView? In my application I read data from database, put it into cursor and pass it to ListView using adapter. These data are numbers from 1 to 12, but I need them to be presented in the ListView as names of months. How and on which step of reading and displaying these data can I intercept them and change from numbers to text?

A: You can modify the data, right before it the adapter sets the text to your TextView. It'll be done in adapter's getView method.

A: Try this
import java.text.DateFormatSymbols;
public String getMonth(int month) {
    return new DateFormatSymbols().getMonths()[month-1];
}

A: You may right a custom adapter for that!. If your data is cursor object you can write custom adapter class extending from "CursorAdapter". Other wise you can extend from "BaseAdapter".
call it by:
   ShowListCursorAdapter adapter = new ShowListCursorAdapter(getActivity(), R.layout.fragment_list_detail, cursor,
      columns, views, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    getListView().setAdapter(adapter);

In custom Adapter extends cursorAdapter:
Constructor:
 public ShowListCursorAdapter(Context context, int layout, Cursor cursor,  String[] columns, int[] views, int flag) {
      super(context,cursor,flag);
        mInflater =      (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

 mCursor = cursor;
        mLayout = layout;
        mTo = views;
        mFrom = columns;
    }

Implement 2 methods in CursorAdapter.
  @Override
    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {//This will be called once
        mView = mInflater.inflate(mLayout, viewGroup, false);
        return mView;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {//This is called no.of row times
        for(int i = 0; i< mTo.length;i++) {//If you have single column no need of for loop
            TextView content = (TextView) view.findViewById(mTo[i]);
            content.setText(mCursor.getString(mCursor.getColumnIndex(mFrom[i])));////here you can convert number to month and display
        }
    }


text:
Q: I am having difficulty using mincemeat in python for map-reduce to calculate wordcount of different files Here is the code:
import glob
import mincemeat
import re

text_files = glob.glob('finalcount/1/*')
def file_contents(file_name):
    f = open(file_name)
    try:
        return f.read()
    finally:
        f.close()

source = dict((file_name, file_contents(file_name))
          for file_name in text_files)

def mapfn(key, value):
    for line in value.splitlines():
        list1 = [ ]
        for temp in re.split('[\t]+',line):
            list1.append(temp)
        x = int(list1[1].strip());
        yield [list1[0],x]

def reducefn(key, value):
    return key, sum(value)

s = mincemeat.Server()
s.datasource = source
s.mapfn = mapfn
s.reducefn = reducefn

results = s.run_server(password="wola")
print results

This code is supposed to compute word counts of multiple files. But it keeps returning an error:
error: uncaptured python exception, closing channel <__main__.Client connected at 0x25c1990>
(<type 'exceptions.ValueError'>:invalid literal for int() with base 10: ''
 [C:\Python27\lib\asyncore.py|read|83]
 [C:\Python27\lib\asyncore.py|handle_read_event|444]
 [C:\Python27\lib\asynchat.py|handle_read|140]
 [mincemeat.py|found_terminator|97]
 [mincemeat.py|process_command|195]
 [mincemeat.py|call_mapfn|171]
 [projcount.py|mapfn|21])

The input files that I am working on look like this. Now I want to add the words and sum the number next to them in different files.
fawn    24
gai 1
nunnery 11
sowell  3
sonja   29
woods   591
clotted 1
spiders 84
hanging 522

After replacing re.split with line.split(), I got this error.
error: uncaptured python exception, closing channel <__main__.Client connected at 0x2531990>
(<type 'exceptions.IndexError'>:list index out of range
 [C:\Python27\lib\asyncore.py|read|83]
 [C:\Python27\lib\asyncore.py|handle_read_event|444]
 [C:\Python27\lib\asynchat.py|handle_read|140]
 [mincemeat.py|found_terminator|97]
 [mincemeat.py|process_command|195]
 [mincemeat.py|call_mapfn|171]
 [projcount.py|mapfn|21])

A: I had got this error on a different occasion, i figured out that the problem comes when you are using python 3.3, i removed 3.3 and installed 2.7.5(http://python.org/download/) and it works fine now. :)


text:
Q: Variável não designada Dá-me erro dizendo que a variável remainder não foi designada. Há várias partes do código que eu não percebo e gostaria de explicação.

*Write a program that continually reads in integer values until a four digit number in the range 111 to 9999 is entered. Display the number vertically i.e. each digit on a separate line.

Example:
Input: 1234
Output:
1
2
3
4

    static void Main(string[] args)
    {
        int number, remainder;
        string s = "";

        //Reading a 4-digit number between 1111 and 9999
        do
        {
            Console.WriteLine("Enter a number between 1111 and 9999: ");
            number = int.Parse(Console.ReadLine());
        } while (number < 1111 || number > 9999);/*Por que tenho que pôr esta condição*/

        //Breaking number and formatting it vertically in a string

        while (number > 0)
            remainder = number % 10;
            s = remainder + "\n" + s;
            number = number / 10;

// Não percebi nada das 4 linhas acima, o que fazem?
        //Displaying number vertically
        Console.WriteLine(s); // porquê visualizar a variável s?
        Console.ReadLine();

A: O código está bem confuso, não consegui reproduzir o problema do título, acho até estranho. Na verdade essa variável nem precisa existir.
Vou deixar pra lá os possíveis erros que podem ocorrer em circunstâncias fora do que se espera, comentei de forma simples. Se quiser veja sobre o TryParse().
procure declarar as variáveis mais próximo de onde vai usar. Isto dá mais legibilidade. Também use nomes que identifique o que é a variável.
A condição no primeiro laço está fazendo o que o exercício pede, fica pedindo um novo número até que se digite um número na faixa que é permitida. Se o número está fora dela, repete o pedido.
Mandou imprimir a variável de texto, que chamava s no original porque o exercício manda imprimir, tem que mostrar na tela.
using static System.Console;

public class Program {
    public static void Main() {
        int number;
        do {
            WriteLine("Enter a number between 1111 and 9999: ");
            number = int.Parse(ReadLine()); //isto dá erro se digitar algo errado, deveria usar TryParse()
        } while (number < 1111 || number > 9999);
        var texto = "";
        while (number > 0) {
            texto = number % 10 + "\n" + texto; //o uso de \n pode não ser o ideal sempre
            number /= 10;
        }
        WriteLine(texto);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.


text:
Q: google places api many filters by type Ex.: restaurant,cafe I'm trying to change the radius category/type filter for a checkbox, so I changed the var type to an array.
ORIGINAL WORKING:
var type;
        for (var i = 0; i < document.controls.type.length; i++){
            if (document.controls.type[i].checked){
                type = document.controls.type[i].value;
            }
        }
    startBox.setBounds(map.getBounds());
        var search = {
        // keyword: 'comocomo', // not needed with the autocomplete / startBox
        bounds: map.getBounds()
        };
            if (type != 'establishment'){
                search.types = [ type ];
            }
    places.search(search, function(placesArr, status){

THE ONE WITH THE ARRAY NOT WORKING: edited:
    var type=[];
for (var i = 0; i < document.controls.type.length; i++){
    if (document.controls.type[i].checked){
        type.push(document.controls.type[i].value)
    }
}
startBox.setBounds(map.getBounds());
    var search = {
        bounds: map.getBounds()
    };

var quotedAndCommaSeparated = "'" + type.join("','") + "'";

alert(quotedAndCommaSeparated); // 'establishment','restaurant','lodging'

search.types = [ quotedAndCommaSeparated ];

I made many tests, and I don't see what I'm doing wrong. the map doesn't even show.

A: What's this meant to be, doesn't look like valid Javascript to me:
var type[];

Should be
var type = [];

Fix the javascript errors in your code otherwise the map won't show up.
Update:
What you have in quotedAndCommaSeparated is a string like "'a','b','c'" that looks a bit like the contents of an array: ['a','b','c']. But it's not an array, it's just a single string. If you check the length of your search.type array, I'm guessing it equals 1.
What you can do is split your string on the comma to turn it into an array:
search.types = quotedAndCommaSeparated.split(",");


text:
Q: TypefaceJS site down / need help converting Can anyone help me convert two type faces to typeFace.js code. The site seems down or no longer in service.
Font types
univers 67 condensed Bold 14pt
Novecento Light Wide / Light Wide 53pt
Novecento Light Wide / Light Wide 18pt
Let me know thanks.

A: http://gero3.github.io/facetype.js/ is another convertor for typeface.js.
PS: I'm the author of facetype.js


text:
Q: Buffer process in polygon using GDAL I am trying to decrease the size of a polygon so to avoid having mixels. Thus, I use the GDAL function buffer:
distance = -5
bufferedGeometry= initialGeometry.Buffer(distance)

In addition, the geometry is in 3857 Projection.
Does -5 mean -5 meters for each point of the polygon's ring?
How does the buffer process takes place?


text:
Q: Is there a built in way to make custom events in JavaScript natively? I was playing around with JavaScript a little while ago, and it irritated me that I couldn't create my own event.
I've seen Framework's with this built in (jQuery, MooTools, Prototype. Dojo doesn't which is weird because it seems to do everything and your laundry) and I actually built my own system for creating and firing custom events.
It just feels like there should be a native way to do it. Does anyone know how to do this/if you even can?

A: var dragEvent = document.createEvent("Event");
dragEvent.initEvent("dragged", true, true);
el.dispatchEvent(dragEvent);

For official specs, see DOM Level 2 Events. See also createEvent(), initEvent() / initMouseEvent() / initUIEvent(), and dispatchEvent() at MDC.
I use this technique to create custom drag and resize events for communication on this sample page.


text:
Q: webservices access from other application So i have a website in angularJS.
Users can login and receive sensible data via REST webservice.
Some users leave their login+password in a post-it, in their table. (i cant change this)
In the same room there is another person, that does not have login to the system. He sees the login+pass on the post-it, and he made a 'bot' application, to login and retrieve all sensible information from webservice. (i dont know who is this person)
How can i block him, and keep my website working normally?
Thanks


text:
Q: Elasticsearch nested object filter I am new to Elasticsearch and I am trying to create a filter to retrieve documents that have specific attributes.
The attributes are defined as nested objects in the mapping like so:
"attributes": {
  "type": "nested",
    "properties" : {
      "id": {
        "type": "integer"
      },
      ...
    }
  }
}

I am trying to perform a complex query in the form of:
(attribute.id == 1 OR attribute.id == 2) AND (attribute.id == 3 OR attribute.id == 4)

According to what I've read so far I've created the following query to es:
{
  "query": {
    "filtered": {
     "query": {
        "match_all": {}
     },
     "filter": {
        "nested": {
           "path": "attributes",
           "filter": {
              "bool": {
                "must": [
                    { "bool" : {
                      "should" : [
                        { "term": { "attributes.id": 1 }},
                        { "term": { "attributes.id": 2 }}
                      ]
                    }},
                    { "bool" : {
                      "should" : [
                        { "term": { "attributes.id": 3 }},
                        { "term": { "attributes.id": 4 }}
                      ]
                    }}
                ]
              }
           }
        }
     }
  }
},
"sort": {
    "date": { "order": "desc" }
  }
}

However this doesn't return any results. If I remove one of the two bools in the must block it filters the documents correctly.
Same problem exists (no results) if I change the query (for testing purposes) to:
"must": [
  { "term": { "attributes.id": 3 }},
  { "bool" : {
    "should" : [
      { "term": { "attributes.id": 1 }},
      { "term": { "attributes.id": 2 }}
    ]
  }}
]

which to my understanding translates to attributes.id == 3 AND (attributes.id == 1 OR attributes.id == 2)
This is elasticsearch 2.x. What I am doing wrong?

A: In order to get the results you are looking for, you will need to do two separate nested queries and link them together with a bool query.
Here is an example:
{
  "bool":{
    "must":[
      {
        "nested":{
          "path":"attributes",
          "filter":{
            "bool":{
              "should":[
                { "term": {"attributes.id": 1 }},
                { "term": {"attributes.id": 2 }}
              ]
            }
          }
        }
      },
      {
        "nested":{
          "path":"attributes",
          "filter":{
            "bool":{
              "should":[
                { "term": {"attributes.id": 3 }},
                { "term": {"attributes.id": 4 }}
              ]
            }
          }
        }
      }
    ]
  }
}

The reason for this is due to a subtle nuance with nested documents and nested queries. Have a look at the part of the documentation on nested queries that says:

The query is executed against the nested objects / docs as if they
  were indexed as separate docs (they are, internally) and resulting in
  the root parent doc (or parent nested mapping).

When doing a nested query, you are not actually performing your query against the root document (though it feels that way). The query is operating against the nested documents as if they were separate docs.
Therefore, when you query for a nested document that has both id=(1 or 2) AND id=(3 or 4) you get no results. Each nested document, in your data it seems, has only one of these id values.


text:
Q: QNX's shutdown_system is not function well when ZMQ lib is used When QNX's shutdown_system() is called from command line (shutdown) or from within any process, it's expected to restart the system,when called as shutdown_system(SHUTDOWN_REBOOT, 0);
There are several processes running on our QNX system. For interproces communication we are using libzmq.
When shutdown_system is called from command line, it is working all good. The system is restarted as expected.
But when the shutdown_system is called from a particular process ( when libzmq calls are enabled ) what is observed is that the process from which shutdown_system is called is killed and the QNX system goes off network. But all other processes are running well on QNX system.
I commented all zmq's related calls and rerun the system, this time shutdown_system when called from within a process restarts the system as expected.
Something in ZeroMQ is stopping the SIGTERM | SIGKILL to other process and also stopping the restart of the system. I tried disconnecting the ZeroMQ connection before issuing the system_shutdown in process, but it did not help.


text:
Q: Can not restore minimized/switched full-screen applications/games Recently I re-installed a fresh copy of Windows 7 with all available updates downloaded for both Windows and Drivers and with no problems at all.
Everything was good but when last night I started Steam in full-screen mode then started a video game and switched to desktop, then I couldn't switch back to either both of them from the taskbar or even with Alt-Tab.
I had figured only two ways to switch back; the first by Bring to Front from the task manager (Doesn't work with all) and by Restore by right-clicking the taskbar icon preview.
What could be causing this, and how can I fix it?

A: Different games behave differently in Full-Screen mode. If you can run the game in a Window or a Full-Screen-Window you should not have this issue. If you must run in Full-Screen then do not ALT-TAB out if you know there is an issue. The way the graphics sub-system behaves with Full-Screen (non-Windowed) games is completely different to a Windowed app.
Are you saying it use to work correctly before your re-install and now does not (you are not clear on this matter).


text:
Q: Function that receives a char and returns the square power of it's integer value I need to create a function that transmits a parameter as a 'char' and returns the value of that 'char' as a integer at its square value.
For example:
char nr[] = "11";
cout << strToNumber(nr);//will return the value 121;

int strToNumber (char c[]) {
int cifra, rezultat, fin;
cifra = c - '0';
return cifra * cifra;
}

int main () {

char sir[9] = "13";
char c;

int n = strlen(sir);
  for (int i = 0; i < n; ++i) {
   c = sir[i];
    strToNumber(c);
  }
return 0;
}

I tried to send the whole 'char' as a parameter one at a time. First I sent sir[0] which is '1' and afterwards I sent sir[1] which is '3'. The problem is that I did not manage to save the parameters in one variable so that I can easily multiply it by itself. In this case each parameter is multiplied by itself one at a time. '1' * '1' and '3' * '3'.
I am new to this 'char' and I do not fully understand it yet. If there is another way to send my parameters and to handle the function I would truly appreciate it... Thanks in advance!


text:
Q: Add header and footer to XPS print output XpsDocument is loaded from disk
Create a FixedDocumentSequence via XpsDocument.GetFixedDocumentSequence Method ()
Display the via a DocumentViewer
Would like to add to add header and footer to print
I don't need to add the header and footer back to the XPS document - only to the print output
I tried implementing DocumentPaginator but cannot get the sizing or placement to work
NOT the same as this footer to FlowDocument
I use the solution there for FlowDocuments just fine
Convert XAML Flow Document to XPS with Style
On the FixedDocumentSequence the sizing comes from document (I guess)
For example could mix landscape and portrait
I cannot figure out how to hook into the sizing and make room for a header and footer
I can stamp a header on it but it is over the top of the page
And landscape pages are cut off
Cannot assign a PageSize when it comes from a FixedDocumentSequence
As stated in the link it is a suggested pages size
DocumentPage.Size is read only
Even if I create DocumentPage of the Size I want when the page is loaded using DocumentPaginator.GetPage then the Size is overwritten
Even worse the  DocumentPaginator does not seem to be properly aware of the Size as it does not deal with mixed landscape and portrait properly.  Landscape is printed portrait and just runs off the page.
some one asked me to post code
there also might be a just plain better approach
see footer to FlowDocument for how to use it
this is where it breaks
// this gets the page size from GetPage - ignores size above
public class DocumentPaginatorWrapperXPS : DocumentPaginator
{
    System.Windows.Size m_PageSize;
    System.Windows.Size m_Margin;
    DocumentPaginator m_Paginator;
    FixedDocumentSequence fixedDocumentSequence;
    Typeface m_Typeface;
    private string printHeader;
    private int? sID;
    private string docID;

    public DocumentPaginatorWrapperXPS(FixedDocumentSequence FixedDocumentSequence, System.Windows.Size margin, string PrintHeader, int? SID, string DOCID)
    {
        //m_PageSize = pageSize;
        //m_PageSize = new Size(800, 600);

        fixedDocumentSequence = FixedDocumentSequence;

        m_Margin = margin;
        m_Paginator = fixedDocumentSequence.DocumentPaginator;
        //m_Paginator.PageSize = new System.Windows.Size(m_PageSize.Width - margin.Width * 2,
        //                                               //m_PageSize.Height - margin.Width * 2);
        printHeader = PrintHeader;
        sID = SID;
        docID = DOCID;
    }
    Rect Move(Rect rect)
    {
        if (rect.IsEmpty)
        {
            return rect;
        }
        else
        {
            return new Rect(rect.Left + m_Margin.Width, rect.Top + m_Margin.Height,
                            rect.Width, rect.Height);
        }
    }
    private Size sizeXPS;
    public override DocumentPage GetPage(int pageNumber)
    {
        System.Windows.Documents.DocumentPage page = m_Paginator.GetPage(pageNumber);
        Debug.WriteLine(page.Size.Width + " " + page.Size.Height);

        m_Paginator.PageSize = new System.Windows.Size(page.Size.Width/2 - m_Margin.Width * 2, page.Size.Height/2 - m_Margin.Height * 2);

        page = m_Paginator.GetPage(pageNumber);  // this get the page size from GetPage - ignores size above
        Debug.WriteLine(page.Size.Width + " " + page.Size.Height);

        DynamicDocumentPaginator paginatorPage = fixedDocumentSequence.DocumentPaginator as DynamicDocumentPaginator;
        paginatorPage.PageSize = new System.Windows.Size(page.Size.Width / 2 - m_Margin.Width * 2, page.Size.Height / 2 - m_Margin.Height * 2);
        sizeXPS = new System.Windows.Size(page.Size.Width / 2 - m_Margin.Width * 2, page.Size.Height / 2 - m_Margin.Height * 2);
        page = paginatorPage.GetPage(pageNumber);  // still does not change the page size
        Debug.WriteLine(page.Size.Width + " " + page.Size.Height);

        //page.PageSize = new System.Windows.Size(m_PageSize.Width - margin.Width * 2,
        //m_PageSize.Height - margin.Width * 2);
        //page.Size = new System.Windows.Size(page.Size.Width - m_Margin.Width * 2, page.Size.Height - m_Margin.Height * 2);
        //page.Size.Width = page.Size.Width - m_Margin.Width * 2;
        // Create a wrapper visual for transformation and add extras

        ContainerVisual newpage = new ContainerVisual();
        DrawingVisual title = new DrawingVisual();
        using (DrawingContext ctx = title.RenderOpen())
        {
            if (m_Typeface == null)
            {
                m_Typeface = new Typeface("Segoe UI Symbol");  //Ariel
            }
            //FormattedText text = new FormattedText("Attorney eyes only  \uE18B  \u1F440                Page " + (pageNumber + 1),
            //                                        System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
            //                                        m_Typeface, 14, System.Windows.Media.Brushes.Black);

            string pageS = "m_PageSize.Width " + m_PageSize.Width + "  m_Margin.Width " + m_Margin.Width + "  m_PageSize.Height " + m_PageSize.Height + "  m_Margin.Height " + m_Margin.Height + Environment.NewLine +
                            "page.Size.Width " + page.Size.Width + "  page.Size.Height " + page.Size.Height;
            FormattedText header = new FormattedText("\u1F440 " + printHeader + Environment.NewLine + pageS,
                                                    System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                                                    m_Typeface, 14, System.Windows.Media.Brushes.Black);
            ctx.DrawText(header, new System.Windows.Point(96 / 2, -96 / 4)); // 1/4 inch above page content
            //text = new FormattedText(pageS, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
            //                         m_Typeface, 14, System.Windows.Media.Brushes.Black);

            string goGabe = string.Empty;
            if (sID != null)
            {
                goGabe += Environment.NewLine + "Gabriel Docs™ sysDocID: " + sID;
                if (!string.IsNullOrEmpty(docID))
                    goGabe += "  docID: " + docID;
            }
            goGabe += Environment.NewLine + "Page: " + (pageNumber + 1) + "   Date: " + DateTime.Now.ToString() + "  User: " + App.StaticGabeLib.CurUserP.UserID;
            FormattedText footer = new FormattedText(goGabe
                                                    , System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                                                        m_Typeface, 14, System.Windows.Media.Brushes.Black);
            ctx.DrawText(footer, new System.Windows.Point(96 / 2, page.Size.Height - m_Margin.Height));
            //ctx.DrawText(footer, new System.Windows.Point(96 / 2, m_Paginator.PageSize.Height - m_Margin.Height));
        }
        DrawingVisual background = new DrawingVisual();
        using (DrawingContext ctx = background.RenderOpen())
        {
            ctx.DrawRectangle(new SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240)), null, page.ContentBox);
        }
        newpage.Children.Add(background); // Scale down page and center
        ContainerVisual smallerPage = new ContainerVisual();
        smallerPage.Children.Add(page.Visual);
        smallerPage.Transform = new MatrixTransform(0.8, 0, 0, 0.8, 0.1 * page.ContentBox.Width, 0.1 * page.ContentBox.Height);
        newpage.Children.Add(smallerPage);
        newpage.Children.Add(title);
        newpage.Transform = new TranslateTransform(m_Margin.Width, m_Margin.Height);
        return new DocumentPage(newpage, m_PageSize, Move(page.BleedBox), Move(page.ContentBox));
    }
    public override bool IsPageCountValid
    {
        get
        {
            return m_Paginator.IsPageCountValid;
        }
    }
    public override int PageCount
    {
        get
        {
            return m_Paginator.PageCount;
        }
    }
    public override System.Windows.Size PageSize
    {
        get
        {
            Debug.WriteLine("PageSize " + sizeXPS.Width + " " + sizeXPS.Height);
            return sizeXPS;  // this is not called

            //m_Paginator.PageSize;
        }
        set
        {
            sizeXPS = value;
            // m_Paginator.PageSize = value;
        }
    }
    public override IDocumentPaginatorSource Source
    {
        get
        {
            return m_Paginator.Source;
        }
    }
}


text:
Q: second form action attribute not working I have 2 form action below and whenever I click the 2nd form action (post /logout), the first action (get /journey) get triggered.
<form action="/journey" method="get"><input type="submit" value="Journey" />
<form action="/logout" method="POST"><input type="submit" value="Logout" />

The second action works if I didn't add in the /journey action.
Anyone can tell me what's wrong? Thanks.

A: try after closing form tags as shown below :

   <form action="/journey" method="get">
       <input type="submit" value="Journey" />
    </form>

    <form action="/logout" method="POST">
        <input type="submit" value="Logout" />
    </form>


text:
Q: rect error-boundary doesn't work properly When using react-boundary and throw a manual error, the error-boundary works! The problem is, after 1-2 seconds it renders the error as if there wasn't an error-boundary
This is the code
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  render() {
    console.log('has error', this.state);
    if ((this.state as any).hasError) {
      // You can render any custom fallback UI
      return
Something went wrong.
;
    }

    return this.props.children;
  }
}

function Bomb(): any {
  const a = null;
  return {a.b.c};
}

function App() {
  const [explode, setExplode] = React.useState(false);

  return (

      <button onClick={() => setExplode((e) => !e)}>toggle explode</button>
      <ErrorBoundary>{explode ? <Bomb /> : null}</ErrorBoundary>

  );
}

And this is the behavior:

A: For those interested, I just found out that it actually works properly. ErrorBoundary fallback is rendered and because NODE_ENV is set to development, debug overlay appears. When you set display: none to overlay iframe, you'll see expected "Something went wrong.".


text:
Q: Something like "Power assert" in Scala similar to Groovy? I'm wondering if there is something that can give me results similar to Groovy's nice power assert statement.
> assert ["1", '2']*.size() == [2, 3]

Result: Assertion failed:

assert ["1", '2']*.size() == [2, 3]
                   |      |
                   [1, 1] false

AFAIK there is no support for such thing neither in language, nor in
scalatest, which I'm currently using.
But maybe someone can suggest some side library doing that? It's a pet project, so experimental and not well-supported libs are fine.
EDIT: I know about matchers (scalatest ones, or even plain-java hamcrest matchers). I find them verbose to write and that their output lacks details.
The example above shows intermediate computation steps, facilitating detection of errors. It shows you what's wrong with tested code with more details.
I expect, that introducing such behaviour will require having information about expression AST at runtime. But I suppose, that this information can be "baked" compile time with usage of macroses.
I.e. if we have expression assert a + b == c scala (or some macro extension I'm looking for) can rewrite it to something like:
if (!(a + b == c)) {
  // detailed message is
  // compute a
  // compute b
  // compute a + b
  // compute c
  // compute a + b == c
  // Make it pretty.

  throw new AssertionFailedException(prettyDetailedMessage)
}

So I'm looking if it's already implemented, and if yes - where.

A: In ScalaTest, you can use DiagrammedAssertions.
See http://www.scalatest.org/release_notes/2.2.0#diagrammedAssertions
This is based on Expecty which is a macro-based implementation of Spock's power assertions. See https://github.com/pniederw/expecty

A: Specs2 matchers do a good job with error messages:
class Specs2Specification extends Specification {
  "specs2 assertion" should {
    "fail" in {
      List("1", "2").map(_.length) must_=== List(2, 3)
    }
  }
}

run output:
[info] Specs2Specification
[info]
[info] specs2 assertion should
[error]   x fail
[error]    List(1, 1) is not equal to List(2, 3)
[info]
[error] Added (2)
[error] 1
[error] 1
[info]
[error] Missing (2)
[error] 2
[error] 3

or
List("1", "2").map(_.length) must contain(exactly(2, 3)).inOrder

which produces
[error]   x fail
[error]    the values 2, 3 are not in order

There are lots of them and you can create custom ones.

A: Your groovy code snippet is literally translated to the following scala code (given that you're already using scalatest):
assert((List("1", "2") map (_.length)) === List(2, 3))

It produces the following error message:
*** FAILED ***
List(1, 1) did not equal List(1, 3)


text:
Q: Extract Max single upper character from table in oracle I have test input table
-----------------------
RN | IDs
1  | Az
2  | Azz
3  | B
4  | C
5  | a
6  | e
--------------------

I need Output
----------
RN | IDs
4  |  C

I need to get Id which is in UPPER case and single(length 1) also that ID should max in sequence. Like in this example C is the output.
Because Size is 1 , case is UPPER and MAX in sequence.
Can you please help me here.

A: The first step is identifying the ids values you want to consider. One way it to check the length and the character range:
where length(ids) = 1
and ids between 'A' and 'Z'

which makes some assumptions about your character set, or use a regular expression which also makes some assumptions:
where regexp_like(ids, '^[A-Z]$')

or preferably one which doesn't, using a class instead of a fixed range:
where regexp_like(ids, '^[[:upper:]]$')

With your data any of those give you two rows, for B and C.
You then need to find the row with the maximum ids value. You could do a self-join which is a bit wasteful; or use a subquery that calculates a ranking column and then filter on that:
select rn, ids
from (
  select rn, ids, rank() over (order by ids desc) as rnk
  from your_table
  where regexp_like(ids, '^[[:upper:]]$')
)
where rnk = 1;

        RN IDS
---------- ---
         4 C

or you could use a variant of the max() function with last to do it in one step:
select max(rn) keep (dense_rank last order by IDs) as rn, max(ids)
from your_table
where regexp_like(ids, '^[[:upper:]]$');

        RN MAX
---------- ---
         4 C

You haven't said what should happen if there is a tie, e.g. two rn values with C. The first of those approaches will show you both - but could be modified to only show one, if you can specify which you want to see. The second will only show you one, and which is indeterminate at the moment as there is no information in the order by on how to break the tie.

A: Use the ASCII Function
select max(RN) as MAX_ID from yourTableName t1
where length(t1.IDs)=1 and  ascii(IDs)  between ascii('A') and  ascii('Z');

A: Try this:
SELECT MAX(RN) FROM test
WHERE LENGTH(ID)=1 AND (UNICODE(ID) != UNICODE(LOWER(ID))
GROUP BY ID;

A: You can do it in this way, enjoy :)
select h.ID, h.DESC
  from test_table h
 where length(h.DESC) = 1
   and upper(h.DESC) = h.DESC
   and h.ID = (select MAX(y.ID)
                 from test_table y
                where length(y.DESC) = 1
                  and upper(y.DESC) = y.DESC)

A: It's enough to filter out length(IDs)=1 firstly, and ordering with respect to decode(upper(IDs),IDs,0,1), IDs desc
select RN , IDs
  from
    (
     select t.*,
            row_number() over (order by decode(upper(IDs),IDs,0,1), IDs desc )
            as rn2
       from t
      where length(IDs)=1
    )
 where rn2 = 1;

 RN      IDS
 -----   -----
  4        C

Rextester Demo


text:
Q: Show that an operator with certain properties is an isomorphism Suppose $H$ is an infinite dimensional separable Hilbert space, with $\langle \cdot,\cdot\rangle$ denoting the duality pairing between the dual $H'$ and $H$  and $(\cdot,\cdot)$ the inner product on $H$.  Let $A\,:\,H \to H'$ be a bounded linear functional such that
(a) there exists $\gamma \in H$ such that for all $v \in H$ we have $\langle A\gamma, v\rangle = \mu (\gamma,v)$, where $\mu < 0$;
(b) there exists $c > 0$ such that $\langle Aw,w\rangle \geq  c \|w\|^2$ for all $w \in W$, where $W := \{ v \in H\,|\, (v,\gamma) = 0\}$.
It seems untuitively clear that $A$ is invertible, because we have a sole negative eigenvalue $\mu$ and the rest of the spectrum is bounded below by $c$. Is it an isomorphism? For that we would have to be able to find $c_2 > 0$ such that for all $v \in H$ we would have $\|Av\| \geq c_2 \|v\|$.
My futile attempt at establishing such an inequality centered around the decomposition $v = \alpha \gamma + w$, where $w \in W$ and $\alpha$ is some scalar. For instance we then have
$$
\langle Av,v \rangle = \alpha^2\mu\|\gamma\|^2 + \langle Aw,w \rangle \geq \alpha^2 \mu \|\gamma\|^2 + c\|w\|^2,
$$
but the fact that $\mu < 0$ seems to destroy the usual argument. I have a strong imppresion I am missing something obvious here. I'll gladly accept any comments you might have.
Edit: I probably should have also mentioned that $A$ is assumed self-adjoint in the sense that $\langle Av,w \rangle = \langle Aw,v \rangle$ for any $v,w \in H$.

A: Let $v = \alpha \gamma + w$.
Instead of $v$ we use $ -\alpha \gamma + w$ as test function:
$$
\langle Av, -\alpha \gamma + w \rangle = \alpha\mu (\gamma,-\alpha \gamma + w) + \langle A(-\alpha \gamma + w),w\rangle
=- \alpha^2 \mu \|\gamma\|^2 + \langle Aw,w\rangle \\
\ge
\alpha^2 |\mu| \cdot\|\gamma\|^2 + c \|w\|^2.
$$
Now $\|{\pm}\alpha\gamma + w\|^2 = \alpha^2 \|\gamma\|^2 + \|w\|^2$, which implies
$$
\langle Av, -\alpha \gamma + w \rangle \ge \min(|\mu|,c) \|v\|\cdot \|-\alpha \gamma + w\|$$
and
$$
\|Av\|_{H'} \ge \min(|\mu|,c) \|v\|.
$$

A: Here is a different way to look at this. If you identify $H$ with $H'$ and decompose $H$ as $H=\mathrm{lin}\{\gamma\}\oplus\{\gamma\}^\perp$, then $A$ decomposes as
$$
A=\begin{pmatrix}B&C\\D&E\end{pmatrix}.
$$
By property (a), $B=-\mu$ and $D=0$. Self-adjointness implies $C=0$ and $E=E^\ast$. Finally, $E$ is invertible by property (b). Thus $A$ is invertible as diagonal operator matrix with invertible diaogonal entries with inverse
$$
A^{-1}=\begin{pmatrix}\mu^{-1}&0\\0&E^{-1}\end{pmatrix}.
$$


text:
Q: Is RETRACT stream necessary in Flink? When using RETRACT stream in Flink, update message is finished by two stages, while when using UPSERT stream, it's finished by one stage, which is more efficient.
However, UPSERT stream is not allowed when converting a Dynamic table to a DataStream according to this page, why such a limitation exists? What kinds of problems will be met when we totally replace RETRACT with UPSERT in Flink's design?

A:
What kinds of problems will be met when we totally replace RETRACT with UPSERT in Flink's design?

As the page you linked to mentions, upsert streams require a primary key. Getting rid of retract streams as a concept, consequently, would break all scenarios where you do not have such a key (at all or just not defined).


text:
Q: Isomorphism between two $K$-algebras Consider a field extension $L\subseteq K$ and suppose that $I=(f_1,\ldots,f_m)$ is an ideal of $L[T_1,\ldots,T_n]$. Denote with $I^e\subseteq K[T_1,\ldots,T_n] $ the extended ideal of $I$ through the canonical immersion $\iota:L[T_1,\ldots,T_n]\longrightarrow K[T_1,\ldots,T_n] $. Now I have to prove the following isomorphism of $K$-algebras
$$ \frac{L[T_1,\ldots,T_n]}{I}\otimes_L K\cong \frac{K[T_1,\ldots,T_n]}{I^e}  $$
Maybe an explicit isomorphism can be given by $I+g\otimes a\longmapsto I^e +ag $, but I have problems to find the inverse. Any suggestion?
Thanks in advance

A: Firstly, note that $L[T_1,\ldots,T_n]$ is a $L$-vector space. You can see pretty easily that $L[T_1,\ldots,T_n]\otimes_L K\cong K[T_1,\ldots,T_n]$. Similarly, it should be clear that $I^e = I\otimes_L K$.
Consider the exact sequence of $L$-modules (ie, $L$-vector spaces)
$$0\rightarrow I\rightarrow L[T_1,\ldots,T_n]\rightarrow L[T_1,\ldots,T_n]/I\rightarrow 0$$
Since $K$ is a flat $L$-module (any module over a field is flat), you get an exact sequence
$$0\rightarrow I\otimes_L K\rightarrow L[T_1,\ldots,T_n]\otimes_L K\rightarrow (L[T_1,\ldots,T_n]/I)\otimes_L K\rightarrow 0$$
ie, you have an exact sequence
$$0\rightarrow I^e\rightarrow K[T_1,\ldots,T_n]\rightarrow(L[T_1,\ldots,T_n]/I)\otimes_L K \rightarrow 0$$
which presents $(L[T_1,\ldots,T_n]/I)\otimes_L K$ as a quotient of $K[T_1,\ldots,T_n]$ by $I^e$.


text:
Q: The product of a separable metric space and a Lindelöf space need not be Lindelöf In my chinese book, it offers an example: there exist a separable metric space $X$ and a Lindelöf space $Y$, such that $X \times Y$ is not a Lindelöf space. However, the construction of this space is unclear, and I think maybe something is wrong. Does somebody know this example?

A: The spaces $X\,'$ and $Y\,'$ in the next-to-last paragraph of this classic paper by E.A. Michael are respectively regular Lindelöf and metrizable, and their product is not Lindelöf. Dan Ma explains a similar example in this post to his Topology Blog.


text:
Q: How to watch changestream in mongoDB and send the updates to an ajax call? I'm using the new feature of MongoDB 3.6 watch() in order to send updates of the database from the node server to ajax in the client side.
I created a webservice queried periodically by an ajax call. Between two successive ajax calls, i want the second one to get all the updates that occurred in the mean time. I know that i have to resume the change stream as shown in the official documentation here : https://docs.mongodb.com/manual/changeStreams/#resume-a-change-stream . However i didn't find out how to apply this to my specific needs, by that i mean, in which callback can i process my data and send it to the webservice response ?
Here is a part of my server side code : server.js
const pipeline = [
  {
    $match : {
      "operationType" : "insert"
      ,
      "fullDocument.T" : { "$exists":true}
    }
  },
  {
    $project: { "fullDocument.ts": 1,
                "fullDocument.T":1}
  }
];

function getLiveData(handler){

console.log("in getLiveData");
var liveArray=[];

var resumeToken;

const changeStream = dbObject.collection('status').watch(pipeline);
changeStream.hasNext(function(err, change) {
  if (err) return console.log(err);
  expect(err).to.equal(null);
  expect(change).to.exist;
  console.log("in changeStream.hasNext");

  changeStream.next(function(err, change) {
    if (err) return console.log(err);
    expect(err).to.equal(null);
    console.log("in changeStream.next");
    resumeToken = change._id;

    expect(change._id).to.exist;
    expect(changeStream.resumeToken).to.exist;

    changeStream.close(function(err) {
      if (err) return console.log(err);
      expect(err).to.equal(null);
      console.log("in changeStream.close");
      const newChangeStream = dbObject.collection('status').watch({ resumeAfter: resumeToken });

      newChangeStream.next(function(err, next) {
        if (err) return console.log(err);
        expect(err).to.equal(null);
        expect(next).to.exist;
        console.log("in newChangeStream.next");

        //my own code
        newChangeStream.on("change", function(change) {
        console.log('in change stream, change : ',change);
        liveArray.push([change.fullDocument.ts, change.fullDocument.T]);

        var response = {
            "liveArray" : liveArray
        };

        console.log("from getLiveData : " , response);

        handler(response);
      });
        //my own code

        // Since changeStream has an implicit seession,
        // we need to close the changeStream for unit testing purposes
        newChangeStream.close();
      });
    });
  });
});

}

webservice part :
 app.get("/liveDataRequest", function(req, res){
      getLiveData(function(data){
        console.log("in handler", data);
        res.status(200).send(data);
      });

And here is the console log, as we can see, the part where i process my data never gets called :
in getLiveData
in changeStream.hasNext
in changeStream.next
in changeStream.close
in newChangeStream.next
in getLiveData
in changeStream.hasNext
in changeStream.next
in changeStream.close
in newChangeStream.next


text:
Q: Run multiple updated Docker containers in Jenkins pipeline separated steps without inside commands I have a requirement to run 2 docker containers in Jenkins pipeline separated steps.
I am looking for the exact code to do so in a pipeline.
The issue is that I found an example with running command/s inside the Docker container.
I don't need to run any other command rather than the container's default.
Also, the containers should both run in the same specific Docker network.
I don't want to use a Dockerfile to run each container.
The container images are downloaded from DockerHub.
I'm trying to avoid shell commands in the Jenkins pipeline  (sh) like:
sh 'docker pull someimage:latest'

Edit:
Currently I cannot run a container and leave it running because

docker.image('someimage').run

doesn't work.
I get an error:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No
signature of method:
org.jenkinsci.plugins.docker.workflow.Docker.run() is applicable for
argument types: (java.lang.String) values: [server] Possible
solutions: dump(), find(), grep(), any(), build(java.lang.String),
find(groovy.lang.Closure)

The only options which work are .withRun or .inside but the container stops after a few seconds.
The jenkinsfile without the exact URLs and Docker image name
docker.image .withRun and .inside examples


text:
Q: Multithreading: simple program Segment fault (core dumped) I am trying to create a program which calculates prime numbers from 1 to 1000. I believe the code is having trouble either creating or joining the pthreads. I keep getting a core dump error. My main concern is in the second for loop where I am joining the pthreads. Is this the correct way to check if a thread has ended?
I am using gcc --std=c99 -Wall -Werror -pthread primes.c -o primes in the terminal.
    while (test_val <= FINAL){
        //loop to check if thread is finished
        for(int i = 0; i < THREADS; i++){
            if(tid[i] == 0){
                pthread_create(&tid[i], NULL, testprime, NULL);

            }
        }
        //wait for thread to end
        for(int i = 0; i < THREADS; i++){
            pthread_join(tid[i], NULL);

This is the error:
Segmentation fault (core dumped)

A: Here:
for(int l = 0; ti < MAX_THREADS; ti++){
    if(tid[l] == 0){
        pthread_create(&tid[l], NULL, testprime, NULL);
        tid[l] = 1;
    }
}

First argument of pthread_create is an output thread handle. On the next line, you're setting this value to 1 (probably to mark it as used).
When performing pthread_join on those invalid handles, you invoke undefined behaviour.
Remove this assignment, thread handles aren't 0, so your code will work anyway.

A: You just need to correct your for loop here. You don't need to assign a value in the array. When you call pthread_create it will store the thread id in every location of your thread array.
for(int ti = 0; ti < MAX_THREADS; ti++){
        if(tid[ti] == 0){
            pthread_create(&tid[ti], NULL, testprime, NULL);
            //tid[l] = 1;
        }


text:
Q: The destructor in a class keeps calling it's self when using the class I'm running this code:
import random
class Pound:
    def __init__(self):
        self.value=1.00
        self.color="gold"
        self.num_ages=1
        self.diameter=22.5
        self.thickness=3.15
        self.heads=True
        self.num_pocket=10

    def __del__(self):
        print("Coin spent!")

    def rust(self):
        self.color="greenish"

    def clean(self):
        self.color="clean"

    def flip(self):
        heads_options=[True,False]
        choice=random.choice(heads_options)
        self.heads=choice

coin1=Pound()
print(coin1.value)

When I run it in the Python IDLE I have no issues whatsoever. But when I run it in ATOM (using the atom-python-run or the script package) it always shows me this output:
1.0
Coin spent!

The destructor seems to call itself. I have no clue how to solve the issues and I haven't found anything asked about this anywhere.

A: In this code, when interpreted as a script, the object goes out of scope right after print since after that, the program ends. __del__ is called in that case because at that point, "the instance is about to be destroyed" (docs).
When run from a REPL though (like IDLE), it doesn't go out of scope until you kill the REPL, so __del__ isn't called right away.
This is the expected behavior.

Also note, the docs don't prefer the word "destructor":

This is also called a finalizer or (improperly) a destructor.


text:
Q: Edit/Delete Google Calendar Events and get event Id I am trying to edit and delete events in Google calendar using Calendar Provider. I have already Created event using Calendar Provider .
Here is my code to create an event :
    Calendar beginTime = Calendar.getInstance();
    beginTime.set(2014, 5, 19, 7, 30);
    Calendar endTime = Calendar.getInstance();
    endTime.set(2014, 5, 19, 8, 30);
    Intent intent = new Intent(Intent.ACTION_INSERT)
            .setData(Events.CONTENT_URI)
            .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
            .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
            .putExtra(Events.TITLE, "")
            .putExtra(Events.DESCRIPTION, "")
            .putExtra(Events.EVENT_LOCATION, "")
            .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
            .putExtra(Intent.EXTRA_EMAIL, email);
    startActivity(intent);

event is getting created successfully. now i want to edit/delete the event. so, how can i perform this. And for edit/delete i need event id for created event how i can get that??
Please... help me guys.

A: Check this url
Update and delete calendar events in android through my application
Hope it helps :)
Get Event Id :
private int ListSelectedCalendars(String eventtitle) {

    Uri eventUri;
    if (android.os.Build.VERSION.SDK_INT <= 7) {
        // the old way

        eventUri = Uri.parse("content://calendar/events");
    } else {
        // the new way

        eventUri = Uri.parse("content://com.android.calendar/events");
    }

    int result = 0;
    String projection[] = { "_id", "title" };
    Cursor cursor = getContentResolver().query(eventUri, null, null, null,
            null);

    if (cursor.moveToFirst()) {

        String calName;
        String calID;

        int nameCol = cursor.getColumnIndex(projection[1]);
        int idCol = cursor.getColumnIndex(projection[0]);
        do {
            calName = cursor.getString(nameCol);
            calID = cursor.getString(idCol);

             if (calName != null && calName.contains(eventtitle)) {
            result = Integer.parseInt(calID);
            }

        } while (cursor.moveToNext());
        cursor.close();
    }

    return result;

}

Update Event :
@SuppressLint("InlinedApi")
private int UpdateCalendarEntry(int entryID) {
    int iNumRowsUpdated = 0;

    Uri eventUri;
    if (android.os.Build.VERSION.SDK_INT <= 7) {
        // the old way

        eventUri = Uri.parse("content://calendar/events");
    } else {
        // the new way

        eventUri = Uri.parse("content://com.android.calendar/events");
    }

    ContentValues values = new ContentValues();
    values.put(Events.TITLE, "test");
    values.put(Events.EVENT_LOCATION, "Chennai");

    Uri updateUri = ContentUris.withAppendedId(eventUri, entryID);
    iNumRowsUpdated = getContentResolver().update(updateUri, values, null,
            null);

    return iNumRowsUpdated;
}

Delete Event :
    private int DeleteCalendarEntry(int entryID) {
    int iNumRowsDeleted = 0;

    Uri eventUri = ContentUris
            .withAppendedId(getCalendarUriBase(), entryID);
    iNumRowsDeleted = getContentResolver().delete(eventUri, null, null);

    return iNumRowsDeleted;
}

private Uri getCalendarUriBase() {
    Uri eventUri;
    if (android.os.Build.VERSION.SDK_INT <= 7) {
        // the old way

        eventUri = Uri.parse("content://calendar/events");
    } else {
        // the new way

        eventUri = Uri.parse("content://com.android.calendar/events");
    }

    return eventUri;
}


text:
Q: How can I include Metafield data into the Shopify product.description property? I am working with a shopify 2.0 theme and I would like to include relevant product datapoints (meta fields) in the product.description property.
Examples—

*

*Condition: New

*Brand: Hester & Orchard

*Department: Womens

*Size: M

*Size Type: Regular

*Color: Blue

*Pattern: Solid

*Closure: Pullover

*Sleeve Length: Short Sleeve

*Chest Size: 42 in

*Length: 23 in

*Material: Cotton Blend

*Country: China

I need these rendered specifically in the description property so that each key:value are available and readable for outside listings.
I am currently producing this list on my store product page using a snippet right under the description, but my ultimate goal is to make these meta fields the product.description content inclusion.

A: So just save all that data in the description? Why waste effort on saving them as metafields, when you say you want them as a description.


text:
Q: Newbie: How to make .pl file executable? I don't know anything about PERL first of all. I know very limited html. My assignment is to upload a .pl file (provided to me) to my cg-bin dir on my web server, then make the file executable. I had to manually create a cgi-bin dir into my public_html dir. I uploaded the .pl file. How do I make it executable?

A: chmod a+rx /path/to/your/file.pl

You may want to check out the chmod man page as well. Just type
man chmod

in your terminal.

A: Manually creating the cgi-bin directory probably isn't going to work. The web server needs to be configured to recognise the directory as well. And we can't help you with that as we don't know which web server you are using.

A: As others have said, you will need to chmod
Also (depending on webserver, which you haven't tolYou need to put the path to your Perl executable in the first line of your script:
#!/bin/perl

This will be particular to your server though - you'll need to ask your admin or teacher what it should be for you.


text:
Q: ASP.Net MVC: Access validation error messages in the controller? Is there a way to access validation error messages in the controller. I'm not finding them anywhere in ModelState.

A: Iterating over ModelState is used for this purpose.
Something along these lines:
if (!ModelState.IsValid)
{
    StringBuilder result = new StringBuilder();

    foreach (var item in ModelState)
    {
        string key = item.Key;
        var errors = item.Value.Errors;

        foreach (var error in errors)
        {
            result.Append(key + " " + error.ErrorMessage);
        }
    }

    TempData["Errors"] = result.ToString();
}

A: I realize this is old but I just stumbled into it looking for something else and will leave it here - perhaps someone could find it useful:
var err = ModelState.Values.SelectMany(x => x.Errors).Select(e => e.ErrorMessage);

foreach(var y in err)
{
    // add each to your list of strings
}

A: You can validate an object in the controller using the Validator


text:
Q: Unable to pull Tar files from Jfrog Artifactory when file size is over 7gb We have tried with the JFrog CLI and the curl command but unable to pull the tar files, it is failing around 5-6gb, below are the errors.
Using Jfrog CLI
$ jf rt dl /tarFile /mnt/sdc.tar --server-id=1 --retries=6 --quiet --flat --threads=1

[Warn] [Thread 0] [2]: (Attempt 7) - Failure occurred while downloading part 2 of https://artifactUrl/artifactory/tarFile: open /tmp/jfrog.cli.temp.-1668500133-936929090/2_3393945811: no space left on device
[Info] [Thread 0] [2]:  executor timeout after 6 attempts with 0 milliseconds wait intervals
[Error] [Thread 0]  Received an error: open /tmp/jfrog.cli.temp.-1668500133-936929090/0_261788985: no space left on device
[Error] open /tmp/jfrog.cli.temp.-1668500133-936929090/0_261788985: no space left on device
[Error] open /tmp/jfrog.cli.temp.-1668500133-936929090/0_261788985: no space left on device

Using curl
$ curl -H "X-JFrog-Art-Api:ApiKey" https://artifactUrl/artifactory/tarFile -O /mnt/downloads/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
13 7468M   13  974M    0     0  9861k      0  0:12:55  0:01:41  0:11:14 6639k
curl: (23) Failed writing body (1227 != 1400)
curl: (3) <url> malformed

We are trying to pull the Tar file but unable to pull.

A: The below message
[Error] open /tmp/jfrog.cli.temp.-1668500133-936929090/0_261788985: no space left on device

indicates that there is no space for Artifactory to materialise and give it to user/client. Make sure, there is enough space for Artifactory to download it.
You can validate with storage commands like df -h


text:
Q: How to return a value from a method that needs to perform some operations inside a Runnable? To get the width of a view when the Activity/Fragment is still measuring its views, you use a ViewTreeObserver or  the View's post method with your own Runnable. I usually adopt de second one. But now -after some calculations, I would like to return the value, but because the method run doesn't return any value (void), and I must way to measure the width of the view, I have come to a dead end. Has someone any idea?
Thanks!
int getDesiredWidth(final View view) {
    final int[]finalWidth = {0};

    view.post(new Runnable() {
        @Override
        public void run() {
            int width = view.getLayoutParams().width;
            //Calculate 'finalWidth' computing margins and other size's view
            return finalWidth[0]; //error: cannot return a value from a method with void type
        }
    });

    return finalWidth[0];
}

A: You are quite close to technically correct decision. The only one thing which has lef to do is:
    public void run() {
        finalWidth[0] = view.getLayoutParams().width;
    }

The only one problem is that this Runnable object will be placed inside the message queue and will not be invoked sequentially. That means, that you should think about how to wait for internal run() method will be invoked. This could be archived using CountDownLatch object for example:
final CountDownLatch latch = new CountDownLatch(1);

view.post(....

  public void run() {
            finalWidth[0] = view.getLayoutParams().width;
            latch.countDown();
  }
);

countDownLatch.await();
return finalWidth[0];

A: You will have to create a custom Interface to return a value from a different thread:
public interface FooBar{
    public abstract void onCalculationFinished(int result);
}

Then create a custom Class that extends Runnable with an constructor you can pas an instance of your interface to:
public class NameItHoweverYouLike extends Runnable{
    FooBar i;
    public NameItHoweverYouLike(FooBar interface){
        this.i = interface;
    }
    @Override
    public void run() {
        int width = view.getLayoutParams().width;
        //Calculate 'finalWidth' computing margins and other size's view
        if(i != null){
            i.onCalculationFinished(width);
        }
    }
}

Create a new Instance of this class and run in.

A: You could use a BlockingQueue.
int getDesiredWidth(final View view) {
    final BlockingQueue<Integer> result = new ArrayBlockingQueue<>(1);

    view.post(new Runnable() {
        @Override
        public void run() {
            result.put(view.getLayoutParams().width);
        }
    });

    return result.take();
}

Added:
Here's an alternative - instead of returning the width it returns a Future which will give you the width when asked. You just need to make sure you do not request the result until you are in a state where the message queue can continue running.
Future<Integer> getDesiredWidth(final View view) {
    final BlockingQueue<Integer> result = new ArrayBlockingQueue<>(1);

    view.post(new Runnable() {
        @Override
        public void run() {
            result.put(view.getLayoutParams().width);
        }
    });

    return new Future<Integer> () {

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            // Cannot imterrupt it.
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return result.peek() != null;
        }

        @Override
        public Integer get() throws InterruptedException, ExecutionException {
            return result.take();
        }

        @Override
        public Integer get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            return result.poll(timeout, unit);
        }

    };
}

A: Instead of creating your variable int width within the method run, have you tried using a global variable (class member) ?
You will then be able to use the variable within the whole class.


text:
Q: file_get_contents('http://localhost/api/index.php?get=x'); how to make it work? On my local host i wanna test my API, put every time i use the statement :
file_get_contents('http://localhost/api/index.php?get=x');

the script stops with " timeout ", while the URL up there works fine when requested the normal way !.
Hint: i think it have something to do with the php.ini file !?
secondly, using cURL, (file_get_contents+stream_creat_content), would be faster ?, i needed it to respond very fast
Thanks in advance :)

A: This is probably more of a firewall issue than to do with php.ini.
The fastest way to do this, however, will always be a direct include() to a file path. It would probably require some re-working of the API (because you shouldn't set $_GET variables programmatically), but saves a ton of overhead. If you need this in production, it's most likely worth making the changes.


text:
Q: NSURLConnection Taking Too long time i have written this code :
  data = ([NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]);
if request url is not accessible then it will take too long time and then
it will crash
if request is available then it load data
how to check faster that given url on request object is available or not and if not available then give user error .

A: Use sendAsynchronousRequest to avoid hanging your UI and set the timeout Interval if you URL taking too long time.
[NSMutableURLRequest setTimeoutInterval:10.0f];

Hope it cures....:)

A: use "if else " to avoid crash
if (condition )
{
block of code
}
else
{
alert
}


text:
Q: MapBox React Native : 'Could not resolve com.squareup.okio:okio:1.13.0' I try to install : MapBox but I have those errors :
Could not resolve all files for configuration ':mapbox-react-native-mapbox- gl:debugCompileClasspath'.
> Could not resolve com.squareup.okio:okio:1.13.0.
Required by:
  project :mapbox-react-native-mapbox-gl
> Cannot find a version of 'com.squareup.okio:okio' that satisfies the version constraints:
    Dependency path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.facebook.react:react-native:0.59.6' --> 'com.squareup.okio:okio:1.15.0'
    Dependency path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okhttp3:okhttp:3.9.1' --> 'com.squareup.okio:okio:1.13.0'
    Dependency path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.facebook.react:react-native:0.59.6' --> 'com.squareup.okhttp3:okhttp:3.9.1' --> 'com.squareup.okio:okio:1.13.0'
    Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0
    Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0
    Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0
    Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0

> Could not resolve com.squareup.okio:okio:1.15.0.
Required by:
  project :mapbox-react-native-mapbox-gl > com.facebook.react:react-native:0.59.6
> Cannot find a version of 'com.squareup.okio:okio' that satisfies the version constraints:
    Dependency path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.facebook.react:react-native:0.59.6' --> 'com.squareup.okio:okio:1.15.0'
    Dependency path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okhttp3:okhttp:3.9.1' --> 'com.squareup.okio:okio:1.13.0'
    Dependency path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.facebook.react:react-native:0.59.6' --> 'com.squareup.okhttp3:okhttp:3.9.1' --> 'com.squareup.okio:okio:1.13.0'
    Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0
    Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0
    Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0
    Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0

> Could not resolve com.squareup.okio:okio:1.13.0.
 Required by:
  project :mapbox-react-native-mapbox-gl > com.squareup.okhttp3:okhttp:3.9.1
> Cannot find a version of 'com.squareup.okio:okio' that satisfies the version constraints:
     Dependency path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.facebook.react:react-native:0.59.6' --> 'com.squareup.okio:okio:1.15.0'
     Dependency path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okhttp3:okhttp:3.9.1' --> 'com.squareup.okio:okio:1.13.0'
     Dependency path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.facebook.react:react-native:0.59.6' --> 'com.squareup.okhttp3:okhttp:3.9.1' --> 'com.squareup.okio:okio:1.13.0'
     Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0
     Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0
     Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0
     Constraint path 'projekt:mapbox-react-native-mapbox-gl:unspecified' --> 'com.squareup.okio:okio' strictly '1.13.0' because of the following reason: debugRuntimeClasspath uses version 1.13.0

I tried the solutions found on the web, but nothing works.
This is my build.gradle file :
buildscript {
ext {
    minSdkVersion = 26
    compileSdkVersion = 28
    targetSdkVersion = 28
    supportLibVersion = "28.0.0"
}

repositories {
    google()
    jcenter()
}

dependencies {
    classpath 'com.android.tools.build:gradle:3.3.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    configurations.all { resolutionStrategy { force "com.squareup.okhttp3:okhttp:3.9.1" } }
    mavenLocal()
    google()
    jcenter()
    maven {
        // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
        url "$rootDir/../node_modules/react-native/android"
    }
 }
}

I tried lot of things : suppress node_modules and npm install, clean cache, restart all... I am sure it is a react-native version porblem, but I am quite new to gradle and I don't understant how to fix a specific version for com.squareup.
I don't even understand if I must fix the version 15 or 13 of com.squareup for the project. Downgrad the react native version doesn't please me, I tried and nothing changed. I had much more lines of error at install, and now, I am blocked at this step. That is very frustrating, because it stops my project at this point.
Have you an idea ?
Thank you for your help.

A: Try this in your app/build.gradle, I had this issue once...
compile (project(':@mapbox_react-native-mapbox-gl')) {
    compile ('com.squareup.okhttp3:okhttp:3.6.0') {
        force = true
    }
}

My root build.gradle (ignore the version numbers, obviously I haven't updated this project for a while) looks like:
buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}

UPDATE
As the OP cannot create build, I have created one - this is how I did it. The issue is (that I was running into also) when you use npm install from the github repo Read Me, it for some reason doesn't install the correct SDK version from NPM. Therefore we have to rectify the package.json to force install from a GH url
(https://github.com/nitaliano/react-native-mapbox-gl/issues/1602)
Run:
react-native init MyProject
Go to: package.json and add in dependancies (at the top):
"@mapbox/react-native-mapbox-gl": "https://github.com/nitaliano/react-native-mapbox-gl.git"
run
npm install
react-native link
react-native run-android


text:
Q: java HttpClient asynchronous error handling I want to use Java Http Client: java.net.http.HttpClient in asynchronous way.
When I receive http response (any http code) or timeout I want to execute some custom Java code. I struggle to complete the body of error handling.
CompletableFuture<HttpResponse<String>> response =
httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
  .thenApplyAsync(body -> {
    System.out.println("Request finished");
    return body;
  })
  .exceptionallyAsync(exception -> {

     // WHAT TO RETURN HERE ?
  });

The method: exceptionallyAsync returns: CompletableFuture<T>, but I do not know how to complete this method.
Can you please help me to finish this method? I cannot find example in GitHub or Google.

A: You can use
.exceptionally(this::handlError)

If this is your response handler with a method like:
    private Void handlError(Throwable ex) {
        System.out.println(ex.toString());
        return null;
    }


text:
Q: Is there some way to automate connections to nREPL from Vim Fireplace? I'm running lein repl in a project, and it successfully starts up and creates the file target/repl-port.
Using VIM version 7.4.86 I can use a command like:
:Connect nrepl://localhost:57644
Vim then successfully connects to the repl, and all is good.
However, my understanding is that vim-fireplace is able to make this connection all by itself using the target/repl-port file. That is not happening. I did see a comment about lein 2.3 changing to use target/repl/repl-port (I use lein 2.0.0 for this project - a requirement that is out of my control) so I tried to creating a symlink at this location, but that isn't picked up either.
I'm using the version of vim-fireplace from:
github.com/tpope/vim-fireplace
at the latest commit, which is currently:
f1b8096b3fe00cd9594c8a2bf0819efc154e9843
(Date:   Wed Oct 23 21:25:53 2013 -0700)

I'm hoping to automate this connection. I'm not big on VIMscript, so I was hoping that there might be some way to track down the issue without having to delve into the sources.

A: struggled a little bit with that too.

*

*Start lein repl in your project directory

*Start vim any-clojure-file.clj also  in your project directory

Then it should connect automatically.
Fireplace only connects automatically, when you open a clojure file.
best regards
adrian

A: I think the best way to handle this "nowadays" is with vim-leiningen.  :Console will connect to a REPL if there already is one running and will start one if there isn't.

A: I too was annoyed by this and also didn't want to learn to write vim script just for this. You can work around it with your shell:
$ alias rvim="gvim $1 +\":FireplaceConnect nrepl://localhost:`cat .nrepl-port`\""
$ rvim src/something.clj


text:
Q: Remove an HTTP Request PATH Variable if null I have this script in JMeter, PUT method,
how can i remove a path variable if the value from the input data is blank?
I know i can remove this if the parameter were in the Parameter tab of the HTTP request using the remove Arguments, the thing is I have a value in the body data so I have to put the URL parameters in the path that's why remove arguments is not working anymore.
code:
if ("${thisfromCSV}" == "") {
    sampler.getArguments().removeArgument("thisParameter");
}

this works if the parameter is located at the Parameters tab of the HTTP Request

A: *

*Add JSR223 PreProcessor as a child of the HTTP Request you would like to modify

*Put the following code into "Script" area:
def url = new URL("http://example.com" + sampler.getPath())

def params = url.query.split('&').collectEntries({ param ->
    param.split('=').collect {
        URLDecoder.decode(it, 'UTF-8')
    }
})

if (vars.get('thisfromCSV') == '') {
    params.remove('thisParameter')
}

def query = params.collect { k, v -> "$k=$v" }.join('&')

sampler.setPath(url.path + '?' + query)

*That's it, the code will remove thisParameter from the Sampler's URL query string in case of thisfromCSV variable is empty.
See Apache Groovy - Why and How You Should Use It for more information on using Groovy scripting in JMeter tests.


text:
Q: How to Pass Variable and not values in URL in jsp page I have a String called var2="ASDFDE" whose value keeps changing.
Now I want to pass this variable(row_id) in URL.
For that I may need to write
action=action.jsp?var1=var2

In the action jsp page when I retrieve the row
out.println("Row_ID from previous jsp page is: "+request.getParameter("var1"));

It prints out
Row_ID from previous jsp page is: var2
whereas what I want is
Row_ID from previous jsp page is: ASDFDE
How do I do that? How do I just pass the variable through the URL without mentioning its value so that whatever would be the current value of that String is passed to next jsp page.
If it cannot be done through URL then what is the alternative. It would be really helpful if someone can explain with the example, I am new to this.

A: check out how session works
session.setAtribute('var1','value');
String var1=session.getAtribute('var1') ;


text:
Q: Criar um arquivo ".TXT" de configuração Meu problema é o seguinte, preciso fazer um arquivo configuravel para integrar ao meu projeto, segue o formato dele atualmente:
PRINTER = 127.0.0.12
PRINTER_PORT = 9100

Gostaria de formatar ele pra esse estilo:
[PRINTER]
PRINTER = 127.0.0.12
PRINTER_PORT = 9100

Atualmente estou utilizando o metódo de Dictionary pra obter os dados, tem alguma opção melhor? Já que se usar colchetes pra destaque no arquivo minha função não os lê.
Função:
var dic = File.ReadAllLines("config.txt")
          .Select(l => l.Split(new[] { '=' }))
          .ToDictionary(s => s[0].Trim(), s => s[1].Trim());
                VariaveisGlobais.DEFAULT_PRINTER = dic["PRINTER"];
                VariaveisGlobais.DEFAULT_PRINTER_PORT = dic["PRINTER_PORT"];

A: Se o formato é semelhante ao do .ini pode experimentar algo pronto, procurar no nuget, exemplo: https://www.nuget.org/packages/ini-parser/, para instalar:
PM> Install-Package ini-parser -Version 2.5.2

A vantagem dessa lib especifica é que ela não depende do WindowsAPI, o que é vantajoso para portar seu código para outros ambientes.
Exemplo de uso:
Adicione as classes:
using IniParser;
using IniParser.Model;

Para carregar o arquivo:
var parser = new FileIniDataParser();
IniData data = parser.ReadFile("Configuration.ini");

Para ler como string:
 string useFullScreenStr = data["UI"]["fullscreen"];

No exemplo se o valor for "true" você pode fazer o parse assim:
bool useFullScreen = bool.Parse(useFullScreenStr);


text:
Q: Spring Boot how can i customize BadRequestException I have created a BadRequestException class and I want to show this when the controller returned 400 errors. But I couldn't make this.
My controller:
@GetMapping("/{id}")
    public ResponseEntity<PostDto> getPostById(@PathVariable Long id) {
          if(!(id instanceof Long))
               throw new BadRequestException("your request is not valid !");
        return ResponseEntity.ok(restTemplateService.getPostById(id));
    }

My General Exception Handler:
@RestControllerAdvice
public class GeneralExceptionHandler extends ResponseEntityExceptionHandler {
    @NotNull
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  @NotNull HttpHeaders headers,
                                                                  @NotNull HttpStatus status,
                                                                  @NotNull WebRequest request) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(PostNotFoundException.class)
    public ResponseEntity<?> postNotFoundExceptionHandler(PostNotFoundException exception) {
        return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(BadRequestException.class)
    public ResponseEntity<?> badRequestExceptionHandler(BadRequestException exception) {
        return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
    }

}

BadRequestException class:
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
    public BadRequestException(String message) {
        super(message);
    }
}


text:
Q: Did I really just get my CV for only $9? OK this makes no sense but I just got my CV for $9 (USD). Is this a new special? Is this any different from the $19 one?
Also if this is a secret then I'm sorry!

A: This is normal -- we plan to make periodic special CV filing offers available, for new CV filers and "special friends of Stack Overflow".
https://blog.stackoverflow.com/2010/01/new-lower-careers-pricing/

We plan to keep improving and refining the careers service throughout the year. Specifically, we'll be exploring other options to reduce barriers to filing CVs, as well as publishing broad statistics about employer searches.


text:
Q: Parsing a field that only some object contains <collection>
    <personRepresentaion>
        <theId>1</theId>
        <name>John</name>
        <height>10</height>
        <width>12</width>
        <relationships>
            <inputId>1324</inputId>
            <outputId>1325</outputId>
        </relationships>
    </personRepresentaion>
    <personRepresentaion>
        <theId>2</theId>
        <name>Bill</name>
        <height>10</height>
        <width>12</width>
    </personRepresentaion>
    <personRepresentaion>
        <theId>3</theId>
        <name>Bob</name>
        <height>10</height>
        <width>12</width>
        <relationships>
            <inputId>1324</inputId>
            <outputId>1325</outputId>
        </relationships>
    </personRepresentaion>
</collection>

CurrentlyI am this XML file, and I want to parse out the field < outputId >, so I can use my function connectId(source, destination) to connect those 2 objects.
The problem is that I am using a for loop like the following to display them on my page:
var x=xmlDoc.getElementsByTagName("personRepresentaion");

for(i=0;i<x.length;i++) {
connectId(x[i].getElementsByTagName("theId")[0].childNodes[0].nodeValue,
x[i].getElementsByTagName("relationships")[0].getElementsByTagName("outputId")[0].childNodes[0].nodeValue);
}

But Bill in the XML does not have the field < relationships >, so the loop just stops and exits when it gets to Bill.
I need to first find only the persons that HAS < relationships > field, then use a for loop, then call connectId() for those objects, how do I achieve this?

A: Try
var $xml = $(xmlDoc);
$xml.find('personRepresentaion').has('outputId').has('inputId').each(function () {
    var $br = $(this);
    connectId($br.find('theId').text(), $br.find('outputId').text());
})

Demo: Fiddle


text:
Q: Сортировка постов WordPress по сумме чисел, которые выведены произвольными полями Всем привет. Вопрос сложный, как по мне, не знаю как решить.
Делаю сайт, в нем имеется 4 рейтинга, 3 оценки забиваются через админку в произвольных полях а 1 - это плагин "kk star ratings". Привходе на страницу, считается рейтинг введенный мной через админку и плагином, рейтинга. Выходит сумма и делится на 4, чтобы получить среднюю оценку.
Так вот. Каким образом можно вывести посты по этой сортировке?
Голова крутом, не понимаю. Как можно произвести вычисление за пределами цикла и чтобы в цикле по убыванию сортировались. Спасибо! Хотя бы за хоть какую-то наводку :)


text:
Q: Products to opportunities, and the SortOrder field While adding products to an opportunity in Salesforce, you can not specify the values for the 'SortOrder' field on Opportunity Line Items. That is very weird, and is a feature requested more than 7 years ago right now (as I've seen in an Idea Exchange thread).
I have a request that I need to be able to build a page that parses a CSV file, and creates the listed products and create a relationship with a specified opportunity. Parsing is fine, and so is creating all of the objects. However, I can't seem to find a way to sort the products the way I want to.
If the list is like this:

*

*Product C

*Product A

*Product B

Then I would like them to appear just like that in the opportunity's related list. But Salesforce orders them by the name, so the lists end up like:

*

*Product A

*Product B

*Product C

The order is relevant in my situation, so I would like to know if it is possible to insert the Opportunity Line Items records in a specific order, so that they end up in the right order. I'm asking this because I've tested my work so far, and I got the products inserted, but not in the right order.


text:
Q: Request Timeout - socket Java Having some problems with the following code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

class Main {
    public static void main(String args[]) {
        try {
            Socket s = new Socket("ark.intel.com", 80);

            PrintWriter out = new PrintWriter(s.getOutputStream());
            out.write("GET / HTTP/1.1\r\n"
                + "Host: ark.intel.com\r\n"
                + "Connection: keep-alive\r\n"
                + "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\r\n"
                + "Accept: text/html"
                + "\r\n");
            out.flush();

            BufferedReader read = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String line;
            String data = "";

            while ((line = read.readLine()) != null) {
                data += line;
                System.out.println(line);
            } read.close();
        } catch (Exception error) {}
    }
}

i keep getting
HTTP/1.0 408 Request Time-out
Server: AkamaiGHost
Mime-Version: 1.0
Date: Tue, 06 Feb 2018 11:43:41 GMT
Content-Type: text/html
Content-Length: 218
Expires: Tue, 06 Feb 2018 11:43:41 GMT

<TITLE>Request Timeout</TITLE>

Request Timeout

The server timed out while waiting for the browser's request.

Reference #2.403b3717.1517917421.0

any idea on how to fix this?
Edit:
The host ark.intel.com is using HTTPS, i need to find a way to send the requests over HTTPS rather then HTTP.

A: Host ark.intel.com is using https so you should use port 443.
Socket s = new Socket("ark.intel.com",443);

Then you will get another error, that will not be visible, because you are not handling exception
} catch (Exception error) {}

Here is example how to handle secure connections with use of SSL Socket: https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/samples/sockets/client/SSLSocketClient.java What you need to do is to change request with your parameters in this line out.println("GET / HTTP/1.0");

A: There is a missing \r\n:
        + "Accept: text/html\r\n"

UPDATE
As we have seen, this will allow you to do the request, but you will get a redirect, forcing you to use HTTPS.
Try using an HttpURLConnection instead of plain sockets:
    try {
        URL url = new URL("https://ark.intel.com/");
        HttpURLConnection cnt = (HttpURLConnection) url.openConnection();
        cnt.setRequestProperty("Host", "ark.intel.com");
        cnt.setRequestProperty("Connection", "keep-alive");
        cnt.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        cnt.setRequestProperty("Accept", "text/html");

        int stat = cnt.getResponseCode();
        if (stat != 200) {
            throw new IOException("HTTP error " + stat);
        }
        BufferedReader read = new BufferedReader(new InputStreamReader(cnt.getInputStream()));
        String line;
        String data = "";

        while ((line = read.readLine()) != null) {
            data += line;
            System.out.println(line);
        } read.close();
    } catch (Exception error) {
        error.printStackTrace();
    }


text:
Q: Implementing LEFT JOIN explicitly in Django I have been thru endless posts on Django and the LEFT JOIN problem and but have not found anyone that has a solution in the 2.2 version of Django. Whilst in years past it seems there were ways to get around this problem, the Django team seem to have shut down every mechanism people have employed to achieve the most simple but necessary query - the LEFT JOIN.
Here is a simle example of what I am trying to do (it is a simple example to reflect a real world scenario so please do not offer ways to redesign the models... all I want is the age old LEFT JOIN in SQL .... that simple):
from django.db import models
from uuid import uuid4
class People(models.Model):
    id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
    name = models.CharField(max_length=255)

class Book(models.Model):
    id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
    name = models.CharField(max_length=255)
    author = models.ForeignKey(People)
    publisher = models.ForeignKey(People, on_delete=models.PROTECT, null=True)

How would I achive an output showing all books and the publisher if there is a publisher (otherwise just blank)
Books.objects.filter(Q(publisher__isnull=True | Q(publisher__isnull=False)

... produces an INNER JOIN which will obviously only show books that have a publisher assigned.
The query I am looking for would be of the form:
    select * from book LEFT JOIN people ON book.publisher_id=people.id
... or do I have to resort to raw SQL for this most simple of requirements?

A: You can perform a .select_related(..) [Django-doc] here:
Book.objects.select_related('publisher')
This will fetch both the Book data and the related Publisher if it exists. So some_book.publisher where some_book originates from this queryset, will not result in an extra query to fetch the publisher. The query this will look like:
SELECT book.id, book.name, book.author_id, book.publisher_id,
       people.id, people.name
FROM book
LEFT OUTER JOIN people ON book.publisher_id = people.id


text:
Q: are accessiblity and anti-scrapabality mutually exclusive? I want to make a site that is both difficult to screen-scrap and accessible.
Is that an oxymoron?

A: Most likely. Accessibility relies on tools that parse the underlying code. For example the table "summary" attribute, or more common, the "alt" attribute on the img tag. In addition, these tools may interpret the code in ways that may not be as straight-forward as this.
So, if a site is accessible is somewhat the same as saying that the underlying code is easily parseable. And, consequently, if it's parseable, it can easily be scraped.
So, yes, you could say it's an oxymoron.


text:
Q: Как сгруппировать по дням dataframe? Есть dataframe со столбцами:

*

*НоменклатураКод( название),

*КоличествоОборот(сколько продано единиц товара всего за указанный период)

*СуммаОборот(всего продано по деньгам, то есть цена 1 единицы товара умножить на КоличествоОборот)

*Период(дата, какой-то дань)
Как сделать dataframe, чтобы по дням можно было сгруппировать наименования товаров, то есть дата, НоменклатураКод(это название товара) Количество проданное за день этого товара(это сумма КоличествОборот за день), Общая цена(это сумма СуммаОборот за день)?
funcs = dict('КоличествоОборот' ="summ", 'СуммаОборот' ="summ")
art3 = art.resample('D').agg(funcs)

Не получается, надо уникально по каждой НоменклатураКод( название) : То есть Товар - дата - объем - общая цена. То есть по каждому товару посчитать сколько было за день объема с общей ценой.

A: Вот так можно
data = pd.read_csv('art.csv', sep=',', parse_dates=['Период'], dayfirst=True, index_col='Период', decimal=',')
groupDate = data.groupby(['Период','НоменклатураКод']).sum()

У вас проблема в том, что дробная часть в числе отделена запятой, а должна быть точкой.


text:
Q: Check if a dictionary contains any key object with a specific property I'm wondering if this can be done in C#. I have a Dictionary<User, Device>(), where key and value are:
public Device {
    public string Id;
}

public User {
    public string Name;
}

I want to know if my dictionary contains any User key which Name property is equal to "John". Imagine there was something like:
myDictionary.ContainsKey(key => key.Name == "John");

Is this possible?

A: With two modifications (ie. pick one that suits your needs) you can do it:

*

*You can override GetHashCode and Equals on User to make two distinct User instances equal if they have the same Name value

*You can provide a IEqualityComparer<User> instance to the dictionary, which would have the same effect as point 1, except that the comparison it outside of User
Option #1: Override GetHashCode and Equals
With this User implementation:
public class User
{
    public string Name;

    public override int GetHashCode() => Name?.GetHashCode() ?? 0;
    public override bool Equals(object other) => (other as User)?.Name == Name;
}

You can query for such a user with this:
myDictionary.ContainsKey(new User { Name = "John" });

(DotNetFiddle example)
Option #2: Implement IEqualityComparer
With this class:
public class UserEqualityComparer : IEqualityComparer<User>
{
    public bool Equals(User x, User y) => x?.Name == y?.Name;
    public int GetHashCode(User obj) => obj?.Name?.GetHashCode() ?? 0;
}

(and no changes to User, keep it like it were in your question)
You can construct your dictionary like this:
var myDictionary = new Dictionary<User, Device>(new UserEqualityComparer());

And then again you can query it like this:
myDictionary.ContainsKey(new User { Name = "John" });

(DotNetFiddle example)

If neither of these are an option, you have linear search which will perform like if it were a collection of KeyValuePair<User, Device>, which is exactly what it will be, and this will probably not have the performance characteristics you want.

A: Dictionary<TKey, TValue> "is" an IEnumerable<KeyValuePair<TKey, TValue>> which means you could do:
myDictionary.Any(kvp => kvp.Key.Name == "John");

That would be an O(n) operation though.
If you care about the hashmap performance (hence using dictionary?) you could override the GetHashCode() and equality of your User class, so that new User { Name = "John" }.Equals(new User { Name = "John" }) would be true, allowing:
myDictionary.ContainsKey(new User { Name = "John" });

which is O(1)


text:
Q: Obtener última ID Insertada Tengo este código para añadir un libro a la base de datos.
    if(count($_POST)>0){
    $a = new SQLMan();
    $a->tablename = "libro";
    $numpag = "0";
    $year = "0";
    // $a->in_test = true;
    $a->isbn = $a->is_string($_POST["isbn"]);
    $a->titulo = $a->is_string(ucwords(mb_strtolower($_POST["titulo"])));
    $a->subtitulo = $a->is_string(ucwords(mb_strtolower($_POST["subtitulo"])));
    $a->num_pag = $a->is_string($numpag);
    $a->anio = $a->is_string($year);
    $a->editorial_id = $a->is_string($_POST["editorial_id"]);
    $a->autor_id = $a->is_string($_POST["autor_id"]);
    $a->add();

    $lastid = LAST_INSERT_ID($a);

        echo $lastid

Y me haría falta sacar el ID pero al usar LAST_INSERT_ID() me tira este error:
Call to undefined function LAST_INSERT_ID()
¿Hay algo que este haciendo mal? Gracias!
Clase SQLMan
Class SQLMan {
    public $tablename;
    public $fields = array();
    public $sql = "";
    public $in_test = false;
    public $lastid;

    public function __set($key,$data){
        $this->fields[$key]=$data;
    }

    public function fields_to_array(){
        return $this->fields;
    }

    public function add(){
        $this->sql = "";
        $this->sql .= "insert into ".$this->tablename." ";
            $d1="";
            $d2="";
            $n=0;
        foreach ($this->fields as $key => $value) {
            $d1 .= $key;
            $d2 .= "$value";
            if($n<count($this->fields)-1){
                $d1 .=",";
                $d2 .=",";
            }
                $n++;
        }
        $this->sql .= "($d1) value ($d2)";

        if($this->in_test){
        echo $this->sql;
        }else{
            return Executor::doit($this->sql);
            return $lastid = $this->insert_id;
        }
    }

    public function update($data,$where=""){
        $this->sql = "update ".$this->tablename." set";
            $d1="";
            $d2="";
            $n=0;
        foreach ($data as $key => $value) {
                $d1 .= $key."=".$value;
            if($n<count($data)-1){
                //$d1 .= $key."=\"".$value."\"";
                 $d1 .=",";
            }
                $n++;
        }
        $this->sql .= " $d1 ";
        if($where!=""){
            $this->sql .=" where ".$where;
        }

        if($this->in_test){
        echo $this->sql;
        }else{
            return Executor::doit($this->sql);
        }
    }

    public function is_string($v){ return "\"$v\"";}

    // $type default = many, optional = one
    public function select($type="",$fieldx="", $where="",$order="",$limit=""){
        $this->sql = "select ";
        if($fieldx ==""){ $this->sql .= "*" ; }else{ $this->sql .= $fieldx ; }
        $this->sql .= " from ".$this->tablename;
        if($where!="") { $this->sql .= " where ".$where ;}
        if($order!="") { $this->sql .= " order by ".$order ;}
        if($limit!="") { $this->sql .= " limit ".$limit ;}
        if($this->in_test){
            echo $this->sql;
        }else{
            if($type=""){$type="many"; }
            return Selector::process($type,$this->sql,$this);
        }

    }

    }

}

Executor:
<?php

    class Executor {

        public static function doit($sql){
            $con = Database::getCon();
            return array($con->query($sql),$con->insert_id);
        }
    }
    ?>

Database código
<?php
/// evilnapsis.tk evilnaps 6RSk!IpTJ]vv
class Database {
    public static $db;
    public static $con;
    function Database(){
        $this->user="root";$this->pass="";$this->host="localhost";$this->ddbb="library";
//      $this->user="minedeck_mduser";$this->pass="l00lapal00za";$this->host="localhost";$this->ddbb="minedeck_md";
    }

    function connect(){
        $con = new mysqli($this->host,$this->user,$this->pass,$this->ddbb);
        return $con;
    }

    public static function getCon(){
        if(self::$con==null && self::$db==null){
            self::$db = new Database();
            self::$con = self::$db->connect();
        }
        return self::$con;
    }

}

A: En mysqlideberías usar lo que ya tienes en el método doit() de la clase Executor:
$con->insert_id;

Pues se accede a través de una propiedad, no de un método:
https://www.php.net/manual/es/mysqli.insert-id.php
Fíjate que esa clase devuelve un array con el id que puedes recuperar, tras pasar por varios return, como:
list($rs,$lastid)=$a->add();

En vez de:
 $a->add();
 $lastid = LAST_INSERT_ID($a);

Te paso una versión simplificada de tu código para que compruebes su funcionamiento:
<?php

$a = new SQLMan();
list($rs,$lastid)=$a->add();
echo $lastid;

class SQLMan {
    public function add(){
        $this->sql="
            INSERT INTO libros (titulo)
              VALUES ('Platero y yo');
        ";
        return Executor::doit($this->sql);
    }
}
class Executor {
    public static function doit($sql){
        $con = Database::getCon();
        return array(
            $con->query($sql),
            $con->insert_id
        );
    }
}
class Database {
    public static $db;
    public static $con;
    function Database(){
        $this->user="root";$this->pass="";
        $this->host="localhost";
        $this->ddbb="stackoverflow";
    }
    function connect(){
        $con = new mysqli($this->host,
            $this->user,$this->pass,$this->ddbb);
        return $con;
    }
    public static function getCon(){
        if(self::$con==null && self::$db==null){
            self::$db = new Database();
            self::$con = self::$db->connect();
        }
        return self::$con;
    }
}

Y del dataset:
CREATE TABLE libros(
  id_libro int AUTO_INCREMENT PRIMARY KEY,
  titulo varchar(64)
  );
INSERT INTO libros (titulo)
  VALUES ('Platero y yo');
SELECT * FROM libros;