text:
Q: freeBSD9.0 autoinstall Everybody, Hello! We use Freebsd9.0 for our workstation. Everytime, we start a new machine. We must install freeBSD manually. And what we want just autoinstall it. That is, we insert the installation cd and it start to install. When we go back. it finish install. So is there any tool or script fit our needs?

A: Have you read the bsdinstall(8) man page?
Have you asked google, and looked at the FreeBSD forum threads that it [would tell you to look at]?
Since the answer to your question is present in the documentation (and easily google-able) I'm going to assume you did zero research, and suggest that you go and do that now.
Consider this a gentle public-service flogging. :-)


text:
Q: sort values in column and plot ordered values How do I order the numbers in the second column so that the lowest values come first? Please look at my example data and my code.
> TumorSize
   Tumour.size
1           15
2         12,5
3           10
4            4
5            8
6            9
7           12
8            7
9            5
10           2
11         4,5
12           8
13          12

Tried this, but it does not work for values above 10:
TumorSize$Tumour.size <- with(TumorSize, TumorSize[order(Tumour.size), 1])

ggplot(TumorSize, aes(Tumour.size)) + geom_dotplot() + theme_bw() +
  labs(x="Tumor Size", y="Frequency") +
  theme(axis.text.x = element_text( angle = 90))

A: You have to clean up your values:
dta <- read.table(textConnection("Tumour.size
                            1           15
                            2         12,5
                            3           10
                            4            4
                            5            8
                            6            9
                            7           12
                            8            7
                            9            5
                            10           2
                            11         4,5
                            12           8
                            13          12"),
              header=TRUE)

# to num accounting for ,
dta$Tumour.size <- as.numeric(sub(",",".",dta$Tumour.size))

Then you can conveinetly sort your data, like in the syntax below that uses dplyr:
require(dplyr)
dta_ord <- arrange(dta, Tumour.size)

With respect to the chart, you don't actually have to pass the sorted data frame if you tidy up your values:
require(ggplot2)
ggplot(dta, aes(Tumour.size)) + geom_dotplot() + theme_bw() +
    labs(x="Tumor Size", y="Frequency") +
    theme(axis.text.x = element_text( angle = 90))

would give you the following chart:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does the term "page responsible" make any sense in English? Each page on my organizations web site is assigned a person that takes responsibility for the content of that page.
E.g. in the page footer
Page Responsible: John Doe

The current term used to denote this person is "Page Responsible" which does not sound like something you can say in English.
English however, is not my native tongue. Therefore, I ask you English Language & Usage, does the term "Page Responsible" sound ok to you? Or should something else be used, e.g.

*

*Responsible for page content: John Doe

*Responsibility for page content: John Doe

*Page owner: John Doe

A: I'm a native speaker, and it doesn't sound okay to me.  Although I don't think it's completely incomprehensible, it certainly takes some work to figure out what that string of words means.
To me, page responsible sounds like it's elliptical for "page [that is] responsible [for something]".  But the page isn't responsible for anything; a person is, so that interpretation doesn't make sense.  And since that doesn't work, I'm left guessing at what the relationship between the two words is.
Of your choices, page owner seems to fit best to me.  Failing that, all the choices that come to mind are longer--person responsible for content on this page, for example.  Your other options look fine, too.  But personally, I'd stick with page owner, since it's concise and just as easily understood.

A: I have seen the term "focal" (short for "focal point") used for this purpose in recent years. If that's a bit trendy, "owner" would be a more traditional noun, in the sense that the person "owns" the responsibility for the content.

A: What about

*

*Page Master

*Page Manager

*Page Director

*Page Wrangler

*Page Shepherd

*Page Guru

*Page Chief

*Page Maven

*Page Holder

*Page Warden

*Page Handler

*Page Coach

*Page Leader

*Page Czar

*Page Prince


text:
Q: Sbt: is it possible to import a file outside the project in build.sbt? Context:
I have several applications and each has its own build.sbt.
Those applications depend on an other app with
lazy val sharedApp = RootProject(file("../shared-app"))

The problem is that I have to repeat on every build.sbt the configuration of the shared app and it is cumbersome.
How could I do in order to do that?
Is there a way to import a file that I would place in this shared app? (and so in the parent folder of the build.sbt file)

A: You could use Scala code in the build "project", to do whatever you want and it could be the case if you store parent project config there.
I see it something like this:
Parent.scala
import sbt._

object Dependencies {
  // Versions
  lazy val someVersion = "2.3.8"

  // Libraries
  val someLib = "com.typesafe.akka" %% "akka-actor" % akkaVersion
  val someLib2 = "com.typesafe.akka" %% "akka-cluster" % akkaVersion

}

and later in your build.sbt you could import it and it could reduce your cumbersome code, e.g.
build.sbt
import Parent._

// user keys from Parent.scala to quicker setup your parent project

Make any sense for your use-case?
Some reference materials - here


text:
Q: Bing Speech Recognition API returns 408 "Request timed out (> 14000 ms)" I'm trying to use the Bing Speech Recognition API in a project I am working on.
I've created a small file to test the API:
$ file test5.wav
test5.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 16000 Hz
$ ls -lah test5.wav
-rw-r--r-- 1 bauer 1049089 288K Jun 26 12:38 test5.wav

To rule out any errors in my application, I am using the cURL command from the Get Started with Speech REST API in cURL article:
curl -v -X POST "https://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?language=de-DE" -H "Authorization: $ACCESS_TOKEN" -H 'Content-type: audio/wav; codec="audio/pcm"; samplerate=16000' --data-binary @test5.wav

This is the response I get:
Note: Unnecessary use of -X or --request, POST is already inferred.
* timeout on name lookup is not supported
*   Trying 204.79.197.200...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Connected to speech.platform.bing.com (204.79.197.200) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: C:/Users/bauer/AppData/Local/Programs/Git/mingw64/ssl/certs/ca-bundle.crt
  CApath: none
* TLSv1.2 (OUT), TLS header, Certificate Status (22):
} [5 bytes data]
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
} [512 bytes data]
* TLSv1.2 (IN), TLS handshake, Server hello (2):
{ [81 bytes data]
* TLSv1.2 (IN), TLS handshake, Certificate (11):
{ [4514 bytes data]
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
{ [365 bytes data]
* TLSv1.2 (IN), TLS handshake, Server finished (14):
{ [4 bytes data]
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
} [102 bytes data]
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
} [1 bytes data]
* TLSv1.2 (OUT), TLS handshake, Finished (20):
} [16 bytes data]
* TLSv1.2 (IN), TLS change cipher, Client hello (1):
{ [1 bytes data]
* TLSv1.2 (IN), TLS handshake, Finished (20):
{ [16 bytes data]
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-SHA384
* ALPN, server did not agree to a protocol
* Server certificate:
*        subject: CN=www.bing.com
*        start date: Nov  4 17:10:22 2016 GMT
*        expire date: May  4 17:10:22 2018 GMT
*        subjectAltName: speech.platform.bing.com matched
*        issuer: C=US; ST=Washington; L=Redmond; O=Microsoft Corporation; OU=Microsoft IT; CN=Microsoft IT SSL SHA2
*        SSL certificate verify ok.
} [5 bytes data]
> POST /speech/recognition/interactive/cognitiveservices/v1?language=de-DE HTTP/1.1
> Host: speech.platform.bing.com
> User-Agent: curl/7.47.1
> Accept: */*
> Authorization: ***
> Content-type: audio/wav; codec="audio/pcm"; samplerate=44100
> Content-Length: 294666
> Expect: 100-continue
>
{ [5 bytes data]
< HTTP/1.1 100 Continue
} [5 bytes data]
* We are completely uploaded and fine
100  287k    0     0  100  287k      0  20521  0:00:14  0:00:14 --:--:--     0{ [5 bytes data]
< HTTP/1.1 408 Request timed out (> 14000 ms)
< Transfer-Encoding: chunked
< Content-Type: text/plain
< Server: Microsoft-IIS/10.0
< X-MSEdge-Ref: Ref A: B46AA40C68BF4806B277B7D97D5CC386 Ref B: BER30EDGE0215 Ref C: Mon Jun 26 03:39:09 2017 PST
< Date: Mon, 26 Jun 2017 10:39:08 GMT
<
{ [36 bytes data]
100  287k    0    30  100  287k      2  20454  0:00:14  0:00:14 --:--:--     0Request timed out (> 14000 ms)
* Connection #0 to host speech.platform.bing.com left intact

Why does the API call fail? Is there something wrong with the test file? Did I miss a required parameter?

A: Try forcing the chunked transfer instead, by adding --header "Transfer-Encoding: chunked".  The full command will therefore be:
curl -v -X POST "https://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?language=de-DE" -H "Authorization: $ACCESS_TOKEN"  -H 'Transfer-Encoding: chunked' -H 'Content-type: audio/wav; codec="audio/pcm"; samplerate=16000' --data-binary @test5.wav


text:
Q: How to build paho mqtt c++ on windows I have few json data which I need to upload on azure iot hub. I am writing code in c++ and need mqtt to publish all the data to iot hub. I am referring this github page: https://github.com/eclipse/paho.mqtt.cpp
But instruction on how to build it is a bit confusing and not seems to be working. Can anyone please explain how can I install mqtt in windows and can use it with visual studio c++. Please help. Thanks

A: I struggled the last few days too and I finally got it running.
I succeeded using the CMake GUI and the Developer Console from Visual Studio 2019.
The instructions I (kinda) followed, were these: https://github.com/eclipse/paho.mqtt.cpp. Scroll down to the Windows part, it's actually very straight forward. However, instead of using the terminal for the cmake -BBuild ... commands I used the CMake GUI, where I configured the variables appropriately.
Installing paho.mqtt.c
So, as mentioned on the instructions, you first need to install paho.mqtt.c. For that, just clone the repo somewhere on your machine. Inside the paho.mqtt.c folder create a "build" folder.
Open the CMake GUI, then click on "Browse Source" and set the folder where the repo was cloned ../paho.mqtt.c/.
For "Browse Build" select the build folder you just created ../paho.mqtt.c/build/
The click on "Configure" (I used the default Generator Visual Studio 16 2019). At this instance I didn't touch the configuration variables, so I just went ahead and clicked on "Generate".
CMake GUI for paho.mqtt.c
Then, open a developer console (press the windows key, type "developer" and open the Developer Command Prompt for VS 2019, or whatever version you use) and navigate to the paho.mqtt.c folder. There, according to the instructions on the github page, type the command:
cmake --build build --target install

This will install the paho.mqtt.c in C:\Program Files(x86)\Eclipse Paho C\. Note that this location can be changed by modifying the CMAKE_INSTALL_PREFIX variable on the CMake GUI to a custom location.
Installing paho.mqtt.cpp
The procedure is in nature the same: open the CMake GUI, select the folder that contains the source, then the build folder and then click on "Configure".
Now, since paho.mqtt.cpp relies on libraries from paho.mqtt.c, you must tell cmake where to find the corresponding paho.mqtt.c libraries.
In order to do this, configure the variables PAHO_MQTT_C_INCLUDE_DIRS and PAHO_MQTT_C_LIBRARIES.

*

*PAHO_MQTT_C_INCLUDE_DIRS should point to the "include" folder inside the paho.mqtt.c installation, in my case: C:/Program Files (x86)/Eclipse Paho C/include

*PAHO_MQTT_C_LIBRARIES I set up to point to the paho-mqtt3c.dll, in my case: C:/Program Files (x86)/Eclipse Paho C/bin/paho-mqtt3c.dll
The other options I left untouched.
Finally, go back to the Developer Command Prompt, navigate to the paho.mqtt.cpp folder and run cmake --build build --target install.
If everything goes well, paho.mqtt.cpp will be installed in C:/Program Files (x86)/paho-mqtt-cpp, according to the configuration variable CMAKE_INSTALL_PREFIX.
Now, you can reference both libraries in your c++ projects. Be aware that if you want to use the paho.mqtt.cpp library on your project you'll also have to include paho.mqtt.c.


text:
Q: Why is Crystal automatically adding Guidelines whenever I expand a section? I'm using Crystal 9, and whenever I add a new section to a report, and attempt to expand it, Crystal adds a BUNCH of horizontal guidelines.
It's really irritating. I figure there's got to be some setting I've tripped, but I can't figure out which one.
Any ideas?

A: Found the answer on Tek-Tips. Needed to set "Free Form Placement" in the File-> Options menu
Link to Tek-Tips Discussion

A: Try disabling guidelines in Design mode and see if that helps.  View | Guidelines | Design.
Not sure if it will work in v9, but selecting 'Fit section' will usually remove unnecessary ones.
** edit **
Position a field in the section of irritation at the vertical location that will preserve the section height, then to a 'fit section'.

A: I had the same issue and to solve it I just open File>Option and change the GridSize.  After this each time I added new section no Guidelines was added automatically.


text:
Q: Language switcher implementation in JSF I have a complex jsf page with some widgets developed in PrimeFaces. Up to now, the application is completely ajaxified, meaning that there aren't submits, but all the events and updates are handled through Ajax behavior (this is not a must, but a nice-to-have feature). I have also done a SelectOneMenu for switching the language:
<h:form>
    <p:panelGrid columns="2" >
        <h:outputText value="#{msgs.SelectLanguage}" />
        <p:selectOneMenu value="#{languageSwitcher.selectedLanguage}" >
            <f:selectItems value="#{languageSwitcher.languages}" ></f:selectItems>
        </p:selectOneMenu>
    </p:panelGrid>
</h:form>

The switcher works well.
My problem is how to reload the translated messages when a language is selected.
I have tried these options:
Option 1
With an ajax update inside the selectOneMenu:
<p:ajax update="myFormsTobeUpdated" ></p:ajax>

This works great, and is the preferred solution because it's Ajax, but
EDITED
this solution doesn't ajax-update the Tab titles in the PrimeFaces TabView, and this is problem is blocking because the Tab titles need to be translated.
Option 2
With a complete reload of the page in Javascript. I have tried this but doesn't work (can't tell why):
<p:selectOneMenu value="#{languageSwitcher.selectedLanguage}" onchange="window.location.reload()" >

Option 3
With a complete reload of the page in Java like explained here: https://stackoverflow.com/a/1821708/870122 (to be honest I haven't tried it yet, but will do soon!)
Any suggestions are welcome.

A: If you're using at least PrimeFaces 3.2, then you can use
<p:ajax update="@all" />

to update the entire view. Before this version, the @all wasn't supported.

A: In your Form:
<h:selectOneRadio   value="#{localeBean.language}"
                        onchange="submit()">
                        <f:selectItems value="#{collection.listLangs()}" var="s"
                            itemLabel="${s.description}" itemValue="${s.code}" />
                    </h:selectOneRadio>

but your not have a collection (REMEMBER, IN YOUR FORM):
<h:selectOneMenu value="#{localeBean.language}"
                                        onchange="submit()">
                                        <f:selectItem itemValue="en" itemLabel="English" />
                                        <f:selectItem itemValue="es" itemLabel="Español" />
                                    </h:selectOneMenu>

IN Primefaces, use this: p:selectOneMenu

In your Bean:
import java.lang.invoke.MethodHandles;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@ManagedBean
@SessionScoped
public class LocaleBean {

    private static final Logger LOG = LogManager.getLogger(MethodHandles.lookup().lookupClass());

    private Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();

    public Locale getLocale() {
        return locale;
    }

    public String getLanguage() {
        return locale.getLanguage();
    }

    public void setLanguage(String language) {
        LOG.info("Vamos a Cambiar a: " + language);
        locale = new Locale(language);
        LOG.info("Vamos a Cambiar a: " + locale.getDisplayName() + FacesContext.getCurrentInstance().getViewRoot());
        FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
    }

}

A: Since with Option 1 it's not possible to ajax-update the Tab titles in the PrimeFaces TabView, I have switched to Option 2, a complete reload of the page using JavaScript.
The code that makes it work is:
<h:form id="selectLanguage">
    <p:panelGrid columns="2">
        <h:outputText value="#{msgs.SelectLanguage}" />
        <p:selectOneMenu value="#{languageSwitcher.selectedLanguage}" onchange="document.getElementById('selectLanguage').submit();" >
            <f:selectItems value="#{languageSwitcher.languages}" ></f:selectItems>
        </p:selectOneMenu>
    </p:panelGrid>
</h:form>


text:
Q: Fit image to width using fixed positioned button I have a page with the following functionality: there is a large image that generates scoll (both horizontally and vertically) and a button in a fixed position (it remains in the top left corner, even with scroll) that, when clicked, fits the image to the client width.
Since position: fixed is not supported in Internet Explorer 8, I used a workaround - this is the function:
function setFixedPosition(jqueryWrapper, pixelsFromTop, pixelsFromLeft) {

    jqueryWrapper.css('position', 'absolute');

    var setOffsets = function() {
        jqueryWrapper.css("top", (($(window).scrollTop() + pixelsFromTop) + "px"));
        jqueryWrapper.css("left", (($(window).scrollLeft() + pixelsFromLeft) + "px"));
    };

    setOffsets();

    $(window).scroll(function() {
        setOffsets();
    });
}

setFixedPosition($('#zoomFitButton'), 15, 15);

This is the button's action:
$('#zoomFitButton').click(function() {
    $('img.preview').css('width', '100%');
});

The button remains fixed both in Firefox 13 and IE8.
But, under IE8, if I am scrolling somewhere, then I click the button, the button moves to a "strange" position:

*

*If I scroll vertically, then click, it puts the button in the lower-left corner;

*If I scroll horizontally, then click, it puts the button in the upper-right corner;

*If I scroll both ways, then click, it puts the button somewhere in the center.

In Firefox, the button always remains in the upper-left corner (the place where I expect it to be), even after I click the fit to width button.
Here is a test page.
Is my code OK for this functionality (in principle), or I need to add something to the fit to width action (to fix my button positioning); or there is something wrong with IE (and I need a workaround - if so, any suggestions?)?
Thanks.

A: I found a solution that works in IE6 also.
I think the problem has something to do with IE not updating the scrollTop and scrollLeft positions after the document is resized.

So, after I resize the picture, I have to scroll to the upper-left corner (scrollTop(0) and scrollLeft(0)).

Unfortunately, if I have a large picture that needs vertical scrolling even when it's fit to width, the workaround brings me to the top of the page. So I added code to bring me back proportionally to the aproximate position I was before. I wrapped the logic in a more generic function:
function doSomethingThatAffectsScrollPosition(affectingScrollPositionFunction) {

    var oldDocumentWidth = $(document).width();
    var oldScrollFromLeft = $(window).scrollLeft();

    var oldDocumentHeight = $(document).height();
    var oldScrollFromTop = $(window).scrollTop();

    affectingScrollPositionFunction();

    var newDocumentWidth = $(document).width();
    var widthRatio = (newDocumentWidth / oldDocumentWidth);
    var newScrollFromLeft = (oldScrollFromLeft * widthRatio);

    var newDocumentHeight = $(document).height();
    var heightRatio = (newDocumentHeight / oldDocumentHeight);
    var newScrollFromTop = (oldScrollFromTop * heightRatio);

    $(window).scrollLeft(0); // Needed for button repositioning
    $(window).scrollLeft(newScrollFromLeft);

    $(window).scrollTop(0); // Needed for button repositioning
    $(window).scrollTop(newScrollFromTop);
}

And I used the function in the fit to width button's action:
$('#zoomFitButton').click(function() {
    doSomethingThatAffectsScrollPosition(function() {
        $('img.preview').css('width', '100%');
    });
});

Here is a test page.


text:
Q: What is the best way to embed Firebird Installation in the Installer for my app? My app has its own installer but I have to guide my users to install Firebird on their own.
I'd like to install it automatically.
Thanks.

A: You can download Firebird source code. It contains InnoSetup script that actually installs firebird on windows targets. You can then modify it to suit your needs.
As a side advice, maybe you should consider Inno Setup yourself.

A: InterBase and hence Firebird provide an API you can use in your installer script to automate installation.
See documentation for this API in the document "InterBase 5.5 Embedded Installation Guide" http://dn.codegear.com/article/26386
The InterBase Express (IBX) components provide a Delphi binding for the installation API.  This is documented in the InterBase 6.0 "Developer's Guide".

@mghie and @TOndrej have made comments about my mistake.  I was the Product Manager for InterBase once upon a time, when InterBase did provide an installation API.  But this answer is outdated, by literally ten years now.
Here's another resource which is more up to date:

*

*Unofficial Firebird Installation page
This has step-by-step instructions for creating your own Inno Setup installer for Firebird, to accompany your own application installer.  No doubt you could use a different installer technology for your application, and simply call the Inno Setup installer as an external program from your installer.  But it would probably be more seamless if you also use the Inno Setup for your own product.

A: If you don't need standalone Firebird server, you could also just include required files in your setup and use Firebird as a embedded SQL server.
See http://www.firebirdsql.org/manual/ufb-cs-embedded.html

A: Create a bootstrapper, for your product and the prerequisites that your product needs.

A: Other products might be a good model to follow.  For example, Pidgin relies on a specific version of GTK and guides you through running the GTK installer.  Being open source, one option would be to look through the source for their NSIS installer package to see how they're doing it.


text:
Q: How to align left last row/line in multiple line flexbox I have a major issue with flexbox layout. I build a container with a boxes filled with images, and i decided to use flexbox layout to justify the content to make it looks like a grid
Her's the code:

    ...

and the CSS:
.container {
    display: flex;
    display: -webkit-flex;
    display: -moz-flex;
    justify-content: space-around;
    -webkit-justify-content: space-around;
    -moz-justify-content: space-around;
    flex-flow: row wrap;
    -webkit-flex-flow: row wrap;
    -moz-flex-flow: row wrap;
}

.container .item { width: 130px; height: 180px; background: red; margin: 0 1% 24px; }

And everything looks good except the last line/row - when it not contain the same number of element that other lines, centering elements and it broke my grid effect.
http://jsfiddle.net/puz219/7Hq2E/
How to align last line/row to left side?

A: I thought this example might be useful for anyone who wanted multiple items and allow for responsiveness, the grid items change depending on the viewport size. It does not use any invisible children, it's all done through css.
Might help someone trying align items to the left when the last row has less items and they require the page to be responsive.
http://codepen.io/kunji/pen/yNPVVb
Sample HTML

Item Name

Item Name

Item Name

Item Name

Item Name

Item Name

Sample CSS
.main-container {
  max-width: 1000px;
  min-width: 300px;
  margin: 0 auto;
  padding: 40px;
  box-sizing: border-box;
  border: 1px solid #000;
}

.main-items-container {
  display: -ms-flexbox;
  display: flexbox;
  display: -webkit-flex;
  display: -ms-flex;
  display: flex;
  padding: 0;
  margin: 10px 0;
  list-style: none;
  width: auto;
  -webkit-flex-flow: row wrap;
  justify-content: flex-start;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-align-items: stretch;
  align-items: stretch;
  box-sizing: border-box;
}

@media (min-width: 971px) {
  .item-container {
    margin: 10px 2%;
    width: 22%;
    padding: 10px;
    border: 1px solid #000;
    box-sizing: border-box;
  }
  .item-container:nth-child(4n+1) {
    margin-left: 0;
  }
  .item-container:nth-child(4n) {
    margin-right: 0;
  }
}

@media (min-width: 550px) and (max-width: 970px) {
  .item-container {
    margin: 10px 2.50%;
    width: 30%;
    padding: 10px;
    border: 1px solid #000;
    box-sizing: border-box;
  }
  .item-container:nth-child(3n+1) {
    margin-left: 0;
  }
  .item-container:nth-child(3n) {
    margin-right: 0;
  }
}

@media (max-width: 549px) {
  .item-container {
    margin: 10px 0;
    width: initial;
    padding: 10px;
    border: 1px solid #000;
    box-sizing: border-box;
  }
}

A: Unfortunately this is not possible with flexbox.
The best work-around is to add invisible children 'filling up' the empty 'blocks' in the last row. That way, the actual, visible, element is aligned left.
Similar question:
Flex-box: Align last row to grid

A: You can use margin-right:auto on the last-child flex item.
The problem here is that you will lose the space-between property on the left for this flex item.
Hope it helps!

A: This is not an effect you wanted to achieve?
http://jsfiddle.net/7Hq2E/21/
CSS:
.container {
    display: flex;
    display: -webkit-flex;
    display: -moz-flex;
    flex-flow: row wrap;
    -webkit-flex-flow: row wrap;
    -moz-flex-flow: row wrap;
}
.container .item {
    width: 23%;
    height: 180px;
    background: red;
    margin: 0 1% 20px;
}

HTML:

A: Got it. (I think)(this is my first contribution here!)
Imagine a layout which needs to have 4 images per row. w:205 h:174
Problem: Using justify-content:space-around, if the last row doesn´t have 4 images (has 3, 2 or 1), they would not respect the grid, they would spread.
So.
Create in the html 3 divs with the class "filling-empty-space-childs" like this.
.filling-empty-space-childs {
    width:205px; /*the width of the images in this example*/
    height:0; /*Important! for the divs to collapse should they fall in a new row*/
}

The flexbox container has display:flex / flex-wrap:wrap; / justify-content:space-around
The last row can have 4, 3, 2, 1 images.
4 images: no problem, this three divs would collapse in a new row since they have no height.
3 images: no problem, one div is going to be in the same row, invisible, and the other two would wrap to a new row, but will collapse since they have no height.
2 images: no problem, two divs are going to be in the same row, invisibles, the rest... collapsed
1 image: no problem, the three divs are going to fill in the space.

A: I've checked it and it worked better in my HTML editor tool
the script should be the way
CSS Part

.container {
      display: flex;
      display: -webkit-flex;
      display: -moz-flex;
      justify-content: space-around;
      -webkit-justify-content: space-around;
      -moz-justify-content: space-around;
      flex-flow: row wrap;
      -webkit-flex-flow: row wrap;
      -moz-flex-flow: row wrap; }
.container .item { width: 130px; height: 180px; background: green;
  margin: 0 1% 24px; }

HTML Part

Google

Yahoo

Bing

Google

Yahoo

Bing


text:
Q: React using state array without mutation Can the below code be refactored so as to not mutate the state array. Basically, I want that as I navigate the app back and forth via props.history.push, it should not recreate the array, as I my aim is to preserve the selected option.
const [options1, setOptions1] = useState([
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2}
]);
const [options2, setOptions2] = useState([
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2},
    {value: 'XYZ', text: 'XYZ', id: 3}
]);

