text:
Q: Copying an extra columns rows across if there is a match but ignoring subsequent like matches I have 2 spreadsheets:
main.xlsxm

drs.xlsx

At the moment:

If column value E in drs.xlsx equals column value A in main.xlsx: Then
  on the matching row in main.xlsx Copy column value B in drs.xls to
  column value J in main.xlsx
If a second match is found (provided it is not the same as the first
  match): Where column value E in drs.xlsx equals column value A in
  main.xlsx Copy column value B in drs.xls to column value K in
  main.xlsx
If a third match is found (provided it is not the same as the first
  and second match): Where column value E in drs.xlsx equals column
  value A in main.xlsx Copy column value B in drs.xls to column value L
  in main.xlsx

This is handled by the following code:
Sub drs_Update()
    Dim wb As Workbook
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim user As Range

    Dim lastrowdrs As Long, lastrowMAIN As Long
    Dim rng As Range, res As Range
    Dim k As Byte
    Dim fAddr As String

    Application.ScreenUpdating = False

    ' Specify sheet name for Main wb
    Set sh1 = ThisWorkbook.Worksheets("Master")

    ' Open drs
    Set wb = Workbooks.Open("C:\Working\drs.xlsx")

    ' Specify sheet name for drs wb
    Set sh2 = wb.Worksheets("Sheet1")

    With sh1
        ' Find last row on column A in the Main wb
        lastrowMAIN = .Cells(.Rows.Count, "A").End(xlUp).Row
        ' Clear previous data in columns J:L
        '.Range("J1:L" & lastrowMAIN).ClearContents
    End With

    With sh2
        .AutoFilterMode = False
        ' Find last row on column A in drs wb
        lastrowdrs = .Cells(.Rows.Count, "A").End(xlUp).Row

        ' Apply filter
        With .Range("A1:D1")
            .AutoFilter Field:=1, Criteria1:=Array("TW", "W", "L", "V"), Operator:=xlFilterValues
            .AutoFilter Field:=3, Criteria1:="Microsoft Windows 7 Enterprise", Operator:=xlOr, Criteria2:="Microsoft Windows XP Professional"
            .AutoFilter Field:=3, Criteria1:="Windows 7", Operator:=xlOr, Criteria2:="Windows XP"
            .AutoFilter Field:=4, Criteria1:="Workstation-Windows"
        End With

        On Error Resume Next
        ' Get only visible rows in column E
        Set rng = .Range("E1:E" & lastrowdrs).SpecialCells(xlCellTypeVisible)
        On Error GoTo 0

        ' Loop through every user in Main wb
        For Each user In sh1.Range("A1:A" & lastrowMAIN)
            ' Counter for finding entries
            k = 0
            ' Find first match
            Set res = rng.Find(What:=user.Value, MatchCase:=False)
            If Not res Is Nothing Then
                ' Remember address of first match
                fAddr = res.Address
                Do
                    ' User.Offset(,9 + k) gives you column J for k=0, K for k=1, L for k=2
                    user.Offset(, 9 + k).Value = res.Offset(, -3).Value
                    ' Increment k
                    k = k + 1
                    ' Find next match
                    Set res = rng.FindNext(res)
                    ' If nothing found, exit, stop searching entries for current user
                    If res Is Nothing Then Exit Do
                ' If we already found 3 matches, then stop searching for current user
                Loop While fAddr <> res.Address And k < 3
                ' Update column headers
                sh1.Cells(1, 10).Value = "Hostname1"
                sh1.Cells(1, 11).Value = "Hostname2"
                sh1.Cells(1, 12).Value = "Hostname3"
            End If
        Next user
    End With
End Sub

Now if I wanted to also copy across whatever is in column A on drs.xlsx to column R on main.xlsm for every match found (ignoring any further matches, only the first host for a particular user) so that the column is not overwritten), how would I go about doing it?

A: Just add the code before the do loop, where you ' Remember address of first match.
user.Offset(0, 17).Value = res.Offset(0, -4).Value

A: Would it be as straight forward as adding the following after k = k +1:
If k = 1 Then
    user.Offset(,17).Value = res.Offset(, -4).Value
End If

If k = 1 then it is the first time it has found the match so copy over column A


text:
Q: CSS help - Can't place login form new slider I'm teaching myself CSS and I'm a bit stuck with my page layout. I'm trying to get my login form to be right of my slider, but nothing I do works. Here's what my layout looks like right now...

