text:
Q: Web Service 404 Error I have created a web service that returns JSON data. It works correctly when accessing through my local host.

http://localhost:6553/Service1.svc/GetViewData

but when I deploy and try to run on my production server  I get the following error:

Server Error in '/JSONWebService' Application.
  The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /JSONWebService/Service1.svc/GetViewData

If I remove the /GetViewData from the URL I get the following message:

Server Error in '/JSONWebService' Application.
  The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /JSONWebService/Service1.svc/GetViewData

If I remove the /GetViewData from the URL I get the following message:
You have created a service.
To test this service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line with the following syntax:

svcutil.exe http://ac.gtest.oh.edu/JSONWebService/Service1.svc?wsdl

Here is my web config:
<?xml version="1.0"?>
<configuration>

<connectionStrings>
<add name="Web_TransferConnectionString" connectionString="Data Source=dart;Initial Catalog=Web_Transfer;Integrated Security=True"
  providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
<httpModules>
  <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.serviceModel>
<services>
  <service name="JSONWebService.Service1">
    <endpoint address="../Service1.svc" binding="webHttpBinding" contract="JSONWebService.IService1" behaviorConfiguration="webBehaviour" />
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/>
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="webBehaviour">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
 <!-- <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
   <baseAddressPrefixFilters>
     <add prefix="http://www.JSONWebService.com/"/>
   </baseAddressPrefixFilters>
 </serviceHostingEnvironment> -->
</system.serviceModel>
<system.webServer>
<!--  <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept"/>
  </customHeaders>
 </httpProtocol> -->
 <modules runAllManagedModulesForAllRequests="true">
  <remove name="ApplicationInsightsWebTracking"/>
  <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
    preCondition="managedHandler"/>
 </modules>
   <!--
    To browse web app root directory during debugging, set the value below to true.
    Set to false before deployment to avoid disclosing web app folder information.
    -->
 <directoryBrowse enabled="true"/>
 <validation validateIntegratedModeConfiguration="false"/>

IService1.cs file:
 public interface IService1
{

    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetViewData")]
    //string GetData(string value);
    List<wsUpcomingDissertationsView> GetViewData();

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);

    // TODO: Add your service operations here
}

Service1.svc.cs
 public class Service1 : IService1
{
    //public string GetData(string value)
    //{
    //    return string.Format("You entered: {0}", value);
    //}

    public List<wsUpcomingDissertationsView> GetViewData()
    {

        Upcoming_Dissertations_ViewDataContext dc = new Upcoming_Dissertations_ViewDataContext();
        List<wsUpcomingDissertationsView> results = new List<wsUpcomingDissertationsView>();

        foreach (Upcoming_Dissertations_View UDV in dc.Upcoming_Dissertations_Views)
        {
            results.Add(new wsUpcomingDissertationsView()
            {
                First_Name = UDV.FIRST_NAME,
                Last_Name = UDV.LAST_NAME,
                exam_oral_date = UDV.exam_oral_date,
                Expr1 = UDV.Expr1,

            });
        }

        return results;
    }

A: UPDATE:
I got it to work after hours of trial and error. I made some modifications:
<system.serviceModel>
<services>
  <service name="JSONWebService.Service1">
    <endpoint address="" binding="webHttpBinding" contract="JSONWebService.IService1" bindingConfiguration="webBinding" behaviorConfiguration="webBehaviour"/>
  </service>
</services>
<bindings>
  <webHttpBinding>
    <binding name="webBinding">
      <security mode="Transport">
      </security>
    </binding>
  </webHttpBinding>
</bindings>


text:
Q: a little uitextview position i am writing this code to load a plist into 2 textview but i want them to adjust their height according to content size which i have done but i want the second uitextview to start from where the first one ends .. please help
 for (int i = 0; i < arrresult.count; i++) {

    NSArray *sorteddetail = [self.arrresult sortedArrayUsingFunction:sortint context:NULL];
    DuaObject *duaobj2 = [[DuaObject alloc] initWithFilePath:[sorteddetail objectAtIndex:i]];
    [duaobj2 loadFile];

    CGRect frame;
    frame.origin.x = self.scrollmain.frame.size.width * i;
    frame.origin.y = 0;
    frame.size = self.scrollmain.frame.size;

    UITextView *subview = [[UITextView alloc] initWithFrame:CGRectMake((frame.origin.x)+40,(frame.origin.y)+10, 230, 120)];
    UITextView *subview2 = [[UITextView alloc]initWithFrame:CGRectMake((frame.origin.x)+40,(frame.origin.y)+160,230, 120)];

    subview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"BG_text.png"]];
    subview2.backgroundColor = [UIColor whiteColor];

    [subview setFont:[UIFont boldSystemFontOfSize:14]];
    [subview2 setFont:[UIFont boldSystemFontOfSize:14]];

    subview.layer.cornerRadius = 10 ;
    subview2.layer.cornerRadius = 10;

    NSString *p = [duaobj2 dua_arabic];
    NSString *b = [duaobj2 eng_trans];

    subview.text = p;
    subview2.text = b;

    [self.scrollmain addSubview:subview];
    [self.scrollmain addSubview:subview2];

    subview.editable = NO;
    subview2.editable = NO;

    subview.textColor = [UIColor blackColor];
    subview2.textColor = [UIColor blackColor];

    subview.backgroundColor = [UIColor whiteColor];
    subview2.backgroundColor = [UIColor whiteColor];

    scrollmain.showsHorizontalScrollIndicator = NO;

    CGRect frame1 = subview.frame;
    CGRect frame2 = subview2.frame;

    frame1.size.height = subview.contentSize.height;
    frame2.size.height = subview2.contentSize.height;

    subview.frame = frame1;
    subview2.frame = frame2;

}

A: You can use two UIWebView for this. After fetching text data from plist ,redirect it on particular web view. and use [webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] method to get height in pixel. According to height of pixel you can re-adjust web views frame.
Edit:
Look this one : How do I size a UITextView to its content?
It will help you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling an IBAction from another method I am new to Objective-C, Xcode and all of the good stuff. I am self teaching.
I am trying to call an IBAction from another method.
- (IBAction)strAdj:(UIStepper *)strStepper
{
    // Converts stepper to integer
    NSUInteger strvalue = strStepper.value;

    // Changes the the text to the value of the stepper
    strStat.text = [NSString stringWithFormat:@"%2d", (unsigned)strvalue];

    _strMod.text = [NSString stringWithFormat:@"%2d", (unsigned)stepperAdj(strvalue)];
    // Based on the value it change the strMod to a specific value
}

