text:
Q: Label edits disappear upon saving? I am trying to label a map I'm creating in QGIS v 2.8.9. I'm using data defined labeling to both manually place and rotate labels. I've created the required fields (X, Y, and Rotate) all as decimal with a width of 10. Up to today, I've had no problem editing the labels and saving these edits. However, today, upon moving some labels, and subsequently saving the edits, all the labels (edited today, not earlier edits) snapped back to their original positions. Here's an example:

As you can see the labels for the lakes all show highlighted because they are now pinned since I edited them. Now, when I save the layer edits, this happens:

The labels snap back to their pre-edited positions.
All my layers are shapefiles and have not been touched in ArcGIS at any point if that helps. Also, it seems to only be affecting labels. I can still edit and save polygon, point, and line features.


text:
Q: Where are pages files stored after I export them to itunes? With my iPad connected to my MacBook, I exported some Pages files to iTunes in docx format. Now I'm using my laptop without the iPad, and I want to find these files. Where/how are they stored? Tks.

A: This is a 2 step process:
1/ mark the files to transfer (Export) to iTunes while in Pages on the iPad,
2/ once the iPad is connected, transfer the files from the IPad to the Mac.
I fear you did not do step #2.
In Pages on the iPad, Export in .docx (or .pdf and .pages) format. This creates the file in the selected format and makes the file visible to the iTunes interface on the Mac.
When the iPad is then connected in iTunes, go to the Apps tab > File Sharing section at the very bottom and select the Pages app & its documents. Select a filename or filenames from the list of files. Once selected, you must click the Save to... button to pull up a save dialog. You can then save wherever you like - local or external HD, networked NAS, webDAV server, USB key - whatever.
NOTE: There is no default automatic downloading mechanism - you must first select the destination and then initiate the file transfer(s). If you didn't manually download the files from the iPad, they won't be on your Mac.
To avoid this in the future, I suggest you save your documents using iCloud, for example, or into Dropbox, Google Drive, Evernote and other apps Pages can access in iOS, and which can be retrieved by OSX and Windows. This will guarantee that an important doc is available whenever needed. I use all these technologies on a mixed environment of iOS devices, Macs & PCs.

A: Files that get exported to iTunes on iOS don't automatically transfer to iTunes the next time you sync.
A manual step is required: select the device in iTunes, then click the Apps tab and scroll to the bottom of the page. The file transfer section is where you pick Pages and then place a copy of the exported file onto your computer's file system.
Apple has a longer article with step by step instructions and pictures:

*

*iWork for iOS: About iTunes File Sharing

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to extract "breed" and "#1097" from variable? import re
line = "Jan 31 05:23:14 ubuntu.local ticky: INFO Commented on ticket [#1097] (breed)"
per_user ={}
pattern = r"ticky: INFO ([\w ]*)"
result = re.search(pattern,line)
name = result[1]
per_user[name] = per_user.get(name,0) +1
print(per_user)

This code is returning this:

{'Commented on ticket ': 1}

but I want output getting name breed instead of getting 'commented on ticket' and number #1097.

