text:
Q: Rails Sitemap Generator Uploading to S3 Trying to generate a sitemap and uploading it to my current existing bucket in Amazon's S3, however, I'm getting
Excon::Errors::Forbidden: Expected(200) <=> Actual(403 Forbidden)

This is my sitemap.rb file
SitemapGenerator::Sitemap.default_host = "http://www.example.com"
SitemapGenerator::Sitemap.public_path = 'tmp/sitemaps/'
SitemapGenerator::Sitemap.sitemaps_host = "http://s3.amazonaws.com/#{ENV['S3_BUCKET_NAME']}/"
SitemapGenerator::Sitemap.create do
  add about_path
  add landing_index_path
  add new_user_session_path, priority: 0.0

  Trip.find_each do |trip|
    add trip_path(trip.slug), lastmod: trip.updated_at
  end
end

I have this in my s3.rb file
CarrierWave.configure do |config|
  config.storage = :fog
  config.fog_credentials = {
      :provider               => 'AWS',
      :aws_access_key_id      => Rails::AWS.config['access_key_id'],
      :aws_secret_access_key  => Rails::AWS.config['secret_access_key'],
      :region                 => 'us-east-1'
  }
  config.fog_directory  = Rails::AWS.config['bucket_name']
end

Would someone be able to know what the issue is with this?

A: My working config (which I use in heroku) is a little different than yours, here is what I have:
SitemapGenerator::Sitemap.default_host = 'http://example.com'
SitemapGenerator::Sitemap.public_path = 'tmp/'
SitemapGenerator::Sitemap.adapter = SitemapGenerator::S3Adapter.new(fog_provider: 'AWS', fog_directory: 'sitemap-bucket')
SitemapGenerator::Sitemap.sitemaps_host = "http://#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com/"
SitemapGenerator::Sitemap.sitemaps_path = 'sitemaps/'

I don't use a S3.rb, instead, I set the following environment variables:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
FOG_DIRECTORY
FOG_REGION

I used the tutorial in here: https://github.com/kjvarga/sitemap_generator/wiki/Generate-Sitemaps-on-read-only-filesystems-like-Heroku
I hope it helps!

A: I was experiencing a similar error:
In '/app/tmp/':
rake aborted!
ArgumentError:  is not a recognized provider

Going off the help of renatolond's answer above, this is the configuration that worked for me. The key is to make sure that all of your variables, such as "fog_region:" actually match up to valid values. Do not blindly copy + paste configuration credentials.
SitemapGenerator::Sitemap.default_host = "https://yourwebsitename.com"

SitemapGenerator::Sitemap.public_path = 'tmp/'
SitemapGenerator::Sitemap.adapter = SitemapGenerator::S3Adapter.new(
  fog_provider: 'AWS',
  aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
  aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
  fog_directory: ENV['S3_BUCKET'],
  fog_region: ENV['AWS_REGION'])

SitemapGenerator::Sitemap.sitemaps_host = "http://{ENV['S3_BUCKET']}.s3.amazonaws.com/"
SitemapGenerator::Sitemap.sitemaps_path = 'sitemaps/'


text:
Q: Bandwidth Consumption I am currently getting bandwidth usage per session for RTMP, HTTP and RTP like this:
//RTMP
public void onStreamDestroy(IMediaStream stream) {
        if ( stream.getClient() != null){

            IOPerformanceCounter perf = stream.getMediaIOPerformance();

            Long outbytes = perf.getMessagesOutBytes();
        }
    }

//HTTP
public void onHTTPSessionDestroy(IHTTPStreamerSession httpSession) {
        if ( httpSession != null){

                    IOPerformanceCounter perf = httpSession.getIOPerformanceCounter();
                    Long outbytes = perf.getMessagesOutBytes();
                }
    }

    //RTP
    public void onRTPSessionDestroy(RTPSession rtpSession) {

        if ( rtpSession != null){

            IOPerformanceCounter perf = rtpSession.getIOPerformanceCounter();

            Long outbytes = perf.getMessagesOutBytes();

        }
    }

When I compare my usage with the hosting provider, it is very different.  My usage is lower than my provider.
Is this correct way to get bandwidth usage?

redpajama_set_name: RedPajamaStackExchange


text:
Q: codeigniter path error i have turned off index.php in my codeigniter by .htaccess and also i left blank the index file in config.php
this is .htaccess code
RewriteEngine on
RewriteCond $1 !^(index\.php|images|captcha|css|js|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

i have a link to my controller function as 'cuser/authenticate' so the url looks like
mydoamin.com/cuser/authenticate

but it shows an error telling path not found
when i edit the above url to
mydomain.com/index.php/cuser/authenticate

it displays output
how can i tackle this problem?

A: You may change $uri_protocol in the application/config/config.php from "AUTO" to "REQUEST_URI".

A: have you tried this ?
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

A: RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]

$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';

These settings worked for me

A: Heres straight copy/paste from my codeigniter installs, latest version..
set the following in your config.php
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';

create a .htaccess and fill it with this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin

ErrorDocument 404 /index.php
</IfModule>


text:
Q: Gradle project refresh failed (Android), Not After message i faced with this message when sync gradle :

A: In my case there was problem of JDK path.
I just set  path of JDK for Android Studio.
File -> Project Structure -> From Left Side Panel "SDK Location" -> JDK Location -> Click to select JDK Path.


text:
Q: dividing integrals to derive the equations I'm trying to derive an equation for which I have a relationship between a constant and its integral -- namely, $$W = 2 \int_0^\infty f(L)\,dL$$ -- but also have another definition for $W$ -- $$W = -L\ln(1-P)$$ $f(L)$ itself is $f(L) = P_d$, a value related to $P$ but not the same ($P$ is the value of $P_d$ integrated from $0$ to $L$ somehow, though my sources don't actually give the $P_d$ equation).  So what I need to do is solve $$2\int_0^\infty f(L)\,dL = -L\ln(1-P)$$ so that $P_d$ is the $y$ value and $L$ is the $x$ value, but I'm flubbing this one as I keep coming up with $P_d = \frac{W}{2L}$, which is clearly wrong (partly because it should go to $P_d = 1$ at $L = 0$ rather than infinity).  I'm an experimentalist and out of my depth so long after taking calculus!

A: The first thing you should note is that $\int_0^\infty f(L)\,dL$ is a constant. It is just a number. The only thing that it depends upon is the function $f$. If you change what function you are integrating, you will get a different value. But it does not depend on a value of the variable $L$. The $L$ in $\int_0^\infty f(L)\,dL$ is a dummy variable - it only exists to support the integral notation, and it does not exist outside that integration. You could equally well use any other variable:
$$\int_0^\infty f(L)\,dL = \int_0^\infty f(q)\,dq = \int_0^\infty f({\frak L})\,d{\frak L}$$
And since $L$ is also a variable in use outside this expression, you definitely should use a different dummy variable. Then you don't get confused thinking that the variable $L$ inside the notation means the same thing as the variable $L$ outside the notation.
But since $\int_0^\infty f(q)\,dq$ is just a constant, that means $W$ is a constant. It doesn't change with $L$. So the equation you need to solve is
$$W = -L\ln(1 - P)\\-\dfrac WL = \ln(1 - P)\\e^{-W/L} = e^{\ln(1-P)}\\e^{-W/L} = 1 - P\\P = 1 - e^{-W/L}$$
Now you say that $P = \int_0^L P_d(q)\,dq$. By the fundamental theorem of calculus, that would mean $P_d$ is the derivative of $P$:
$$P_d = \frac{dP}{dL} = -\frac{W}{L^2}e^{-W/L}$$
But alas, this cannot be true. If $P = \int_0^L P_d(q)\,dq$, then $P = 0$ when $L = 0$, but instead $P=1 - e^{-W/L}$ approaches $1$ as $L$ approaches $0$ from above.
So unfortunately something you've said here has been garbled too much to be able to figure out the answer.


text:
Q: Dumping information from Nested Structures defined in C++ header files into XML I'm writing a C/C++ Header file parser that converts .h files into a specific XML format.
I have a structure defined as follows:
struct struct1
{
   struct structchild1
   {
      float child2;
   } child3;
   unsigned int child3;
};

I want the above structure to be represented as:
<tag1= "struct1">
        <name>struct1</name>
        <input_type>byte</input_type>
        <method></method>
        <tag_ref = "structchild1">
            <name>child3</name>
            <tag2 = "child2">
            <name>child2<name>
            <size>4<size>
            </tag2>
        </tag_ref>
     <tag2= "child3">
          <name>child3</name>
          <len>4</len>
          <value> </value>
     </tag2>
</tag1>

My approach: I'm using a 2 stage process, I first convert the header file into a gccXML format and then use xerces-C++ for visual studio to print the results out into the XML file. I'm successfully able to parse everything (enums, typedefs etc) except nested structures or unions. Can somebpdy please help me out as to how to go about doing this? Thanks!

A: I dont know if this would help since you are using C++.But if you want to get this done easily you could go for JDOM or JAXB Parser in Java.The JAXB marshaller creates XML while the JAXB unmarshaller parses the XML.I have used JDOMparser to parse an XML including the CDATA section and it works brilliantly.Hope this helps.
May be you might want to have a look at this example.
http://www.mkyong.com/java/jaxb-hello-world-example/