I am only posting a portion of the next code. It is a simple switch statement. I basically want to call the IBAction above in the Void below.
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (row) {
        case 0:
            break;
// Core races never change
        // defines dwarf stats
        case 1:
            // sets all the increases
            tempCon = 2;
            tempWis = 2;
            tempChr = -2;

            // resets all other stats
            tempStr = 0;
            tempDex = 0;
            tempInt = 0;

            // I want to call the IBAction here...

            break;

This IBAction will need to occur ultimately 15 times. The above switch statement occurs when the picker is changed. Where as the IBAction happens every time the stepper occurs.
I hope that I am not too far from what I want to do. Again I have only been working with this for the last several days and I have not been able to find what I am looking for or if I did then I wasn't sure what to do.

A: It kinda looks like you have a dropdown for the player to select a race and each attribute (str, con, wis, etc.) has a stepper to bump the respective values up or down.
I don't know enough to speculate, but I suspect there is a better approach overall.  That said, I think a brute force solution to what you are trying to do is to make sure each of your steppers has a referencing outlet: stepperWis, stepperCon, stepperInt, etc.  Then in your switch you can do something like so (for each attribute):
stepperWis.value = (whatever value you want);
[self strAdj:self.stepperWis];

A: You can call UIButton TouchUpInside event programatically like :
[YourButtonObject sendActionsForControlEvents: UIControlEventTouchUpInside];


text:
Q: How can I deliver a HTML form created by Django or DRF to React? I'm using React, Django, and DRF.
I wanna send a form consisting of HTML that is auto-generated in Django to React in JSON.
Below is a simple example.
[
    {
        "html": "
Writer:	<input type="text" name="writer" maxlength="20" required id="id_writer">
"
    }
]

I've seen a few times recommending Django as an just JSON API server.
But Django forms are really convenient so I wanna make the most of it.
So I have a few questions I'd like to ask you about.

*

*Is this possible?

*If possible, do you think this is a proper way? I mean, in terms of the philosophy of each framework and library.


text:
Q: Comparing prices between different stores (non-parametric models?) I have thousands of product info in a database with category, title, description, make, model, price and store name. I have grouped those products by store names and it seem to span to 4 stores. So thousands of products in those 4 stores.
I want to compare every store's product with rest of stores' products to see if a product in store A is present in Store B or Store C or Store D.
After reading about Ranking, I think it's non-parametric models which I am going to need. But by reading Non-parametric Statistics I found a lot of methods there and I have never used any of them before. I have used very basic stats like mean, median, variance, regression etc. I am looking for your opinion about what non-parametric method will best estimate product comparisons.

A: My first advice would be to create some plots to visualize your data. Exactly what plot will depend on what software is available to you, what you are comfortable with, and also on the question you want to address.
To know if stores tend to carry products with different price points, I would just plot the price of the various products side-by-side, a bit like the last three plots on this page. You can get a lot of insight from such plots, not only if the average level looks different but also if there is a lot of overlap between stores or if the distributions differ in other ways (perhaps two stores have a similar distribution on the lower end but only one of them carries a few very expensive products or may some store has a wider range of products etc.)
If you want to know if the same products are sold at different prices in different stores, creating an interesting plot is a little more complicated, you could try to represent the differences between pairs of stores or do something like

but it can become unwieldy with a lot of data.
Of course, if there is little overlap in the range of products, the second approach could suggest that two stores are similar even though one sells mostly expensive luxury goods and the other cheap brands only because the few products they have in common are priced similarly. You need to recognize that those are two different question and interpret the results accordingly.
Regarding inferential statistics, one-way ANOVA or Kruskal–Wallis one-way analysis of variance could be relevant to address the first question and repeated-measures ANOVA or Friedman's test to address the second one but given the way you described your problem, I am not sure that running a test would really be helpful.


text:
Q: sql server Reporting Services for subtotals I am new SSRS
I have table that looks like
   Month Sales
   Aug    222
   Aug    500
   Sep    80
   Sep    100

I want totals Sales in  total sales of AUG and  total sales SEP separately .
It should look like
Month                        Sales
Total sales in Aug
Total sales in Sep

A: You can create a Row Group on Month field and use =SUM(Fields!Sales.Value) to get the total per month, only if you are using a tablix.
If you don't want to use a tablix but you want to show the values in separated textboxes you can use expressions like this for every month:
=SUM(IIF(Fields!Month.Value = "Aug",Fields!Sales.Value,0),"DataSetName")

Replace "Aug" by the month you want to get the total.
Let me know if this helps.


text:
Q: Set comprehensions in Python and testing for membership in the set being created This is actually question about the semantics of set comprehensions, but I first need to explain the context. I'm trying to create a new set of tuples where the paired value in the touple is unique regardless of the order of the values in the pair. Simplifying my actual program, what I have is something like {(1, 2), (2, 1), (3, 4)} and I'd like to get {(1, 2), (3, 4)}
I tried doing something like this:
oldSet = {(1, 2), (2, 1), (3, 4)}

newSet = set()
newSet = {(val1, val2) for (val1, val2) in oldSet if not (val2, val1) in newSet}

However, newSet is {(1, 2), (2, 1), (3, 4)}, implying that something is wrong with my conditional expression. My understanding of comprehensions suggests that the above is syntactic sugar for something like this:
newSet =  set()
for (val1, val2) in oldSet:
  if not (val2, val1) in newSet:
    newSet.add((val1, val2))

This traditional looping structure works (newSet is {(1, 2), (3, 4)}). Is there something about comprehensions that causes the conditional to be evaluated before newSet has any members? I'm fairly new to Python, so I'm wondering if there's something subtle I'm missing.
Thanks!

A: You misunderstood; the set comprehension is a distinct expression, separate from the assignment. The expression produces a new set() object that then will be assigned to newSet, replacing the old set() object you had.
As such, as you iterate and build the set, the previous and separate set() object bound to newSet remains empty. In reality, the set comprehension does this:
newSet = set()
_result = set()
for (val1, val2) in oldSet:
    if not (val2, val1) in newSet:
        result.add((val1, val2))
newSet = _result

You could use side effects to alter a separate set as you iterate:
seen = set()
newSet = {(val1, val2) for (val1, val2) in oldSet
          if not ((val2, val1) in seen or seen.add((val1, val2))}

This uses seen to track what has already been processed and includes a tuple if both conditions are true:

*

*the inverse has not already been seen before,

*the seen.add() operation for the tuple returns a false value. Since seen.add() always returns None, that is always going to be the case.

Note that this now builds the same set twice, so you may as well do a regular loop and be done with it:
newSet = set()
for (val1, val2) in oldSet:
    if not (val2, val1) in newSet:
        newSet.add((val1, val2))

Since your tuples are consist of two values only, you may as well use sorting here; any pair of tuples (a, b), (b, a) has one unique sorting, after all:
newSet = {tuple(sorted(t)) for t in oldSet}

A: A working alternative is:
newSet = { tuple(sorted(t)) for t in oldSet }

Your solution is checking the presence of the tuple in the set that is being generated, but the name is not bound to the value yet. It will when the comprehension terminates.


text:
Q: SQL DISTINCT WITH TWO VARIABLES I am creating a messaging site, with php and ajax.
there is a problem on getting conversations.
The problem is that whenever two user chat between them there is two distinct rows with id;
example
A and B is chattting and only written 4 messages to each other
messages database is like this
id senderid recieverid
1   a.id      b.id
2   b.id      a.id
3   b.id      a.id
4   a.id      b.id

My aim is getting records with this code
SELECT DISTINCT senderid, recieverid from messages WHERE (senderid = '".$pageowner."' OR recieverid='".$pageowner."')

the $pageowner is the user who logged in;
with this method i get two same conversations
a<->b and b<->a
and the code gives me two conversations on the page i want to only get one result;
my whole php code is like this
if(isset($_POST['id'])){
    include 'config.php';
    $pageowner = $_POST['id'];
    $sql = "SELECT DISTINCT senderid, recieverid from messages WHERE (senderid = '".$pageowner."' OR recieverid='".$pageowner."')";
    $result = mysqli_query($connect, $sql);
    $conversations = mysqli_fetch_all($result);

    $output = "";
    foreach($conversations as $conversation){
        $senderonmessages = $conversation[0];
        $recieveronmessages = $conversation[1];
        if($pageowner == $senderonmessages){
            $convname = $recieveronmessages;
        }else{
            $convname = $senderonmessages;
        }
        $sql = "SELECT id, name, surname, userimage FROM users WHERE id='".$convname."' ORDER BY id" ;
        $resconv = mysqli_query($connect, $sql);
        $user = mysqli_fetch_assoc($resconv);
        $output .= '

'.$user['name'].' '.$user['surname'].'

Axirinici yazdigim mesaj 10:34 AM

                            1

';
    }
    echo $output;
 }

A: You need to fix your sql injection problem first. If you don't do that, you won't have any data in your database to worry about because somebody will drop it.
https://www.php.net/manual/en/security.database.sql-injection.php
Also, your query gives you exactly what you are asking for: DISTINCT senderid, recieverid
For a solution to your question, I'd create a view that is something like:
create view conversations as
SELECT senderid, recieverid FROM messages GROUP BY 1, 2
UNION
SELECT receiverid, senderid FROM messages GROUP BY 1, 2

Then, you can select from this view and get what you want.
As mentioned in the comment the UNION will give you distinct so you don't even need that...


text:
Q: Managing queries with dynamic parameters in a MVC application I'm developing a web application in which users can save queries, conecction strings and the query parameters as a row of a table in the app database. Later, the application will offer a dropdown with all the queries saved in the database, and the user could select a desired query to run.
My issue is that I'll have the queries with the following format:
select * from table where field = {0} and field = {1}

I will have a column in the database with the exact amount and type of every parameter, that would be something like this: "D|N|S", indicating date, number or string, accordingly.
In the application, I currently have a controller action that retrieves the query in one string and the parameters in another one, so in the controller I know how many and which type of parameters the query has, but I can't come with a good solution of how to create html controls in the view for the user to enter values for such parameters. Since I don't know how many parameters the query has until the controller fetchs it from the database, I'm unsure how to proceed.
Thanks in advance.

A: This will help you get started:
It will add dynamic input elements inside a form. The form directs to a controller post action which will receive list of SqlParams , there you can do whatever you want.
Of course you must add your validations, and adjust it to your needs, it looks something like this:
Server:
public class HomeController : Controller
    {

        public class SqlParams
        {
            public string Name { get; set; }
            public string Value { get; set; }
            public string ParamType { get; set; }

        }

        public ActionResult SQL()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SQL(List<SqlParams> sqlParams)
        {

            foreach (var item in sqlParams)
            {
                //Do whatever
                string query = string.Format("{0} = {1}, {2}",item.Name,item.Value, item.ParamType);
            }

            return View();
        }
}

The view:
<button type="button" onclick="Add();">Click to add param</button>

<form action="@Url.Action("SQL")" method="post">

    <button type="submit">Save query</button>
</form>

@section scripts {

    }

A: I would have a class for the query and parameter, with the query having a collection of parameters.
public class SomeQueryClassName
{
    public int QueryId { get; set; }
    public string ConnectionString { get; set; }
    public string CommandText { get; set; }
    public List<SomeParameterClassName> Parameters { get; set; }

    public SomeQueryClassName()
    {
        ....
    }
}

public class SomeParameterClassName
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string DataType { get; set; }
    public object Value { get; set; }

    public SomeParameterClassName()
    {
        ....
    }
}

Then in your controller get the query and return the list of parameters as your model.
public ActionResult GetQuery(int queryId)
{
    var query =
    return View(SomeFunctionToGetTheQuery(queryId).Select(x => x.Parameters).ToList());
}

public ActionResult RunQuery(List<SomeParameterClassName> parameters)
{
    //some server side validation

    //GetQueryResults will add the parameters and execute the query
    return View(GetQueryResults(parameters);
}

And then in the view
using (Html.BeginForm())
{
    for (int i = 0; i < Model.Count; i++))
    {
        var parameter = Model   [i];

                @parameter.Description

                <input type="text" name="[i].Value" class="someClassUsedForClientSideValidationBasedOnParameterDataType" />
                <input type="hidden" name="[i].Name" value="@parameter.Name"/>
                <input type="hidden" name="[I].DataType" value="@parameter.DataType"/>

    }
}

Make sure when you're saving/executing your queries that you're using parameterized queries and adding parameters rather than concatenating values into the query.
using (var connection = new SqlConnection("some connection string"))
{
    connection.Open();

    string cmd = "select * from testable where testcolumn = @testvalue";

    using (var command = new SqlCommand(cmd,connection))
    {
        command.Parameters.AddWithValue("testvalue",somevalue);

        //execute query and return data in a datatable or yield return objects
    }

    connection.Close();
}


text:
Q: Use pre-defined EXPORT_TAGS within EXPORT and EXPORT_OK I have created a couple of EXPORT_TAGS within my module as below,
package My::Module;

use strict;
use warnings;

require Exporter;

our @ISA = qw ( Exporter );

our %EXPORT_TAGS = (
    'set1' => [
        qw(
            &func1
            &func2
        )
    ],
    'set2' => [
        qw(
            $var1
            $var2
        )
    ],
    'set3' => [
        qw(
            &sub3
            &sub4
        )
    ]
);

# remaining module code

I am now trying to declare the exportable symbols within the EXPORT and EXPORT_OK arrays by simply giving the export tags, instead of specifying each one individually,
our @EXPORT = $EXPORT_TAGS { 'set2' };
our @EXPORT_OK = (
    $EXPORT_TAGS { 'set1' },
    $EXPORT_TAGS { 'set3' }
);

In my target script, I am invoking my module as below,
use My::Module qw ( :set1 :set3 );

The module compiles without errors. However, the target script doesn't and I receive the following error when I try to use the variables/function belonging to the module,
Global symbol "$var1" requires explicit package name`
What am I missing/overlooking? Thanks for the help.

A: The things in %EXPORT_TAGS are arrayrefs; you need to dereference them to flatten them into @EXPORT and @EXPORT_OK. You want to write:
our @EXPORT = @{ $EXPORT_TAGS { 'set2' } };
our @EXPORT_OK = (
    @{ $EXPORT_TAGS { 'set1' } },
    @{ $EXPORT_TAGS { 'set3' } },
);


text:
Q: Jenkins multibranch pipeline build mysteriously setting origin to local repo I'm using Jenkins to perform a multi-branch pipeline build using a github repo, this my checkout stage, contains a single line: checkout scm
However, when I instigate builds on any of the branches other than master, I get the following:
[Pipeline] {
[Pipeline] stage
[Pipeline] { (git checkout)
[Pipeline] git
 > git.exe rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git.exe config remote.origin.url file:///C:/Projects/Demo
# timeout=10
Fetching upstream changes from file:///C:/Projects/Demo

Its almost as if my repo on GitHub things that its origin is on my laptop, can someone advise as to what is awry here ?

A: I eventually figured this out, the answer is in two parts, firstly the "Critical section" that is wrapped by the lock command needs to be present in the Jenkinsfile associated with each branch:
stage('start container') {
        steps {
            RemoveContainer()
            timeout(time: 20, unit: 'SECONDS') {
                lock ('create SQL Server container') {
                    StartContainer()
                }
            }
        }
    }

and secondly, the commands to get the next available port and spin-up the container need to be in the same method that is wrapped by lock.


text:
Q: How can i create a golf gps app showing the distances for each golf hole Trying to develop a Golf Gps app to show the distance to the golf hole to front , middle and back of the golf green..There are many Golf GPS app available. Trying to know if there are API's available as its not possible for a single golf app developer to list out all the golf course in the world but they are doing it i guess through some API. Wanted to know the best way to do it.. Thanks
Unable to find any Golf GPS API


text:
Q: Castle Windsor unable to resolve classes which implement WPF's ICommand I am seeing some strange behaviour whilst trying to register WPF ICommands using Castle Windsor.
When running the included code, I get the following error:
Can't create component 'ConsoleApplication1.TestParent' as it has dependencies to be satisfied.
ConsoleApplication1.TestParent is waiting for the following dependencies:
Keys (components with specific keys)
testChild which was not registered.
However if I change the interface on TestChild from ICommand to ITest then the code works just fine.
Has anyone else witnessed this behaviour and/or know how to resolve it?
I am using VS2008, .NET 3.5 and Castle 2.5.2.
Thanks,
Stuart

    using System;
    using System.Windows.Input;

    using Castle.MicroKernel.Registration;
    using Castle.Windsor;

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var container = new WindsorContainer();

                container.Register(
                    Component.For<TestParent>().ImplementedBy<TestParent>(),
                    Component.For<TestChild>().ImplementedBy<TestChild>()
                    );

                var parent = container.Resolve<TestParent>();
            }
        }

        public interface ITest {}

        public class TestParent
        {
            public TestParent(TestChild testChild) { }
        }

        public class TestChild : ICommand
        {
            public event EventHandler CanExecuteChanged;
            public bool CanExecute(object parameter) { return true; }
            public void Execute(object parameter) {}
        }
    }

A: I am seeing some strange behaviour whilst trying to register WPF ICommands using Castle Windsor.
When running the included code, I get the following error:
Can't create component 'ConsoleApplication1.TestParent' as it has dependencies to be satisfied.
ConsoleApplication1.TestParent is waiting for the following dependencies:
Keys (components with specific keys)
- testChild which was not registered.
However if I change the interface on TestChild from ICommand to ITest then the code works just fine.
Has anyone else witnessed this behaviour and/or know how to resolve it?
I am using VS2008, .NET 3.5 and Castle 2.5.2.
Thanks,  Stuart
using System;
using System.Windows.Input;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var container = new WindsorContainer();

            container.Register(
                Component.For().ImplementedBy(),
                Component.For().ImplementedBy()
            );

            var parent = container.Resolve();
        }
    }

    public interface ITest {}

    public class TestParent
    {
        public TestParent(TestChild testChild) { }
    }

    public class TestChild : ICommand
    {
        public event EventHandler CanExecuteChanged;
        public bool CanExecute(object parameter) { return true; }
        public void Execute(object parameter) {}
    }
}

A: Ignoring the fact that your code sample does not compile due to incorrect calling of Windsor registration, could it be you could want something like this?
class Program
{
    static void Main(string[] args)
    {
        var container = new WindsorContainer();

        container.Register(
            Component.For<TestParent>(),
            Component.For<ICommand>().ImplementedBy<TestChild>()
        );

        var parent = container.Resolve<TestParent>();
    }
}

public class TestParent
{
    public TestParent(ICommand testChild) { }
}

public class TestChild : ICommand
{
    public event EventHandler CanExecuteChanged;
    public bool CanExecute(object parameter) { return true; }
    public void Execute(object parameter) {}
}

}
Note that I removed the ITest interface definition, no clue what that was used for.

A: the TestParent class has only one constructor, which requires passing an object parameter. If it were a basic data type like int or string, you could specify its value in the App.config file. But you can't set objects there. In this case, I recommend you add a blank constructor (without parameters).

A: Thanks for the replies.
Since the corporate filter at work refuses to display the "Captcha" human verification I had to cut and paste from my iphone... anyway this somehow removed the generics from the code sample so apologies for the lack of compilation not to mention the fubar layout...
Should look like:
    private static void Main(string[] args)
    {
        var container = new WindsorContainer();

        container.Register(
            Component.For<TestParent>().ImplementedBy<TestParent>(),
            Component.For<TestChild>().ImplementedBy<TestChild>());

        var parent = container.Resolve<TestParent>();
    }

Registering ICommand does work, however it doesn't solve my problem since I have multiple commands in my real app and I need to Castle to distinguish between them.
I have managed to work around this by creating dummy interfaces for every one of the commands and registering against those - not ideal.
The ITest interface was to allow switching from ICommand and ITest which resolves the issue - i.e. the issue is specific to WPF ICommand.
Stuart


text:
Q: Compiler design prevent register override I'm trying to write a compiler for a self-designed CPU with accompanying instruction set. The CPU has 3 registers, 2 input registers (B and C) and one output register (D). When for example an ADD instruction is executed the sum of B and C is calculated and stored in D.
I'm trying to write the compiler with the visitor design pattern: I have a bunch of language tree classes like "IfStatement", "Addition", "Integer" and a visitor "Compiler". The visitor would look at each node of the tree and append bytecode to the end of the bytecode list. I can't figure out how to cleanly handle register overrides: when evaluating the expression
2*(7+3)

the generated bytecode is
PUTb 2
PUTb 7
PUTc 3
ADD
MOVE D C
MUL

As you can see the 2 is overridden by the 7.
I want the compiler to realize it can reverse the order to
(7+3)*2

or that it can store temporary result is RAM, using some other instructions, this will certainly be necessary for more complex expressions like
(7-5)*(8+3)

Is there a clean/object-oriented way to handle this? Is the Visitor pattern not appropriate here? Do I need to look at some advanced techniques like register coloring? The compiler will be written in Java, bu I don't think that really matters.

A: You're going to need an overflow area, perhaps a stack, or some chunk of memory.
You'll also want to get the generated code correct before optimizing it, because optimizing broken code is basically impossible.
So , given a stack, you should have something like: PUT b,2; Push b; Put b,7; Put c,3; ADD; Pop b; MUL and if using memory, PUT b,2; Store b @1; Put b,7; Put c,3; ADD; Load b @1; MUL.  Next, to get the optimization, you can have a separate pass that balances the tree, by changing the order of the operands based on simple weight.
EDIT:
You create a data structure that tracks the contents of the registers (you might assume empty at statement start).  Each time you generate an instruction you update that data structure to mark what is in it (e.g. what tree node and/or what operand, i.e.variable or constant, or overflow temporary variable).
Before you generate an operation, you ensure that its sources are in the registers as needed, and if not you perform a load from the overflow area, or variable area, or constant area/immediates, or from another register.
(By design, you shouldn't have the case where you need to generate anything else at this point other than a load of some kind, e.g. if you are about to generate the MUL, you won't have to generate an ADD, because that should have been handled already in by the appropriate visiting traversal.)
But -- before you do any load of operands (which will overwrite the register) you generate a store to an overflow area if there is anything being tracked.  Also do the same for the target/output register (e.g. of MUL).  And the whole time updating your tracking structure so the next instruction generated will have the state of the registers & overflow temps as of the current point in the code.


text:
Q: Partial Client Certificate request for Apache HTTP I have an Apache HTTP Server with SSL enabled and requesting a Client Certificate.
How do I set up Apache to only request the certificate when a user hits a certain part of the website?
Example:
/myapp/ should not request the cert
/myapp2/ should request the cert
Note: These applications are being served using the mod-jk

A: Someting like this should do the magic:
<Directory /myapp2>
  SSLVerifyClient require
</Directory>

<Directory /myapp>
  SSLVerifyClient none
</Directory>

More info about SSLVerifyClient directive here.

A: The trick here is that you need to do this in tomcat. Since that is what is actually proccessing the request.
Since client auth is on a per connector basis you'll need to create 2 new connectors. One for the base SSL w/ auth, and one for the mod_jk connector (chosen ports arbitrarily chosen as cur+1).
 <!-- Client Auth Connector on port 8444 -->
    <!--
    <Connector port="8444"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" disableUploadTimeout="true"
               acceptCount="100" debug="0" scheme="https" secure="true"
               clientAuth="true" sslProtocol="TLS" />
    -->

    <!-- Client auth ajp connector on port 8010 -->
    <Connector port="8010"
               enableLookups="false" redirectPort="8444" debug="0"
               protocol="AJP/1.3" />

Then just setup a secondary mod_jk worker to connect to the client auth SSL in apache for /myapp2

A: This might work: http://httpd.apache.org/docs/2.0/ssl/ssl_howto.html#arbitraryclients
How can I authenticate my clients for a particular URL based on certificates but still allow arbitrary clients to access the remaining parts of the server?
For this we again use the per-directory reconfiguration feature of mod_ssl:
httpd.conf
SSLVerifyClient none
SSLCACertificateFile conf/ssl.crt/ca.crt

<Location /secure/area>
SSLVerifyClient require
SSLVerifyDepth 1
</Location>


text:
Q: VertexBuffer3d or ExternalInterface is too slow, how can I optimize? I'm finding some problems uploading a VertexBuffer to the context.
This buffer is ~200000 items long and it takes about +15 seconds, apparently the player has some difficulties uploading it to the context.
Does anyone experienced this? Any solution?
I'm trying to upload the vector in chunks with no success (for now...  )
Update:
Apparently the problem is not the upload, but somewhere else. The data is creating from javascript since is a customized ThreeJS fallback. It works great for small scenes but it slows down exponentially for bigger projects.
Right now I am also investigating ExternalInterface communication speed.
Thanks!

A: Uploading with ByteArray is faster, btw it changed quite a lot from player to player. there is a test between ByteArray and Vector http://jacksondunstan.com/articles/1617 try this with your GPU. and also you can do this with async flag or from separate thread


text:
Q: Video camera tape to PC, recommended formats? I have a stack of MiniDV tapes from an age old video camera and want to import the videos. Right now I'm using VirtualDub and a capture card to import the raw data.
What 2 formats (and settings) can anyone recommend (and respective software) for the following requirements?
An editable format
Something that retains as much data as possible for later editing/conversion. But obviously far smaller than raw AVI as ~50GB/hr is a little too much for me. (Please see extra notes for the raw AVI's details)
A playable format
For distributing to family and friends, so: small and good quality. (I was considering DivX). This could have possibly been answered here (but it looks like the answers tend towards Linux).
Extra notes:

*

*Raw output @ 640x480, 25fps, 119738kbps (so we're not looking at AVCHD)

*I'm on Windows 7

A: Consider buying/borrowing a device, card, laptop, or computer that has a FireWire/iLink/IEEE-1394 port. That way, you can copy the actual DV bytes directly, with no sampling/generation loss, and it's intended as an edit format. It's 13GB per hour. 720x480 non-square pixels.
Barring that, you can consider a lossless codec like Lagarith.
For distribution, H.264 has the broadest support, including mobile devices. You can use Handbrake.


text:
Q: XNA: Orthographic Projection that matches Screen Coordinates I am using XNA with SpriteBatch and custom drawn verticies in parallel. The goal is to have the same coordinate system for both techniques.
That means I need a projection matrix that maps to screen coordinates: (0, 0) is in the top left screen corner, while width and height are determined by the screen resolution.
Matrix.CreateOrthographicOffCenter(0, width, 0, height, -1, 1);
Works well but has the center in the bottom-left corner.
Matrix.CreateOrthographicOffCenter(0, width, height, 0, -1, 1);
Does not display anything at all.
Trying to combine the first projection matrix with a translation and scaling y by -1 does not display anything at all either. Scaling by positive values works well, translation too. But as soon as I scale by a negative value I do not get any output at all.
Any ideas?
PS: For testing purpose I am drawing vertices far beyond the screen coordinates, so I would at least see something if there is some error in translation.

A: I use this code to initialize my 2D camera for drawing lines, and use a basic custom effect to draw.
    Vector2 center;
    center.X = Game.GraphicsDevice.Viewport.Width * 0.5f;
    center.Y = Game.GraphicsDevice.Viewport.Height * 0.5f;

    Matrix View = Matrix.CreateLookAt( new Vector3( center, 0 ), new Vector3( center, 1 ), new Vector3( 0, -1, 0 ) );
    Matrix Projection = Matrix.CreateOrthographic( center.X * 2, center.Y * 2, -0.5f, 1 );

Effect
uniform float4x4 xWorld;
uniform float4x4 xViewProjection;

void VS_Basico(in float4 inPos : POSITION,  in float4 inColor: COLOR0,  out float4      outPos: POSITION,    out float4 outColor:COLOR0 )
{
    float4 tmp = mul (inPos, xWorld);
    outPos = mul (tmp, xViewProjection);
    outColor = inColor;
}

technique Lines
{
    pass Pass0
    {
        VertexShader = compile vs_2_0 VS_Basico();
        FILLMODE = SOLID;
        CULLMODE = NONE;
    }
}


text:
Q: Let $R$, $S$ be rings with identity and $f: R\to S$ a homomorphism. Is there a name for the this subset of the units of $R$? Let $U(R)$ be the set of units in $R$ (the elements that have multiplicative inverses), and consider the subset $\{r\in U(R): f(r) = 1\}$. That is, the set of elements of $U(R)$ that are mapped to the multiplicative identity of $S$. This is analogous to the kernel of $f$, but clearly isn't a subring since if $f(r)=f(s)=1$ then $f(r+s) = f(r)+f(s)=1+1\ne1$. It seems to be a subgroup under multiplication though, since $f(rs) = f(r)f(s) = 1\cdot 1=1$, and $f(r^{-1}) = f(r)^{-1}=1^{-1}=1$. Is there a name or any other interesting properties of this subset (subgroup) of $U(R)$?
My apologies if this question has been asked before; since I don't have a name for it, I wouldn't know what to search for.

A: Every unital morphism between rings $f\colon R\to S$ induces a multiplicative group homomorphism, which we might denote $U(f)\colon U(R)\to U(S)$. Your set is $\mathrm{ker}(U(f))$.

Note that there is a functor from the category of rings with unity and unital morphisms (morphisms that must send the multiplicative identity to the multiplicative identity) to the category of groups, $U\colon \mathscr{R}ing^1\to\mathscr{G}roup$, defined by mapping a ring $R$ to its unit group $U(R)$, and a morphism $f\colon R\to S$ to the restriction $U(f)=f|_{U(R)}$. This is a functor, since
$$\begin{align*}
U(\mathrm{id}_{R}) &= \mathrm{id}_{U(R)}\\
U(g\circ f) &= (g\circ f)|_{U(R)} = g|_{U(S)}\circ f|_{U(R)} = U(g)\circ U(f).
\end{align*}$$
Your set can also be seen as the image of the kernel under the functor.


text:
Q: Representing dimensions in Dirac delta function results The Dirac delta function can be defined as $$\delta(x)=\frac{1}{2\pi}\int_{-\infty}^\infty e^{itx}dt$$
From this we see that the dirac function has units of $x^{-1}$.

How do we represent the units in cases like the momentum eigenvectors which, when units are included, is represented as
  $$\frac{1}{\sqrt{2\pi\hbar\cdot(kg^{-1}m^{-1}s)}}e^{\frac{\iota px}{\hbar}}$$
  or
  $$\frac{1}{\sqrt{2\pi\hbar}}e^{\frac{\iota px}{\hbar}}\cdot(kg^{\frac{1}{2}}m^{\frac{1}{2}}s^{-\frac{1}{2}})\,?$$
Is there a preferred way to write the units(not constrained to SI units, any other system including natural units too) or do we just leave them out, though it would be dimensionally inconsistent without implied units.

Sources I can find for the momentum eigenvector ignore the units of the delta function without even mentioning.
P.S.
The problem comes when trying to normalize the momentum operator.
Define
$$\psi_p(x)=Ae^{\frac{\iota px}{\hbar}}$$
Over here, $A$ has units of $m^{-\frac{1}{2}}$.
Normalizing it,
$$\int_{-\infty}^\infty\psi^*_{p_1}(x)\psi_{p_2}(x)dx$$
$$=|A|^2\int_{-\infty}^\infty e^{\frac{\iota \left(p_2-p_1\right)x}{\hbar}}dx$$
$$=|A|^22\pi\hbar\delta\left(p_2-p_1\right)$$
Therefore, ignoring consistency of units, and assuming $A$ is positive,
$$A=\frac{1}{\sqrt{2\pi\hbar}}$$
Notice that the units do not match

A: The dimension of the Dirac delta function is the inverse of the dimension of its argument. So if $x$ is a length then $\delta(x)$ has the dimension of inverse length.
In your example, the momentum eigenstate in position representation has the wavefunction
$$
\psi_p(x) = A \mathrm{e}^{i p x / \hbar}
$$
The interpretation of the wavefunction is that $|\psi|^2$ is a probability density, which is dimension of 1/Length. Therefore, $A$ has dimension of $1/\sqrt{\mathrm{Length}}$.
As you say, calculating the scalar product of two momentum eigenfunction with eigenvalues $p_1$ and $p_2$ gives
$$
\int_{-\infty}^\infty \mathrm{d}x \, \psi_{p_1}^*(x) \psi_{p_2}(x)
= |A|^2  \int_{-\infty}^\infty \mathrm{d}x \mathrm{e}^{i(p_2-p_1)x/\hbar}
= |A|^2 2\pi \hbar \delta(p_2 - p_1)
$$
The left-hand side is dimensionless, and therefore so is the right-hand side. $\hbar \delta(p_2-p_1)$ has dimension of Length, so again we get that the dimension of $A$ is $1/\sqrt{\mathrm{Length}}$.

A: I am not entirely sure what you mean with the notation e.g.
$$\frac{1}{\sqrt{2\pi\hbar\cdot(kg^{-1}m^{-1}s)}}e^{\frac{\iota px}{\hbar}}.$$
The momentum eigenstates are $\psi_p(x) = \frac{1}{2\pi\hbar} e^{ipx/\hbar}$, this is true in any unit system. You don't need to multiply with any units. In the SI system, this has units of
$$ \frac{1}{\sqrt{kg\, m^2\, s^{-1}}} . \tag{*}$$

Define
  $$\psi_p(x)=Ae^{\frac{\iota px}{\hbar}}$$
  Over here, $A$ has units of $m^{-1}$.

Note that $\int |\psi_p(x)|^2\, dx \neq 1$ (the state is not normalizable), therefore there's no reason why the dimension of $A$ should be inverse length! What we use instead of normalization is the following:
$$ \langle p' \mid p \rangle = \int \psi_p(x) \psi_{p'}(x)^\ast dx = \delta(p'-p) , $$
here the $\delta$-function has units of $kg^{-1}\, m^{-1}\, s$ which is fully compatible with (*).
Or maybe it helps you to consider
$$ \delta(x') = \langle x' | x=0 \rangle = \int \psi_p(0)^\ast \psi_p(x')\, dp = \frac{1}{2\pi\hbar} \int e^{ipx'/\hbar}\, dp , $$
where the units also match (of course).

A: The units do add up in the example you provide:
You've correctly established that the delta distribution has the dimension of the inverse dimension of its argument. This can be seen in a variety of ways, e.g. by looking at $\int f(x)\delta(x-x_0) dx = f(x_0)$, where the LHS has to have whatever dimensions $f$ has.
With this, we look at the dimensions of $\lvert A \rvert^2 2\pi\hbar \;\delta(p_1-p_2)$:
$$
\left[\lvert A \rvert^2 2\pi\hbar\; \delta(p_1 - p_2) \right] = \textsf{L}^{-1} \left[ \hbar \delta(p_1-p_2) \right] = \textsf{L}^{-1} \frac{\left[ \hbar \right]}{[(p_1-p_2)]} = \textsf{L}^{-1} [x] = \textsf{L}^{-1} \textsf{L}^{1} = 1,
$$where I have used that $\frac{p}{\hbar}$ has to have inverse dimensions of $x$ to make the argument of the exponential dimensionless.

NB: For $\psi_p(x)=A\exp(\frac{ipx}{\hbar})$, we want $\int \lvert \psi \rvert^2 dx$ to represent a probability, which is dimensionless. From this it follows that $A$ has to have dimensions $\textsf{L}^{-\frac12}$.

A: tl;dr-  Some of the common "definitions" of the Dirac delta function aren't mathematically rigorous, but rather conceptual.  The confusion about units seems to come from these functions being taken more literally than intended.  In reality, it's a unitless factor.

The Dirac delta function can be defined as $$\delta(x)=\frac{1}{2\pi}\int_{-\infty}^\infty e^{itx}dt$$
  From this we see that the dirac function has units of $x^{-1}$.

This doesn't follow.  The Dirac delta function produces a unitless value, typically used as a factor for some other term to zero out that term's value for most values of $x$.

Sources I can find for the momentum eigenvector ignore the units of the delta function without even mentioning.

They're not assigning units because the Dirac delta function itself lacks them.
On the misconception about units cancelling
Below in the comments, @BySymmetry explained the confusion as resulting from the observation that
$$
\int \text{d}x{\delta}\left(x\right)f\left(x\right)=f\left(0\right),
$$
where if we want the units to cancel, then we need ${\delta}\left(x\right)$ to have units of $x^{-1}$.
As Wikipedia notes:

Consequently, the delta measure has no Radon–Nikodym derivative — no true function for which the property
  $$
 \int _{-\infty }^{\infty }f(x)\delta (x)\,dx=f\left(0\right)
$$
  holds.[21] As a result, the latter notation is a convenient abuse of notation, and not a standard (Riemann or Lebesgue) integral.
-Dirac delta function, Wikipedia

In short, this equation is an "abuse of notation", not the actual definition of a Dirac delta function.  So, the idea that it should have units of $x^{-1}$ based on this equation's just a misunderstanding.
Conceptually, the Dirac delta's just a device to make a function zero everywhere but at one point.  It's fundamentally a $0$-or-$1$ multiplication factor, so it just lacks units.  You can write up that definition however you like to make it fit into conventional mathematical notation, but at the end of the day, that's it.
Example of the fallacy
Having units implies that, if you change the units - say from meters to lightyears - then you need to insert a multiplication factor.  But, if you calculate some value with a Dirac delta, then switch your unit of length, do you actually multiply by such a conversion factor?  Doing so would be a mathematical mistake.
The issue's that a Dirac delta's meant to be over an infinitely small space, so assigning it proportionality through units doesn't make sense.


text:
Q: Simple time parsing of a String In the below code i need to get a parse exception.but the program somehow converts it to a valid date.
But if i give dthours as "07:0567" it is giving parse error.So how to keep the exact format shown.
Can anyone tell me what to do to throw an error if the date string deviates from the given format ("HH:MM:SS") even by a single character.
public static void main(String[] args) {

    String dthours="07:4856:35563333";
    SimpleDateFormat df = new SimpleDateFormat("HH:MM:SS");
    try
    {
        Date d = df.parse(dthours);
        System.out.println("d "+d);
    }
    catch (ParseException e)
    {
        System.out.println("parseError");

    }

A: Set the df.setLenient() to false so that the SimpleDateFormat will throw parse exception in such cases.
public static void main(String[] args)
{
    String dthours = "07:4856:35563333";
    SimpleDateFormat df = new SimpleDateFormat("HH:MM:SS");
    df.setLenient(false);
    try
    {
        Date d = df.parse(dthours);
        System.out.println("d = " + d);
    }
    catch (ParseException e)
    {
        System.out.println("parseError");
    }
}

The above snippet would print "parseError" for that input.


text:
Q: What does  represent in Java? I'm new to Java development and I would like to know what does this statment represent:
private ArrayList<Drawable> images;

to new images ArrayList, with this Drawable something?
Thanks to all.

A: These are generics. images is an ArrayList containing Drawable instances. You must always put Drawables (or subclasses of Drawable) inside the images list and you will always get Drawables back.


text:
Q: Order of slots called on QObject I have a QObject that has multiple slots connected to one of its signals. Is there an order in which of each of these slots are called when the signal is emitted?

A: In Qt v4.5 and earlier: No, the order is undefined as can be seen in the documentation here:

If several slots are connected to one signal, the slots will be executed one after the other, in an arbitrary order, when the signal is emitted.

Edit: From version 4.6 onwards this is no longer true. Now the slots will run in the order they are connected. The relevant paragraph of the current documentation:

If several slots are connected to one signal, the slots will be executed one after the other, in the order they have been connected, when the signal is emitted

A: While the order is undefined, up to now, in all Qt versions it has been connect() order, except when Qt::QueuedConnection is used, in which case, of course, it's not even guaranteed that any or all slots have been executed when emit returns. Relying on the order is still discouraged, though.

A: According to Qt documentation:

If several slots are connected to one
  signal, the slots will be executed one
  after the other, in the order they
  have been connected, when the signal
  is emitted.

http://qt-project.org/doc/qt-4.8/signalsandslots.html

A: Relying on what order the slots will be executed is a bad, bad idea, as it defeats both the spirit of the signals/slots connections and leaves you wide open for undesired behavior if you do any sort of programmatic connections of signals & slots.


text:
Q: Blocky gradient effect in CSS3 Is it possible to make the below gradient look more "blocky", so that instead of switching from green to red gradually, it's done in steps like the below picture?
Desired effect:

Currently:

#gradients {
  background-image: -webkit-gradient(linear, left bottom, right bottom, color-stop(0, #00FF00), color-stop(0.5, #FFFF00), color-stop(1, #FF0000));
  background-image: -o-linear-gradient(right, #00FF00 0%, #FFFF00 50%, #FF0000 100%);
  background-image: -moz-linear-gradient(right, #00FF00 0%, #FFFF00 50%, #FF0000 100%);
  background-image: -webkit-linear-gradient(right, #00FF00 0%, #FFFF00 50%, #FF0000 100%);
  background-image: -ms-linear-gradient(right, #00FF00 0%, #FFFF00 50%, #FF0000 100%);
  background-image: linear-gradient(to right, #00FF00 0%, #FFFF00 50%, #FF0000 100%);
}

Ideally, I'd be able to set a variable so I can choose how many blocks the gradient would consist of. Can anyone help?

A: you can use box-shadow if you want certain color to show

#gradients {
  width: 52px;
  display: block;
  height: 30px;
  background: #22b14c;
  box-shadow: #b5e61d 52px 0px 0px 0px,
              #fff200 104px 0px 0px 0px,
              #ffc90e 156px 0px 0px 0px,
              #ff7f27 208px 0px 0px 0px,
              #ed1c24 260px 0px 0px 0px;
}

A: This can be achieved using linear-gradient. Setting multiple colors to the gradient can be done by assigning multiple color stops and the blocky effect can be achieved by making the next color start at the exact same place where the current color ends (that is, same stop percentage for the current color's end position and the next color's start position).
In standards compliant browsers, the following is the only line of code that would be needed:
background: linear-gradient(to right, green 20%,
                            yellowgreen 20%, yellowgreen 40%,
                            yellow 40%, yellow 60%,
                            orange 60%, orange 80%, red 80%);

However, in-order to produce a similar effect in older browser versions, we have to include the vendor prefixed versions also.

div {
  height: 20px;
  width: 450px;
  background: -webkit-gradient(linear, 0 0, 100% 0, color-stop(0.2, green), color-stop(0.2, yellowgreen), color-stop(0.4, yellowgreen), color-stop(0.4, yellow), color-stop(0.6, yellow), color-stop(0.6, orange), color-stop(0.8, orange), color-stop(0.8, red));
  background: -webkit-linear-gradient(to right, green 20%, yellowgreen 20%, yellowgreen 40%, yellow 40%, yellow 60%, orange 60%, orange 80%, red 80%);
  background: -moz-linear-gradient(to right, green 20%, yellowgreen 20%, yellowgreen 40%, yellow 40%, yellow 60%, orange 60%, orange 80%, red 80%);
  background: -o-linear-gradient(to right, green 20%, yellowgreen 20%, yellowgreen 40%, yellow 40%, yellow 60%, orange 60%, orange 80%, red 80%);
  background: linear-gradient(to right, green 20%, yellowgreen 20%, yellowgreen 40%, yellow 40%, yellow 60%, orange 60%, orange 80%, red 80%);
}

For IE 9 and lower, we would have to use filters like mentioned in this CSS Tricks article because they don't support linear-gradient.
Can I Use - Linear Gradients

A: Some examples using gradients:

.gradient {
  width:450px;
  height:20px;
}
.g-1{
  background-color: #FFFF00;
}
.g-3{
  background-image: linear-gradient(
    to right,
    #00FF00 33%, #FFFF00 33%,
    #FFFF00 66%, #FF0000 66%
  );
}
.g-5{
  background-image: linear-gradient(
    to right,
    #00FF00 20%, #80FF00 20%,
    #80FF00 40%, #FFFF00 40%,
    #FFFF00 60%, #FF8000 60%,
    #FF8000 80%, #FF0000 80%
  );
}
.g-9{
  background-image: linear-gradient(
    to right,
    #00FF00 11%, #40FF00 11%,
    #40FF00 22%, #80FF00 22%,
    #80FF00 33%, #C0FF00 33%,
    #C0FF00 44%, #FFFF00 44%,
    #FFFF00 56%, #FFC000 56%,
    #FFC000 67%, #FF8000 67%,
    #FF8000 78%, #FF4000 78%,
    #FF4000 89%, #FF0000 89%
  );
}
.g-17{
  background-image: linear-gradient(
    to right,
    #00FF00 6%, #20FF00 6%,
    #20FF00 12%, #40FF00 12%,
    #40FF00 18%, #60FF00 18%,
    #60FF00 24%, #80FF00 24%,
    #80FF00 29%, #A0FF00 29%,
    #A0FF00 35%, #C0FF00 35%,
    #C0FF00 41%, #D0FF00 41%,
    #D0FF00 47%, #FFFF00 47%,
    #FFFF00 53%, #FFD000 53%,
    #FFD000 59%, #FFC000 59%,
    #FFC000 65%, #FFA000 65%,
    #FFA000 71%, #FF8000 71%,
    #FF8000 76%, #FF6000 76%,
    #FF6000 82%, #FF4000 82%,
    #FF4000 88%, #FF2000 88%,
    #FF2000 94%, #FF0000 94%
  );
}
.g-inf{
  background-image: linear-gradient(
    to right,
    #00FF00 0%,
    #FFFF00 50%,
    #FF0000 100%
  );
}

A: Use multiple stops (although you need to define the substeps, it cannot be done automatically)

#gradients {
  background-image: linear-gradient(to right,
    green       0%,     green       14.28%,
    greenyellow 14.28%, greenyellow 28.58%,
    yellow      28.58%, yellow      42.85%,
    orange      42.85%, orange      57.14%,
    darkorange  57.14%, darkorange  71.42%,
    red         71.42%, red         85.71%,
    brown       85.71%);
}

A:

div {
  height:200px; width:400px; display:block;
  background-image: linear-gradient(to left, #2BFF00 50%, #00A3EF 50%);
}

you see how the stop of #2BFF00 is at the same location of the #00A3EF in 50%.

A: It also can be dynamically generated by Javascript.

var randomColors =  ["#CA5BBA", "#98B0EB", "#045E4F", "#11D7DD", "#44BFEC", "#80865C", "#A48D16", "#CFD00E", "#3289D0", "#15ED3D", "#48C982", "#95DB00", "#E24730", "#F8705D", "#9467EA", "#EC86AF", "#A1E9DE", "#D220CD", "#F4FE91", "#CC6869", "#DD82D3"]

function generateGradientBanding(direction, colors) {
  const gradientParts = []

  colors.forEach((color, i) => {
    gradientParts.push(`${color} ${(100 / colors.length) * i}%`)
    gradientParts.push(`${color} ${(100 / colors.length) * (i + 1)}%`)
  })

  return `linear-gradient(${direction}, ${gradientParts.join(', ')})`
}

$("#canvas").css({backgroundImage:generateGradientBanding("90deg", randomColors)})
#canvas {
  height: 100%;
  width: 100%;
}


text:
Q: How do you use lambda and map instead of list comprehension do iterate over multiple lists? I'm trying to generate the same list using lambda and map which is e as in d.
However, it does not result in a readable list and instead just the positions of maps.
a=[1,2,3,4,5]
b=[1,2,3]
d=[v+w for v in a for w in b]
e=list(map(lambda v: (lambda w:v+w, b),a))

A: Your lambda needs to have two inputs in order to add two values (or else the first value needs to be already-accessible). I would submit that, instead of nesting lambdas inside each other, just use something like itertools.product() to get every (a, b) pair, and then submit each tuple to the lambda.
e = list(map(lambda t:t[0]+t[1], list(itertools.product(a,b))))

in which case, why even bother with a lambda?
e = list(map(sum, list(itertools.product(a,b))))

A: I would not recommend using lambdas for this (or in general) but you can do this with only built in functions.
e = sum(list(map(lambda v: list(map(lambda w: v + w, b)), a)), [])

# Explanation
# Inner map lambda to add each value from b to v
map(lambda w: v + w, b))

# Outer map lambda that loops through each item in a and runs the inner lambda
map(lambda v: list(map(lambda w: v + w, b)), a)

# Flatten result array
sum(result, [])

A: Actually, you cannot just do this with map in any straightforward way, because the equivalent operation here would be a flat-map operation, so you'd have to include a reduce and materialize the iterator in the internal map. It won't be efficient, i.e. it will be quadratic time, but something like
from functools import reduce
reduce(lambda x,y: x+y, map(lambda v: list(map(lambda w: v+w, b)), a))

Would work. If you want to "cheat", use itertools, but this will be efficient:
from itertools import chain
list(chain.from_iterable(map(lambda v: map(lambda w: v+w, b), a)))


text:
Q: Converting to UTF-8 (again) I've this string Traor\u0102\u0160
Traor\u0102\u0160 Should produce Traoré. Then Traoré utf-8 decoded should produce Traorè
How I can convert it to Traorè ?
What kind of chars are Traor\u0102\u0160? Unicode?
I've already read this http://docs.python.org/howto/unicode.html#encodings many times. But I'm still really confused.
I get this data with the following request:
import json
import requests

# making a request to get this json
r = requests.get('http://cdn.content.easports.com/fifa/fltOnlineAssets/2013/fut/items/web/199074.json')
print r.json

Solution
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import json
import requests

headers = {'Content-Type': 'application/json'}

r = requests.get('http://cdn.content.easports.com/fifa/fltOnlineAssets/2013/fut/items/web/199074.json', headers=headers)

print r.content

#prints
{"Item":{"FirstName":"Lacina","LastName":"Traoré","CommonName":null,"Height":"203","DateOfBirth":{"Year":"1990","Month":"8","Day":"20"},"PreferredFoot":"Left","ClubId":"100766","LeagueId":"67","NationId":"108","Rating":"78","Attribute1":"79","Attribute2":"71","Attribute3":"45","Attribute4":"69","Attribute5":"50","Attribute6":"72","Rare":"1","ItemType":"PlayerA"}}

Basically I needed to set to send the rigth headers.
Thank you all

A: You need tell requests what encoding to expect:
>>> import requests
>>> r = requests.get(url)
>>> r.encoding = 'UTF-8'
>>> r.json[u'Item'][u'LastName']
u'Traor\xe9'

Otherwise, you'll get this:
>>> r = requests.get(url)
>>> r.json['Item']['LastName']
u'Traor\u0102\u0160'

A: You have run into a bug in requests; when the server does not set an explicit encoding, requests uses chardet to make an educated guess about the encoding.
In this particular case, it gets that wrong; chardet thinks it's ISO-8859-2 instead of UTF-8. The issue has been reported to the maintainers of requests as issue 765.
The maintainers closed that issue, blaming the problem on the server not setting a character encoding for the response. The work-around is to set r.encoding = 'utf-8' before accessing r.json so that the contents are correctly decoded without guessing.
However, as J.F. Sebastian correctly points out, if the response really is JSON, then the encoding has to be one of the UTF family of encodings. The JSON RFC even includes a section on how to detect what encoding was used.
I've submitted a pull request to the requests project that does just that; if you ask for the JSON decoded response, and no encoding has been set, it'll detect the correct UTF encoding used instead of guessing.
With this patch in place, the URL loads without setting the encoding explicitly:
>>> import requests
>>> r = requests.get('http://cdn.content.easports.com/fifa/fltOnlineAssets/2013/fut/items/web/199074.json')
>>> r.json[u'Item'][u'LastName']
u'Traor\xe9'
>>> print r.json[u'Item'][u'LastName']
Traoré

A: For me your site returns "Traor\u00e9" (the last character is é):
r = requests.get(url)
print(json.dumps(json.loads(r.content)['Item']['LastName']))
# -> "Traor\u00e9" -> Traoré

r.json (r.text) produces incorrect content here. Either server or requests or both use incorrect encoding that results in "Traor\u0102\u0160". The encoding of JSON text is completely defined by its content therefore it is always possible to decode it whatever headers server sends, from json rfc:

JSON text SHALL be encoded in Unicode.  The default encoding is
UTF-8.
Since the first two characters of a JSON text will always be ASCII
characters [RFC0020], it is possible to determine whether an octet
stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
at the pattern of nulls in the first four octets.

       00 00 00 xx  UTF-32BE
       00 xx 00 xx  UTF-16BE
       xx 00 00 00  UTF-32LE
       xx 00 xx 00  UTF-16LE
       xx xx xx xx  UTF-8

In this case there are no zero bytes at the start of r.content so json.loads works otherwise you need manually to convert it to a Unicode string if the server sends incorrect character encoding in Content-Type header or to workaround requests bug


text:
Q: Does every $3$-regular bipartite graph have a $4$-cycle? Is it the case that every Hamiltonian bipartite $3$-regular graph has a $4$-cycle?
My intuition says 'yes', because one can form such a graph by taking a $n$-cycle and adding a matching to it. When adding the matching, I think it should be inevitable to form a $4$-cycle eventually, either with edges from the $n$-cycle or with other edges of the matching added previously.
Any ideas on how to show this or how to provide a counterexample?

A: A counterexample is for example Tutte $12$-cage. The Tutte $12$-cage is a bipartite cubic Hamiltonian graph. The length of its smallest cycle is $12$ (as a $12$-cage).
Another example is the Tutte–Coxeter graph.
Finally, the smallest graph with the above properties is the Heawood graph.


text:
Q: Soundcloud soundwave I am trying to generate soundwave which would look like the one that soundcloud have.
But i can't figure out how do they make their soundwaves so clear, for example this is an example of soundcloud and my generated soundwave:

I am using to php to read wav file and generate the image, but if there is some better library in any language which would do this better i would definitely like to to hear about it.
I have pasted the class that I'm usin in Pastebin.
I got this code from andrewfreiday.com and modified to fit my website.
I'm really lost at this and any kind of suggestion would help a lot.

A: The waveforms on soundcloud.com are drawn with canvas -- whereas in your sample image, it appears as though it's a larger image which is scaled down to the desired size. When you do this scaling in the browser, it will anti-alias the 'half' pixels. When drawing to the canvas, we draw exactly the pixels needed at the exact resolution needed. This means there's no image scaling and no blurriness.

A: the tool you are looking for is located at https://www.un4seen.com/
soundcloud uses some simple tactics.
say soundwave will be 595 pixels wide.. each bar will be 5 pixels + 2 pixels blank.
595 / ( 5 + 2 ) = 85
length / (bar + space ) = 85 total (bars with space)
device song into 85 parts
lets say song is 3:00 long..
3*60 = 180/85 = 2 seconds
minute * seconds = total seconds / parts = 2 seconds / bar
so, now we get the peak of a song every 2 seconds.
save max peak.
save low peak.
now you have a list of 85 bars with exact highest peak and lowest peak to display them accordingly with song relative to time.
use positive numbers to display upper portion.
divide by 2 OR 3 OR 4 and use negative numbers to display lower portion.
combine the two and use it as a filter to draw the colors of the graph.
kaboom!


text:
Q: Query result in JSON format (key value pair) on using @Query annotation in Spring Boot, Hibernate My Controller
@GetMapping(value="/getAllDetails")
public List<PriceListEntity> getAllDetails() {
    return MyRepository.getAllDetails();
}

My Repository
@Repository
public interface MyRepository extends CrudRepository<TestNativeQ, String> {
    @Query( value="SELECT qplt.name price_list_name,  qplab.status_code, qplab.start_date, (SELECT charge_definition_code FROM oalfsaas_repl.QP_CHARGE_DEFINITIONS_B WHERE charge_definition_id=qplab.charge_definition_id  ) chargedefinitioncode "
            + "FROM  PriceListEntity qplab, PriceListLineEntity qplt "
            + " WHERE qplab.price_list_id  =qplt.price_list_id ", nativeQuery = false)
    public List<PriceListEntity> getAllDetails();
}

Actual Result:
[{"ABC", "DEF", "15/05/2018", "XXZ"}]

Expected Result
[{name: "ABC", statuscode: "DEF", startDate: "15/05/2018", chargedefintioncode: "XXZ"}]

The Query has join with more than one table and also subquery at column level.

A: Your are actually doing a projection with your select which does not return any specific object but a tuple which is an array of objects you select in your query. Whatever way the JSON is made there are no names just values.
You need to create a DTO to hold the values you want to pass by names in your JSON.
A minimal example, having a simple entity like:
@Entity
@Getter
@RequiredArgsConstructor
public class TestClass {
    @Id
    @GeneratedValue
    private Long id;

    @NonNull
    private String a,b,c;
}

and willing to pass -for example - only a & b there might be DTO like:
@RequiredArgsConstructor
public class TupleDto {
    @NonNull
    private String a,b;
}

and in your case some sort of PriceListDetailsDto
the repository might be declared like:
public interface TestClassRepository extends CrudRepository<TestClass, Long> {

    @Query(value="SELECT new org.example.TupleDto(tc.a, tc.b) FROM TestClass tc")
    List<TupleDto> fetchAB();

}

NOTE: in above that there is used operator new and a full path to the entity constructor.
This way Spring repository knows how to assign selected fields and when making a JSON from this DTO will result having fields with names (names in DTO).
The new operator in JPQL is just calling new in java- So any row data a,b,c can be used to construct Java object with that object's class constructor accepting same parameter amount and types (and in the same order) so liie new MyEntityObject(a,b,c).
NOTE ALSO: in this simple case the original entity could have been used as DTO if it was modified to allow null value in c and adding corresponding constructor. In your case where your tuple is constructed from many tables you  need to create a DTO to hold those values.


text:
Q: Stuck comparing two values I am building a javascript remote for Kodi, where i only send data if it is changed. I am stuck with this peace of code. It will check every x seconds for a value but i only want to do something if the value has changed. Can someone shed some light on this?
every((0.35).second(), function() {
  var kodi_api_request = {"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1};
  var kodi = encodeURIComponent(JSON.stringify(kodi_api_request));
  var previous = {};
  var stuff = request
  .get('http://localhost:8080/jsonrpc?request=' + kodi, function (error, response, data) {
    var newdata = data
    if (previous !== newdata) {
      console.log('changed');
      previous = newdata;
      console.log(newdata);
    } else {
      console.log('Error!');
    }
  });
});


text:
Q: I need an unordered list without any bullets I have created an unordered list. I feel the bullets in the unordered list are bothersome, so I want to remove them.
Is it possible to have a list without bullets?

A: If you wanted to accomplish this with pure HTML alone, this solution will work across all major browsers:
Description Lists
Simply using the following HTML:

List Item 1

Sub-Item 1.1

List Item 2

Sub-Item 2.1

Sub-Item 2.2

Sub-Item 2.3

List Item 3

Sub-Item 3.1

Example here: https://jsfiddle.net/zumcmvma/2/
Reference here: https://www.w3schools.com/tags/tag_dl.asp

A: If you're using Bootstrap, it has an "unstyled" class:

Remove the default list-style and left padding on list items (immediate children only).

Bootstrap 2:

...

http://twitter.github.io/bootstrap/base-css.html#typography
Bootstrap 3 and 4:

...

Bootstrap 3: http://getbootstrap.com/css/#type-lists
Bootstrap 4: https://getbootstrap.com/docs/4.3/content/typography/#unstyled
Bootstrap 5: https://getbootstrap.com/docs/5.0/content/typography/#unstyled

A: This orders a list vertically without bullet points. In just one line!
li {
    display: block;
}

A: Small refinement to the previous answers: To make longer lines more readable if they spill over to additional screen lines:
ul, li {list-style-type: none;}

li {padding-left: 2em; text-indent: -2em;}

A: You can remove bullets by setting the list-style-type to none on the CSS for the parent element (typically a
), for example:
ul {
  list-style-type: none;
}

You might also want to add padding: 0 and margin: 0 to that if you want to remove indentation as well.
See Listutorial for a great walkthrough of list formatting techniques.

A: To completely remove the ul default style:
    list-style-type: none;

    margin: 0;
    margin-block-start: 0;
    margin-block-end: 0;
    margin-inline-start: 0;
    margin-inline-end: 0;
    padding-inline-start: 0;

A: You need to use list-style: none;

...

A: If you're unable to make it work at the
 level, you might need to place the list-style-type: none; at the
 level:

Item 1

Item 2

You can create a CSS class to avoid this repetition:

Item 1

Item 2

When necessary, use !important:

A: I used list-style on both the ul and the li to remove the bullets. I wanted to replace the bullets with a custom character, in this case a 'dash'. That gives a nicely indented effect that works fine when the text wraps.

ul.dashed-list {
    list-style: none outside none;
}

ul.dashed-list li:before {
    content: "\2014";
    float: left;
    margin: 0 0 0 -27px;
    padding: 0;
}

ul.dashed-list li {
    list-style-type: none;
}

text

text

A: If you are developing an existing theme, it's possible that the theme has a custom list style.
So if you cant't change the list style using list-style: none; in ul or li tags, first check with !important, because maybe some other line of style is overwriting your style. If !important fixed it, you should find a more specific selector and clear out the !important.
li {
    list-style: none !important;
}

If it's not the case, then check the li:before. If it contains the content, then do:
li:before {
    display: none;
}

A: You can hide them using ::marker pseudo-element.

*

*Transparent ::marker

ul li::marker {
  color: transparent;
}

ul li::marker {
  color: transparent;
}

ul {
  padding-inline-start: 10px; /* Just to reset the browser initial padding */
}

 Bullets are bothersome

 I want to remove them.

 Hey! ::marker to the rescue

*::marker empty content

ul li::marker {
  content: "";
}

ul li::marker {
   content: "";
}

 Bullets are bothersome

 I want to remove them

 Hey! ::marker to the rescue

It is better when you need to remove bullets from a specific list item.
ul li:nth-child(n)::marker { /* Replace n with the list item's position*/
   content: "";
}

ul li:not(:nth-child(2))::marker {
   content: "";
}

 Bullets are bothersome

 But I can live with it using ::marker

 Not again though

A: In BOOTSTRAP You can remove bullets by setting the list-unstyled class on the parent class of the li tag.

One

Two

Three

A: ul{list-style-type:none;}

Just set the style of unordered list is none.

A: In case you want to keep things simple without resorting to CSS, I just put a   in my code lines. I.e.,

.
Yeah, it leaves a few spaces, but that's not a bad thing.

A:

           <input type="checkbox" style="zoom:1.7;vertical-align:bottom;" asp-for="@Model[i].IsChecked" class="custom-control-input" /> @Model[i].Title

A: I tried and observed:
header ul {
   margin: 0;
   padding: 0;
}


text:
Q: Apache restart needed after php code change When I change php code of an application I need to restart apache to make the new code effective.
$ sudo apachectl -l
Compiled in modules:
  core.c
  mod_log_config.c
  mod_logio.c
  itk.c
  http_core.c
  mod_so.c

It is a pretty stock Ubuntu configuration of Apache. I only installed mod_itk and created some vritualhosts.
Any ideas?
APC Support enabled
Version 3.1.7
APC Debugging   Disabled
MMAP Support    Enabled
MMAP File Mask  no value
Locking type    pthread mutex Locks
Serialization Support   php
Revision    $Revision: 307215 $
Build Date  May 2 2011 19:00:42

Directive   Local Value Master Value
apc.cache_by_default    On  On
apc.canonicalize    On  On
apc.coredump_unmap  Off Off
apc.enable_cli  Off Off
apc.enabled On  On
apc.file_md5    Off Off
apc.file_update_protection  2   2
apc.filters no value    no value
apc.gc_ttl  3600    3600
apc.include_once_override   Off Off
apc.lazy_classes    Off Off
apc.lazy_functions  Off Off
apc.max_file_size   1M  1M
apc.mmap_file_mask  no value    no value
apc.num_files_hint  1000    1000
apc.preload_path    no value    no value
apc.report_autofilter   Off Off
apc.rfc1867 Off Off
apc.rfc1867_freq    0   0
apc.rfc1867_name    APC_UPLOAD_PROGRESS APC_UPLOAD_PROGRESS
apc.rfc1867_prefix  upload_ upload_
apc.rfc1867_ttl 3600    3600
apc.serializer  default default
apc.shm_segments    1   1
apc.shm_size    32M 32M
apc.slam_defense    On  On
apc.stat    Off Off
apc.stat_ctime  Off Off
apc.ttl 0   0
apc.use_request_time    On  On
apc.user_entries_hint   4096    4096
apc.user_ttl    0   0
apc.write_lock  On  On

A: You don't list us the PHP modules. You most likely have something like PHP Accelerator, XCache or similar in place, a front-end cache such as Varnish caching stuff or some other black magic you won't reveal us.
For the caches such as XCache, see their manual how to operate from this.
For the front-end caches such as Varnish, see their manual.
Other than that, it's hard to imagine what is actually caching your stuff.

A: The apc.stat option is turned off.
apc.stat    Off Off

In this case APC won't re-read cached files, ever.
The documentation states:

If this setting is off, APC will not check, which usually means that to force APC to recheck files, the web server will have to be restarted or the cache will have to be manually cleared.

To avoid restarting the web server, manually clear the cache by having the web server serve a PHP script containing only:
apc_clear_cache();


text:
Q: HTML - simple input to .txt I am trying to figure out how to make a simple html code so that whenever anyone on the page types anything into the provided text box and hits submit, it adds that written text to an already existing .txt file on my server.
UPDATE 2/20/14 9:29AM: Well that's unfortunate. I kind of figured I required a .php but sadly my wepbage is hosted through homestead and they do not have .php functionality. Was just hoping there was a workaround. Thanks for the responses.

A: If your server can run php then the following page can be requested when the user clicks submit. (using post method)
<?php

    $in = $_POST['name'];
    $file = 'names.txt';
    // Open the file to get existing content
    $current = file_get_contents($file);
    // Append a new person to the file
    $current .= $in;
    // Write the contents back to the file
    file_put_contents($file, $current);
?>

A: You would have to use PHP to do this. Make the form action on your form link to a PHP script and inside have something like this.
<?php
    $file = 'test.txt';
    $currentText = file_get_contents($file);
    $currentText .= $_POST['text'];
    file_put_contents($file, $currentText);
?>


text:
Q: Error when trying to use p-Dropdown from PrimeNG in application I want to use this PrimeNG-Dropdown in my application. So what I did:
npm i primeng --save

Then I added the DropdownModule in my imports from app.module.ts. Afterwards, I included the following code in my html:
<p-dropdown [options]="optionList" [(ngModel)]="selectionString" placeholder="Choose one"></p-dropdown>

On running ng serve and starting localhost:4200 I get the following error:

./node_modules/primeng/components/multiselect/multiselect.js Module
  not found: Error: Can't resolve '@angular/cdk/scrolling' in
  '%projectroot%\node_modules\primeng\components\multiselect'

I also tried removing the import from the imports-Array, which resulted in a different error. What am I doing wrong? I am using Angular 7 btw.
When removing the import I get the following error:
Can't bind to 'options' since it isn't a known property of 'p-dropdown'.
1. If 'p-dropdown' is an Angular component and it has 'options' input, then verify that it is part of this module.
2. If 'p-dropdown' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
      <p-dropdown [ERROR ->][options]="optionList" [(ngModel)]="selectionString" placeholder="Choose one"></p-dropdown"): ng:///AppModule/ProjectGeneratorComponent.html@13:18
'p-dropdown' is not a known element:
1. If 'p-dropdown' is an Angular component, then verify that it is part of this module.
2. If 'p-dropdown' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
      [ERROR ->]<p-dropdown [options]="optionList" [(ngModel)]="selectionString" placeholder="Choose one">"):

A: if you want to use prime NG component, first you should do some steps and be careful about them that it has been done well. first you should install the packages through terminal in your code editor. you should install these:
    npm install primeng --save   //install prime in your machine

    npm install primeicons --save    //install prime icon in your machine

next : you should go to angular.json file in your project and in the style section you should copy these lines. these lines actually are the path of the libraries in your node_module folder. but something that is really important in this chapter is, which version of angular you are using. if you are using angular version 4 and less than that you should copy these path to the style chapter:
"../node_modules/primeicons/primeicons.css",
"../node_modules/primeng/resources/themes/nova-light/theme.css",
"../node_modules/primeng/resources/primeng.min.css",

but if you are using version more than 4 it means 5 or 6 or 7 you should copy these path:
  "./node_modules/primeicons/primeicons.css",
  "./node_modules/primeng/resources/themes/nova-light/theme.css",
  "./node_modules/primeng/resources/primeng.min.css",

then you can go and simply import the primes module in your app.module and use the html markup to render the components. but be aware that some components need animations that you should install that on you machine through npm.
     npm install @angular/animations --save

and import modules in the app module:
 import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

i hope it helps you .

A: You need to install Angular CDK.
use npm install @angular/cdk --save command.
and then import multi selecte module in appModule using
import {MultiSelectModule} from 'primeng/multiselect';

A: Try in appmodule.ts:
import {CUSTOM_ELEMENTS_SCHEMA} from "@angular/core";
@NgModule({
  ...
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

A: Import FormsModule to the module where you imported the DropdownModule. I got the same issue, and that is how I resolved it.


text:
Q: Check if the given time is between two times (Hour,Minute) format I have next 6 fields in MySQL.
TIME_RIGHT_NOW_HOUR (INT)
TIME_RIGHT_NOW_MINUTE (INT)
TIME_WORKING_FROM_HOUR (INT)
TIME_WORKING_FROM_MINUTE (INT)
TIME_WORKING_TO_HOUR (INT)
TIME_WORKING_TO_MINUTE (INT)

Hour and minutes are in 24 time format.
I need to check is the right now time between two working times.
for example if TIME_RIGHT_NOW_HOUR is 15 and TIME_RIGHT_NOW_MINUTE  is 30 -> 15:30
is it between TIME_WORKING_FROM_HOUR 10, TIME_WORKING_FROM_MINUTE 15
10:15 and TIME_WORKING_TO_HOUR 18, TIME_WORKING_TO_MINUTE 20 -> 18:20

A: Very easy solution: Convert hour&time to float then compare:
    TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100 -----> 10.15
    TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100; ------> 18.20
    TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100; ------> 15.30

SQL WHERE:
    WHERE ( (TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100) <= (TIME_RIGHT_NOW_HOUR +   TIME_RIGHT_NOW_MINUTE / 100) )
    AND ( (TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100) >= (TIME_RIGHT_NOW_HOUR +     TIME_RIGHT_NOW_MINUTE / 100) )

A: Perhaps maketime() is what you are seeking.
SELECT 1
FROM table
WHERE
  MAKETIME(TIME_RIGHT_NOW_HOUR,TIME_RIGHT_NOW_MINUTE,0)
    BETWEEN MAKETIME(TIME_WORKING_FROM_HOUR,TIME_WORKING_FROM_MINUTE,0)
    AND MAKETIME(TIME_WORKING_TO_HOUR,TIME_WORKING_TO_MINUTE,0);

A: This will work for both 5:00 -> 23:00 and 23:00 -> 5:00 ( NEXT day)
    WHERE
    (
            -- CASE: 5:00 -> 23:00
            (
                    TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100.00 < TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100.00
            )
            AND
            (
                    (
                            TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100.00 <= TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100.00
                    )
                    AND
                    (
                            TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100.00 >= TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100.00
                    )
            )
    )
    OR
    (
            -- CASE: 23:00 -> 5:00 of Next day
            (
                    TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100.00 >= TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100.00
            )
            AND
            (
                (
                    TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100.00 >= TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100.00
                )
                OR
                (
                    TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100.00 <= TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100.00
                )
            )
    )

A: You can use XOR (or the IF function), in order to cope with midnight rolling (i.e., FROM is 22:00, TO is 06:00, and the question is "is 23:30 inside or outside this period?", which mathematically is outside, but clock-wise is inside).
SELECT
    ( TIME_WORKING_FROM_HOUR*60+TIME_WORKING_FROM_MINUTE <
    TIME_WORKING_TO_HOUR*60+TIME_WORKING_TO_MINUTE )
    XOR NOT
    (
    TIME_RIGHT_NOW_HOUR*60+TIME_RIGHT_NOW_MINUTE BETWEEN
        TIME_WORKING_FROM_HOUR*60+TIME_WORKING_FROM_MINUTE
        AND
        TIME_WORKING_TO_HOUR*60+TIME_WORKING_TO_MINUTE
    )

Test
CREATE TABLE test ( TIME_RIGHT_NOW_HOUR integer, TIME_RIGHT_NOW_MINUTE integer,
TIME_WORKING_FROM_HOUR integer, TIME_WORKING_FROM_MINUTE integer,
TIME_WORKING_TO_HOUR integer, TIME_WORKING_TO_MINUTE integer );

INSERT INTO test VALUES
    ( 7, 30, 8, 00, 17, 00 ),
    ( 12, 30, 8, 00, 17, 00 ),
    ( 4, 30, 22, 00, 06, 00 ),
    ( 0, 0, 22, 00, 06, 00 ),
    ( 22, 0, 6, 0, 6, 5 );

SELECT  TIME_WORKING_FROM_HOUR AS FROM_H,
    TIME_WORKING_FROM_MINUTE AS FROM_M,
    TIME_WORKING_TO_HOUR AS TO_H,
    TIME_WORKING_TO_MINUTE AS TO_M,
    TIME_RIGHT_NOW_HOUR AS NOW_H,
    TIME_RIGHT_NOW_MINUTE AS NOW_M,
    ( TIME_WORKING_FROM_HOUR*60+TIME_WORKING_FROM_MINUTE <
    TIME_WORKING_TO_HOUR*60+TIME_WORKING_TO_MINUTE )
    XOR NOT
    (
    TIME_RIGHT_NOW_HOUR*60+TIME_RIGHT_NOW_MINUTE BETWEEN
        TIME_WORKING_FROM_HOUR*60+TIME_WORKING_FROM_MINUTE
        AND
        TIME_WORKING_TO_HOUR*60+TIME_WORKING_TO_MINUTE
    ) AS in_orario FROM test;

Result:
+--------+--------+------+------+-------+-------+-----------+
| FROM_H | FROM_M | TO_H | TO_M | NOW_H | NOW_M | in_orario |
+--------+--------+------+------+-------+-------+-----------+
|      8 |      0 |   17 |    0 |     7 |    30 |         0 |
|      8 |      0 |   17 |    0 |    12 |    30 |         1 |
|     22 |      0 |    6 |    0 |     4 |    30 |         1 |
|     22 |      0 |    6 |    0 |     0 |     0 |         1 |
|      6 |      0 |    6 |    5 |    22 |     0 |         0 |
+--------+--------+------+------+-------+-------+-----------+
5 rows in set (0.00 sec)

In this SQLfiddle, the condition has been moved into the WHERE.


text:
Q: Factorial using recursion method in IntelliJ I am trying to solve a basic exercise (calculating factorial) but I am getting stuck at an error.
I am working in IntelliJ
Code:
public class calculation {

    public long factorial(long number) {
        if (number <= 0) {
            return 1;
        }
        else
            return number * factorial(number - 1);

    }
}

    public static void main(String[] args) {

        for(int counter = 0; counter <= 21; counter++)
        {
            System.out.printf("%d! = %d", counter, factorial(counter));
        }
    }
}

Error I receive:

Error:(18, 30) java: class, interface, or enum expected - 4 instances

I also tried reading a number from the keyboard using scanner and then calling the function but I got the same result.
Thanks in advance.

A: You have 1 extra closing bracket and because of that your void main() is out of the class. Fix that and try to run the code again. Below code is running fine.
`
public class calculation {
public static long factorial(long number) {
    if (number <= 0) {
        return 1;
    }
    else
        return number * factorial(number - 1);

}

public static void main(String[] args) {

    for(int counter = 0; counter <= 21; counter++)
    {
        System.out.printf("%d! = %d", counter, factorial(counter));
    }
}

}


text:
Q: trying to connect to a mysql database using php I have an HTML form, and I need to past data from it to mysql database in phpMyAdmin. I'm far from php and I don't know what to do with these errors, also I was unable to set up server and phpMyAdmin locally so I test it right away on the hosting.
index.html:

        <form class="form__wrapper" action="form.php" method="post">

Leave your contacts below

Phone

                    <input type="tel" value="+380">

Name

                    <input type="text">

Company

                   <input type="text">

Email

                    <input type="email">

Consumption

                    <input type="text" pattern="[0-9]*">

                <button type="submit" class="form__wrapper_inputs_send">Submit</button>

        </form>

form.php:
<?php
$dbhost = "***Link to phpmyadmin of my hosting***";
$dbuser = "***phpmyadmin unsername***";
$dbpass = "***phpmyadmin password";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);