let finalOpts = options1; // Is there a better way to do this ?
if (someConditionIsTrue) {
    finalOpts = options2;
}

const [selectedOpt, setSelectedOpt] = useState(finalOpts[0]);

<MyList
    id="myDD"
    selectedOpt={selectedOpt}
    options={finalOpts}
/>

A: Use useMemo to precalculate the values if your UI logic depends on some conditional.
This alone will not preserve the selectedState if the component is unmounted.
In order to preserve the selected state even after the component has been unmounted, you will have to store the selection in some kind of global state.

const options = useMemo(() => {
  if(someConditionIsTrue) {
    return [
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2}
    ];
  }
  return [
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2},
    {value: 'XYZ', text: 'XYZ', id: 3}
]
}, [someConditionIsTrue]);

const [selectedItem, setSelectedItem] = useState();

return (<MyList
    id="myDD"
    selectedOpt={selectedItem || options[0]}
        onSelectionChanged={setSelectedItem}
    options={options}
/>)


text:
Q: Как впихнуть actionbarsherlock в свой проект?
If you're using the Eclipse
  Development Environment with the ADT
  plugin version 0.9.7 or greater you
  can include ActionBarSherlock as a
  library project. Create a new Android
  project in Eclipse using the library/
  folder as the existing source. Then,
  in your project properties, add the
  created project under the 'Libraries'
  section of the 'Android' category.

