Q:

Using Apache POI HSSFListener how to identify date type

Due to millions of records to handle, I have to handle SAX parsing using the technique given here.  http://poi.apache.org/spreadsheet/how-to.html#event_api.  However Date type is convered to Number.  How to distinguish between Date and Number when using HSSFListener?

A:

The Excel file formats store all dates as numbers with special formatting rules. It's not that HSSF is converting it, you're getting exactly what Excel stores in the file!
If you want good examples of HSSF Event processing for .xls files, I would suggest you take a look at XLS2CSVmra from Apache POI and ExcelExtractor from Apache Tika
Both show a number of common things you'll want to do, including detecting Date cells and formatting them appropriately for display


Q:

get method not working on Parse current User

I am making an express app with Parse. In my cloud code, I am trying to get an attribute of the current user, but it is returning me undefined. My code looks like following:
app.get('/home/subscriptions',function(req,res){

    Parse.Cloud.useMasterKey();
    var user = Parse.User.current();

    var ifstud = user.get("isStudent");

    console.log('student: ' + ifstud); // undefined
    console.log('id: ' + user.id); // OK. works fine.
    }

I am able to retrieve the id of the user as above but not able to call the get method on user. In their API reference, they have mentioned that Parse.User.current() returns a Parse.Object, so I think in user I have _User object and I should be able to call all methods supported by a Parse.Object.
What might be the issue here?
Thanks

A:

I figured it out and putting this answer for future reference to users who visit this question.
The Parse.User.current() returns only a pointer to the user and not the complete user object. To get access to all fields of the user, fetch the entire object using the fetch method.
var fullUser;
Parse.User.current.fetch().then(user){
fullUser = user;
}).then(function(){
// Place your code here
});


Q:

SQL Server Profiler missing after installation

Does anyone know if there is some type of bug in the installation of SQL Server 2008 R2? It seems if you have Express edition installed, then upgrade to anything (developer, enterprise, etc.)  the SQL Server tools that don't come with Express will never show up because the Express edition is installed on your computer. *Even though you just paid for Enterprise edition
This has happened to me on 3 different computers. I have to copy the binn folder from a computer that actually works. Just today I decided to try to uninstall the Express edition before upgrading - instead of letting Microsoft handling the upgrade and it worked. I'm thinking maybe this is a bug...

A:

When you upgrade from Express version, need to install Management Tools - Complete -

A:

I know this question is old and answered, but I was having the same problem. I wanted to upgrade from Express to Developer and none of these answers helped me.
What I´ve done to be able to add features is:

Open the SQL Server Installation Center.
Click on Maintenance > Edition Upgrade and follow the steps.
Click on Installation > New installation or add features to an existing installation and follow the steps.

There you can add all the new features from your new version of SQL Server. Hope that helped..

A:

(Instructions for 2008 R2)
If you installed Express before Enterprise/Developer you most likely have Management Tools - Basic installed.  I used the following steps to get SQL Server Profiler Installed, which is bundled with the Management Tools - Complete tool set.
Step 1: Remove Management Tools - Basic

Control "Panel -> Programs -> Programs and Features"
Uninstall/Change "Microsoft SQL Server 2008 R2"
Select "Remove"
In the "Select Instance" dialog, "Instances to remove features from:" drop-down choose Remove shared features only
Check "Management Tools - Basic"
Follow the rest of the uninstall dialogs

Step 2: Install Management Tools - Complete

Run setup from the Enterprise\Developer Edition installation media
Choose "New installation or add features to an existing installation"
A few screens later choose "SQL Server Feature Installation"
Check "Shared Features -> Management Tools-Complete"
Follow the rest of the dialogs to install.

You should now have SQL Server Profiler installed.


Q:

What is good route template for api?

What is good API route template? I other words, is there template that i  more expectable, or it is not important at all?
first:
"api/{controller}/{action}/{id}"
http://example.com/WorkItem/details/5

second:
"api/{controller}/{id}/{action}"
http://example.com/WorkItem/5/details

A:

I consider it good practice to use your second approach in a RESTful szenario. Common frameworks handle it this way:
Example 1: Rails
see the docs at 2.2 CRUD, Verbs, and Actions, where
GET /photos/{:id}/edit refers to the PhotosControllers edit-method to return an HTML form for editing a photo
Example 2: Laravel
see the docs at RESTful Resource Controllers, where
GET /photo/{photo}/edit also refers to a  PhotoControllers  edit-method.
Also, see the section on Nested Resources below which looks a bit more like your use case:
Route::resource('photos.comments', 'PhotoCommentController');
 registers a nested route in the way of photos/{photos}/comments/{comments} which is your use case and looks more like your second approach.


Q:

Which arptables rules to avoid man-in-the-middle attack?

One strategy to stop a man-in-the-middle attacker is to restrict accepted ARPs packet to only those need to the router.
What are the arptables rules to restrict accepted ARPs to only my router with known MAC?
The ARP packet generated with the following command from the attacker machine have all to be dropped:
arpspoof -i wlan0  -t <Victim IP (me) > < gateway IP >

PS: I am aware that IGMP can also be used to route the packet to the attacker.

A:

# Block ARP traffic from and to all machines (default: DENY)
arptables -P INPUT DROP
arptables -P OUTPUT DROP

# Allow router (fixed ARP)
arptables -A INPUT --source-mac <ROUTER_MAC> --destination-mac <USER MAC> -j ACCEPT

where <ROUTER_MAC> is the mac of the subnet router.


Q:

Check software version on website versus installed

I have two things in place.

Just a normal, run of the mill wordpress site, userspice.com
A downloadable php script called UserSpice that is used for managing users/controlling access to pages, etc.  It's a complete PDO/OOP rewrite of UserCake.  It is going through a lot of updates and features are being added weekly.  UserSpice 4 has a dashboard for the administrator to administrate things.  I would like the dashboard to be able to phone home to UserSpice.com to check what the latest version of UserSpice (the php app) is and offer to download the update.

I have searched extensively, but most searches involve updating the php version, NOT the app itself.  Is there a particular phone home api or something like that which is built specifically for this purpose.    I would assume it would involve just putting a version.txt or xml file in the root of userspice.com that contains the current version, but ideally I would want it to phone home at some sort of interval so as not to bring the userspice.com server down with useless requests.

A:

I tend to embed a constant in the code with the current version number and update it as necessary (usually manually to match notes in a version history page).  That makes it easy to put the version on the screen and use it in code logic.
That's better both because you don't have to read the file and it's one less component to manage and distribute.
"Phone home" is then implemented using a web api call that compares the internal constant with the return value from the api call to your central website.  That can be called from jquery so that it doesn't slow down the page load.  A couple of seconds after the admin page loads something would display in the header with the "new version" message attached.


Q:

On getting reviews for research work as independent learners

Consider an undergrad student (who wishes to dive into STEM research) in an obscure university in an obscure town who has a few ideas which he converts into a well documented article. All of this by learning completely on his own. He has no faculty within his institute (or locality) to turn to (they aren't as active in research) for help.
Where should such students/learners try to get comments/criticism on their work?

Sending it out to publishing is not a good idea because it will get rejected with cliched answers and will rarely help the candidate improve his work.
Stackexchange/Quora/Reddit etc. are great for small answers but it is too much to ask to read and rate someone's work
One can send out mails but Professors/Grad Students/Researchers in the field might not have the time to reply to such mails. Further, if the work is fundamentally flawed, the student might never get replies.
Any other repository site (ArXiv?) might cause the paper to be drowned by more successful ones and the student might never get comments.

What can he do?

A:

You want to try a combination of networking and learning how to ask good questions.

Networking—you have to find people in your field in order to grow, and you can only find people in your field by networking appropriately. Try to find money in the department/broader university to attend a conference, or even just email authors of papers you cite. Describe your situation (briefly). If they're local, ask to meet with them for 30 minutes-1 hr; if not, try for phone calls.
Do note that, generally speaking, graduate students/postdocs will be more willing to give you time than advisors; try to get in touch with them as well.

Asking good questions—you can and should assume that no one has time to act as your advisor. Because of this, your interaction with those whom advise you will be brief. Make the most of those minutes. Give a summary of your work, ask very directed, substantial questions. Make the most of your meetings.

Personally, the most productive meeting I had in the entirety of my just-under-five year graduate school stint was one with a member of my thesis committee, and the entire meeting lasted 15 minutes. I gave the right background, asked the right questions, and came away with what turned into my thesis project. (I don't think I've done that well since.) Do your homework, and you may benefit nicely.

A:

It may be that even if the faculty at the institution are not themselves active in research, they are likely to know people they are (after all, they got their own degrees somewhere).  The best route, if at all possible, would be for one of the the local faculty to put the student in touch with someone who is active in research.  The personal introduction makes it much likely that the work will get actual feedback.  (I'm assuming here that the student has actually talked to the local people and determined that they're not interested; just because a faculty members isn't currently active in research doesn't automatically mean they don't care and won't be able to help an interested student.)
If that's not an option, the student might be able to meet researchers through some sort of event, either one aimed directly at undergraduates (for instance, in the US, there are many summer programs for undergraduates), or even just by attending a conference and trying to meet people.  This may not be an option (summer programs require being accepted, for instance, and attending a conference on one's own can be expensive).
If that's off the table as well, it may be time to personally e-mail researchers in the area.  It's true that there's some risk the work will be ignored, but there are steps that can be taken to minimize this: choose a person to contact carefully, making sure it's someone actually interested in the exact topic of your research (on the one hand, you want it to be someone you cite, or at least someone who's worked directly in the area, but on the other hand, you don't want to e-mail the biggest name who has anything to do with the subject); and write a personal e-mail which makes your situation clear without being too verbose, and which explains why you're e-mailing this particular person.


Q:

how to retrive User name/login name from gmail?

I am using google login for custom website. here i wrote the code for it
var sOAuthServiceEndPoint = "https://accounts.google.com/o/oauth2/auth?scope=http://gdata.youtube.com https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&response_type=token&";
var sOAuthRedirectURL = "http://example.com/testpage/test.html";
var termsAndCondURL = "termsandcondition.html";
var sOAuthClientID = "294016263542.apps.googleusercontent.com";
var sAuthenticationURL = sOAuthServiceEndPoint + "redirect_uri=" + sOAuthRedirectURL + "&client_id=" + sOAuthClientID;

even i got an access token using below function
    function fnOnLoad() {
      //alert("Form Loaded");
      var sAccessToken = '';
      var params = {}, queryString = location.hash.substring(1),regex = /([^&=]+)=([^&]*)/g, m;
      while (m = regex.exec(queryString)) {
            params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
        }
        if(params.error){
            if(params.error == "access_denied"){
                sAccessToken = "access_denied";
                alert(sAccessToken);
            }
        }else{
                sAccessToken = params.access_token;
                alert(sAccessToken);
        }
        window.opener.fnAuthorisationSuccess(sAccessToken);
        window.close();
    }