if(! $conn) {
    die('Could not connect: ' . mysqli_error());
}

if(isset($_POST['submit']))
{
    $number = $_POST['number'];
    $name = $_POST['name'];
    $company = $_POST['company'];
    $email = $_POST['email'];
    $consumption = $_POST['consumption'];

    $insert = mysqli_query($db,"INSERT INTO `form`(`number`, `name`, `company`, `email`, `consumption`) VALUES ('$number',
    '$name', '$company', '$email', '$consumption')");

    if(!$insert)
    {
        echo mysqli_error();
    }
    else
    {
        echo "Records added successfully.";
    }
}

mysqli_close($conn);
?>

When I press submit button, I get following errors:
Warning: mysqli_connect(): php_network_getaddresses: getaddrinfo failed: Name does not resolve in /sata2/home/users/***user***/www/***site***/form.php on line 5

Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: Name does not resolve in /sata2/home/users/***user***/www/***site***/form.php on line 5

Warning: mysqli_error() expects exactly 1 parameter, 0 given in /sata2/home/users/***user***/www/***site***/form.php on line 8
Could not connect:

In comments I've been told that $dbhost variable is wrong, but I'm not sure what to use there. If I assign it IP of my hosting, I get timed out error.

A: index.html (note: you are missing the HTML input element name attributes, so nothing is being sent)

        <form class="form__wrapper" action="form.php" method="post">

