text:
Q: An error happened during template parsing (template: "class path resource [templates/index.html]") I'm trying to open my html page but I'm stuck with these error whenever I try to get access to localhost.

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Aug 11 18:24:14 CEST 2020
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/index.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/index.html]")
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100)
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072)
    at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:362)
    at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:189)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "index" - line 9, col 36)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
    at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
    ... 48 more
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "index" - line 9, col 36)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:117)
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918)
    at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleStandaloneElementEnd(TemplateHandlerAdapterMarkupHandler.java:260)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleStandaloneElementEnd(InlinedOutputExpressionMarkupHandler.java:256)
    at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleStandaloneElementEnd(OutputExpressionInlinePreProcessorHandler.java:169)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleStandaloneElementEnd(InlinedOutputExpressionMarkupHandler.java:104)
    at org.attoparser.HtmlElement.handleStandaloneElementEnd(HtmlElement.java:79)
    at org.attoparser.HtmlMarkupHandler.handleStandaloneElementEnd(HtmlMarkupHandler.java:241)
    at org.attoparser.MarkupEventProcessorHandler.handleStandaloneElementEnd(MarkupEventProcessorHandler.java:327)
    at org.attoparser.ParsingElementMarkupUtil.parseStandaloneElement(ParsingElementMarkupUtil.java:96)
    at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:706)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301)
    ... 50 more
Caused by: org.springframework.beans.NotReadablePropertyException: Invalid property 'fullName' of bean class [com.example.demo.domain.User]: Bean property 'fullName' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
    at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:622)
    at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:612)
    at org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:104)
    at org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:228)
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:129)
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903)
    at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:258)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227)
    at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
    ... 63 more

I will attach the files involved:
Home controller:
@Controller
public class HomeController {

    @RequestMapping("/")
    public String home(Model model) {
        model.addAttribute("formData", new User());
        return "index";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String processFormData(User user) {
        return "results";
    }
}

User domain class:
public class User {
    private String fullName;
    private int age;
    private boolean employed;
    private String gender;

    public User() {}

    public User(String full_name, int age, boolean employed, String gender) {
        super();
        this.fullName = full_name;
        this.age = age;
        this.employed = employed;
        this.gender = gender;
    }

    // GETTER AND SETTERS HERE
}

index.html:
<!doctype html>

    <meta charset="UTF-8" />
    <title>Home page</title>

    <form action="/create" method="POST" th:object="${formData}">

Full name: <input type="text" th:field="${formData.fullName}" />

Age: <input type="text" th:field="${formData.age}" />

Employed: <input type="checkbox" th:field="${formData.employed}" th:value="true"/>

            Gender:

            Male <input type="radio" th:field="${formData.gender}" th:value="Male" />
            Female <input type="radio" th:field="${formData.gender}" th:value="Female" />

            <input type="submit" value="Submit"/>
            <input type="reset" value="Reset"/>