Проект из шерлока создал, но как его впихнуть в мой проект as a library?

A: На so есть подробная инструкция, как это сделать в эклипсе. Не для Шерлока конечно, а более общая инструкция.
Но зачем создавать проект из под шерлока - не знаю.

A: В свойствах проекта вкладка "Android" -> "Add library project".


text:
Q: Multicast discovery Of Hazelcast Can someone tell how Multicast Discovery of HazelCast actually works. I want details on each member discovers its peers.
I have been trying to find some good resource but haven't found any detailed explanation for it.

A: From the Mastering Hazelcast online book (https://hazelcast.org/mastering-hazelcast/#join-mechanism):

With multicast discovery, a member will send a message to all members that listen to a specific multicast group.

(i.e. when trying to join). This boils down to binding to a multicast group address and port and listening for incoming connections. The address+port pair must be known to all nodes. So instead of each node knowing in advance the actual address of all other nodes, they all need to know the multicast group address and port.
Also described here: http://docs.hazelcast.org/docs/3.10.4/manual/html-single/index.html#discovering-members-by-multicast
While a node is connected, it will periodically send heartbeats to other nodes. If heartbeats are missed for a certain period of time, then the node is assumed disconnected (http://docs.hazelcast.org/docs/3.10.4/manual/html-single/index.html#failure-detector-configuration)


text:
Q: What is the definitive way to use Gmail with OAuth and Nodemailer? Desired Behaviour
Use Gmail, OAuth2 and Nodemailer to send an email from a server side node.js file.
What I've Tried
Relevant Documentation
https://nodemailer.com/smtp/oauth2
https://nodemailer.com/usage/using-gmail
https://developers.google.com/gmail/api/auth/web-server
Relevant Questions
send emails from MY gmail account with OAuth2 and nodemailer
How do I authorise an app (web or installed) without user intervention?
https://stackoverflow.com/a/47936349
https://stackoverflow.com/a/22572776
There were gaps in the instructions of the above sources and some information was outdated, so the answer below was my final implementation which appears to be working.
I'm posting this solution for confirmation it is best practice and, if it is, to save others time.

A: The following worked for me, there are two parts:
01) app.js
02) Google and OAuth2 setup

app.js
var nodemailer = require("nodemailer");

var transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
        type: 'OAuth2',
        user: local_settings.my_gmail_username,
        clientId: local_settings.my_oauth_client_id,
        clientSecret: local_settings.my_oauth_client_secret,
        refreshToken: local_settings.my_oauth_refresh_token,
        accessToken: local_settings.my_oauth_access_token
    }
});

var mail = {
    from: "John Smith <me@mydomain.com>",
    to: "user@userdomain.com",
    subject: "Registration successful",
    text: "You successfully registered an account at www.mydomain.com",
    html: "
You successfully registered an account at www.mydomain.com
"
}

transporter.sendMail(mail, function(err, info) {
    if (err) {
        console.log(err);
    } else {
        // see https://nodemailer.com/usage
        console.log("info.messageId: " + info.messageId);
        console.log("info.envelope: " + info.envelope);
        console.log("info.accepted: " + info.accepted);
        console.log("info.rejected: " + info.rejected);
        console.log("info.pending: " + info.pending);
        console.log("info.response: " + info.response);
    }
    transporter.close();
});

Google and OAuth Setup
The code above requires the following setup:
01)  Go to https://console.developers.google.com
02)  If you don't have a project, you will be prompted to create one

03)  Click on Create Project
04)  Click on Create

05)  Enter a Project Name and click Create

06)  Select the Gmail API

07)  Click on Enable

08)  Click on Create Credentials

09)  Enter the required settings

10)  Give the OAuth client a name and ensure you add https://developers.google.com/oauthplayground as a redirect URI in order to generate the refresh and access tokens later

11)  Define the consent screen settings

12)  Click I'll do this later and Done

13)  Click on the Edit icon, to view your Client ID and Client Secret

14)  To generate access and refresh tokens, go to https://developers.google.com/oauthplayground
15)  Click on the cog icon in the top right, check Use your own OAuth credentials and enter Client ID and Client Secret

16)  In the left column, select Gmail API v1 and click Authorise APIs

17)  If you are signed into multiple accounts, when prompted select the relevant account

18)  Click Allow