Leave your contacts below

Phone

                    <input name="number" type="tel" value="+380">

Name

                    <input name="name" type="text">

Company

                   <input name="company type="text">

Email

                    <input name="email" type="email">

Consumption

                    <input name="consumption" type="text" pattern="[0-9]*">

                <button type="submit" class="form__wrapper_inputs_send">Submit</button>

        </form>

form.php
<?php

// check if form is empty out here before wasting a database connection
if (!empty($_POST['submit'])) {

    $dbname = "database_name"; // you must specify the database name
    $dbhost = "127.0.0.1";
    $dbuser = "database_username"; // add your username here
    $dbpass = "database_password"; // add your password here

    // use PDO instead, it is safer than mysqli functions
    // see: https://www.php.net/manual/en/book.pdo.php

    // pdo options
    $pdo_options = [
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ];

    try {

        // connect to database
        $db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8mb4", $dbuser, $dbpass, $pdo_options);

        // use prepared statements to help prevent sql injection

        // insert query
        $query = "INSERT INTO `form` (`number`, `name`, `company`, `email`, `consumption`) VALUES (?, ?, ?, ?, ?)";

        // prepare statement
        $stmt = $db->prepare($query);

        // execute with bound parameters
        $stmt->execute([
            $_POST['number'],
            $_POST['name'],
            $_POST['company'],
            $_POST['email'],
            $_POST['consumption']
        ]);

        // success
        echo "Form submitted successfully";

    } catch (Exception $e) {
        // error
        echo "Error inserting record into database, " . $e->getMessage();
    }
}