text:
Q: EC2Config Cloudwatch logs streaming not working I was hoping someone could help with this, I'm trying to stream logs from a Windows Server 2012 with EC2config service installed.
I have followed the following documentation:
https://aws.amazon.com/blogs/devops/using-cloudwatch-logs-with-amazon-ec2-running-microsoft-windows-server/
Unfortunately nothing is streaming to cloudwatch logs.
Here is the Json I'm using:
{
"EngineConfiguration": {
    "PollInterval": "00:00:15",
    "Components": [
        {
            "Id": "ApplicationEventLog",
            "FullName": "AWS.EC2.Windows.CloudWatch.EventLog.EventLogInputComponent,AWS.EC2.Windows.CloudWatch",
            "Parameters": {
                "LogName": "Application",
                "Levels": "1"
            }
        },
        {
            "Id": "SystemEventLog",
            "FullName": "AWS.EC2.Windows.CloudWatch.EventLog.EventLogInputComponent,AWS.EC2.Windows.CloudWatch",
            "Parameters": {
                "LogName": "System",
                "Levels": "7"
            }
        },
        {
            "Id": "SecurityEventLog",
            "FullName": "AWS.EC2.Windows.CloudWatch.EventLog.EventLogInputComponent,AWS.EC2.Windows.CloudWatch",
            "Parameters": {
            "LogName": "Security",
            "Levels": "7"
            }
        },
        {
            "Id": "ETW",
            "FullName": "AWS.EC2.Windows.CloudWatch.EventLog.EventLogInputComponent,AWS.EC2.Windows.CloudWatch",
            "Parameters": {
                "LogName": "Microsoft-Windows-WinINet/Analytic",
                "Levels": "7"
            }
        },
        {
            "Id": "IISLog",
            "FullName": "AWS.EC2.Windows.CloudWatch.IISLogOutput,AWS.EC2.Windows.CloudWatch",
            "Parameters": {
        "LogDirectoryPath": "C:\\inetpub\\logs\\LogFiles\\W3SVC1"
        "AccessKey": "",
        "SecretKey": "",
        "Region": "eu-west-1",
        "LogGroup": "Web-Logs",
        "LogStream": "IIStest"
            }
        },
        {
            "Id": "CustomLogs",
            "FullName": "AWS.EC2.Windows.CloudWatch.CustomLog.CustomLogInputComponent,AWS.EC2.Windows.CloudWatch",
            "Parameters": {
                "LogDirectoryPath": "C:\\CustomLogs\\",
                "TimestampFormat": "MM/dd/yyyy HH:mm:ss",
                "Encoding": "UTF-8",
                "Filter": "",
                "CultureName": "en-US",
                "TimeZoneKind": "Local"
            }
        },
        {
            "Id": "PerformanceCounter",
            "FullName": "AWS.EC2.Windows.CloudWatch.PerformanceCounterComponent.PerformanceCounterInputComponent,AWS.EC2.Windows.CloudWatch",
            "Parameters": {
                "CategoryName": "Memory",
                "CounterName": "Available MBytes",
                "InstanceName": "",
                "MetricName": "Memory",
                "Unit": "Megabytes",
                "DimensionName": "",
                "DimensionValue": ""
            }
        },
        {
            "Id": "CloudWatchLogs",
            "FullName": "AWS.EC2.Windows.CloudWatch.CloudWatchLogsOutput,AWS.EC2.Windows.CloudWatch",
            "Parameters": {
                "AccessKey": "",
                "SecretKey": "",
                "Region": "eu-west-1",
                "LogGroup": "Win2Test",
                "LogStream": "logging-test"
            }
        },
        {
            "Id": "CloudWatch",
            "FullName": "AWS.EC2.Windows.CloudWatch.CloudWatch.CloudWatchOutputComponent,AWS.EC2.Windows.CloudWatch",
            "Parameters":
            {
                "AccessKey": "",
                "SecretKey": "",
                "Region": "eu-west-1",
                "NameSpace": "Windows/Default"
            }
        }
    ],
    "Flows": {
        "Flows":
        [
            "(ApplicationEventLog,SystemEventLog),CloudWatchLogs",
    "IISLog"
        ]
    }
}
}

At this moment in time i only want to stream the IIS logs, from my understanding the Cloudwatch Log group and stream should automatically create.

A: The issue with Flows section is the second component of Flow definition is missing :
instead of
"Flows": {
    "Flows":
    [
        "(ApplicationEventLog,SystemEventLog),CloudWatchLogs",
"IISLog"
    ]
}

It should be
    [
        "(ApplicationEventLog,SystemEventLog),CloudWatchLogs",
        "IISLog,CloudWatchLogs"
    ]

The Flows section defines the source and target of the  components from Components section first being what/how to get and second is how to send.
e.g. consider following snippet here ApplicationEventLog and SystemEventLog will be sent to CloudWatch (refers to "Id" : "CloudWatch" defined in Components instead of AWS CloudWatch).
The second line defines second flow i.e. PerformanceCounter sent to CloudWatch1
    "Flows": {
        "Flows":
        [
            "(ApplicationEventLog,SystemEventLog),CloudWatchLogs",
            "PerformanceCounter,CloudWatch1"
        ]
    }

hope this explains how it resolved the issue.

A: Looks like i made a few mistakes on the JSON file itself, specifically the FLOW area.
Got this working now :)


text:
Q: How do you access items from an SQLAlchemy many-to-many relationship using Python? My many-to-many model looks like this, with an association table:
class Puppy(Base):
    __tablename__ = "puppy"
    id = Column(Integer, primary_key=True, nullable=False)
    name = Column(String(80))

class Adopter(Base):
    __tablename__ = "adopter"
    id = Column(Integer, primary_key=True, nullable=False)
    name = Column(String)
    puppies = relationship('Puppy', secondary='puppy_adopters', backref="puppy")

puppy_adopters = Table('puppy_adopters', Base.metadata,
                       Column('puppy_id', Integer, ForeignKey('puppy.id')),
                       Column('adopter_id', Integer, ForeignKey('adopter.id')))

If I have created an Adopter named Bill, I can easily add and retrieve his puppies with Python:
bill.puppies.append(fido)
bill.puppies.append(rex)
for puppy in bill.puppies:
    print puppy.name     # Fido, Rex

The puppy_adopters association table is populated with Bill's id and Fido's id when I do this. But how do I see that Bill is related to Fido, using Python? I get a Python object for Fido using fido = session.query(Puppy).filter_by(name="Fido"), but there is no fido.adopters list that contains Bill. How can I see all the people that have adopted Fido?
I tried this line in the puppy table:
adopter_id = Column(Integer, ForeignKey('adopter.id'))

but it did not get populated when I added an adopter, and it couldn't hold multiple adopters anyway.

A: The SQLAlchemy docs provide what you need under their Many to Many section. What you are looking for is back_populates.
class Puppy(Base):
    __tablename__ = "puppy"
    id = Column(Integer, primary_key=True, nullable=False)
    name = Column(String(80))
    adopters = relationship('Adopter',
        secondary="puppy_adopters",
        back_populates="puppies")

class Adopter(Base):
    __tablename__ = "adopter"
    id = Column(Integer, primary_key=True, nullable=False)
    name = Column(String)
    puppies = relationship('Puppy',
        secondary="puppy_adopters",
        back_populates="adopters")

puppy_adopters = Table('puppy_adopters', Base.metadata,
                       Column('puppy_id', Integer, ForeignKey('puppy.id')),
                       Column('adopter_id', Integer, ForeignKey('adopter.id')))

Rex = Puppy(name='Rex')
Fido = Puppy(name='Fido')
Bob = Adopter(name='Bob')
Steve = Adopter(name='Steve')

Steve.puppies.append(Fido)
Bob.puppies.append(Fido)
Bob.puppies.append(Rex)
print [adopter.name for adopter in Fido.adopters] # ['Steve', 'Bob']
print [puppy.name for puppy in Bob.puppies] # ['Fido', 'Rex']


text:
Q: @media only screen does not work I have to optimize the website for mobile devices. Tried to do it through @media only screen, but it did not work for me. Maybe someone knows how to put it in the code properly ?

body {
  background-color: black;
  background-image: url(../images/background.jpg);
  background-size: 100vw 100vh;
}
header {
  box-sizing: border-box;
  top: 0;
  right: 0;
  left: 0;
  position: absolute;
  width: 100vw;
  height: 15vh;
  border-top: 0.5vmin ridge gray;
  border-right: 0.5vmin ridge gray;
  border-left: 0.5vmin ridge gray;
}
header img {
  max-height: 14vmin;
  display: block;
  margin-left: auto;
  margin-right: auto;
  vertical-align: center;
}
etc.
<!DOCTYPE html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link type="text/css" rel="stylesheet" href="css/homepage.css">
  <meta http-equiv="Content-type" content="text/html;charset=utf-8" />
  <title>Airinn hotel // Home</title>
</head>

<body>

  <header>
    <img src='images/logo.png' />etc.

A: Did you try having several css ?
The first one, global(homepage.css) and one for each kind of support ?
<link type="text/css" rel="stylesheet" href="css/homepage.css" />
<!-- Now for "normal" screens" -->
<link type="text/css" rel="stylesheet" href="css/screen.css" media="screen" />
<!-- And for mobiles / small screens -->
<link type="text/css" rel="stylesheet" href="css/small.css" media="handheld" />

the @media doesn't need the "only", it will be read only by the matching media

A: This is how it should be done (Mobile first):
.test {
    width: 200px;
}

@media screen and (min-width: 1024px) {
    .test {
        width: 1000px;
    }
}

Demo: http://jsfiddle.net/yzt9zjno/
Also, this tutorial should help.


text:
Q: Tag dispatching, variadic template, universal reference and the missed const specifier Please, consider the following example (tag dispatching, variadic template, perfect forwarding, and so on, all in one):
#include <iostream>
#include <utility>
#include <string>

struct A { };
struct B { };

void doIt(A&&, const std::string &) {
    std::cout << "A-spec" << std::endl;
}

template<typename T, typename... Args>
void doIt(T&&, Args&&...) {
    std::cout << "template" << std::endl;
}

template<typename T, typename... Args>
void fn(Args&&... args) {
    doIt(T{}, std::forward<Args>(args)...);
}

int main() {
    const std::string foo = "foo";
    std::string bar = "bar";
    fn<A>(foo);
    fn<A>(bar);
    fn<B>(foo);
}

In that case, the output is:
A-spec
template
template

The reason is quite obvious, it doesn't bother me.
What I'd like to achieve is to call the first instance of the doIt function in both the cases, no matter if the string has the const specifier or not.
Of course, a possible solution is to define a new doIt with the right prototype, anyway I'd like to know if there is also another solution.
So far, I've tried to get it by means of add_const, but I'm quite sure I missed something.
Is there any viable solution to add silently the const specifier and get it working?
EDIT
I've updated the example above, in order to be more coherent with the real problem.
Moreover, despite the interesting answers, I forgot to cite that this is only a reduced example, so the real problem does not involve only std::string. Instead, it could happen that (as an example) for tag A the arguments are int and const std::string &, while for tag B the arguments are float, instance of class C, and so on.
Because of that, those answers that try to solve the problem using somehow the std::string type won't solve the real problem, I'm sorry.

A: Introduce two separate functions, so that they won't collide with each other and the compiler won't raise any ambiguity error:
void doIt(A&&, const std::string &)
{
    std::cout << "A-spec" << std::endl;
}

template <typename T, typename... Args>
void doIt_template(T&&, Args&&...)
{
    std::cout << "template" << std::endl;
}

Prioritize two additional overloads; the preferred one is that which tries to call a specialized, non-templated version of a target function:
template <typename T, typename... Args>
auto fn_impl(int, Args&&... args)
    -> decltype(doIt(T{}, std::forward<Args>(args)...), void())
{
    doIt(T{}, std::forward<Args>(args)...);
}

template <typename T, typename... Args>
void fn_impl(char, Args&&... args)
{
    doIt_template(T{}, std::forward<Args>(args)...);
}

Introduce a single, general dispatcher:
template <typename T, typename... Args>
void fn(Args&&... args)
{
    fn_impl<T>(0, std::forward<Args>(args)...);
}

DEMO

A: Overloading on forwarding references is a pain, as they are very, very greedy.
One option would be to disable the template version if Args... is a single argument convertible to std::string:
template<typename... Args>
struct convertible_to_single_string {
    static std::true_type help (std::string);
    static std::false_type help (...);
    using type = decltype(help(std::declval<Args>()...));
    static constexpr auto value = type::value;
};

template<typename... Args>
std::enable_if_t<!convertible_to_single_string<Args...>::value, void>
doIt(int, Args&&...) {
    std::cout << "template" << std::endl;
}

This would also call the string version for const char* or anything with a user-defined conversion to std::string. If you don't want that, there are other possibilities, like removing all references and cv-qualifiers from the type and checking if it std::is_same<std::string, T>.
Live Demo

A: template<class String,
  std::enable_if_t<std::is_same<std::decay_t<String>,std::string>{},int> =0
>
void doIt(int, String&&) {
  std::cout << "std::string" << std::endl;
}