    </form>

A: Invalid property 'fullName' of bean class [com.example.demo.domain.User]: Bean property 'fullName' is not readable or has an invalid getter method
Thymeleaf can only access the properties of objects via getters. Also if you were to use object binding with Thymeleaf you would have to make sure you have setters and default constructor.
In general whenever you work with Thymeleaf it is a good idea to define all the getters, setters and default constructor for all objects being passed to thymeleaf.

A: you should change the visibility of the user's properties to public.
and it's done.
greetings from El salvador


text:
Q: Why xpath doing nothing? source code of login bar
    BasicConfigurator.configure();
    System.setProperty("webdriver.chrome.driver","C:\\Users\\Piotrek\\projekciki\\src\\main\\java\\selenium\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("https://twitter.com/login?lang=pl");
    WebElement element = driver.findElement(By.xpath("/html/body/div/div/div/div[2]/main/div/div/form/div/div[1]/label/div/div[2]/div/input"));
    element.sendKeys("LOGIN");

just opening twitter and doing nothing.
where is the problem?

A: Modified code
BasicConfigurator.configure();   System.setProperty("webdriver.chrome.driver","C:\\Users\\Piotrek\\projekciki\\src\\main\\java\\selenium\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.navigate("https://twitter.com/login?lang=pl");
    WebDriverWait wait = new WebDriverWait(driver, 10);
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[contains(@name,'username_or_email')]")));
        WebElement element = driver.findElement(By.xpath("//input[contains(@name,'username_or_email')]"));
        element.sendKeys("LOGIN");

if above xpath doesn't work use this one-//input[contains(@name,'username_or_email' )and (@type='text')]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Array values in body of email on separate lines I've put together a PS script that takes values from an AD group and puts them in an email to send to our helpdesk.  The issue I am having is that the values from the AD group are in an array but I cannot figure out how to display those values on separate lines.  Below is the code where I'm using an AD group with three testusers:
$members = @(Get-qADGroupMember adgroup -IncludedProperties "DisplayName,sAMAccountName")
$smtp = "smtpserver.domain.com"
$to = "helpdesk@domain.com"
$from = "security@domain.com"
$subject = "Accounts Disabled"
$body = "Helpdesk, `n `n"
$body += "These users have had their passwords reset and their accounts disabled. There is no action required on the part of IT helpdesk, this is strictly to notify you.  These users will probably be calling soon: `n `n"

$body += For ($i=0; $i -lt $members.Length; $i++) {
    $members[$i -join "`n"]
}

$body += "`n"
$body += "For any questions regarding this, please contact the Information Security Team  `n `n"
$body += "Thank you `n"
$body += "Information Security"

This is the output:

Helpdesk,
These users have had their passwords reset and their accounts.  There is no action required on the part of IT helpdesk, this is strictly to notify you.  These users will probably be calling soon:
domain\testuser1 domain\testuser2 domain\testuser3
  For any questions regarding this, please contact the Information Security Team
Thank you
  Information Security

How can I get the users from that group to be displayed on their own line like this?

domain\testuser1
  domain\testuser2
  domain\testuser3

A: You're over-working it. PowerShell likes to write lines. Since you already have an array here you can simple add to it.
$body = @("Helpdesk,")
$body += "These users have had their passwords reset and their accounts disabled. There is no action required on the part of IT helpdesk, this is strictly to notify you. These users will probably be calling soon:"

$body += $members

Before you sent it, you only need convert it to a string.
Send-MailMessage -Body ($body | Out-String) <OtherParameters>


text:
Q: output of ntpd --version In my ubuntu 12.04
#ntpd --version
ntpd 4.2.8p6@1.3265-o Wed Mar  2 06:23:51 UTC 2016 (5)

in the above "(5)" represents what?

A: The date after the version number stands for the time when the version was compiled.
My guess is that the (5) has something to do with the Coordinated Universal Time (UTC) value. Maybe the time difference to UTC, in this case +5 hours? So far I couldn't find a document for that.
Seems like the number (5) stands for the times the makefile was executed (thx @ Sharath Manchala).

The version style is the following, just for proving my guess about the UTC date.
NTP uses A.B.C - style release numbers.

At the moment:

 A is 4, for ntp V4.
 B is the major release number.
 C is the minor release number.  Even numbers are 'stable' releases and
 odd numbers are "development" releases.

Following the release number may be the letter 'p' followed by a number.
This indicates a point (or patch) release.

Release candidates have -RC in the release number.

Here are some recent versions numbers as an example:

 4.2.2      A production release (from the ntp-stable repository)
 4.2.2p2    A production release (from the ntp-stable repository)
 4.2.3p12   A development release
 4.2.3p15-rc1   A release candidate for 4.2.4


text:
Q: How does this Java initialisation work? Apologies for a newbie question, but my textbooks and web searches are not helping me (probably because I don't know the right name of what I'm looking at). In some example code, I see a member declaration and initialisation of a javafx.scene.shape.Rectanglelike this:
var bgRect = Rectangle {
    x: 0
    y: 0
    width: bind listView.width
    height: bind this.itemText.boundsInLocal.height
    fill: bind bgColor;
}

I can see what this is doing, but not how. How does what's inside the braces get turned into a Rectangle instance?

A: This is not Java, this is a special language that early versions of JavaFX used, called JavaFX Script.


text:
Q: How can I add custom attribute in mxCell tag of mxgraph? How can I add custom attribute in mxCell tag of mxgraph? I want to add value2="customValue"
<mxGraphModel dx="872" dy="535" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" background="#ffffff">
  <root>
    <mxCell id="0"/>
    <mxCell id="1" parent="0"/>

    <mxCell id="2" value="wfState_1" value2="customValue" style="strokeColor:red" vertex="1" parent="1">
      <mxGeometry x="50" y="110" width="120" height="70" as="geometry"/>
    </mxCell>
  </root>
</mxGraphModel>


text:
Q: How to manually add Shadowbox.setup() to the footer of your theme? I have a Wordpress website with two versions, one full-sized and one for mobile browsers.
I want to shut down the Shadowbox.JS plugin for the mobile theme. (I want images to be opened directly)
I've found something in the Advanced settings of the plugin.

Skip setup: true/false.
Set this true to skip Shadowbox.setup() during Shadowbox.init(). For purposes of this plugin you will have to manually add Shadowbox.setup() to the footer of your theme. Defaults to false.

How do I manually add Shadowbox.setup() to the footer of my theme?
The idea is I will add it to the full theme, and Shadowbox will work, but I won't add it to the mobile theme, and links will open the images directly.

A: Sounds like Shadowbox.setup() is a custom action hook created by Shadowbox-js.  If placed in your footer, like any other WordPress template tag, it triggers the plugin to get the option you set in the advanced configuration screen.
I recommend setting the advanced option to true (as in "skip the setup") , and placing the template tag in the footer of your mobile theme. When the mobile theme footer loads, the plugin should deactivate. Do not place it in your full theme, and the plugin will ignore the advanced setting, keeping the plugin active.

A: You can use regular expressions to test the domain name and its path.
if( /mobile.example.com/.test(window.location) == false ) {
  Shadowbox.init();
}

// Or check the path for (example.com/mobile)
if( /example.com\/mobile/.test(window.location) == false ) {
  Shadowbox.init();
}

A: @kevtrout: Skip setup = true means the plugin doesn't work. False (default) means it works.
From what I gather, it says I need to put in that Shadowbox.setup() template tag in the footer in order to make it work again, because it's missing it. So I have to include it in the full theme, not the mobile theme.
I've tried both variants, anyway! The problem is when I set "Skip setup" to true Shadowbox doesn't work for either theme. I'm probably not inserting the code right in the footer!
I apoligise for that, could you please write the exact syntax I should be using?

A: Oh. Sorry to bother you, it was probably some sort of cache issue, I wasn't very thorough. Yes, indeed:
Advanced settings > Skip setup = true
footer.php of Full theme
<script type="text/javascript">
Shadowbox.init();
Shadowbox.setup();
</script>
leave footer.php of Mobile theme unaltered.
And it works!


text:
Q: Lambda function with four lists of strings and if-else condition I have a request from tech lead to rewrite this code and replace for-loop with generic lambda. I doubt that this will lead to more simpler, more readable and maintainable code.
Is there a really a good way to do that, please?
The question is about how to transform current for-loop into the lambda function. Change of item's data structure is completely out of scope. See the loop - it is a devision of the states list while simultaneously checking value in addressType at the same index.
How to do that with lambda and will it actually simplify the code?
List<String> states = Arrays.asList(item.getState().split(","));
List<String> addressType = Arrays.asList(item.getAddressType().split(","));
List<String> mailingStates = new ArrayList<>();
List<String> physicalStates = new ArrayList<>();

for(int i = 0; i<states.size(); i++){
    if(Constants.MAILING.equals(addressType.get(i))){
        mailingStates.add(states.get(i));
    } else {
        physicalStates.add(states.get(i));
    }
}

Need to say - Java 8 only

A: The code will be the same, so I don't know what the point would be, but it will use a lambda expression block.
List<String> states = Arrays.asList(item.getState().split(","));
List<String> addressType = Arrays.asList(item.getAddressType().split(","));
List<String> mailingStates = new ArrayList<>(), physicalStates = new ArrayList<>();

        IntStream.range(0, states.size()).forEach(i -> {
            if (Constants.MAILING.equals(addressType.get(i))) {
                mailingStates.add(states.get(i));
            } else {
                physicalStates.add(states.get(i));
            }
        });

A: What you want to do is go through two lists at the same name. The generic name for this operation is "zip" - when you go through two (or sometimes more) arrays/lists/streams/etc and do something with each element.
You can pick an implementation for streams from here: Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip) there are many that are already implemented in existing libraries, as well. If you already have such a library in your project, you need but an import to use it.
For illustrative purposes, I'll assume there is an implementation available with this signature:
<A, B, C> Stream<C> zip(Stream<? extends A> a,
                        Stream<? extends B> b,
                        BiFunction<? super A, ? super B, ? extends C> zipper)

Also, a good simple generic utility would be a Pair class that has two values. There are many existing implementations. I'll an implementation with this this signature is available:
class Pair<LEFT, RIGHT> {
    Pair(LEFT left, RIGHT right);
    LEFT getLeft();
    RIGHT getRight();
}

This will hold the related state and address type. But you can also consider creating a specific object that encapsulates a given state and address type.
With these generic helpers, your code can look like this:
Stream<String> states = Arrays.stream(item.getState().split(","));
Stream<String> addressType = Arrays.stream(item.getAddressType().split(","));

Map<Boolean, List<String>> splitStates = zip(states, addressTypes,
    (state, addressType) -> new Pair<String, String>(state, addressType))
    .collect(
      Collectors.partitioningBy(pair -> Constants.MAILING.equals(pair.getRight()),
        collectors.mapping(pair -> pair.getLeft())
      )
    );

List<String> mailingStates = split.get(true);
List<String> physicalStates = split.get(false);

If lambdas are replaced with method references and some minor rearrangement when possible, then you get:
private static final Predicate<Pair<String, String> IS_Mailing =
    pair -> Constants.MAILING.equals(pair.getRight());

/* ... */

Stream<String> states = Arrays.stream(item.getState().split(","));
Stream<String> addressType = Arrays.stream(item.getAddressType().split(","));

Map<Boolean, List<String>> splitStates = zip(states, addressTypes, Pair::new)
    .collect(Collectors.partitioningBy(IS_MAILING),
        collectors.mapping(Pair::getLeft()));

List<String> mailingStates = split.get(true);
List<String> physicalStates = split.get(false);

And if instead of generic Pair class you implement a class like:
class StateData {
    private String state;
    private String addressType;

    public StateData(String state, String addressType) {
        this.state = state;
        this.addressType = addressType;
    }

    public String getState() { return this.state; }
    public String getAddressType() { return this.addressType; }
    public boolean isMailing() {
        return Constants.MAILING.equals(this.getAddressType());
    }
}

The code becomes more semantic:
Stream<String> states = Arrays.stream(item.getState().split(","));
Stream<String> addressType = Arrays.stream(item.getAddressType().split(","));

Map<Boolean, List<String>> splitStates = zip(states, addressTypes, StateData::new)
    .collect(Collectors.partitioningBy(StateData::isMailing),
        collectors.mapping(StateData::getState()));

List<String> mailingStates = split.get(true);
List<String> physicalStates = split.get(false);

One final consideration would be to create an enum for addressType instead of comparing to a constant.

A: You may use the partitioningBy to separate out items based on the Constants.MAILING.equals(addressType.get(i)) condition.
Map<Boolean, List<Integer>> map
    = IntStream.range(0, states.size())
               .boxed()
               .collect(Collectors.partitioningBy(i -> Constants.MAILING.equals(addressType.get(i))));

List<String> mailingStates = map.get(true);
List<String> physicalStates = map.get(false);


text:
Q: Why difference between Google Earth and QGIS distance measurement? I am quite new to QGIS.
I wanted to test if Google Earth and QGIS distance measurement tools are actually getting the same results. Turns out, they don't -at least not in my case.
I'm pretty sure the project CRS (Stockholm, Sweden) is the right one - and I guess Google is always right (!)?
The CRS is SWEREF99 18 00, EPSG::3011 (OTF).
Method:

*

*DRAWING LINE: new layer -> draw line

*MEASURING in QGIS: attribute table -> field calc -> $Length/1000*

*EXPORT TO GOOGLE EARTH: save layer as.. -> KML-file (aware of correct CRS)

*MEASURING in GOOGLE EARTH: import KML-file -> measure manually w/ GEarth measurement tool

(please look at the picture to see how different they measure 3 different lines, *= I've seen this in several tutorials)
So, my question is either;
1) Which measurement should I trust - QGIS or Google EArth?
and/or
2) How do I get QGIS to measure correctly?

A: A Projected Coordinate System (PCS) like the one you're using here, SWEREF99 18 00, is always based off an underlying Geographic Coordinate System (GCS).
Google Earth uses the widely used WGS84 GCS, whereas the SWEREF99 18 00 projection is actually based off the SWEREF99 GCS. These differ in their coverage and, slightly, in the way they approximate the shape of the earth. As a result, coordinates are not directly comparable between them.
Transformations are used to convert from one GCS to another. In order to ensure accurate display on Google Earth you should transform your data to a WGS84-based PCS or the WGS84 GCS. Therefore, I would say your QGIS results are more reliable.
You should find that repeating your methodology with your data transformed to the local UTM Zone (a PCS based off the WGS84 GCS) gives you similar distance measurements.

A: I can understand that the approach of the topic provided by this answer, through the projection system, can help you obtain acceptable inaccuracies.
But let me dig a little deeper on the subject.
Beyond that we all know that a curved surface can not be represented on a plane without producing modifications, it is not necessary to measure areas and distances on the plane: we can measure curved areas and distances. And that is precisely what should be done in these cases.
Leaving the theme of how Google Earth manages to adjust and represent their images on our flat screen, or what are the projection systems that each country establishes in order to represent their cartographic maps on paper (or digital cartesian coordinates), trying to produce as little distortion as possible, we will think that given two longitude-latitude coordinates on an ellipsoidal body, it is perfectly possible to know the distance that separates them, measured on the curved surface of the body. And that's what Google Earth does when measuring distances, and also what QGIS can do with its area and length functions.
Google Earth does it without asking us or allowing us to answer what ellipsoid is being measured. Simply measured on the ellipsoid defined by the WGS 84 system. Google Earth Pro also measures on the EGM96 geoid or on the SRTM model when the Terrain layer is active.
QGIS can measure on any system instead. But so much flexibility can play against us if we do not know what it's measuring.
First and foremost, let it know if we want measuring on a plane or ellipsoidal system. In the General Properties of the project we can specify that the measurements are made on an ellipsoid or that they are planimetric.

*

*If we choose None/Planimetric, the length and area functions will perform their measurements in the projection system of the layer in which the geometries measured are located.

*Instead, we can choose an Ellipsoid on which to measure among the many available, or even set the parameters for a custom one. In this case, length and area functions will measure ellipsoidal lengths and areas in the QGIS expressions (except labeling).
Therefore, my answer is: Choose the WGS 84 ellipsoid in the General Properties of your project in QGIS, and in Google Earth you will get values as identical as you can point to the correct line endpoints with the mouse.

A: In terms of measure the distance, the coordinate system is the key.
In your case, the measurement are both right but in different coordinate system. The difference is caused by the distortion of map projection.https://en.wikipedia.org/wiki/Map_projection
Usually, we use WGS84(EPSG:4326) or pseudo mercator(EPSG:3857) to calculate the distance.


text:
Q: compare strings of uneven length in TSQL I have two tables. Both of them contain (dutch) postalcodes.
Those have the format 9999AA and are stored as varchar(6).
In the left table the codes are complete
John Smith        1234AB
Drew BarryMore    3456HR
Ted Bundy         3456TX
Henrov            8995RE
My mother         8995XX

In the right table the codes can be incomplete
1234AB Normal neigbourhood
3456   Bad neighbourhood
8995R  Very good neighbourhood

I need to join these tables on the postalcodes. In this example the output would have to be
John Smith        Normal neighbourhood
Drew BarryMore    Bad neighbourhood
Ted Bundy         Bad neighbourhood
Henrov            Very good neighbourhood
My mother         -unknown-

So I have to join the two tables based on the length of the postal code in the right table.
Any suggestions as to how to do this? I could only come up with a CASE in the ON statement but that was not so smart ;)