A: If I understood correctly that you want to grab breed as key and the ticket number as value then you need to adjust your regexp and add capture groups for those two elements:
import re
line = "Jan 31 05:23:14 ubuntu.local ticky: INFO Commented on ticket
[#1097] (breed)"
per_user ={}
pattern = r"ticky:\s+INFO.*?\[#(\d+)\]\s+\((.*?)\)$"
result = re.search(pattern,line)
ticket = result.group(1)
name = result.group(2)
per_user[name] = ticket
print per_user


text:
Q: Delete an image without reloading a page I am using below function in my page.
I use this function to delete an one or more uploaded images.
The code is working fine,but its reloading a page when i click on "delete" button.
Is it possible to delete an images  without reloading a page using "post" method or ajax?
<div onclick="delete_Files_Inmos1('Seguro de Eliminar el Archivo','im_Delete_Chk','im_FileUp','im_imgF','<?php echo $url?>',<?php echo $this->config->maxFileUpload?>,<?php echo $count?>);">delete

A: You have to return false in your onClick function!


text:
Q: Flexbox is not applying space between divs I am applying Flexbox concepts but there is something I am struggling with here, I applied display: flex; and applied the direction to be column.
Now as the main axis is column I made justify-content as space between but this space between is not applied to make space between navbar and section-main and footer.

.page-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.navbar {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.section-main {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

          Oka brand

          nav buttons

          left nav

          middle section

          nav icons

        footer

A: The problem is that the flexbox container calculates the height based on available content. If you set the parent height to 100% it will adjust accordingly. Note that I added html, body to height: 100% in order to calculate full page height.

html,
body {
  height: 100%;
}

* { /* Reset properties to avoid any browser related spacing */
  margin: 0;
  padding: 0;
}

.page-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%; /* Calculate from parent's height */
}

.navbar {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.section-main {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

        Oka brand

        nav buttons

        left nav

        middle section

        nav icons

      footer

A:

.page-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.navbar {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.section-main {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin: 1em 0;
}

          Oka brand

          nav buttons

          left nav

          middle section

          nav icons

        footer


text:
Q: Add a watermark with Apache POI to a docx that already have a header How can I add a watermark to a docx file that already have a header.
All the examples code show how to add to a doc with an empty header, but if the document already have one, the code fail.
The main issue is in XWPFHeaderFooterPolicy.createHeader(..) because it ignore the call if a header exist, so the paragraph with the watermark info is not added.
public XWPFHeader createHeader(Enum type, XWPFParagraph[] pars) {
    XWPFHeader header = getHeader(type);

    if (header == null) {
        HdrDocument hdrDoc = HdrDocument.Factory.newInstance();

        XWPFRelation relation = XWPFRelation.HEADER;
        int i = getRelationIndex(relation);

        XWPFHeader wrapper = (XWPFHeader) doc.createRelationship(relation,
                XWPFFactory.getInstance(), i);
        wrapper.setXWPFDocument(doc);

        CTHdrFtr hdr = buildHdr(type, wrapper, pars);
        wrapper.setHeaderFooter(hdr);
        hdrDoc.setHdr(hdr);
        assignHeader(wrapper, type);
        header = wrapper;
    }

    return header;
}

When createWatermark call that method, it simply enter and out doing nothing.
I do not found a way to do the same. How could I correct this?

A: The XWPFHeaderFooterPolicy.createHeader is only used to create new headers. If headers are already present, then nothing will be changed in those headers.
If you look into the source code of XWPFHeaderFooterPolicy, as you had done already, you will see that the watermark simply is a WordArt shape within a paragraph in the header. So you simply could create that kind of WordArt shape in a already existant paragraph in a header. To do so try to understand XWPFHeaderFooterPolicy.getWatermarkParagraph(String text, int idx) and rewrite it into a setWatermarkInParagraph(XWPFParagraph paragraph, String text). Then you can get or create a paragraph in any header you want and put the watermark into that paragraph.
Following complete example shows this. It works using apache poi 5.0.0. Using apache poi 3.17 or apache poi 4.1.2 the commented changes in import statements need to be done.
import java.io.*;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import com.microsoft.schemas.office.office.*;
import com.microsoft.schemas.office.office.CTLock;
import com.microsoft.schemas.vml.*;

import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STTrueFalse; // apache ppi 5.0.0
//import com.microsoft.schemas.vml.STTrueFalse; // apache poi 3.17 and apache poi 4.1.2

public class CreateWordHeaderWatermarkInExistingDocument {

 private static void setWatermarkInParagraph(XWPFParagraph paragraph, String text) {
  //CTP p = CTP.Factory.newInstance();
  CTP p = paragraph.getCTP();
  XWPFDocument doc = paragraph.getDocument();
  CTBody ctBody = doc.getDocument().getBody();
  byte[] rsidr = null;
  byte[] rsidrdefault = null;
  if (ctBody.sizeOfPArray() == 0) {
   // TODO generate rsidr and rsidrdefault
  } else {
   CTP ctp = ctBody.getPArray(0);
   rsidr = ctp.getRsidR();
   rsidrdefault = ctp.getRsidRDefault();
  }
  p.setRsidP(rsidr);
  p.setRsidRDefault(rsidrdefault);
  CTPPr pPr = p.getPPr(); if (pPr == null) pPr = p.addNewPPr();
  CTString pStyle = pPr.getPStyle(); if (pStyle == null)  pStyle = pPr.addNewPStyle();
  pStyle.setVal("Header");
  // start watermark paragraph
  CTR r = p.addNewR();
  CTRPr rPr = r.addNewRPr();
  rPr.addNewNoProof();
  int idx = 1;
  CTPicture pict = r.addNewPict();
  CTGroup group = CTGroup.Factory.newInstance();
  CTShapetype shapetype = group.addNewShapetype();
  shapetype.setId("_x0000_t136");
  shapetype.setCoordsize("1600,21600");
  shapetype.setSpt(136);
  shapetype.setAdj("10800");
  shapetype.setPath2("m@7,0l@8,0m@5,21600l@6,21600e");
  CTFormulas formulas = shapetype.addNewFormulas();
  formulas.addNewF().setEqn("sum #0 0 10800");
  formulas.addNewF().setEqn("prod #0 2 1");
  formulas.addNewF().setEqn("sum 21600 0 @1");
  formulas.addNewF().setEqn("sum 0 0 @2");
  formulas.addNewF().setEqn("sum 21600 0 @3");
  formulas.addNewF().setEqn("if @0 @3 0");
  formulas.addNewF().setEqn("if @0 21600 @1");
  formulas.addNewF().setEqn("if @0 0 @2");
  formulas.addNewF().setEqn("if @0 @4 21600");
  formulas.addNewF().setEqn("mid @5 @6");
  formulas.addNewF().setEqn("mid @8 @5");
  formulas.addNewF().setEqn("mid @7 @8");
  formulas.addNewF().setEqn("mid @6 @7");
  formulas.addNewF().setEqn("sum @6 0 @5");
  CTPath path = shapetype.addNewPath();
  path.setTextpathok(STTrueFalse.T);
  path.setConnecttype(STConnectType.CUSTOM);
  path.setConnectlocs("@9,0;@10,10800;@11,21600;@12,10800");
  path.setConnectangles("270,180,90,0");
  CTTextPath shapeTypeTextPath = shapetype.addNewTextpath();
  shapeTypeTextPath.setOn(STTrueFalse.T);
  shapeTypeTextPath.setFitshape(STTrueFalse.T);
  CTHandles handles = shapetype.addNewHandles();
  CTH h = handles.addNewH();
  h.setPosition("#0,bottomRight");
  h.setXrange("6629,14971");
  CTLock lock = shapetype.addNewLock();
  lock.setExt(STExt.EDIT);
  CTShape shape = group.addNewShape();
  shape.setId("PowerPlusWaterMarkObject" + idx);
  shape.setSpid("_x0000_s102" + (4 + idx));
  shape.setType("#_x0000_t136");
  shape.setStyle("position:absolute;margin-left:0;margin-top:0;width:415pt;height:207.5pt;z-index:-251654144;mso-wrap-edited:f;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin");
  shape.setWrapcoords("616 5068 390 16297 39 16921 -39 17155 7265 17545 7186 17467 -39 17467 18904 17467 10507 17467 8710 17545 18904 17077 18787 16843 18358 16297 18279 12554 19178 12476 20701 11774 20779 11228 21131 10059 21248 8811 21248 7563 20975 6316 20935 5380 19490 5146 14022 5068 2616 5068");
  shape.setFillcolor("#d8d8d8");
  shape.setStyle(shape.getStyle() + ";rotation:315");
  shape.setStroked(STTrueFalse.FALSE);
  CTTextPath shapeTextPath = shape.addNewTextpath();
  shapeTextPath.setStyle("font-family:"Cambria";font-size:1pt");
  shapeTextPath.setString(text);
  pict.set(group);
 }

 public static void main(String[] args) throws Exception {

  //XWPFDocument doc= new XWPFDocument();
  XWPFDocument doc= new XWPFDocument(new FileInputStream("./WordDocument.docx"));

  // the body content
  XWPFParagraph paragraph = doc.createParagraph();
  XWPFRun run=paragraph.createRun();
  run.setText("New text in body.");

  // get or create the default header
  XWPFHeader header = doc.createHeader(HeaderFooterType.DEFAULT);
  // get or create first paragraph in first header
  paragraph = header.getParagraphArray(0);
  if (paragraph == null) paragraph = header.createParagraph();
  // set watermark to that paragraph
  setWatermarkInParagraph(paragraph, "Watermark default");

  header = doc.createHeader(HeaderFooterType.EVEN);
  paragraph = header.getParagraphArray(0);
  if (paragraph == null) paragraph = header.createParagraph();
  setWatermarkInParagraph(paragraph, "Watermark even");

  header = doc.createHeader(HeaderFooterType.FIRST);
  paragraph = header.getParagraphArray(0);
  if (paragraph == null) paragraph = header.createParagraph();
  setWatermarkInParagraph(paragraph, "Watermark first");

  FileOutputStream out = new FileOutputStream("./WordDocumentWithWatermark.docx");
  doc.write(out);
  out.close();
  doc.close();

 }
}

A: Based on the excellent answer of Axel I wrote this code:
    public DocumentTools addWatermark(String watermark) throws IOException {
        addWatermark(watermark, "#d8d8d8", 315, HeaderFooterType.DEFAULT);
        return this;
    }

    public DocumentTools addWatermark(String watermark, String color, float rotation, HeaderFooterType... hft) throws IOException {
        if (hft.length == 0) {
            hft = new HeaderFooterType[1];
            hft[0] = HeaderFooterType.DEFAULT;
        }

        for (HeaderFooterType headerFooterType : hft) {

            // get or create the default header
            XWPFHeader header = doc.createHeader(headerFooterType);
            // get or create first paragraph in first header
            XWPFParagraph paragraph = header.getParagraphArray(0);
            if (paragraph == null) {
                paragraph = header.createParagraph();
            }
            // set watermark to that paragraph
            setWatermarkInParagraph(paragraph, watermark, color, rotation);

        }
        return this;

    }

    //=====================================================
    // Axel code with a minimal fix for color and rotation parameters.
    //=====================================================
    private static void setWatermarkInParagraph(XWPFParagraph paragraph, String text, String color, float rotation) {
        //CTP p = CTP.Factory.newInstance();
        CTP p = paragraph.getCTP();
        XWPFDocument doc = paragraph.getDocument();
        CTBody ctBody = doc.getDocument().getBody();
        byte[] rsidr = null;
        byte[] rsidrdefault = null;
        if (ctBody.sizeOfPArray() == 0) {
            // TODO generate rsidr and rsidrdefault
        } else {
            CTP ctp = ctBody.getPArray(0);
            rsidr = ctp.getRsidR();
            rsidrdefault = ctp.getRsidRDefault();
        }
        p.setRsidP(rsidr);
        p.setRsidRDefault(rsidrdefault);
        CTPPr pPr = p.getPPr();
        if (pPr == null) {
            pPr = p.addNewPPr();
        }
        CTString pStyle = pPr.getPStyle();
        if (pStyle == null) {
            pStyle = pPr.addNewPStyle();
        }
        pStyle.setVal("Header");
        // start watermark paragraph
        CTR r = p.addNewR();
        CTRPr rPr = r.addNewRPr();
        rPr.addNewNoProof();
        int idx = 1;
        CTPicture pict = r.addNewPict();
        CTGroup group = CTGroup.Factory.newInstance();
        CTShapetype shapetype = group.addNewShapetype();
        shapetype.setId("_x0000_t136");
        shapetype.setCoordsize("1600,21600");
        shapetype.setSpt(136);
        shapetype.setAdj("10800");
        shapetype.setPath2("m@7,0l@8,0m@5,21600l@6,21600e");
        CTFormulas formulas = shapetype.addNewFormulas();
        formulas.addNewF().setEqn("sum #0 0 10800");
        formulas.addNewF().setEqn("prod #0 2 1");
        formulas.addNewF().setEqn("sum 21600 0 @1");
        formulas.addNewF().setEqn("sum 0 0 @2");
        formulas.addNewF().setEqn("sum 21600 0 @3");
        formulas.addNewF().setEqn("if @0 @3 0");
        formulas.addNewF().setEqn("if @0 21600 @1");
        formulas.addNewF().setEqn("if @0 0 @2");
        formulas.addNewF().setEqn("if @0 @4 21600");
        formulas.addNewF().setEqn("mid @5 @6");
        formulas.addNewF().setEqn("mid @8 @5");
        formulas.addNewF().setEqn("mid @7 @8");
        formulas.addNewF().setEqn("mid @6 @7");
        formulas.addNewF().setEqn("sum @6 0 @5");
        CTPath path = shapetype.addNewPath();
        path.setTextpathok(STTrueFalse.T);
        path.setConnecttype(STConnectType.CUSTOM);
        path.setConnectlocs("@9,0;@10,10800;@11,21600;@12,10800");
        path.setConnectangles("270,180,90,0");
        CTTextPath shapeTypeTextPath = shapetype.addNewTextpath();
        shapeTypeTextPath.setOn(STTrueFalse.T);
        shapeTypeTextPath.setFitshape(STTrueFalse.T);
        CTHandles handles = shapetype.addNewHandles();
        CTH h = handles.addNewH();
        h.setPosition("#0,bottomRight");
        h.setXrange("6629,14971");
        CTLock lock = shapetype.addNewLock();
        lock.setExt(STExt.EDIT);
        CTShape shape = group.addNewShape();
        shape.setId("PowerPlusWaterMarkObject" + idx);
        shape.setSpid("_x0000_s102" + (4 + idx));
        shape.setType("#_x0000_t136");
        shape.setStyle("position:absolute;margin-left:0;margin-top:0;width:415pt;height:207.5pt;z-index:-251654144;mso-wrap-edited:f;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin");
        shape.setWrapcoords("616 5068 390 16297 39 16921 -39 17155 7265 17545 7186 17467 -39 17467 18904 17467 10507 17467 8710 17545 18904 17077 18787 16843 18358 16297 18279 12554 19178 12476 20701 11774 20779 11228 21131 10059 21248 8811 21248 7563 20975 6316 20935 5380 19490 5146 14022 5068 2616 5068");
        shape.setFillcolor(color);
        shape.setStyle(shape.getStyle() + ";rotation:"+rotation);
        shape.setStroked(STTrueFalse.FALSE);
        CTTextPath shapeTextPath = shape.addNewTextpath();
        shapeTextPath.setStyle("font-family:"Cambria";font-size:1pt");
        shapeTextPath.setString(text);
        pict.set(group);
    }


text:
Q: Xamarin iOS FFImageLoading load image from asset-library I can't load image from an ImageCached object on iOS.
I got an asset-library url from the ALAsset but when I create the ImageCached object it d'ont show the image, ending with error that file is not found.
I take the image url from (ALAsset)asset.AssetUrl.AbsoluteString
Here is the bit of code that init my CachedObject
CachedImage image = new CachedImage();
image.Source = url;
image.HeightRequest = heightRequest;
image.WidthRequest = widthRequest;
image.DownsampleWidth = downSample;
image.CacheDuration = TimeSpan.FromDays(30);
image.LoadingPlaceholder = "Images/loading_grey.png";
image.ErrorPlaceholder = "Images/placeholder.png";
image.Transformations = new System.Collections.Generic.List<ITransformation>() {
    new CropTransformation(1, image.Width / 2 - heightRequest, image.Height / 2 - widthRequest)
};
image.CacheType = FFImageLoading.Cache.CacheType.Disk;
image.GestureRecognizers.Add(new TapGestureRecognizer
{
    Command = new Command(() => {
        Navigation.PushModalAsync(new ViewImagePage(url));
    }),
    NumberOfTapsRequired = 1
});
return image;

From an another posts i got a trail with this when i browse my image
ImagesNames.Add(asset.DefaultRepresentation.Url.AbsoluteString);

But image Path just link to asset.JPG that doesn't point to the file


text:
Q: Monitoring GPS receiver/adapter status I just need to monitor the status of GPS Receiver or adapter, cause my application don't want to work if gps is disabled manually by user...
Tried to use info from this link, but didn't help - How can I monitor the status of the GPS adapter using Android SDK?
Any ideas what to do?

A: To check the availability of GPS you can use the following code
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        //gps off. User turned the GPS off manually.
    }

A:    boolean gpSstate = locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER);
    boolean networkState =locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!gpsState && !networkState) {// no GPS Service }


text:
Q: submit form on check box checked and unchecked forms.py
class SearchKeyword(Form):
    status = forms.BooleanField(widget=forms.CheckboxInput(attrs={'id':'status'}),required=False, label="Status")

javascript:
$(function() {
    $('#status:checkbox').attr('checked', true);
    $("#status-form").submit();
    return false;
});

I want to show Live report by default,so the check box is checked.If it is checked it will show the Live report alone,if unchecked it shows Live as well as  Test reports.I need to submit the same form for checkbox checked as well as for check box uncheck.I tried with the above code,the problem is it is showing Live reports but page gets refresh again and again.

A: Try this:
$(function() {
    var chkBox = $('#status:checkbox');
    chkBox.on('change', function() {$("#status-form").submit();});
    chkBox.attr('checked', true);
});


text:
Q: Non-zero order parameters in the disordered phase We often learn that the order parameter is a perfect tool for the study of a phase transition (assuming Landau-Ginzburg theory is applicable). The order parameter is finite in the ordered phase, and perfectly zero in the disordered phase. Indeed, this is how we define the order parameter; if a physical observable is finite in the disordered phase, then it wouldn't be an order parameter by definition.
However, experimentally speaking, such a perfect order parameter seems unlikely. Are there any experimental, real-world examples (in condensed matter, high-energy, statistical physics, etc.) where the order parameter is nearly zero but still finite in the disordered phase, just above the critical point?

A: The version you learn in class is the simplest version. In practice, the order parameter doesn't need to be zero, it just needs to have a sharp change. For example: the liquid gas transition, the order parameter (density) is finite on both sides of the first order transition, but there is a sharp change.
If you're coming down through the critical point (like lowering $T$ with $h=0$ in a FM), there won't be a sharp change, but the density is still finite the whole time. You could define a modified density $\tilde \rho \equiv \rho - \rho_c$ where $\rho_c$ is the density at the critical point.


text:
Q: What is the correct usage of "std::reduce" The following code compiles on MSVC but it fails on GCC. It seems GCC requires the type of the dereferenced iterator and init to be the same, even though there is no such requirement according to this reference. Note that if I replace std::reduce() with std::accumulate() then it works.
std::random_device e;
std::uniform_int_distribution<> dist(1, 10);
const int n = 10;
std::vector<int> v(n);
std::generate(v.begin(), v.end(), [&]() {return dist(e); });
const auto result = std::reduce(v.begin(), v.end(), std::make_pair(0, 0),
    [](std::pair<int,int> sum,int n) {
        if (n % 2 == 1) sum.first += n;
        else sum.second += n;
        return sum;
    });

A: From [reduce]/5

Mandates: All of

*

*binary_op(init, *first),

*binary_op(*first, init),

*binary_op(init, init), and

*binary_op(*first, *first)

  are convertible to T.

You lambda can't work for binary_op(*first, *first) so gcc is correct in rejecting it.


text:
Q: How safe is following code for creating mysql - yearly resetting field, safety also considering input from multiple requests I HAVE tables in this test code:
table WORKER -> name varchar(50)      , spec varchar(50) UNIQYE
table KEYGEN- > id INT AUTO_INCREMENT , year varchar(50)
spec should be like = 2009/54.
CODE: for checking and reseting (truncating) keygen table.
$insertedid=""; //to put last inserted id from keygen
$spec="";   //spec number generated from year + $insertedid in table keygen
$year=date("Y");  //current year

$query="SELECT * from keygen WHERE year='{$year}' ";

    if($noviRed=$mysqli->query($query))
    {
        if($noviRed->num_rows==0)
        {
            $truncate="truncate keygen";
                if($mysqli->query($truncate)) {echo"<h2> TRUNCATING  TABLE OK </h2>";}  else { exit("fatal error");}

            $query2="INSERT INTO keygen(year) values('{$year}') ";
                if($mysqli->query($query2)) {$insertedid=$mysqli->insert_id;} else {exit("fatal error");}
        }
        else
        {

            $query2="INSERT INTO keygen(year) values('{$year}') ";
                if($mysqli->query($query2)) {$insertedid=$mysqli->insert_id;} else {exit("fatal error");}
        }
    }
    else {exit("fatal error");}

CODE: for inserting data into worker table.
$spec=$year."/".$insertedid; //generating spec number

if($insertedid!="" AND $spec!="")
{
    $query3="INSERT INTO worker(name,spec) values('{$name}','{$spec}') ";

    if($noviRed=$mysqli->query($query3)){echo"<h1>SUCCES </h1>";}
    else {exit("fatal error");}
}

A: Not entirely safe.
If multiple requests come in at once near the beginning of a year, the TRUNCATE query may end up running twice, as the SELECT will return zero rows for both requests. This would probably result in a unique key collision on one of the subsequent inserts.


text:
Q: How to get categories ordered by displayName with Google My business API does the Google API provide a way to get the categories ordered by displayName or do I have to order them on my end?

A: I think you need to order them as you need after getting the data. I have never found a sort query param to apply.


text:
Q: ComboBox SelectedValue Returning an Object And Not The Value Goal: When my form loads I am doing a database call which is returning to me a DataTable that I want to assign as a KeyValuePair(string,string) as the datasource to a combo-box. With the Display Member being the key (RailCarID) and the Value Member being the value (RailcarTransaction_Guid)(I am storing it as a string).
The problem I am having, is when I do combobox.SelectedValue...It is returning to me an object rather than a string. Can anyone suggest what I am doing wrong here?
I was originally using a dictionary (and it would error out), and thru searching to resolve my issue ended up using a BindingList. Now my combobox on my application displays the object array in the display. Below, is some code snippets:
    private void GetAllTransactions()
    {
        BindingList<KeyValuePair<string, string>> Transactions = new BindingList<KeyValuePair<string, string>>();
        string sql = "SELECT * FROM RailcarTransaction WHERE IsComplete = 'True' AND IsUploaded = 'False'";
        DataTable transactions = session1.GetRecords(sql);
        for (int i = 0; i < transactions.Rows.Count; i++)
        {
            Transactions.Add(new KeyValuePair<string, string>(transactions.Rows[i]["RailCarID"].ToString(), transactions.Rows[i]["RailcarTransaction_Guid"].ToString()));
        }
        cboxRailCars.DisplayMember = "Key";
        cboxRailCars.ValueMember = "Value";
        cboxRailCars.DataSource = Transactions;
    }

A: Since ComboBox.ValueMember could be set to a property of any data type (it could be an int or DateTime for example, not necessarily a string), the SelectedValue property is an object.
You have to know what type you're actually dealing with and convert it back:
var selectedRailCar = Convert.ToString(cboxRailCars.SelectedValue);


text:
Q: Why does my UIAlertController not appear until the second time I press it's tab? I am using the following class to try and make an alert popup when I click on a specific tab (rather than switching to that tab). The first time I click the tab it goes to an empty view and does not show the alert.
The second time I click it (and beyond) it works as intended.
Is there a way to make the alert fire the first time I click the tab?
Code for the class is below:
class TabOverlayViewController: UIViewController, UITabBarControllerDelegate {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.delegate = self

    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

        if viewController == tabBarController.viewControllers?[1] {
            let alert = UIAlertController(title: "Add", message: "", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Album", style: .default) { action in

            })
            self.present(alert, animated: true, completion: {

            })

            return false
        } else {
            return true
        }
    }
}

A: This happens because you set UITabBarViewControllerDelegate only in viewWillAppear method. So first time there is no delegate's call, view appears, sets delegate and involves func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool method only on following taps.
UPD:
By the way, are you sure that this particular controller should be a delegate for UITabBarController? Is it correct that concrete controller decides which tab could be opened and which not? In a simple app I would assign to delegate tab bar controller itself:
final class TabBarVC: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
    }
}