This uses a forwarding reference, then SFINAE to get any string types only in it.
If you are willing to bundle your args into a tuple, you can also do this usimg tag dispatching.  is_same can be replaced with is_convertible, then a helper function with a different name that actually converts to std::string can be used.
Another approach would be to reserve the first arg in the 2nd layer for tags, then manually work out what overload you want, and generate that tag type.


text:
Q: Is it possible to hide classes from ui tests I have a few helper classes like UnlockedTestCase that configure my app for special scenario tests.
Theses classes show up in the test navigator without tests.
Is there a way to mark then as "not test classes" in order for them to be ignored by the test navigator?
UPDATE: Sample code:
class UnlockedTestCase: XCTestCase {
    var app = XCUIApplication()

    override func setUp() {
        super.setUp()

        continueAfterFailure = false

        app.launchArguments = ["uiTesting", "unlock"]
        app.launch()
    }
}

A test would then be written as:
class UnlockedUITests: UnlockedTestCase {
    func testButton() {
        XCTAssers(app.buttons["SomeButtonInTheUnlockedState"].exists)
    }
}

A: No, there is not a way to exclude that kind of class from the test navigator without losing the ease of defining the setUp(), as the way that it discovers test case classes is simplistic, and from the point of view of the navigator, you could add test cases to the parent/helper class at any moment since it is an XCTestCase descendant.
There is no protocol for 'helper' or 'abstract-only' classes which support inheritance in the way that you require, since inheritance from XCTestCase is required for the automatic discovery and usage of tests and test hooks like setUp().
If you really want to get rid of your helper entities from the test navigator, you could abstract them into protocols with extensions where Self: XCTestCase (to allow you access to XCTestCase's interface in the extension), have your test class conform to them, and override setUp() in the class where your tests are.
protocol UnlockableTest {}
extension UnlockableTest where Self: XCTestCase {
    func unlockSetUp() {
        continueAfterFailure = false

        app.launchArguments = ["uiTesting", "unlock"]
        app.launch()
    }
}

class UnlockedUITests: XCTestCase, UnlockableTest {
    var app = XCUIApplication()

    override func setUp() {
        super.setUp()

        unlockSetUp()
    }

    func testButton() {
        XCTAssert(app.buttons["SomeButtonInTheUnlockedState"].exists)
    }
}

However, I think the simplicity and convenience of your current approach is the preferable compromise. Protocols also can't contain stored properties though, so in order to get the benefit of a stored property, you'd need to add the app property to every XCTestCase descendant too.

A: You can do this with Swift packages now, if your tests are in a Swift Package then you can have a helper module that contains your base classes and these will not be added to the sidebar as empty test cases.
You can mix an xcodeproj with a local to the source folder swift package to facilitate this, and in general I would personally recommend this as it improves build times and allows you to make your codebase more modular with granular access control.

A: Assuming the following structure:
MyTestHelperClassName: XCTestCase {
    //... your helper methods
}

Remove its subclass declaration of XCTestCase
i.e the : XCTestCase part
Then it will not appear in the "Test Navigator"


text:
Q: Sending jwt token redirecting to a single page app In my server I get a request from an external app, check that its validity and then create jwt token and redirect to my single my app. I am thinking about two posible options.
One is to put that jwt token in a cookie and redirect to my app, then read the cookie from js side and use it to make api request from my spa app.
Another one is to redirect to my spa like this: https://my-spa.com/?token=jwtoken, then read query param of token with js and use it later for api calls.
The first option presents one trouble: let's say I have the same user call this scenario from two different browser tabs to two slightly different server url, which will generate different jwt token encoding in it the different url's context. So the user would get two different jwt tokens in in each tab's response via cookie. However, the response of the last browser tab would overwrite the cookie from the first tab. Then when the user hits refresh on the first tab, the overwritten cookie (with the context from the cookie from another tab) would be sent and that would be incorrect.
So I guess I only have the second option, where the user can refresh the page and my server would still get the correct token in query param from each browser tab. Is there something wrong with approach?


text:
Q: Text not wrapping I have following structure:
html

TITLE TEXT GOES HERE

css
.article-list-item {
    margin: 0 0 2px 0;
    position: relative;
    overflow: hidden;
}
.article-list-item h3.overlay-title {
    z-index: 600;
    display: inline;
    width: 99.9%;
    position: absolute;
    bottom: 0;
    margin: 0;
    padding: 0px 0 5px 10px !important;
}

Issue
The text within the link of the h3.overlay-title extends beyond the width of the a tag instead of wrapping and taking up multiple lines.
Demo
You can see it in action here: http://2be.be/ on the videoslider on top of the page. Items that have title wider that the image they're on will run behind the next slide instead of wrapping within the slide.

A: Try this:
.article-list-item h3.overlay-title
{
    white-space: normal;
    z-index: 600;
    display: inline;
    width: 99.9%;
    position: absolute;
    bottom: 0;
    margin: 0;
    padding: 0px 0 5px 10px !important;
}


text:
Q: how to apply event on moving image(Animating from top to bottom) i have an example,in this the image moves from top to bottom and bottom to top,this is fine but my requirement is i want to generates some events on the screen by clicking on that moving image thats it .
please any one help me.
 xml file:

     <FrameLayout
     android:layout_width="match_parent"
     android:layout_height="406dp"
     android:layout_gravity="bottom"
     android:background="@anim/graphics" >

     <!-- <ImageView
      android:id="@+id/androidimage"
      android:layout_width="100dp"
      android:layout_height="100dp"
      android:layout_gravity="bottom"
      android:onClick="imageButtonClicked"
      android:src="@drawable/android"
      android:layout_marginLeft="100dp"/> -->

  <ImageButton
      android:id="@+id/androidimage"
      android:layout_width="100dp"
      android:layout_height="100dp"
      android:layout_gravity="bottom"
      android:onClick="imageButtonClicked"
      android:src="@drawable/android"
      android:layout_marginLeft="100dp" />

  </FrameLayout>

A: You need to use nineoldandroids library.
use ObjectAnimator calss to animate.


text:
Q: Pasar datos de Activity a una clase Resulta que quiero pasar datos de una actividad hacia una clase para utilizar los métodos de esa clase pero quiero enviar un dato desde la actividad instanciando la clase pero no me llega el dato, seguramente se hace de otro modo no lo sé, hace mucho tiempo que no utilizo android, a continuación el código.
public class Guardar {
   private String address="no llegan datos";

   //Intent intent=getIntent
   public String GetAddress(){
       return address;
   }

   public void setAddress(String address){
      this.address=address;
   }

}

A continuación la actividad
Guardar g=new Guardar();
g.setAddress(address);

Estuve revisando pero muchas personas solo utilizan datos entre actividades pero no hay información de como enviar datos a una clase o como utilizar los métodos de una clase correctamente de antemano gracias.

A: Si deseas enviar datos desde una Activity a una clase, lo aconsejable es realizarlo definiendo un constructor que reciba estos datos, ejemplo:
public class Guardar {

 private String address="";

    //constructor
    public Guardar(String address) {
       this.address = address;
    }

   //Intent intent=getIntent
   public String GetAddress(){
       return address;
   }

  public void setAddress(String address){
      this.address=address;
  }
}

De esta forma al instanciar la clase Guardar puedes definir el valor:
Guardar g = new Guardar(address);

al realizar lo anterior puedes obtener el valor que originalmente definiste en la clase, ejemplo:
System.out.println("valor de address : " + g.getAddress());

A: Ya lo pude solucionar, el error era que estaba creando nuevas instancias en cada activity y recordé la arquitectura singleton que permite acceder a una misma instancia desde cualquier clase.
public class Guardar {
    private String address=null;

    private static Guardar guardar;
    //permite que otras clases eviten la creación de una nueva instancia
    public static synchronized Guardar getInstance(){
        if(guardar==null){//verifica que no se haya instanciado la clase
            guardar=new Guardar();//crea la nueva instancia
        }
        return guardar;//devuelve la única instancia
    }
    //constructor de clase privado
    //evita que accedan al constructor
    private Guardar(){

    }

    public String GetAddress(){
        return address;
    }

    public void setAddress(String address){
        this.address=address;
    }

}

A: Puedes crear una interfaz y hacer que la clase destino implemente dicha interfaz. O sea que obtienes una instancia de la actividad y le envías la información a la interfaz y con esto consigues que la clase destino contenga un método con la información pasada. Claro está que la interfaz debe contener un método que acepte por parámetros  un argumento del mismo tipo. Buena suerte


text:
Q: Compile template client side in ember using HTMLbars I have created a CMS where it is be possible to use HTMLbars to create templates. The templates should be compiled client side and there is component that should display the template. I'm setting the template property of the component to a function that returns the compiled template using HTMLBars.
import Ember from 'ember';

export default Ember.Component.extend({
  content: null,
  template: function () {
    return Ember.HTMLBars.compile(this.get('content.template'));
  }
}

I've included the ember-template-compiler in my Brocfile.
app.import('bower_components/ember/ember-template-compiler.js');

also tested
app.import('bower_components/ember-template-compiler/index.js');

But the template is never rendered.

A: It should be a property, and on a component it should be layout, but it will only be evaluated once, so updating the content won't rebuild the template.
http://emberjs.jsbin.com/vayereqapo/1/edit?html,js,output
Ember.Component.extend({
  content: {template: 'Hello'},
  layout: function () {
    return Ember.HTMLBars.compile(this.get('content.template'));
  }.property()
});

Rerender when template content changes:
App.FooBarComponent = Ember.Component.extend({
  content: {template: 'Hello'},
  foo: function(){
    var self = this;
    Em.run.later(function(){
      self.set('content.template', 'Bye');
      self.rerender();
    }, 3000);
  }.on('init'),
  layout: function () {
    return Ember.HTMLBars.compile(this.get('content.template'));
  }.property('content.template')
});

http://emberjs.jsbin.com/qebuxuxasu/1/edit


text:
Q: Finding all integers $a,b>1$ such that $a^n-n^a$ divides $b^n-n^b$ for all sufficiently large integers $n$ I just saw this question, and I recalled a similar problem.
Problem. Find all integers $a,b>1$ such that $a^n-n^a$ divides $b^n-n^b$ for all sufficiently large integers $n$.

A: Partial results:
Clearly $a=b$ works. As $a>b$ implies $a^n-n^a>b^n-n^b$ for $n$ large enough, we are left with the case $a<b$.
Let $p$ be a prime and let $v_p(x)$ denote the exponent of $p$ in $x$; so $v_p(xy)=v_p(x)+v_p(y)$, $v_p(x^y)=yv_p(x)$ and $v_p(x+y)\ge\min\{v_p(x),v_p(y)\}$ (with equality if $v_p(x)\ne v_p(y)$).
Assume $p\mid a$. Let $n$ be a large multiple of $p$. Then $p\mid a^n-n^a$, hence also $p\mid b^n-n^p$ and ultimately $p\mid b$.
Assume $p\nmid a$. Then $a^{p-1}\equiv 1\pmod p$. Now pick large $n$ that is $\equiv 0\pmod{p-1}$ and $\equiv 1\pmod p$. With this we get $p\mid a^n-n^a$, hence $p\mid b^n-n^b$, so that $b^n\equiv 1\pmod p$. Especially, $p\nmid b$.
So we have
$$ p\mid a\iff p\mid b$$


text:
Q: ARCore Visualizing video, image and 3D object So far I have my ARCore project display videos on top of images pretty consistently, but for more in depth understanding I wanted to be able to blend in 3D objects and still images as well. So say for a poster with three scanned image points, I would like to have one playing a video, other display a cube and third display an image.
Kind of multiple visualizers displaying different objects. My problem is I can't seem to integrate the simple cube and I feel that's either because:
-My visualizer object is a Quad and that dabbles with the placement of the object
-Not calling my cube prefab correctly, considering it is added to the visualizer prefab
-Also I can't seem to call an image instead of a video, and that's my lack of knowledge over here.
My AugmentedImageVisualizer seems pretty catered to video playback:
public class AugmentedImageVisualizer : MonoBehaviour

[SerializeField] private VideoClip[] _videoClips;

public AugmentedImage Image;
public GameObject[] Models;
private VideoPlayer _videoPlayer;

void Start()
{
    _videoPlayer = GetComponent<VideoPlayer>();
    _videoPlayer.loopPointReached += OnStop;
}

private void OnStop(VideoPlayer source)
{
  gameObject.SetActive(false);
}

void Update()
{
    if (Image == null || Image.TrackingState != TrackingState.Tracking)
    {
      Models[Image.DatabaseIndex].SetActive(false);

      return;
    }

    if (!_videoPlayer.isPlaying)
    {
      _videoPlayer.clip = _videoClips[Image.DatabaseIndex];
      _videoPlayer.Play();

      Models[Image.DatabaseIndex].SetActive(true);
    }

    transform.localScale = new Vector3(Image.ExtentX, Image.ExtentZ, 1);
}

The AugmentedImageController is pretty straight forward, yet I have not edited anything to accomodate the addition of a 3D object:
public class AugmentedImageController : MonoBehaviour

[SerializeField] private AugmentedImageVisualizer _augmentedImageVisualizer;

private readonly Dictionary <int, AugmentedImageVisualizer> _visualizers =
          new Dictionary <int, AugmentedImageVisualizer>();

private readonly List<AugmentedImage> _images =
          new List<AugmentedImage>();

private void Update()
{
  if (Session.Status != SessionStatus.Tracking)
  {
    return;
  }

  Session.GetTrackables(_images, TrackableQueryFilter.Updated);
  VisualizeTrackables();
}

private void VisualizeTrackables()
{
  foreach (var image in _images)
  {
    var visualizer = GetVisualizer(image);

    if (image.TrackingState == TrackingState.Tracking && visualizer == null)
    {
      AddVisualizer(image);
    }
    else if (image.TrackingState == TrackingState.Stopped && visualizer != null)
    {
      RemoveVisualizer(image, visualizer);
    }
  }
}

private void AddVisualizer(AugmentedImage image)
{
  var anchor = image.CreateAnchor(image.CenterPose);
  var visualizer = Instantiate(_augmentedImageVisualizer, anchor.transform);
  visualizer.Image = image;
  _visualizers.Add(image.DatabaseIndex, visualizer);
}

private void RemoveVisualizer(AugmentedImage image, AugmentedImageVisualizer visualizer)
{
  _visualizers.Remove(image.DatabaseIndex);
  Destroy(visualizer.gameObject);
}

private AugmentedImageVisualizer GetVisualizer(AugmentedImage image)
{
  AugmentedImageVisualizer visualizer;
  _visualizers.TryGetValue(image.DatabaseIndex, out visualizer);
  return visualizer;
}

This is my visualizer object, which might cause the restrictions for adding varied media, but I can't seem to make sense of how to modify it.
Wondering if I could add multiple visualizers that I can add new objects, videos and images to. (like the way videos already are in the project)
Goal is to allow adding extra files to display on visualizer
I was thinking of a way to make the Visualizer script on an empty and call a quad for videos, an empty with added 3D objects and another quad for images. But it feels like that is straying away from what I have so far.
Not sure what path would work, keep to the one AugmentedImageVisualizer or is there a way to create multiple Visualizers for displaying different objects. How to make it more modular, in order to display other media but still keep the functionality of adding and removing videos, objects and images and retain the order of anchoring

A: I assume that you are setting prefabs from your assets into the AugmentedImageVisualizer class, have you tried to Instantiate them?
The default ARCore augmented doesn't assign prefabs from assets, the script is in the prefab with the 3D object.
Also try to move the object at the center of the image, because you may be casting the objects far away from your view.
Sorry for my english.
Example:
Put this in the start void for each item in models.
GameObject.Instantiate(Models[Image.DatabaseIndex], Image.CenterPose.position, new Quaternion());


text:
Q: How can I troubleshoot high Kernel time? I have unusually high Kernel time on my CPUs as shown in task manager.
What are some ways I can troubleshoot this?

A: I had the issue myself with high kernel times consuming 50% of CPU, while other processes accounted for the remaining 40%.  The issue was caused by not properly disabling and uninstalling Trend AV.
Even though the services were stopped, and the realtime scan disabled, kernel mini filters appeared to be enabled.  I deduced that they were consuming kernel time after I unstalled the software properly and observed that the kernel time reduced to 1/10th of the previous load.
To view the list of filters on your system, type
C:\Users\TEMP>fltmc filters
Filter Name                     Num Instances    Altitude    Frame
------------------------------  -------------  ------------  -----
TmPreFilter                             3       328500         0
luafv                                   1       135000         0

Microsoft has a list of 3rd party filters available here.  According to that spreadsheet, TmPreFilter is Trend Micro, an AV Scanner.

A: The definitive tool for finding out exactly what is using kernel time is kernrate.exe. It comes with the Windows SDK/WDK Visual Studio, etc.
Also Xperf can do the same kernel polling/tracing as well... and is probably a lot easier to use. Kernrate was kind of a beast.

A: This is probably easier than you think.  If you have consistent, high system usage, Process Explorer provides a Threads tab that you can use for the System process (process id: 4).  The offending module and function should be displayed.

If you need a formal tool for collecting the empirical data to analyze the issue, you may use the Windows Performance Recorder/Windows Performance Analyzer, part of the Windows Performance Toolkit.
https://blogs.technet.com/b/yongrhee/archive/2012/11/23/installing-the-windows-performance-toolkit-v5-0-wprui-wpr-xperf.aspx
https://blogs.technet.com/b/yongrhee/archive/2012/11/23/wpr-xperf-capture-high-cpu-disk-i-o-file-registry-networking-private-bytes-virtual-bytes-paged-pool-nonpaged-pool-and-or-application-slowness.aspx

A: Have a nose using Process Monitor and DiskMon (Microsoft SysInternals) to see what the machine is doing.  One common culprit, aside from dodgy device drivers, is good old paging.


text:
Q: Lixo na memoria ao imprimir vetor de trás para frente
02 - Crie um algoritmo que solicite que o usuário entre com o seu nome e armazene em um vetor,
   o programa deverá armazenar em outro vetor o nome escrito de tráz para frente.
   Ao final, deverá ser escrito os dois vetores. Ex.: vinicius - suiciniv

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cstring>

using namespace std;

main(){

    char vetor[10];
    cout << "Digite um nome:";
    cin >>vetor;
    vetor[strlen(vetor)] = '\0';
    char contrario[strlen(vetor)];
    int tamanho =strlen(vetor-1);

    int j=0;

    for(int i=0;i<strlen(vetor);i++){

        cout<<vetor[i];

    }

    for(int i=strlen(vetor)-1;i>=0;i--){
        //cout <<vetor[i];
        contrario[j] = vetor[i];
        j+=1;
    }
    cout<< "--" <<contrario;

return 0;
}


text:
Q: My auto-generated doctrine file still includes and executes previous migrations commands I have a problem with how doctrine migration files are generated in my Symfony 4 app. My understanding is that each migration file should contain only the changes made since the last migration file was generated. For example, if I only made a small change in my Entity class e.g User class by only adding the age property I should expect that when I run make: migration in my console the only thing that my new migration file will contain is the command to add a Age column in my User Table. However, in my situation, the newer auto-generated file also contains older commands from a previous migration version which also get executed. Is there a way I could get rid of the older commands being included in my new migration file?
I'm running the latest Symfony 4.3 with Doctrine2


text:
Q: conversion fftw_complex to std::complex I used FFTW to calculate FFT of a complex vector .
the std::vector<std::complex<double>> successfully converted to fftw_complex array , but now i need to convert the output aray (which is an array with variables of fftw-complex type ) again to std::vector<std::complex<double>> and can not do this .
how may i do this conversion ?
the vector has converted to fftw_complex array in this way :
for (int i = 0 ;  i< fftrate ; i++){
       memcpy( &fftwarray[i], &inputvector[i]sizeof(fftw_complex ) );
            }

but i get segmentation fault err when i wanna convert back output with :
for (int j = 0 ;  j< fftrate ; j++){
 memcpy( &outputvector[j], &fftwarray[j],sizeof(fftw_complex ) );

           }

also i have tried reinterpret casting and it did not work .
EDIT :  example of program :
std::vector<std::complex<double>>input,output ;
std::vector<std::complex<double>> fft (void) {
   fftw_complex in[fftrate], out[fftrate];
   for (int i = 0 ;  i< fftrate ; i++){
       memcpy( &in[i], &input[i], sizeof( fftw_complex ) );
   }
   fftw_plan p=fftw_create_plan(fftrate, FFTW_FORWARD, FFTW_ESTIMATE);
   fftw_one(p, in, out);
   for (int j = 0 ;  j< fftrate ; j++){
       memcpy( &output[j], &out[j], sizeof( fftw_complex ) );
   }

   return output;
}

A: From std::complex:

For any pointer to an element of an array of complex<T> named p and any valid array index i, reinterpret_cast<T*>(p)[2*i] is the real part of the complex number p[i], and reinterpret_cast<T*>(p)[2*i + 1] is the imaginary part of the complex number p[i].

Since those are guaranteed, just skip the fftw_complex arrays completely:
std::vector<std::complex<double>> fft() {
    output.resize(input.size());

    fftw_plan p = fftw_create_plan(fftrate, FFTW_FORWARD, FFTW_ESTIMATE);

    fftw_one(p, reinterpret_cast<double*>(input.data()),
                reinterpret_cast<double*>(output.data()));

   return output;
}


text:
Q: IntelliJ CodeStyle Java - wrap if statement I'm having trouble configuring the formatter "correctly".
Intellij is formatting like this :
if (person.getPhoneNumber().equals(otherPerson.getPhoneNumber()) && person.getAddress()
                                                                         .equals(otherPerson.getAddress())
       && person.getFirstName().equals(person.getFirstName())) {
    ...
}

While I would like to format like this :
if (person.getPhoneNumber().equals(otherPerson.getPhoneNumber())
       && person.getAddress().equals(otherPerson.getAddress())
       && person.getFirstName().equals(person.getFirstName())) {
    ...
}

Is there any way to achieve this ?


text:
Q: Loop x words and move 1 position I want to loop through a String and return an array of strings that are the same length of the first argument. For example if I call search("one two three", "one two three four five"), it should return ["one two three", "two three four", "three four five"]
I've tried
        int numQualified = (int) (Math.floor(searchInWords.length / searchForWords.length) + 1);
        String[] qualified = new String[numQualified];
        for (int i = 0; i < numQualified; i++) {
            StringBuilder builder = new StringBuilder();
            for (int j = 0; j < searchForWords.length; j++) {
                if (searchInWords.length <= (searchForWords.length * i) + j) break;
                builder.append(searchInWords[(searchForWords.length * i) + j]).append(" ");
            }
            qualified[i] = builder.toString().trim();
            System.out.println("t: " + qualified[i]);
        }

However, it doesn't really work. If I input "one two three four five," I get [{four five}, {one two three}] instead of ["one two three", "two three four", "three four five"].

A: It looks like there are multiple issues here.  I think they all result from some ambiguity about whether you want to allow overlapping answers.  In your example, you listed both "one two three" and "two three four" as strings you want to find, so it appears that you do want to include overlapping strings.  However, the code that you've shown appears to have been written with the assumption that you do not want overlapping answers, and I think that is the cause of the issues.
First, the calculation for numQualified appears wrong.  Say, for example, that searchInWords contained 100 words, and searchForWords contained 2 words.  Your calculation for numQualified would yield 100/2 + 1 = 51.  But, aren't there really 99 different two-word-strings to be found in this case?
Second, inside your for loop, you use (searchForWords.length * i) + j to calculate the index of a string that you are examining.  This formula assumes non-overlapping strings, so it isn't going to get the results you want.  In your example, searchForWords.length is 3, so when i is 0, this formula will calculate indices 0,1,2.  When i is 1, it would calculate indices 3,4,5.  When i is 2, it would be 6,7,8.  Note that these sequences do not overlap.
I hope these observations help you get the results you are looking for.


text:
Q: AJAX Uncaught reference error, unclear why? I am in the process of converting my existing standard JS ajax functions to jQuery. So far I have converted all but one successfully, which seems to be causing an uncaught reference error.
For my add URL feature, I have a button which triggers this ajax function:
function showAdd(str)
    {
    document.getElementById("content01").innerHTML="";
    if (str=="")
    {
    document.getElementById("content01").innerHTML="";
    return;
    }
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("content01").innerHTML=xmlhttp.responseText;
    document.getElementById("response").innerHTML = "";
    }
    }
    xmlhttp.open("GET","addUrlForm.php?addUrl="+str,true);
    xmlhttp.send();
}