19)  Click Exchange authorisation code for tokens

I'm not sure why there is a count down on the access token, but hopefully the message at the bottom of the screen means that the token won't expire.

A: OAuth Consent Screen
You are definetely right about the gaps and outdated information, and you did a really great job on documenting the steps needed to use Gmail with OAuth and nodemailer!
Nevertheless, I think it worths mentioning that in the Credentials page there is another step: the OAuth Consent Screen tab.
It contains a form like a Google Play app submission that requires validation from Google, if you choose your app to not being validated, you have a limitation of 100 calls of what they call Sensitive scopes before being asked for submission.
What about quota?
It's still not clear to me if this 100 calls quota will be consumed even if you don't select any additional permission to use sensitive scopes (the default ones are email, profile, openid). I hope not, since the OAuth Consent Screen asks for things like the Application Homepage Link and Authorised domains that is something you might not have if you are working on a backend application.
I think that this whole procedure is really slow and uselessly complex since most people do all these steps to just send an email from their app using nodemailer...


text:
Q: Sails.js: Inserting one-to-many associated models to MongoDB I am trying to take advantage of the Waterline ORM in Sails.js to build an example app that has a model called 'Category'. Because a category can have multiple sub categories, I have the following one-to-many association for this model:
module.exports = {

  adapter: 'mongo',
//  adapter: 'someMysqlServer',

  attributes: {
    categoryTitle: {
      type: 'string',
      required: true
    },

    parentCat: {
      model: 'category'
    },

    subCategories: {
      collection: 'category',
      via: 'parentCat'
    },

    articles: {
      collection: 'article',
      via: 'category',
      required: false
    }

  }
};

In the CategoryController.js, I have the create method that first tries to see if the new category has a parent category assigned to it; however, I feel the code is quite messy, and the parentCat in Mongodb is always empty even if I tried to assign a parent category in the form submission. So I am wondering if this is the right way to do it:
 create: function(req, res, next) {
        var params = req.allParams();

        // set parent category if exists
        if (params.parentCat) {

            Category.findOne({categoryTitle : params.parentCat})
                .exec(function(err, category) {
                if (err) {
                    return false; //not found
                } else {
                    params.parentCat = category.id;  //found the parent category
                    console.log('parent cat id is: ', category.id);
                }
            });
      }

        Category.create(params, function(err, newCategory) {
            if (err) {
                return next(err);
            } else {
                console.log('new category created');
            }
            console.log('successfully added the category: ' + newCategory.categoryTitle)
            res.redirect('/category');
        }); // create the category
    }

A: The issue of your code is the callback.
I created a new version of code with the async feature (which is already in your sails app), hope it will help you.
create: function(req, res, next) {
    var params = req.allParams();

    async.waterfall([
        function(callback) {
            // set parent category if exists
            if (params.parentCat) {
                Category.findOne({
                        categoryTitle: params.parentCat
                    })
                    .exec(function(err, category) {
                        if (err) {
                            return false; //not found
                        }
                        params.parentCat = category.id; //found the parent category
                        console.log('parent cat id is: ', category.id);
                        callback(null, params);
                    });
            } else {
                callback(null, params);
            }
        },
        function(params, callback) {
            Category.create(params, function(err, newCategory) {
                if (err) {
                    return next(err);
                }
                console.log('successfully added the category: ' + newCategory.categoryTitle);
                callback(null, newCategory);
            }); // create the category
        }
    ], function(err, result) {
        console.dir(result);
        res.redirect('/category');
    });
}


text:
Q: Reading a CSV file using CsvHelper I'm a newbie. I want to get data from the CSV file-the Id and Name fields, but when I run the reading method, I get only 100 lines of an incomprehensible type: "CsvHelper.CsvReaderd__87`1[Program+Product]". I do not know how to get data from CSV, I also cannot understand where the error is.
Although the documentation says that having the same names of properties and CSV headers, you do not need to write additional configurations. However, I get the result specified above. The CSV names match the classes. Link to the documentation:https://joshclose.github.io/CsvHelper/getting-started/
reading method:
  {
        using (var reader = new StreamReader("C:\\Users\\Saint\\Desktop\\TaskRetail\\file.csv", Encoding.UTF8))
        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            var records = csv.GetRecords<Product>();
            Console.WriteLine($"{records}");
        }
    }

CSV is created without problems, there are two columns with Id and Name with filled rows, there are 100 rows in total:

method for creating a csv with the Id and Name fields:
   using (var writer = new StreamWriter("C:\\Users\\Saint\\Desktop\\TaskRetail\\file.csv", false, Encoding.UTF8))
    using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
    {
        csv.WriteRecords(products);
    }

the entire code:
using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;

public class Program
{

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public Product(int id, string name)
        {
            Id = id;
            Name = name;
        }
    }
    public const string PathToDoc = "C:/Users/Saint/Desktop/TaskRetail/yml.xml";

    public static void Main(string[] args)
    {
        string url = "https://www.googleapis.com/drive/v3/files/1sSR9kWifwjIP5qFWcyxGCxN0-MoEd_oo?alt=media&key=AIzaSyBsW_sj1GCItGBK0vl8hr9zu1I1vTI1Meo";
        string savePath = @"C:\Users\Saint\Desktop\TaskRetail\yml.xml";
        WebClient client = new WebClient();
        client.DownloadFile(url, savePath);

        Research();
    }

    public static void Research()
    {
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

        var document = new XmlDocument();
        document.Load(PathToDoc);
        var xmlDoc = document.SelectNodes("/yml_catalog/shop/offers/offer");
        var count = xmlDoc.Count;
        var products = new List<Product>();
        Console.WriteLine($"Offers count: {count}");
        for (var i = 0; i < count; i++)
        {
            var element = xmlDoc.Item(i);
            var id = int.Parse(element.Attributes.GetNamedItem("id").Value);
            var name = element.SelectSingleNode("name").InnerText;
            var product = new Product(id, name);
            //Console.WriteLine($"Id: {id}, name: {name}");

            products.Add(product);

            using (var writer = new StreamWriter("C:\\Users\\Saint\\Desktop\\TaskRetail\\file.csv", false, Encoding.UTF8))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                csv.WriteRecords(products);
            }

         var config = new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter = ",", PrepareHeaderForMatch = header => header.Header.ToLower() };
        using (var reader = new StreamReader("C:\\Users\\Saint\\Desktop\\TaskRetail\\file.csv", Encoding.UTF8))
        using (var csv = new CsvReader(reader, config))

        {
            var records = csv.GetRecords<Product>();

            foreach (var record in records)
            {
                Console.WriteLine($"{record.Id} {record.Name}");
            }
        }
    }
}

}

A: Because GetRecords() does return an object of type IEnumerable,
you have to iterate over your records to print each one of them:
foreach(var record in records)
{
   Console.WriteLine($"{record.Id} {record.Name}");
}

Furthermore you have to access each property you want to print individually.
Another option would be to override the ToString() method in your Product class.
EDIT
The initial problem wasn't the correct printing of the values but the parsing of the file as I learned from this comment:

CsvHelper.HeaderValidationException: 'Header with name 'id'[0] was not found. Header with name 'name'[0] was not found.

To tackle this problem one have to make sure that the delimiter character is set correctly. This can be enforced in the config object of the CsvHelper. Furthermore to avoid casing errors the configuration can be set to ignore the casing of the headers:
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
   Delimiter = ",", // Enforce ',' as delimiter
   PrepareHeaderForMatch = header => header.Header.ToLower() // Ignore casing
};

using (var csv = new CsvReader(reader, config))
{
   ...
}


text:
Q: Data Validation and Reconciliation in SSIS I have to migrate data from one Non-SQL Server-database to SQL-Server database using ssis.
Data contains millions of rows.
However I want to make sure that data in the source and data in the destination remains same.
One of the answer that i followed is suggesting to use Staging Tables.
In addition to above technique What could be the best technique for doing this.
Any Thought/Suggestion would be appreciated.
Thanks

A: The staging area in the world of Data warehouse is the place where you just copy the data from the source for multiple reasons :

*

*To only execute bulk copy from production server and then avoid to use too much ressources from production servers.

*To keep the data unmodified during your calculation

*To apply filter and other aggregation to prepare your queries that fill the DWH.

In your case, the staging area is a good idea to make the first step from non-sql to relationnal Database.
Moreover the staging is just a copy then you won't alter the integrity of the data during this step.
Because of this you can run some "integrity tests" after your migration by running count on the staging table and you final structure or by summing data and compare the global result to identify differences.


text:
Q: Displaying last 3 blog posts on wordpress custom theme I have a custom theme I am working on in wordpress, and I want to display the last 3 blog posts made onto my home page. I also want to style certain information regarding each post differently, like have the month and year be a certain font, and the day be much bolder and different font as well, along with displaying like a sentence or less of the article, followed by a "..." and "read more" type of thing.
How do I pull data from the blog? I know there are certain wordpress functions that can get me this data but I haven't been able to quite figure out how to do it, I'm not really well versed in the wordpress php functions. Right now I just have it hard coded but it's annoying to have to retype everything when I make a new post. I know you can set to show however many blog posts on the settings->reading but I want to be able to fully customize how it looks.
Let me know any suggestions on how I should go about doing this!

Blog

April 25
2014

blog title 1

lksj sldkf jsl lsdkfj sdklf sd

                Read More >

April 24
2014

blog title 2

lsdkjf lsdk fjsl dkkddk lsdkfjpaskldfj;

                Read More >

April 23
2014

blog title 3

lksdjf slkdfjsldkfj;as dfklsd;j fsld;kfj

                Read More >

A: Try the snippet below. Use your custom HTML block (the one with botom_box class) instead of this used below.
<?php $posts = get_posts("numberposts=3"); ?>
<?php if($posts) : ?>
    <?php foreach( $posts as $post ) : setup_postdata( $post ); ?>

<a href="<?php echo get_permalink($post->ID); ?>" ><?php echo $post->post_title; ?>

        <?php the_excerpt(); ?>" rel="bookmark">read more

    <?php endforeach; ?>
<?php endif; ?>


text:
Q: Does any uniform function exists instead of htons htonl I am trying new the C++ socket programming. I am having some difficulty for understanding functionality of htons, htonl and related functions. I read some documents but still my questions are as follows,
for a single server and and single client I am using htons both side for the port number and the code is working fine. Even if I don't use these functions and both my server-clients are Intel based 64 bit machines, the codes are working fine. But what if multiple clients try to connect my server and the clients use different data storage format. For example, x86 is little-endian and ARM A-53 is both little- and big-endian and others, where some of them are 32 bits, 16 bits or 64 bits etc. My server is 64 bits. So I'm now confused which functions I have to use that uniformly serves all purpose ? Or, I have to always detect the client type and convert it's data format (port number) to 64 bit (as my server is 64 bit) and then use htonl() function to reach the server. It would be great someone please reply or points me out if I am on the wrong path ...