extension TabBarVC: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
       // do your logic here
    }
}

Of course, you should specify, that your current tab bar controller is type of TabBarVC.


text:
Q: jQuery change time of setInterval using range input I am trying to access the time value of setInterval, however I am new in jQuery and JavaScript and I am not sure how can I achieve this. Here is what I have for now:
<form name="form4" oninput="amount.value=rangeInput.value">
    <input type="range" id="rangeInput" value="1000" name="rangeInput" min="1000" max="10000" step="500"/>
    <output name="amount" for="rangeInput">1000</output>
</form>

And the code would be:
$(function randomName() {
    setInterval(function(){
        //alert("some text");
    }, 10000);
});

Here is a fiddle of what I have for now https://jsfiddle.net/mLk3wb50/
Is there a way to change the value of time, link it to the range input?
Basically, I would like to execute the alert or whatever action at intervals set by the range input. Is this possible? Thanks!

A: This seems to be the way. You will need to clear the interval before reinitializing it.
function someFunc(){ alert("hi"); }
var interval;

$(function randomName() {
    interval = setInterval(someFunc, 10000);;
});

$("#rangeInput").on("change", function(){
    clearInterval(interval);
    interval = setInterval(someFunc, $(this).val());
});

FIDDLE

A: Here's a way to change the interval:
 function myFunc(){ alert('hi'); }

 var myInterval = setInterval(myFunc, 1000);

 function changeInterval(){
    clearInterval(myInterval);
    myInterval = setInterval(myFunc, 2000);
 }


text:
Q: найти css selector по тексту Подскажите пожалуйста, как записать селектор для следующего элемента:

Пробовал вот так: span:contains('Mozah'), но не получается

A: У вас не работал вариант  div:contains('my text'), потому эта конструкция работает только с jQuery

$("span:contains('Ьщяфр')").text("Mozah");

Ьщяфр


text:
Q: How to check number of cores and ram capacity left in kubernetes cluster I have a Kubernetes cluster of around 18 nodes where few are with 4 cores and 16G RAM, and few are with 16 core and 64G RAM, and there are around 25-30 applications running on
the cluster.
Each of the applications are configured with requests and limit parameter, around 2-3cores & 4-8G ram and allocated to each of the application.
Now how do I get the current utilization report saying how many cores/ram I am left within the current cluster? before deploying any new application.
I tried using the below commands:
kubectl top no;    kubectl describe no [node-name]

These are not giving me the exact no. of cores or ram I am left with.
Any leads to this will help a lot.
Note: I am using version 1.19 of Kubernetes.

A: You can use a kubectl plugin to view the resourses capacity, usage etc.
Here, are few related plugins.

*

*etopeter/kubectl-view-utilization

*davidB/kubectl-view-allocations

*robscott/kube-capacity
You can use krew to install those plugins.

A: kubectl describe node <insert-node-name-here>
You should see something like this:
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource                       Requests      Limits
  --------                       --------      ------
  cpu                            1130m (59%)   3750m (197%)
  memory                         4836Mi (90%)  7988Mi (148%)
  ephemeral-storage              0 (0%)        0 (0%)
  hugepages-1Gi                  0 (0%)        0 (0%)
  hugepages-2Mi                  0 (0%)        0 (0%)
  attachable-volumes-azure-disk  0             0