The ajax directs to a html form echoed from php (I wont include as I know this isn't causing the issue). The form action directs to my insert ajax function here:
function insert()
{
    var name= encodeURIComponent(document.getElementById('name').value);
    var releaseTime = encodeURIComponent(document.getElementById('releaseTime').value);
    var releaseDay = encodeURIComponent(document.getElementById('releaseDay').value);
    var category = encodeURIComponent(document.getElementById('category').value);
    var genre = encodeURIComponent(document.getElementById('genre').value);
    var url= encodeURIComponent(document.getElementById('url').value);

    xmlhttp.open('get', 'addUrl.php?name='+name+'& releaseTime=' +releaseTime+'& releaseDay=' +releaseDay+'& category=' +category+'& genre=' +genre+'& url=' +url);
    xmlhttp.onreadystatechange = urlRefresh;
    document.getElementById("response").innerHTML = "Processing Request. Please wait a moment...";
    xmlhttp.send(null);
    return;
}

And from this function the data goes to an insert statement and ends up in the DB. As it is the code above is working. When I change the SHOWADD ajax function to jQuery:
function showAdd(str)   {
    $('#response').html('loading...');
       $.ajax({
           type: "GET",
           url: "addUrlForm.php",
           data: "addUrl=" + str,
           success: function(msg)   {
               $('#response').empty();
               $('#content01').html(msg).show();
           },
           error: function () {
               alert('error');
        }
    });
};

Its spitting out the uncaught reference error. I know this isn't a huge error but if another peer of eyes could take a look and see what I missed that would be helpful. Thanks.
error reads: "Uncaught ReferenceError: xmlhttp is not defined" on line 105:
"xmlhttp.open('get', 'addUrl.php?name='+name+'& releaseTime=' +releaseTime+'& releaseDay=' +releaseDay+'& category=' +category+'& genre=' +genre+'& url=' +url);"

A: When you switched to the 2nd showAdd() function, it does not initialize the xmlhttp object like the 1st showAdd() function did, but your insert() function is still trying to use xmlhttp, but since it is not defined, it causes an error.
Probably the best thing is to switch the insert() function over to use jQuery also so none of your code is trying to use the xmlhttp variable.


text:
Q: How do I prevent screen tearing in Windows 7 desktop with Aero disabled? After disabling all the Windows 7 visual enhancements, I began noticing some screen tearing while playing YouTube videos, dragging windows, etc.. It's very noticeable while looking at this:
 Barcode Animation
It looks like the fps exceeds the monitor's refresh rate capabilities (60Hz). Are there any hidden functions in the Windows desktop that can sync fps with monitor's refresh rate?


text:
Q: RichTextBlockOverflow.HasOverflowContent always false in Windows 8 Metro app since you have to support multiple screen resolutions in Windows 8 Metro Apps I want to split up my RichTextBlock to show text that would be cut off in a RichTextBlockOverflow control (or multiple controls, depending how much text I have to show).
In order to determine if I have to show an additional RichTextBlockOverflow-Control I check the
HasOverflowContent-Property of my RichTextBlocks. But it always returns false.
It's super easy to reproduce:

*

*Create a new "Windows Store -> Blank App"

*Replace the xaml of MainPage.xaml with the following code:

<StackPanel Orientation="Horizontal" Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <RichTextBlock x:Name="test1" Width="100" Height="300" OverflowContentTarget="{Binding ElementName=test}">
        <Paragraph>
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
            lkj halks dflkjha skld fkla hsdkl hfakl dsflk hasdkl fakl hsdklf halks dflka jhsdhfklaj hsdklf jhakls dflkaj hsdlkfjh alks dflkajh s
        </Paragraph>
    </RichTextBlock>
    <RichTextBlockOverflow x:Name="test" Width="100" Height="300" />

</StackPanel>

Then go the code behind file (MainPage.xaml.cs) and replace the constructor with that code:
public MainPage()
{
    this.InitializeComponent();
    if (test.HasOverflowContent)
    {
        // Will never be entered
    }
    if (test1.HasOverflowContent)
    {
        // Will never be entered
    }
}

Set a breakpoint in the on this.InitializeComponent() and see how the HasOverflowContent will never be true.
What am I doing wrong? Or is it a bug in .NET?
Any help would be very appreciated ;)
Andi