Here is my CSS for the form:
.login-body { background-color: #f1f2f7 }
.form-signin {
    max-width: 330px;
    //margin: 50px auto 50px;
    background: #fff;
    border-radius: 3px;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
}
.form-wrapper { //padding-bottom: 70px }
.login-bg {
   margin-top: -40px;
   margin-bottom: -50px;
   //background-color: #f1f2f7;
}

HTML:

                BUSINESS TOOLS

                FOR YOUR

                SUCCESS

                Data visualized

                to meet your needs!

                Read more

          RESPONSIVE VIDEO

          SUPPORT AND

          MANY MORE

          Lorem ipsum dolor amet

          tempor incididunt ut

          Read more

          USING BEST WEB

          SOLUTIONS WITH

          HTML5/CSS3

          Lorem ipsum dolor amet

          tempor incididunt ut

          veniam omnis

          Read more

            <form class="form-signin wow fadeInUp" action="index.html">

sign in now

                <input type="text" class="form-control" placeholder="User ID" autofocus>
                <input type="password" class="form-control" placeholder="Password">

                    <input type="checkbox" value="remember-me"> Remember me

                         Forgot Password?

                <button class="btn btn-lg btn-login btn-block" type="submit">Sign in</button>

or you can sign in via social network

                        Facebook

                        Twitter

                    Don't have an account yet?

                        Create an account

                              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Forgot Password ?

Enter your e-mail address below to reset your password.

                              <input type="text" name="email" placeholder="Email" autocomplete="off" class="form-control placeholder-no-fix">

                              <button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
                              <button class="btn btn-success" type="button">Submit</button>

          </form>

A: You could try to give the login form a position: relative tag and then move it to the top by giving it a negative top: property.
If the login form is displayed directly under the slider then you can give top the negative value of the height of the slider and it should work

A: Design your two parts in separate Div tag.
Give width in percentage and set float property to left

redpajama_set_name: RedPajamaStackExchange


text:
Q: integrated twillio verify service in my App we already created a Twilio service, but don't know how to integrated it into our APP application for user verify ?
where is the demo API ?

A: The documentation of the Verify service can be found here. As you already created a Verify service instance (Step 1), you need to add these two steps in your code:
Step 2: Send a Verification Token
client.verify.v2.services('VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
      .verificationChecks
      .create({to: '+15017122661', code: '123456'})
      .then(verification_check => console.log(verification_check.status));

Step 3: Check the Verification Token
client.verify.v2.services('VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
      .verificationChecks
      .create({to: '+15017122661', code: '123456'})
      .then(verification_check => console.log(verification_check.status));

PS: Other snippets are available on the site I linked above.


text:
Q: Yaw rate calculation from GPS Heading I have a dual GPS mounted on robot and getting data at 20Hz. I got heading data from GNTRA sentence which gives the heading from dual antenna. I am trying to get yaw rate of vehicle. I am having problem when I turn to left side of North. Normally, I am trying to get difference of two measurement and divide it with time interval. I am not good at trigonometry. For example, when I am driving to 5 degree of heading and making turn to left to 350 degree.I need to measure -15 degree/ time_interval. But I am measuring 345/time_interval with my code. I am making mistake and I could not figure out how to solve it. Can anybody help me? Thanks
        public double calc_yawrate(heading)
        {
         mywatch.Stop();
         double t = (double)mywatch.ElapsedMilliseconds / 1000;
         mywatch.Reset();
         mywatch.Start();

         Speed = Speed / 3.6;
         Speed = Math.Round(Speed, 2);
         double yaw = heading;
         double yawrate;
         yawrate = (yaw- yawpast) / t;
         yawpast = yaw;
        }

A: It seems like you want the difference in range [-180°, 180°], then you can add/minus the value by 360° until it's in range.
var diff = yaw - yawpast;

if(diff > 180)
{
    do
    {
        diff -= 360;
    }
    while(diff <= 180);
}
else if(diff < -180)
{
    do
    {
        diff += 360;
    }
    while(diff >= -180);
}

yawrate = diff / t;


text:
Q: How to validate formfield Am a newbie though. I followed a tutorial for my code below which is a register form. How can i validate each input field since it's just one widget which is reused for the entire input field.
............................................................................................................................................................
Code
import 'package:flutter/material.dart';
import 'package:flutterlogindesign/utils/color.dart';
import 'package:flutterlogindesign/widgets/btn_widget.dart';
import 'package:flutterlogindesign/widgets/herder_container.dart';

class RegPage extends StatefulWidget {
  @override
  _RegPageState createState() => _RegPageState();
}

class _RegPageState extends State<RegPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: EdgeInsets.only(bottom: 30),
        child: Column(
          children: <Widget>[
            HeaderContainer("Register"),
            Expanded(
              flex: 1,
              child: Container(
                margin: EdgeInsets.only(left: 20, right: 20, top: 30),
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    _textInput(hint: "Fullname", icon: Icons.person),
                    _textInput(hint: "Email", icon: Icons.email),
                    _textInput(hint: "Phone Number", icon: Icons.call),
                    _textInput(hint: "Password", icon: Icons.vpn_key),
                    Expanded(
                      child: Center(
                        child: ButtonWidget(
                          btnText: "REGISTER",
                          onClick: () {
                            Navigator.pop(context);
                          },
                        ),
                      ),
                    ),
                    RichText(
                      text: TextSpan(children: [
                        TextSpan(
                            text: "Already a member ? ",
                            style: TextStyle(color: Colors.black)),
                        TextSpan(
                            text: "Login",
                            style: TextStyle(color: orangeColors)),
                      ]),
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _textInput({controller, hint, icon}) {
    return SingleChildScrollView(
      child: Container(
        margin: EdgeInsets.only(top: 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(20)),
          color: Colors.white,
        ),
        padding: EdgeInsets.only(left: 10),
        child: TextFormField(
          controller: controller,
          decoration: InputDecoration(
            border: InputBorder.none,
            hintText: hint,
            prefixIcon: Icon(icon),
          ),
        ),
      ),
    );
  }
}

A: Use Form Widget like the following
  final _formKey = GlobalKey<FormState>();
  bool autoValidate = false;
   String  phone;

 child:Form( key: _formKey,
      autovalidateMode: autoValidate ? AutovalidateMode.always : AutovalidateMode.disabled,
                   child: Column(
                           children: [
                                   AppTextFormField(
                                        initialValue: phone,
                                        onChanged: (value) {
                                          phone = value;
                                        },
                                        validator: (value) {
                                          if (value.isEmpty) {
                                            return 'Enter Phone number';
                                          }
                                        },

                                      ),
                                      PrimaryButton(
                                        text: 'Go',
                                        onTap: () {
                                          if (_formKey.currentState.validate()) {
                                            _formKey.currentState.save();

                                          } else {
                                            autoValidate = true;
                                          }
                                        },
                                      ),
                                    ],
                                  ),
                              ),


text:
Q: Recursive neural network implementation in TensorFlow Is there any available recursive neural network implementation in TensorFlow TensorFlow's tutorials do not present any recursive neural networks. Most TensorFlow code I've found is CNN, LSTM, GRU, vanilla recurrent neural networks or MLP. I am most interested in implementations for natural language processing.
Example of a recursive neural network:

The tree structure may vary between different inputs. I.e., I do not want the tree structure to be fixed.

A: Take a look at Tensorflow Fold:
https://github.com/tensorflow/fold
TensorFlow Fold is a library for creating TensorFlow models that consume structured data, where the structure of the computation graph depends on the structure of the input data.

A: These types of architectures are awkward in Tensorflow. I think someone did implement them though. http://www.kdnuggets.com/2016/06/recursive-neural-networks-tensorflow.html
You might prefer to use DyNet, which was designed to allow for dynamically changing architectures. https://github.com/clab/dynet

A: I hope this is what you need:
https://github.com/sapruash/RecursiveNN:

Tensorflow implementation of Recursive Neural Networks using LSTM units as described in "Improved Semantic Representations From Tree-Structured Long Short-Term Memory Networks" by Kai Sheng Tai, Richard Socher, and Christopher D. Manning.


text:
Q: passport-jwt, not throing error, but not authenticating. wont even console.log I am trying to authenticate using passport-jwt, express etc.
I currently am not getting authenticated, but most troubling is that I cant seem to console.log inside the function... nothing happens.
Here is the full passport.js
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/database');

module.exports = function(passport) {
    let opts = {};
    opts.jwtFromRequest = ExtractJwt.fromHeader();
    opts.secretOrKey = config.secret;

    console.log(opts); // THIS SHOW PRIORE TO THE EXPRESS LISTEN MSG!

    passport.use(new JwtStrategy(opts, (jwt_payload, done) => {

        console.log(jwt_payload); // THIS DOESNT EVER SHOW!

        User.getUserById(jwt_payload._id, (err, user) => {
            if (err) {
                return done(err, false);
            }
            if (user) {
                return done(null, user);
            } else {
                return done(null, false);
                // or create a new account
            }
        });
    }));
}

the users.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');

const config = require('../config/database');
const User = require('../models/user');

...code removed for brevity...

router.get('/profile', passport.authenticate('jwt', {session:false}), (req,res,next) => {
    res.json({user: req.user});
});

module.exports = router;

Any ideas on how I can 'see' my payload so I can find whats going on?
Im using postman to hit 'http://localhost:3000/users/profile'
passing headers "authentication" and the token "JWT my-token..."
THx - I realize this is a bit of an odd request...The tutorial I was following, indicates I should be able to see the payload, even if i am not authenticated...
So Im kinda stuck with no idea where to turn.

A: UGH - this is the second time I've continued to plug away at something after I asked, only to hit upon a solution. apperantly the version Im am using is newer than the examples and ExtractJwt.fromHeader() should be .fromAuthHeaderWithScheme("jwt"). It is frustrating that it did not error, and did not progress enough to log, however - NOW I get my console log, and can see my payload... I hope this helps someone else. (I am frustrated with the pace and changes made to js libs, that destroy backwards compatibility, and do not clearly document a path, I understand kinda why it happens, but it makes learning and troubleshooting very frustrating)


text:
Q: Dual Booting Problems Windows 8.1/Ubuntu 14.04 Separate Hard Drives I have Windows 8.1 on one hard drive and Ubuntu 14.04 on a second hard drive (installed in a HP Desktop).  My problem is that being a newbie I can not get Ubuntu to boot.  I tried a few things (i.e. EasyBCD) and none have worked.  Where or what have I done wrong?

A: In my opinion you need to change booting order, as your systems are installed in separate drives. On most computers when computer starts you can pop-up the boot menu, usually by pressing F12 of F10 key (message regarding the proper key is usually shown for a short time in the right bottom corner of the screen). Then choose the drive on which the Ubuntu is installed. If that works, and you would like to have such order always, you need to change the boot order in your BIOS settings.


text:
Q: Clarification on Dynamic Xpath for SVG icon I am trying to get the xpath and click that particular xpath, but xpath keeps on varying(dynamic) like below
//*[@id="slipstream_action_bar_widget599"]/dl/dd[2]/span/span/svg
//*[@id="slipstream_action_bar_widget414"]/dl/dd[2]/span/span/svg

I need your help to get the xpath on the fly and pass that

A: Please try xpath as copied below:
//*[contains(@id,"slipstream_action_bar_widget")]/dl/dd[2]/span/span/svg


text:
Q: Spring Security OAuth2 client: access the expires_in value I'm using the current release of Spring Security as an OAuth2 client.
It is working fine. But how do I get the value of the expires_in the authentication server sent back along with the Access and Refresh tokens, etc?
Or does Spring Security convert the expires_in to a timestamp with a timeLeft method or similar?


text:
Q: How to enable experimentalForceLongPolling in @angular/fire There is an issue with Cypress and Firebase, based on some research I've done here it seems that Cypress intercepts all network requests and due to the nature of how firebase works it emits multiple values on the same request (It should be noted this only happens when using the emulators) Cypress code is not setup to handle this so it only emits the first value.
It seems that the accepted solution is to enable 'experimentalForceLongPolling' in the firebase settings, however I am unsure of how to do this in @angular/fire it says this has already been called with different settings.
I've tried placing it as a parameter to the initializeApp method that is returned in the provideFirebaseApp callback however nothing happens.
@angular/fire provides a method called 'initalizeFirestore' this takes an instance of the app and a parameter, which is an object that seems to allow you to set 'experimentalForceLongPolling' however when used it throws an error saying that 'initialize app has been called with different settings' makes sense as in the root module we provided firebase and Firestore. However you cannot call this method without an instance of the app so its a catch 22, you can't initialize the app because you need the injected database, and you can't call the method because initialize app has already been called.
How can I enable this setting through the library?
Thanks.

A: I think this will resolve your issue as it has resolved mine.
Add this into you app.module.ts file where you are configuring firebase and local emulator stuff.
providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    {
      provide: USE_FIRESTORE_SETTINGS,
      useValue: { experimentalForceLongPolling: true },
    },
    {
      provide: USE_AUTH_EMULATOR,
      useValue: environment.useEmulators
        ? ['http://localhost:9099']
        : undefined,
    },

A: There is a exemple of my current configuration with type provider ( autocomplete  )
(You have also the experimentalAutoDetectLongPolling option)
⚠ SETTINGS_FIRESTORE is an alias of SETTINGS import
import { SETTINGS as SETTINGS_FIRESTORE } from '@angular/fire/firestore';
import firebase from 'firebase/app'

@NgModule({
    declarations: [],
    imports: [
        // ....
        AngularFireModule.initializeApp(environment.firebase),
        // ....
    ],
    exports: [],
    providers: [
        {
            provide: SETTINGS_FIRESTORE,
            useValue: {
                experimentalforcelongpolling: true,
            } as firebase.firestore.Settings,
        },
    ],
})
export class AppModule {}

Working with AngularFire 6.1.5 and Angular 12


text:
Q: Torsocks not connecting For some reason I can't connect with torsocks via command line.
Every time I try to run something (irssi, mcabber, apt-get, whatever) it simply does not connect. I used to run terminal with tor in the past and never had a problem so far.
I run Debian 7, and this is my torsocks conf (I only paste the uncommented parts):
local = 127.0.0.0/255.128.0.0
local = 127.128.0.0/255.192.0.0
local = 169.254.0.0/255.255.0.0
local = 172.16.0.0/255.240.0.0
local = 192.168.0.0/255.255.0.0

server = 127.0.0.1

server_port = 9050

Thank you!


text:
Q: PHP PDO related: Update SQL statement not updating the content of the database  I am trying to implement an update statement using a prepared statement in a PHP script, but it appears that it is not updating the record in the database and I am not sure why and so would appreciate if you can share some insights.
Code
$query = "UPDATE DatTable SET DF_PARTY_ID = :party_id,
          DF_PARTY_CODE = :party_code,
          DF_CONNECTION_ID = :connection_id WHERE DF_PARTY_ID = ':party_id'";
$stmt = $this->connection->prepare($query);
$stmt->bindValue(':party_id', $data[0], PDO::PARAM_INT);
$stmt->bindValue(':party_code', $data[1], PDO::PARAM_INT);
$stmt->bindValue(':connection_id', $data[2], PDO::PARAM_INT);
$stmt->execute();

Inspiring solution leading to this approach. How can I fix this problem?

A: Make sure that the party_id you are trying to update exists in the database.
Also, if your table is InnoDB, make sure that you have autocommit on or issue an explicit commit after the update is made.

A: Instead of guessing, basic error handling must be implemented:
$arr = $stmt->errorInfo();
print_r($arr);

A: Might not help, but why are you only binding 3 variables, when there are 4?  I can't say that I have experience doing this in PHP, but in Perl and Oracle it would throw an error.  I'd try binding the 2 SETs and the 1 WHERE, and removing the first assignment, and see if that works.

A: I'm not sure if you want to do what you're trying to do.
Your UPDATE statement basically says update the key and two values based on the NEW value, since party_id is in the SET and WHERE clauses.
You may want to change your prepared statement to this:
UPDATE DatTable SET DF_PARTY_ID = :party_id,
DF_PARTY_CODE = :party_code,
DF_CONNECTION_ID = :connection_id
WHERE DF_PARTY_ID = ':old_party_id'
bind your NEW party_id value to :party_id and the CURRENT one to :old_party_id


text:
Q: How do I get rid of the need for the "/app.php/" in a new Symfony2 app's production URL? I've done a 1st install of Symfony2,
    php app/console --version
        Symfony version 2.0.11 - app/dev/debug

I installed it under an existing DocumentRoot by configuring my apache2 server vhost
    <VirtualHost 127.0.0.1:80>
        ...
        DocumentRoot /srv/www/localhost_www
        ...
        <Directory "/srv/www/localhost_www" >
            AllowOverride none
            Options -ExecCGI +FollowSymLinks +Includes +Indexes +MultiViews
            Order Allow,Deny
            Allow from All
        </Directory>
        ...
        Alias /TESTAPP  "/srv/www/TESTAPP/web/"
        <Directory "/srv/www/TESTAPP/web/">
            Options All
            AllowOverride All
            Allow from All
        </Directory>

        Alias /TESTAPP.symfony  "/srv/www/TESTAPP/"
        <Directory "/srv/www/TESTAPP/">
            Options All
            AllowOverride All
            Allow from All
        </Directory>
        ...

After an OK install, and successfully following "The Book" to build the demo "Hello" app, if I nav in a browser to any/all of,
  dev:
        http://localhost/TESTAPP.symfony/web/app_dev.php/hello/ME
        http://localhost/TESTAPP/app_dev.php/hello/ME
  prod:
        http://localhost/TESTAPP.symfony/web/app.php/hello/ME
        http://localhost/TESTAPP/app.php/hello/ME

I see the expected,
"Hello ME!"
I want to rewrite only the production URLs, hiding "app.php" so that the following set of URLs work in the nav bar of a browser for my Symfony2 app:
  dev:
        http://localhost/TESTAPP.symfony/web/app_dev.php/hello/ME
        http://localhost/TESTAPP/app_dev.php/hello/ME
  prod:
     !! http://localhost/TESTAPP.symfony/web/hello/ME
     !! http://localhost/TESTAPP/hello/ME

Iiuc, the default web/.htaccess
        cat web/.htaccess
                <IfModule mod_rewrite.c>
                    RewriteEngine On
                    RewriteCond %{REQUEST_FILENAME} !-f
                    RewriteRule ^(.*)$ app.php [QSA,L]
                </IfModule>

needs to change.
I've dug around in the docs and on the web, tried vdiffferent recommendations for modding the RewriteRule, adding 'RedirectMatch permanent', etc., and I'm not managing to get a simple
http://localhost/TESTAPP/hello/ME
to ever work.  I always seem to need to add the "/app.php/".
What are the specific changes I'd need to make in order to get this to work?
Thanks.

@chasen

is mod_rewrite enabled for apache?

yes

if you have your .htaccess file in your web directory

i do

and you host file pointing to the web folder the

it is, as above,
    Alias /TESTAPP  "/srv/www/TESTAPP/web/"
        <Directory "/srv/www/TESTAPP/web/">

app.php should not be needed.

that's my problem.  without it, it's not working for me.
Specifically,
    https://localhost/TESTAPP/app.php/hello/ME

returns:
"Hello Me!"
but
    https://localhost/TESTAPP/hello/ME

returns
Object not found!

The requested URL was not found on this server.
If you entered the URL manually please check your
spelling and try again.

If you think this is a server error, please contact
the webmaster.
Error 404

A: In my case I need to modify the line containing AllowOverride None to read AllowOverride All. This tells Apache that it's okay to allow .htaccess files to over-ride previous directives. You must reload Apache before this change will have an effect (https://help.ubuntu.com/community/EnablingUseOfApacheHtaccessFiles):
Do this: - go to "/etc/apache2" modify file "apache2.conf" section:
<Directory /var/www/>
    Options FollowSymLinks
    AllowOverride All
    Require all granted

*

*restart server: /etc/apache2# service apache2 restart

it should work. If it does not work, still you have done 1 step right to insure .htaccess is allowed to override. There are many other reasons can be fixed with the above instruction.

A: i know that its a silly question but is mod_rewrite enabled for apache?
if you have your .htaccess file in your web directory and you host file pointing to the web folder the app.php should not be needed.
if you are running ubuntu or a similar distro you can do:
sudo a2enmod rewrite
sudo service apache2 reload
sudo service apache2 restart

That should enable the mod, and reload apache.
EDIT:
That response you are getting back is it in a symfony page?  if it is its likely that your prod cache needs to be cleared, from the root directory for the application use the symfony console to clear the cache:
php app/console cache:clear --env="prod"

EDIT:
If neither of those have worked you may try adding a RewriteBase to the htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /TESTAPP
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app.php [QSA,L]
</IfModule>

A: Adding the RewriteBase rule with the name of the folder in which the project is held to the .htaccess file does it's job! Thanks!
RewriteBase /project_name


text:
Q: Best way for downloading many files in a website I'm designing a website that will let the user synchronize a local folder to an online folder (Kinda like dropbox).
I'm trying to find a way to avoid developing a local tool to do the download and synchronization. And do it somehow online.
Is it possible to download multiple files in a certain directory tree?
Can a website have free write access to local directories?
A zip file is not an option, since the file batch could get pretty big.
EDIT: Synchronization shouldn't occur periodically. Just when the user logs in the website.

A: My recommendation is to use something like WebDAV then see here


text:
Q: Jquery (Datatables) features not fully initializing? php/mysql I am attempting to apply Jquery's Datatables to display my database. In the example featured in this link, the table is searchable, can be ordered, and has nice color seperation.
http://www.datatables.net/examples/basic_init/zero_configuration.html
My current code displays the data, but with no sorting functionality, no search option, just the raw data, bold titles, and bars separating the rows (no alternating colors as in the example.) Pic with junk data:
It seems it is applying some of the css but not all? I'm lost on why the functionality and remaining style is missing. I went back and put in html structure from my last code with the same results and no errors thrown.
Code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT Sid, Fname, Lname, Email, Dtype, Mac, Date FROM StudentDeviceReg";
$result = $conn->query($sql);
?>
<!Doctype html>

        <title>DataTables</title>
        <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<?php

if ($result->num_rows > 0) {
    echo "

        ID
        First Name
        Last Name
        Email
        Device
        Mac Address
        Date

";
?>

<?php

    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "

        ".$row["Sid"]."
        ".$row["Fname"]."
        ".$row["Lname"]."
        ".$row["Email"]."
        ".$row["Dtype"]."
        ".$row["Mac"]."
        ".$row["Date"]."

";
    }
    echo "
";

} else {
    echo "0 results";
}
$conn->close();
?>

A: Your table tree is not structured properly.

<?php

 if ($result->num_rows > 0) {
   echo "

        ID
        First Name
        Last Name
        Email
        Device
        Mac Address
        Date

";

    while($row = $result->fetch_assoc()) {
     echo "

        ".$row["Sid"]."
        ".$row["Fname"]."
        ".$row["Lname"]."
        ".$row["Email"]."
        ".$row["Dtype"]."
        ".$row["Mac"]."
        ".$row["Date"]."

";
    }
    echo "

";
 }

?>


text:
Q: Is there an easy way to see that ${1\over5} + \frac{1}{6} + \frac{1}{7} + \frac{1}{8} + \frac{1}{9} + \frac{1}{10} + \frac{1}{11} + \frac{1}{12} > 1$? The sum $$\frac{1}{5} + \frac{1}{6} + \frac{1}{7} + \frac{1}{8} + \frac{1}{9} + \frac{1}{10} + \frac{1}{11} + \frac{1}{12}$$ is just a bit larger than $1$.  Is there some clever way to show this other than to add the fractions together by brute-force?  For example, is there some way to group terms together and say something like "These terms sum to more than $\frac{1}{3}$, these terms sum to more than $\frac{1}{2}$, and these terms sum to larger than $\frac{1}{6}$, so the whole thing sums to more than $1$"?

A: $\dfrac{1}{5}+\dfrac{1}{10}=\dfrac{3}{10}=\dfrac{6}{20}$
$\dfrac{1}{6}+\dfrac{1}{12}=\dfrac{3}{12}=\dfrac{5}{20}$
$\dfrac{1}{7}+\dfrac{1}{8}>\dfrac{2}{8}=\dfrac{5}{20}$
$\dfrac{1}{9}+\dfrac{1}{11}=\dfrac{20}{99}>\dfrac{4}{20}$

A: By C-S we obtain:
$$\frac{1}{5} + \frac{1}{6} + \frac{1}{7} + \frac{1}{8} + \frac{1}{9} + \frac{1}{10} + \frac{1}{11} + \frac{1}{12}=$$
$$=\frac{17}{60}+\frac{17}{66}+\frac{17}{70}+\frac{17}{72}\geq\frac{17\cdot4^2}{60+66+70+72}=\frac{68}{67}>1.$$

A: For positive, unequal $a$ and $b$:
$\dfrac1a+\dfrac1b=\dfrac{a+b}{ab}>\dfrac4{a+b}$
because $(a+b)^2>4ab$ (the difference between these is $(a-b)^2$).  So,
$\dfrac15+\dfrac17>\dfrac4{12}=\dfrac13$
$\dfrac19+\dfrac1{11}>\dfrac4{20}=\dfrac1{5}$
$\dfrac18+\dfrac1{12}>\dfrac4{20}=\dfrac1{5}$
When these inequalities are put into the given sum the claimed bound follows.

A: Since $y=\frac{1}{x}$ is convex we have:-
$\dfrac15+\dfrac16+\dfrac17>\dfrac36=\dfrac12$
$\dfrac18+\dfrac19+\dfrac1{10}+\dfrac1{11}+\dfrac1{12}>\dfrac5{10}=\dfrac12$


text:
Q: Getting slot from an S4 object I would like to get all p.values that are under the 5% level.
I tried to use the tseries package to implement the kpss test.
> dput(datSel)
structure(list(oenb_dependent = c(142.8163942, 143.5711365, 145.3485827,
142.0577145, 139.4326176, 140.1236581, 138.6560282, 136.405036,
133.9337229, 133.8785538, 132.0608441, 130.0866307, 120.1320237,
119.6368882, 114.3312943, 117.5084111, 114.4960017, 112.9124518,
112.8185478, 112.3047916, 106.632639, 106.2107158, 106.8455028,
106.3879556, 104.3451786, 102.9085952, 101.0967783, 101.7858278,
101.0749044, 102.6441976, 102.0666152, 100, 97.14084104, 97.49972913,
96.91453836, 96.05132443, 94.98057971, 92.78373451, 92.67526281,
91.82430571, 91.4153859, 89.51740671, 89.01587176, 84.62259911,
91.48598494, 89.12053042, 90.02364352, 90.92496121, 89.42963565,
91.93886583, 88.83918306, 90.39513509, 87.54571761, 91.3386451,
87.7836994, 91.79178376, 87.56903138, 87.77875755, 89.29938784,
90.88084014), gdp = c(17703.7, 17599.8, 17328.2, 17044, 17078.3,
16872.3, 16619.2, 16502.4, 16332.5, 16268.9, 16094.7, 15956.5,
15785.3, 15587.1, 15460.9, 15238.4, 15230.2, 15057.7, 14888.6,
14681.1, 14566.5, 14384.1, 14340.4, 14383.9, 14549.9, 14843,
14813, 14668.4, 14685.3, 14569.7, 14422.3, 14233.2, 14066.4,
13908.5, 13799.8, 13648.9, 13381.6, 13205.4, 12974.1, 12813.7,
12562.2, 12367.7, 12181.4, 11988.4, 11816.8, 11625.1, 11370.7,
11230.1, 11103.8, 11037.1, 10934.8, 10834.4, 10701.3, 10639.5,
10638.4, 10508.1, 10472.3, 10357.4, 10278.3, 10031), employ = c(71.0619,
70.9383, 71.162, 71.138, 71.2286, 71.5095, 71.565, 71.3246, 71.4963,
71.3738, 71.4276, 71.3065, 71.0246, 71.3244, 71.0619, 70.9811,
71.2149, 70.8342, 70.5568, 70.5444, 70.3286, 70.179, 70.2555,
70.5103, 70.8038, 70.6748, 70.9769, 70.6988, 70.2125, 70.1661,
69.6284, 69.5613, 68.9837, 68.8606, 68.4223, 67.963, 67.6293,
67.5905, 67.1857, 67.1248, 66.7075, 66.5857, 66.4303, 66.2826,
68.7514, 68.8897, 69.0824, 68.9718, 68.7927, 68.6387, 68.8053,
68.7286, 68.4141, 68.2357, 68.4785, 68.4171, 68.4782, 68.3978,
68.5344, 68.4772)), .Names = c("oenb_dependent", "gdp", "employ"
), row.names = c(NA, -60L), class = "data.frame")
> resKpss <- lapply(datSel,function(x){ kpss.test(x,"Trend") })
> cv.kpss <- sapply(resKpss, function(x){ x@p.value < 0.05 } )
Error in FUN(X[[1L]], ...) :
  trying to get slot "p.value" from an object (class "htest") that is not an S4 object

However, I cannot access the p.value object. I tried str(resKpss[1]) and got:
List of 1
 $ variName1:List of 5
  ..$ statistic: Named num 0.693
  .. ..- attr(*, "names")= chr "KPSS Trend"
  ..$ parameter: Named num 1
  .. ..- attr(*, "names")= chr "Truncation lag parameter"
  ..$ p.value  : num 0.01
  ..$ method   : chr "KPSS Test for Trend Stationarity"
  ..$ data.name: chr "x"
  ..- attr(*, "class")= chr "htest"

I also tried the $ operator, but I get an error that this is an S4 method.
Any suggestions what I am doing wrong?

A: There's no S4 object here to get a slot from.
resKpss is a ordinary R list because its the output from lapply. To get an element of a list you use double-square brackets: resKpss[[1]] and resKpss[[2]] for example.
Each of those is then a list. To get a component of a list by name you use dollar signs - the at-sign is used to get parts of an S4 class. So:
resKpss[[1]]$p.value
[1] 0.01

Your sapply just needs a dollar sign instead of an at-sign:
> sapply(resKpss, function(x){ x$p.value < 0.05 } )
oenb_dependent            gdp         employ
          TRUE           TRUE           TRUE


text:
Q: execute query according to condition PreparedStatement pstmt = null;
    ResultSet rs = null;

    List<SelectItemsDTO> listItem = new ArrayList<SelectItemsDTO>();
    try {
        StringBuilder query =new StringBuilder();

        query = query.append(SLCMQueryConstant.GET_CollegeChid_LIST);

        pstmt = conn.prepareStatement(query.toString());
        pstmt.setInt(1,commonDto.getOrgID());
        rs = pstmt.executeQuery();
        int pid= 0;
        while (rs.next()) {
        pid= rs.getInt("organization_parent_id");
        }

        if(pid!= 0)
        {
            query = query.append(SLCMQueryConstant.GET_CollegeSub_LIST.toString());

            pstmt = conn.prepareStatement(query.toString());

        }
        else
        {

            query = query.append(SLCMQueryConstant.GET_College_LIST.toString());
            pstmt = conn.prepareStatement(query.toString());

        }

       pstmt.setInt(1,commonDto.getOrgID());
        rs = pstmt.executeQuery();
        while (rs.next()) {
            SelectItemsDTO itemTo = new SelectItemsDTO();

            itemTo.setItemCode(rs.getString("Organization_Name"));
            itemTo.setItemIds(rs.getInt("Organization_ID"));

            listItem.add(itemTo);

        }
    }
public static final String GET_College_LIST= " SELECT Organization_Name,Organization_ID FROM m_organization_master WHERE organization_parent_id = ? ";
public static final String GET_CollegeSub_LIST = " SELECT  Organization_Name,Organization_ID FROM m_organization_master WHERE Organization_ID = ? ";

I want to execute query according to if condition .I am getting PID value from database and then used as if condition .This code seems an error no value specified for parameter 1 I have already initialized parameter for passing the values.


text:
Q: Use Margin Auto and Center to center Float Left Div I know this question had been asked many times.
Align a div to center
However, I follow their suggestion :

    Menu Item 1
    Menu Item 2
    Menu Item 3

(source: google.com)
By using "Center" and "Margin Auto", "Text Align Center" ... I still unable to center the menu item.

A: Why not use an unordered list? After all, you are creating a list of links.

Menu Item 1

Menu Item 2

Menu Item 3

li {
  display: inline;
}

ul {
  width: 50%;
  margin: 0 auto;
}

A: Your code works fine, but the div is 100% wide by default so you won't notice any centering.
Either give the div a width (fixed in pixels or relative in percent) or, if you just want to center the menu items, give the div a text-align setting:

A: use inline-block instead of float left.

    Menu Item 1
    Menu Item 2
    Menu Item 3

A: Work for me (not used float, only text-align):
      http://jsfiddle.net/vnAvk/20/

A div Hello

        B Div hello
        C Div Hello
        D div Hello
        E div Hello

div.a { border: 1px solid red;}
p.center { text-align: center; }

a.b { border: 2px solid blue; }
a.c { border: 2px solid green; }
a.d { border: 2px solid black; }
a.e { border: 2px solid yellow; }


text:
Q: How to randomly select an element in a 2D numpy array in the same row or column of specified element using vectorization? I have a 2D NumPy array (say arr1) containing values 0 or 1 as float values. Let size of arr1 be h x w. I have another NumPy array (say arr2) of size n x 2, where each row specifies a location (row and column index) in arr1. For every arr1 location (say (x1, y1) ) specified by each row of arr2, I need to select another location (say (x2, y2)) in arr1 which is in the same row or column as (x1, y1), such that there is atleast one cell between (x1, y1) and (x2, y2), including these two cells, whose value in arr1 is 1.
How can I achieve this efficiently in time? Typical values of h,w,n are 800,800,500000 respectively. So, I would like to achieve this without any for loops.
Example:
import numpy

h=4
w=4
n=3
arr1 = numpy.array([
        [0, 1, 0, 0],
        [1, 0, 1, 0],
        [0, 1, 0, 0],
        [0, 0, 1, 0],
      ])
arr2 = numpy.array([
        [1, 1],
        [2, 2],
        [0, 2],
      ])

Expected solution:
First row of arr2 is (1,1). Valid solutions in 2nd column as (0,1), (2,1), (3,1) and valid solutions in 2nd row are (1,0), (1,2), (1,3). So the code should randomly pick one of these.
Similar for second row of arr2 which is (2,2), valid solutions are (0,2), (1,2), (3,2), (2,0), (2,1), (2,3).
For third row of arr2 which is (0,2), valid solutions are (0,0),(0,1),(1,2),(2,2),(3,2). Note that (0,3) is not a valid solution since there is no cell containing 1 between (0,2) and (0,3).
Note that if a row in arr2 is (0,3), there is no cell in that column with the value 1. Such cases are extremely rare and in such cases, it suffices to pick a location that is sufficiently far away in that column. It is not necessary to detect such cases and pick a location in the same row.
PS: I have a solution by iterating over each row of arr2, but that takes over 1 minute. I am looking for a vectorized solution

A: I tried writing a solution to this using vectorization, but it still need to uses masked reduce operations which makes things way slower than normal broadcasting
The basic idea behind what i did is to rotate every row by the col index in arr2 and find the min/max index of a non 0 element. Than you select a random number between this 2 (all possible rotated solutions) and rotate it back to get the actual solution for that row.
You than do the same on the transposed arr1 and arr2 to get the the solution by columns and than you randomly select if you want the row or colum solution.
Still this take ~26s to execute
PS: If no solution is possible for the initial point (both row and col are all zeros), a -1 will appear in those coordinates
import time
import numpy as np

def get_same_row_random(arr, pos, shift):
    width = arr.shape[1]
    app1 = -np.ones_like(arr, dtype=np.int64)
    app2 = np.zeros_like(arr, dtype=np.bool8)
    w1 = np.where(arr == 1)
    app1[w1] = w1[1]
    app2[w1] = True

    res = app1[pos]
    mask = app2[pos]

    mask[np.arange(shift.size), shift] = False # Can't select original coordinates
    res = (res - shift.reshape(-1,1)) % width
    res_min = np.min(res, initial=width, where=mask, axis=1)
    res_max = np.max(res, initial=-1, where=mask, axis=1)

    w = (res_min == width)
    res_min[w] = -1
    res_max += 1

    res = (np.random.randint(res_min, res_max) + shift) % width
    res[w] = -1

    return res

h, w, n = 800,800, 500000
arr1 = np.random.randint(2, size=(h,w))
arr2_1 = np.random.randint(h, size=n)
arr2_2 = np.random.randint(w, size=n)
arr2 = np.vstack((arr2_1, arr2_2)).T

start = time.time()

row_indexes = get_same_row_random(arr1, arr2[:,0], arr2[:,1])
col_indexes = get_same_row_random(arr1.T, arr2[:,1], arr2[:,0])

r_or_c = np.random.randint(2, size=n)
exc_row = np.where(row_indexes == -1)[0]
exc_col = np.where(col_indexes == -1)[0]
r_or_c[exc_row] = 1
r_or_c[exc_col] = 0

wr = np.where(r_or_c == 0)[0]
wc = np.where(r_or_c == 1)[0]
res = np.array(arr2)
res[wr,1] = row_indexes[wr]
res[wc,0] = col_indexes[wc]

end = time.time()


text:
Q: Como usar arquivos PHP com página de erro customizada no Web.config Tenho um arquivo chamado error.php, ele pega o valor GET ou uma variável já definida e exibi os erros em vários idiomas e de todos os tipos.
Eu utilizo o IIS e já tentei no Web.config usar páginas PHP, mas não obtive sucesso, consigo apenas com páginas HTML que não é o meu propósito.
Como posso usar o arquivo erro.php como página de erro no Web.config?
Web.config atual:
    <?xml version="1.0" encoding="UTF-8">
    <configuration>
       <system.webServer>
            <httpErrors errorMode="Custom">
                <remove statusCode="401" />
                <error statusCode="401" path="sys\error\401.html responseMode="File" />
                .....
            </httpErrors>
        </system.webServer>
    </configuration>

E eu tentei utilizar da seguinte maneira, mas não funcionou:
 <error statusCode="401" path="sys\error.php?number=401" responseMode="File" />

A: Creio que responseMode="File" mandar a resposta como se o arquivo fosse um arquivo estático, se você quer "executar ele", não deve usar \ invertida neste caso e o caminho deve começar do "root" / (com barra na frente) assim:
<error statusCode="401" path="/sys/error.php?number=401" responseMode="ExecuteURL" />

Testado no IIS8 Express, acredito que não mude no IIS padrão e nem na versão 7.

Nota:
Acredito que os códigos de status não possam ser customizados: 400, 403.9, 411, 414, 500, 500.11, 500.14, 500.15, 501, 503 e 505.
https://technet.microsoft.com/en-us/library/cc753103%28v=ws.10%29.aspx?f=255&MSPPError=-2147217396

Se não der certo tente apenas:
<error statusCode="401" path="/sys/error.php" responseMode="ExecuteURL" />

E ao invés de usar _GET use a função http_response_code() (requer php5.4+) faça isto no seu error.php:
<?php
echo http_response_code();