text:
Q: Set line alpha when plotting multiple roc curves (in same color) with plotROC I'm ploting my ROC curves with plotROC. Below is the example code. I need to plot multiple roc curves with the same color. I found I need to use alpha in aes.  Now I need to control the transparency of my curves. Using alpha in geom_roc is not working. Does anyone knows what I can do? Thanks a lot.
D.ex <- rbinom(50, 1, .5)
rocdata <- data.frame(D = c(D.ex, D.ex),
                   M = c(rnorm(50, mean = D.ex, sd = .4),
                         rnorm(50, mean = D.ex, sd = 1)),
                   Z = rep(c('A', 'B', 'C', 'D', 'E'), each=20) )
library(plotROC)
ggplot(rocdata, aes(m=M, d=D, alpha=Z)) +
            geom_roc(cutoffs.at = NULL, n.cuts=0, color='blue')+
            theme(legend.position="none")

A: For plotROC::geom_rec you have to set alpha with linealpha argument (not within aes). But for this to work you also need to specify line group. Usually in ggplot2 it's done with group = Z, but in geom_rec it doesn't work. Quick solution would be to set color by Z (color = Z) and with scale_color_manual set same color.
library(plotROC)
ggplot(rocdata, aes(m = M, d = D, color = Z)) +
    geom_roc(cutoffs.at = NULL, n.cuts = 0, linealpha = 0.5) +
    scale_color_manual(values = rep("black", length(unique(rocdata$Z)))) +
    theme(legend.position = "none")


text:
Q: Resize UICollectionViewCell on touch and hold I'm trying to accomplish the same effect that the iPhone springboard does when moving icons. When the icons are in "wiggle" mode, and you touch and hold one, it will expand a little bit.
I am currently UILongPressGestureRecognizer to handle the resize animation like this:
func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {

    let p = gestureReconizer.location(in: collectionView)
    let indexPath = self.collectionView?.indexPathForItem(at: p)

    if indexPath != nil && indexPath?.row != collectionData.count {
        if gestureReconizer.state == UIGestureRecognizerState.began {

            let cell = collectionView?.cellForItem(at: indexPath!)

            UIView.animate(withDuration: 0.5, animations: {
                cell?.frame = CGRect(x: (cell?.frame.origin.x)!, y: (cell?.frame.origin.y)!, width: (cell?.frame.width)! + 5, height: (cell?.frame.height)! + 5)
            })
        }
        else if gestureReconizer.state == .ended {

            let cell = collectionView?.cellForItem(at: indexPath!)

            UIView.animate(withDuration: 0.5, animations: {
                cell?.frame = CGRect(x: (cell?.frame.origin.x)!, y: (cell?.frame.origin.y)!, width: (cell?.frame.width)! - 5, height: (cell?.frame.height)! - 5)
            })
        }
    }
}

This does resize the cell but as soon as I move it it goes back to its original size.


text:
Q: Rsync from Linux to Windows SFTP Server I'm trying to sync documents to an Windows SFTP server via RSYNC on a Linux Machine.
This is my command
rsync -e ssh /home/antony/Documents/Test user1@172.20.1.18:Test

This is the error
exec request failed on channel 0
rsync connection unexpectedly closed (0 bytes recieved so far)[sender]
rsync error: unexplained error (code 255) at io.c(226) [sender=3.1.0]

A: The above may happen for several different reasons.
Maybe the SSH subsystem of rsync is refusing the server key, but this is unlikely because from your description seems like the server is "cutting" the connection, not the client.
Another possibility is that there is no SSH/SFTP server listening on the default port on 172.20.1.18
Or maybe password authentication is not enabled on the server, and you need to authenticate via PKI using a key that you (on the client side) do not have...
In any case, the best thing to do is to double check with the administrator who has configured the server side.


text:
Q: Как я могу проверить на наличие одинакового значения value в теги и добавить класс? Есть блок html

      <button class="btn radio" value="1">s</button>
      <button class="btn radio" value="2">m</button>
      <button class="btn radio" value="3">xl</button>

        <button class="btn color" value="1">red</button>
        <button class="btn color" value="2">black</button>
        <button class="btn color" value="3">green</button>

Не могу понять как правильно написать проверку, чтобы при клике на button с одинаковыми value добавлялся класс active
Понимаю что можно класс radio сравнивать с color
$(".btn").each(function() {
  let BtnRadio = $('.btn.radio').attr("value");
  let BtnColor = $('.btn.color').attr("value");

  if ($(BtnRadio) === $(BtnColor)) {
    $(this).addClass("active");
  }
});