A: If you have no "duplicates" in the second table, you could use like:
SELECT t1.*, t2.col2
FROM table1 AS t1
JOIN table2 AS t2
ON t1.postalcode LIKE t2.postalcode + '%';

However, this is not going to be efficient.  Instead, an index on table2(postalcode) and a series of LEFT JOINs is probably faster:
SELECT t1.*, COALESCE(t2a.col2, t2b.col2, t2c.col2)
FROM table1 t1
LEFT JOIN table2 t2a ON t2a.postalcode = t1.postalcode
LEFT JOIN table2 t2b ON t2b.postalcode = LEFT(t1.postalcode, LEN(t1.postalcode) - 1)
LEFT JOIN table2 t2c ON t2c.postalcode = LEFT(t1.postalcode, LEN(t1.postalcode) - 2)

This can take advantage of an index on table2(postalcode).  In addition, it only returns one row, even when there are multiple matches in table2, returning the best match.

A: Use JOIN.
Query
SELECT t1.col1 as name,
       coalesce(t2.col2,'-unknown-') as col2
FROM table_1 t1
LEFT JOIN table_2 t2
ON t1.pcode LIKE t2.col1 + '%';

SQL Fiddle

A: You can use:
on '1234AB' like '1234'+'%'

on firstTable.code like secondTable.code+'%'

In you Join search condition.

A: You can Use LEFT(column,4)
select t1.*, t2.col2
from table1 t1 join
     table2 t2
     on LEFT(t1.postalcode,4)=t2.postalcode


text:
Q: How to suppress blank lines with git log pretty format? I am trying to extend the git log --oneline format to show a little more information, specifically the committer and commit time.
The original command is git log --oneline --name-status
and produces this output:
[master] ~/temp/tempgit$ git log --oneline --name-status
809d815 (HEAD -> master) modified bar
M       bar.txt
352d6d3 modified foo
M       foo.txt
e4150f4 initial commit
A       bar.txt
A       baz.txt
A       foo.txt

I've duplicated this format with additional information as
git log --oneline --name-status --pretty='format:%C(yellow)%h %C(auto)%d %s %C(red)(%cn, %cr)'
and it produces this output:
[master] ~/temp/tempgit$ git log --oneline --name-status --pretty='format:%C(yellow)%h %C(auto)%d %s %C(red)(%cn, %cr)'
809d815 (HEAD -> master) modified bar (Mike Harvey, 29 seconds ago)
M       bar.txt

352d6d3 modified foo (Mike Harvey, 49 seconds ago)
M       foo.txt

e4150f4 initial commit (Mike Harvey, 2 minutes ago)
A       bar.txt
A       baz.txt
A       foo.txt

What I want to do is suppress the blank lines between log entries, but cannot find an option to remove it, nor why it is being inserted. The only difference here is that I am using a pretty format.
UPDATE: It seems there is no workaround, so I adapted Kjele's solution. Piping the output loses the color info, which I really wanted, so I forced it with -c color.ui=always.
This is the final version that does what I wanted:
git log ${REV}..HEAD --oneline --name-status -c color.ui=always --pretty=format:%C(yellow)%h %C(auto)%d %s %C(red)(%cn, %cr) | sed '/^\s*$/d'
Thanks!

A: You could pipe your command into:
sed '/^\s*$/d'

git log --oneline --name-status --pretty='format:%C(yellow)%h %C(auto)%d %s %C(red)(%cn, %cr)' |  sed '/^\s*$/d'

but this will not allow you to scroll down like you normally would.
A workaround could be to select the desired number of commits:
-n 10

git log --oneline --name-status --pretty='format:%C(yellow)%h %C(auto)%d %s %C(red)(%cn, %cr)' -n 10 |  sed '/^\s*$/d'

A: I also found that sed '/^$/d' works as well.  See tldp


text:
Q: Multithreaded backpropagation I have written a back propagation class in VB.NET -it works well- and I'm using it in a C# artificial intelligence project.
But I have a AMD Phenom X3 at home and a Intel i5 at school. and my neural network is not multi-threaded.
How to convert that back propagation class to a multithreaded algorithm? or how to use GPGPU programming in it? or should I use any third party libraries that have a multithreaded back propagation neural network?

A: JeffHeaton has recommend that you use resilient propagation (RPROP) instead of backpropagation. There are examples on how to do multithreaded RPROP (MPROP):

*

*Article on C# multithreaded backpropagation (from Jeff heaton)

