text:
Q: How to set active profile on Spring Boot while building bootJar? how to set profile just for the executable (jar) built by calling bootJar task? Ideally, it would override (or add) a property in application.properties inside the jar or something like that.

A: I expect he is trying to do exactly what we are. In maven one can do something along these lines:
<profile>
  <id>openshift</id>
  <properties>
    <activatedProperties>openshift</activatedProperties>
  </properties>
</profile>

Which can be used to replace @activatedProperties@ in application.properties to, e.g., openshift. If this is the case, we solved it by modifying build.gradle as follows:
import org.apache.tools.ant.filters.ReplaceTokens

# whatever you have here

def springProfile = project.hasProperty("profile") ? profile : ""
bootRun {
    systemProperties["spring.profiles.active"] = springProfile
}

processResources {
    with copySpec {
        from "src/main/resources/"
        filter(ReplaceTokens, tokens: ["activatedProperties": springProfile])
    }
}

and in the application.properties have:
spring.profiles.active=@activatedProperties@

However, I would like to note that we consider this a temporary hack. Build scripts should not be modifying files, even if it's limited to resource files. A more correct approach would be to use templates in a separate location and output those to the resources. Or even better (which is what we will do in due time), fix the deployment setup, so it's part of the deployment configuration, as it should be.

A: You can provide spring.profiles.active=dev,mysql in your application/bootstrap.properties file of your spring boot application.
Or while running the jar you can provide the active profile as argument,
java -jar fatJar.jar --spring.profiles.active=dev,mysql


text:
Q: Updating tcl/tk version of Homebrew python3 on macOS My environment:
macOS 10.13
python 3.7.1 from Homebrew
I'm having lots of Tcl/TK quirks on the stock Tcl/TK 8.5 under /System/Library/Frameworks/Tcl.framework/Versions/8.5/, and would like to upgrade my Tcl/TK.
But with this question I couldn't find any working tips for upgrading, including:

*

*https://discussions.apple.com/thread/8066794

*IDLE warns against an old TCL version even though I've installed a newer version

*Why my Python installed via home brew not include Tkinter

*How to change the tk version of your Python installation?

*How do I link the ActiveState distribution of Tcl/Tk to HomeBrew installed Python
My test results

*

*--with-tcl-tk no longer works with the latest Homebrew. Running brew install python --with-tcl-tk still points to system Tcl/TK 8.5.9.

*The above is also tested with an uninstall/install cycle.

*Python keeps using system Tcl/TK after installing latest ActiveTcl.

A: After many more failures, I concluded that the easiest way to make this work is to completely forget about Homebrew, uninstall its python packages.
Then install the latest ActiveTcl and then the python.org version instead. The python.org version will work on top of the latest "System" Tcl/TK, which will be refreshed after installing the ActiveTcl. Unfortunately, Homebrew ignores it.
The current 3.7.2 from python.org is compiled with Tcl/TK 8.6.8:
$ python3
Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter as tk
>>> print(tk.Tcl().eval('info patchlevel'))
8.6.8

After updating it, several bugs like checkbuttons showing wrong checkmarks on a menu disappeared.

A: This post provides a neat way:
https://stackoverflow.com/a/60469203/10606936
NOT NEEDED to use actviveTk or python.org python installation.
Keypoint is  provide the correct ENV for installtion.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue with Jupyter notebook and virtual environment pip I have created a virtual environment using the following commands:
python3 -m venv venv
.\venv\Scripts\activate.bat
pip3 install ipykernel
pip3 install jupyter
python3 -m ipykernel install --user --name=venv

I have created a Jupyter notebook using the venv that I created, but when I install a package in the virtual environment, it is not recognised in the notebook.
For example, I tried to install pandas using pip3 install pandas, but when I try and import it into my notebook I get the error ModuleNotFoundError: No module named 'pandas'
The module has installed in the right place venv\Lib\site-packages\pandas\
Any ideas on what I should do?
EDIT:
I noticed that even though I created the notebook using the venv, it uses the normal python environment rather than the virtual one. Ideas on how to fix this?

A: Well I think I solved it. If ran the following command:
python -c "import IPython"

Which just installs IPython in my venv.

A: You need to restart the notebook kernel, it will probably work then.
In the future, in a notebook cell you can run
%%bash
pip install pandas

then you should be able to continue without restarting


text:
Q: I want to integrate XERO to WebAPI C# Can someone provide me sample code for oauth2 I have tried the below
        XeroConfiguration xeroConfig = new XeroConfiguration();
        xeroConfig.ClientId = "****";
        xeroConfig.ClientSecret = "****";
        xeroConfig.CallbackUri = new Uri("http://localhost"); //default for standard webapi template
        xeroConfig.Scope = "openid profile email files accounting.transactions accounting.contacts offline_access";
        var client2 = new XeroClient(xeroConfig, httpClientFactory);
        var test = client2.BuildLoginUri();

        return Redirect(client2.BuildLoginUri());

After redirection it is giving below error
Error code: 500 Error: unauthorized_client : Invalid redirect_uri

A: It is because you have registered your app in the Authorization Server using a different redirect URI and in the above you are using a different redirect URI which will be validated by the Authorization Server and on mismatch, it is throwing you the Error.
You have to register your app with the Redirect URI that you will be using
Ex: If your app is running in http://localhost:6500 and your redirect URI to receive the token and process is http://localhost:6500/login. You have to provide this value to the Authorization Server.
ex: The setting would look like
xeroConfig.CallbackUri = new Uri("http://localhost:6500/login")


text:
Q: Is is possible to have a bidirectional edge in Cytoscape.js? I want to make a network graph that looks similar to this below image.
Click on this link to view the image
I have searched across and have not found a solution for this using Cytoscape.

A: Yes, you can create bidirectional edges in Cytoscape.js. First, the curve-styles of your edges should be different than 'haystack' (below I set it as 'straight'), because 'haystack' doesn't support edge endpoint arrows. Second, you need to specify source and target endpoint arrow shapes. Possible values for arrow shapes are listed here (I used 'triangle-backcurve' below). If you want one directional edge, you can set the arrow shape only for source or target.

var cy = window.cy = cytoscape({
  container: document.getElementById('cy'),

  style: [{
      selector: 'node',
      css: {
        'content': 'data(id)',
        'text-valign': 'center',
        'text-halign': 'center'
      }
    },
    {
      selector: 'edge',
      css: {
        'curve-style': 'straight',
      }
    }
  ],
  elements: {
    nodes: [{
        data: {
          id: 'n0'
        }
      },
      {
        data: {
          id: 'n1'
        }
      },
      {
        data: {
          id: 'n2'
        }
      },
      {
        data: {
          id: 'n3'
        }
      }
    ],
    edges: [{
        data: {
          id: 'n0n1',
          source: 'n0',
          target: 'n1'
        }
      },
      {
        data: {
          id: 'n1n2',
          source: 'n1',
          target: 'n2'
        }
      },
      {
        data: {
          id: 'n2n3',
          source: 'n2',
          target: 'n3'
        }
      }
    ]
  }
});

cy.getElementById('n0n1').style({'source-arrow-shape': 'triangle-backcurve', 'target-arrow-shape': 'triangle-backcurve'});
cy.getElementById('n1n2').style({'target-arrow-shape': 'triangle-backcurve'});
cy.getElementById('n2n3').style({'source-arrow-shape': 'triangle-backcurve'});
body {
  font: 14px helvetica neue, helvetica, arial, sans-serif;
}

#cy {
  height: 95%;
  width: 95%;
  left: 0;
  top: 0;
  position: absolute;
}

  <meta charset=utf-8 />
  <meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">