A: Try using a different event, by putting your code in the Page_Loaded event I was able to get HasOverflowContent to work.


text:
Q: Getting clusters of rows close together in time I have a table basically like so
   ID   |  ItemID  |       Start        |         End        |
---------------------------------------------------------------
    1       234      10/20/09 8:34:22      10/20/09 8:35:10
    2       274      10/20/09 8:35:30      10/20/09 8:36:27
    3       272      10/21/09 12:15:00     10/21/09 12:17:00
    4       112      10/21/09 12:20:14     10/21/09 12:21:21
    5       15       10/21/09 12:22:39     10/21/09 12:24:15

There are two "clusters" of entries here, 1-2 and 3-5 separated by a gap in time, specifically > 30 minutes is what I'm interested in.
What I would like is the first and last rows of the cluster of entries. This is fairly easy to achieve by retrieving all the rows and looping through them in order of start time, but I'd like to have it in SQL if possible.
I'm using SQL Server 2008, thanks.
Edit:
Each row would contain
  first.* , last.*

where first is the first row in the cluster and last is the last row.
the results of this table would be
    1       234      10/20/09 8:34:22      10/20/09 8:35:10           2       274      10/20/09 8:35:30      10/20/09 8:36:27
    3       272      10/21/09 12:15:00     10/21/09 12:17:00          5       15       10/21/09 12:22:39     10/21/09 12:24:15

A: try this out:
DECLARE @YourTable table (ID int, ItemID int, StartD datetime, EndD datetime)
INSERT @YourTable VALUES (1,234,'10/20/09 8:34:22' ,'10/20/09 8:35:10' )
INSERT @YourTable VALUES (2,274,'10/20/09 8:35:30' ,'10/20/09 8:36:27' )
INSERT @YourTable VALUES (3,272,'10/21/09 12:15:00','10/21/09 12:17:00')
INSERT @YourTable VALUES (4,112,'10/21/09 12:20:14','10/21/09 12:21:21')
INSERT @YourTable VALUES (5,15 ,'10/21/09 12:22:39','10/21/09 12:24:15')

;WITH AggValues AS
(SELECT
     MAX(ID) AS MaxID, COUNT(ID) AS CountOf, MIN(ID) AS MinID
     FROM @YourTable
)
, NumberRows AS
(SELECT --generate a first row to help get a range
     0 AS ID, a.StartD-1 AS StartD, a.EndD-1 AS EndD, 0 AS RowNumber
     FROM @YourTable a
         INNER JOIN AggValues dt ON a.ID=dt.MinID
 UNION
 SELECT --get all actual rows
     ID, StartD, EndD, ROW_NUMBER() OVER(ORDER BY ID) AS RowNumber
     FROM @YourTable
 UNION
 SELECT --generate a last row to help get a range
     dt2.MaxID+1 AS ID, a.StartD+1 AS StartD, a.EndD+1 AS EndD, dt2.CountOf+1 AS RowNumber
     FROM @YourTable a
         INNER JOIN AggValues dt2 ON a.ID=dt2.MaxID
)
, FindGaps AS
(SELECT
     a.ID,DATEDIFF(minute,b.StartD,a.EndD) AS Diff, a.RowNumber, c.RowNumber AS PreviousRowNumber
     FROM NumberRows                 a
         LEFT OUTER JOIN NumberRows  b ON a.RowNumber=b.RowNumber+1
         LEFT OUTER JOIN NumberRows  c ON a.RowNumber-1=c.RowNumber
)
, Gaps AS
(SELECT
     f.ID,f.RowNumber, f.PreviousRowNumber, ROW_NUMBER() OVER(ORDER BY ID) AS GapRowNumber
     FROM FindGaps f
     WHERE f.Diff>30
)
, Results AS
(SELECT
     g.ID,n.ID AS IDEnd
     FROM Gaps                       g
         LEFT OUTER JOIN Gaps        x ON g.GapRowNumber+1=x.GapRowNumber
         LEFT OUTER JOIN NumberRows  n ON x.PreviousRowNumber=n.RowNumber
     WHERE n.ID IS NOT NULL
)
SELECT
    a.*,b.*
    from Results                      r
        LEFT OUTER JOIN @YourTable    a ON r.ID=a.ID
        LEFT OUTER JOIN @YourTable    b ON r.IDEnd=b.ID

OUTPUT:
ID          ItemID      StartD                  EndD                    ID          ItemID      StartD                  EndD
----------- ----------- ----------------------- ----------------------- ----------- ----------- ----------------------- -----------------------
1           234         2009-10-20 08:34:22.000 2009-10-20 08:35:10.000 2           274         2009-10-20 08:35:30.000 2009-10-20 08:36:27.000
3           272         2009-10-21 12:15:00.000 2009-10-21 12:17:00.000 5           15          2009-10-21 12:22:39.000 2009-10-21 12:24:15.000

(2 row(s) affected)