*Chapter 7.2.1- "Propagation and Multithreading" (p.94 of Introduction to Encog 2.5 for C#)
It's a difficult to discuss all of the details here, so I would recommend that you either read that article and take a look at the relevant chapters of the book I referenced. This, of course, is assuming you're familiar with concurrent programming.
Update:

Resilient propagation will typically outperform backpropagation by a
  considerable factor. Additionally, RPROP has no parameters that must
  be set. Backpropagation requires that a learning rate and momentum
  value be specified. Finding an optimal learning rate and momentum
  value for backpropagation can be difficult. This is not necessary with
  resilient propagation.
  (source: Encog Machine Learning)

A: I've tried implementing multiple threads for RPROP batch processing, but it seemed it was always slower than using a single thread. I've tried to implement separately at the loop level "#pragma omp parallel" and by calculating the errors, gradients and weights in separate threads. In my interpretation, it seems that the computing done in each thread is too small to outcome the computing done in switching the threads and synchronizing the results (mutex.) I'm wondering if I've done something wrong? My conclusion is that would be smarter to run RPROP single-threaded, while processing multiple neuronal networks at the same time in separate threads. Most of the implementations usually imply multiple interconnected NNs so that would make sense.


text:
Q: eclipse launcher icon in kde I installed 14.04 with Unity on my new box. Works pretty good. I installed Eclipse under Unity, but still haven't been able to create a launcher that displays the Eclipse icon. For other reasons I installed kubuntu-desktop and would now like to create a desktop launcher for the already installed Eclipse.
Initially I did a search in kickstart and drug the icon onto the desktop. This launches Eclipse with no trouble, but it has only the default gear icon.
So then I went to Dolphin and browsed to /usr/share/applications and drug out the .deskktop file I created there for Unity onto the KDE desktop. Now I have a desktop icon that has the proper Eclipse icon. But when I click it, Eclipse doesn't launch.
How can I get one icon on the KDE desktop with the proper Eclipse Luna icon (which is /usr/share/icons/eclipse.png -- I converted the icon.xpm file and put it there) that actually launches Eclipse?
Update --
Two things were needed. I had the permissions wrong on the .png file. It needed to be readable by everyone. Then the .desktop file needed to look like this:
[Desktop Entry]
Comment[en_US]=
Comment=
Exec=/home/tarka/eclipse/eclipse
GenericName[en_US]=
GenericName=
Icon=eclipse
MimeType=
Name[en_US]=eclipse
Name=eclipse
Path=
StartupNotify=true
Terminal=false
TerminalOptions=
Type=Application
X-DBUS-ServiceName=
X-DBUS-StartupType=
X-KDE-SubstituteUID=false
X-KDE-Username=

The key piece as in the comment was the line Icon=eclipse. Still don't know why it wouldn't work with the full path.

A: Open the shortcut with some text editor like gedit or kate icon by right-clicking on it, and selecting "Open with gedit". In the text editor, shortly after the 'comment' and 'app command' text, you should see something like 'Icon=exec,' (ignore the quotes) change it to Icon=/usr/share/icons/eclipse.png or Icon=eclipse


text:
Q: unfortunately google play services has stopped in genymotion Hi friends I added google play service to genymotion emulator,I drag the zip files of gapps and also arm v1 to it but when I opening the emulator its getting unfortunately google play services has stopped and also when I am trying to add account in it showing loading.. can anyone tell me the solution for it.

A: I faced this same issue.This issue is generally due to not following order of
flashing Gapps appropriately.Being a beginner in  android programming.Well, I learnt following things to keep in mind while setting up google play services:

*

*Download the ARM Translation Installer v1.1 and drag and drop the zip file onto the running Genymotion emulator device. The ARM emulator is only needed for apps that trigger a

INSTALL_FAILED_CPU_ABI_INCOMPATIBLE

error.

*You must close and restart the emulator fully before continuing.

*The Google Play APK package needed is specific to the Android emulator version. You must use the corresponding Google Play Service package. Otherwise, you may notice problems with Google Play not having Internet connectivity or other strange issues.

*If you are using below listed specific versions ,sometimes files you are using get corrupted.
Solution:
Check android version and apk link for gapps to be flashed:

*

*Google Apps for Android 6.0 (see instructions for flashing)

1) (https://www.androidfilehost.com/?fid=96042739161891406 - gapps-L-4-21-15.zip)
2) (https://www.androidfilehost.com/?fid=24052804347835438 - benzo-gapps-M-20151011-signed-chroma-r3.zip)

*

*Google Apps for Android 5.1
(https://www.androidfilehost.com/?fid=96042739161891406 -
gapps-L-4-21-15.zip)

*Google Apps for Android 5.0
(https://www.androidfilehost.com/?fid=95784891001614559 -
gapps-lp-20141109-signed.zip)

*Google Apps for Android 4.4.4
(https://www.androidfilehost.com/?fid=23501681358544845 -
gapps-kk-20140606-signed.zip)

*Google Apps for Android 4.3
(https://www.androidfilehost.com/?fid=23060877490000124 -
gapps-jb-20130813-signed.zip)

*Google Apps for Android 4.2
(https://www.androidfilehost.com/?fid=2306087749000018 -
gapps-jb-20130812-signed.zip)

*Google Apps for Android 4.1
(https://www.androidfilehost.com/?fid=22979706399755082 -
gapps-jb-20121011-signed.zip)

Update or reinstall Genymotion and Virtual box :
If you are flashing all gapps apk correctly and you are still facing this issue.
You need to check which version of genymotion and virtual box you are using .Use latest version of genymotion and VB.
Uninstall Genymotion and Virtualbox :
If updating or re-installation doesn't work you  need to remove old registry files hidden in your computer which are preventing you from flashing Gapps properly.Repeat steps of flashing mentioned above.
Note: Don't forgot to restart genymotion after flashing files.
Hope it helps,Cheers..Happy Coding!!!

A: I had the same issue and found lots of solutions available on the internet. I followed the steps given in http://www.thecrazythinkers.com/how-to-fix-unfortunately-google-play-services-has-stopped/ and got a perfect solution.

A: To setup Google Play Service in your genymotion follow my answer in this question, hope it will help you. Question link


text:
Q: Database Location in Scheme I have a program which make use of a local database (sqlite3 and i use db module). What i want to do is using the database without knowing where it is.
For example, if i code the location of database in my program (like C:/my documents/my program/localdb.db), it is working correctly.
But if i just write "localdb.db", it doesn't find the database even if database is in the same folder with the .rkt file which use the database. (i dont know how but in earlier versions of my program, it was working).
Thus, how can i ensure to use the database without coding its location?
Thanks a lot!

A: Instead of "localdb.db", try using a runtime-path like this:
(define-runtime-path localdb "localdb.db")

and use localdb in place of the path string. You'll need to (require racket/runtime-path).


text:
Q: Execute some shell code before Maven package When I package a jar, the jar will include some files from the other directory. I want maven package to automatically to run a shell script to check if the dependency directory is clean and up-to-date. If the script returns non-zero, then maven packet should stop. Is that possible? If yes, how to implement?

A: See if the exec-maven-plugin can help in your case.
You can associate it to the package phase, as in this instance. It will fail the maven process if the script returns a non-zero status.


text:
Q: GitHub overwriting work on push. I've been working with a three man team using github and netbeans to work on the same project. On multiple occasions while working independently we've tried to merge our branches into the trunk which sometimes result in some of our changes being overwritten by the next commit and push/merge. Instead of trying to figure out what we're doing wrong would it be possible for someone to give me a quick description from the point of view of a single programmer as to how to get work from his branch to the main trunk without removing working that another programmer has done.
I could go with more detail but I'd just like Step 1, Step 2, ... Steps that all three of us can follow so to not step on each others toes. Assume we are fresh out of code monkey school and have never used Github. (Github is already setup on netbeans)

A: *

*Dev A & Dev B are working on the same branch

*Dev A & B start their day after a git clone or pull to have the same codebase.

*At some point Dev A will commit, and push his changes.

*When Dev B wants to also to commit his changes he should commit git commit -a -m "something", pull the changes git pull origin yourbranch, and push again git push origin yourbranch.

This step should create a merge commit because you have done a commit based on the history you had, and when you pull the changes it has to rewrite the history based on dev A.


text:
Q: How to add a value conditional in a array of object I have an array of object which looks like
@observable setting = [
    {
      collapseHeader: SettingsSectionDisplayName.Settings,
      section: SettingsSection.Settings,
      isSelected: isLogged() ? true :  false, ==> This does not work.
    }

  ]

So,Here I have a function which is
isLogged = () => {

return //boolean on some condition

}

Now, Here How can I set the value of a key isSelected on the basis of function returned result ?
It throws an error
TypeError: Object(...) is not a function

Can any one help me with this ?


text:
Q: Order by date and auto increment column (id), but order rows with same value for third column (oid) alphabetically by fourth column (ab) Following Quassnoi's answer I have edited to show what happens using his advice and added letters to the OID to show the problematic ordering.
I have a table in a mysql database that I first want to order by the date it was supposed to be added to the database.
SELECT * FROM table ORDER BY date_placed DESC;

Next where the date is the same I want to order by an auto incremented id. So I've added:
SELECT * FROM table ORDER BY date_placed DESC, id DESC;

I end up with something like this:

Date_Placed |  ID  |  OID   |  AB
05/01/2012  | 1100 |  A50   |  A
05/01/2012  | 1109 |  A50   |  B
05/01/2012  | 1108 |  B40   |  A
05/01/2012  | 1107 |  B40   |  B
04/01/2012  | 1106 |  C30   |  A
04/01/2012  | 1105 |  C30   |  B

The AB field will always only by A or B, and OID may either exist twice or be a unique value.
What I want now is in those cases where OID is duplicated, for B to come before A in the AB column. Note that ID will then be out of order to an extent.

Date_Placed |  ID  |  OID   |  AB
05/01/2012  | 1109 |  A50   |  B
05/01/2012  | 1110 |  A50   |  A
05/01/2012  | 1107 |  B40   |  B
05/01/2012  | 1108 |  B40   |  A
04/01/2012  | 1105 |  C30   |  B
04/01/2012  | 1106 |  C30   |  A

I'd prefer to do this on the mysql side since I'll be retrieving quite a few rows. Is this possible? If not in mysql then I am using php so what would be the best way to do it in that? Thank you in advance to anyone who can help.
Quassnoi's answer gives this:

Date_Placed |  ID  |  OID   |  AB
05/01/2012  | 1107 |  B40   |  B
05/01/2012  | 1108 |  B40   |  A
05/01/2012  | 1109 |  A50   |  B
05/01/2012  | 1110 |  A50   |  A
04/01/2012  | 1105 |  C30   |  B
04/01/2012  | 1106 |  C30   |  A

ID order is lost

A: SELECT  m.*
FROM    (
        SELECT  date_placed, oid, MAX(id) AS mid
        FROM    mytable
        GROUP BY
                date_placed, oid
        ) md
JOIN    mytable m
ON      (m.date_placed, m.oid) = (md.date_placed, md.oid)
ORDER BY
        m.date_placed DESC, mid DESC, ab DESC

If two conditions hold:

*

*id within a single oid are consecutive (no gaps between them), and

*B always goes before A in id order,

use this:
SELECT  *
FROM    mytable
ORDER BY
        date_placed DESC,
        CASE ab WHEN 'A' THEN id - 1 ELSE id END DESC,
        id

, without joins.


text:
Q: Prolog behavior I've been trying to learn Prolog by solving project euler. To solve problem #1, I came up with the following.
divides(X,Y) :- Y mod X =:= 0.

sumlist([],0).
sumlist([H|T],X) :-
    sumlist(T,Y), X is Y + H.

mult_3_or_5(X) :- between(1,999,X),
                  (divides(3,X); divides(5,X)).

find_sum(Z) :- findall(X,mult_3_or_5(X),Y),
               sumlist(Y,Z).

The problem with this is that it counts numbers that are divisible by both 3 and 5 twice. I certainly have a misunderstanding of how Prolog operates and I believe I need to use the cut operator or something like that. I would appreciate a good explanation of what's going on.


text:
Q: How code changes take affect immediately with docker-compose? I'm new to MEAN applications and currently working on a project. I have included both Front and Back end to a docker container. Application is build and run on a docker with no probs. My problem is when I want to perform changes in the code in both front and back.
Any changes performed are not taking place immediately. I read a couple of articles of how to do it but it was not very clear to me, probably the ones I've read. Please find below some data from my current project.
[Backend dockerfile]
# Dockerfile

FROM node:10.16.0-alpine
RUN mkdir -p /opt/app
WORKDIR /opt/app
RUN adduser --disabled-password app
COPY ./* ./
RUN chown -R app:app /opt/app
USER app
RUN npm install
CMD [ "npm","run", "start:dev" ]

[Front dockerfile]
# Dockerfile

FROM node:10.20.0-alpine AS builder
RUN apk add --no-cache git=2.24.3-r0 \
    --repository https://alpine.global.ssl.fastly.net/alpine/v3.10/community \
    --repository https://alpine.global.ssl.fastly.net/alpine/v3.10/main

COPY . ./app
WORKDIR /app
RUN npm i -g @angular/cli
RUN npm install
RUN ng build --prod --aot
# RUN $(npm bin)/ng build --prod --aot

# FROM nginx:1.15.8-alpine
# COPY --from=builder /app/dist/ /usr/share/nginx/html
EXPOSE 4200
#CMD [ "npm", "start" ]
CMD ng serve --host 0.0.0.0 --disable-host-check
# EXPOSE 80 443
# CMD [ "nginx", "-g", "daemon off;" ]

[docker-compose.yml]
version: "3.7"

services:
    evillio-backend:
        build:
            context: evillio-backend/
        ports:
            - '3000:3000'

    evillio-frontend:
        build:
            context: evillio-frontend/
        ports:
            - '4200:4200'

[Backend package.json]
"start": "node dist/main.js",
    "start-local": "nest start",
    "start:dev": "nest start",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",


text:
Q: Cant Map() Through An Array Of Objects Been trying to solve this one for quite a while now.
I am saving an array which contains objects to my data base,
When I try to map() through it to retrieve the object's properties its just rendering nothing.
This is the app.js code :
app.get("/:plasticcategory/product/:plasticproduct", (req, res) => {

   const plasticCategory = _.startCase(_.toLower(req.params.plasticcategory));

   const plasticProduct =  req.params.plasticproduct;

   Product.find({category: plasticCategory, title: plasticProduct},'alt', (err, foundItem) => {

     if(err){

       console.log(err)

     }else {

       console.log(foundItem);

      res.render('alternatives', {altProduct: foundItem});

     }

   });

 });

When I console.log(foundItem) the result is [ { _id: 5f5f9b2a9f999b1e9009072b, alt: [ [Object] ] } ]
This is my ejs code(trying to render the alt's array objects properties:
    <% altProduct.map(alt => {%>

<%=alt.altTitle %>

       <img src="<%=alt.altImage%>" alt="alt-image">

       <a href="<%=alt.altUrl %>">Get it now!

    <% }) %>

I have added images to make it more clear, Thank You <3
enter image description here

A: When you render the template, I see you call it like this:
res.render('alternatives', {altProduct: foundItem});

Where foundItem is the array [{ id: 'something', alt: [{ someObject }] }].
This is an array of results. Each of those results has a key called 'alt' with items in it. If you want to render all of those items together, you will need to compile them all into a single array. (This is called 'flat-mapping'.)
Starting inside the else block of the callback of Product.find:
const itemArrays = foundItem.map(item => item.alt); // Get the inner array from each result
const allAlternativeProducts = [].concat(...itemArrays); // Collect all these products into a single array
  res.render('alternatives', {altProduct: allAlternativeProducts});


text:
Q: Best way to import DB in Android I need some advices about good practices of importing data from server to local device. The amount of data is not very big ~1-3 MB So, I have to choose between:

*

*receive json - parsing it, using GSON lib for simplicity and insert data into local DB

*receive whole DB in cvs format and then to populate my DB like is described here

*or receive the whole DB directly from server side and use it somehow like local one

I know, each method works but if somebody can give some arguments it will be appreciated.

A: You can provide an already populated db with your app ( put it in your asset folder ).
Then all you have to do is keeping up to date the fields you have to update on the app using a timestamp field or any sql request to find the outdated fields or the entry which are not present in your db.
This way you avoid useless process in you app to populate the db, and you can limit the query to your server aiming the data after s specific time, this time being the last update of the database.

A: what worked for me was my php file was reading data from sql ...
so I used buffer reader to read content on those file its fast and easy
worked for me
public String getInternetData() throws Exception{

        BufferedReader in=null;
        String data=null;
        try{
            HttpClient client=new DefaultHttpClient();
            URI website=new URI("http://address of that paticular page.php");
            HttpGet request=new HttpGet();

            request.setURI(website);

            HttpResponse response=client.execute(request);
            HttpEntity ent=response.getEntity();
            String dt=EntityUtils.toString(ent);

            data=dt;
            //in=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        }catch(Exception e){

        }

        return data;

A: tl;dr;
I will keep the first solution.
Arguments
Solution 1
JSON is a standard ! You can use any library that you want and even change from to another if you have any problem ! Moreover, JSON is a lightweight format.
Also, transferring the data this way, you will be able to store as you want : with the same scheme or with another one; you will be able to remove useless data, ...
The only problem : you cannot validate that the data you received are like you think. You will have to handle the verification on your mobile.
Solution 2
I think that this solution is just the same that with the JSON one, but using a really ugly format... I will definitely not use it !
Solution 3
You will send a binary file through the network. If something bad happened, you will not be able to know it before trying to open the DB and see that it fails.
Moreover, you are stuck with the DB scheme that your server decides. I think it's way better to let your device handle the DB scheme by itself. The server is responsible to transfer correctly formatted data. Then, your device is responsible to store them the way it wants.


text:
Q: MTKView - Draw on to Two Views at Once What I got
I am following Apple sample code AVCamPhotoFilter to display camera feed on a MTKView.
What I am trying to do
In addition to above MTKView, I need to display a second MTKView.  However, the second one will be displaying exactly the same content as the first one.  So I do not want to duplicate the code and do work twice.
Current drawing method
override func draw(_ rect: CGRect) {
        var pixelBuffer: CVPixelBuffer?
        var mirroring = false
        var rotation: Rotation = .rotate0Degrees

        syncQueue.sync {
            pixelBuffer = internalPixelBuffer
            mirroring = internalMirroring
            rotation = internalRotation
        }

        guard let drawable = currentDrawable,
            let currentRenderPassDescriptor = currentRenderPassDescriptor,
            let previewPixelBuffer = pixelBuffer else {
                return
        }

        // Create a Metal texture from the image buffer
        let width = CVPixelBufferGetWidth(previewPixelBuffer)
        let height = CVPixelBufferGetHeight(previewPixelBuffer)

        if textureCache == nil {
            createTextureCache()
        }
        var cvTextureOut: CVMetalTexture?
        CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
                                                  textureCache!,
                                                  previewPixelBuffer,
                                                  nil,
                                                  .bgra8Unorm,
                                                  width,
                                                  height,
                                                  0,
                                                  &cvTextureOut)
        guard let cvTexture = cvTextureOut, let texture = CVMetalTextureGetTexture(cvTexture) else {
                print("Failed to create preview texture")

                CVMetalTextureCacheFlush(textureCache!, 0)
                return
        }

        if texture.width != textureWidth ||
            texture.height != textureHeight ||
            self.bounds != internalBounds ||
            mirroring != textureMirroring ||
            rotation != textureRotation {
            setupTransform(width: texture.width, height: texture.height, mirroring: mirroring, rotation: rotation)
        }

        // Set up command buffer and encoder
        guard let commandQueue = commandQueue else {
            print("Failed to create Metal command queue")
            CVMetalTextureCacheFlush(textureCache!, 0)
            return
        }

        guard let commandBuffer = commandQueue.makeCommandBuffer() else {
            print("Failed to create Metal command buffer")
            CVMetalTextureCacheFlush(textureCache!, 0)
            return
        }

        guard let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: currentRenderPassDescriptor) else {
            print("Failed to create Metal command encoder")
            CVMetalTextureCacheFlush(textureCache!, 0)
            return
        }

        commandEncoder.label = "Preview display"
        commandEncoder.setRenderPipelineState(renderPipelineState!)
        commandEncoder.setVertexBuffer(vertexCoordBuffer, offset: 0, index: 0)
        commandEncoder.setVertexBuffer(textCoordBuffer, offset: 0, index: 1)
        commandEncoder.setFragmentTexture(texture, index: 0)
        commandEncoder.setFragmentSamplerState(sampler, index: 0)
        commandEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
        commandEncoder.endEncoding()

        commandBuffer.present(drawable) // Draw to the screen
        commandBuffer.commit()
    }

Question
Is there a way I can simply pass on the texture to the second MTKView and draw without doing work twice?

A: If you set the framebufferOnly property of the first MTKView to false, you can submit commands which read from its drawable texture. Then, you can use a blit command encoder to copy from the first drawable's texture to the second's, if they are compatible. Otherwise, you can draw a quad to the second drawable's texture with the first drawable's texture as the source for texturing the quad.
Personally, I think I would prefer all of the rendering to go to a texture of your own creation (not any drawable's texture). Then, copy/draw that to both of the drawable textures.
In any case, if you need the two views to update in perfect sync, you should set presentsWithTransaction to true for both views, synchronously wait (using -waitUntilScheduled) for the command buffer that does (at least) the copy/draw to the drawable textures, and then call -present directly on both drawables. (That is, don't use -presentDrawable: on the command buffer.)


text:
Q: How to get a program's running time in Haskell How can I go about getting a program's running time through system time functions in Haskell? I would like to measure the execution time of a whole program and/or an individual function.

A: :set +s is really neat if use ghci, otherwise you can use Criterion.Measurement, see my answer to another question with example.

A: I'm not sure how accurate it is, but using :set +s in ghci will show the time and space used for subsequent computations.

A: 1) If you want to benchmark something, use the criterion package.
2) If you want to time a function and are positive you have controlled for laziness as needed, then just use Data.Time.getCurrentTime from the time package.:
import Data.Time
...
   start <- getCurrentTime
   runOperation
   stop <- getCurrentTime
   print $ diffUTCTime stop start

A slicker packaging of the above pattern can be found in the timeit package.
3) If you actually want the running time of a program that just happens to be written in Haskell then use your systems time utility.  For most POSIX systems (Mac, Linux) just run:
$ time ./SomeProgram

And it will report user, wall, and system time.

A: Assuming you don't just want to measure the total running time of your program, like so:
 $ time ./A

Then you can time a computation a number of ways in Haskell:

*

*Basic timing (e.g. as in the timeit package)

*Timing in cycles
For more statistically sound measurement, consider

*

*The Criterion package.

Finally, in all cases, you need to think about lazy evaluation: do you want to measure the cost of fully evaluating whatever data you produce, or just to its outermost constructor?


text:
Q: cant call a function on onclick event of button in react js i am working on a reactjs project and i have to call a function through onclick event of button but the problem is that function is already in another function so cant call it. its giving error that handleClickEvent function isn't declared. here is the code.
import React, { useState } from "react";

const Square = (props) => {
return (
<button
className="Square"
onClick={handleClickEvent}
>
{props.value}
</button>
 );
 };

 const Board = () => {
 const initialSquares = Array(9).fill(null);
 const [squares, setSquares] = useState(initialSquares);

 const handleClickEvent = (i) => {
    const newsquares = [...squares];
    newsquares[i] = "X";
    setSquares(newsquares);
   }
   }


text:
Q: Como fazer form filho alterar valores no form pai C#? Tenho um cadastro em C#. Existe um botão "pesquisa rua" que abre um form filho de pesquisa. Ao se executar a pesquisa, apresenta o resultado no datagrid desse form filho. Gostaria que o evento cell_click do datagrid completasse a combobox existente no form pai.

A: Nesse caso você pode passar o form pai como parâmetro para a classe, e através desse parâmetro (no caso o objeto do form pai) você pode interagir com o form pai.
Codigo do Form1:
public Form1()
{
       InitializeComponent();
}
    //botao que ABRE o FORM B
private void button1_Click(object sender, EventArgs e)
{
    Form2 formB = new Form2(this); //this, significa que estou passando ESSA classe (instância dela) como param
    formB.Show();
}

Codigo do Form2:
public partial class Form2 : Form
{
    Form1 instanciaDoForm1; //objeto do tipo FORM 1, que será usado dentro da classe
    //inicializador do FORM
    public Form2(Form1 frm1) //recebo por parametro um objeto do tipo FORM1
    {
        InitializeComponent();
        instanciaDoForm1 = frm1; //atribuo a instancia recebida pelo construtor a minha variavel interna
        //associo o mesmo texto do tbxTextBoxFormA ao meu FORM B
        txtTextBoxFormB.Text = instanciaDoForm1.txtTextBoxFormA.Text.ToString();
    }
    //botao alterar
    private void button1_Click(object sender, EventArgs e)
    {
        //passo para a textbox do FORM A o mesmo texto que está na minha do FORM B
        instanciaDoForm1.txtTextBoxFormA.Text = txtTextBoxFormB.Text.ToString();
        instanciaDoForm1.txtTextBoxFormA.Refresh(); //recarrego ela
    }
}

Assim é possível interagir com o grid da mesma forma que foi feita com o textbox.
Artigo adaptado do meu amigo Fernando Passaia
http://www.linhadecodigo.com.br/artigo/1741/trocando-informacoes-entre-windows-forms-em-csharp.aspx

A: Não é uma boa prática delegar essa responsabilidade para o formulário filho. Em geral seria responsabilidade do formulário pai (que contém o combobox) modificar o conteúdo deste combo. Você pode criar o formulário filho como uma fonte de dados (o trabalho dele seria listar os itens e dizer qual foi selecionado)
Ao exibir o formulário com um "ShowDialog" você recebe um enum com o resultado daquele form (OK, Cancelar, etc) e pode usar esta flag para saber se o usuário não fechou a tela sem selecionar nada.
Para obter o item selecionado você pode, através de propriedades, expor o conteúdo do form filho. Isso permite que esse formulário filho seja utilizado por qualquer formulário pai.
public class Cidade
{
    public string Nome { get; set; }
}

public partial class FormPai : Form
{
    private void btnObterCidade_Click(object sender, EventArgs e)
    {
        var seletorCidade = new SeletorCidade();
        var resultadoSeletor = seletorCidade.ShowDialog();

        if (resultadoSeletor == DialogResult.OK)
        {
            var cidadeSelecionada = seletorCidade.CidadeSelecionada;
            comboCidade.SelectedItem = cidadeSelecionada;
        }
    }
}

public partial class SeletorCidade : Form
{
    public Cidade CidadeSelecionada { get; set; }

    private void btnOk_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.OK;
    }

    private void btnCancelar_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.Cancel;
    }
}

A: Uma boa maneira de fazer isso em C# é criar um evento no Form filho.
Por exemplo:
public event Action<String> EnderecoSelecionado;

Quando você criar o Form filho no Form pai, você se registra neste evento:
formFilho.EnderecoSelecionado += enderecoSelecionado_event;

Quando o usuário clicar no grid do Form filho, você verifica se existe funções registradas no evento, se houver você o executa:
if( EnderecoSelecionado != null ) {
    EnderecoSelecionado( o_endereco_selecionado );
}

Desta forma a interface entre Pai e Filho ficará bem explicita e o mesmo evento pode ser reaproveitado em outras partes da sua aplicação.
Este é uma expressão idiomatica comum do C# e poucas vezes me arrempedi de usa-la.

A: O jeito mais fácil de fazer isso é criar uma variável publica no FormFilho e usar o ShowDialog() para chamaer ele com o DialogResult, assim, quando clicar no datagrid vc chama este código:
Declaração no formFilho
public int codigo { get; set; }

Comando do click
codigo = valor;
DialogResult = DialogResult.OK;

Chamada do formFilho no FormPai
Form2 formFilho = new Form2();
if (formFilho.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
     comboBox1.SelectedValue = formFilho.codigo;
}

A: É possível resolver o seu problema passando a referência do pai para o filho. Imagino que você cria uma instância dessa Form filha dentro da Form pai, sendo assim, basta passar a referência da seguinte forma:
Na Form pai
FormFilha container = new FormFilha(this);

Na Form filha
private FormPai parent = null;
public FormFilha(FormPai _parent){
  this.parent = _parent;
}

A partir daí é possível controlar a Form pai de dentro da Form filha, inclusive elementos que estejam internos a FormPai, como o ComboBox por exemplo, desde que a referência para esse elemento tenha nível de encapsulamento public.

A: Pra mim funcionou assim.
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    // no meu caso quis pegar um Objeto do form filho.
    private Cliente cliente = null;
    public Cliente Cliente {
        get { return cliente; }
        set { cliente = value; }
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        Form2 filho = new Form2();
        filho.Pai = this;
        filho.Show();
        Visible = false;
    }
}

Agora no Form filho.
public partial class Form2 : Form
{
    public Form2
    {
        InitializeComponent();
    }

    private Form1 pai = null;
    public Form1 Pai {
        get { return pai; }
        set { pai = value }
    }

    private void Button1_click(object sender, EventArgs e)
    {
        Cliente cliente = new Cliente(long.parse(textBox1.Text));
        pai.Cliente = cliente;
        pai.Visible = true;
        this.Close();
    }
}

desta forma eu chamo o filho, passo o pai para um atributo dentro do filho e retorno um objeto para o form pai.
tentei de outras formas porém no meu Visual Studio 2017 essas outras formas estavam iniciando um Form vazio que não era o que eu estava iniciando.
e na hora de passar o Objeto do Filho para o pai, estava dando um erro de estância nula(null).
espero ter ajudado.

A: Você pode fazer via Eventos / delegados [a qual acho mais robusto], retorno de valores com variável estática em classe terceira, passagem do formulário via argumento para alteração de propriedades e, também há uma possibilidade que ninguém cita - acho que é a mais complicada - você PODE acessar a informação diretamente através da lista de formulários abertos [Application.OpenForms], encontrá-lo e alterar a propriedade.
O Ponto negativo é, se você mudar o nome do controle ou formulário, terá que alterá-lo também no código, tornando mais complicado a manutenção.
Fiz um projeto de exemplo para ficar mais simples o entendimento:

*

*frmMain - formulário Pai

*frmSearch - form pesquisa

*No frmMain, crio um TextBox, com nome txtEx

*Chamo o formulário Pesquisa frmSearch . Aberto o frmSearch , chamo o clique de botão e nele Tento alterar o controle pai:

Exemplo:
// Inicio
private void button1_Click(object sender, EventArgs e)
    {
        TextBox myText = (TextBox)Application.OpenForms["frmMain"].Controls["txtEx"];

        myText.Text = "10";

        this.Dispose();
    }

Pronto, quando retorno ao formulário frmMain, o valor "10" está escrito no TextBox.
Tenha cuidado, se você errar o nome do formulário ou do controle, irá se deparar com o lançamento de um System.NullReferenceException. Trate este código.
Uso:
// Acesse: Application.OpenForms["NomeDoFormulário"]  e Controls["NomeDoControle"]
// Declara um controle TextBox, que servirá de ponteiro para o seu controle no formulário pai
// Faz a Conversão explícita de tipo de Controle (para poder alterar as propriedades) [(TextBox) ObjetoXYZ]
TextBox myText = (TextBox) Application.OpenForms["frmMain"].Controls["txtEx"];

// Altera de fato a propriedade
myText.Text = "XYZ";

// Encerra seu formulário Filho
this.Dispose();

Simplificando:
(Application.OpenForms["frmMain"].Controls["txtEx"] as TextBox).Text = "Meu valor";


text:
Q: Interfacing and extending ApplicationClass I am trying to write a module in F#, making it easier working with Excel, by extracting rows, columns, etc. along with type casting and so on. One of the first things I wanted to do, was to extend various classes/types to implement the IDisposable interface. I tried to write something like the following
type Excel.ApplicationClass with
    interface IDisposable with
        member this.Dispose() =
            this.excel.Quit()
            Marshal.ReleaseComObject(this.excel) |> ignore

What I wasn't aware of, was that I would get the following error "All implemented interfaces should be declared on the initial declaration of the type".
My question is the following: Since I am not allow to extend a type with an interface - what else could I do?

A: If you inherit from the base class it can work, like this
type myAppClass() =
    inherit Excel.ApplicationClass() //may not be correct signature - you need to match the base constructor
    interface IDisposable with
        member this.Dispose() =
            //function body


text:
Q: How can I control the visual affect with Camera class? I've checked the document:
http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/media/Camera.html
But still don't find info on how to control the visual affect(like lightness, saturation and so on) of my pc camera.
Is that kind of job possible with actionscript?

A: You can't alter the actual Camera data (there is a difference between that and what I am describing further), but it's possible to do what you want easily, after attaching the Camera object to a Video object and using the variety of transformation filters and routines from other native ActionScript classes like ColorTransform, DisplayObject.transform.colorTransform and DisplayObject.filters, to alter what is displayed on the screen/memory, which, I believe, is probably what you want anyway.
To give you a real world usage example, you can adjust saturation of the camera data being displayed in your video with the following code:
/// Desaturate displayed image completely
video.filters = [ new ColorMatrixFilter(saturation_filter_matrix(0)) ];

where I have defined the methods as:
static inline var RWGT = 0.3086;
static inline var GWGT = 0.6094;
static inline var BWGT = 0.0820;

static public function brightness_filter_matrix(b: Float)
{
    return [    b, 0, 0, 0, 0,
                0, b, 0, 0, 0,
                0, 0, b, 0, 0,
                0, 0, 0, 1, 0 ];
}

static public function saturation_filter_matrix(s: Float)
{
    var b = (1 - s) * RWGT;
    var a = b + s;
    var d = (1 - s) * GWGT;
    var e = d + s;
    var g = (1 - s) * BWGT;
    var i = g + s;

    return [    a, d, g, 0, 0,
                b, e, g, 0, 0,
                b, d, i, 0, 0,
                0, 0, 0, 1, 0 ];
}

static public function contrast_filter_matrix(v: Float)
{
    v += 1;

    var r = v;
    var g = v;
    var b = v;

    return [    r, 0, 0, 0, 128 * (1 - r),
                0, g, 0, 0, 128 * (1 - g),
                0, 0, b, 0, 128 * (1 - b),
                0, 0, 0, 1, 0 ];
}

I also think that transform.colorTransform may be more efficient with doing the same job, somehow I have observed that filters tend to tax Adobe Flash Player to moderate to high degree, so be advised.
The implications of the fact that you cannot change actual camera input, are that when you publish your camera across network (to Flash Media Server for instance), no matter what effects you use to display the data in your own video object, the party playing the stream will see the original unaltered data. A "workaround" would be to announce to the receiving party the exact parameters you want them to apply to their video object that is playing the stream. Assuming they apply these parameters in the same way you do for your displayed camera image, they will see your camera image the way you see it.
Note: The code is written in Haxe, but the two languages are very similar. The changes you need to be aware of are (blatant advertisement for Haxe follows :-) Float in Haxe is Number in ActionScript 3 for example, and Haxe uses type inference which makes it possible to omit variable types at will, letting Haxe figure it out itself (when you add two int's what do you get? On Flash platform, you always get an int as well.) Also AS3 does not have the concept of inlining (yet?) and so you must simply remove inline syntax from the code, that's all.

A: In response to your comment regarding accessing the camera data directly, the only area I can think of where this would be an issue is if you are recording to a FMS (flash media server, Red5, wowza etc), in which case the data comes directly out of the camera and into the netstream (netStream.attachCamera(cam)). For this there is no direct workaround, you could maybe store the brightness and contrast settings (from a filter effect) as flv metadata when you publish/stream the video, but then the person on the other end would have to decode this metadata (i.e. playback using a Flash component or something that can decode AMF data), for this see the setDataFrame method of NetConnection
For everything else you can use the methods suggested above, take the cam, shove it into a Video instance with video.attachCamera and then use video.filters = [myFilter] to apply the effect you desire. If you want to get down and dirty with the pixels you could use the draw property of a BitmapData object to draw the camera image from the video onto a bitmap for manipulation, you must however do this on an enterFrame or Timer to keep the bitmapData in sync.
var video:Video = new Video(w,h);
video.attachCamera(Camera.getCamera());
var bmd:BitmapData = new BitmapData(w,h);
bmd.draw(video);

Hope this is helps


text:
Q: How to translate a 'where' mySQL query to method syntax? I want to write a mySQL read query:
    String query = "SELECT  * FROM " + MY_TABLE
            + "where phone=" + phone + "AND isBloacked =1";

how can I transform this to method syntax?
    Cursor cursor = getReadableDatabase().query(MY_TABLE,
            new String[] { "phone" }, "phone", new String[] {}, null, null,
            null);

A: Your 3rd parameter is basically a WHERE clause, just without the word WHERE.
public Cursor query (String table, String[] columns,
    String selection, String[] selectionArgs,
    String groupBy, String having, String orderBy, String limit)

From the method signature the selection is the WHERE clause, and selectionArgs allows you to add parameters outside of the string.
For example, for your query you may want to do something like:
Cursor cursor = getReadableDatabase().query(MY_TABLE,
        new String[] { "phone" },
        "phone = ? AND isBloacked = ?", new String[] { phone, "1" },
        null, null, null);

A: The most efficient and probably the most convenient way for you is to use .rawQuery, which also returns a Cursor, just as simple .query. I assume it's good since you obviously know what to write in it, and it works a tiny bit faster. Here it goes:
Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + MY_TABLE
    + " WHERE phone = " + phone + " AND isBloacked = 1", new String[]{phone});


text:
Q: joining tables with merge command in R I have two tables that I'd like to join using the column "SPENO", but am receiving this error:
Error in fix.by(by.x, x) : 'by' must specify a uniquely valid column

Here are the commands I'm using:
setwd("P:/Users/Richmond/PEP_tagData")

read.csv("pepdeployments.csv", header=TRUE)
read.csv("pepdeployments_endDate.csv", header=TRUE)

pep_deploy1 <- "pepdeployments.csv"
pep_deploy2 <- "pepdeployments_endDate.csv"

combined <- merge(x=pep_deploy1,y=pep_deploy2,by.x="SPENO",by.y="SPENO")

Any suggestions on what I'm doing wrong? Thanks.

A: You are not reading your data in correctly. You need to assign the read.csv(...) to an object
setwd("P:/Users/Richmond/PEP_tagData")

pep_deploy1 <- read.csv("pepdeployments.csv", header=TRUE)
pep_deploy2 <- read.csv("pepdeployments_endDate.csv", header=TRUE)

combined <- merge(x=pep_deploy1,y=pep_deploy2,by.x="SPENO",by.y="SPENO")

What you're doing is:
Reading in the .csv file, but just printing it to the console. It's not being assigned to any objects:
read.csv("pepdeployments.csv", header=TRUE)
read.csv("pepdeployments_endDate.csv", header=TRUE)

Then assigning the strings pepdeployments.csv and pepdeployments_endDate.csv to the objects. So your objects are just those strings, not the data.
pep_deploy1 <- "pepdeployments.csv"
pep_deploy2 <- "pepdeployments_endDate.csv"


text:
Q: C++ self-referencing array? I accidentally created a bug in a program by self-referencing in an array. Here's a very simplified demo program similar in concept:
#include <iostream>
using namespace std;

int kTest[] = {
    kTest[0]
};

int main() {
    cout << kTest[0] << endl;
}

I was surprised that I received neither a compiler error or even a warning on this code! In my case it ended up producing unpredictable output. Is it accessing garbage memory?
I was curious about under what circumstances this would have well-defined output (if ever!).
Edit: Does it make a difference if kTest is static? What about const? Both?

A: I'm not so sure this is undefined. Quote from the current draft:

[basic.start.static]/3
If constant initialization is not performed, a variable with static
  storage duration ([basic.stc.static]) or thread storage duration
  ([basic.stc.thread]) is zero-initialized ([dcl.init]). Together,
  zero-initialization and constant initialization are called static
  initialization; all other initialization is dynamic initialization.
  Static initialization shall be performed before any dynamic initialization takes place.

To me it looks like kTest is already zero-initialized when the dynamic initialization starts, so it may be defined to initialize to 0.

A: int kTest[] = {
    kTest[0]
};

is similar to, if not exactly same as
int x = x;

It will be undefined behavior, if declared locally in a function.
It seems to be well defined when kTest is a global variable. See the other answer for additional details.


text:
Q: Problem with linker script (undefined reference to `puts') So, here is my problem.
I have been trying to link an .asm with a .c file using a ld script, but all I get is
hello.c:(.text+0xa): undefined reference to `puts'
My files are as follows:
bootinit.asm:

    global main
    extern zain

    KERNEL_STACK_SIZE equ 4096                  ; size of stack in bytes

        section .bss
        align 4                                     ; align at 4 bytes
        kernel_stack:                               ; label points to beginning of memory
            resb KERNEL_STACK_SIZE                  ; reserve stack for the kernel
            mov esp, kernel_stack + KERNEL_STACK_SIZE   ; point esp to the start of the
                                                    ; stack (end of memory area)

    section .text
    main:
        mov ecx,'A'
        mov edx, 1
        int 0x80
        call zain
        ret

hello.c:

    #include <stdio.h>

    void zain(){
            printf("Hello! \n\n");

    }

linker.ld:

    ENTRY(main)

    MEMORY {
        bootsector(rwx) : ORIGIN = 0x70000, LENGTH = 50k
    }

makefile:
    ARCH_PREFIX:=i386
    LINKER=linker.ld

    LDFLAGS = \
        -T$(LINKER)

    C_FILES := $(shell find ./ -type f -name '*.c' | sort)
    ASM_FILES := $(shell find ./ -type f -name '*.asm' | sort)
    OBJ := $(ASM_FILES:.asm=.o) $(C_FILES:.c=.o)

    all:  bootFinal.bin

    bootFinal.bin: bootinit.elf
        objcopy --binary-architecture=i386:x86-64  --remove-section=.comment $< $@

    bootinit.elf: $(OBJ)
        ld  -melf_x86_64 -T$(LINKER) $(OBJ)  -o $@

    %.o: %.asm
        nasm $< -f elf64  -o $@

    %.o: %.c
        gcc -I/usr/include  -m64 -libc  -Wall -Wextra -Werror  -c -o $@ $<

The .c and the .asm can be linked without problem and call one another if I run
gcc -m64 $(OBJ) -o $@
instead of the corresponding ld command, but this doesn't take into account the linker.ld .
I tried the -lc option but it doesn't work either.
I use fedora 33 if that plays any role.
Any suggestions?

A: To integrate an assembly file into a normal C program, you just write your assembly code and link it in the program as normal.  For example, you can simply do
main.asm
        global  main:function
        extern  zain
        section .text
main:   push    rbp
        mov     rbp, rsp
        call    zain
        pop     rbp
        ret

hello.c
#include <stdio.h>

void zain(){
        printf("Hello! \n\n");
}

and then assemble, compile, and link like this:
nasm -felf64 main.asm
cc -o hello main.o hello.c

This'll do the right thing and you end up with a working binary.  There's no need to write linker scripts, initialisation code, stack set up code, or to even invoke the linker yourself.  Just let the C compiler deal with all this.
One caveat is that you need to fulfil the AMD64 SysV ABI whenever you call C functions.  This not only mandates which arguments go into which registers, but also tells you that the stack pointer must be aligned to a multiple of 16 on function call.  For this reason, a push rbp; mov rbp, rsp prologue is used.  It pushes 8 bytes on the stack to restore the alignment that was lost when the startup code pushed the return address of main.


text:
Q: Finding determinant of matrix through row operations [problem help]? I am having trouble understanding a problem that my Linear Algebra class gave. I understand that determinants can be found through row operations with the following points:

1.) Adding a multiple of one row to another - Doesn't change the determinant.
  2.) Interchanging two rows - Reverse the sign of the determinant.
  3.) Scaling a row by some constant $s$- Multiplies the determinant by that constant $s$.

Finally, we take it as noted that the determinant of the elementary square matrix is 1.
Here is the problem with the work they provide for solving it:

Now, I understand you can use the simple short cut of multiplying across the diagonal but I am confused about the long way of finding it (with the rules above).
You can see that to make this turn into the elementary matrix you must:

1.) Multiply row 2 by 1/2 2.) Multiply row 3 by 1/7

According to the scaling rule for finding determinants with row operations (number 3 above), I must scale the determinate by 1/2 and then by 1/7, not 2 and then 7. Why did they do it by 2 and 7? What is flawed in my understanding here?

A: Okay, I was able to figure it out with some help.
The reason why they multiplied by 7 and 2 is because of this fundamental point:

The determinate of the elementary matrix is 1.

By solving this problem, starting with some square matrix A, we are basically working backwards to get the determinant as we reduce to the elementary matrix.
When given a 3 x 3 elementary matrix (pertaining to the example above), to obtain a second row with the value of: [0, 2, 0]

We must multiply the elementary matrix by 2 and because we know that det(I) = 1, we used rule 3 (from my question above) to scale the determinate by 2.
This concept is then applied to the third row for which we scale this already scaled determinate by 7. This gives up the final value of 14, like how pictured in the slides above.
Basically I can reason that when given some square (n x n) matrix A, if we scale a row in A by some constant c, then we scale the elementary matrix's determinate by 1/c.
Because rule 1 and rule 2 don't deal with any specific numbers exactly, this is the only rule we need to alter to be forwards compatible.


text:
Q: Voice recognition program works sporadically I am not sure why but it only finds, converts and transcribes all of the mp3 files in the directory occasionally but never 100 percent of the time.  I am not sure why.  I hope I am asking in the right place.    My goal is to find all m4a files and then convert to wav files and then find all wav files and transcribe them.  The program does this some of the time but not all of the time.
#!/usr/bin/env python3

    import speech_recognition as sr
    import time
    import subprocess
    import os
    from os import path
    from os import listdir

    # find and convert mp3 files to wav files

    # find all files with an extension, convert to wav files, transcribe to text file then transfer all wav files and mp3 files to finished directory and email transcribed files.

    # find files with mp3 extension

    def list_files1(directory, extension):
        ext = []
        for root, dirs, files in os.walk(directory):
            for file in files:
                if file.endswith(extension):
                    ext.append(file)
        print(ext)
        return ext

    # get directory path
    originalDir = os.getcwd()

    # call function to find files with mp3 extension
    mp3files = list_files1(originalDir, "m4a")

    # os.chdir("/Users/williamjohnson/Dropbox/goodscrapers/publimaison2/")

    # convert all mp3 files to wav files
    for x in mp3files:
        print(x)
        timestr = time.strftime("%Y%m%d-%H%M%S")
        command = "ffmpeg -i " + x + ' ' + timestr + ".wav"
        print(command)
        subprocess.call(command, shell=True)

    # find all converted wav files

    wavfiles = list_files1(originalDir, "wav")

    for y in wavfiles:
        print(y)
        # obtain path to "english.wav" in the same folder as this script
        AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), y)
        # AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "french.aiff")
        # AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "chinese.flac")

        # use the audio file as the audio source
        r = sr.Recognizer()
        with sr.AudioFile(AUDIO_FILE) as source:
            audio = r.record(source)  # read the entire audio file

        # recognize speech using Sphinx
        try:
            print("Sphinx thinks you said " + r.recognize_sphinx(audio))
            timestr = time.strftime("%Y%m%d-%H%M%S")
            text_file = open(timestr + ".txt", "a")
            text_file.write(r.recognize_sphinx(audio))
            text_file.close()
        except sr.UnknownValueError:
            print("Sphinx could not understand audio")
        except sr.RequestError as e:
            print("Sphinx error; {0}".format(e))

Edit:It was a really dumb mistake that I was making, I was naming all outputted text files with the same name so they were being overwritten I made sure to give them a unique name by going down to the millisecond as the name and then adding a random number to the file name for good measure.

A: When you use os.walk(), it returns the files without any directory so you are collecting a list of files but discarding their directory name.
Your wrapper does not seem to be adding any value over os.walk(); I would refactor to convert one file at a time anyway.  Tangentially, you also don't need to call getcwd if you don't particularly care about the absolute path to the current directory.
import os

def get_next_file(directory, extension):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(extension):
                yield os.path.join(root, file)

for x in get_next_file('.', 'm4a'):
    print(x)


text:
Q: jqGrid - I have a column say ColumnA but needs to load from a different list for the Add Form In the grid I show "Column A" field from a user editable database table via a java servlet returning XML type.  But when the user clicks on the "Add", I need this field "Column A" in the add form to be a select list that is loaded from a different database table, e.g. a lookup/reference table that allows the user to choose from a list of available values.  How can I do that? Is there way to set a data URL that loads a field but only that particular field in the Add Form only?

A: I do not know if I understand correctly the question..
but i think you need in col model to define the edit type and edit dataUrl..
Try this
{
     name:'Column A',
     index:'Column A',
     editable:true,
     edittype:'select',
     editoptions:{
          dataUrl:'your/url/for/data/data.php'
     }
}


text:
Q: Signal safety of __sync_fetch_and_add() I have a program that accepts socket clients and forks a child process. To keep the count of the child processes, I am using a global variable and atomic functions are used for incrementing and decrementing the count.
I am concerned about the signal safety of __sync_fetch_and_add(). Is there a possibility of deadlock when the multiple childs are connecting and disconnecting frequently.
Below is a snippet of my code.
   int main()
   {
            ...
            signal(SIGCHLD, handle_sigchild);
            ...
            if ((pid = fork()) == -1) {
                close(sock);
                continue;
            } else if (pid > 0) { //Parent
                __sync_fetch_and_add(&counter, 1);
                close(sock);
                continue;
            } else if (pid == 0) {
            ...
            }
        ...
    }

    // Signal Handler
    void handle_sigchild(int arg)
    {
        while( waitpid(-1, NULL, WNOHANG) > 0){
            __sync_fetch_and_add(&counter, -1);
        }
        signal(SIGCHLD, handle_sigchild);
    }

A: Atomic functions are typically implemented as a loop around a critical instruction that performs the actual operation, and that can fail in which case it needs to be retried.
Any conflict would cause the critical instruction to fail, and that also goes for conflicts introduced by signal handlers.
For example, fetch-and-add is typically something like
.L2:
    lwarx 10,0,3
    addi 9,10,1
    stwcx. 9,0,3
    bne 0,.L2
    extsw 3,10
    blr

So the value is loaded and a reservation made, then incremented, then stored back if the reservation is still valid. If that failed, we restart with fetching the new value (since it is likely that someone wrote in the meantime).
On Intel, this process is hidden inside
    mov     eax, 1
    lock xadd       DWORD PTR [rdi], eax
    ret

On old machines, this would indeed have locked the entire bus for the duration of the add instruction, on newer, it silently generates a loop in microcode that repeatedly tries to increment the value.
Any interrupt (which would be necessary to deliver a signal) would just extend the time between load and store, which makes it more likely that the current iteration fails to update the value because something else was faster.


text:
Q: Delete words in Word Document that are not in Excel list I'm working on a school project where I have a lot of Word Documents and I want to remove all words in those documents that are not on a specific list that I have in Excel. I've never worked with both Excel and Word and I've used clunky find and delete options in both individually but I have a lot of documents and doing this in a brute force method seems like it'll take too long.
The documents I have are transcripts of conversations so I want to keep the words chronologically in the same place if possible, but I want to remove filler words that are not related to the words I am interested in. I have a list of words that I am interested in in an Excel document, but I'm not sure how to search through the whole document and have the words that are not in my Excel list deleted.
EDIT: I've found a lot of find and replace macros but I'm trying to figure out how to have every word that is not on my excel list deleted.
Thank you all in advance for your time.

A: For example, supposing you have an Excel workbook named WordList.xlsx in your Documents folder:
Sub Demo()
Application.ScreenUpdating = False
Dim xlApp As Object, xlWkBk As Object, StrWkBkNm As String
Dim xlFList As String, i As Long
StrWkBkNm = "C:\Users\" & Environ("Username") & "\Documents\WordList.xlsx"
If Dir(StrWkBkNm) = "" Then
  MsgBox "Cannot find the designated workbook: " & StrWkBkNm, vbExclamation
  Exit Sub
End If
'Get the folder to process
strFolder = GetFolder
If strFolder = "" Then Exit Sub
On Error Resume Next
'Start Excel
Set xlApp = CreateObject("Excel.Application")
If xlApp Is Nothing Then
  MsgBox "Can't start Excel.", vbExclamation
  Exit Sub
End If
On Error GoTo 0
With xlApp
  'Hide our Excel session
  .Visible = False
  ' The file is available, so open it.
  Set xlWkBk = .Workbooks.Open(StrWkBkNm, False, True)
  If xlWkBk Is Nothing Then
    MsgBox "Cannot open:" & vbCr & StrWkBkNm, vbExclamation
    .Quit: Set xlApp = Nothing: Exit Sub
  End If
  ' Process the workbook.
  With xlWkBk
    With .Worksheets(1)
      ' Find the last-used row in column A and capture the F data.
      For i = 1 To .Cells(.Rows.Count, 1).End(-4162).Row ' -4162 = xlUp
        ' Skip over empty fields to preserve the underlying cell contents.
        If Trim(.Range("A" & i)) <> vbNullString Then xlFList = xlFList & "|" & Trim(.Range("A" & i))
      Next
    End With
    .Close False
  End With
  .Quit
End With
' Release Excel object memory
Set xlWkBk = Nothing: Set xlApp = Nothing
'Exit if there are no data
If xlFList = "" Then Exit Sub
strFile = Dir(strFolder & "\*.doc", vbNormal)
'Process each document in the folder
While strFile <> ""
  If strFolder & "\" & strFile <> strDocNm Then
    Set wdDoc = Documents.Open(FileName:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
    'Process each word from the F/R List
    With wdDoc
      With .ActiveWindow.View
        bHid = .ShowHiddenText
        .ShowHiddenText = True
      End With
      'Format all content as hidden text
      .Range.Font.Hidden = True
      With .Range.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Font.Hidden = True
        .Replacement.Font.Hidden = False
        .Format = True
        .Forward = True
        .MatchWholeWord = True
        .Wrap = wdFindContinue
        .Replacement.Text = "^& "
        'Unhide each item from the Find List
        For i = 1 To UBound(Split(xlFList, "|"))
          .Text = Split(xlFList, "|")(i)
          .Execute Replace:=wdReplaceAll
        Next
        'Delete any remaining hidden text
        .Replacement.ClearFormatting
        .MatchWholeWord = False
        .Text = ""
        .Replacement.Text = ""
        .Execute Replace:=wdReplaceAll
      End With
      .ActiveWindow.View.ShowHiddenText = bHid
      'Close the document
      .Close SaveChanges:=True
    End With
  End If
  'Get the next document
  strFile = Dir()
Wend
Set wdDoc = Nothing
Application.ScreenUpdating = True
End Sub

Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function


text:
Q: Hiding some URL parameters, but not all (with .htaccess) I have URL like that
  test/users?p=show

and i made it to be like
test/users/show

by using rule:
 RewriteRule  ^users/(\w+)$      users.php?p=$1 [L]

Parameter p could be different and it contains words as arguments, but i would like to add some additional parameters to it in some situations. When im using
  test/users?p=show&wg=1

it works, but i'd like to work it with
test/users/show&wg=1 or test/users/show?wg=1

How to achieve that effect ??
Is it even possible to add parameters with & to already made rule like that (it could be 1 to 4 additional parameters) ??

A: Simple add QSA:
RewriteRule  ^users/(\w+)$      users.php?p=$1 [QSA,L]

Then it will also pass your parameters into query string.