text:
Q: The cursor is already open..I have multiple cursors in my stored procedure ALTER Procedure [dbo].[SELECT_SANSTHA_DEVIANCE](@DIVISION_ID int, @ZONE_ID int, @WARD_ID int, @ELECTORAL_ID int,
           @VASTI_ID int, @SANSTHA_ID int, @MONTH int, @YEAR int)
  As
    Begin
        DECLARE @ID INT
        DECLARE @SANSTHA INT

        DECLARE @USER table(USER_ID int, DATE_OF_VISIT date, TOTAL_MARKS int, SANSTHA_ID int)

        DECLARE CUR1 CURSOR FOR
        Select Distinct USER_ID From INSPECTION_RATING_MASTER

        DECLARE CUR2 CURSOR FOR
        Select Distinct SANSTHA_ID From INSPECTION_RATING_MASTER

        OPEN CUR1
        FETCH CUR1 INTO @ID
        WHILE @@FETCH_STATUS = 0
        BEGIN

            OPEN CUR2
            FETCH CUR2 INTO @SANSTHA
            WHILE @@FETCH_STATUS = 0
                BEGIN
                     Insert Into @USER
                            Select Top 2 USER_ID, DATE_OF_VISIT, SUM(TOTAL) As 'MARKS', SANSTHA_ID
                            From INSPECTION_RATING_MASTER
                            Where USER_ID = @ID
                            And SANSTHA_ID = @SANSTHA
                            And Month(DATE_OF_VISIT) = Case When @MONTH = -1 Then Month(DATE_OF_VISIT) Else @MONTH End
                            And Year(DATE_OF_VISIT) = @YEAR
                            Group By DATE_OF_VISIT, USER_ID, SANSTHA_ID
                            Order By DATE_OF_VISIT Desc
                FETCH NEXT FROM CUR2 INTO @SANSTHA

                END

                FETCH NEXT FROM CUR1 INTO @ID
            END

        Close CUR2
        DEALLOCATE CUR2

        Close CUR1
        DEALLOCATE CUR1

        Select D.DIVISION_NAME, Z.ZONE_NAME,
               W.WARD_NAME, E.ELEC_COUNCILOR_NAME, V.VASTI_NAME,S.SANSTHA_NAME, UI.FIRST_NAME + ' ' + UI.LAST_NAME As 'NAME',
               Convert(Varchar,U.DATE_OF_VISIT,105) As 'DATE_OF_VISIT', '160' As 'TOTAL_MARKS', U.TOTAL_MARKS As 'MARKS_OBTAINED'
               From @USER U
               Inner Join SANSTHA_POOL_MASTER S On U.SANSTHA_ID = S.ID
               Inner Join MASTER_DATA M On U.SANSTHA_ID = M.SANSTHA_ID And U.USER_ID = M.USER_INFO_ID
               Inner Join DIVISION_MASTER D On M.DIVISION_ID = D.ID
               Inner Join ZONE_MASTER Z On M.ZONE_ID = Z.ID
               Inner Join WARD_MASTER W On M.WARD_ID = W.ID
               Inner Join ELEC_COUNCILOR_MASTER E On M.EC_ID = E.ID
               Inner Join VASTI_MASTER V On M.VASTI_ID = V.ID
               Inner Join USER_INFO_MASTER UI On M.USER_INFO_ID = UI.ID
               Where M.DIVISION_ID = Case When @DIVISION_ID = -1 Then M.DIVISION_ID Else @DIVISION_ID End
               And M.ZONE_ID = Case When @ZONE_ID = 0 Then M.ZONE_ID Else @ZONE_ID End
               And M.WARD_ID = Case When @WARD_ID = 0 Then M.WARD_ID Else @WARD_ID End
               And M.EC_ID = Case When @ELECTORAL_ID = 0 Then M.EC_ID Else @ELECTORAL_ID End
               And M.VASTI_ID = Case When @VASTI_ID = 0 Then M.VASTI_ID Else @VASTI_ID End
               And M.SANSTHA_ID = Case When @SANSTHA_ID = 0 Then M.SANSTHA_ID Else @SANSTHA_ID End
               And Month(U.DATE_OF_VISIT) = Case When @MONTH = -1 Then Month(U.DATE_OF_VISIT) Else @MONTH End
               And Year(U.DATE_OF_VISIT) = @YEAR

        Select D.DIVISION_NAME, Z.ZONE_NAME, W.WARD_NAME, E.ELEC_COUNCILOR_NAME, V.VASTI_NAME, S.SANSTHA_NAME,
               UI.FIRST_NAME + ' ' + UI.LAST_NAME As 'NAME', MAX(TOTAL_MARKS) - MIN(TOTAL_MARKS) As 'VARIANCE'
               From @USER U
               Inner Join SANSTHA_POOL_MASTER S On U.SANSTHA_ID = S.ID
               Inner Join MASTER_DATA M On U.SANSTHA_ID = M.SANSTHA_ID And U.USER_ID = M.USER_INFO_ID
               Inner Join DIVISION_MASTER D On M.DIVISION_ID = D.ID
               Inner Join ZONE_MASTER Z On M.ZONE_ID = Z.ID
               Inner Join WARD_MASTER W On M.WARD_ID = W.ID
               Inner Join ELEC_COUNCILOR_MASTER E On M.EC_ID = E.ID
               Inner Join VASTI_MASTER V On M.VASTI_ID = V.ID
               Inner Join USER_INFO_MASTER UI On M.USER_INFO_ID = UI.ID
               Where M.DIVISION_ID = Case When @DIVISION_ID = -1 Then M.DIVISION_ID Else @DIVISION_ID End
               And M.ZONE_ID = Case When @ZONE_ID = 0 Then M.ZONE_ID Else @ZONE_ID End
               And M.WARD_ID = Case When @WARD_ID = 0 Then M.WARD_ID Else @WARD_ID End
               And M.EC_ID = Case When @ELECTORAL_ID = 0 Then M.EC_ID Else @ELECTORAL_ID End
               And M.VASTI_ID = Case When @VASTI_ID = 0 Then M.VASTI_ID Else @VASTI_ID End
               And M.SANSTHA_ID = Case When @SANSTHA_ID = 0 Then M.SANSTHA_ID Else @SANSTHA_ID End
               And Month(U.DATE_OF_VISIT) = Case When @MONTH = -1 Then Month(U.DATE_OF_VISIT) Else @MONTH End
               And Year(U.DATE_OF_VISIT) = @YEAR
               Group By D.DIVISION_NAME, Z.ZONE_NAME, W.WARD_NAME, E.ELEC_COUNCILOR_NAME, V.VASTI_NAME,
                        S.SANSTHA_NAME, UI.FIRST_NAME, UI.LAST_NAME
        --Select USER_ID, SANSTHA_ID, MAX(TOTAL_MARKS) - MIN(TOTAL_MARKS) As 'DIFF'
        --     From @USER
        --     Group By USER_ID, SANSTHA_ID;
        End

A: You are opening CUR2 within the CUR1 loop without closing/deallocating it first
Before
FETCH NEXT FROM CUR1 INTO @ID

you need to put your
Close CUR2
DEALLOCATE CUR2


text:
Q: past simple versus past perfect Should I write:

*

*He wrote in his last email that he did not find the time to do it yet, but was going to do it pretty soon . In fact he  has still not done it.

*He wrote in his last email that he had not found  the time to do it yet, but was going to do it pretty soon. In fact he has still not done it.