text:
Q: How can i unpack a list of dicts. in python? The output of my code is a list of dictionaries and I want to unpack this list and print each dictionary alone in one line and tried the join method but I couldn't work with it and I also want to erase the single quote from text, I just want the text to appear only and i can't do that.
here's a sample of the list that i'm workin' with:
[{'نوع البطولة': 'الدوري المصري', 'الفريق الأول': 'المصري', 'الفريق الثانى': 'المقاولون العرب', 'وقت المباراة': '21-12-2022 - 17:00', 'النتيجة': '- - -'}, {'نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'المنصورة', 'الفريق الثانى': 'نبروه', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'}, {'نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'الحمام', 'الفريق الثانى': 'المجد السكندري', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'}, {'نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'أبو قير للأسمدة', 'الفريق الثانى': 'هلال مطروح', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'}]

i'm expecting to get a text like this:
'نوع البطولة': 'الدوري المصري', 'الفريق الأول': 'المصري', 'الفريق الثانى': 'المقاولون العرب', 'وقت المباراة': '21-12-2022 - 17:00', 'النتيجة': '- - -'
 نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'المنصورة', 'الفريق الثانى': 'نبروه', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'
, {'نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'الحمام', 'الفريق الثانى': 'المجد السكندري', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'
 'نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'أبو قير للأسمدة', 'الفريق الثانى': 'هلال مطروح', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'

A: If I understand correctly, you want to print the entire array of dictionaries on one line. To do this, you can loop through the initial array, and print them, but specify an ending with the print statement, and don't let it end with a newline (\n).
In Python:
list = ['str1', 'str2', 'str3']
for i in list:
    print(i, end=' ')

If you do not want a space in-between each element, make the print statement print(i, end='').

A: There's nothing built-in that prints a dictionary without its {} delimiters, so you need write your own formatter.
def format_dict(d):
    return ', '.join(f'{repr(key)}: {repr(value)}' for key, value in d.items())

for d in list_of_dicts:
    print(format_dict(d))


text:
Q: Can developers of gsuite addons view the data in your sheets / docs? Suppose we install a gsuite addon, we may see something like:

Suppose we have a google sheet/doc containing some plain text (a pretty standard use), equations, etc; e.g. it may contain: Here's something top secret: my_secret_123_abcxyz?!
Are there circumstances under which the developers of the addon be able to read the text contained in the cells of a google sheet (or in a google doc)?
For reference: here are the T&C and privacy policy for the example above - note that there's no clear answer to the question contained in either of those policies.
Note: this is an extremely important consideration for handling client data, or meeting data governance requirements/laws at company and/or federal levels.

A: I think it is possible. See below link.
https://developers.google.com/gsuite/add-ons/editors/sheets
You can create custom functions. Then you can use UrlFetchApp to communicate with external server.
https://developers.google.com/apps-script/reference/url-fetch
This service requires script.external_request scope.
I have attached a screenshot below.You can see all the scopes this particular add-on needs. You will get this prompt while installing the add-on. Connect to an external service is the scope you are looking for.

A: I'm the developer of the smart references plugin for google docs.
https://gsuite.google.com/marketplace/app/smart_references/139900623597
The answer is that it depends on how the plugin works. The google plugin sandbox is quite limited. The code developers provide that can run on googles servers or in the users browser is limited to a few JavaScript files, and without the ability to import or export data there is only so much those scripts could do. So many plugins send document data to external applications to provide advanced functionality. For example the Smart References plugin does not need to export any data from the docs context because it is relatively simple plugin that just synchronises headings within a document - but consider a grammar checking plugin or an integration into a crm - all the smarts live on external servers that google does not control. As developers we are asked to disclose if and how we use document data in the privacy policy and terms of service. Google does have an independent review process for new plugins but they only review the plugin code not the workings or administration of any external api.
So when you permission a plugin you are potentially giving access to your data to the plugin developers and you should make an active decision on whether or not to trust them. This is the case with any cloud software or desktop apps that use APIs to work.

A: Q. Are there circumstances under which the developers of the addon be able to read the text contained in the cells of a google sheet (or in a google doc)?
A.Yes, the developers can read the text. Specifically what the application reads and what is done with that data is a mystery however.
When developing Gsuite add-ons you use a programming language called Google Apps Script.(Google gives the creators and internal editor to work in).
When the creator of the add-on writes code wanting to access different parts of the Gsuite API, a scope is automatically added to the manifest file for the application.
The scope list explains what the application is attempting to access as it runs. That list generates the screen seen below.

The permission screen doesn't get anymore specific than that. However, everyone who wants to submit an application into the GSuite marketplace has to submit to a review process.
One of Google's priorities in that process is making sure the add-on's publishers "Take appropriate steps to safeguard user data.".


text:
Q: Can `ItemReader` in spring batch wait until the point in time when the data can be available for processing similar like Blocking Queues? At present I am following the below strategy for processing items in a step.
TaskletStep processingStep = stepBuilderFactory.get(getLabel() + "-" + UUID.randomUUID().toString())
                        .<Object, Object>chunk(configuration.getChunkSize())
                        .reader(reader)
                        .processor(processor)
                        .writer(writer).transactionManager(txManager).build();
TypedJobParameters typedJobParameters = new TypedJobParameters();
runStep(processingStep, typedJobParameters);

This Task Step does some additional work too like compressing the file and copying it to a different location therefore it took so long time to complete. How can I offload this additional work to background threads.
If  background thread keep polling till new file arrives for compression then it may consume more CPU cycles whereas if we can put that thread on wait and notify it when new file arrives then it will become more complex.
How can I start a new TaskStep parallel to my existing above TaskStep in such way that ItemReader of that new TaskStep wait until the point in time when the file arrives for processing like blocking queues?

A: You can delegate "expensive" work to background thread if you define your processor as an AsyncItemProcessor. You can assign task executor to it with thread pool and delegate processor which will do actual work in background thread.
Item reader will accept other files and will assign them to threads in task executor. When background thread completes processing of file it will be then assigned back to writer.
AsyncProcessor asyncProcessor = new AsyncProcessor();
asyncProcessor.setDelegate(processor);
asyncProcessor.setTaskExecutor(taskExecutor);

AsyncItemWriter asyncItemWriter = new AsyncItemWriter();
asyncItemWriter.setDelegate(writer);

TaskletStep processingStep = stepBuilderFactory.get(getLabel() + "-" + UUID.randomUUID().toString())
                    .<Object, Object>chunk(configuration.getChunkSize())
                    .reader(reader)
                    .processor(asyncProcessor)
                    .writer(asyncWriter).transactionManager(txManager).build();
TypedJobParameters typedJobParameters = new TypedJobParameters();
runStep(processingStep, typedJobParameters);


text:
Q: Mistake in SageMathCell code, finding integral points on elliptic curves I've the following number:
$$12\left(n-2\right)^2x^3+36\left(n-2\right)x^2-12\left(n-5\right)\left(n-2\right)x+9\left(n-4\right)^2\tag1$$
Now I know that $n\in\mathbb{N}^+$ and $n\ge3$ (and $n$ has a given value) besides that $x\in\mathbb{N}^+$ and $x\ge2$.
I want to check if the number is a perfect square, so I can rewrite $(1)$ as follows:
$$y^2=12\left(n-2\right)^2x^3+36\left(n-2\right)x^2-12\left(n-5\right)\left(n-2\right)x+9\left(n-4\right)^2\tag2$$
Where $y\in\mathbb{Z}$.
In this problem I've: $n=71$, the number is equal to;
$$y^2=57132x^3+2484x^2-54648x+40401\tag3$$
So, I used SageMathCell to look for the integral points on the elliptic curve and the code that was used is the following:
E = EllipticCurve([0, β, 0, γ, δ])
P = E.integral_points()
for p in P:
    if p[0] % α == 0:
        print(p[0] // α, p[1] // α)

I found the coeficients I need to use using equation $(2)$ and $(3)$ (but I do not know if they are corect):

*

*$$\alpha=12(71-2)^2=57132\tag4$$

*$$\beta=36(71-2)=2484\tag5$$

*$$\gamma=-144(71-5)(71-2)^3=-3122149536\tag6$$

*$$\delta=1296(71-4)^2(71-2)^4=131871507195024\tag7$$
So the final code looks like:
E = EllipticCurve([0, 2484, 0, -3122149536, 131871507195024])
P = E.integral_points()
for p in P:
    if p[0] % 57132 == 0:
        print(p[0] // 57132, p[1] // 57132)

But I found no solutions and it should give at least one solution at $x=1585$.

What mistake have I made?

A: After about an hour and a half running SageMath 9.0.beta7 on my computer, I see this:
sage: E = EllipticCurve([0, 2484, 0, -3122149536, 131871507195024])
sage: P = E.integral_points()
sage: for p in P:
....:    if p[0] % 57132 == 0:
....:        print(p[0] // 57132, p[1] // 57132)
....:
(-1, 201)
(0, 201)
(1, 213)
(1585, 15083061)


text:
Q: How do I turn my NEI on in Minecraft? I have installed NEI onto my minecraft and it was there when i logged off my world but when I went back onto my world my NEI wasn't there.
Does anyone know where or what button I press to get my NEI back as I really need it?

A: Try enabling NEI in the inventory by pressing "o", if that doesn't work identify that the mod is installed by clicking the mods button, If the mod is not in that list re-install it.

A: Press the O key, it's the default for turning the mod on/off. Check if the mod is installed correctly as well. If it isn't installed that could be your problem!

A: Go to inventory > options > and make sure gamemode is on.
After that, go to inventory again and click the yellow "C" on your top left corner until it says "C+". If it already says that already click it 4 times.

A: Try changing your GUI scale in options > video settings, and see if it is on 'auto'.
If that does not work, go into your inventory, and press o or e.

A: Try pressing "O" or "CTRL" and "O"


text:
Q: fopen is duplicating the same line I have a file that looks like this:
1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]||55.183.567

I made a function that when executed adds a given number or removes it if already present, which is $added and equals 100 for this example. This is my code:
$added = $_GET['added']; //100 for this example

$f = fopen($file, "w");
$list = file($file);
foreach ($list as $line) {
    $details = explode("||", $line);
    if (preg_match("~\b$details[0]\b~", 3)) {
        foreach ($details as $key => $value) {
            if ($key == 5) {
                $newline .= str_replace("[" . $added . "]", "", $value);
            } else {
                $newline .= $value . "||";
            }
        }
        $line = $newline . "\n";
    }
    fputs($f, $line);
}
fclose($f);
}

this code is supposed to remove the [100] from the Rocky line since its already present which it kinda does. However, upon further execution instead of adding it back it duplicates the Rocky line and messes it up so the file looks like this:
1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]55.183.567

3||Rocky||21||male||USA||[100][200]55.183.567
||
||

why is it doing this? I cant make any sense out of it...
Thank you.

A: First, you should read the file before you open it for output, because opening with the w mode truncates the file.
Second, you don't need to loop over the fields in $details if you just want to change one of them. Just access and assign it by index.
Then you can put the line back together with implode().
$list = file($file);
$f = fopen($file, "w");
foreach ($list as $line) {
    $details = explode("||", $line);
    if (preg_match("~\b$details[0]\b~", 3)) {
        if (strpos("[$added]", $details[5]) === false) {
            $details[5] = "[$added]" . $details[5];
        } else {
            $details[5] = str_replace("[$added]", "", $details[5]);
        }
        $line = implode('||', $details)
    }
    fputs($f, $line);
}
fclose($f);


text:
Q: Comparação com 3 tabelas create table Pessoa (
    id int not null primary key auto_increment,
    nome varchar(150) not null,
    cidade varchar(100) not null,
    cpf char(14) not null unique,
    rg int not null unique,
    INDEX idx_nome(nome)
);

create table conta(
    id int not null primary key auto_increment,
    numero int not null,
    agencia int not null,
    saldo decimal(20,2) not null,
    pessoa_id int not null,
    foreign key(pessoa_id) references Pessoa(id)
        ON UPDATE CASCADE,
    INDEX idx_numero_agencia(numero, agencia)
);

create table medico(
    pessoa_id  int primary key not null,
    especialidade varchar(100)not null,
    FOREIGN KEY(pessoa_id) references Pessoa(id)
        ON UPDATE CASCADE
);

create table paciente (
    pessoa_id int primary key not null,
    doenca varchar(100)  not null,
    FOREIGN KEY(pessoa_id) references Pessoa(id)
        ON UPDATE CASCADE
        ON DELETE RESTRICT
);

create table consulta(
    medico_id int,
    paciente_id int,
    horario datetime not null,
    FOREIGN KEY(medico_id) references medico(pessoa_id)
        ON UPDATE CASCADE
        ON DELETE RESTRICT,
    FOREIGN KEY(paciente_id) references paciente(pessoa_id)
        ON UPDATE CASCADE
        ON DELETE RESTRICT,
    INDEX idx_medico_horario(medico_id,horario),
    INDEX idx_paciente_horario(paciente_id,horario)
);

select Pessoa.nome `Nome do Médico`,
    Pessoa.cpf `CPF do Médico`,
    Pessoa.nome `Nome do Paciente`,
    Pessoa.cpf `CPF do Paciente`,
    consulta.horario `Horário da Consulta`
    from Pessoa inner join consulta on (consulta.medico_id = Pessoa.id)
    inner join medico on (consulta.medico_id = Pessoa.id)
    inner join paciente on (consulta.paciente_id= Pessoa.id)
    order by consulta.horario asc;

Eu criei um banco onde uma pessoa pode ser um medico ou paciente, mas quando vou mostrar a tabela que mostra o  nome e o cpf do medico, e o nome e o cpf do paciente, dá erro.


text:
Q: Functions in Access SQL not available in Oracle SQL I posted a question a few days ago. I have a query made with the query wizard in Access (I am by no means an SQL expert) and was trying to connect Excel directly to my data source (Oracle ORAD database) and it wasn't working. We determined that is because the SQL generated from Access is not the type of SQL the Oracle DB will interpret.
My Access based SQL query uses functions:

*

*Trim

*IIf(IsNull([Table1]),[Table 2], [Table 3])

*Val([Table 4])

*Sum

*(in the format): Sum(IIf(Not(IsNull([Table])),[Table], 0))

Which functions can I keep and which should I change, and what should I change them to? I keep trying to look things up in the Oracle Help website but it is confusing and there aren't many examples of syntax.
Any help is greatly appreciated!


text:
Q: Change object value to array I am having JSON object as follow:
testUser3: "{"accountDetails":"false"}"

I want this object to change to
accountDetails: ["false"]

I used $.each
$.each(value, function(key,value){
            this.data = value;
        });

but again for this i have to iterate again which i don't want. something like below
//for (var i in this.data) {
          //  anarray.push(this.data[i]));
         //

Is there any single liner which content the value to array.

A: Just assign the value in an array.
object.testUser3.accountDetails = [object.testUser3.accountDetails];

var object = { testUser1: { accountDetails: true } , testUser3: { accountDetails: false } };

Object.keys(object).forEach(function (a) {
    object[a] = Object.keys(object[a]).map(function (b) {
        return [object[a][b]];
    });
});

document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');

A: Asuming that you ment this:var yourObj = {testUser3:
{"accountDetails":"false"}};
var newObj = {
    testUser3: {}
};

for(var key in yourObj.testUser3) {
  newObj.testUser3[key] = [yourObj.testUser3[key]];
}
JSON.stringify(newObj);

Good luck

edited code on bases of comments


text:
Q: How to create a table with some rows merged on the right column I want to create a table like

There are 2 cells in the 4th column which are merged vertically on the right side.
While it is easy to merge them on the left side using multirow, I'm at a loss on how to merge on the right side
Here is my source code (using IEEEtran.cls):
\documentclass[conference]{IEEEtran}
% Add the compsoc option for Computer Society conferences.
% *** GRAPHICS RELATED PACKAGES ***
%
\ifCLASSINFOpdf
   \usepackage[pdftex]{graphicx}
  % declare the path(s) where your graphic files are
  % \graphicspath{{../pdf/}{../jpeg/}}
  % and their extensions so you won't have to specify these with
  % every instance of \includegraphics
   \DeclareGraphicsExtensions{.pdf,.jpeg,.png,.eps}
\else
  % or other class option (dvipsone, dvipdf, if not using dvips). graphicx
  % will default to the driver specified in the system graphics.cfg if no
  % driver is specified.
   \usepackage[dvips]{graphicx}
  % declare the path(s) where your graphic files are
  % \graphicspath{{../eps/}}
  % and their extensions so you won't have to specify these with
  % every instance of \includegraphics
   \DeclareGraphicsExtensions{.eps}
\fi

% correct bad hyphenation here
\hyphenation{op-tical net-works semi-conduc-tor}
\usepackage{lscape}
\usepackage{multirow}
%\usepackage{subfig}
\usepackage{subfigure}
%\usepackage{subcaption}

\usepackage{tikz}
\def\checkmark{\tikz\fill[scale=0.4](0,.35) -- (.25,0) -- (1,.7) -- (.25,.15) -- cycle;}

 \documentclass[conference]{IEEEtran}

    \ifCLASSINFOpdf
       \usepackage[pdftex]{graphicx}

       \DeclareGraphicsExtensions{.pdf,.jpeg,.png,.eps}
    \else
       \usepackage[dvips]{graphicx}
       \DeclareGraphicsExtensions{.eps}
    \fi

    % correct bad hyphenation here
    \hyphenation{op-tical net-works semi-conduc-tor}
    \usepackage{lscape}
    \usepackage{multirow}

    \usepackage{subfigure}

    \begin{document}

    \section{Introduction}

    \section{xxx}

    \begin{table}[h]
    \centering
    \begin{tabular}{ |p{0.6cm}|p{1cm}|p{0.6cm}|p{4cm}| }
    \hline
    {\fontsize{7}{60}\selectfont Source IP} & {\fontsize{7}{60}\selectfont Destination IP} & {\fontsize{7}{60}\selectfont CCN Name} & Example Application Scenarios \\
        \hline
    $\times$ & xx & xx& Content requester wants to hide its location/IP \\
        \hline
    dul & $\times$ & lus &  \multirow{2}{*}{Content requester wants to hide its location/IP} \\
        \cline{1-3}
    ddd & $\times$ & lus & \\
        \hline
    $\times$ & Lucus & lus & Content requester wants to hide its location/IP \\
        \hline
    $\times$ & Lucus & lus & Content requester wants to hide its location/IP \\
        \hline
    \end{tabular}
    \caption{xxxx}
    \label{tab:header}
    \end{table}

    \begin{thebibliography}{1}

    \end{thebibliography}

    \end{document}

The result is the width of that two cells are not equal.

A: @egreg deserves the glory. Here is a MWE:
\begin{tabular}{l|l|l|l}
a1 & a2 & a3 & a4\\ \hline
b1 & b2 & b3 & \multirow{2}{*}{bc4}\\ \cline{1-3}
c1 & c2 & c3 & \\ \hline
d1 & d2 & d3 & d4
\end{tabular}

A: Try the following code:
\begin{table}[h]
\centering
\begin{tabular}{ |p{0.6cm}|p{1cm}|p{0.6cm}|p{4cm}| }
\hline
{\fontsize{7}{60}\selectfont Source IP} & {\fontsize{7}{60}\selectfont Destination IP} & {\fontsize{7}{60}\selectfont CCN Name} & Example Application Scenarios \\
\hline
$\times$ & v & v & Content requester wants to hide its location/IP \\
\hline
dul & $\times$ & lus &  \multirow{2}{*}{\parbox[t]{4cm}{Content requester wants to hide its location/IP}} \\
\cline{1-3}
ddd & $\times$ & lus & \\
\hline
$\times$ & Lucus & lus & Content requester wants to hide its location/IP \\
\hline
$\times$ & Lucus & lus & Content requester wants to hide its location/IP \\
\hline
\end{tabular}
\caption{xxx }
\label{tab:header}
\end{table}


text:
Q: Referance a static resource via aura:attribute I have created a new component and I want to be able to pass an image from a static resource and a custom label via aura:attribute. This is what I tried and it does not work. How can I make the image/text to show?
<aura:attribute name="profileImage" type="string" default="Standard_Profile" />
<aura:attribute name="categoryName" type="string" default="Standard_Name" />

{!$Label.'categoryName'}

I am very new to Salesforce.

A: Map the values from your custom label and static resource as default values in the attributes and use it in the code
<aura:component implements="flexipage:AvailableForAllPageTypes">
    <aura:attribute name="profileImage" type="string" default="{!$Resource.profileImage}" />
    <aura:attribute name="categoryName" type="string" default="{!$Label.c.categoryName}" />

        {!v.categoryName}

</aura:component>


text:
Q: Как узнать активный элемент dropDownList в yii2 Нужно чтобы в зависимости от выбранного элемента в dropDownList был вывод следующего поля - если string, то выводим текстового поля, если image - fileInput
Вот такой код листа
<?= $form->field($model, 'type')->dropDownList([
    'string' => 'string',
    'image' => 'image',
]);

Пытался так делать, но ни работает
if($model->type = 'image')
{
    echo $form->field($model, 'file')->fileInput();
}
else
{
   echo $form->field($model, 'value')->textInput();
}

Нужно как-то считывать активный элемент и в if() записывать ?

A: тебе нужна повесить js обработчик на твой <select> и в зависимости от выбраного типа показывать/разблокировать или скрывать/блокировать нужные поля.
Если у тебя всего 2 поля тогда можно организовать переключатьли типов с помощью input:radio:
$this->registerJs(<<<JS
$('#type_switcher input:radio').on('click', function() {
    $('#type_switcher').find('input:not(:radio)').each(function(){
        this.disabled = true;
    });
    $(this).closest('.form-group').find('input:not(:radio)').each(function(){
        this.disabled = false;
    });
});
JS
);

Выводим поля для формы
<div id="type_switcher" class="form-group" style="margin-left: 0; margin-right: 0;">
<?= $form->field($model, 'file')
    ->fileInput([
        'class' => 'form-control',
        'disabled' => $model->type != $model::TYPE_FILE
    ])
    ->label(
        Html::activeRadio($model, 'type', [
            'value' => $model::TYPE_FILE,
            'label' => $model->getAttributeLabel('file'),
            'id' => Html::getInputId($model, 'type') . '_' . $model::TYPE_FILE,
        ])
    ) ?>

<?= $form->field($model, 'value')
    ->textInput([
        'maxlength' => true,
        'disabled' => $model->type != $model::TYPE_VALUE
    ])
    ->label(
        Html::activeRadio($model, 'type', [
            'value' => $model::TYPE_VALUE,
            'label' => $model->getAttributeLabel('value'),
            'id' => Html::getInputId($model, 'type') . '_' . $model::TYPE_VALUE,
            'uncheck' => null, // !!!
        ])
    ) ?>
</div>


text:
Q: Count many items in one query This is what I got at the moment:
SELECT `p`.`name`, SUM(`count`) FROM `player_items`
LEFT JOIN `players` `p` ON (`p`.`id` = `player_items`.`player_id`)
WHERE `itemtype` IN (2148, 2152, 2160) GROUP by `player_id`, `itemtype`

It withdraw player name and the SUM of the item types with ID 2148, 2152, 2160.
I need to rewrite this query so it will select items count for each ID, this is how the results should look like:
| NAME   | ITEM | COUNT |
| Player | 2148 | 10    |
| Player | 2152 | 760   |
| Player | 2160 | 0     |

|  NAME   | ITEM | COUNT |
| Player1 | 2148 | 890   |
| Player1 | 2152 | 5560  |
| Player1 | 2160 | 2584  |

Structure:
Table name = player_items
ITEM ID(2148, 2152, 2160) - itemtype
ITEM COUNT - count.

Keep in mind that each item id can have other "COUNT" value for example for one player in the player_items table will look like:
PLAYER_NAME | 2148 | 10
PLAYER_NAME | 2148 | 4
PLAYER_NAME | 2148 | 4
PLAYER_NAME | 2152 | 60
PLAYER_NAME | 2152 | 20
PLAYER_NAME | 2160 | 100

Let me know, if you don't get anything.

A: I'm not quite sure what your problem is. Don't you just want to return the item id (called itemtype) ??
SELECT
    `p`.`name` AS `Name`,
    `i`.`itemtype` AS `Item`,
    SUM(`i`.`count`) AS `Count`
FROM
    `player_items` AS `i`
LEFT JOIN
    `players` AS `p`
    ON
        (`p`.`id` = `i`.`player_id`)
WHERE
    `i`.`itemtype` IN (2148, 2152, 2160)
GROUP BY
    `i`.`player_id`,
    `i`.`itemtype`

This is a community wiki so it can be corrected if need be.


text:
Q: State Confusion This code works:
const defaultState = {
  myProp: false
};

it('should change the value of myProp', () => {
  let state = defaultState;

  console.log(state);
  state.myProp = true;
  console.log(state)
});

myProp is successfully changed to true, as one would expect.
But this doesn't appear to work:
const myReducer = (state, action) => {
  switch(action.type) {
    case CHANGE_PROP: {
      return {
        ...state,
        myProp: action.myProp
      };
    }
  }
};

const defaultState = {
  myProp: false
};

it('should change the value of myProp', () => {
  let state = defaultState;

  console.log(state);
  myReducer(state, {type: types.CHANGE_PROP, myProp: true});
  console.log(state)
});

I've simplified the code for this posting but the core code is there.  Simply put, state.myProp doesn't change.
Yet, this works:
expect(
  myReducer(state, {type: types.CHANGE_PROP, myProp: true})
).toEqual(
  {
    ...state,
    myProp: true
  }
);

So, in my unit test, why can't I change the myProp value and have it persist?

A: I think I know where I got confused.
I can solve the problem this way
let newState = myReducer(state, {type: types.CHANGE_PROP, myProp: true});

And newState.myProp will definitely be true.
My confusion was that I assumed that state was being passed by reference so I thought that updating a property of it would cascade back to where it was called from.  Apparently not.
In my Context that uses this reducer is this:
const [state, dispatch] = useReducer(myReducer, defaultState);

So I can infer that state props updated by myReducer return a new instance of state to the Context.  At least this is my assumption.


text:
Q: Show only parent categories and sub-categories in left nav I have currently implemented a code which shows all categories on the left nav instead of that I want current category and current category's all sub categories.
Now my category structure is like
-parent1
 -sub 1
  -sub sub 1
 -sub 2
-parent2
 -sub 3

Now if i am on page Sub1 then I must be able to see all sub categories of sub 1 and also the sub categories of parent1
If I am on sub sub 1 then I must be able to see sub categories of sub1 .
I have currently implemented the following code

        Categories

    <?php $helper = $this->helper('catalog/category') ?>
    <?php $categories = $this->getStoreCategories() ?>
    <?php if (count($categories) > 0): ?>

            <?php foreach($categories as $category): ?>
                <li class="level0<?php if ($this->isCategoryActive($category)): ?> active<?php endif; ?>">
                   <a href="<?php echo $helper->getCategoryUrl($category) ?>"><?php echo $this->escapeHtml($category->getName()) ?>
                    <?php //if ($this->isCategoryActive($category)): ?>
                        <?php $subcategories = $category->getChildren() ?>
                        <?php if (count($subcategories) > 0): ?>
                            <ul id="leftnav-tree-<?php echo $category->getId() ?>" class="level1">
                                <?php foreach($subcategories as $subcategory): ?>
                                    <li class="level1<?php if ($this->isCategoryActive($subcategory)): ?> active<?php endif; ?>">
                                        <a href="<?php echo $helper->getCategoryUrl($subcategory) ?>"><?php echo $this->escapeHtml(trim($subcategory->getName(), '- ')) ?>
                                         <?php $secondLevelSubcategories = $subcategory->getChildren() ?>
                                         <?php if (count($secondLevelSubcategories ) > 0): ?>
                            <ul id="leftnav-tree-<?php echo $subcategory->getId() ?>" class="level2">
                                <?php foreach($secondLevelSubcategories as $secondLevelSubcategory ): ?>
                                    <li class="level2<?php if ($this->isCategoryActive($secondLevelSubcategory )): ?> active<?php endif; ?>">
                                        <a href="<?php echo $helper->getCategoryUrl($secondLevelSubcategory ) ?>"><?php echo $this->escapeHtml(trim($secondLevelSubcategory ->getName(), '- ')) ?>

                                    <?php endforeach; ?>

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

                        <?php endif; ?>
                    <?php //endif; ?>

            <?php endforeach; ?>

    <?php endif; ?>

I this code gives all categories including sub categories.

A: if you are extend this class class Mage_Catalog_Block_Navigation
then you can check with the function like below
if ($this->isCategoryActive($category)) {
            $classes[] = 'active';
            $activeClass = ' class="cur-act-cat"';
        }

or if not you can add below two function to your block to check if category is active or not
     /**
     * Check whether specified category is active
     *
     * @param Varien_Object $category
     * @return bool
     */
    public function isCategoryActive($category)
    {
        return $this->getCurrentCategory()
            ? in_array($category->getId(), $this->getCurrentCategory()->getPathIds()) : false;
    }

     /**
     * Check whether specified category is active
     *
     * @param Varien_Object $category
     * @return bool
     */
    public function isCategoryActive($category)
    {
        return $this->getCurrentCategory()
            ? in_array($category->getId(), $this->getCurrentCategory()->getPathIds()) : false;
    }

hope this will sure help you


text:
Q: Logging in via Facebook Messenger login connect flow isn't working correctly I want to utilize Facebook Messenger login connect flow in my web application - https://developers.facebook.com/docs/facebook-login/login-connect/
For that, I've created a test app and set up an initial page in the "messenger" section.
And I have, basically, this code (shown partially):
<script async='' defer='' crossorigin='anonymous' src='https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v10.0&appId=<skipped>&autoLogAppEvents=1' nonce='<skipped>' />

and
window.fbAsyncInit = function() {
  window.FB.init({
    appId: "<skipped>",
    autoLogAppEvents: true,
    xfbml: true,
    version: "v10.0"
  });

  window.FB.getLoginStatus(function(response) {
    // Called after the JS SDK has been initialized.
    console.log("Inside window.FB.getLoginStatus");
    statusChangeCallback(response); // Returns the login status.
  });
};

function loginUsingJSSDKLoginDialog() {
  console.log("Inside loginUsingJSSDKLoginDialog");
  window.FB.login(
    function(response) {
      if (response.status === "connected") {
        window.FB.api("/me", function(response) {
          console.log("Successful login for: " + response.name);
          var element = document.getElementById("status");
          document.getElementById("status").innerHTML =
            "Thanks for logging in, " + response.name + "!";
        });
      } else {
        document.getElementById("status").innerHTML = "You are not logged in!";
      }
    },
    {
      scope: "public_profile,email,user_messenger_contact",
      messenger_page_id: "<skipped>",
      reset_messenger_state: true
    }
  );
}

An issue is that the login dialog that'll pop up won't be the one of Messenger but the standard Facebook login one.
Why is that? How to fix it?
What I need is, as mentioned, "Facebook Messenger login connect flow"


text:
Q: Calculating t-test with apply (by row) returns data are essentially constant I'm trying to use the t-test with just two values:
1 and n.
This works:
a <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
     8.97, 8.97, 8.97, 8.97, 8.97, 8.97, 8.97, 8.97, 8.97, 8.97, 8.97, 8.97, 8.97, 8.97, 8.97)