This это же должно быть у нас .btn? или я не туда иду?
ну чето не так (

A:

$('.btn').click(function(){
  $('.btn').removeClass('active');
  $(`.btn[value="${this.value}"]`).addClass('active');
});
.active {
  color: red;
}

.btn:not(.active){
  color: green;
}

      <button class="btn radio" value="1">s</button>
      <button class="btn radio" value="2">m</button>
      <button class="btn radio" value="3">xl</button>

        <button class="btn color" value="1">red</button>
        <button class="btn color" value="2">black</button>
        <button class="btn color" value="3">green</button>

A:

$(document).on('click', 'button.radio', function() {
    let value = $(this).val();
    $('.btn.color').removeClass('active');
    $(`.btn.color[value=${value}]`).addClass('active');
});
.btn.color.active {
  background: blue;
  color: white;
}

      <button class="btn radio" value="1">s</button>
      <button class="btn radio" value="2">m</button>
      <button class="btn radio" value="3">xl</button>

        <button class="btn color" value="1">red</button>
        <button class="btn color" value="2">black</button>
        <button class="btn color" value="3">green</button>


text:
Q: i can't deserializing into JSON in C#. Is it something wrong with my classes? I'm having trouble when tryin to Deserialize a string into JSON.
I'm making a call to a API. The anwer i get is stored i a variable(body)
Root Api = JsonConvert.DeserializeObject<Root>(body);
//var json = JsonConvert.DeserializeObject<Root>(body);

public partial class All
{
    public int matchsPlayed { get; set; }
    public int win { get; set; }
    public int draw { get; set; }
    public int lose { get; set; }
    public int goalsFor { get; set; }
    public int goalsAgainst { get; set; }
}

public partial class Home
{
    public int matchsPlayed { get; set; }
    public int win { get; set; }
    public int draw { get; set; }
    public int lose { get; set; }
    public int goalsFor { get; set; }
    public int goalsAgainst { get; set; }
}

public partial class Away
{
    public int matchsPlayed { get; set; }
    public int win { get; set; }
    public int draw { get; set; }
    public int lose { get; set; }
    public int goalsFor { get; set; }
    public int goalsAgainst { get; set; }
}

public partial class Standings // Offers
{
    public int rank { get; set; }
    public int team_id { get; set; }
    public string teamName { get; set; }
    public string logo { get; set; }
    public string group { get; set; }
    public string forme { get; set; }
    public string status { get; set; }
    public string description { get; set; }
    public All all { get; set; }
    public Home home { get; set; }
    public Away away { get; set; }
    public int goalsDiff { get; set; }
    public int points { get; set; }
    public string lastUpdate { get; set; }
}

public partial class Api // ProductListing
{
    public int results { get; set; }
   // public Standings[] Standings { get; set; }
    public List<Standings> standings { get; set; }
}

public partial class Root // RootObject
{
    public Api api { get; set; }
}

I get this error message: "

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'Standings' because the type requires a JSON object (e.g.
{"name":"value"}) to deserialize correctly. To fix this error either
change the JSON to a JSON object (e.g. {"name":"value"}) or change the
deserialized type to an array or a type that implements a collection
interface (e.g. ICollection, IList) like List that can be
deserialized from a JSON array. JsonArrayAttribute can also be added
to the type to force it to deserialize from a JSON array.

"
This is the whole json text i'm tryin to deserialize:
> {"api":{"results":1,"standings":[[{"rank":1,"team_id":45,"teamName":"Everton","logo":"https:\/\/media.api-sports.io\/football\/teams\/45.png","group":"Premier League","forme":"DWWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":5,"win":4,"draw":1,"lose":0,"goalsFor":14,"goalsAgainst":7},"home":{"matchsPlayed":3,"win":2,"draw":1,"lose":0,"goalsFor":11,"goalsAgainst":6},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":3,"goalsAgainst":1},"goalsDiff":7,"points":13,"lastUpdate":"2020-10-19"},{"rank":2,"team_id":66,"teamName":"Aston Villa","logo":"https:\/\/media.api-sports.io\/football\/teams\/66.png","group":"Premier League","forme":"WWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":4,"win":4,"draw":0,"lose":0,"goalsFor":12,"goalsAgainst":2},"home":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":8,"goalsAgainst":2},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":4,"goalsAgainst":0},"goalsDiff":10,"points":12,"lastUpdate":"2020-10-19"},{"rank":3,"team_id":40,"teamName":"Liverpool","logo":"https:\/\/media.api-sports.io\/football\/teams\/40.png","group":"Premier League","forme":"DLWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":5,"win":3,"draw":1,"lose":1,"goalsFor":13,"goalsAgainst":13},"home":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":7,"goalsAgainst":4},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":6,"goalsAgainst":9},"goalsDiff":0,"points":10,"lastUpdate":"2020-10-19"},{"rank":4,"team_id":46,"teamName":"Leicester","logo":"https:\/\/media.api-sports.io\/football\/teams\/46.png","group":"Premier League","forme":"LLWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":5,"win":3,"draw":0,"lose":2,"goalsFor":12,"goalsAgainst":8},"home":{"matchsPlayed":3,"win":1,"draw":0,"lose":2,"goalsFor":4,"goalsAgainst":6},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":8,"goalsAgainst":2},"goalsDiff":4,"points":9,"lastUpdate":"2020-10-19"},{"rank":5,"team_id":42,"teamName":"Arsenal","logo":"https:\/\/media.api-sports.io\/football\/teams\/42.png","group":"Premier League","forme":"LWLWW","status":"same","description":"Promotion - Europa League (Group Stage)","all":{"matchsPlayed":5,"win":3,"draw":0,"lose":2,"goalsFor":8,"goalsAgainst":6},"home":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":4,"goalsAgainst":2},"away":{"matchsPlayed":3,"win":1,"draw":0,"lose":2,"goalsFor":4,"goalsAgainst":4},"goalsDiff":2,"points":9,"lastUpdate":"2020-10-19"},{"rank":6,"team_id":39,"teamName":"Wolves","logo":"https:\/\/media.api-sports.io\/football\/teams\/39.png","group":"Premier League","forme":"WWLLW","status":"same","description":null,"all":{"matchsPlayed":5,"win":3,"draw":0,"lose":2,"goalsFor":5,"goalsAgainst":7},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":2,"goalsAgainst":3},"away":{"matchsPlayed":3,"win":2,"draw":0,"lose":1,"goalsFor":3,"goalsAgainst":4},"goalsDiff":-2,"points":9,"lastUpdate":"2020-10-19"},{"rank":7,"team_id":47,"teamName":"Tottenham","logo":"https:\/\/media.api-sports.io\/football\/teams\/47.png","group":"Premier League","forme":"DWDWL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":2,"lose":1,"goalsFor":15,"goalsAgainst":8},"home":{"matchsPlayed":3,"win":0,"draw":2,"lose":1,"goalsFor":4,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":11,"goalsAgainst":3},"goalsDiff":7,"points":8,"lastUpdate":"2020-10-19"},{"rank":8,"team_id":49,"teamName":"Chelsea","logo":"https:\/\/media.api-sports.io\/football\/teams\/49.png","group":"Premier League","forme":"DWDLW","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":2,"lose":1,"goalsFor":13,"goalsAgainst":9},"home":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":7,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":1,"draw":1,"lose":0,"goalsFor":6,"goalsAgainst":4},"goalsDiff":4,"points":8,"lastUpdate":"2020-10-19"},{"rank":9,"team_id":48,"teamName":"West Ham","logo":"https:\/\/media.api-sports.io\/football\/teams\/48.png","group":"Premier League","forme":"DWWLL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":11,"goalsAgainst":7},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":4,"goalsAgainst":2},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":7,"goalsAgainst":5},"goalsDiff":4,"points":7,"lastUpdate":"2020-10-19"},{"rank":10,"team_id":63,"teamName":"Leeds","logo":"https:\/\/media.api-sports.io\/football\/teams\/63.png","group":"Premier League","forme":"LDWWL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":9,"goalsAgainst":9},"home":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":5,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":4,"goalsAgainst":4},"goalsDiff":0,"points":7,"lastUpdate":"2020-10-19"},{"rank":11,"team_id":50,"teamName":"Manchester City","logo":"https:\/\/media.api-sports.io\/football\/teams\/50.png","group":"Premier League","forme":"WDLW","status":"same","description":null,"all":{"matchsPlayed":4,"win":2,"draw":1,"lose":1,"goalsFor":7,"goalsAgainst":7},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":3,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":1,"draw":1,"lose":0,"goalsFor":4,"goalsAgainst":2},"goalsDiff":0,"points":7,"lastUpdate":"2020-10-19"},{"rank":12,"team_id":41,"teamName":"Southampton","logo":"https:\/\/media.api-sports.io\/football\/teams\/41.png","group":"Premier League","forme":"DWWLL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":8,"goalsAgainst":9},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":4,"goalsAgainst":5},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":4,"goalsAgainst":4},"goalsDiff":-1,"points":7,"lastUpdate":"2020-10-19"},{"rank":13,"team_id":34,"teamName":"Newcastle","logo":"https:\/\/media.api-sports.io\/football\/teams\/34.png","group":"Premier League","forme":"LWDLW","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":7,"goalsAgainst":9},"home":{"matchsPlayed":3,"win":1,"draw":0,"lose":2,"goalsFor":4,"goalsAgainst":8},"away":{"matchsPlayed":2,"win":1,"draw":1,"lose":0,"goalsFor":3,"goalsAgainst":1},"goalsDiff":-2,"points":7,"lastUpdate":"2020-10-19"},{"rank":14,"team_id":52,"teamName":"Crystal Palace","logo":"https:\/\/media.api-sports.io\/football\/teams\/52.png","group":"Premier League","forme":"DLLWW","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":6,"goalsAgainst":8},"home":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":3,"goalsAgainst":3},"away":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":3,"goalsAgainst":5},"goalsDiff":-2,"points":7,"lastUpdate":"2020-10-19"},{"rank":15,"team_id":33,"teamName":"Manchester United","logo":"https:\/\/media.api-sports.io\/football\/teams\/33.png","group":"Premier League","forme":"WLWL","status":"same","description":null,"all":{"matchsPlayed":4,"win":2,"draw":0,"lose":2,"goalsFor":9,"goalsAgainst":12},"home":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":2,"goalsAgainst":9},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":7,"goalsAgainst":3},"goalsDiff":-3,"points":6,"lastUpdate":"2020-10-19"},{"rank":16,"team_id":51,"teamName":"Brighton","logo":"https:\/\/media.api-sports.io\/football\/teams\/51.png","group":"Premier League","forme":"DLLWL","status":"same","description":null,"all":{"matchsPlayed":5,"win":1,"draw":1,"lose":3,"goalsFor":9,"goalsAgainst":11},"home":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":3,"goalsAgainst":6},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":6,"goalsAgainst":5},"goalsDiff":-2,"points":4,"lastUpdate":"2020-10-19"},{"rank":17,"team_id":60,"teamName":"West Brom","logo":"https:\/\/media.api-sports.io\/football\/teams\/60.png","group":"Premier League","forme":"DLDLL","status":"same","description":null,"all":{"matchsPlayed":5,"win":0,"draw":2,"lose":3,"goalsFor":5,"goalsAgainst":13},"home":{"matchsPlayed":3,"win":0,"draw":2,"lose":1,"goalsFor":3,"goalsAgainst":6},"away":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":2,"goalsAgainst":7},"goalsDiff":-8,"points":2,"lastUpdate":"2020-10-19"},{"rank":18,"team_id":44,"teamName":"Burnley","logo":"https:\/\/media.api-sports.io\/football\/teams\/44.png","group":"Premier League","forme":"DLLL","status":"same","description":"Relegation - Championship","all":{"matchsPlayed":4,"win":0,"draw":1,"lose":3,"goalsFor":3,"goalsAgainst":8},"home":{"matchsPlayed":1,"win":0,"draw":0,"lose":1,"goalsFor":0,"goalsAgainst":1},"away":{"matchsPlayed":3,"win":0,"draw":1,"lose":2,"goalsFor":3,"goalsAgainst":7},"goalsDiff":-5,"points":1,"lastUpdate":"2020-10-19"},{"rank":19,"team_id":62,"teamName":"Sheffield Utd","logo":"https:\/\/media.api-sports.io\/football\/teams\/62.png","group":"Premier League","forme":"DLLLL","status":"same","description":"Relegation - Championship","all":{"matchsPlayed":5,"win":0,"draw":1,"lose":4,"goalsFor":2,"goalsAgainst":7},"home":{"matchsPlayed":3,"win":0,"draw":1,"lose":2,"goalsFor":1,"goalsAgainst":4},"away":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":1,"goalsAgainst":3},"goalsDiff":-5,"points":1,"lastUpdate":"2020-10-19"},{"rank":20,"team_id":36,"teamName":"Fulham","logo":"https:\/\/media.api-sports.io\/football\/teams\/36.png","group":"Premier League","forme":"DLLLL","status":"same","description":"Relegation - Championship","all":{"matchsPlayed":5,"win":0,"draw":1,"lose":4,"goalsFor":4,"goalsAgainst":12},"home":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":0,"goalsAgainst":6},"away":{"matchsPlayed":3,"win":0,"draw":1,"lose":2,"goalsFor":4,"goalsAgainst":6},"goalsDiff":-8,"points":1,"lastUpdate":"2020-10-19"}]]}}

A: If you change the definition of Api so standings is a list of lists it should work as the JSON has an array of arrays.
public partial class Api // ProductListing
{
    public int results { get; set; }
    public List<List<Standings>> standings { get; set; }
}


text:
Q: Python - Move Elements in a 2-Dimensional Array? Given this 2D Array -
[[0, 0, -1], [0, 0, -2], [0, 0, 0], [0, 0, 3], [0, 0, 0]]
How can I code something in Python that shifts once to the end each time it's called? However, it has to stop if it reaches a positive value.
So I get something like this
[[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 3], [0, 0, 0]]
This is what I have. It works for condition 1 but it does not work for condition 2. What can I tweak so condition 2 also works?
# Condition 1 - Works
data = [[0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0], [0, 0, 0]]
expected = [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0]] # My Results.

# Condition 2 - Does Not Work
data = [[0, 0, -1], [0, 0, -2], [0, 0, 0], [0, 0, 3], [0, 0, 0]]
expected = [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 3], [0, 0, 0]] # This is what I want to get. (But it doesn't work)

rows = len(data)

if data[-1][-1] == 0:
    count = rows-1
    while count > 0:
        data[count][-1] = data[count-1][-1]
        count -= 1
    data[0][-1] = 0

print(data)
print(expected)

This is what I am getting currently. I want to get the expected for Condition 2 listed in the code snipped above.:
Condition 2 Result:
   [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 0], [0, 0, 3]]
Thanks
Update @Furas:
Something like this to find the positive value location?
   possitive_value = []
    for i in range(len(data)):
        if data[i][-1] > 0:
            possitive_value.append(i, -1)

A: I think you have to find first positive value and use its position as rows
EDIT: I changed name count to last to make it more readable
# --- function ---

def move(data):

    rows = len(data)

    # - find positive -

    for x in range(rows):
        if data[x][-1] > 0:
            rows = x # use its position as `rows`
            break    # don't seach other positiove values

    # - star moving -

    # set "last" checked row
    last = rows-1

    # check "last" row
    if data[last][-1] == 0:

        # move previous values
        while last > 0:
            data[last][-1] = data[last-1][-1]
            last -= 1

        # put 0 in first place
        data[0][-1] = 0

# --- tests ---

examples = [
  {
    # Condition 1 - Works
    'data': [[0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0], [0, 0, 0]],
    'expected': [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0]], # My Results.
  },
  {
    # Condition 2 - Works
    'data': [[0, 0, -1], [0, 0, -2], [0, 0, 0], [0, 0, 3], [0, 0, 0]],
    'expected': [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 3], [0, 0, 0]], # This is what I want to get. (But it doesn't work)
  }
]

for example in examples:
    data = example['data']
    expected = example['expected']

    print('  before:', data)
    move(data)
    print('   after:', data)
    print('expected:', expected)
    print(' correct:', data == expected)
    print('---')

Result:
  before: [[0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0], [0, 0, 0]]
   after: [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0]]
expected: [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, -3], [0, 0, 0]]
 correct: True
---
  before: [[0, 0, -1], [0, 0, -2], [0, 0, 0], [0, 0, 3], [0, 0, 0]]
   after: [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 3], [0, 0, 0]]
expected: [[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 3], [0, 0, 0]]
 correct: True
---

EDIT:
BTW: instead of while you can use for with reversed range() if it makes it more readable
def move(data):

    rows = len(data)

    # - find positive -

    for x in range(rows):
        if data[x][-1] > 0:
            rows = x # use its position as `rows`
            break    # don't seach other positiove values

    # - star moving -

    # set "last" checked row
    last = rows-1

    # check "last" row
    if data[last][-1] == 0:

        # move previous values
        for pos in range(last, 0, -1): # range with reversed order
            data[pos][-1] = data[pos-1][-1]

        # put 0 in first place
        data[0][-1] = 0