It's working succesfully and redirect into the other page where I want. but my problem is how to retrive user login name..?
I am using javascript for it.
Thanks in Advance

A:

This can be found in the documentation.

After your application acquires an access token and has (if necessary) verified it, you can use that access token when making requests to a Google API. If the https://www.googleapis.com/auth/userinfo.profile scope was included in the access token request, then you may use the access token to acquire the user's basic profile information by calling the UserInfo endpoint.
Endpoint: https://www.googleapis.com/oauth2/v1/userinfo
Returns basic user profile information, including name, userid, gender, birthdate, photo, locale, and timezone. If the https://www.googleapis.com/auth/userinfo.email scope was present in the request, then the user's email will also be present in the response. If the email has been verified, then there is also a field that indicates the email is a verified address.


Q:

What is happening with this destructor? (segfault)

I'm writing a program aiming to simulate coral growth and I want corals to be some kind of binary tree. Branches are the equivalent of nodes. When I run the program I got a "segmentation fault" error and after testing and doing some research I'm thinking it is because the destructor of Coral class is trying to delete a NULL object. However I have no clue on how to solve it since I don't fully understand how a destructor works and I'm not familiar at all with the concept of class.
I give you the header file where CoralBranch and Coral classes are declared, the .cpp where the classes are implemented and the main.cpp.
Thank you all in advance.
Working in a  Minimal, Complete, and Verifiable example that reproduces my problem, I run into no problem. I think I have other errors in my program which provoque the segmentation faults at methods which shouldn't have problems.
coral2.h
#ifndef __CORAL2_H_INCLUDED__
#define __CORAL2_H_INCLUDED__

class CoralBranch{

  public:

CoralBranch(); // class constructor 1
CoralBranch(double xpos, double zpos, double th); // class constructor 2
~CoralBranch();

CoralBranch *left; // pointer to left child
CoralBranch *right; // pointer to right child
double x; // x-position of the beggining of the branch
double z; // z-position of the beggining of the branch
double theta; // branch's direction: angle between the branch and z-axis
double length; // branch's length
int state; // state==1: branch is able to grow, state==0: branch can't grow

};

class Coral{

  public:

Coral(); // class constructor 1
Coral(double bl, double gr, double ir, double dt); // class constructor 2
~Coral(); // class destructor

// adds theta-oriented left son to coral-branch *leaf
void add_left(CoralBranch *leaf, double theta);
// adds theta-oriented right son to coral-branch *leaf
void add_right(CoralBranch *leaf, double theta);
// destroys coral-branch *branch and its decendents
void destroy_coral(CoralBranch *branch);
// tests if the growing branch influence zone penetrates testbranch influence zone
void distance_test(Coral crl, CoralBranch *growingbranch, CoralBranch *testbranch);
// tests if the growing branch is big enough to have children and adds them
void branching_test(Coral crl, CoralBranch *growingbranch, double thetaleft, double thetaright);
// applies grow mechanism to growing branch
void branch_grow(Coral crl, CoralBranch *growingbranch);
// simulates the growing process for the entire colony after one time step by
// applying "branch_grow" to the whole colony
void coral_grow(Coral crl, CoralBranch *growingbranch);

  //private:

CoralBranch *trunk;

double branching_length;
double growth_rate;
double influence_radius;
double Deltat;

};

#endif

coral2.cpp (only constructors and destructors)
CoralBranch::CoralBranch():left(NULL),right(NULL),x(0.0),z(0.0),theta(0.0),length(1.0),state(1)
{
 // there isn't any methods in this class
}

CoralBranch::CoralBranch(double xpos, double zpos, double th):left(NULL),right(NULL),x(xpos),z(zpos),theta(th),length(1.0),state(1)
    {

    }

CoralBranch::~CoralBranch(){

  delete left;
  delete right;

}

Coral::Coral(){

  trunk=new CoralBranch();

  branching_length=1.0;
  growth_rate=1.0;
  influence_radius=1.0;
  Deltat=1.0;

}

Coral::Coral(double bl, double gr, double ir, double dt){

 trunk=new CoralBranch();
    //trunk=NULL;

  branching_length=bl;
  growth_rate=gr;
  influence_radius=ir;
  Deltat=dt;

}

Coral::~Coral(){ // coral destruction

  destroy_coral(trunk);

}

void Coral::destroy_coral(CoralBranch *branch){ // destroys branch *branch and its decendents

  if(branch == NULL) return;

  destroy_coral(branch->left);
  destroy_coral(branch->right);
  delete branch;

  /*if(branch!=NULL){

    destroy_coral(branch->left); // destruction advance
    destroy_coral(branch->right);
    delete branch; // currently considered branch is deleted if it exists

  }*/
}

main.cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "coral2.h"
#include <math.h>
using namespace std;

int main(){

  /* Variable declaration, these variables need to be initialized in order to
  construct the coral with the characteristics we desire */
  double branchinglength, growthrate, influenceradius, deltat;
  /* Declaration and initialization of the total simulation time */
  double TotalTime=2;
  /* Declaration and initialization of counters */
  int i=0;
  int j=0;
  printf("%d\n",j);

  /* Initialization of Coral class parameters*/
  branchinglength=0.2;
  growthrate=1.0;
  influenceradius=0.1;
  deltat=1.0;

  /* Creation of the coral object*/
  static Coral GrowingCoral(branchinglength, growthrate, influenceradius, deltat);

  /* Starting growth process */
  for(i=0; i<TotalTime; i=i+deltat){

    j++;
    printf("%d\n",j);

    GrowingCoral.coral_grow(GrowingCoral, GrowingCoral.trunk);

  }

  printf("%f\n",GrowingCoral.branching_length);

  return 0;
}

A:

You are deleting the left and right branches twice.
Think how your CoralBranch works: It owns a left branch and a right branch. Since it owns the branches, it can and should delete them in the destructor ~CoralBranch. And it does! Good.
Your class Coral owns only one object, the trunk. But look what Coral::destroy_coral does! It is allowed to delete branch objects that class Coral does not own! The only CoralBranch it should destroy is the one that it owns, trunk. That one will delete its own child branches via the destructor, and those their own, recursively. Hence, all you have to do is remove the recursive destroy_coral invocations from destroy_coral.


Q:

How get raw response (array of parameters) in POST method in SpringMVC?

I pass a reference third-party system and this system return me some parameters but I not understand What are the parameters. It is my controller with POST method
@Controller
@RequestMapping("/success")
public class SuccessController {

     @RequestMapping(value = "/eventlogs/logs", method = RequestMethod.POST)
        public String logs(@RequestParam("Approved") String json) {
            System.out.println("Received POST request:" + json);

            return "success";
        }
    }

But I not understand how type parameters I get/ I my example I wait  parameter  "Approved" and type String
But How can I get raw  response in my method? for example like this
@Controller
@RequestMapping("/success")
public class SuccessController {

        @RequestMapping(value = "/eventlogs/logs", method = RequestMethod.POST)
        public String logs(HttpResponse response) {
    System.out.println("Received POST request:" + response.get("p1"));
    System.out.println("Received POST request:" + response.get("p2"));
    System.out.println("Received POST request:" + response.get("p3"));
    ....
            return "success";
        }
    }

I know that third-party system set to my method many parameters and I do not want write something like
public String logs(@RequestParam("p1") String p1, @RequestParam("p2") int p2, @RequestParam("p3") boolean p3 .......)

I want something like JavaEE servlet's method
@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
 resp.get(......)
        super.doPost(req, resp);
    }

A:

You can set the HttpServletRequest (not HttpServletResponse) as parameter:
@Controller
@RequestMapping("/success")
public class SuccessController {

    @RequestMapping(value = "/eventlogs/logs", method = RequestMethod.POST)
    public String logs(HttpServletRequest req) {
        System.out.println("Received POST request:" + req.getParameter("..."));
....
        return "success";
    }
}

To know all the parameters sent in a request, use HttpServletRequest#getParameterNames or HttpServletRequest#getParameterMap to evaluate each parameter and its value or values.


Q:

ModelMapper flatten array property (get(0)) to String?

Src object has a property:
private List<Pojo> goals;

Dest object has a property
private String goal;

I want to map Src.goals.get(0).getName() -> Dest.goal. goals will always contain one item, but it has to be pulled in as a list because its coming from Neo4j.
I tried doing:
    userTypeMap.addMappings(mapper -> {
        mapper.map(src -> src.getGoals().get(0).getName(), UserDto::setGoal);
    });

But modelmapper didn't like the parameter. Then I tried:
    userTypeMap.addMappings(mapper -> {
        mapper.map(src -> src.getGoals(), UserDto::setGoal);
    });

And that gave me:
"goal": "[org.xxx.models.Goal@5e0b5bd8]",

I then tried to add a converter for List -> String, but that didn't get called. If I add a converter for the entire pojo to dto then I have to map the whole pojo which I don't want to do, I just want to override this one property.

A:

You can wrap the List access in a Converter and use this in a PropertyMap like follows:
ModelMapper mm = new ModelMapper();
Converter<List<Pojo>, String> goalsToName =
    ctx -> ctx.getSource() == null ? null : ctx.getSource().get(0).getName();
PropertyMap<Src, Dest> propertyMap = new PropertyMap<>() {
    @Override
    protected void configure() {
        using(goalsToName).map(source.getGoals()).setGoal(null);
    }
};
mm.addMappings(propertyMap);


Q:

Adding delay in data acquisition in labview

(Sorry I was not able to post picture as my reputation level is below 10)
What I wanted to do is, I want my laser displacement daq to start acquiring data after one second after the another daq acquisition  starts acquiring data.
I am not able to add delay  on the laser displacement daq.
(Both method should run for 10 second and laser displacement daq should be 1 second late at acquiring data.)
Thanks

A:

There are different ways to do that. Here are two ideas:

Acquire 11 seconds of data for both, and throw away the first 1 second of data from the laser.
Use the Time Delay Express VI and wires to control the order of code execution, as suggested by @nekomatic:  (Note: My original code, which uses Sequence Structures and the Wait (ms) Function, is at http://i.stack.imgur.com/9pIwb.png)


Q:

Angular-cli 'JavaScript heap out of memory' on asset optimization

I'm creating a leaflet map inside an Angular-cli project. Map tiles are stored locally in the 'assets' folder because it's a raster map. The problem is when I've many zoom levels of the map, I've more than 280 thousands images with approximate size of 1.1 GB and It will get bigger.
when I use ng serve here is the console output (it is stuck @ assets optimization):
** NG Live Development Server is running on http://localhost:4200. **
25234ms building modules
69ms sealing
0ms optimizing
0ms basic module optimization
96ms module optimization
1ms advanced module optimization
16ms basic chunk optimization
0ms chunk optimization
1ms advanced chunk optimization
0ms module and chunk tree optimization
179ms module reviving
9ms module order optimization
4ms module id optimization
6ms chunk reviving
23ms chunk order optimization
36ms chunk id optimization
61ms hashing
1ms module assets processing
149ms chunk assets processing
4ms additional chunk assets processing
0ms recording
1ms additional asset processing
2693ms chunk asset optimization
 94% asset optimization
<--- Last few GCs --->

  119106 ms: Mark-sweep 1333.6 (1409.7) -> 1333.6 (1415.7) MB, 1402.0 / 2.1 ms [allocation failure] [GC in old space requested].
  120570 ms: Mark-sweep 1333.6 (1415.7) -> 1333.6 (1427.7) MB, 1464.2 / 2.2 ms [allocation failure] [GC in old space requested].
  122079 ms: Mark-sweep 1333.6 (1427.7) -> 1340.0 (1409.7) MB, 1508.1 / 2.5 ms [last resort gc].
  123749 ms: Mark-sweep 1340.0 (1409.7) -> 1346.3 (1409.7) MB, 1670.2 / 2.1 ms [last resort gc].

<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 000001AA792CFB61 <JS Object>
    1: inflight [C:\Workspace\node_modules\inflight\inflight.js:~7] [pc=00000202BF9894B7] (this=000001AA792E6661 <JS Global Object>,key=00000045863E5881 <Strin
g[90]\: lstat\x00C:/Workspace/src/assets/leafletmap_files/9/42/176.png>,cb=00000045863E5839 <JS Function lstatcb_ (SharedFunctionInfo 00000253E9EFC219
)>)
    2: wrapper [C:\Workspace\...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

I tried using:
node --max_old_space_size=8192 --optimize_for_size --max_executable_size=4096 --stack_size=4096, but It doesn't make any difference.
1- Is there is any other way to avoid optimizing all the assets folder? If it is the source of the problem as I think, because the project were running smoothly before adding more leaflet tile images.
2- Is there are any workarounds to solve this issue?
UPDATE:
There is an open issue at Angular-cli repository related to this question.

A:

Add the below line to Package.json
"aot": "node --max-old-space-size=8192 ./node_modules/@angular/cli/bin/ng
build --prod --aot"

and try running with "npm run aot".
It worked for me.

A:

You can add NODE_OPTIONS as a system variable. To set memory to 4 gigs,
--max-old-space-size=4096
Lots more info on this thread, they deserve the votes


Q:

NuxtJS & Vuetify - Webpack build exited with errors

I use Vuetify v0.17.6 and NuxtJS v1.3.0.
I get this error when I push my project on production: https://pastebin.com/AJWHZE9q
I think is the import of Vuetify as plugin on NuxtJS.
My vuetify.js file for NuxtJS plugin:
import Vue from 'vue'
import Vuetify from 'vuetify'

import 'vuetify/dist/vuetify.min.css'

Vue.use(Vuetify, {
  theme: {
    primary: "#F57C00",
    secondary: "#EF6C00",
    accent: "#E65100",
    error: "#F44336",
    warning: "#ffeb3b",
    info: "#2196F3",
    success: "#4CAF50"
  }
})

A:

I found the root cause!
I downgraded postcss-loader v2.1.2 package in my project with this command:

npm install postcss-loader@^2.1.1 --save-dev

or

yarn add postcss-loader@^2.1.1 -D

An option was changed in node_modules/postcss-loader/lib/options.json
And I forgot to commit the yarn.lock file.


Q:

Undefined method - NOMethod error with Resque gem

I am trying to generate xml file as a background task using resque gem here is the class which generates xml file ....
ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV']
require File.expand_path(File.dirname(__FILE__) + "/../../config/environment")
require  'rubygems'
require 'builder'

class GenerateXml
  @queue = :worker

  def self.perform
    file_name = "#{Time.now.strftime('%Y_%m_%d')}_export.xml"

    xml = Builder::XmlMarkup.new(:target => file_name, :indent => 2)
    xml.instruct!(:xml, :encoding => "UTF-8")

    xml.Postings do
      Result.find_in_batches do |result|
        xml.Posting do
          xml.JobID result.job_id
          xml.JobURL result.job_url
        end
      end
    end
  end
end

and my result model from where I am extracting the fields for the xml tags is like this
require 'active_record'

class Result < ActiveRecord::Base
  def job_id
    self.link
  end

  def job_url
    self.link
  end
end

My question is why result.job_url and result.job_id from class GenerateXml is not able to map to Result class correctly?
and one more thing the Result class is under app/models directory where as GenerateXml class is under lib/jobs directory
Here is the trace of error.
      undefined method `job_id' for #<Array:0xb3f26738>

/home/netserv/RubymineProjects/crawler/lib/jobs/generate_xml.rb:22:in `perform'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:155:in `call'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:155:in `_nested_structures'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:63:in `method_missing'
/home/netserv/RubymineProjects/crawler/lib/jobs/generate_xml.rb:21:in `perform'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/activerecord-3.2.3/lib/active_record/relation/batches.rb:72:in `find_in_batches'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/activerecord-3.2.3/lib/active_record/querying.rb:8:in `__send__'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/activerecord-3.2.3/lib/active_record/querying.rb:8:in `find_in_batches'
/home/netserv/RubymineProjects/crawler/lib/jobs/generate_xml.rb:20:in `perform'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:155:in `call'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:155:in `_nested_structures'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:63:in `method_missing'
/home/netserv/RubymineProjects/crawler/lib/jobs/generate_xml.rb:19:in `perform'

A:

find_in_batches returns arrays. Inside the Postings block, you could do this:
  Result.find_in_batches do |results|
    results.each do
      xml.Posting do
        xml.JobID result.job_id
        xml.JobURL result.job_url
      end
    end
  end

But why even bother with find_in_batches?


Q:

Master on/off switch in ActionBar

I have worked out a design for settings by using Android's Preference API.
But I don't know how to create a "Master on/off switch". It is mentioned here http://developer.android.com/design/patterns/settings.html but there is no document of how to implement it.
Technically it is a SwitchPreference located in the Action Bar which disables all child settings when it is turned off.
Any ideas?

A:

you have to create it manually . This is a pattern that you should implement. you can add a button in action bar and on click you can enable or disable the feature and change the drawable accordingly. you can use switch tag but this is introduce in api 14 only. example,
  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <Switch
        android:id="@+id/switchForActionBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</RelativeLayout>

Then, in your mainmenu.xml add the item as follows
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/myswitch"
        android:title=""
        android:showAsAction="always"
        android:actionLayout="@layout/switch_layout"
    />
</menu>

you can add use this as well
public class TogglePreference extends Preference {

    public TogglePreference(Context context) {
        super(context);
    }

    public TogglePreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TogglePreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public View getView(View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = new LinearLayout(getContext());
            ((LinearLayout) convertView)
                    .setOrientation(LinearLayout.HORIZONTAL);

            TextView txtInfo = new TextView(getContext());

            txtInfo.setText("Test");
            ((LinearLayout) convertView).addView(txtInfo,
                    new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.FILL_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT, 1));

            ToggleButton btn = new ToggleButton(getContext());
            ((LinearLayout) convertView).addView(btn);
        }

        return convertView;
    }

And the preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory android:title="Test custom preferences" >

        <android.dumdum.TogglePreference />
    </PreferenceCategory>

</PreferenceScreen>


Q:

Ruby on Rails exception handling basics

I have a Rails 3 app that is using the exception_notification gem to send emails about exceptions.
I would also like to show users specific error messages when exceptions occur, but by catching a generic Exception because I'm not sure of all the exceptions that can occur.  I'm thinking the way to do this is to rescue from Exception, and then raise a custom exception.  That way I'm still getting an email about the exception, and the user can see the custom exception's error page.
Does this sound like a Rails 3 way to do things?
Thanks a lot.

A:

I think not.
As Ryan Davis says

Don’t rescue Exception. EVER. Or I will stab you.

More info about that statement here.
Rails 3.2 does exception handling in two middlewares:

ActionDispatch::ShowExceptions
ActionDispatch::DebugExceptions

You can check that one by running
$ rake middleware

ActionDispatch::ShowExceptions [source]
Used in production to render the exception pages.
ActionDispatch::DebugExceptions [source]
Used in development environment to render detailed stack traces when exceptions occur. Stops  the middleware call chain and renders the stack trace if action_dispatch.show_detailed_exceptions is true to be more precise.

So the most simple way of doing something normal with this middleware would be monkeypatching the call method of ActionDispatch::DebugExceptions, doing all you need to do and then calling the original method.
The better way of doing this is, however, including your own middleware between those two. In it, you would wrap the call inside a rescue block and do your custom processing.
I am a maintainer of Airbrake and this is exactly what we're doing right now.
You might also want to check Errbit, the self-hosted alternative.


Q:

How to read required values from a list and store it in csv using python?

I have a response in the list format. I have to read the list and store only required values in CSV file in ';' separated values.
 row = "[('Employee', 'Shift', 'IT', '5:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'IT', '6:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'CALL CENTER', '7:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'CALL CENTER', '8:15AM', 'Server', 'Manager', 'empemail@cmp.com')]"

Now I need to store the list in CSV file in the below expected  format.
param_Name,Param_Value
p_Name,Employee
p_operationType,IT;IT;CALL CENTER;CALL CENTER
p_Time,5:15 AM;6:15 AM;7:15 AM;8:15 AM
p_avaiablity,Daily
p_email,empemail@cmp.com

I am trying in pandas.
 import csv
 import pandas as pd
 df = pd.DataFrame(data=row).T
 df.to_csv('csvfile.csv',sep=';',index=False,header=False)
 print(df)
 for item in df:
    print(item)
    #Stuck on how to proceed further...

With this code I am geting a csv file as
param_Name,Param_Value
p_name,Employee;Employee;Employee;Employee
p_avaiablity,Daily;Daily;Daily;Daily

How can I iterate into the list and get only required values and store as expected format?

A:

Hope this helps
import pandas as pd

row = [('Employee', 'Shift', 'IT', '5:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'IT', '6:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'CALL CENTER', '7:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'CALL CENTER', '8:15AM', 'Server', 'Manager', 'empemail@cmp.com')]

# use dataframe constructor properly and name your columns
cols = ['Employee', 'Dont_know_what_this_is', 'department', 'time', 'location', 'status', 'email']
df = pd.DataFrame.from_records(row, columns=cols)

for index, row in df.iterrows():
    # do what you want with your data
    print(row)

# or use 'loc' function to get specific columns
df = df.loc[df.department == 'IT']
print(df)
# then export your csv
df.to_csv('csvfile.csv',sep=';',index=False,header=False)

Outputs:
    Employee Dont_know_what_this_is   department    time location   status             email
0  Employee                  Shift           IT  5:15AM   Server  Manager  empemail@cmp.com
1  Employee                  Shift           IT  6:15AM   Server  Manager  empemail@cmp.com
2  Employee                  Shift  CALL CENTER  7:15AM   Server  Manager  empemail@cmp.com
3  Employee                  Shift  CALL CENTER  8:15AM   Server  Manager  empemail@cmp.com

After loc:
Employee Dont_know_what_this_is department    time location   status             email
0  Employee                  Shift         IT  5:15AM   Server  Manager  empemail@cmp.com
1  Employee                  Shift         IT  6:15AM   Server  Manager  empemail@cmp.com


Q:

Why do people suggest you try using another USB port?

Just curious why this is always on the list for trouble shooting USB devices.
Is it just because how USB works, some kind of tech myth, or just in case there's an actual hardware fault with the USB port?

A:

Why not?
Firstly, not all USB ports are made the same. Front usb ports are notorious for not supplying enough power for many devices, especially with older/cheaper cases. USB 3.0 may not work for keyboards at boot time for many devices. You might have more than one controller on a system for USB, and that controller may be flakey. In short, it rules out an error with a specific port, its controller, or the physical electrical subsystem that is supporting it.
It is no different from running a minimal system to work out why a motherboard or other device is acting up, and adding things till something fails.

A:

Sometimes, Windows will see the same device on a different port as a different device, and reload the drivers for it.


Q:

Remove dict which have the same id from a list of dict

I want to remove from a list of dicts, dicts which have the same ID.
def removeDuplicate(elems, id):
    new_list = []
    for elem in elems:
        if not elem[id] in [d[id] for d in new_list if id in d]:
            new_list.append(elem)
    return new_list

a = [
    {0 : 'a', 'id' : 2, 2 : 'c', time : '1'},
    {0 : 'a', 'id' : 2, 2 : 'c', time : '2'},
    {0 : 'a', 'id' : 3, 2 : 'c', time : '3'},
    {0 : 'a', 'id' : 4, 2 : 'c', time : '4'},
    {0 : 'a', 'id' : 5, 2 : 'c', time : '5'},
    {0 : 'a', 'id' : 4, 2 : 'c', time : '6'},
    {0 : 'a', 'id' : 2, 2 : 'c', time : '7'},
    {0 : 'a', 'id' : 3, 2 : 'c', time : '8'},
]
print(a)

a = removeDuplicate(a, 'id')

print(a)

It's work fine for 7000 elements but it's take to much time for 500 000 elements.
Is there a better way to delete these occurrences ?

A:

Try using set when you are doing a lookup because it is only O(1) complexity. Also try not looping when is not necessary.
This slightly modified code of yours should be fast enough even for half a million elements
def removeDuplicate(elems, id):
    new_list = []
    read_ids = set()
    for elem in elems:
        if elem[id] not in read_ids:
            read_ids.add(elem[id])
            new_list.append(elem)
    return new_list

A:

The complexity of your code is O(n^2) (or even worse). You keep recreating and reiterating over new_list.
Simply make a set of all the ids you already saw. An in check in a set is an O(1) operation.
def removeDuplicate(elems, id):
    seen_ids = set()
    new_list = []
    for elem in elems:
        if elem[id] not in seen_ids:
            new_list.append(elem)
            seen_ids.add(elem[id])
    return new_list

a = [
    {0 : 'a', 'id' : 2, 2 : 'c', time : '1'},
    {0 : 'a', 'id' : 2, 2 : 'c', time : '2'},
    {0 : 'a', 'id' : 3, 2 : 'c', time : '3'},
    {0 : 'a', 'id' : 4, 2 : 'c', time : '4'},
    {0 : 'a', 'id' : 5, 2 : 'c', time : '5'},
    {0 : 'a', 'id' : 4, 2 : 'c', time : '6'},
    {0 : 'a', 'id' : 2, 2 : 'c', time : '7'},
    {0 : 'a', 'id' : 3, 2 : 'c', time : '8'},
]
print(a)

a = removeDuplicate(a, 'id')

print(a)


Q:

Number Partitions With Unique Difference but Symmetrical

For an even integer $n$, line up the integers from $1$ to $n$ so that:
the differences are all different in one half but symmetrically the same in the other
example for $14$:
$$7 \ \ 1 \ \ 10 \ \ 2 \ \ 3 \ \ 6 \ \ 4 \ \ 11 \ \ 9 \ \ 12 \ \ 13 \ \ 5 \ \ 14 \ \ 8$$
Clearly the additional symmetry around the centre is $n+1$
e.g. $15=11+4=9+6=12+3+\cdots$
Can you always do this?
if so, in how many ways for given $n$?
Can it be made into a cycle so that the 'centres' also have the same difference?
(e.g. above $8 \ \ 7$ is diff $1$ but $4 \ \ 11$ is diff $7$)

A:

One way is to make the pairs $(k, n+1-k)$  for $k$ from $1$ to $\frac n2$.  The first $\frac n2$ numbers must be one of each pair, but otherwise there is no restriction, and the last $\frac n2$ numbers are fixed.  That gives $\left(\frac n2\right)!\cdot2^{n/2}$ possibilities.  I am not sure there are no more.
As each pair has a unique difference of $n+1-2k$ this approach cannot close the cycle.


Q:

How is complex permittivity measured?

Complex relative permittivity is defined as
$$\epsilon_r = \frac{\epsilon(\omega)}{\epsilon_0}=\epsilon_r^{\prime}(\omega) + i\epsilon_r^{\prime\prime}(\omega) = \epsilon_r^{\prime}(\omega) + \frac{i\sigma}{\omega\epsilon_0}$$
Measuring the real static permittivity, $\epsilon_r(\omega=0)$, can be done by a plate capacitor, $\epsilon_r=\frac{C_x}{C_0}$. But how can I get a chart like this one?

EDIT: A practical question about the same thing was posted on electronics.SE.

A:

First make a parallel plate capacitor with plates of area A and spacing d.  Fill the space between the plates with the dielectric whose complex permittivity $\epsilon(\omega)$ you wish to measure.
The formula for this capacitance is a complex function of frequency because the permittivity is a complex function of frequency.
$$
C(\omega)={{\epsilon(\omega)A}\over{d}}
$$
This capacitor has a complex impedance $Z(\omega)$ which is also a function of frequency
$$
Z(\omega)={1\over {i\omega C(\omega)}}={1 \over {i\omega {{\epsilon(\omega)A}\over d}}}
$$
Rearranging gives
$$
\epsilon(\omega)={d\over {i\omega Z(\omega)A}}
$$
Now from a signal generator put a voltage $V sin(\omega t)$ across Z, measure the amplitude ($I(\omega)$) and phase shift ($\delta(\omega)$) of the current $I(\omega) sin(\omega t - \delta(\omega))$ that flows through Z, and use Ohm's law to calculate the complex impedance.
$$
Z(\omega)={V \over {I(\omega)}}e^{i\delta (\omega)}
$$
Plug this into the previous equation to get the complex $\epsilon(\omega)$.
There are commercial instruments called LCR Meters or Network Analyzers which have a signal generator built in and are used to measure complex impedances as described above.
This method will work to about 1 GHz.  Studying the transmission and reflection in a dielectric filled wave guide will work for about 1-10 GHz.  Infrared, visible, and ultraviolet light transmission and reflection from the dielectric can be used at higher frequencies.  Remember the index of refraction is also complex and related to $\epsilon$ by:
$$
n = \sqrt{\epsilon \mu}
$$
The materials are often non-magnetic so the magnetic permeability $\mu$ is very close to the constant $\mu_0$.


Q:

sending 'F2' over serial port c#

i have some kind of parser that receive a configuration file, and it resolves its data. One possible type of data is Hex characters. I am formatting the Hex character ie(0D), and for most hex chars i am not facing problems. However, for the 'F2' key, I am not able to send it.
The following snippet is how i am resolving the Hex chars:
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
     raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return Encoding.GetEncoding("iso-8859-1").GetString(raw);

I am sending data serially over a Gold x usb to serial. And all my data is passing including '\n\r'. For 'F2' i am using the Hex value of 'A1'

A:

forming a char from the Byte array and then converting the char to string, and encoding this string using UTF-8 fixed the issue for me


Q:

JQuery Post Can't Reach Controller One Folder Above Root

Haven't had much luck with my keywords in Google or here so I'm asking this even though I am sure its trivial...
I want to use a JQuery $.POST method to ask for information from a controller that is located above the server root... I have found answers in .ASP and J2EE but not simple PHP/HTML/etc...
This controller does not need to be instantiated so the simple URL should be enough to send it info and ask for a response. I have used JQuery a long time so I don't need answers that ask if I am using .POST correctly as I have used this AJAX method for over two years.... Just not in MVC architecture.
I have a PHP MVC built site that I am running and I basically just want to get some info from my controller so I am trying this $.post("../../../controller/controllerScript.php", {...}, function() {...}) ... I also have tried removing each of the ../ individually and tested each. No luck... So far I am getting consistent error 404 messages that it can't find the file. This makes sense to me because this is above the server root and shouldn't be publicly accessible.
I am aware that this is because I am looking for a file above the server root but I thought that was supposed to be the magic of MVC that I can set the root to the public folder and have a lot more security and clear programming. I know the problem probably lies in needing an .HTACCESS file which I suck at doing, or some other URL redirection method but I just don't know which.
My server folder architecture
-controller
    -fileINeed.php
-model
-public
    -js
        -myPOSTfunction
-view

I thought a simple action="../../../controller/fileINeed.php" would at least let me submit the form to an empty page so I could debug it but even this cant be found. It changes the URL to //BASE/controller/fileINeed.php which I am sure is part of the server security to files above the root.
Anyone able to quickly give me a MVC-101 schooling and show me how dumb I am? lol

A:

The issue is JQuery is a client side language, thus is restricted to the document root and cannot traverse above, this is a security feature because if a JQuery could traverse above root so could your visitors and this would cause major security issues. Depending on how your server is set up you can use the JQuery to call a php or any other server side application that resides inside the root then inside that script make a call or reference a app located above it.
Create a caller php inside public\ then include it from there
include('/home/controller/fileINeed.php');

Keeping in mind you need to figure out the directory structure between your server root and the public folder and replace /home with it. some use /www.


Q:

Import data from Raspberry Pi to PC using Ethernet

I am using Raspberry Pi model B, in which I am running a program created with python, my program has to write some data into some Excel files. Now I want to import those files using my PC via ehernet. My pc is running windows. It would be more useful to create a gui which can help users to easily import those files.

A:

You can use CIFS. Just create a shared folder in Windows and bind it in the /etc/fstab on RPi.
Another approach would be to use SSH i.e. scp.


Q:

uml-include or extend

I am trying to make a use case diagram for library management system. I have two actors admin and user.
Now, the admin has three functions manageCategories (of books like history, geography etc.) manageUser and manageBooks..
What I am doing is considering these 3 functions in a single function manage i.e manage is a single use case.
How should I consider the three functions managerUser, manageBooks, manageCategories in the diagrams?
Should I use include or extend the three functions in a single use case manage, or use anything else?

A:

Edited after the corrects comments of @vainolo about the included use case confusion in my answer:
If the manage use case needs the callable use cases (managerUser, manageBooks, manageCategories) in order to make sense (produce value) for the main actor, then you should use the include relationship.
If the actor can complete the manage use case executing zero or all three of the callable use cases (managerUser, manageBooks, manageCategories) then you should use the extend relationship and you may specify the extension point conditional statements for them.
If the manage use case is a container used to organize the three callable use cases which can be executed independently, then I'd modelize manage as a  Use Case Package containing the three use cases rather than a use case per se.

Please find the following excerpt from that post about the NOT mandatory execution of an included use case (as correctly pointed out by @vainolo):

Point 5: Inclusion use cases may be optional
A UML superstructurestatement Section 16.3.5 of 2 states:
“Note that the [inclusion] use case is not optional, and is always
required for the [base] use case to execute correctly.”
Cause for confusion
Some seem to interpret this to mean that an inclusion use
case must be performed during each and every execution of a base use
case.
Nothing is further from the truth and the truth is simple.
The simple truth
Whether an inclusion use case is mandatory or
optional to a base use case depends on where in the base use case the
fragment was defined that is now replaced with an include statement
for the inclusion use case.
If that fragment was part of the base use case’s unconditional flow
(steps that always get executed), the inclusion use case is mandatory.
If that fragment was part of a conditional flow (steps that get
executed optionally), the inclusion use case is optional.
So what does the UML statement mean?
The purpose of the UML statement seems to
be to contrast the include relationship with the extend relationship,
as follows.
At an extension point (not for the entire base use case), the
extension use case’s execution is optional.
When the execution of a base use case reaches an extension point, an
extension use case may or may not be inserted, because there may be a
condition attached to the extend relationship. However, at an
“inclusion point” (not for the entire base use case), the inclusion
use case’s execution is mandatory.
When the execution of a base use case reaches an inclusion point
(i.e., an include statement in the base use case), the inclusion use
case will always be performed, because there is no provision for
attaching a condition to the include relationship.


Q:

Node js too many redirect using middleware redirect

In my Node.js application (I'm using express 4.x) I want to check if the user is logged. If the user isn't logged I want to redirect to my login page. Then I do that in the middleware like this :
Server.js
app.use(function (req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/login');
});

Login route
// Login page
app.get('/login', function(req, res){
    res.render('pages/login', {
                error   : req.flash('loginError'),
                info    : req.flash('info'),
                success : req.flash('success')
            });
});

But when I add this code in my middleware, the login page is called more than 30 times... And my browser says Too many redirect.
Do you know why my login page is called a lot ?

A:

You catch in infinite loop because if the requested path is login even so redirect to login again
app.use(function (req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    if(req.route.path !== '/login')
      res.redirect('/login');
    next();
});


Q:

Laravel - Delete local file after served to client

I am using the following to serve a PDF file to a user return
response()->download($filename);

Once the file has been served for download, there is no need to keep it on the server and I would like to remove it so they don't clog the server storage. What is the best way to remove the file after it has been downloaded? I was going to use terminable middleware to handle it. Is that the best way to do it with Laravel 5.1?

A:

Just to post this here in case anyone else has this question...
It is possible to flash the file name to the session and then use terminable middleware to fetch the session variable and unlink the file.


Q:

Split string into bbcode sections. PHP

I have a BBcode wysiwyg editor for only the basics styles bold, italic and underline. I need to take the stored data from it and use it to convent it into a PHPWord friendly array.
PHPWord works with something called textrun so to have many styles within a line you would simple do something like...
$PHPWordTextRun = new TextRun();
$PHPWordTextRun->addText('This is some text that contains ', 'NORMAL');
$PHPWordTextRun->addText('Italic ', 'ITALIC');
$PHPWordTextRun->addText(' and ', 'NORMAL');
$PHPWordTextRun->addText('bold', 'BOLD');
$PHPWordTextRun->addText('text', 'NORMAL');

Im still completely unsure about how i do the nested tags.
So anyway here is what i need help doing. Turning this string below...
$string = "This is some text that contains [i]Italic[/i] and [b]bold[/b] text"

and turn it into an array like so
Array("This is some text that contains ","[i]Italic[/i]","and ","[b]bold[/b]","text");

Im a complete novice at regex and not even sure if you would use regex here.
My end goal is to end up with something like...
$PHPWordTextRun = new TextRun();
foreach($array as $line) {
    $PHPWordTextRun->addText($line['text'], $line['style']);
}

UPDATE:
So after testing around and playng with a couple of the answers i have come up with the following.
As suggested below i have tried the following.
$array = preg_split('/(.*?)(\[.+?\].+?\[\/.+?\])(.*?)|(.*)/m', $txt, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

This is working to a degree but it did have plenty of blanks but fixed with PREG_SPLIT_NO_EMPTY but it doesnt support nested brackets.

A:

This expression might likely return what we wish to output, maybe with slight modifications, if not:
(.*?)(\[.+?\].+?\[\/.+?\])(.*?)|(.*)

Test
$re = '/(.*?)(\[.+?\].+?\[\/.+?\])(.*?)|(.*)/m';
$str = 'This is some text that contains [i]Italic[/i] and [b]bold[/b] text This is some text that contains [i]Italic[/i] and [b]bold[/b] text This is some text that contains [i]Italic[/i] and [b]bold[/b] text';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

Demo
RegEx Circuit
jex.im visualizes regular expressions:


Q:

Cell Cross-Reference using VBA

I have done some searching and cannot figure out the syntax for what I would like to accomplish.  I would like to have a specific, static cell on a Summary sheet automatically update to a dynamic cell on a different worksheet.  I started with the following code:
Sheets("Summary").Activate
Range("B1").Select
ActiveCell.FormulaR1C1 = "='Current Billing'!R[46]C"
Range("B2").Select
ActiveCell.FormulaR1C1 = _
    "='Current Billing'!R[45]C[3]+'Current Billing'!R[45]C[4]"

After getting some advice on a different topic for this same workbook, I now know .Select is a no-no and should be avoided.  I also know that my last row on the "Current Billing" worksheet will change when I copy the code to another workbook for billing that project.  This has led to me to modify my code to make it more fool-proof and versatile.
I have figured out how to get the the cell value to insert from my "Current Billing" sheet to my "Summary" sheet.  But if something changes on the "Current Billing" sheet, the "Summary" sheet will not automatically update.  This is the code I have that sort of works:
Dim ws5 As Worksheet
'ws5 is "Current Billing"
Dim ws6 As Worksheet
'ws6 is "Summary"
Dim LRowB2 As Long
Dim LRowB3 As String
LRowB2 = ws5.Cells(Rows.Count, "B").End(xlUp).Row
LRowB3 = ws5.Cells(LRowB2, "B")
ws6.Cells(1, "B").Formula = LRowB3

I tried these two code sequences, but kept getting errors:
Dim LRowB4 As String
Dim LRowE2 As Long
Dim LRowF2 As Long

LRowB4 = "= & ws5 & ! & LRowB3"
ws6.Cells(2, "B").Formula = "=sum(& LRowE2 &,& LRowF2 &)"

In short, is there a way to mimic the function of the first code procedure, but have the stability and fool-proofness of the second procedure?  And, is there a way to integrate a =Sum() formula into the second procedure so I can add two cells from "Current Billing" on the "Summary" page?  Thanks for the help!

A:

The syntax of the formula is similar to =SUM('Current Billing'!C9, 'Current Billing'!D9)
This will check for errors, and is a bit more dynamic

Option Explicit

Public Sub UpdateSummary()
    Dim wsCB As Worksheet, lrCB As Long, cbCellC As Range, cbCellD As Range
    Dim wsSummary As Worksheet, sumCell As Range

    Set wsCB = ThisWorkbook.Worksheets("Current Billing")
    Set wsSummary = ThisWorkbook.Worksheets("Summary")

    lrCB = wsCB.Cells(wsCB.Rows.Count, "C").End(xlUp).Row

    'Verify that we have the same last row for col C and D on sheet "Current Billing"
    If wsCB.Cells(wsCB.Rows.Count, "D").End(xlUp).Row = lrCB Then
        Set cbCellC = wsCB.Cells(lrCB, "C")     '"Current Billing".Cell(lr, C)
        Set cbCellD = wsCB.Cells(lrCB, "D")     '"Current Billing".Cell(lr, D)
        Set sumCell = wsSummary.Cells(2, "B")   '"Summary".Cell(2, B)
        sumCell = "Invalid 'Current Billing' values"    'Default (in case of errors)

        'Check "Current Billing" cells for errors (#N/A, #VALUE!, #REF!, #DIV/0!, etc)
        If Not IsError(cbCellC) And Not IsError(cbCellD) Then

            'Verify that "Current Billing" cells are numbers
            If IsNumeric(cbCellC) And IsNumeric(cbCellD) Then
                Dim cbC As String, cbD As String

                cbC = "'" & wsCB.Name & "'!" & cbCellC.Address(0, 0) 'Current Billing'!C9
                cbD = "'" & wsCB.Name & "'!" & cbCellD.Address(0, 0) 'Current Billing'!D9

                'Final format: =SUM('Current Billing'!C9, 'Current Billing'!D9)

                sumCell.Formula = "=SUM(" & cbC & ", " & cbD & ")"  'Update Summary cell
            End If
        End If
    End If
End Sub

If the formula will contain a division, verify that the divisor is not 0
But if you are using VBA for this, you can simplify the syntax: sumCell = cbCellC + cbCellD

Note:
String variables become more complex when we have to use quotes inside quotes:

Str with ""double quotes"" can be built like this

str = "Str with """"double quotes""""", or
str = "Str with " & Chr(34) & """double quotes""" & Chr(34), or
str = "Str with " & Chr(34) & Chr(34) & "double quotes" & Chr(34) & Chr(34)

This string str = "Str with 'double quotes'" is Str with 'double quotes'


Q:

How do you acquire more Pharros Lockstones if you have already used all of them?

Pharros lockstones allow you to open certain areas and manipulate certain contraptions in the game. Merchants sell a limited amount of these items yet they are integral in progressing through the storyline. There are far more Pharros Contraptions than there are lockstones and using them will destroy them.
How can I acquire more lockstones if I have already bought the ones the merchants sell and used them?

A:

In either Doors of Pharros or the well down Majula, if you're summoned as a gray phantom and win, you're awarded with one, so they're pretty easy to farm, since you get summoned super easily in those areas


Q:

How to override the "get-childItem" command in Powershell?

Could I override this command? I want to do my own job when I execute the "Get-ChildItem" command in Powershell.

A:

Yes, you can override Get-ChildItem or any other cmdlet in Powershell.
Name Your Function The Same
If you make a function with the same name in the same scope, yours will be used.
Example:

Function Get-ChildItem {
[CmdletBinding()]
param(
    # Simulate the parameters here
)
    # ... do stuff
}

Using Aliases
Create your own function, and then create an alias to that function, with the same name as the cmdlet you want to override.
Example:
Function My-GetChildItem {
[CmdletBinding()]
param(
    # Simulate the parameters here
)
    # ... do stuff
}

New-Alias -Name 'Get-ChildItem' -Value 'My-GetChildItem' -Scope Global

This way is nice because it's easier to test your function without stomping on the built-in function, and you can control when the cmdlet is overridden or not within your code.
To remove the alias:
Remove-Item 'Alias:\Get-ChildItem' -Force

Know the Command Precedence
about_Command_Precedence lists the order in which commands of different types are interpreted:

If you do not specify a path, Windows PowerShell uses the following
           precedence order when it runs commands:

Alias
Function
Cmdlet
Native Windows commands


Q:

C# + Overrride Delegate

I have some code that is using a third-party library that I can't bypass. This library provides some auxiliary features that I need. At this time, my code is setup like this:
static Engine engine = new Engine();

static void Main(string[] args)
{
   engine.Execute(MyCode);
}

private static void MyCode()
{
  // my code goes here
}

Here's my challenge: I have to instantiate some code before MyCode can use it because that instantiation must hit a database and takes longer than the threshold allowed by Engine. I can't use a static variable because multiple instances will be necessary. Which basically means, I want something like this:
static Engine engine = new Engine();

static void Main(string[] args)
{
   MyClass c = new MyClass();
   c.Initialize();  // This is the db call

   engine.Execute(MyCode); // This line is the problem
}

private static void MyCode(MyClass c)
{
  // my code goes here
  c.DoStuff();
}

My problem is, I basically need to create an overloaded method that takes a parameter. However, the Execute method in the third-party library doesn't let me do that. Is there some C# syntactial way I can do this that I'm missing?

A:

You're looking for lambda expressions:
engine.Execute(() => MyCode(c));


Q:

How to loop json format array variable in javascript

This is my code, using for marking all places that I fetched from my database in google map.
 $.ajax({
        url:"http://localhost/church_finder/index.php/MapController/search_church",
                type:'POST',
                data:{coordinates:coordinates}
                 success: receiver
               });

Here I call the function receiver with the result I got from the database.
function receiver(data, textStatus, XMLHttpRequest) {

var json = JSON.parse(data);

var features = [
            for( var i=0; i<json.length; i++) {
            var lat=json[0]["lat"];
            var lng=json[0]["lng"];
                {
                    position: new google.maps.LatLng(lat,lng),
                },
            }
            ];

     features.forEach(function(feature) {
                var marker1 = new google.maps.Marker({
                    position: feature.position,
                    map: map
                });
            });
}

This is the result data I getting from ajax

[{"lat":"10.526800731337735","lng":"76.20941162109375"},
  {"lat":"10.622100079463674","lng":"76.1424207687378"},{"lat":"10.604004340704408","lng":"76.14100456237793"},{"lat":"10.608644375798574","lng":"76.13735675811768"},{"lat":"10.624419968495433","lng":"76.13675594329834"},{"lat":"10.62436724394038","lng":"76.13685250282288"},{"lat":"10.624377788852131","lng":"76.13693833351135"},{"lat":"10.615815200680679","lng":"76.1367130279541"},{"lat":"10.601726479547619","lng":"76.13688468933105"},{"lat":"10.610500370131295","lng":"76.13244295120239"},{"lat":"10.631991120088175","lng":"76.13566160202026"}]

but when am using forloop inside var feature I got error like this "Uncaught SyntaxError: Unexpected token for". How can i loop and mark all this coordinate in google map.

A:

This is your approach
var json = JSON.parse(data);

var features = [
    for( var i=0; i<json.length; i++) {
    var lat=json[0]["lat"];
    var lng=json[0]["lng"];
        {
            position: new google.maps.LatLng(lat,lng),
        },
    }
    ];

features.forEach(function(feature) {
        var marker1 = new google.maps.Marker({
            position: feature.position,
            map: map
        });
    });
}

There are some issues in your code
You're trying to execute a for-loop within both brackets []
var features = [
    for( var i=0; i<json.length; i++) { <- Here
    var lat=json[0]["lat"];
    var lng=json[0]["lng"];
        {
            position: new google.maps.LatLng(lat,lng),
        },
    }
    ];
    ^

You're always itetaring with position 0
var lat=json[0]["lat"];
var lng=json[0]["lng"];
             ^

You have an expression that never was assigned to a variable:
{
    position: new google.maps.LatLng(lat,lng),
},
^

Look this code snippet with those fixes
var json = [{"lat":"10.526800731337735","lng":"76.20941162109375"}, {"lat":"10.622100079463674","lng":"76.1424207687378"},{"lat":"10.604004340704408","lng":"76.14100456237793"},{"lat":"10.608644375798574","lng":"76.13735675811768"},{"lat":"10.624419968495433","lng":"76.13675594329834"},{"lat":"10.62436724394038","lng":"76.13685250282288"},{"lat":"10.624377788852131","lng":"76.13693833351135"},{"lat":"10.615815200680679","lng":"76.1367130279541"},{"lat":"10.601726479547619","lng":"76.13688468933105"},{"lat":"10.610500370131295","lng":"76.13244295120239"},{"lat":"10.631991120088175","lng":"76.13566160202026"}];

var features = [];

for (var i = 0; i < json.length; i++) {
  var lat = json[i]["lat"];
  var lng = json[i]["lng"];

  features.push({
    position: new google.maps.LatLng(lat, lng),
  });
}

features.forEach(function(feature) {
  var marker1 = new google.maps.Marker({
    position: feature.position,
    map: map
  });
});

Resources

Loops and iteration


Q:

How to flush all session in laravel

I need to flush all user sessions after a migration, but the session keep persists even after I had try

session()->flush();
Session::flush();

Any idea how should I remove all the session? will deleting all the files in storage/framework/sessions help?

A:

If you are using file based session then you have to delete all files from storage/framework/sessions & null remember_token field from users table


Q:

Solve for n in Compound Interest Formula

I would like to solve the compound interest formula
$$V = Pz^n + c\left(\frac{z^{n+1}-z}{z-1}\right)$$
for $n$. Or, given what I would like the final value to be, the amount I can save a year, an interest rate, and how much money I have to invest initially, I would like to find how long it would take to reach my goal.

A:

We have:
\begin{align*}
V &= Pz^n + c\left(\frac{z^{n+1}-z}{z-1}\right)\\
V(z-1) &= Pz^n(z-1) + cz^{n+1} - cz\\
V(z-1) &= Pz^{n+1} - Pz^n + cz^{n+1} - cz\\
V(z-1) + cz &= z^n(Pz - P + cz)\\
\frac{V(z-1) + cz}{(P+c)z - P} &= z^n\\
\ln(V(z-1)+cz) - \ln((P+c)z - P) &= n\ln(z),
\end{align*}
so
$$n= \frac{\ln(V(z-1)+cz) - \ln((P+c)z-P)}{\ln z}.$$
You can use logarithms base 10 (or any base) if you prefer.


Q:

Override Java version when building a Cordova project with gradle

I am trying to build a Cordova project using gradle as a build tool. In the Cordova project I have my own plugin that requires Java 1.7.
In the build.gradle that comes with Cordova the java version is 1.6.
build.gradle:
android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_6
        targetCompatibility JavaVersion.VERSION_1_6
    }
}

The build.gradle comes with a great big warning that says it is a generated file that should not be edited, the way to customize the gradle build step is - as I understand - to create a build-extras.gradle file.
I have created a build-extras.gradle file and tried the following:
android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

But it does not seem to work. I still get an error when I build my project.
Error:
> strings in switch are not supported in -source 1.6
>         switch (action) {
>                 ^   (use -source 7 or higher to enable strings in switch)

Can someone please help me figure out how to setup gradle to make this work?

A:

I've been trying to solve the same problem, and came here hoping to find an answer! Anyway, although there was no answer, your mention of build-extras.gradle put me on the right track, and the following now works for me...so thanks.
To begin with I thought I might as well try using the same syntax as you, so as to try to work out what was wrong. As far as I can tell it fails because the build-extras.gradle file is not magically merged into build.gradle, but is instead loaded and executed using the Gradle apply from approach. And since this happens before the android closure it is too early in the process, and those android values override our 'extra' values.
(I don't have time to delve more than I need to into Gradle or Groovy, so apologies if my terminology is not precise...)
However, I could get it to work if I used the postBuildExtras() method.
If you look at the bottom of the build.gradle file that is generated by Cordova you'll see that if such a method (i.e., postBuildExtras) exists on ext, then it gets called. Since this is the last thing in the configuration script then I guess the point of this method is that we can use it to override anything.
I therefore ended up with this as my build-extras.gradle:
ext.postBuildExtras = {
    android {
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_7
            targetCompatibility JavaVersion.VERSION_1_7
        }
    }
}

I actually had this working quite early in my investigations but kept trying other approaches since I suspect this technique will fail when we try to have multiple build-extras.gradle files -- which, given that we're both talking specifically about Cordova plugins, is very likely.
There is a technique that looks promising for plugins, which is to use the <framework> element in plugin.xml, but with this approach I could never get the plugin-specific module to load/import/whatever. I'll take another look at this when I get to plugin #2, but for now the technique described above gets me a big leap further on where I was this morning, so thanks again for the build-extras.gradle clue. ;)

A:

Regarding the answer of Mark, i got a solution to add the build-extras.gradle into the plugin.xml file. So it will be added automatically to the platform folder to the right place.
<source-file src="src/android/lib/build-extras.gradle" target-dir="src/.." />


Q:

Why does my CTE join update so much slower than my Table variable join?

I've seen a couple of similar threads, but they all seem to be about massive databases. I've created a dummy database to demonstrate the issue after seeing this crop up in a small live database this morning.
The basis for this data is as follows: a company keeps track of stock portfolios for its 100 clients. Each of 1000 stocks has a daily record that lists the four investors that own it, along with their percentage. Unfortunately, it has a glitch that allows for an owner to show up multiple times. The procedure parses the data and separates the records out so there are 4 records for each stock on each day, and it will then add up the portfolio total for each owner. However, because there are multiple records, that can overstate the value for that owner. So a flag is being inserted to identify any of these duplicates. Later in the code, the value of each line is multiplied by that flag, which is 0 for a duplicate and 1 if not.
I have five methods of updating that flag. I start with 0, which is just to use a CTE with a SELECT statement as a baseline; it takes about 0.07 seconds. 1 uses that CTE with a JOIN to update the table and takes about 48 seconds. 2 uses a nested select statement instead of the CTE and takes about 48 seconds. 3 dumps that CTE to a table variable and and joins to that and takes about 0.13 seconds. 4 I had thought would be the least efficient because it uses a counter loop and updates one row at a time, but it only took 0.17 seconds. 5 uses a CASE statement to update all rows, joined to a CTE, and takes about 48 seconds.
DECLARE @OwnRec TABLE (
      StockID           INT
    , TradeDate         DATE
    , Shares            DECIMAL(4,0)
    , Price             DECIMAL(4,2)
    , Owner1            INT
    , Owner1Pct         DECIMAL(3,2)
    , Owner2            INT
    , Owner2Pct         DECIMAL(3,2)
    , Owner3            INT
    , Owner3Pct         DECIMAL(3,2)
    , Owner4            INT
    , Owner4Pct         DECIMAL(3,2)
    )

DECLARE @OwnRec2 TABLE (
      RecID             INT IDENTITY
    , StockID           INT
    , TradeDate         DATE
    , Shares            DECIMAL(4,0)
    , Price             DECIMAL(4,2)
    , Owner0            INT
    , Owner0Pct         DECIMAL(3,2)
    , OwnerNum          INT
    , DupeOwner         TINYINT
    )

DECLARE @CullDupe TABLE (
      ID                INT IDENTITY
    , RecID             INT
    )

DECLARE   @Method       INT
        , @Counter1     INT = 0
        , @StartTime    DATETIME

--Populate tables with dummy data
WHILE @Counter1 < 1000
    BEGIN
        SET @Counter1 += 1
        INSERT INTO @OwnRec (
              StockID
            , TradeDate
            , Shares
            , Price
            , Owner1
            , Owner1Pct
            , Owner2
            , Owner2Pct
            , Owner3
            , Owner3Pct
            , Owner4
            , Owner4Pct
            )
        SELECT @Counter1
            , '2016-09-26'
            , ROUND((RAND() * 1000 + 500)/25,0)*25
            , ROUND((RAND() * 30 + 20),2)
            , ROUND((RAND() * 100 + .5),0)
            , CAST(ROUND((RAND() * 5 + .5),0)*.05 AS DECIMAL(3,2))
            , ROUND((RAND() * 100 + .5),0)
            , CAST(ROUND((RAND() * 5 + .5),0)*.05 AS DECIMAL(3,2))
            , ROUND((RAND() * 100 + .5),0)
            , CAST(ROUND((RAND() * 5 + .5),0)*.05 AS DECIMAL(3,2))
            , ROUND((RAND() * 100 + .5),0)
            , CAST(ROUND((RAND() * 5 + .5),0)*.05 AS DECIMAL(3,2))
    END

SET @Counter1 = 0

WHILE @Counter1 < 1000
    BEGIN
        SET @Counter1 += 1
        INSERT INTO @OwnRec (
              StockID
            , TradeDate
            , Shares
            , Price
            , Owner1
            , Owner1Pct
            , Owner2
            , Owner2Pct
            , Owner3
            , Owner3Pct
            , Owner4
            , Owner4Pct
            )
        SELECT @Counter1 + 1000
            , '2016-09-27'
            , Shares
            , ROUND(Price * ROUND(RAND()*10 + .5,0)*.01+.95,2)
            , Owner1
            , Owner1Pct
            , Owner2
            , Owner2Pct
            , Owner3
            , Owner3Pct
            , Owner4
            , Owner4Pct
            FROM @OwnRec WHERE StockID = @Counter1
    END

UPDATE orx
    SET Owner2Pct = Owner1Pct
        FROM @OwnRec orx
            WHERE Owner1 = Owner2

UPDATE orx
    SET Owner3Pct = Owner1Pct
        FROM @OwnRec orx
            WHERE Owner1 = Owner3

UPDATE orx
    SET Owner4Pct = Owner1Pct
        FROM @OwnRec orx
            WHERE Owner1 = Owner4

UPDATE orx
    SET Owner3Pct = Owner2Pct
        FROM @OwnRec orx
            WHERE Owner2 = Owner3

UPDATE orx
    SET Owner4Pct = Owner2Pct
        FROM @OwnRec orx
            WHERE Owner2 = Owner4

UPDATE orx
    SET Owner4Pct = Owner3Pct
        FROM @OwnRec orx
            WHERE Owner3 = Owner4

INSERT INTO @OwnRec2
    SELECT StockID, TradeDate, Shares, Price, Owner1 AS Owner0, Owner1Pct, 1, 1 AS Owner0Pct
        FROM @OwnRec
    UNION
    SELECT StockID, TradeDate, Shares, Price, Owner2 AS Owner0, Owner2Pct, 2, 1 AS Owner0Pct
        FROM @OwnRec
    UNION
    SELECT StockID, TradeDate, Shares, Price, Owner3 AS Owner0, Owner3Pct, 3, 1 AS Owner0Pct
        FROM @OwnRec
    UNION
    SELECT StockID, TradeDate, Shares, Price, Owner4 AS Owner0, Owner4Pct, 4, 1 AS Owner0Pct
        FROM @OwnRec
--END Populate tables with dummy data

SET @StartTime = GETDATE()

SET @Method = 5 -- Choose which method to test

--CASE 0: Just identify duplicates

IF @Method = 0
    BEGIN
        ; WITH CullDupe
            AS (
                SELECT RecID, ROW_NUMBER() OVER (PARTITION BY StockID, TradeDate, Owner0 ORDER BY OwnerNum) AS rn
                    FROM @OwnRec2
                )
        SELECT * FROM CullDupe WHERE rn > 1
    END

--CASE 1: Update on JOIN to CTE

IF @Method = 1
    BEGIN
        ; WITH CullDupe
            AS (
                SELECT RecID, ROW_NUMBER() OVER (PARTITION BY StockID, TradeDate, Owner0 ORDER BY OwnerNum) AS rn
                    FROM @OwnRec2
                )
        UPDATE OR2
            SET DupeOwner = 0
                FROM @OwnRec2 OR2
                    JOIN CullDupe cd
                        ON OR2.RecID = cd.RecID
                    WHERE rn > 1
    END

--CASE 2: Update on JOIN to nested SELECT

IF @Method = 2
    BEGIN
        UPDATE OR2
            SET DupeOwner = 0
                FROM @OwnRec2 OR2
                    JOIN (SELECT RecID, ROW_NUMBER() OVER
                        (PARTITION BY StockID, TradeDate, Owner0 ORDER BY OwnerNum) AS rn
                        FROM @OwnRec2) cd
                        ON OR2.RecID = cd.RecID
                    WHERE rn > 1
    END

--CASE 3: Update on JOIN to temp table

IF @Method = 3
    BEGIN
        ; WITH CullDupe
            AS (
                SELECT RecID, ROW_NUMBER() OVER (PARTITION BY StockID, TradeDate, Owner0 ORDER BY OwnerNum) AS rn
                    FROM @OwnRec2
                )

        INSERT INTO @CullDupe SELECT RecID FROM CullDupe WHERE rn > 1

        UPDATE OR2
            SET DupeOwner = 0
                FROM @OwnRec2 OR2
                    JOIN @CullDupe cd
                        ON OR2.RecID = cd.RecID
    END

--CASE 4: Update using counted loop

IF @Method = 4
    BEGIN
        ; WITH CullDupe
            AS (
                SELECT RecID, ROW_NUMBER() OVER (PARTITION BY StockID, TradeDate, Owner0 ORDER BY OwnerNum) AS rn
                    FROM @OwnRec2
                )

        INSERT INTO @CullDupe SELECT RecID FROM CullDupe WHERE rn > 1
        SET @Counter1 = 0
        WHILE @Counter1 < (SELECT MAX(ID) FROM @CullDupe)
            BEGIN
                SET @Counter1 += 1
                UPDATE OR2
                    SET DupeOwner = 0
                        FROM @OwnRec2 OR2
                            WHERE RecID = (SELECT RecID FROM @CullDupe WHERE ID = @Counter1)
            END
    END

--CASE 5: Update using JOIN to CTE, but updating all rows (CASE to identify)

IF @Method = 5
    BEGIN
        ; WITH CullDupe
            AS (
                SELECT RecID, ROW_NUMBER() OVER (PARTITION BY StockID, TradeDate, Owner0 ORDER BY OwnerNum) AS rn
                    FROM @OwnRec2
                )

        UPDATE OR2
            SET DupeOwner = CASE WHEN rn > 1 THEN 0 ELSE 1 END
                FROM @OwnRec2 OR2
                    JOIN CullDupe cd
                        ON OR2.RecID = cd.RecID
    END

SELECT 'Method ' + CAST(@Method AS NVARCHAR(1)) + ': ' + CAST(DATEDIFF(ms,@StartTime,GETDATE()) AS NVARCHAR(10)) + ' milliseconds'

A:

This is a common issue with table variables.
The execution plans for your statements referencing them are compiled before the batch even begins executing and thus before the insert statements have executed.
If you select one in one of your problem execution plans and look in the properties window you will see that the table cardinality is 0.

It still nonetheless assumes that 1 row will be emitted from the empty table as this is the minimum row estimate in most circumstances from a leaf operator in an execution plan. The sub tree on the inside of the nested loops is executed once for each row from the driving table. As this is estimated to be 1 row the highlighted sub tree below is estimated to be executed once. In fact the whole sub tree will be executed 8,000 times (including the expensive table scan and  sort operators).

When you materialise the result of the row numbering to a table variable you store the result of that subtree and thus ensure that this is only calculated once (though the plan using it still has a sub optimal nested loops join onto the new table variable).
Common solutions to the one row estimate are to add OPTION (RECOMPILE) to problem statements so that table cardinality at statement execution time can be taken into account, or use trace flag 2453 (which can trigger automatic recompiles after cardinality changes)
or use a #temp table instead (which can trigger automatic recompiles and additionally benefit from column statistics)
More details about some of this can be found in my answer here.


Q:

efficient way to union non-set iterables within groups

I have this df
df = pd.DataFrame(dict(
        A=['b', 'a', 'b', 'c', 'a', 'c', 'a', 'c', 'a', 'a'],
        B=[[0, 2, 3, 1],
           [9, 6, 7, 2],
           [6, 0, 1, 4],
           [9, 2, 5, 1],
           [5, 1, 4, 8],
           [8, 5, 6, 6],
           [0, 9, 0, 0],
           [2, 6, 1, 8],
           [7, 3, 2, 6],
           [8, 7, 1, 9]]
        ))

I want to group by 'A' and union all the lists in 'B'
Neither df.groupby('A').B.union() nor df.groupby('A').B.apply(set.union) work.
I want the result to be
A
a    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
b                {0, 1, 2, 3, 4, 6}
c                {1, 2, 5, 6, 8, 9}
Name: B, dtype: object

A:

The problem is that you need to cast them as sets first before applying the union. One solution would be to use sum to concatenate the groups, then cast to set using map
In [28]: df.groupby('A').B.sum().map(set)
Out[28]:
A
a    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
b                {0, 1, 2, 3, 4, 6}
c                {1, 2, 5, 6, 8, 9}
dtype: object


Q:

Trouble passing clicked value (PHP) to ajax function

I'm having trouble passing the value of the clicked element into an ajax function. Below is the ajax function.
// Get values from all three dropdown menus
        var state = $('#states').val();
        var status = $('#status').val();
        var services = $('#services').val();
// Get value from clicked element
        var pagedtest = pagednum;

function do_ajax() {
            $.ajax({
                url: ajaxurl,
                data: {
                    'action' : 'json_info2',
                    'state' : state,
                    'status' : status,
                    'services' : services,
                    'pagedtest' : pagedtest
                },
                success:function(moredata) {
                    // This outputs the result of the ajax request
                    $('#project-list').html( moredata );
                    $('#project-list').fadeIn();
                }/*,
                error: function(errorThrown){
                    var errorMsg = "No results match your criteria";
                    $('#project-list').html(errorMsg);
                }*/
            }); // end of ajax call
        } // end of function do_ajax

Then let's say I have a series of  tags that are each assigned a title dynamically, like this:
90
87
102

And I'm trying to run the following code in my php page in order to pick up the clicked value to pass to ajax.
$(".page-link").click(function() {
      var pagednum = $(".page-link").val($(this).attr('title'));
      return false;
});

When I click one of the links, nothing happens. Where am I going wrong?
How can I pass the value of the title attribute, of the clicked tag, when the ajax function runs?

A:

Try this:
 $(".page-link").click(function() {
       var pagednum = $(this).attr('title');
 });

Also, ensure your anchor tags have href attributes.


Q:

git export from github remote repository

I'd like to export from github remote repository, not cloning it. Similar to svn export, I do not want to get .git folder with it. I can work around it by cloning and removing .git folder. I wonder if there is a cleaner way?
I read it somewhere you can use git archive to achieve this.
However I got the following errors..
$ git archive --format=tar --remote=git@github.com:xxx/yyy.git master | tar -xf -

Invalid command: 'git-upload-archive 'xxx/yyy.git''
You appear to be using ssh to clone a git:// URL.
Make sure your core.gitProxy config option and the
GIT_PROXY_COMMAND environment variable are NOT set.
fatal: The remote end hung up unexpectedly

Any help would be great. Thanks.

A:

Thanks to the Subversion support by GitHub, you can use svn export to get the project without any version control files:
svn export https://github.com/user/project/trunk

Notice the URL format:

The base URL is https://github.com/
USERNAME/PROJECTNAME without .git
/trunk appended at the end

This way you can get branches and subdirectories too.
This creates a directory with the exported files. It's not possible to create a tar/zip directly, you have to do in two steps (export + zip). This is a limitation of svn export itself.
As @Jon pointed out, this will create the export in a directory named trunk by default. You can specify a different name if you prefer:
svn export https://github.com/username/projectname/trunk projectname

You can use this technique to export any sub-directory of the project.
For example if you want only some/path, you can do:
svn export https://github.com/username/projectname/trunk/some/path local-dir-name

You can get paths from branches and tags too. The endpoint https://github.com/username/projectname behaves fully as a Subversion repository with a regular layout, so you will find branches in https://github.com/username/projectname/branches and tags in https://github.com/username/projectname/tags.
Before you export something large by mistake, it's good to check first the content of the path. You can do that using svn ls, for example:
svn ls https://github.com/username/projectname/

Normally this should give you:
branches/
tags/
trunk/

You could iteratively explore the repository this way.

A:

For unknown (to me at least) reasons GitHub doesn't support this.
We don’t support people running git-archive against our servers.

Seems silly, since via SVN you can, but... I upvoted @Janos' answer.

A:

If you're only interested in exporting from GitHub then they provide a mechanism to download tarballs. For example:
https://github.com/torvalds/linux/downloads
Even though it says "there aren't any downloads for this repository." you can still use the buttons to download a tarball of the master branch.
Or see this link for a list of tarballs linked to tags:
https://github.com/torvalds/linux/tags
This should work for any GitHub repo, not just the linux kernel.


Q:

How to get image src url in source code with xpath in python

So, i'm developing a program to download some images from sites, and i have to somehow get the "src" part of the img tag.
I was able to do this with selenium, but i had to adapt the code and now i'm using BeautifulSoup4 and lxml.
I currently have the whole source code of the page (site) in a variable "mystr", and i wanted to give an xpath and find that xpath inside that variable? Is it possible? (probably)
The reason i'm posting this question is because i can't seem to parse the variable to lxml and use it's function .xpath()
--READ FOR MORE CONTEXT OF THE PROBLEM--
I'm reading some data from an excel file (reference values and url's), i want to open the url, download the product image, and rename it for it's reference.
I can do this with multiple images, but when the url only has 1 image, i wanted to go with the xpath to download the image and i didn't want to use selenium again.
Thanks in advance.
I think this is the part of the code that matters for this question.
try: #Extrair o html
    fp = urllib.request.urlopen(links[i])
    mybytes = fp.read()
    mystr = mybytes.decode("utf8")
    fp.close()
except Exception as ex: #Exceção do html
    print("Não foi possivel extrair o HTML deste url")
    erros.append(i)
    continue
try: #Passar para Beautiful soup 4
    soup = BeautifulSoup(mystr, "lxml")
    #print(mystr, file = open("teste.txt", "a"))
except Exception as ex: # Exceção do Beautiful soup 4
    print("Não foi possivel converter o HTML para bs4\n\n" + ex)
    erros.append(i)
    continue
try: #Navegar até ao DIV dentro do html extraido
    main_div = soup.find_all("div", {"id": div_id})
    if len(main_div) == 0:
        parser = etree.HTMLParser()
        tree = etree.parse(mybytes, parser)
        #print(tree, file=open("tree.txt", "a"))
        #image = tree.xpath('//*[@id="image"]')
        image = tree.xpath("/html/body/div[1]/div/div/div/div[1]/div[1]/div[1]/a/img")
        print(image[0].tag)
        #input("--------------------------------------------------")
except Exception as ex: #Exceção se não existir um div dentro do HTML extraido com o ID fornecido
    print("Não existe nenhum DIV com o id fornecidon\n\n" + ex)
    erros.append(i)
    continue

A:

One BeautifulSoup way:
img_src=soup.find("img")["src"]

One lxml etree way:
img_src=tree.xpath('//img')[0].attrib.get('src')


Q:

Get dimensions programmatically

I am writing an Android application with Xamarin.Android. I am trying to get the dimensions programmatically like this:
float dim = Resources.System.GetDimensionPixelSize(Resource.Dimension.my_dim);

And I get this error:

Android.Content.Res.Resources+NotFoundException has been thrown

But I see on other questions on SO that this should work...any idea why it wouldn't?

A:

I am not familiar with Xamarin.Android, only standard Android, but I believe that this will still answer your question.
The Resources.getSystem() call (which I assume is the equivalent of your Resources.System property) returns a Resources object that can only access system resources. This Resources object cannot access application resources or resources that depend on the screen and/or screen configuration... including dimensions.
From the stock Android documentation:

Return a global shared Resources object that provides access to only system resources (no application resources), and is not configured for the current screen (can not use dimension units, does not change based on orientation, etc).

You will need to get your hands on a Resources object in some manner other than Resources.System if you want to access dimensions. If you have a Context object, you can use the Resources public property of the context.


Q:

Render alternate component in Visualforce for $Permission

I am attempting to present an alternate message to a user if they do not have a particular Custom Permission assigned to them.
<apex:form>
    <apex:pageBlock rendered="{!$Permission.Allow_This}">
        <apex:outputText>Click this button to do something</apex:outputText>
        <apex:commandButton value="Click Me!" action="{!clickButton}" />
    </apex:pageBlock>
    <apex:pageBlock rendered="!{!$Permission.Allow_This}">
        <apex:outputText>You do not have the necessary permissions to even see the button, let alone click it.</apex:outputText>
    </apex:pageBlock>
</apex:form>

It seems like $Permission only return true or null. If the custom permission is assigned to the User, you can render or not render based on $Permission. However if the custom permission is not assigned, neither pageBlock renders.
Is there a way to render a component only if a user does not have a particular Custom Permission assigned to them?

A:

No. $Permission returns true or false, but never null. The problem was that your NOT operator was in the wrong place:
<apex:form>
    <apex:pageBlock rendered="{!$Permission.Allow_This}">
        <apex:outputText>Click this button to do something</apex:outputText>
        <apex:commandButton value="Click Me!" action="{!clickButton}" />
    </apex:pageBlock>
    <apex:pageBlock rendered="{!!$Permission.Allow_This}">
        <apex:outputText>You do not have the necessary permissions to even see the button, let alone click it.</apex:outputText>
    </apex:pageBlock>
</apex:form>

Everything you wish to evaluate must be between the {! and }, as everything outside of it would be treated literally. !{!$Permission.Allow_This} would render as the literal strings !true and !false. Visualforce treats any non-empty string that is not exactly false as a true value, and empty strings as a false value.
For readability, I prefer to write it as:
rendered="{!NOT($Permission.Allow_This)}"