or
a <- rep(c(1, 8.97), each = 15)

and:
t.test(x = a, mu = 2.33, alternative = "greater")

    One Sample t-test

data:  a
t = 3.5879, df = 29, p-value = 0.0006046
alternative hypothesis: true mean is greater than 2.33
95 percent confidence interval:
 3.727653      Inf
sample estimates:
mean of x
    4.985

Right, but:
variavel <- seq(from = 1, to = 9, by = .01)

df <- data.frame(fix1 = 1, fix2 = 1, fix3 = 1, fix4 = 1, fix5 = 1, fix6 = 1, fix7 = 1, fix8 = 1, fix9 = 1, fix10 = 1, fix11 = 1, fix12 = 1, fix13 = 1, fix14 = 1, fix15 = 1,
               ge1 = variavel, ge2 = variavel, ge3 = variavel, ge4 = variavel, ge5 = variavel, ge6 = variavel, ge7 = variavel, ge8 = variavel, ge9 = variavel, ge10 = variavel, ge11 = variavel, ge12 = variavel, ge13 = variavel, ge14 = variavel, ge15 = variavel
               )

When I go to calculate the test for each line and obtain the p-value,
apply(X = df, MARGIN = 1, FUN = function(x) {
  t.test(x = x, mu = 2.33, alternative = "greater")$p.value
})

it gives me the error:

Error in t.test.default(x = x, mu = 2.33) :
data are essentially constant

What happens?

A: Your first row is invariant, and since that's an error, the rest of the data is never tested.
table(unlist(df[1,]))
#  1
# 30

You have two options:

*

*Omit row 1 in your calculation:
head(apply(X = df[-1,], MARGIN = 1, FUN = function(x) {
  t.test(x = x, mu = 2.33, alternative = "greater")$p.value
}))
# 2 3 4 5 6 7
# 1 1 1 1 1 1

*Catch it inside the loop:
head(apply(X = df, MARGIN = 1, FUN = function(x) {
  tryCatch(t.test(x = x, mu = 2.33, alternative = "greater")$p.value,
           error = function(e) NA_real_)
}))
# [1] NA  1  1  1  1  1