BTW: both versions move items in original data ("in-place") so they don't need return data.

A: Here's a variation, a function that can be called and will shift data by one every time. I wasn't entirely clear from your question if this was the behavior you wanted.
import numpy as np

def shift_data(data):
    ele_idx = [i  for i,x in enumerate(data) if x != [0,0,0]]
    zero_idx = [i for i,x in enumerate(data) if x == [0,0,0] and i != 0]

    if max(np.diff(ele_idx)) == 1 or max(np.diff([i for i,x in enumerate(data) if x == [0,0,0]])) == 1:#things are consecutive
        data.insert(0,data.pop(-1))
    else:
        tt = [l for l in data[ele_idx[0]:zero_idx[0]+1]]
        tt.insert(0,tt.pop(-1))
        data = data[:ele_idx[0]] + tt + data[zero_idx[0]+1:]

    return data

data = [[0, 0, -1], [0, 0, 0], [0, 0, -2], [0, 0, 0], [0, 0, 3]]
print(data)
for _ in range(0,6):
    data = shift_data(data)
    print(data)

This code outputs:
[[0, 0, -1], [0, 0, 0], [0, 0, -2], [0, 0, 0], [0, 0, 3]]
[[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 0], [0, 0, 3]]
[[0, 0, 0], [0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 3]]
[[0, 0, 3], [0, 0, 0], [0, 0, 0], [0, 0, -1], [0, 0, -2]]
[[0, 0, -2], [0, 0, 3], [0, 0, 0], [0, 0, 0], [0, 0, -1]]
[[0, 0, -1], [0, 0, -2], [0, 0, 3], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, -1], [0, 0, -2], [0, 0, 3], [0, 0, 0]]


text:
Q: I can't log in, how to reset password macbook m1 the password is wrong it shows but I have taken the pic of the password last night

A: To reset password for macbook m1 (icloud password needed) press power button until shut down then before the keyboard on and in case in turn on again before logo appeared or opening sound we press power button for long time until the logo appear and said continue holding for start up option
https://youtube.com/watch?v=pXiqUwB0piE&si=EnSIkaIECMiOmarE


text: Q: how to protect method from concurrent invocation in reactor. Invoked by user via rest I understand that synchronization is discouraged. Can someone show how to protect method from concurrent invocation, when paralel invocation comes from the users over rest? I can think of some of queue through which we serialize requests, but as beginner I wouldn't like to come up with crazy ideas. Can you show how this could look like done correctly? Also serializing is easy, but how about rejecting concurrent request while current one is already in progress?


text:
Q: does someone know why after i decrypt file it breaks? import os
def encrypt(filename,extension):
    file = open(filename+'.'+extension,'r',encoding="Latin-1")
    red = str(file.read())
    final = [extension+'Q']
    fin = ''
    for x in range(len(red) - 1):
        if red[x] == '0':
            final.append('#!#')
        else:
            final.append(red[x])
    for x in final:
        fin += x
    file.close()
    os.system('del '+filename+'.'+extension)
    file = open(filename,'a')
    file.close()
    file = open(filename,'w',encoding="Latin-1")
    file.write(fin)
    file.close()
def decrypt(filename):
    ignore = 0
    file = open(filename,'r',encoding="Latin-1")
    dat = str(file.read())
    final = []
    fin = ''
    exten = ''
    is_done = False
    for x in range(len(dat) - 1):
        if dat[x] == '#' and dat[x + 1] == '!' and dat[x + 2] == '#' and ignore == 0:
            final.append('0')
            ignore = 2
        elif ignore == 0 and is_done == True:
            final.append(dat[x])
        elif not ignore < 1:
            ignore -= 1
        if dat[x] == 'Q':
            is_done = True
        if is_done == False:
            exten += dat[x]
    for x in final:
        fin += x
    print(filename)
    print(exten)
    file.close()
    file = open(filename+'.'+exten,'a')
    file.close()
    file = open(filename+'.'+exten,'w',encoding="Latin-1")
    file.write(str(fin))
    file.close()
    os.system('del '+filename)
decrypt('eee')
#encrypt('eee','png')
#print(open('test.docx','r',encoding="Latin-1").readlines())
#print(open('eee.png','r',encoding='latin-1').read())

i just want it to work as i expect to work and i dont have idea what breaks it help btw when i open files with notepad it looks same so idk whats wrong at all thats weird , sorry for that my code is messy XD thats how my every code looks like

A: What do you mean by it 'breaks'? What I'm seeing in your code is:

*

*When you run open(filename,...), you assume file is correctly holding the file object. You have no error-checking in either encrypt() or decrypt(). After those lines, read the documentation for the function and see what it returns. You should be able to do something in the lines of:

try:
  file = open(filename,'r',encoding="Latin-1")
except err:
  ...

#  start file operations here.

File handling can and will go wrong at some point. You can give the program any file that you can specify, but you need to make sure that operation will run successfully. Common file errors are it not existing, being already open, or the permissions being wrong

*In both encrypt() and decrypt() you repeat this block:

os.system('del '+filename+'.'+extension)
file = open(filename,'a')
file.close()
file = open(filename,'w',encoding="Latin-1")
file.write(fin)
file.close()

where you tell the system to DELETE your file and then re-open it. I suspect that is a part of why you have issues with the file. I'd also consider removing the second close() & open() calls to see if you can change the mode without manipulating the file pointer. If this block of code has to be in both parts, separate it into its own function. And run error handling on Everything.


text:
Q: How to convert JSON to Spark schema automatically? I have a big JSON which is want to use in Spark Structured Streaming. I don't want to re-type this JSON as Spark schema expression manually. Can I do this automatically once?

I wrote this
from pyspark.sql import SparkSession

spark = SparkSession \
    .builder \
    .appName("Infer Schema") \
    .getOrCreate()

df = spark \
    .read \
    .option("multiline", True) \
    .json("file_examples/dataflow/row01.json")

df.printSchema()

df.show()

with open("dataflow_schema.json", "w") as fp:
    fp.write(df.schema.json())

Is this ok?

A: You are on the right path. You may save your schema as a json and then load it later. Be sure to convert it to json and then a StructType before use
import json
from pyspark.sql.types import StructType

with open("dataflow_schema.json", "r") as fp:
    json_schema_str = fp.read()
    my_schema = StructType.fromJson(json.loads(json_schema_str))

In your structured streaming query if you have a json column you may use the from_json method to convert your json to a struct type and eventually several columns eg:
from pyspark.sql.functions import from_json,col

# Assume that we have a kafkaStream
kafkaStream.selectExpr("CAST(value as string)")\
           .select(from_json(col("value"),my_schema).alias("json_value"))\
           .selectExpr("json_value.*") # extract as columns


text:
Q: Microsoft Azure Mobile authentication with Google provider SDK in Android I am currently testing Microsoft Azure and the App Service/Mobile Apps feature using a native Android app and C# on the back end.
I started with the Getting Started application (ToDo) as the base app and now I am trying to enable Authentication using the https://azure.microsoft.com/en-us/documentation/articles/app-service-authentication-overview/ page and Google as the provider.
So far I have

*

*created a Google project with a OAuth Web client

*the authorized redirect uri set there is: https://.azurewebsites.net/.auth/login/google/callback

*in the Azure portal and the App Service instance I have enabled Authorization/Authentication

*the "Action to take when request is not authenticated" option is set to "Allow Request"

*For the Google Provider I have set the Client Id and Client Secret

In the Android app I am using the GoogleApiClient class to let the user select a Google Account. Also I get the ID token and the Server Auth Code
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestIdToken(getString(R.string.server_client_id))
            .requestServerAuthCode(getString(R.string.server_client_id))
            .build();
    mScopes = gso.getScopeArray();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

Once the user picks up an account I retrieve the token and code and then I ask for an access token using the GoogleAuthUtil class. After I get the access_token I try to exchange it with an App Service token (authenticate2 method)
private void handleSignInResult(GoogleSignInResult result) {
    Log.d("", "handleSignInResult: " + result.isSuccess());

    if(result.isSuccess()) {
        final GoogleSignInAccount account = result.getSignInAccount();

        final String idToken = account.getIdToken();
        String serverAuthCode = account.getServerAuthCode();

        mSignInButton.setVisibility(View.GONE);
        mGoogleUserText.setText(account.getDisplayName());
        mGoogleUserText.setVisibility(View.VISIBLE);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putString("idToken", idToken).commit();
        prefs.edit().putString("serverAuthCode", serverAuthCode).commit();

        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... params) {
                try {

                    StringBuilder scopesBuilder = new StringBuilder("oauth2:");
                    for(Scope scope : mScopes) {
                        scopesBuilder//.append("https://www.googleapis.com/auth/")
                                .append(scope.toString())
                                .append(" ");
                    }

                    String token = GoogleAuthUtil.getToken(ToDoActivity.this,
                            account.getEmail(), scopesBuilder.toString());

                    return token;
                } catch (IOException | GoogleAuthException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ToDoActivity.this);
                prefs.edit().putString("accessToken", result).apply();

                authenticate2();
            }
        }.execute();
    } else {
        mSignInButton.setVisibility(View.VISIBLE);
        mGoogleUserText.setVisibility(View.GONE);
    }
}

private void authenticate2() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    String idToken = prefs.getString("idToken", null);
    String serverAuthCode = prefs.getString("serverAuthCode", null);
    String accessToken = prefs.getString("accessToken", null);

    JsonObject json = new JsonObject();
    json.addProperty("access_token", accessToken);
    json.addProperty("id_token", idToken);
    json.addProperty("authorization_code", serverAuthCode);

    ListenableFuture<MobileServiceUser> loginFuture =
            mClient.login(MobileServiceAuthenticationProvider.Google, json);

    Futures.addCallback(loginFuture, new FutureCallback<MobileServiceUser>() {
        @Override
        public void onSuccess(MobileServiceUser result) {
            createTable();
        }

        @Override
        public void onFailure(Throwable t) {
            Log.e(TAG, t.getMessage(), t);
        }
    });
}

So I am using the MobileServiceClient.login() method to send back to the server the access_token of the user in order to get back an Azure session.
Nevertheless, this call fails and I get back a MobileServiceException:
com.microsoft.windowsazure.mobileservices.MobileServiceException: You do not have permission to view this directory or page.
Any ideas what am I missing here?
Thanks