A: These functions convert from and to network byte order (that is in fact big endian). No matter on whether the architecture you're programming they will perform that task (if you're on a big endian architecture it will just be a no-op).
Using these consequently will make the code portable. Note though that you should not use htonl at both conversions. When you send data to another host you use htonl (host to network byte order) before you send the data and then ntohl (network to host byte order) when you receive.
Note that ntohl and htonl are not guaranteed (although I can't give an example) to be the same and you should therefore use the correct one.

A: It's good that you're asking the question. It shows that you're worrying about the right things.
Documentation here:
http://linux.die.net/man/3/htonl
note that the arguments and return types have specific sizes no matter which system you're on.


text:
Q: Delphi 2010 - Thread error: The handle is invalid (6) I've created a thread that checks if a port is opened or closed. After running 753 times i get "Thread error: The handle is invalid (6)". What am I doing wrong? I've tested it against 50 ports and haven't had a problem. Now I try to check 65536 ports on my local ip an I get this error after the 731 port.
Thank you!
Here is the thread code:
   {==============================START THREAD VERIFICARE PORT PRIN EXTRAGERE NUME HOST,IP,PORT============================================}

function elimina_toate_spatiile_goale(const s: string): string;
var
  i, j: Integer;
begin
  SetLength(Result, Length(s));
  j := 0;
  for i := 1 to Length(s) do begin
    if not TCharacter.IsWhiteSpace(s[i]) then begin
      inc(j);
      Result[j] := s[i];
    end;
  end;
  SetLength(Result, j);
end;

function Parse2(str: String; delimiter: Char; param_num: Integer): String;
var
  c, x, y : LongInt;
begin
  x := 1;   // param number that we're currently 'in'
  y := 0;   // position of previous delimiter
  for c := 1 to Length(str) do
    if str[c] = delimiter then  // this char is a delimiter
    begin
      if x = param_num then
        Break;
      inc(x);
      y := c;
    end;
  if x = param_num then
    Result := Copy(str, y + 1, c - y - 1)
  else
    Result := '';
end;

    type
      TThread_extrage_hostname_ip_si_port = class(TThread)
      private
        fStringul_ce_trebuie_parsat: string;
        fHostname,fIP_de_verificat,fPort_de_verificat,fIP_si_port:string;
        REZULTAT_verificare_port:BOOLEAN;
        flistbox_porturi_online,flistbox_porturi_offline:Tlistbox;
        fmemo_loguri:Tmemo;
       procedure semnalizare_port_online_sau_offline;

      protected
        procedure Execute; override;
      public

        constructor Create(aStringul_ce_trebuie_parsat: string;alistbox_porturi_online,alistbox_porturi_offline:Tlistbox;amemo_loguri:Tmemo);
      end;

    constructor TThread_extrage_hostname_ip_si_port.Create(aStringul_ce_trebuie_parsat: string;alistbox_porturi_online,alistbox_porturi_offline:Tlistbox;amemo_loguri:Tmemo);
    begin
    inherited Create(False);
      freeonterminate:=true;
      fStringul_ce_trebuie_parsat:=aStringul_ce_trebuie_parsat;
      flistbox_porturi_online:= alistbox_porturi_online;
      flistbox_porturi_offline:= alistbox_porturi_offline;
      fmemo_loguri:= amemo_loguri;
    end;

    procedure TThread_extrage_hostname_ip_si_port.Execute;
    var
      IdTCPClient : TIdTCPClient;
    begin

      // use fURL, fMethod, and fParam as needed...
    REZULTAT_verificare_port := False;

    fhostname:=(Parse2(fStringul_ce_trebuie_parsat,'=', 1));

    fIP_si_port:=elimina_toate_spatiile_goale(Parse2(fStringul_ce_trebuie_parsat,'=', 2));

    fIP_de_verificat:=elimina_toate_spatiile_goale(Parse2(fIP_si_port,':', 1));

    fPort_de_verificat:=elimina_toate_spatiile_goale(Parse2(fStringul_ce_trebuie_parsat,':', 2)) ;

    if (fIP_de_verificat<>'') and (fport_de_verificat<>'') then begin

      try
        IdTCPClient := TIdTCPClient.Create(nil);
        try
          IdTCPClient.Host := fIP_de_verificat;
          IdTCPClient.Port := strtoint(fPORT_de_verificat);
          IdTCPClient.ConnectTimeout:=5000;
          IdTCPClient.Connect;
          REZULTAT_verificare_port := True;
        finally
          IdTCPClient.Free;

        end;
      except
        //Ignore exceptions
      end;
     Synchronize(semnalizare_port_online_sau_offline);
    end;
    end;

    procedure TThread_extrage_hostname_ip_si_port.semnalizare_port_online_sau_offline;
    begin
    if REZULTAT_verificare_port=true then
    begin
    {verific daca in listbox-ul pentru porturi online exista deja elementul testat.
    Daca elementul nu exista, il adaug.
    Daca exista deja, nu il mai adaug.
    }
    if fListBox_porturi_online.Items.IndexOf(fStringul_ce_trebuie_parsat) = -1 then
    begin
    fmemo_loguri.lines.add(datetimetostr(now)+' - '+fStringul_ce_trebuie_parsat +' => ACTIV');
    fListBox_porturi_online.Items.Add(fStringul_ce_trebuie_parsat);
    end;
    Form2.GroupBox_porturi_online.Caption:='PORTURI ONLINE: '+inttostr(fListBox_porturi_online.Items.Count);
    end
    else
    begin
    {verific daca in listbox-ul pentru porturi online exista deja elementul testat.
    Daca elementul nu exista, il adaug.
    Daca exista deja, nu il mai adaug.
    }
    if fListBox_porturi_offline.Items.IndexOf(fStringul_ce_trebuie_parsat) = -1 then
    begin
    fmemo_loguri.lines.add(datetimetostr(now)+' - '+fStringul_ce_trebuie_parsat +' => OPRIT');
    fListBox_porturi_offline.Items.Add(fStringul_ce_trebuie_parsat);
    end;
    end;
    Form2.GroupBox_porturi_offline.Caption:='PORTURI OFFLINE: '+inttostr(fListBox_porturi_offline.Items.Count);
    end;

            {==============================STOP THREAD EXTRAGERE NUME HOST,IP,PORT============================================}

A: A wild guess.
      // ........ CODE ABOVE REMOVED
      IdTCPClient.Connect;
      REZULTAT_verificare_port := True;
    finally
      if IdTCPClient.connected then  // ADD SOMETHING LIKE THIS SECTION ?
      begin
       IdTCPClient.IOHandler.InputBuffer.clear;
       IdTCPClient.Disconnect;
      end;
      IdTCPClient.Free;
      // ........ CODE BELOW REMOVED

If this fixes it then the problem is that a single process can only have around 731 open sockets at once using the APIs you are using.
Alternatively maybe the system you are connecting to also has limits on the total number of open sockets (it can receive) simultaneously?
Either way you are hit a system limit somewhere.
...
UPDATE due to your comment.
Threads have resource limits too.  You can not create unlimited threads (like you can not create unlimited TCP sockets).  Can you use a thread-safe counter and ensure you stop creating threads when you hit 100 threads, until one of the previous thread exit.

*

*So the counter starts at 0.

*Counter is checked to be less than 100, to allow creation of a thread.

*If 100 or more, then it waits to be woken up (this is done by exiting threads)

*Counter increments by 1 when a thread is created.

*Ideally the check less than 100 and increment by one are done atomically.

*As each thread exits the counter is decremented by 1.  This must be done reliably, as in there maybe many ways (normal termination, exceptions thrown, etc..) for a thread to exit, you need to catch them all.  When the counter is decremented you always wake up any waiters.

Now you can create this yourself with a basic sleep()/wait()/synchronize() like in Java.  You have a method that only returns when it increments (it will wait as needed, until it can increment) and another method that always decrements.
Now you may find your main thread can not sleep for other reasons, some systems need to call API to reap the dead/exited threads, before the threads resources are really freed up.  In this case you decrement by one when the resource is available, not at the point of the thread execution ended.
Even 100 threads running your code will run very fast, you may find that if you limit the number of threads to between the number of core and double the number of cores in your system, that you can make the whole thing faster (if the tasks are CPU bound).
Since 100 threads active on a 8 core system, is not as efficient as 16 threads active on an 8 core system.  However a lot of your process time will be dominated by waiting for network connection delays.  So 16 thread will not be enough.
This pattern is often call a semaphore (with counter).
Google hit for "delpi semaphore threading" http://edn.embarcadero.com/article/29908


text:
Q: How to show Up/Down arrows for Input type number in mobile view? For an input type number, up/down arrows on the right side of the input box in web view is easily displayed. I have also preventDefaulted the typing for the input so you are forced to use the arrows to increase/decrease number. But the arrows won't show in mobile view. Is there any way to force arrows in the mobile view so that user won't type in the number but uses the increment/decrement ??

A: try this media query
@media only screen and (max-width : 1024px) {
    input[type=number]::-webkit-inner-spin-button,

    input[type=number]::-webkit-outer-spin-button {
      -webkit-appearance: none
      margin: 0;
    }
}


text:
Q: Extract a txz file inside a zipfile in Python I have a zipfile which has the .txz file. Something like this:
 file1.zip
         |
          -- file2.txz
         |
          -- abc.txt

I have used ZipFile to extract the contents of file1.zip as below:
with zipfile.ZipFile(mainFile) as zf:
     for files in zf.namelist():
         zf.extract(files, dst)

But with this file2.txz is empty having 0 bytes although abc.txt is extracted properly.
How do I properly extract this txz file?


text:
Q: Long-running Ajax call returns http status 401 I have an asp.net page that loads, then makes am ajax call that can take some time. Sometimes the call times out. This is expected in some cases where data is less than perfect. I have been noticing that it will actually prompt for the end users username and password. This seems new: This page has been making this call with no 401 errors like this for several years and I have not heard reports of this behavior. When I look in fiddler, I see that the web server is returning 401.1 errors when the web service call is made.
More info:
This is an ASP.NET page calling a local web service. Here the script manager:
    <ajax:ToolkitScriptManager  ID="ScriptManager1" runat="server" AsyncPostBackTimeout="5000">
     <Services>
<asp:ServiceReference Path="~/WebService/DataWebService.asmx" />
   </Services>
    </ajax:ToolkitScriptManager >

Here is the call to the WS:
 WSNameSapce.WebService.set_timeout(2000000)
 WSNameSapce.DataWebService.GetValues('<%=Current.AccountId%>',displayResult, displayErrorMessage);

The websits uses IIS2 win server 2003, and is configured to use Anonymous Authentication.
The web service calls some stored procs and makes some (WCF) webservce calls. When the procs/WS calls take a long time. I see thread aborted exceptions, and I am prompted to provide my windows login info: as though Basic authentication was configured.
I understand everything up to the when i am prompted to provide my windows login. If the Webservice times out, I should get a 500 error, which my code handles.
Any help usderstanding why users are being prompted for a login, and how I can prevent thi from happening would be appreciated.

A: The dreaded 401.1.  You are failing to authenticate via NTLM somewhere in your pipeline.  Make sure you can authenticate on all your endpoints.
401.1 and 401.2-Authentication Problems


text:
Q: MS Access M:N Relationship query: exclude records with more than the requested values I have a little problem when looking up records that have m:n relationships to other tables and therefore appear multiple times in link tables. I try to show it with a minimal example here:
Let's assume we have a table called "books", one called "authors" and a link table connecting both.

Some books are written by one author, others are written by multiple authors.

As we can see, book one (book_id = 1) is written by only one person (authorID = 1) while book two (book_id = 2) is written by two people (authorID 1 and 3).
If we now try to get the book which is written by author 1 and author 3 we can go like this:
SELECT book_id, title, year_of_publication, pagecount, cover FROM (book
INNER JOIN
(SELECT * FROM link_author_book WHERE author = 1) AS author1
ON author1.book = book.book_id)
INNER JOIN
(SELECT * FROM link_author_book WHERE author = 3) AS author2
ON author2.book = book.book_id

which leads to this:

I am pretty sure that my solution to this is not the best way to do it but in this case it works... anyway, when we try to get only those books returned that are written by author 1 and nobody else, we have a problem. In code, this selection looks like this:
SELECT book_id, title, year_of_publication, pagecount, cover FROM book
INNER JOIN
link_author_book ON link_author_book.book = book.book_id
WHERE author = 1;

and leads to this recordset:

while it is technically true that authorID = 1 is the author of both of these books, what I really wanted to get was only book one (book_id = 1). So here is my question: How can I exclude records that have more than the queried values linked to them in this kind of m:n relationship? And how can this be done as a SQL statement in Access 2016? Thanks in advance

A: The key is learning to write queries which directly answer the questions.  Start with getting books with only one author ("and nobody else").  This will require an aggregate query which counts the authors per book:
SELECT lab.book FROM link_author_book AS lab
GROUP BY lab.book
HAVING Count(lab.author) = 1

Now join the results to the other tables to get detail you desire/require.  I personally prefer saving such intermediate queries then referencing them by name in the next query (since you can then use the Access query designer to edit them individually), but to be explicit I'll include it as a subquery:
SELECT book.title, author.lastname
  ((SELECT lab.book, first(lab.author) AS author
    FROM link_author_book AS lab
    GROUP BY lab.book
    HAVING Count(lab.author) = 1)
  AS SingleAuthor
  INNER JOIN book ON SingleAuthor.book = book.book_id)
  INNER JOIN author ON SingleAuthor.author = author.auth_id

Really, you could also write a query which answers your other questions like getting records with "more than the queried values"...
SELECT lab.book FROM link_author_book AS lab
GROUP BY lab.book
HAVING Count(lab.author) <> 1

and then "exclude" such records:
SELECT book.title, author.lastname
  ((book
  LEFT JOIN (SELECT lab.book FROM link_author_book AS lab
  GROUP BY lab.book
  HAVING Count(lab.author) <> 1)
  AS OtherAuthors
  ON book.book_id = OtherAuthors.book)
  INNER JOIN link_author_book AS lab ON book.book_id = lab.book)
  INNER JOIN author ON author.auth_id = lab.author
WHERE OtherAuthors.book Is NULL

This will initially select all records in [books] due to the left join, but will subsequently exclude books with more than 1 author by keeping only records which are NOT in the [OtherAuthors] subquery. But as you see this is an overly complex way to get the same results.  I only included this to show that it is possible to exclude records using other types of joins and appropriate conditions.  This is a useful technique especially when there is no way of selecting the desired records directly. (Sometimes excluding records really is the best approach, but it just isn't necessary in this case with the link table.)


text:
Q: I want to add an option using optparse. I would like the code to subtract when i give a specific option else I want it to add and print the result I am trying to have multiple options in my python code. The following is the code.
from ast import arguments
import optparse
from requests import options

parser = optparse.OptionParser()
parser.add_option("-a", "--Avalue", dest="a", help="Set the value of A")
parser.add_option("-b", "--Bvalue", dest="b", help="Set the value of B")

(options, arguments)=parser.parse_args()

a = options.a
b = options.b

def pfunc():
    final = a + b
    return final

print(pfunc())

Now I want to add an option "-d" which, when given by the user; the code should subtract rather than add. And if -d is not present; then it should simply add and print the result. How do I do it ? Please guide me regarding this


text:
Q: How can I create a function which contains local_mock()? Currently I am working on several UnitTests and my tests also contain mocking.
In order to "pass" on functions part of my function, I am applying the local_mock() function from the testthat package.
However, there are several functions on which the local_mock function needs to be applied.
They have a different structure, but same number of arguments.
Hence, I created a function as following:
.apply_local_mock = function(Function, File){
   local_mock(Function = function(Argument1, Argument2, Argument3) {
      result = .readCsv(file.path(targetPath, "Input", paste(File))) %>%
      return(result)
   })
}

An example of two functions to which local_mock will be applied to:
CalcProfitability <- function(IncomeStatement, BalanceSheet, Months){
  result = (12/Months) * (IncomeStatement / BalanceSheet)
  return(result)
}

CalcDiffDivByPl <- function(BalanceSheetCY, BalanceSheetPY, IncomeStatement){
  result = (BalanceSheetCY - BalanceSheetPY) / IncomeStatement
  return(result)
}

So the mocking test code looks as following:
.apply_local_mock(CalcProfitability,"CalcProfitability.csv")
.apply_local_mock(CalcDiffDivByPl ,"CalcDiffDivByPl.csv")

But I am receiving the following error:
Error: Function FunctionName not found in environment testthat.

Can anyone please advise how to include local_mock() function in a new function?


text:
Q: differences between capture by reference and by copy in lambda expressions I am using Microsoft Visual Studio trying to run the following code:
#include <iostream>
#include <functional>

using depFunction = std::function<void()>;

class Man
{
public:
    class BankAccount {
    public:
        BankAccount(double b, double d) : balance(b), dept(d) {};
    protected:
        double balance;
        double dept;
    };
    class ID {
    public:
        ID(std::string n, int a, std::string s) : name(n), age(a), sex(s) {};
        double getAge() {
            return age;
        }
    protected:
        std::string name, sex;
        int age;
    };
};

depFunction deposit(Man::ID& myManID) {
    double age = myManID.getAge();
    double* agePointer = &age;
    depFunction theFunc = [=]() {
        std::cout << age << std::endl;
        std::cout << agePointer << std::endl;
    };
    return theFunc;
}

int main() {
    Man::BankAccount myManBankAccount(1000, 0);
    Man::ID myManID("Mohammad", 23, "Male");
    depFunction dep = deposit(myManID);
    dep();

    return 0;
}

As expected, the output is:
23
010FFC08

In this case, I used capture by copy in the lambda expression and everything seems okay; but when I'm trying to capture by reference instead of by copy:
depFunction deposit(Man::ID& myManID) {
    double age = myManID.getAge();
    double* agePointer = &age;
    depFunction theFunc = [&]() {
        std::cout << age << std::endl;
        std::cout << agePointer << std::endl;
    };
    return theFunc;
}

the output would be:
1.82171e-303
CCCCCCCC

I expected the output to be as same as the former case; However, I don't know why it happened. I would be glad to know what's going on!

A: age and agePointer are local variables in the function deposit. When the lambda theFunc captures them by reference, those references are only valid while theFunc is used in the same scope as the function deposit.
When you return theFunc from deposit, those references to the local variables are dangling, and so you invoke undefined behavior when you call the lambda which tries to access those references.
When theFunc captures by copy, it has its own copies of those local variables, and there's no issues with them dangling when you return the lambda from the function. Note that while the values themselves are valid, agePointer is a pointer that points to a local variable. Accessing the pointed at memory is invalid, since it's pointing to age which is out of scope.


text:
Q: Firebase Realtime data is only available after saving the edited source file? I'm relatively new to RN / Javascript, so this might be a rookie mistake - strangely I couldn't find anything close to it on my research.
My setup: I'm developing a RN app with Expo and I'm using the Expo Go app to see any changes.
Since I want to enable cloud services, I'm using the Firebase Realtime database with the official packages in my app. So far, so good.
My issue: Every time I start the developement server (npm start) or reload the app with the 'r' shortcut on my Accounts screen (basic screen displaying the names of the accounts the user created), see attached screenshot, the app refuses to load the data from Realtime - instead I'm greeted with a 'undefined is not an object (evaluating 'obj['accounts']'). Once I hit 'STRG + S' on my keyboard in any file opened, the Expo Go app refreshes and the data is somehow found.
If anyone could help me with this issue, you would surely save my day. :)
CODE
My data is loaded from here (dataHandler.js):
// auth stuff
import { Auth, getAuth } from "firebase/auth";

// database stuff
import { db } from "./firebase";
import { get, onValue, ref } from 'firebase/database'

// more auth stuff
const auth = getAuth()
const userID = auth.currentUser?.uid;

// database Path for retrieving data
const databasePath = userID

export var cachedData = {};

// Gets data from the firebase server, set's it to a local value
export function getData() {
    return onValue(ref(db, databasePath), querySnapshot => {
        let data = querySnapshot.val() || {};
        let downloadedData = {...data};

        // set data to a public var
        cachedData = downloadedData;
        console.log('DEBUG: Data loaded from the server')
    })
}

My account data is then loaded from here (accountData.js):
// load the data from dataHandler.js
import { cachedData } from "./dataHandler";

import { getAuth } from "firebase/auth";

const auth = getAuth()
const userID = auth.currentUser?.uid;

export function getAccountData() {

    console.log('accountData receives = ', cachedData)

    let obj = cachedData[userID];
    let accounts = obj['accounts'];

    console.log('getAccountData returns: ', accounts)

    return accounts;
}

I'm calling the files here:

// experimental stuff
import { getData } from '../../core/dataHandler';
import { getAccountData } from '../../core/accountData'

const Accounts = () => {

    // Downloads data on the app start
    getData();

    // load the data for the account
    const accounts = getAccountData()
    console.log('accountData = ', accounts)

    const accountKeys = Object.keys(accounts)

    const [ accountName, setAccountName ] = useState('')

    return( <SomeView /> )

}


text:
Q: (Python , OpenCV) Extract picture from picture I want to extract each sticker 5x6 and to total 30  sticker
like below ,  how do I do so
(expect pic ) https://imgur.com/a/C5CiSxM
(original picture) https://imgur.com/a/V0lvqU3

from below link I come up my code
How extract pictures from an big image in python

*

*following the suggestion:

The black pixels along the top are a distraction, so are the black
pixels of the QR codes. You are only interested in the white stickers.
So, take a copy of your image and threshold at a high value to give
you pure white stickers surrounded by black and with black QR codes
within each sticker. Now find white contours and reject black ones.
Apply the contours found on the thresholded image to your original
image.

I'm doing the Thresholding expecting pure white stickers surrounded by black and with black QR codes within each sticker
import numpy as np
import glob
import matplotlib.pyplot as plt
import skimage.io
import skimage.color
import skimage.filters

from PIL import Image
import pytesseract
import cv2 as cv
import numpy as np

def custom_blur_demo(image):
    kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32) #锐化
    dst = cv.filter2D(image, -1, kernel=kernel)
    cv.imwrite("/home/joy/桌面/test_11_4/sharpen_images.png", dst)
    cv.imshow("custom_blur_demo", dst)