A: You are connecting to mysql not to phpmyadmin.
So you should change your credentials like this:
$dbhost = "***Link to mysql of my hosting***";
$dbuser = "***mysql username***";
$dbpass = "***mysql password";

These credentials have been provided to you by your hosting. $dbuser and $dbpass are the same that you use for phpmyadmin but the dbhost should be different

A: it would be network configuration. The database server is blocking ext-connection to port 3306.
$dbhost = "***Link to phpmyadmin of my hosting***";
$dbuser = "***phpmyadmin unsername***";
$dbpass = "***phpmyadmin password";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);

Those info should be:
$dbhost = "***Database server IP***";
$dbuser = "***phpmyadmin unsername***";
$dbpass = "***phpmyadmin password";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);

Make sure your server open port 3306 from your webserver.
Thanks.


text:
Q: Puppeteer. How click on btn after API load data in input Have SPA. Open form with cople imputs(value inside imputs generate js).
When i enter some code in one of my special field for search - after that all of my fields take some data from API.
After all the inputs accept their own data - i click the button to create the entry.
Can i push button after complited load data in inputs from API?
im try stuff like that, but its dosen't work - button dont wait and click
    await page2.focus("body > div.viewport > div.overlay.dialog-overlay > div > div.tabs-container > div.tabs-wrapper > ul > li.tab-content.active > div > div.content > div:nth-child(1) > div.content > div:nth-child(2) > div:nth-child(1) > div > div.content > input");

    await page2.keyboard.type('14129513');  //after type - make req/res for load other fields

    page2.waitForNavigation({waitUntil: 'networkidle0'})  //dont work

    const daliButton = await page2.waitForSelector('body > div.viewport > div.overlay.dialog-overlay > div > div.tabs-container > div.tabs-wrapper > ul > li.tab-content.active > div > div.buttons > div.button.waves-effect.action')
    await daliButton.evaluate(b => b.click());