What is the difference?
(I am thinking that #2 is better.)

A:
He wrote in his last email that he had not found the time to do it yet, but was going to do it pretty soon.

The sentence above would be used more often, although I believe both are technically correct. As for the last sentence, I would say "He still has not done it".

A: Grammatically speaking, both the sentences are correct. The only difference is that when the speaker says he did not find (or hasn't found) the time to do it yet, it means that he has not done it so far because he has not had the time (maybe because he is still busy doing other work). On the other hand, when he says he had not found the time to do it yet, it means that he did not do it in the past because he didn't have the time (but now he has got the time to do it). So it is up to the speaker which situation he wants to express in the email.

A: Actually, it should be "he has/had not find the time to do it yet". You cannot use past simple because of the adverb "yet". Remember that this is reported speech, so you can used present or past participle according to the context.
In my opinion it would be better to write: "He wrote in his last email that he has not found the time to do it yet, but was going to do it pretty soon. however, he still has not done."


text:
Q: Can a single point be considered a function? A relation is defined as a set of ordered pairs. A set can include a single point. A function is a relation. Does that mean a single point can be considered a function? Say you have the point (1,0). There is a unique output for the input, but does there need to be multiple inputs and multiple outputs?

A: Yes, $\{(1,0)\}$ is a function. For that matter, $\emptyset$ is a function. A function can have a domain of any size, including $1$ and $0$.

A: In my view, any point can be considered function. Specifically, any function with a single answer and a single element may be a function.
For example, {{1},{0}} can be Considered a function if the answer for f{1}~ {0} and the set contains the single element. Thank you for the cooperation.
A function can also have a single element.


text:
Q: Force close on break point Has anybody experienced getting a forced close on their apps because of a breakpoint? When I try to run normally, the app does not close.
It also gives this error on the logcat:
09-11 23:46:35.346 32708-32708/com.xxxxxxx.xxxxxxxx A/libc: Fatal signal 11
(SIGSEGV), code 1, fault addr 0x28 in tid 32708 (jumblednameofapplicationclass)


text:
Q: Logstash file / csv filter not working I'm trying to parse a csv file with logstash in order to load on elasticsearch. This filter works on logstash 1.4 but no after upgrade to logstash 2.3. No error given in execution, neither in debug mode, but not work.
The filter is the following
input {
file {
        path => "/usr/local/scripts/get_billinginfo/csv/aws-billing-detailed-line-items-with-resources-and-tags-2016-04.csv"
        start_position => beginning
        type => "billing_info"
        sincedb_path => "/dev/null"
        ignore_older => "2592000000"
    }
}

filter {
        if [type] == "billing_info" {
                csv {
                columns => [
                "InvoiceID",
                "PayerAccountId",
                "LinkedAccountId",
                "RecordType",
                "RecordId",
                "ProductName",
                "RateId",
                "SubscriptionId",
                "PricingPlanId",
                "UsageType",
                "Operation",
                "AvailabilityZone",
                "ReservedInstance",
                "ItemDescription",
                "UsageStartDate",
                "UsageEndDate",
                "UsageQuantity",
                "Rate",
                "Cost",
                "ResourceId",
                "aws_autoscaling_groupName",
                "aws_cloudformation_stack-id",
                "aws_cloudformation_stack-name",
                "user_Name",
                "user_Project"
                ]
                separator => ","
                remove_field => ["message"]
                }
                 if [InvoiceID] == "InvoiceID" {
                        drop { }
                }
                 if [RecordType] == "Rounding" {
                        drop { }
                }
                 if [RecordType] == "StatementTotal" {
                        drop { }
                }
                 if [RecordType] == "InvoiceTotal" {
                        drop { }
                }

        date {
                match => ["UsageStartDate", "yyyy-MM-dd HH:mm:ss"]
        }
        mutate {
                convert => {
                        "UsageQuantity" => "float"
                        "Rate" => "float"
                        "Cost" => "float"
                        "ResourceId" => "float"
                }
                gsub => ["ProductName", " ", "_"]
                gsub => ["UsageType", "-", "_"]
                gsub => ["UsageType", "\.", "_"]
                gsub => ["aws_autoscaling_groupName", "-", "_"]
                gsub => ["aws_cloudformation_stack-id", "-", "_"]
                gsub => ["aws_cloudformation_stack-name", "-", "_"]
                gsub => ["user_Name", "-", "_"]
                gsub => ["user_Project", "-", "_"]

        }
        }
}

output {
        if [type] == "billing_info" {
        elasticsearch {
        index => "detailed-billing-aws-%{+YYYY.MM}"
                document_type => "billing_details"
                hosts => "somehost.somedomain.net"
                }

        }
}

No output is received, neither if i change to stdout output. Files are touched in order to be fresh, I've tried to add info at the end of the file during execution time ... Any ideas is working for me.
This logstash filter was working previously on a 1.4 logstash installation. Now i've updated to 2.3 and doesn't work.
The debug output is the following
Reading config file {:config_file=>"/usr/local/scripts/get_aws_billinginfo/load_billinginfo.conf", :level=>:debug, :file=>"logstash/config/loader.rb", :line=>"69", :method=>"local_config"}
Plugin not defined in namespace, checking for plugin file {:type=>"input", :name=>"file", :path=>"logstash/inputs/file", :level=>:debug, :file=>"logstash/plugin.rb", :line=>"76", :method=>"lookup"}
Plugin not defined in namespace, checking for plugin file {:type=>"codec", :name=>"plain", :path=>"logstash/codecs/plain", :level=>:debug, :file=>"logstash/plugin.rb", :line=>"76", :method=>"lookup"}
config LogStash::Codecs::Plain/@charset = "UTF-8" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@path = ["/usr/local/scripts/get_billinginfo/csv/aws-billing-detailed-line-items-with-resources-and-tags-2016-04.csv"] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@start_position = "beginning" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@type = "billing_info" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@sincedb_path = "/dev/null" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@ignore_older = 2592000000 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@codec = <LogStash::Codecs::Plain charset=>"UTF-8"> {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@add_field = {} {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@stat_interval = 1 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@discover_interval = 15 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@sincedb_write_interval = 15 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@delimiter = "\n" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Inputs::File/@close_older = 3600 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
Plugin not defined in namespace, checking for plugin file {:type=>"filter", :name=>"csv", :path=>"logstash/filters/csv", :level=>:debug, :file=>"logstash/plugin.rb", :line=>"76", :method=>"lookup"}
config LogStash::Filters::CSV/@columns = ["InvoiceID", "PayerAccountId", "LinkedAccountId", "RecordType", "RecordId", "ProductName", "RateId", "SubscriptionId", "PricingPlanId", "UsageType", "Operation", "AvailabilityZone", "ReservedInstance", "ItemDescription", "UsageStartDate", "UsageEndDate", "UsageQuantity", "Rate", "Cost", "ResourceId", "aws_autoscaling_groupName", "aws_cloudformation_stack-id", "aws_cloudformation_stack-name", "user_Name", "user_Project"] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::CSV/@separator = "," {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::CSV/@remove_field = ["message"] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::CSV/@add_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::CSV/@remove_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::CSV/@add_field = {} {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::CSV/@periodic_flush = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::CSV/@source = "message" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::CSV/@quote_char = "\"" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::CSV/@autogenerate_column_names = true {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::CSV/@skip_empty_columns = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::CSV/@convert = {} {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
Plugin not defined in namespace, checking for plugin file {:type=>"filter", :name=>"drop", :path=>"logstash/filters/drop", :level=>:debug, :file=>"logstash/plugin.rb", :line=>"76", :method=>"lookup"}
config LogStash::Filters::Drop/@add_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@remove_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@add_field = {} {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@remove_field = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@periodic_flush = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@percentage = 100 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@add_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@remove_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@add_field = {} {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@remove_field = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@periodic_flush = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@percentage = 100 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@add_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@remove_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@add_field = {} {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@remove_field = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@periodic_flush = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@percentage = 100 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@add_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@remove_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@add_field = {} {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@remove_field = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@periodic_flush = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Drop/@percentage = 100 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
Plugin not defined in namespace, checking for plugin file {:type=>"filter", :name=>"date", :path=>"logstash/filters/date", :level=>:debug, :file=>"logstash/plugin.rb", :line=>"76", :method=>"lookup"}
config LogStash::Filters::Date/@match = ["UsageStartDate", "yyyy-MM-dd HH:mm:ss"] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Date/@add_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Date/@remove_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Date/@add_field = {} {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Date/@remove_field = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Date/@periodic_flush = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Date/@target = "@timestamp" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Date/@tag_on_failure = ["_dateparsefailure"] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
Plugin not defined in namespace, checking for plugin file {:type=>"filter", :name=>"mutate", :path=>"logstash/filters/mutate", :level=>:debug, :file=>"logstash/plugin.rb", :line=>"76", :method=>"lookup"}
config LogStash::Filters::Mutate/@convert = {"UsageQuantity"=>"float", "Rate"=>"float", "Cost"=>"float", "ResourceId"=>"float"} {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Mutate/@gsub = ["ProductName", " ", "_", "UsageType", "-", "_", "UsageType", "\\.", "_", "aws_autoscaling_groupName", "-", "_", "aws_cloudformation_stack-id", "-", "_", "aws_cloudformation_stack-name", "-", "_", "user_Name", "-", "_", "user_Project", "-", "_"] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Mutate/@add_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Mutate/@remove_tag = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Mutate/@add_field = {} {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Mutate/@remove_field = [] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Filters::Mutate/@periodic_flush = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
Plugin not defined in namespace, checking for plugin file {:type=>"output", :name=>"elasticsearch", :path=>"logstash/outputs/elasticsearch", :level=>:debug, :file=>"logstash/plugin.rb", :line=>"76", :method=>"lookup"}
starting agent {:level=>:info, :file=>"logstash/agent.rb", :line=>"207", :method=>"execute"}
starting pipeline {:id=>"main", :level=>:info, :file=>"logstash/agent.rb", :line=>"461", :method=>"start_pipeline"}
Settings: Default pipeline workers: 4
Registering file input {:path=>["/usr/local/scripts/get_billinginfo/csv/aws-billing-detailed-line-items-with-resources-and-tags-2016-04.csv"], :level=>:info, :file=>"logstash/inputs/file.rb", :line=>"171", :method=>"register"}
config LogStash::Codecs::Plain/@charset = "UTF-8" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@index = "detailed-billing-aws-%{+YYYY.MM}" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@document_type = "billing_details" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@hosts = ["172.16.230.48"] {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@codec = <LogStash::Codecs::Plain charset=>"UTF-8"> {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@workers = 1 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@manage_template = true {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@template_name = "logstash" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@template_overwrite = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@parent = nil {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@flush_size = 500 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@idle_flush_time = 1 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@upsert = "" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@doc_as_upsert = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@max_retries = 3 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@script = "" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@script_type = "inline" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@script_lang = "" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@script_var_name = "event" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@scripted_upsert = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@retry_max_interval = 2 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@retry_max_items = 500 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@retry_on_conflict = 1 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@action = "index" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@path = "/" {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
_globbed_files: /usr/local/scripts/get_billinginfo/csv/aws-billing-detailed-line-items-with-resources-and-tags-2016-04.csv: glob is: [] {:level=>:debug, :file=>"filewatch/watch.rb", :line=>"346", :method=>"_globbed_files"}
config LogStash::Outputs::ElasticSearch/@ssl_certificate_verification = true {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@sniffing = false {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
config LogStash::Outputs::ElasticSearch/@sniffing_delay = 5 {:level=>:debug, :file=>"logstash/config/mixin.rb", :line=>"153", :method=>"config_init"}
Normalizing http path {:path=>"/", :normalized=>"/", :level=>:debug, :file=>"logstash/outputs/elasticsearch/http_client_builder.rb", :line=>"14", :method=>"build"}
Elasticsearch HTTP client options {:hosts=>["http://172.16.230.48:9200/"], :ssl=>nil, :transport_options=>{:socket_timeout=>0, :request_timeout=>0, :proxy=>nil}, :transport_class=>Elasticsearch::Transport::Transport::HTTP::Manticore, :level=>:debug, :file=>"logstash/outputs/elasticsearch/http_client.rb", :line=>"127", :method=>"build_client"}
Using mapping template from {:path=>nil, :level=>:info, :file=>"logstash/outputs/elasticsearch/template_manager.rb", :line=>"6", :method=>"install_template"}
Attempting to install template {:manage_template=>{"template"=>"logstash-*", "settings"=>{"index.refresh_interval"=>"5s"}, "mappings"=>{"_default_"=>{"_all"=>{"enabled"=>true, "omit_norms"=>true}, "dynamic_templates"=>[{"message_field"=>{"match"=>"message", "match_mapping_type"=>"string", "mapping"=>{"type"=>"string", "index"=>"analyzed", "omit_norms"=>true, "fielddata"=>{"format"=>"disabled"}}}}, {"string_fields"=>{"match"=>"*", "match_mapping_type"=>"string", "mapping"=>{"type"=>"string", "index"=>"analyzed", "omit_norms"=>true, "fielddata"=>{"format"=>"disabled"}, "fields"=>{"raw"=>{"type"=>"string", "index"=>"not_analyzed", "ignore_above"=>256}}}}}], "properties"=>{"@timestamp"=>{"type"=>"date"}, "@version"=>{"type"=>"string", "index"=>"not_analyzed"}, "geoip"=>{"dynamic"=>true, "properties"=>{"ip"=>{"type"=>"ip"}, "location"=>{"type"=>"geo_point"}, "latitude"=>{"type"=>"float"}, "longitude"=>{"type"=>"float"}}}}}}}, :level=>:info, :file=>"logstash/outputs/elasticsearch/template_manager.rb", :line=>"8", :method=>"install_template"}
Found existing Elasticsearch template. Skipping template management {:name=>"logstash", :level=>:debug, :file=>"logstash/outputs/elasticsearch/http_client.rb", :line=>"30", :method=>"template_install"}
New Elasticsearch output {:class=>"LogStash::Outputs::ElasticSearch", :hosts=>["172.16.230.48"], :level=>:info, :file=>"logstash/outputs/elasticsearch/common.rb", :line=>"19", :method=>"register"}
Will start workers for output {:worker_count=>1, :class=>LogStash::Outputs::ElasticSearch, :level=>:debug, :file=>"logstash/output_delegator.rb", :line=>"77", :method=>"register"}
Adding type with date config {:type=>nil, :field=>"UsageStartDate", :format=>"yyyy-MM-dd HH:mm:ss", :level=>:debug, :file=>"logstash/filters/date.rb", :line=>"301", :method=>"setupMatcher"}
Starting pipeline {:id=>"main", :pipeline_workers=>4, :batch_size=>125, :batch_delay=>5, :max_inflight=>500, :level=>:info, :file=>"logstash/pipeline.rb", :line=>"188", :method=>"start_workers"}
Pipeline main started {:file=>"logstash/agent.rb", :line=>"465", :method=>"start_pipeline"}
Flushing buffer at interval {:instance=>"#<LogStash::Outputs::ElasticSearch::Buffer:0x73031cf0 @operations_mutex=#<Mutex:0x7dc4ece0>, @max_size=500, @operations_lock=#<Java::JavaUtilConcurrentLocks::ReentrantLock:0x79fb7780>, @submit_proc=#<Proc:0x57768928@/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-output-elasticsearch-2.6.2-java/lib/logstash/outputs/elasticsearch/common.rb:57>, @logger=#<Cabin::Channel:0xd0fdcca @metrics=#<Cabin::Metrics:0x2f6aed9c @metrics_lock=#<Mutex:0x5cd61994>, @metrics={}, @channel=#<Cabin::Channel:0xd0fdcca ...>>, @subscriber_lock=#<Mutex:0x3f8ae4ef>, @level=:debug, @subscribers={12448=>#<Cabin::Subscriber:0x346e844b @output=#<Cabin::Outputs::IO:0x589821eb @io=#<IO:fd 1>, @lock=#<Mutex:0x305d0b8b>>, @options={}>}, @data={}>, @last_flush=2016-05-11 16:01:01 +0200, @flush_interval=1, @stopping=#<Concurrent::AtomicBoolean:0x78b7799e>, @buffer=[], @flush_thread=#<Thread:0x38bbe61f run>>", :interval=>1, :level=>:debug, :file=>"logstash/outputs/elasticsearch/buffer.rb", :line=>"90", :method=>"interval_flush"}
Flushing buffer at interval {:instance=>"#<LogStash::Outputs::ElasticSearch::Buffer:0x73031cf0 @operations_mutex=#<Mutex:0x7dc4ece0>, @max_size=500, @operations_lock=#<Java::JavaUtilConcurrentLocks::ReentrantLock:0x79fb7780>, @submit_proc=#<Proc:0x57768928@/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-output-elasticsearch-2.6.2-java/lib/logstash/outputs/elasticsearch/common.rb:57>, @logger=#<Cabin::Channel:0xd0fdcca @metrics=#<Cabin::Metrics:0x2f6aed9c @metrics_lock=#<Mutex:0x5cd61994>, @metrics={}, @channel=#<Cabin::Channel:0xd0fdcca ...>>, @subscriber_lock=#<Mutex:0x3f8ae4ef>, @level=:debug, @subscribers={12448=>#<Cabin::Subscriber:0x346e844b @output=#<Cabin::Outputs::IO:0x589821eb @io=#<IO:fd 1>, @lock=#<Mutex:0x305d0b8b>>, @options={}>}, @data={}>, @last_flush=2016-05-11 16:01:02 +0200, @flush_interval=1, @stopping=#<Concurrent::AtomicBoolean:0x78b7799e>, @buffer=[], @flush_thread=#<Thread:0x38bbe61f run>>", :interval=>1, :level=>:debug, :file=>"logstash/outputs/elasticsearch/buffer.rb", :line=>"90", :method=>"interval_flush"}
Flushing buffer at interval {:instance=>"#<LogStash::Outputs::ElasticSearch::Buffer:0x73031cf0 @operations_mutex=#<Mutex:0x7dc4ece0>, @max_size=500, @operations_lock=#<Java::JavaUtilConcurrentLocks::ReentrantLock:0x79fb7780>, @submit_proc=#<Proc:0x57768928@/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-output-elasticsearch-2.6.2-java/lib/logstash/outputs/elasticsearch/common.rb:57>, @logger=#<Cabin::Channel:0xd0fdcca @metrics=#<Cabin::Metrics:0x2f6aed9c @metrics_lock=#<Mutex:0x5cd61994>, @metrics={}, @channel=#<Cabin::Channel:0xd0fdcca ...>>, @subscriber_lock=#<Mutex:0x3f8ae4ef>, @level=:debug, @subscribers={12448=>#<Cabin::Subscriber:0x346e844b @output=#<Cabin::Outputs::IO:0x589821eb @io=#<IO:fd 1>, @lock=#<Mutex:0x305d0b8b>>, @options={}>}, @data={}>, @last_flush=2016-05-11 16:01:03 +0200, @flush_interval=1, @stopping=#<Concurrent::AtomicBoolean:0x78b7799e>, @buffer=[], @flush_thread=#<Thread:0x38bbe61f run>>", :interval=>1, :level=>:debug, :file=>"logstash/outputs/elasticsearch/buffer.rb", :line=>"90", :method=>"interval_flush"}
Flushing buffer at interval {:instance=>"#<LogStash::Outputs::ElasticSearch::Buffer:0x73031cf0 @operations_mutex=#<Mutex:0x7dc4ece0>, @max_size=500, @operations_lock=#<Java::JavaUtilConcurrentLocks::ReentrantLock:0x79fb7780>, @submit_proc=#<Proc:0x57768928@/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-output-elasticsearch-2.6.2-java/lib/logstash/outputs/elasticsearch/common.rb:57>, @logger=#<Cabin::Channel:0xd0fdcca @metrics=#<Cabin::Metrics:0x2f6aed9c @metrics_lock=#<Mutex:0x5cd61994>, @metrics={}, @channel=#<Cabin::Channel:0xd0fdcca ...>>, @subscriber_lock=#<Mutex:0x3f8ae4ef>, @level=:debug, @subscribers={12448=>#<Cabin::Subscriber:0x346e844b @output=#<Cabin::Outputs::IO:0x589821eb @io=#<IO:fd 1>, @lock=#<Mutex:0x305d0b8b>>, @options={}>}, @data={}>, @last_flush=2016-05-11 16:01:04 +0200, @flush_interval=1, @stopping=#<Concurrent::AtomicBoolean:0x78b7799e>, @buffer=[], @flush_thread=#<Thread:0x38bbe61f run>>", :interval=>1, :level=>:debug, :file=>"logstash/outputs/elasticsearch/buffer.rb", :line=>"90", :method=>"interval_flush"}

Any help would be appreciated

A: Finally I've found the root cause, and it's a bit embarrassing ... but it is.
I've made a typo on the logfile path and logstash, instead of bring an error or warning ... only wait eternally for if the file one day appear. Even with the debug mode on, no info about that the file doesn't exist is showed.
Thanks for your patience.


text:
Q: Alternative for mysql_real_escape_string in mysql? DESCRIPTION
I want to be able to eliminate special characters in mysql. I WAS using mysql_real_escape_string but I was told it was not correct, and soon to be discontinued
Question
What is an alternative for using mysql_real_escape_string in my case below? Or is there another approach?
ISSUE
I am parsing CSV form URL, and creating INSERT statements.  In my case I'm reading in data from an CSV via URL, examples online don't take into account $f_pointer.
Here is an example of one of data lines to insert:
Note: the ' in Green's Mill is causing the issue.
INSERT INTO scores(place,person,score,grade,round,location)values('-','Alex','2','5','','Green's Mill')

My Failed Approach for solving the ISSUE:
I was using mysql_real_escape_string - clearly badly
SCRIPT - Parse Data & Create Insert
 <?php

$servername = "localhost";
$username = "root";
$password = "XXXX";
$dbname = "player";

 // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);

        $f_pointer=fopen("compress.zlib://https://www.url.com/api/v2/projects/xxxx/last_ready_run/data?api_key=xxx&format=csv","r");

 $sql = "TRUNCATE TABLE scores";
 $conn->query($sql);

    if ( $f_pointer === false )
        die ("invalid URL");

   $ar=fgetcsv($f_pointer);
   while(! feof($f_pointer)){
        $ar=fgetcsv($f_pointer)

;
$sql="INSERT INTO    scores(place,person,score,grade,round,location)values('$ar[0]','$ar[1]','$ar[2]','$ar[3]','$ar[4]','$ar[5]')";
 $conn->query($sql);
  echo $sql;
 echo "<br>";

   }
?>

OUTPUT RESULTS
Fails to insert because of the special character ' in the location field.
DESIRED RESULTS
INSERT INTO scores(place,person,score,grade,round,location)values('-','Alex','2','5','','Greens Mill')

Note: Green's Mill would needs to be Greens Mill without the '.


text:
Q: Display a message when a document is being printed I'm new to C# and my mentor wanted me to do a program that would show a message stating that a document is being printed.
I already tried searching the internet and found nothing.
If you know anything, please help me.

A:
You say you searched on Google but you did not find anything

But the truth is that the documentation is there, you just have to search correctly
PrintDocument.Print Method()

The following code is illustrative, it does not intend to do your work, but to guide you in what you want to do

 using System.Drawing.Printing; //For PrintDocument
 using System.Windows.Forms //For MessageBox

 public class PrintingExample
 {
    private void pd_PrintPage(object sender, PrintPageEventArgs ev)
    {
        MessageBox.Show("Printing");
    }

    public static void Main(string[] args)
    {
       PrintDocument pd = new PrintDocument();
       pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
       //Print the document.
       pd.Print();
    }
 }

As you see, you need to use the PrintPage event of PrintDocument, which is executed when you give the print order

pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);

This, in turn, calls the pd_PrintPage() method, which in turn displays the message

private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
    MessageBox.Show("Printing");
}


text:
Q: Finite range operator is compact This theorem is from Rudin book which he says that obvious, but I'm quite confused how to prove it completely. Hope someone can help me clarify.

Let $X$, $Y$ be Banach spaces, If $T \in B(X,Y)$ and dim $R(T) \lt \infty$, then $T$ is compact

Because dim $R(T) \lt \infty$, $R(T)$ is closed in $Y$. Then $R(T)$ is complete because $Y$ is complete. Following from open mapping theorem, we conclude that $T$ is an open mapping from $X$ onto $R(T)$. Because $\overline{T(U)}$ is closed, we need to prove that it is bounded. But $U$ is bounded, then $T(U)$ is bounded, so $\overline{T(U)}$ is bounded. Therefore $\overline{T(U)}$ is compact (without using dim $R(T) \lt \infty$). So what did I do wrong? Where to use the statement dim $R(T) \lt \infty$. Thanks

A: You use the fact that the range is finite dimensional to conclude that it is closed. In general it may not be closed! I would prove it like this:
Let $\{x_n\}$ be a sequence in the unit ball of $X$. Then $T(x_n)$ is bounded: For any $n\in \Bbb{N}$, we have
$$\|T(x_n)\| \leq \|T\| \|x_n\| \leq M$$
for some constant $M$ because $T$ is bounded and $\{x_n\}$ is in the unit ball. Furthermore $T(x_n)$ is contained in a finite dimensional subspace. Now use the fact that a bounded sequence in a finite dimensional complete normed vector space has a convergent subsequence.


text:
Q: lost access to my store I have changed the URL of my site from DNS and I did the change on the admin for the new site but now it seems that I lost access, cant access the site or the admin panel, any ideas?

A: I did that many times :)  if your new site is www.example.com then run the following commands from your root install directory of Magento, for instance, if its var/www/html/magento2 then go there and run
php bin/magento setup:store-config:set --base-url="http://www.example.com"
php bin/magento setup:store-config:set --base-url-secure="https://www.example.com"
php bin/magento cache:flush
and you should be set.


text:
Q: Why is my method printing out the last element of the list when its not supposed to? Using a singly linked list, I am returning a Set c containing elements found only in set A and not in set B.
Set A contains : 30, 20, item2, item1, 10, 26
Set B contains: 88, item3, 30, item4, 26, 100
A.complement(B); should give an output of { 20 item2 item1 10  },
but I'm getting { 20 item2 item1 10 26 } and '26' shouldn't be in the set.
I can't figure out what's wrong even after drawing out a diagram of the list.
public boolean otherContain(Object obj) { // returns true if object is
                                            // inside singly linked list
    Node cur = head.next;

    while (cur != null) {
        if (cur.object.equals(obj))
            return true;
        else
            cur = cur.next;
    }

    return false;
}

public Set complement(Set a) {// return set containing elements only in A
                                // not shared with B
    Set c = new Set();
    Node curC = c.head;
    Node cur = head.next;

    while (cur != null) {

        if (a.otherContain(cur.object)) {
            cur = cur.next;
        } else if (!a.otherContain(cur.object)) {
            curC.next = cur;
            curC = curC.next;
            cur = cur.next;
        }
    }
    return c;
}

*************Updated Working Method************************
    public Set complement(Set a) {// return set containing elements only in A
                                // not shared with B
    Set c = new Set();
    Node newNode = c.head;
    Node cur = head.next;

    while (cur != null) {

        if (a.otherContain(cur.object)) {
            cur = cur.next;
        } else if (!a.otherContain(cur.object)) {
            newNode.next = new Node(cur.object, newNode.next);
            cur = cur.next;
        }
    }
    return c;
}

A: Your problem is that you are reusing the Nodes of the input Set in the output Set, so the final Node you add to the output Set - 10 - still refers to the last Node of the input Set - 26. You should create new Nodes for the output Set.
public Set complement(Set a) {
    Set c = new Set();
    Node curC = c.head;
    Node cur = head.next;

    while (cur != null) {
        if (!a.otherContain(cur.object)) {
            Node newNode = new Node();
            newNode.object = cur.object;
            newNode.next = null;
            curC.next = newNode;
            curC = curC.next;
        }
        cur = cur.next;
    }
    return c;
}


text:
Q: How to Edit only required fields from database collection (azure Cosmosdb) using C# in ASP.NET MVC I am trying to edit CosmosDb collection using C# in ASP.NET MVC. It's editing given fields correctly but deleting fields which are not in form.
My controller:
[HttpPost]
[ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EditAsync([Bind(Include = "Id, DeviceId,GroupId,IPaddress,Name,Address,Lat,DeviceTypeId, DeviceModelId, Long, UserName, Password, PhoneNo, IMEI,PUK, SimPin, SpeedLimit, ActivationSpeed, SpeedLog, EnvLog, Status")] Editdevice item)//LastContact.Ping, LastContact.Voltage, LastContact.EnLog, LastContact.SpdLog,
{
    if (ModelState.IsValid)
    {
        await DocumentDBRepository<Editdevice>.UpdateDeviceAsync(item.Id, item);
        return RedirectToAction("EditIndex");
    }

    return View(item);
}

[ActionName("Edit")]
public async Task<ActionResult> EditAsync(int GroupId, string id)
{
    List<SelectListItem> items = new List<SelectListItem>();

    items.Add(new SelectListItem { Text = "ChainZone", Value = "1" });
    items.Add(new SelectListItem { Text = "Particle", Value = "2" });
    items.Add(new SelectListItem { Text = "Raspberry Pi", Value = "3" });

    ViewBag.Type = items;

    var DeviceModel = await DocumentDBRepository<Devicemodel>.GetDeviceModelAsync(d => d.Id != null);
    // var  selectList =
    ViewBag.Model = DeviceModel.ToList();

    //   string DId = DeviceId.ToString();
    //   var item = await DocumentDBRepository<EditDevice>.GeteditDeviceAsync(d => d.DeviceId == DId);

    var item = await DocumentDBRepository<Editdevice>.GeteditDeviceAsync(GroupId, id);

    return View(item);
}

Collection before saving Edit is:
{
"id": "93607e3f-9e99-4f74-9f54-5f3306bf3fea",
"Long": "153.359726",
"IPaddress": "192.168.2.180",
"SpeedLog": true,
"DeviceModelId": 16,
"Address": "10 A.B. Paterson Drive, Arundel, Qld",
"Lat": "-27.927782",
"EnvLog": true,
"Name": "A.B. Paterson College, Sign 1. FULL MATRIX FTP [2-180]",
"DeviceTypeId": 1,
"RoadSpeedLimit": 20,
"ActivationSpeed": 20,
"DeviceId": "51",
"UserName": "hvswireless171@hvsigns.com.au",
"Password": "hvs171",
"PhoneNo": null,
"IMEI": "8000 0860 1049 5N",
"Puk": null,
"SimPin": null,
"LastContact": {
    "EnvLog": "2020-06-12T11:52:10",
    "Ping": "2020-06-12T03:10:28",
    "Voltage": 12.28,
    "SpdLog": "2020-06-12T11:52:10"
},
"Sensors": [
    1,
    3
],
"GroupId": 28,
"_rid": "sklTANWqGFAUAAAAAAAAAA==",
"_self": "dbs/sklTAA==/colls/sklTANWqGFA=/docs/sklTANWqGFAUAAAAAAAAAA==/",
"_etag": "\"00006af1-0000-1a00-0000-5ee308170000\"",
"_attachments": "attachments/",
"_ts": 1591937047
}

after saving edit it is:
{
"id": "93607e3f-9e99-4f74-9f54-5f3306bf3fea",
"Long": "153.359726",
"IPaddress": "192.168.2.180",
"SpeedLog": true,
"DeviceModelId": 16,
"Address": "10 A.B. Paterson Drive, Arundel, Qld",
"Lat": "-27.927782",
"EnvLog": true,
"Name": "A.B. Paterson College, Sign 1. FULL MATRIX FTP [2-180]",
"DeviceTypeId": 1,
"RoadSpeedLimit": 20,
"ActivationSpeed": 20,
"DeviceId": "51",
"UserName": "hvswireless171@hvsigns.com.au",
"Password": "hvs171",
"PhoneNo": null,
"IMEI": "8000 0860 1049 5N",
"Puk": null,
"SimPin": null,
"GroupId": 28,
"_rid": "sklTANWqGFAUAAAAAAAAAA==",
"_self": "dbs/sklTAA==/colls/sklTANWqGFA=/docs/sklTANWqGFAUAAAAAAAAAA==/",
"_etag": "\"00006af1-0000-1a00-0000-5ee308170000\"",
"_attachments": "attachments/",
"_ts": 1591937047
}

Please help. How can I just edit few fields and leave the others as they are? It has many fields which don't need to be edited. But they are vanishing or set as null after submitting edit form.


text:
Q: c++ error when installing package in R I cannot install any errors any more when installing a package in RStudio in Ubuntu.
The error I receive is

checking for g++... g++
  checking whether the C++ compiler works... no
  configure: error: in /tmp/RtmpSkung5/R.INSTALL70592285d1c6/nloptr':
  configure: error: C++ compiler cannot create executables
  Seeconfig.log' for more details

Things I already tried
- install g++
- install cpp
- Try to look into config.log but I don't find this file anywhere.
Any idea how to proceed?
Thanks


text:
Q: How to capture the output of a process (from OR Tools solver) and display it through console I have a C# winform application in which an optimization model is solved by OR-Tools. The optimization solver has the capability of sending the whole optimization process as stdout.This is done by:
    Slvr.EnableOutput();
    Solver.ResultStatus restatus = Slvr.Solve();

However, the solver does not automatically open up the console.
Currently, what I have done is:
Projects properties --> Application --> Output type --> Console Application
and the console is ready from the beginning till the end of the application run. Hence, that process stdout is automatically displayed.
What I want is to open the console exactly when the above part of code is run and display the stdout from the solver. Then wait for a key from the user to close the console and continue with the main application.

A: I guess your problem is you are trying to run the solver as part of the Winforms application, inside the GUI process right? But Console output is usually disabled in a Winforms application. You have basically two options:

*

*use one of the options described here in this older SO answer to attach a console window for output to a Winforms application

*split the application into two exe files: one command line program which runs the solver, and a Winforms part, just containing the UI. Then run the command line part as a separate process by System.Diagnostics.Process.Start, which allows finegrained control about output redirection. You may need the UI to pass parameters to the command line program, for example, by using a temporary file.
The second option is more work, especially for the communication between the GUI and the command line tool, but can be implemented easier in a way the GUI is not blocked, is more robust against bugs / program crashes in the solver part and performs usually better in case you want to introduce parallelization / run multiple solver processes at once.

A: Doc Brown has already answered your question, I'm only adding this to provide some code of how we implemented it here-- it's exactly what he suggests. We have a separate testPlugin.exe that get's started here. The communication is via files read and written on the file system. The console output gets captured in the "output handlers"
using System;
using System.Diagnostics;
using System.IO;

...

        private void startTest()
        {
            int result = 2;
            setFormStatus("working...");   // My method to inform the user with the form to wait.

            getFormData();  // My method to get the data from the form

            string errorMessage = null;
            System.Diagnostics.Process testPlugInProcess = new System.Diagnostics.Process();
            try
            {
                using (testPlugInProcess)
                {
                    testPlugInProcess.StartInfo.UseShellExecute = false;
                    testPlugInProcess.StartInfo.FileName = System.IO.Path.Combine(assemblyDirectory, TestPlugInExe); // The name of the exe file
                    testPlugInProcess.StartInfo.CreateNoWindow = false;
                    testPlugInProcess.StartInfo.Arguments = getModelTestCommandLineArgs(); // My method to create the command line arguments
                    testPlugInProcess.StartInfo.RedirectStandardError = true;
                    testPlugInProcess.StartInfo.RedirectStandardOutput = true;
                    testPlugInProcess.OutputDataReceived += pluginTestOutputHandler;
                    testPlugInProcess.ErrorDataReceived += pluginTestOutputHandler;
                    testPlugInProcess.Start();
                    testPlugInProcess.BeginErrorReadLine();
                    testPlugInProcess.BeginOutputReadLine();
                    testPlugInProcess.WaitForExit();
                    result = testPlugInProcess.ExitCode;
                }
                setFormStatus("");
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }
            testPlugInProcess = null;
        }

Both the console and error output get written to the same file here, but you could separate them.
The plug-in handler looks like this:
        private static void pluginTestOutputHandler(object sendingProcess,
           DataReceivedEventArgs outLine)
        {
            if (!String.IsNullOrEmpty(outLine.Data))
            {
                for (int i = 0; i < numberOfTriesForWriting; i++)
                {
                    try
                    {
                        using (StreamWriter sw = File.AppendText(lastPlugInTestTraceFilePath)) // The file name where the data is written.
                        {
                            sw.WriteLine(outLine.Data);
                            sw.Flush();
                            return;
                        }
                    }
                    catch (IOException)
                    {
                        System.Threading.Thread.Sleep(msToWaitBetweenTries);
                    }
                }
            }
        }


text:
Q: Two-way authentication using ssl in dotnet I have a project where I need to send a datafile through a web request.  We need to setup Two-way authentication also known as mutual authentication.  We are not sure if we need a special cert or not but we know that it needs to be level 3.
I am having trouble finding sample code for this case. I don't know where to add our cert information.  With this code a Underlying connection is closed error is thrown when we try to read the response stream and ServicePointManager.ServerCertificateValidationCallback is never called.  Here is what I have:
ServicePointManager.ServerCertificateValidationCallback = New Security.RemoteCertificateValidationCallback(AddressOf MyCertValidationCb)
            httpReq = CType(System.Net.HttpWebRequest.Create(url), HttpWebRequest)
            For Each cert As String In certs
                X509cert = X509Certificate2.CreateFromCertFile(cert)
                X509cert2 = New X509Certificate2(X509cert)
                httpReq.ClientCertificates.Add(X509cert2)
            Next
            httpReq.Method = "POST"        ' Post method
            httpReq.ContentType = "text/xml"               ' content type

            ' Wrap the request stream with a text-based writer
            writer = New StreamWriter(httpReq.GetRequestStream())
            ' Write the XML text into the stream
            reader = New StreamReader(filename.Name)
            ret = reader.ReadToEnd()
            reader.Close()
            ' Send the data to the webserver
            writer.WriteLine(ret)
            writer.Close()
            ' Wait for response
            Dim httpRsp As System.Net.HttpWebResponse = CType(httpReq.GetResponse(), HttpWebResponse)
            sr = New StreamReader(httpRsp.GetResponseStream)
            responseText = sr.ReadToEnd

            If httpReq IsNot Nothing Then
                httpReq.GetRequestStream().Close()
            End If
            If httpRsp IsNot Nothing Then
                httpRsp.GetResponseStream().Close()
            End If

Any tips or links to blogs with sample code would be great.
Thanks.

A: You don't need a 'special' certificate. Your client needs its own certificate and use it in the connection to tell the server its identity. That is called a Client Certificate. The server should handle this properly.
The following MSDN article talks about how to set your ClientCertificate:
http://msdn.microsoft.com/en-us/library/ms732391.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2


text:
Q: Does setter generates hibernate query for Entity class automatically I have an entity class in Hibernate JPA spring boot app using lombok. While analysing the code , I could not find any save() code. Does the setter automatically generates the Hibernate queries and saves them to DB.
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString(callSuper = true)
@Entity
@Table(name = "operation", schema = "ssp")
public class Operation extends CommonEntity{
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ToString.Exclude
    @ManyToOne
    @JoinColumn(name = "router_ref_id")
    private Router router;

    @ToString.Exclude
    @OneToMany(mappedBy = "operation", cascade = CascadeType.ALL)
    @OrderBy("sequence")
    private List<OperationQr> qrList;

    @ToString.Exclude
    @OneToMany(mappedBy = "operation", cascade = CascadeType.ALL)
    private Set<OperationDependency> operationDependencies;

    @ToString.Exclude
    @OneToMany(mappedBy = "operation", cascade = CascadeType.ALL)
    @OrderBy("sequence")
    private Set<OperationDocument> opnDocumentList;

    @ToString.Exclude
    @OneToOne
    @JoinColumn(name = "operation_interface")
    private OperationInterface operationInterface;

    @Column(name = "router_operation_id")
    private Integer routerOperationId;

    @Column(name = "tenant_id")
    private String tenantId;

    @Column(name = "external_system_sequence")
    private String externalSystemSequence;

The code which saves the Operation and its parts are :
private Operation saveDetails(OperationDetailsViewModel newOperationData, String sso, Router router, Operation operation) {
    copyProperties(newOperationData, operation);

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    Optional<XRefWorkcenterRequirementProfile> requirementProfile = workCenterService.getRequirementProfileFor( router, newOperationData.getWorkCenter().getId() );

    operation.setRequrementProfile(requirementProfile.isPresent() ? requirementProfile.get().getProfileId() : null);

    if (isOperationInterfaceChanged(operation.getOperationInterface(), newOperationData.getOperationInterface())) {
        OperationInterface newOperationInterface = operationInterfaceService.getOperationInterface(
                router.getEnterprise(), router.getBusinessUnit(), router.getPlant(), newOperationData.getOperationInterface().getId());
        operation.setOperationInterface(newOperationInterface);
    qualityResultService.removeOldQr(operation);
    List<OperationQr> qrList = qualityResultService.createQrList(sso, operation, newOperationData.getGlobalQr());
    qrList.addAll(qualityResultService.createQrList(sso, operation, newOperationData.getLocalQr()));
    operation.setQrList(qrList);

    Set<OperationDependency> operationDependencies = operationDependenciesService.createDependencies( sso, operation, newOperationData.getDependencies() );
    operationDependencySetValidator.validateDependencySet( operationDependencies );
    operationDependenciesService.removeOldDependencies( operation );
    operation.setOperationDependencies( operationDependencies );

    documentService.removeOldOperationDocuments(operation);
    operation.setOpnDocumentList(documentService.createDocuments(sso, operation, newOperationData.getDocuments()));

    purchaseDetailService.updatePurchaseDetail(sso, operation, newOperationData.getPurchaseDetails());
    addCustomFields( sso, operation, newOperationData ) ;

    OperationUtils.setEntityUpdateData( operation, sso );

    stopWatch.stop();
    LOGGER.info("..........SaveOperationDetails.......... Total time = " + stopWatch.getTotalTimeMillis() + " ms");

    return operation;
}

saveDetails() is wrapped in another method which is @Transactional
 @Transactional
    public Operation addOperation( OperationDetailsViewModel newOperationData, int indexToAdd, String sso, String changeRequestNumber ) {
        Router router = getEditableRouter( newOperationData.getRouterId(), sso, changeRequestNumber );
        Operation operation = prepareNewOperation(sso, router);
        OperationUtils.addOperationToIndexWithResequencing( router.getOperationsList(), operation, indexToAdd );
        return saveDetails(newOperationData, sso, router, operation);
    }

private Operation mergeOperation(OperationDetailsViewModel operationDetailsViewModel, int i, String sso,
    String changeRequestNumber, Router router, RouterLock routerLock) {
    Operation operation;

    if(operationDetailsViewModel.getId() == null) {
        operation = saveOperationDetailsService
            .addOperation(operationDetailsViewModel, i, sso, changeRequestNumber);
    }
    else {
        operation = saveOperationDetailsService
            .updateOperation(operationDetailsViewModel, sso, changeRequestNumber, router, routerLock);
    }

    return operation;
}

  public static void addOperationToIndexWithResequencing(List<Operation> operations,
      Operation newOperationWithoutSequence, int indexToAdd) {
    operations.sort(Comparator.comparing(Operation::getSequence));

    if (indexToAdd < operations.size()) {
      operations.add(indexToAdd, newOperationWithoutSequence);
    } else {
      operations.add(newOperationWithoutSequence);
    }

    resequenceOperations(operations);
  }

A: "Does the setter automatically generates the Hibernate queries and saves them to DB. - NO
Basically save() is present on CrudRepository. JpaRepository extends the CrudRepository. Hence it inherits all the methods from CrudRepository. Check the docs link.
https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html
https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html

A: If Operation entity is a managed entity (it is retrieved from some jpa repository, for example findOne etc), then explicit save or persist call is not needed. It gets automatically saved at the end of a transaction.
I believe, you must be having a repository call somewhere here -
Operation operation = prepareNewOperation(sso, router);
OperationUtils.addOperationToIndexWithResequencing( router.getOperationsList(), operation, indexToAdd );

Similar answer here - https://stackoverflow.com/a/46708295/11244881


text:
Q: Running Test NG test suite from command line - Error: Could not find or load main class org.testng.TestNG As the title says
I tried to follow the clues mentioned in
How to run TestNG from command line
but I get Error: Could not find or load main class org.testng.TestNG
Here is the detailed command I use:
java -cp "testng-6.8.jar:C:\Users\...\src\test\java\unit_tests\libs_test" org.testng.TestNG "C:\Users\...\src\test\resources\AllUnitTests.xml"

The point is that when I opened testng-6.8.jar in 7zip, I can see the org.testng.TestNG class:
screenshot
What is wrong with that command?


text:
Q: Changes in Water Bonding Angle I heard something recently in a casual discussion, but have yet to be able to confirm it: is there any evidence that the bonding angle for a water molecule, currently defined as 104.5, has been either steadily growing or shrinking since it was first observed and measured? Is there any possibility that water samples from different locales would produce different results? I am speaking strictly of water in as pure a form as possible, not water affected by impurities or physical manipulation.

A: No, there has been no change to the bond angle of pure water,1 nor does anyone expect to measure one. The reason is this angle is set by fundamental physical constants - things like the mass of the proton and the speed of light - albeit in a complicated way. Such things are called constants for a reason. Now there are some theories out there, a number of them a bit far-fetched, that speculate that maybe some of our constants have been evolving extremely slowly over billions of years, but certainly there has been no detected variation over the course of human scientific inquiry. Such a discovery would be huge, causing much agitation in all of physics and chemistry.
It should also be noted that the bond angle can both be calculated from theory and measured from experiment, and neither method yields exactly $104.5^\circ$. Now your theoretical calculations might improve if you make fewer simplifying assumptions than your predecessors, and your measurements might improve if you develop better apparatus and technique, but the true underlying value of the bond angle is not changing.

1 Defined here as oxygen-16 bonded to two atoms of hydrogen-1. Now the angle could vary with isotopic abundances, so perhaps someone was referring to changing isotopic abundances of a source of water. You might see this, for instance, in extreme climate change, since as temperatures rise the fraction of "heavy" water ($\mathrm{D}_2\mathrm{O}$, etc.) evaporated from oceans increases relative to "normal" water.

A: This is really just a footnote to Chris' answer, but any change in the bond angle of water would change its rotational and vibrational spectra. We can detect the spectrum of water molecules in the Orion nebula, which is 1,344 light years away, so we know the bond angle hasn't changed in the last 1,344 years.
Presumably we can detect water in more distant nebulae, but no change for a thousand years seems a fairly definitive test in this context :-)


text:
Q: Prove that $X(R)$ is not normal I was doing an exercise guide and the following is related to this
Prove that it is first countable
Let $H:=\{(x,y)\in \mathbb{R}^2\;:\; y>0\}$ and $R=\{(x,y)\in  \mathbb{R}^2\;:\; y=0\}$. Notice that $\tau$ he topology of $H$ induced by $ \mathbb{R}^2$. Let the set  $X(S):=H\cup S$, where  $S\subset R$.
Define the topology $\tau^{\star}$ over the set  $X(S)$ as  the generated topology $\tau$ and the set $\mathcal B$, where $\mathcal{B}$ is formed by all the sets of form$\{x\}\cup B$, where $x\in S$ and $B\subset H$ is an open ball tangent to $R$ at the point $\{x\}$.
Prove that $X(R)$ is not normal
My attempt:
Let  $Q=\{(x,0)\in R\;:\; x\in \mathbb{Q}\}$ and $I:=R\setminus Q$ (are closet of $X(R)$). Let $Q\subset V$, $I\subset U$ two open set of $X(R)$,
Let $I_n$ is the set of all  $x\in I$ such that there exists an open ball, $B\subset H$, of radius $1/n$, tangent to $x$ such that  $\{x\}\cup B\subset U$.
Let $I=\cup_{n=1}^{\infty}I_{n}$. (how can i test this?)
Now there is $n$ such that $(\overline{I_n})^{\circ}\cap Q\neq \emptyset$ ((because R is not the countable union of closed interior empty
but I know how to continue
Thanks

A: $\Bbb Q^2 \cap H$ is countable and dense in $X(R)$.
If $X(R)$ were metrisable, it would thus be second countable and so all subspaces would be second countable.
But $R$ as a subspace is discrete (every basic neighbourhood of $(x,0)$ intersects $R$ only in that point) and uncountable so not second countable.
This contradiction is sufficient.
In fact one can even show with Jones' lemma (look it up) that $X(R)$ is not even normal. Your approach to showing non-normality is not needed. Said lemma suffices.


text:
Q: gcc optimizations I would like to know if the following piece of code is going to throw an error or a warning upon compilation with any kind of gcc/g++ optimizations enabled.
int a;
a = func();
if (a == 2) {
    assert(false);
}

I think the following code can throw a warning "set but unused variable", in release configuration.
int a;
a = func();
assert(a != 2);

But what about the above code? (gcc can remove the if statement itself because nothing is going to be done either in the if-statement or in the if-block (in release build), and then throw a warning "unused but set variable" )
edit : this definitely is not a question regarding reducing the size of code or exe. I want to know a piece of code that succeeds in any build configuration.
edit: we disable assert in release mode

A: According to my tests, the following code generates a warning with -Wall -Wextra -O2 -DNDEBUG:
int a = func(); // warning: unused variable 'a'
assert(a != 2);

But the following code does not:
// no warnings
int a;
a = func();
assert(a != 2);

However, you can always suppress unused variable warnings by casting to void.
int a = func();
(void) a; // suppresses "unused variable" warning
assert(a != 2);

As far as I can tell, the line a = func() statement always counts as use of the variable a, whereas initialization does not count as use.
I wouldn't try to hedge against future possible compiler warnings as compilers change and their diagnostics improve, since the hedges can sometimes suppress valid warnings by accident.
How is assert defined?
The standards committees and C implementers have designed assert carefully so it doesn't generate spurious warnings.  Note how common casts to void are...

*

*Without NDEBUG, glibc defines assert roughly in the following way (except with something other than abort):
#define assert(expr) ((expr) ? (void) 0 : abort())

*With NDEBUG, glibc defines it this way (as mandated by the C standard):
#define assert(expr) ((void) 0)

*The following definition of assert is not compliant, since it does not expand to an expression:
#define assert(expr) { if (expr) { ... } } // wrong

The definitions are slightly different for C++, too.  So you see, assert is defined in just the right way so it doesn't create any bogus compiler warnings, and it really does behave syntactically like a function call.

A: It's not possible in general to say a piece of code will never get any warnings from a compiler, as new warnings could be added in future or compiler bugs could cause spurious warnings.
I'm pretty sure GCC will not warn for an empty if body defined with braces, precisely because that can easily happen in valid code, such as this (which is essentially very similar to your case):
int a = func();
if (a == 2)
{
#ifdef SOME_BUILD_SETTING
    launch_missiles();
#endif
}

The manual shows

-Wempty-body    Warn if an empty body occurs in an if, else or do while statement.   This warning is also enabled by -Wextra.

Which would apply for:
#ifdef SOME_BUILD_OPTION
# define LAUNCH_MISSILES launch_missiles()
#else
# define LAUNCH_MISSILES
#endif
if (a==2)
  LAUNCH_MISSILES;

Then compiled with -Wextra without SOME_BUILD_OPTION defined.
But with the braces it doesn't warn, and as Dietrich Epp comments, with assert it doesn't warn because it doesn't expand to nothing even with NDEBUG defined.
In your code a is initialized and its value is used, so I would be surprised for it to warn.

A: This may cause problems if your assert is removed by the preprocessor, like this:
#ifdef ENABLE_ASSERT
#define assert (CONDITION) {if (!(CONDITION)) abort ();}
#else
#define assert (CONDITION) /* Nothing */
#endif

But, if you do it properly then there will be no problems:
#define assert (CONDITION) {if ((ENABLE_ASSERT) && !(CONDITION)) abort ();}

In this case the compiler will still see that a is used in CONDITION, but will optimize it away when ENABLE_ASSERT is zero. It's usually better to let the compiler optimizers remove code than using the preprocessor: it avoids warnings like this, and usually leads to more readable code, and the code doesn't need to be rewritten if it turns into a run-time test one day.
Obviously, ENABLE_ASSERT must always be defined to either zero or non-zero.

A: Both code blocks are ok, but i would prefere:
int a = func();
assert(a != 2);

A: As you probably know the assert macro is managed with the macro NDEBUG. I think something that uses an #ifdef NDEBUG would be easier to read and have the same effect.

A: Yes, this code may emit warnings with some odd compiler setting at some point in time in the future.
Your question will never be answered in the affirmative. It can't be. The future is unpredictable. And even in the present, the number of compiler flags represents a combinatorial explosion that can be very difficult to fully analyze. Anybody who gave you a 'yes' answer to that is likely overlooking something.
Now, I will say that the compiler generally (in my experience) only issues warning for what your code actually looks like, not for what it looks like after the optimizer finishes with it. Yes, if you run the optimizer it may be able to do a deeper analysis and find more subtle problems. But it isn't going to start flagging you about a construct that's now superfluous because the optimizer was able to completely remove it.
So, I think you're mostly safe here, which is as close to a 'yes' as you're going to get from me.


text:
Q: jquery conditional operator for attr function $("<button>")
    .addClass("radio")
    .addClass(this._getValue(lbl) ? "checked" : "")
    .attr(this._getDisableProp(lbl) ? ("disabled", "disabled") : "")
    .prop(this._getDisableProp(lbl) ? ("disabled", true) : ("disabled", false));

in the above code, i am trying to add attr and prop only when my function returns true. i did that similarly for addClass and it worked, but it is not working for attr and prop.
is there any work arounds please?

A: You cannot chose multiple function arguments based on the ternary operator. You can only select one. So do something like:
$("button")
         .addClass("radio")
         .addClass(this._getValue(lbl) ? "checked" : "")
         .attr("disabled" , this._getDisableProp(lbl) ? "disabled" : "")
         .prop("disabled", this._getDisableProp(lbl) ? true : false);

However I would recommend only using the property as "disabled" attribute set to "" will still disable the element (which would get overridden by property anyway):
$("button")
         .addClass("radio")
         .addClass(this._getValue(lbl) ? "checked" : "")
         .prop("disabled", this._getDisableProp(lbl) ? true : false);

A: Do something like this:
.prop("disabled", this._getDisableProp(lbl))

You don't want the ternary operator on the whole thing... just the value (which will be different depending on the condition)
Do note that even a blank value for the disabled attribute will cause the element to be disabled, that's why we use prop.

A: You can't do it directly like that, but you could do this:
var btn = document.createElement("button");
btn.className = "radio";
if( this._getValue(lbl)) btn.className += " checked";
if( this.getDisableProp(lbl)) btn.disabled = true;

Sometimes plain JavaScript in multiple steps is easier than trying to chain everything in one go ;)

A: In your style,
  $("<button>")
        .addClass("radio")
        .addClass(this._getValue(lbl) ? "checked" : "")
        .prop('disabled',this._getDisableProp(lbl));

More flexible approach,
$("<button>")
    .addClass("radio")
    .addClass(function () {
        if(this._getValue(lbl)) return 'disabled';
     })
    .prop('disabled',function () {
        return this._getDisableProp(lbl) ;
     });

Also, why are you using both attr and prop to add disabled property. You should be using prop only and disabled does not require a value.


text:
Q: which is a better language (C++ or Python) for  complex problem solving exercises (ex. Graphs)? I am trying to work on some problems and algorithms. I know C++ but a friend told me that it would be better if done with Python.As it would be much faster to develop and less time is spent in programming details which does not actually earn anything solution wise.
EDIT 2: I plan to use python-graph lib from Google-codes, Please provide example codes if you have used it.
EDIT 1: faster  - less time && less work to code the solution
Thank you all for your help !

A: Instead of focusing on the language, you should focus on the libraries available to you.
You shouldn't write your own graph library when there are already plenty (read, "too many") available, both in C++ and in Python. [Stack Overflow has a list of Python Graph packages with recommendations that you should check out. I didn't find an equivalent question for C++. You could start one.] Also, unless this is an academic excercise or research on truly novel graph algorithms, you should browse through the libraries available to see if any of them already implement those algorithms of interest to you.
Using libraries mitigate the gain of the higher level language of Python, since you won't be working with raw C++ per se, but with a C++ library. Since the Python language has a very small core, it is fairly easy to learn, however, it still takes time. You will need factor in that additional time on top of learning a library, if you choose the Python route, so make sure to weigh that in your decision.
Thus, given you already know C++, you may ultimately find it faster to develop in C++, since you only have to commit the time necessary to learn the library, not a library plus a new—albeit easy to learn—language.

A: A bit subjective, but I'd vote for python because it has good libraries and abstracts a lot of the low level 'detail' that you'd have to consider when using c++...

A: I did all my algorithms work in college in C++ because I knew it.
If I'd had to learn a language at the same time, I would have picked Python most likely.

A: I am under the impression that it really depends from what you mean by faster.
Faster to develop: go python.
Faster to run: go C++.
However python can use a lot of external C libraries, so the difference in processing time might not be that relevant, depending on the type of implementation.

A: At my university the 500 students in the "Algorithms and Datastructures" class get to choose the language they want.
Python is by far the most popular choice there, and personally I'm happy I also chose that, even though I already knew C++.

A: Agree with your friend - use Python and put them within a unit test framework.
I worked for a number of years with scientists who did a lot of their algorithmic work in Python.
The example below shows typical tests (the import statement is for the stuff being tested),  with a couple of niceties that might save you some time.
The business with the save and restore of sys.path is so you can have all your tests sitting in a directory adjacent to the src directory, without having to install the source into your main Python modules.
This test script is written so it can be imported into a larger suite of unit tests or simply run with python thisfile.py.
#!/usr/bin/python
"""
VRML Writer tests
"""

import unittest
import os
import sys

if __name__ == '__main__':
    global save_syspath
    save_syspath = sys.path
    sys.path = [os.path.abspath("../src/")] + sys.path

from cgtools.VizValueTools import *

if __name__ == '__main__':
    sys.path = save_syspath  # RESTORE SYS.PATH

# use some common constants to make tests easier
MINV = 0.002
MAXV = 12.789

class TestColdHotColorGeneration(unittest.TestCase):

    def testGeneratesLimitValues(self):
        assert generateColdHotColorValue(MINV, MAXV, MINV) == (0.0, 0.0, 1.0)
        assert generateColdHotColorValue(MINV, MAXV, MAXV) == (1.0, 0.0, 0.0)
        assert generateColdHotColorValue(0, 0, 0) == (1.0, 0.0, 0.0)  # cope with weird case where range is effectively one value, should be always top

    def testGeneratesLimitValuesWithClipping(self):
        assert generateColdHotColorValue(MINV, MAXV, MINV - 1.2) == (0.0, 0.0, 1.0)
        assert generateColdHotColorValue(MINV, MAXV, MAXV + 49) == (1.0, 0.0, 0.0)

    def testGeneratesMiddleValue(self):
        """
        Note to be careful picking values so your value IS in the middle,
        to generate pure green
        """
        assert generateColdHotColorValue(1.0, 3.0, 2.0) == (0.0, 1.0, 0.0)

if __name__ == '__main__':
    # When this module is executed from the command-line, run all its tests
    unittest.main()

A: I would go for python. And if you really need the performance, then you can always write C/C++ extensions and use them in python.

A: Algorithms are fine in Python (allthough you can only fly one OS scheduled python thread due to the global lock); however, when it comes to data structures + algorithms you need fixed complexity guarantees, and this case you mix Python with C.
I suppose what I have said applies more to long running computations. You can emulate data structures on-top of the python hashmap primitive.

A: I think you're looking for Python, because you can:

*

*Focus on the algorithms themselves and not have to worry about other detail like memory management.

*Do more with less code

*The syntax is almost like working with pseudo code.

*There is great built in language support for lists, tuples, list comprehensions, etc...

But more specifically...

*

*If by better you mean speed of development, then chose Python.

*If by better you mean sheer execution speed, then chose C++.

A: I also vote for python. When do algorithm, we tend to work on the algorithm itself rather than language, low level details. Basically, we works on abstraction level. And using python, we're less likely to be side-tracked.
But if you're very familiar and comfortable with C++ and can use it freely to express your idea, just use it.

A: With C++, you'd sometimes be concentrating more on the language issues than the problem itself, so Python. I'd even be recommending you do it in a higher-level language like Matlab (although the language itself can be a bit ugly).

A: If using C++ means that STL is fair game, I'd say that it deserves serious consideration.  STL is a fantastic library, combining structures, iterators, and algorithms.  I love the Python recommendations, but if I could use STL I'd reconsider C++.

A: Remember that Python is compiled to bytecode and then interpreted in a VM. So, in performance isn't better (faster) than C++.


text:
Q: Detect marker with opencv and python I am trying to detect a marker in a webcam video feed and overlay it with a 3d object - pretty much exactly like this: http://www.morethantechnical.com/2009/06/28/augmented-reality-with-nyartoolkit-opencv-opengl/
I know artoolkit is the best module for this, but I was hoping to just use opencv in python since I dont know nearly enough c/c++ to be able to use artoolkit. I am hoping someone will be able to get me on the right track towards detecting the marker and determining its location and orientation etc since I have no idea how best to go about this or what functions I should be using.

A: OpenCV doesn't have marker detection / tracking functionality out of box. However it provides all algorithms needed so it's fairly easy to implement your own one.
The article you are referring to uses OpenCV only for video grabbing. The marker detection is done by NyARToolkit which is derived from ARToolkit. NyARToolkit have versions for Java, C# and ActionScript.
ARToolkit is mostly written in plain C without using fancy C++ features. It's probably easier to use than you thought. The documentation contains well explained tutorials. e.g http://www.hitl.washington.edu/artoolkit/documentation/devstartup.htm
The introductory documentation can help you understand the process of marker detection even if you decide not to use ARToolkit.

A: I think the most used way to perform marker detection using python and open CV is to use SURF Descriptors.
I have found very useful this video and the linked code you can find in this page. Here you can download the code. I don't know how to overlay it with a 3d object but I'm sure you can do something with pygame or matplotlib.


text:
Q: Is there a way to extract the pixel co-ordinates of a plotted line in matplotlib Similar to in this StackOverflow post, I understand that it is possible to extract the pixel co-ordinates from points plotted in a pyplot figure.
How to get pixel coordinates for Matplotlib-generated scatterplot?
However, what if we plotted a line between each of those points and wanted to get the location of all the pixels of not just those plotted dots, but all pixels that make up the line.
Is this something that is possible with matplotlib?

A: A line isn't made up of pixels. The pixels in its trajectory are modified taking line width and antialiasing into account. Drawing a line with default settings and zooming in on the image looks like the image below. Very few pixels get the full 100% of the given color. Lots of pixels are changed.

Depending on your final goal, you could calculate pixel coordinates using the method described in the post you linked (note that the pixels on a saved image can deviate a bit from the pixels on-screen). And then use e.g. Bresenham's line algorithm to find the coordinates of points in-between. Note that a naive Bresenham's algorithm would draw a 45 degree line much thinner looking than a horizontal line. On a modern screen a one-pixel wide line would be almost invisible.
Here is a possible Bresenham-like interpretation of the linked code:
import numpy as np
import matplotlib.pyplot as plt

def points_in_line(x0, y0, x1, y1):
    dx = np.round(np.abs(x1 - x0))
    dy = np.round(np.abs(y1 - y0))
    steps = int(np.round(max(dx, dy))) + 1
    return np.vstack([np.linspace(x0, x1, steps), np.linspace(y0, y1, steps)]).T

fig, ax = plt.subplots()
points, = ax.plot([0, 1, 2, 4, 5, 6, 9], [0, 5, 3, 2, 2, 9, 8], 'b-')
ax.axis([-1, 10, -1, 10])

# Get the x and y data and transform them into pixel coordinates
x, y = points.get_data()
xy_pixels = ax.transData.transform(np.vstack([x, y]).T)
x_pix, y_pix = xy_pixels.T

# find all points in each line
all_pix = [points_in_line(x0, y0, x1, y1) for x0, y0, x1, y1 in zip(x_pix[:-1], y_pix[:-1], x_pix[1:], y_pix[1:])]
all_x_pix, all_y_pix = np.concatenate(all_pix).T

# In matplotlib, 0,0 is the lower left corner, whereas it's usually the upper
# left for most image software, so we'll flip the y-coords...
width, height = fig.canvas.get_width_height()
all_y_pix = height - all_y_pix

print('Coordinates of the lines in pixel coordinates...')
for xp, yp in zip(all_x_pix, all_y_pix):
    print(f'{x:0.2f}\t{y:0.2f}')

# save the figure with its current DPI
fig.savefig('test.png', dpi=fig.dpi)


text:
Q: Deleting element in row of 2D Vector - With Iterators I have 7x20 2D Vector of an "Entry" object. The Entry object has an ID. I want to iterate through my vector and do:
if( idToDelete == entry.getID() )
    //Delete entry

Currently the code looks like this:
for(auto day : entryRegister)
{
    for(auto entry : day)
    {
        if(entryID == entry.getID())
        {
            //Delete Entry
        }
    }
}

I'm unsure how to formulate the expression to actually delete an item. I've tried doing entryRegister[day].erase(entry) but I get an error because there is no operator found that takes an iterator in the square brackets.
I saw the request for the declaration of EntryRegister. The relevant information is just that it is declared like this: vector< vector<Entry> > and has 7 colums, each with a maximum of 20 rows.
getID returns an unsigned char that is some value between 1 and 70.
This is part of a function where I pass in an ID that i wish to delete. I then iterate through the register, and delete any entry with that ID.

A: C++ does not have a function "delete a value" in a vector, since it can be done in two more fundamental steps, commonly known as the erase-remove idiom:

*

*Find all items in the vector equal to the value, and swap them to the end of the vector, using std::remove or remove_if

*Resize the vector to delete those found items, using std::vector::erase
Note that erase takes one or two iterators. It only supports erasing items where you already knew the position.
for (auto& day : entryRegister) {
    auto erase_begin = std::remove_if(
                day.begin(),
                day.end(),
                [=](const Entry& entry) { return entry.EntryID() == entryID; }
    );
    day.erase(erase_begin, day.end());
}

Note that I changed the entryRegister loop to get day by reference, so the changes actually affect the real day instead of a copy.


text:
Q: Convert map to mapPartitions in spark I have a code to analyze the log file using map transformation. Then the RDD got converted to DF.
val logData = sc.textFile("hdfs://quickstart.cloudera:8020/user/cloudera/syslog.txt")

val logDataDF = logData.map(rec => (rec.split(" ")(0), rec.split(" ")(2), rec.split(" ")(5))).toDF("month", "date", "process")

I would like to know whether I can use mapPartitions in this case instead of map.

A: I don't know what is your use case but you can definitely use mapPartition instead of map. Below code will return the same logDataDF.
val logDataDF = logData.mapPartitions(x => {
  val lst = scala.collection.mutable.ListBuffer[(String, String, String)]()
  while (x.hasNext) {
    val rec = x.next().split(" ")
    lst += ((rec(0), rec(2), rec(5)))
  }
  lst.iterator
}).toDF("month", "date", "process")