src = cv.imread("/home/joy/桌面/test_11_4/original.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
custom_blur_demo(src)

cv.waitKey(0)
cv.destroyAllWindows()

# load the image
image = skimage.io.imread("/home/joy/桌面/test_11_4/sharpen_images.png")[:,:,:3]

# image = imageio.imread(image_name)[:,:,:3]
# img = rgb2gray(image)

fig, ax = plt.subplots()
plt.imshow(image)

# convert the image to grayscale
gray_image = skimage.color.rgb2gray(image)

# blur the image to denoise
blurred_image = skimage.filters.gaussian(gray_image, sigma=1.0)

fig, ax = plt.subplots()
plt.imshow(blurred_image, cmap="gray")

# create a histogram of the blurred grayscale image
histogram, bin_edges = np.histogram(blurred_image, bins=256, range=(0.0, 1.0))

fig, ax = plt.subplots()
plt.plot(bin_edges[0:-1], histogram)
plt.title("Grayscale Histogram")
plt.xlabel("grayscale value")
plt.ylabel("pixels")
plt.xlim(0, 1.0)

# create a mask based on the threshold
t1 = 0.72
t2 = 0.05
binary_mask = blurred_image < t1

fig, ax = plt.subplots()
plt.imshow(binary_mask, cmap="gray")

aaa = plt.imshow(binary_mask, cmap="gray")

plt.show()

plt.savefig("/home/joy/桌面/test_11_4/sharpen_images_del_gray_part.png", aaa)

img = Image.open('/home/joy/桌面/test_11_4/sharpen_images_del_gray_part.png')
text = pytesseract.image_to_string(img, lang='eng')

print("file name" ,"final output", ".png")

print("size")

print(img.size)

print(text)

here is the output for mine Thresholding : https://imgur.com/a/V0lvqU3
the product does after Thresholding but the word on every sticker seems blur (I'm going to OCR image to text every single sticker img later)

*

*not correct yet, I want sticker part only that without gray color part

(pic 5b) in same link is how I reach for now
https://imgur.com/a/V0lvqU3
How to cut them in small piece, the sticker size
(expect pic ) https://imgur.com/a/C5CiSxM

A: The black pixels along the top are a distraction, so are the black pixels of the QR codes. You are only interested in the white stickers.
So, take a copy of your image and threshold at a high value to give you pure white stickers surrounded by black and with black QR codes within each sticker. Now find white contours and reject black ones.
Apply the contours found on the thresholded image to your original image.

A: This effort is probably not scientifically generalizable.
Just wanted to show it doesn't need Contour-finding/Binarization. just pixel value comparison might be enough.
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

orig_image = cv.imread("sample.png")
gray = cv.cvtColor(orig_image, cv.COLOR_BGR2GRAY)
kernel = np.ones((3,3),np.uint8)
eroded = cv.erode(gray,kernel,iterations = 1)

def show_img(img_bgr):
    fig, ax = plt.subplots(figsize=(5, 5))
    rgb = cv.cvtColor(img_bgr, cv.COLOR_BGR2RGB)
    ax.imshow(rgb)
    return fig

def detect_top_bottom(original_img, erodded_img):
    """Detects only top and bottom row number of each row of Qr_Codes.
    """
    line_img = original_img.copy()
    height, width = erodded_img.shape
    top = 0
    top_drawn = False
    rows_range = []
    for row in range(erodded_img.shape[0]):
        for col in range(erodded_img.shape[1]):
            if np.mean(erodded_img[row,col]) > 190:
                if row - top > 3 and not top_drawn:
                    cv.line(line_img, (0, row), (width, row), (0,255,0), 2)
                    rows_range.append([row,None])
                    top_drawn = True
                top = row
                break
        else:
            if top_drawn:
                cv.line(line_img, (0, row), (width, row), (0,255,0), 2)
                rows_range[-1][1] = row
                top_drawn = False
    return line_img, rows_range

# make original image grayscale
gray = cv.cvtColor(orig_image, cv.COLOR_BGR2GRAY)
# erode image with 3x3 kernel in order to remove small noises
kernel = np.ones((3,3),np.uint8)
eroded = cv.erode(gray,kernel,iterations = 1)

line_img, rows_range = detect_top_bottom(orig_image, eroded)
# Rotate image 90 degs clockwise in order to use same function for detection
eroded_rotated_90 = cv.rotate(eroded, cv.ROTATE_90_CLOCKWISE)
line_img_rotated_90 = cv.rotate(line_img, cv.ROTATE_90_CLOCKWISE)
line_img, cols_range = detect_top_bottom(line_img_rotated_90, eroded_rotated_90)
# finally rotate 90 deg counter clockwise in to get orignal.
line_img= cv.rotate(line_img, cv.ROTATE_90_COUNTERCLOCKWISE)
fig = show_img(line_img)
fig.savefig("original_grid.png")

fig, axs = plt.subplots(len(rows_range), len(cols_range))
for i, row in enumerate(rows_range):
    for j, col in enumerate(cols_range):
        axs[i,j].axis('off')
        # just for sake of visualization conver to RGB
        # axs[i,j].imshow(orig_image[row[0]:row[1], :][:,col[0]:col[1]])  probabely is enough
        orig_sub_channels = cv.cvtColor(orig_image[row[0]:row[1], :][:,col[0]:col[1]], cv.COLOR_BGR2RGB)
        axs[i,j].imshow(orig_sub_channels)
fig.savefig("splitted_grid.png")


text:
Q: Checking greater than for date not working I am trying to fetch data based on greater than condition for date field. The stored format of date "08-MAY-13". I have added the condition
      SELECT * FROM EMP WHERE JOINING DATE > TO_DATE('14-NOV-13','dd-mm-yy').

But in the results i see '08-MAY-13' date also appearing. Please let me know.
Thanks in advance.

A: Maybe you should give format to date column, like:
SELECT * FROM EMP WHERE JOINING TO_DATE(DATE,'dd-mm-yy') > TO_DATE('14-11-13','dd-mm-yy');

I hope to be helpful.


text:
Q: How to query the 'Metadata' field from 'FieldDefinition' with SOQL? I tried the following SOQL query:
select id, DataType,NamespacePrefix, DeveloperName, Metadata from FieldDefinition where EntityDefinition.QualifiedApiName = 'Account' AND DurableId ='Account.Industry'

I received this error:

INVALID_FIELD:
NamespacePrefix, DeveloperName, Metadata from FieldDefinition where
ERROR at Row:1:Column:53
No such column 'Metadata' on entity 'FieldDefinition'.

Why? According to the documentation the field 'Metadata' is available if the query result contains no more than one record - which is the case here.
How can I access this field?

A: Tooling API Documentation refers only to Tooling API queries.
This is not obvious that Metadata is available only for Tooling API Calls.
This is not obvious but actually FieldDefinition and ObjectDefinition standard objects are available by usual SOQL queries from usual Apex code.
Except for Metadata field, which is only  available for Tooling API Calls.
There was once in the past list of all Salesforce Standard Objects in salesforce documentation, now it is gone. There is only list of Standard Objects available in SOAP API but this is not what we are looking for.
So, let's document ourselves the current behavior.
If we run a query select id, DataType,NamespacePrefix, DeveloperName from FieldDefinition where EntityDefinition.QualifiedApiName = 'Account' AND DurableId ='Account.Industry' in Developer Console Query Editor even without having checked Tooling API checkbox or if we run this query in Apex Code we will receive results without error.

If we run a query select id, DataType,NamespacePrefix, DeveloperName, Metadata from FieldDefinition where EntityDefinition.QualifiedApiName = 'Account' AND DurableId ='Account.Industry' in Developer Console Query Editor without having checked Tooling API checkbox or if we run this query in Apex Code we will obtain an error

Please notice that Tooling API checkbox is unchecked.
If we run a query select id, DataType,NamespacePrefix, DeveloperName, Metadata from FieldDefinition where EntityDefinition.QualifiedApiName = 'Account' AND DurableId ='Account.Industry' in Developer Console Query Editor having checked Tooling API checkbox or if we run this query through callout to Tooling API we will receive results without error.

Which proves my statements above that:

*

*Standard objects FieldDefinition and ObjectDefinition are available by usual SOQL queries from usual Apex code except for Metadata field.

*Field Metadata on  FieldDefinition is available only by Tooling API calls.
However in my humble opinion this is useless to run this query in Developer console query editor since Developer Console will not show us any data but only [Object object] string which is not really helpful.
So to get that information in Apex you really need to make self-callout.
Before doing that you need to go to Remote Site Settings by link https://login.salesforce.com/0rp/e?SiteName=self&EndpointUrl=https://yourinstance.salesforce.com/ on production or Developer Edition instance or https://test.salesforce.com/0rp/e?SiteName=self&EndpointUrl=https://yourinstance.salesforce.com/ on any of sandbox instance and input your data and click save like this is done on this screenshot

Then you can run the following code to get the field metadata
static String restGet(String endPoint, String method, String sid) {
    Http h = new Http();
    HttpRequest hr = new HttpRequest();
    hr.setHeader('Authorization', 'Bearer ' + sid);
    hr.setTimeout(60000);
    hr.setEndpoint(endPoint);
    hr.setMethod(method);
    HttpResponse r = h.send(hr);
    return r.getBody();
}

     String baseURL = URL.getSalesforceBaseUrl().toExternalForm();
     //restGet( baseURL, 'GET', UserInfo.getSessionId() );
     String body = restGet( baseURL + '/services/data/v38.0/tooling/query?q=select+id,+DataType,NamespacePrefix,+DeveloperName,+Metadata+from+FieldDefinition+where+EntityDefinition.QualifiedApiName+=+\'Account\'+AND+DurableId+=\'Account.Industry\'', 'GET', UserInfo.getSessionId() );
     System.debug(LoggingLevel.ERROR, '@@@ v: ' + body );
     String metadata = body.substringBetween('"Metadata":{"', '}}]}');
     System.debug(LoggingLevel.ERROR, '@@@ v: ' + metadata );

However, if you really need metadata you could just run Apex Field Describe methods because this might be more easy than accessing FieldDefinition object Metadata field through callout.

A: I ran the exact same query through the Tooling API and got a result back.
I suspect you are missing a required permission to access the Metadata field.
Ensure that the user running the query has the ModifyAllData permission. This is required to access the Metadata API, which is essentially what you would get back in the CustomField. See About the 'Modify All Data' permission


text:
Q: MySQL SELECT QUERY same column different where statements Currently I have 2 tables. Service 1 name and Service info.
I need to grab all Unique names from service name and show how many service infos are attached to it eg.
SELECT cs.serviceDesc as 'SERVICE', COUNT(cr.serviceId) as 'Count',
FROM consultationRequests cr
JOIN consultationServices cs on cs.serviceId = cr.serviceId
JOIN demographic d on d.demographic_no = cr.demographicNo
WHERE cs.active = 1
AND cr.referalDate between '2018-11-31' and '2019-01-20'
GROUP BY cr.serviceId

There is also another column in consultationRequests that has a status number between 1-4. I need to add in another column for each status and count the number of infos that are within that status WITHIN the service name.

A: You can use conditional aggregation:
SELECT cs.serviceDesc as SERVICE,
       COUNT(cr.serviceId) as Count,
       SUM(cr.consultationRequests = 1) as cnt_1,
       SUM(cr.consultationRequests = 2) as cnt_2,
       SUM(cr.consultationRequests = 3) as cnt_3,
       SUM(cr.consultationRequests = 4) as cnt_4
FROM consultationRequests cr JOIN
     consultationServices cs
     ON cs.serviceId = cr.serviceId JOIN
     demographic d
     ON d.demographic_no = cr.demographicNo
WHERE cs.active = 1  AND
      cr.referalDate between '2018-11-31' and '2019-01-20'
GROUP BY cr.serviceId


text:
Q: What happens when a java class is annotated @WebService? A WebService Java class is same as normal class, but what is the initialization or sequence happens inside server or What actually server does internally when it looks up those classes?

A: I think you want to know how does a simple class change to be a Web Service, if is that, the use o the @webservice notation enables the code injection that transforms your simple class in a servlet that will be answering http requests, and perform the desired @webmethod.


text:
Q: Decompositions LAPACK Could you please provide an example of these 3 decompositions on LAPACK, or just an idea how to use this library to solve them??
Eigen-value decomposition.
Orthogonal decomposition.
Schur decomposition.

A: Examples of eigenvalue problems are vibrations in mechanical systems; the eigenvalues are the natural frequencies and the eigenvectors are the normalized modes of vibration.
It turns out that PageRank is also just a huge eigenvalue decomposition.  Page and Brin are billionaires because of it.
I don't know what's in LAPACK, but look for Jacobi, Householder, or Lanczos methods.
Orthogonal decomposition can be used to invert a special class of matrix:
http://en.wikipedia.org/wiki/Orthogonal_matrix
Here are the LAPACK docs:
http://www.netlib.org/lapack/lug/node39.html
Schur decomposition is similar to orthogonal decomposition, except for a diagonal matrix in the middle whose values are equal to the diagonal values of the matrix in question:
http://en.wikipedia.org/wiki/Schur_decomposition
I've never heard it called Schur decomposition, but here are the LAPACK docs for symmetric, real matricies:
http://www.netlib.org/lapack/lug/node48.html
The latter two are techniques for solving special classes of matricies.


text:
Q: SPFx web part with CDS I am looking for help to create SPFX web part where I want to access CDS entities and perform below actions

*

*Retrieve entity records

*Add record

*Update record

*Delete a record

A: You can use the Web API web services to get CDS data.
For authentication an Azure AD app will need to be registered like mentioned in this documentation article.
And for executing the api calls from the SPFx web part the AADHttpClient library can be used like mentioned in this documentation article.


text:
Q: STM32CubeIDE: What is the correct method to import drivers and middleware from example projects to the current project? When we are importing an example project to the STM32CubeIDE, it probably uses .cproject and .project files present in the project directory to import required drivers and middleware. For example, here's a list of source files for an example project import into the IDE:

How can I automatically add the set of sources part of Middleware and Drivers folder above to a new project's .project and .cproject files, so that they are properly added to the build configuration?


text:
Q: Can't connect to Android devices when using Network Service Discovery through Wi-Fi P2P everyone!
I'm developing an Android app that allows to chat with nearby devices that have installed this app. In order to accomplish this, I'm using the Wi-Fi P2P API and Network Service Discovery to search for such nearby devices.
I've written the code for searching the nearby devices in a thread started by a Service. When a device is detected, the Service sends it (through a broadcast intent) to an Activity which displays the devices detected so far.
The detected devices are added to a recyclerView and, when the user presses one of them, a connection must be established to such device.
The Wi-Fi Direct connection gets established successfully (that is, the WifiP2pManager.connect() method succeeds) and the WIFI_P2P_CONNECTION_CHANGED_ACTION is caught.
In the broadcast receiver, when such broadcast intent is caught, the following code is executed:
NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
            if (networkInfo.isConnected()) {

                mManager.requestConnectionInfo(mChannel, connectionInfoListener); }

With the requestConnectionInfo() method I can obtain more information about the connection, such as the IP address of the device I'm trying to connect to.
To obtain such information, I provide an implementation of WifiP2pManager.ConnectionInfoListener to that method, which is denoted by the connectionInfoListener variable.
This is the code of my implementation of WifiP2pManager.ConnectionInfoListener:
private WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener() {

        @Override
        public void onConnectionInfoAvailable(WifiP2pInfo info) {

            InetAddress deviceIP = info.groupOwnerAddress;

            int port = servicesConnectionInfo.get(device);

            ConnectThread connectThread = new ConnectThread(deviceIP, port, device);
            connectThread.start();

"device" is an instance variable of my implementation of BroadcastReceiver which is not important right now. What is important, instead, is the ConnectThread thread. That's the thread that handles the code necessary to connect the socket between the two devices. When I try to connect to a detected device, ConnectThread, in its run() method, creates a new instance of ChatConnection passing the IP address and the port number previously obtained to this constructor:
 public ChatConnection(InetAddress srvAddress, int srvPort, String macAddress) throws IOException {
        ...

        connSocket = new Socket(srvAddress, srvPort);

        ...

    }

And here is where the problem occurs. When I test my app on my physical device, all I get is this exception:
W/System.err: java.net.ConnectException: failed to connect to /192.168.49.1 (port 6770): connect failed: ECONNREFUSED (Connection refused)

Of course, I installed my app on a second physical device too, which gets successfully detected and a Wi-Fi Direct connection gets successfully established. But, when comes to this line of code:
connSocket = new Socket(srvAddress, srvPort);

that exception is thrown...
I apologize for the length of this question, but I wanted to be the clearest possible.
I really thank you in advance for any help.
EDIT: I forgot to mention the code for initializing the ServerSocket.
The ServerSocket is initialized in a thread that is started as soon as the Wi-Fi is enabled.
That is, when the WifiP2pBroadcastReceiver (an inner class of the app's Service which extends BroadcastReceiver) catches a WIFI_P2P_STATE_CHANGED_ACTION intent, it checks if the Wi-Fi is enabled and, if enabled, it starts the the thread where the ServerSocket is located:
public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        if (action.equals(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION)) {

            int statoWiFi = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
            if (statoWiFi == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {

                mNsdService = new NsdProviderThread();
                mNsdService.start();
            }

The ServerSocket is initialized in the run() method of NsdProviderThread:
public void run() {
        ...

        try {
            server = new ServerSocket(0);
        } catch (IOException ex) {

            return;
        }

        ...

        while (!Thread.currentThread().isInterrupted()) {

            Socket clientSocket = null;
            try {
                clientSocket = server.accept();
            } catch (IOException ex) {

                break;
            }
            try {

                ChatConnection chatConn = new ChatConnection(clientSocket);
                synchronized (connections) {
                    connections.add(chatConn);
                }

            } catch (IOException ex) {

                continue;
            }
        }

"server" is an instance variable of NsdProviderThread declared as ServerSocket.

A: It looks like you just need to use the correct port number on both ends.
You're using zero, which from the documentation means:

A port number of 0 means that the port number is automatically
  allocated, typically from an ephemeral port range.

So, when you create your ServerSocket, make sure it is listening on the same port that the other device uses to initiate the connection:
private static final int port = 6770;

//.....

try {
    server = new ServerSocket(port);
} catch (IOException ex) {
    ex.printStackTrace();
}

A: again! I've finally managed to get my app working. Here's what I've done:

*

*Hard-code the port number;

*When you get the group owner address in the ConnectionInfoListener implementation, make sure if it is the IP address of the device in use. If it is not, connect a client socket to the group owner address; otherwise, make your app wait for an incoming connection;

*Initialize the ServerSocket as soon as possible (for example, when the app starts up).

In order to get the device actual IP address after a Wi-Fi Direct connection has been established, I've used this function which I've found in this project (which is derived by the original Android WiFiDirectdemo) in the "Utils" class:
public static String getLocalIPAddress() {
    /*
     * modified from:
     *
     * http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/
     *
     * */
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();

                String iface = intf.getName();
                if(iface.matches(".*" +p2pInt+ ".*")){
                    if (inetAddress instanceof Inet4Address) { // fix for Galaxy Nexus. IPv4 is easy to use :-)
                        return getDottedDecimalIP(inetAddress.getAddress());
                    }
                }
            }
        }
    } catch (SocketException ex) {
        Log.e("AndroidNetworkAddressFactory", "getLocalIPAddress()", ex);
    } catch (NullPointerException ex) {
        Log.e("AndroidNetworkAddressFactory", "getLocalIPAddress()", ex);
    }
    return null;
}

"p2pInt" is a private static String costant declared in the Utils class as:
private final static String p2pInt = "p2p-p2p0"

However, in my app, I've changed the "p2p-p2p0" string in "p2p-wlan0" since it looks like the network interface of my device for Wi-Fi Direct has that (different) name.
I hope this can help any developer who's trying to create an app that uses Wi-Fi Direct connectivity.


text:
Q: Nature of C Complex numbers data type I did research trying to visualise how complex number in <complex.h> are stored in RAM. I know for integers, floating points but not for complex. Is it just 2 number like in complex struct ?

A: The layout is specified in C11 6.2.5/13:

Each complex type has the same representation and alignment requirements as an array
type containing exactly two elements of the corresponding real type; the first element is
equal to the real part, and the second element to the imaginary part, of the complex
number.