my solition right now is timeout
await page2.focus("body > div.viewport > div.overlay.dialog-overlay > div > div.tabs-container > div.tabs-wrapper > ul > li.tab-content.active > div > div.content > div:nth-child(1) > div.content > div:nth-child(2) > div:nth-child(1) > div > div.content > input");
    await page2.keyboard.type('14129513');

    function delay(time) {
      return new Promise(function(resolve) {
          setTimeout(resolve, time)
      });
    }

    await delay(2000);

    const daliButton = await page2.waitForSelector('body > div.viewport > div.overlay.dialog-overlay > div > div.tabs-container > div.tabs-wrapper > ul > li.tab-content.active > div > div.buttons > div.button.waves-effect.action')
    await daliButton.evaluate(b => b.click());

I also tried to take the values of the fields whether they were empty or with data, but the values were taken too quickly - when the information via the API had not yet arrived and had not been filled in the fields
Does anyone know what the code should be so that the button is clicked only when the data in all fields is filled?
Without using timeout of course)

A: that's what working
await page2.waitForResponse(response => response.status() === 200)

EDIT: oh...that's working just for 6/10 cases lol.
I think function waitForResponse working kind of delay and on this time all scripts and fields load and mostly ready for next step - to click button and create record
EDIT prt2: after API load data in inputs - i see what that inputs take a new class, so if u have simular case u can use next code:
 await page.waitForFunction('document.querySelector("ur selector").classList.contains("active")')//waits until a new class "active" is added to the selector