A: Well this is more than embarassing :-)
I first tried to "manually" verify the id_token using the Google tokeninfo endpoint:
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=
but I was getting a generic error that didn't give a lot of info.
Then I used the Google API Java client library and created a small test to verify my token (more info here: https://developers.google.com/identity/sign-in/android/backend-auth)
That test was failing as well and I realized that the reason for that was the expiring time of my token which was smaller than the current time. And this was happening because my emulator time was not correct!
When I set the "correct" timezone everything worked as expected.
Sorry for the post guys. You can use the code here as a template and don't forget to check your emulator time :-)


text:
Q: What's the best way to put a c-struct in an NSArray? What's the usual way to store c-structures in an NSArray? Advantages, disadvantages, memory handling?
Notably, what's the difference between valueWithBytes and valueWithPointer  -- raised by justin and catfish below.
Here's a link to Apple's discussion of valueWithBytes:objCType: for future readers...
For some lateral thinking and looking more at performance, Evgen has raised the issue of using STL::vector in C++.
(That raises an interesting issue: is there a fast c library, not unlike STL::vector but much much lighter, that allows for the minimal "tidy handling of arrays" ...?)
So the original question...
For example:
typedef struct _Megapoint {
    float   w,x,y,z;
} Megapoint;

So: what's the normal, best, idiomatic way to store one's own structure like that in an NSArray, and how do you handle memory in that idiom?
Please note that I am specifically looking for the usual idiom to store structs.  Of course, one could avoid the issue by making a new little class. However I want to know how the usual idiom for actually putting structs in an array, thanks.
BTW here's the NSData approach which is perhaps? not best...
Megapoint p;
NSArray *a = [NSArray arrayWithObjects:
    [NSData dataWithBytes:&p length:sizeof(Megapoint)],
    [NSData dataWithBytes:&p length:sizeof(Megapoint)],
    [NSData dataWithBytes:&p length:sizeof(Megapoint)],
        nil];

BTW as a point of reference and thanks to Jarret Hardie, here's how to store CGPoints and similar in an NSArray:
NSArray *points = [NSArray arrayWithObjects:
        [NSValue valueWithCGPoint:CGPointMake(6.9, 6.9)],
        [NSValue valueWithCGPoint:CGPointMake(6.9, 6.9)],
        nil];

(see How can I add CGPoint objects to an NSArray the easy way?)

A: I would suggest you stick to the NSValue route, but if you really do wish to store plain 'ol struct datatypes in your NSArray (and other collection objects in Cocoa), you can do so -- albeit indirectly, using Core Foundation and toll-free bridging.
CFArrayRef (and its mutable counterpart, CFMutableArrayRef) afford the developer more flexibility when creating an array object. See the fourth argument of the designated initialiser:
CFArrayRef CFArrayCreate (
    CFAllocatorRef allocator,
    const void **values,
    CFIndex numValues,
    const CFArrayCallBacks *callBacks
);

This allows you to request that the CFArrayRef object use Core Foundation's memory management routines, none at all or even your own memory management routines.
Obligatory example:
// One would pass &kCFTypeArrayCallBacks (in lieu of NULL) if using CF types.
CFMutableArrayRef arrayRef = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
NSMutableArray *array = (NSMutableArray *)arrayRef;

struct {int member;} myStruct = {.member = 42};
// Casting to "id" to avoid compiler warning
[array addObject:(id)&myStruct];

// Hurray!
struct {int member;} *mySameStruct = [array objectAtIndex:0];

The above example completely ignores the issues with respect to memory management. The structure myStruct is created on the stack and hence is destroyed when the function ends -- the array will contain a pointer to an object that is no longer there. You can work around this by using your own memory management routines -- hence why the option is provided to you -- but then you have to do the hard work of reference counting, allocating memory, deallocating it and so on.
I would not recommend this solution, but will keep it here in case it is of interest to anyone else. :-)

Using your structure as allocated on the heap (in lieu of the stack) is demonstrated here:
typedef struct {
    float w, x, y, z;
} Megapoint;

// One would pass &kCFTypeArrayCallBacks (in lieu of NULL) if using CF types.
CFMutableArrayRef arrayRef = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
NSMutableArray *array = (NSMutableArray *)arrayRef;

Megapoint *myPoint = malloc(sizeof(Megapoint);
myPoint->w = 42.0f;
// set ivars as desired..

// Casting to "id" to avoid compiler warning
[array addObject:(id)myPoint];

// Hurray!
Megapoint *mySamePoint = [array objectAtIndex:0];

A: A similar method to add c struct is to store the pointer and to de-reference the pointer as so;
typedef struct BSTNode
{
    int data;
    struct BSTNode *leftNode;
    struct BSTNode *rightNode;
}BSTNode;

BSTNode *rootNode;

//declaring a NSMutableArray
@property(nonatomic)NSMutableArray *queues;

//storing the pointer in the array
[self.queues addObject:[NSValue value:&rootNode withObjCType:@encode(BSTNode*)]];

//getting the value
BSTNode *frontNode =[[self.queues objectAtIndex:0] pointerValue];

A: it would be best to use the poor-man's objc serializer if you're sharing this data across multiple abis/architectures:
Megapoint mpt = /* ... */;
NSMutableDictionary * d = [NSMutableDictionary new];
assert(d);

/* optional, for your runtime/deserialization sanity-checks */
[d setValue:@"Megapoint" forKey:@"Type-Identifier"];

[d setValue:[NSNumber numberWithFloat:mpt.w] forKey:@"w"];
[d setValue:[NSNumber numberWithFloat:mpt.x] forKey:@"x"];
[d setValue:[NSNumber numberWithFloat:mpt.y] forKey:@"y"];
[d setValue:[NSNumber numberWithFloat:mpt.z] forKey:@"z"];

NSArray *a = [NSArray arrayWithObject:d];
[d release], d = 0;
/* ... */

...particularly if the structure can change over time (or by targeted platform). it's not as fast as other options, but it's less likely to break in some conditions (which you haven't specified as important or not).
if the serialized representation does not exit the process, then size/order/alignment of arbitrary structs should not change, and there are options which are simpler and faster.
in either event, you're already adding a ref-counted object (compared to NSData, NSValue) so... creating an objc class which holds Megapoint is the right answer in many cases.

A: if you're feeling nerdy, or really have a lot of classes to create: it is occasionally useful to dynamically construct an objc class (ref: class_addIvar). this way, you can create arbitrary objc classes from arbitrary types. you can specify field by field, or just pass the info of the struct (but that's practically replicating NSData). sometimes useful, but probably more of a 'fun fact' for most readers.

How would I apply this here?

you can call class_addIvar and add a Megapoint instance variable to a new class, or you can synthesize an objc variant of the Megapoint class at runtime (e.g., an instance variable for each field of Megapoint).
the former is equivalent to the compiled objc class:
@interface MONMegapoint { Megapoint megapoint; } @end

the latter is equivalent to the compiled objc class:
@interface MONMegapoint { float w,x,y,z; } @end

after you've added the ivars, you can add/synthesize methods.
to read the stored values on the receiving end, use your synthesized methods, object_getInstanceVariable, or valueForKey:(which will often convert these scalar instance variables into NSNumber or NSValue representations).
btw: all the answers you have received are useful, some are better/worse/invalid depending on the context/scenario. specific needs regarding memory, speed, ease to maintain, ease to transfer or archive, etc. will determine which is best for a given case... but there is no 'perfect' solution which is ideal in every regard. there is no 'best way to put a c-struct in an NSArray', just a 'best way to put a c-struct in an NSArray for a specific scenario, case, or set of requirements' -- which you'd have to specify.
furthermore, NSArray is a generally reusable array interface for pointer sized (or smaller) types, but there are other containers which are better suited for c-structs for many reasons (std::vector being an typical choice for c-structs).

A: NSValue doesn't only support CoreGraphics structures – you can use it for your own too. I would recommend doing so, as the class is probably lighter weight than NSData for simple data structures.
Simply use an expression like the following:
[NSValue valueWithBytes:&p objCType:@encode(Megapoint)];

And to get the value back out:
Megapoint p;
[value getValue:&p];

A: I suggest you to use std::vector or std::list for C/C++ types, because at first it's just faster than NSArray, and at second if there will be not enough speed for you - you're always can create your own allocators for STL containers and make them even more fast. All modern mobile Game, Physics and Audio engines uses STL containers to store internal data. Just because they really fast.
If it's not for you - there is good answers from guys about NSValue - i think it's most acceptable.

A: Instead of trying to put c struct in a NSArray you can put them in a NSData or NSMutableData as a c array of structs. To access them you would the do
const struct MyStruct    * theStruct = (const struct MyStruct*)[myData bytes];
int                      value = theStruct[2].integerNumber;

or to set then
struct MyStruct    * theStruct = (struct MyStruct*)[myData mutableBytes];
theStruct[2].integerNumber = 10;

A: While using an NSValue works fine for storing structs as an Obj-C object, you cannot encode an NSValue containing a struct with NSArchiver/NSKeyedArchiver. Instead, you have to encode individual struct members...
See Apple's Archives and Serializations Programming Guide > Structures and Bit Fields

A: For your structure you can add an attribute objc_boxable and use @() syntax to put of your structure into NSValue instance without calling valueWithBytes:objCType::
typedef struct __attribute__((objc_boxable)) _Megapoint {
    float   w,x,y,z;
} Megapoint;

NSMutableArray<NSValue*>* points = [[NSMutableArray alloc] initWithCapacity:10];
for (int i = 0; i < 10; i+= 1) {
    Megapoint mp1 = {i + 1.0, i + 2.0, i + 3.0, i + 4.0};
    [points addObject:@(mp1)];//@(mp1) creates NSValue*
}

Megapoint unarchivedPoint;
[[points lastObject] getValue:&unarchivedPoint];
//or
// [[points lastObject] getValue:&unarchivedPoint size:sizeof(Megapoint)];

A: Instead of using NSArray, there is another container NSPointerArray for the pointer type:
Megapoint point = ...;
NSPointerArray *arr = [NSPointerArray weakObjectsPointerArray];

[arr addPointer:&point];

for (NSUInteger i = 0; i < arr.count; i++) {
    Megapoint *ppoint = [arr pointerAtIndex:i];
    NSLog(@"%p", ppoint);
}

It's your own risk to retain the object's memory.

A: You can use NSObject classes other than the C-Structures to store information. And you can easily store that NSObject in to NSArray.

A: An Obj C object is just a C struct with some added elements.  So just create a custom class and you will have the type of C struct that an NSArray requires.  Any C struct that does not have the extra cruft that an NSObject includes within its C struct will be indigestible to an NSArray.
Using NSData as a wrapper might only be storing a copy of the structs and not the original structs, if that makes a difference to you.


text:
Q: Using `request` with formData containing a file (client-side) I'm trying to upload form data from a client-side form containing a file object, but am having issues doing so using request - https://github.com/request/request#forms
This throws an exception (because of the file object):
var request = require('request');
var myData = {
    a_key: 'a value!',
    a_file: fileInputElement.files[0]
}
request.post({url: 'http://foo.com/upload', formData: myData});

This submits an empty request:
var formData = new FormData();

formData.append('a_key', 'a value!');
formData.append('a_file', fileInputElement.files[0]);

request.post({url: 'http://foo.com/upload', formData: formData});

I'm able to get it working when I don't use request and instead verbosely do:
var formData = new FormData();

formData.append('a_key', 'a value!');
formData.append('a_file', fileInputElement.files[0]);

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://foo.com/upload');
xhr.send(formData);

https://github.com/request/request#forms only has examples using fs.createReadStream which you can't do on client code.
Is this just a limitation of the request module? Any help would be appreciated!


text:
Q: cheap sugar high -- what is that? Source: Obama again gets the last laugh against Putin
Example:

The New York Times' Thomas Friedman wrote two months ago, "[T]oday's reigning cliche is that the wily fox, President Vladimir Putin of Russia, has once again outmaneuvered the flat-footed Americans, by deploying some troops, planes and tanks to Syria to buttress the regime of President Bashar al-Assad and to fight the Islamic State forces threatening him. If only we had a president who was so daring, so tough, so smart…. Putin stupidly went into Syria looking for a cheap sugar high to show his people that Russia is still a world power."

In Urban Dictionary, it says that a sugar high is the high one gets after consuming large amounts of sugar, but I'm not sure I fully understand how they use this expression in this news article.

A: It's a metaphor. A president or any other ruler has a range of choices for improving the citizens' opinion of the government.
He can build hospitals, schools, develop infrastructure and the environment for the business. This will not result in an immediate spike in the popularity of the state, but will gradually increase its prestige.
On the other hand, he can opt for a "quick sugar high". Project military force somewhere, ramp up jingoistic rhetoric. The result: a spike in popularity, in patriotic feeling among the citizens. Such a spike is inevitably short-lived.
Compare with sugar metabolism: if you eat healthily, this will strengthen your organism over the long run, but keeping to a diet could be dull. On the other hand, you can just ingest a lot of sugary things in one sitting. This will give you a "cheap sugar high", but the pleasurable effects will wear off soon.
When you eat refined sugar, your blood glucose levels spike, but then go down as rapidly as they had come up. You feel the need for another "sugar high", since the previous portion of sugar had metabolized too soon.
Here's a comparison graph: high-glycemic index food (such as refined sugar) causes a "high" in blood glucose levels (more energy available), but you become hungry again sooner than if you consumed a regular meal:

(source: University of Sydney)


text:
Q: Change product item HTML? I've looked throught almost every single file in woocommerce directory but everything is very modular (as a modern code should be). I cannot figure out how to change the HTML of single product item (do not confuse with product page).
E.g shortcode [recent_products per_page="3"] generated something like this:

Could any WooCommerce developer lend me a hand?

A: that html structure is created by 3 template files... loop\loop-start.php, loop\loop-end.php, and content-product.php. Look for these files on the templates folder of woocommerce plugin folder.
you need to override these templates file.. instructions here: Template structure & Overriding templates via a theme...


text:
Q: Get z-index of element in TinyMce (orchard) I am using TinyMce4.I have some function that go all over my elements inside editor ,and appends to all elements new div ,AND to that DIV i need set z-index of that (parent)element.
i use draggable on all elements,and when i drag them i can see them one over the other,second element(2) over (3) ,(4) over (1),(2),(3).... than means that they have z-index value some where,but when i debug i cant find it
i used
ElementsArr[0].style.zIndex

it is return me empty string.
My code:
var editor = tinymce.activeEditor;
var ed_body = $(editor.getBody());
var ElementsArr = tinyMCE.activeEditor.dom.select(".draggableTemplate");
var el = ElementsArr[0];
var z = ElementsArr[0].style.zIndex;//z=''

In the css z-index is empty ,but when i drag it i can see that they behave like that do have it.
How i can get z-index of this elements,what other way to get it?

A: Try this:
$(ElementsArr[0]).css('z-index'); // jQuery way

or
getComputedStyle(ElementsArr[0]).zIndex; // js way


text:
Q: Using different controls in a editable column I have a kendoGrid initialized in cshtml. It use ajax binding.
The grid model looks like
int id,
int typeId,
string name.
string value.
The grid has 2 columns Name and Value and value is editable InCell.
For now grid works well with using by default usual textbox as editor.
I have to improve the grid to have possibility of using different controls in the "value" field depending of the value of "typeId".
I tried to use custom EditorTemplate for that but I cannot find a way to pass typeId to the template (the column is bound to "value").
Is it possible to pass there an extra parameter from the grid model or reach it somehow from the template?
Regards, Alexey


text:
Q: PC-game controlled via Smartphone - Airconsole I am currently working on a Unity Project where I use the Unity-PlugIn Airconsole to develop a game where the movment of the Player is controlled via the gyro-Sensor of a Smartphone.
To make it clear, my game runs on a PC and the smartphone should be the controller -> therefore Airconsole.
The current state is, that I save the Inputs of the gyro sensor in a Vector3
void Awake () {
    AirConsole.instance.onMessage += OnMessage;
}

void OnMessage (int from, JToken data){

    switch (data ["action"].ToString ()) {
    case "motion":
        if (data ["motion_data"] != null) {

            if (data ["motion_data"] ["x"].ToString() != "") {

                Vector3 abgAngles = new Vector3 (-(float)data ["motion_data"] ["beta"], -(float)data ["motion_data"] ["alpha"], -(float)data ["motion_data"] ["gamma"]);
                Debug.Log ("abgAngles.x: " + abgAngles.x + "abgAngles.y: " + abgAngles.y + "abgAngles.z: " + abgAngles.z);

These angles are then used in the Rigidbody.velocity function (did not bother with Time.deltaTime yet)
float x = Input.GetAxis("Horizontal");
                float z = Input.GetAxis("Vertical");
                var rigidbody = GetComponent < Rigidbody > ();

                if(cameraIsActive == false){

                    rigidbody.velocity = new Vector3(abgAngles.y * 0.5f, velocity.y , abgAngles.x * 0.5f);

This somewhat works quite nice, because the velocity function guarantees a smooth steering, while for example the transform.position stutters because I have no idea how to smoothen the Input.
Now i am stuck implementing two functions. First I want to implement a camera rotation. So on my smartphone i have a html button called "camera", and while u press this button u can steer the camera with the gyroscope and not the movement.
else {
    if (abgAngles.y < -10) {
            m_EulerAngleVelocity = new Vector3(0,100,0);
            Quaternion deltaRotation = Quaternion.Euler (m_EulerAngleVelocity*Time.fixedDeltaTime);
            rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);
    }

Now it works in that way, that I can move the camera as described but it is laggy because I presume the .MoveRotation has no smoothening like the .velocity function. That is a bummer but the real problem is that my player turns but when I return to the movment controls, the player will always move forward in the direction of the global x-Axis (and z-Axis). Instead the player should move in the direction where the camera looks.
My other problem is the implementation of gravity. I set up a test scene where I implemented everything but without gyro steering, instead a normal mouse and keybord steering:
public class PlayerMovement : MonoBehaviour

{
public CharacterController controller;
public float speed = 12f;

//Working on Gravity
Vector3 velocity;
public float gravity = -9.81f;

public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
bool isGrounded;

void Update()
{
    isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

    if (isGrounded && velocity.y < 0)
    {
        velocity.y = -2f;
    }

    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    //das erlaubt uns, dass der Spieler nicht immer in richtung des globalen links läuft wenn wir "d" drücken,
    //sondern der Spieler wird abhängig von seiner Blickrichtung nach links und rechts bewegt.
    Vector3 move = transform.right * x + transform.forward * z;
    controller.Move(move * Time.deltaTime * speed);

    //Gravity
    velocity.y += gravity * Time.deltaTime;
    controller.Move(velocity * Time.deltaTime);

}

I was thinking, that a joistick from a Playstation controller also sends an angle or something similar as a raw input and Unity has a configuration where this Input is configured as for example "move left with velocity 0.5".
How can I adequatly implement a steering like that if I got Gyorscopic angles as an Input ?
Any ideas, suggestions, whatever are warmly welcome
Thanks in advance !


text:
Q: How to add onhover tags/ annotations to a network visualized using cytoscape.js I am working with Rstudio and to create network visualizations, I am using Cytoscape.
I am unable to find any help document to understand how to add annotations to nodes, onHover of the mouse.
It has been done on http://js.cytoscape.org/demos/colajs-graph/ for onmouseclick event of nodes. But my requirement is for onHover.
Any help or direction would be really helpful.

A: There is, for example the tippy.js/popper.js extension, as mentioned in the cytoscape.js documentation, that can handle this feature. With the cytoscape event listeners, you can build these things yourself, but here is an example for your use case:

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),
    style: [{
        selector: "node",
        style: {
          content: "data(id)"
        }
      },
      {
        selector: "edge",
        style: {
          "curve-style": "bezier",
          "target-arrow-shape": "triangle"
        }
      }
    ],
    elements: {
      nodes: [{
        data: {
          id: "a"
        }
      }, {
        data: {
          id: "b"
        }
      }],
      edges: [{
        data: {
          id: "ab",
          source: "a",
          target: "b"
        }
      }]
    },
    layout: {
      name: "grid"
    }
  }));

  function makePopper(ele) {
    let ref = ele.popperRef(); // used only for positioning

    ele.tippy = tippy(ref, { // tippy options:
      content: () => {
        let content = document.createElement('div');

        content.innerHTML = ele.id();

        return content;
      },
      trigger: 'manual' // probably want manual mode
    });
  }

  cy.ready(function() {
    cy.elements().forEach(function(ele) {
      makePopper(ele);
    });
  });

  cy.elements().unbind('mouseover');
  cy.elements().bind('mouseover', (event) => event.target.tippy.show());

  cy.elements().unbind('mouseout');
  cy.elements().bind('mouseout', (event) => event.target.tippy.hide());

});
body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px
}

#cy {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
}

h1 {
  opacity: 0.5;
  font-size: 1em;
  font-weight: bold;
}

/* makes sticky faster; disable if you want animated tippies */

.tippy-popper {
  transition: none !important;
}

  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">

  <link rel="stylesheet" href="https://unpkg.com/tippy.js@4.0.1/index.css" />