text:
Q: Cohomology ring of a projective variety Let $X$ be a projective variety with ample sheaf $\mathcal{O}_X(1)$. Then $H^*(\oplus_n \mathcal{O}_X(n))$ is a graded algebra via the cup product: $H^i(\mathcal{O}(n)) \otimes H^j(\mathcal{O}(m)) \to H^{i+j}(\mathcal{O}(n) \otimes \mathcal{O}(m)) \cong H^{i+j}(\mathcal{O}(n+m))$. Remark that each individual homogeneous component is a graded abelian group (via $n$). Does this "bigraded" cohomology ring have a name, and is it studied in the literature?
If $X,Y$ are projective varieties such that the corresponding "bigraded" cohomology rings are isomorphic, do we then have $X \cong Y$? If this is false, what about the special case $Y=\mathbb{P}^d$ (here the cohomology ring is quite simple).

A: If I understand your construction correctly, the bi-graded algebra is
$$ \oplus_{i,j} H^i(X, O_X(j))$$
and the component of degree $(i,j)$ is $H^i(X, O_X(j))$. So if an isomorphism
$$ \oplus_{i,j} H^i(X, O_X(j)) \simeq \oplus_{i,j} H^i(Y, O_Y(j))$$
of bi-graded algebras is required to preserve bi-degrees, hence induces linear isomorphisms
$$ H^0(X, O_X(j))\simeq  H^0(Y, O_Y(j))$$
then
$$X\simeq \mathrm{Proj}\left(\oplus_{j\ge 0} H^0(X, O_X(j))\right)
\simeq \mathrm{Proj}\left(\oplus_{j\ge 0} H^0(Y, O_Y(j))\right) \simeq Y.$$


text:
Q: How to assign value of SQL query to a MySQL table column I have two MySQL tables, g734 and g8internal. I ran an SQL SELECT query given below in which I would like to put the result of the query to the Maths field and Total_Score field in table g8internal. The fields in g734 and g8internal are uniform. They are StudentID, FirstName, LastName, Maths and Total_Score. Please have a look at my SQL code below. The one I have is giving SQL syntax error in phpMyAdmin. I would like to store the result of the query to Total_Score and Maths in g8internal.
SELECT StudentID, FirstName, LastName, SUM(Total_Score) AS T_Score, SUM(Maths) AS Mth
FROM
(
SELECT StudentID, FirstName, LastName, Total_Score, Maths FROM g734
   UNION ALL
SELECT StudentID, FirstName, LastName, Total_Score, Maths FROM g8internal
) t on g8internal.FirstName = g734.FirstName AND g8internal.LastName = g734.LastName
GROUP BY StudentID, FirstName, LastName
SET g8internal.Total_Score = T_Score,
g8internal.Maths = Mth

A: Try the query like this and see if it works. And i dont think you need to join with FirstName and LastName if Student Id works as key.
update
g8internal g8int
join
(
    select
      t.StudentID,
      t.FirstName,
      t.LastName,
      SUM(t.Total_Score) AS T_Score,
      SUM(t.Maths) AS Mth
    from
      (

        SELECT
          StudentID,
          FirstName,
          LastName,
          Total_Score,
          Maths
        FROM
          g734

        UNION ALL

        SELECT
          StudentID,
          FirstName,
          LastName,
          Total_Score,
          Maths
        FROM
          g8internal
      ) t
    group by
      t.StudentID,
      t.FirstName,
      t.LastName
) t1 on g8int.StudentID = t1.StudentID
          and g8int.FirstName = t1.FirstName
          and g8int.LastName = t1.LastName
set
    g8int.Total_Score = t1.T_Score,
    g8int.Maths = t1.Mth

Reference : MySQL - UPDATE query based on SELECT Query
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to determine version of http in get html? I want to request a server by 'get' and I use this method:
http://smarttracking.ir/gprmc_receiver.php?strVar=27,0,146,1,$GPRMC,213659.000,A,3238.0007,N,05118.5837,E,36.74,274.01,170114,,,N*6A5,username1,64,5}
If you copy this in the address bar on your browser, you will get a response. But there is a problem for me. I send this by sim900 module and it doesn't support http 1.0 or 1.1 and it is less than 1 so I need to send http version by address bar if it is possible. Something like this:
http://smarttracking.ir/gprmc_receiver.php?id=1 http/1.1 strVar=27,0,146,1,$GPRMC,213659.000,A,3238.0007,N,05118.5837,E,36.74,274.01,170114,,,N*6A5,username1,64,5}

A: Open a socket from the sim900 module to  http://smarttraking.it and send a http request in according to the standard. The format of http request offers the possibility to specify the http version.
Look this image:
format http request


text:
Q: Can htpasswd be used to restrict access to a URL rather than a specific folder? I would like to restrict access to certain URLs with htpasswd files, rather than folders, is this possible? For example, I wish to restrict the URL:
www.example.com/pages/id/227/Restricted_Page

But allow access to other URLs such as:
www.example.com/pages/id/100/Normal_Page

Is this possible? The "pages" part of the url refers to a pages.php file, and the "id" part is the function name in that file.
The reason for wanting to do this is because of migrating existing restrict lists, in the form of htpasswd files from another site.
Many thanks.

A: From the docs:
Require Directive

Description:  Selects which authenticated users can access a resource
Syntax:       Require entity-name [entity-name] ...
Context:      directory, .htaccess
Override:     AuthConfig
Status:       Core
Module:       core

"directory" context means that you can put it in <Directory>, <Location>, <Files>, and <Proxy> sections. So, yes.


text:
Q: Choosing an image from gallery with espresso I've been reading into espresso but there aren't many resources available to learn the complex operations. I have an activity where you click an imagebutton and takes you to your library where you can choose a picture, and that picture is displayed in an imageview in that same activity.
How would you ask espresso to choose any picture in my gallery and then making sure it's displayed in the image view?


text:
Q: remove duplicate from combo box connected to database I am trying to remove duplicates from a Combobox, however, this doesn't seem to result in a correct Combobox, since he fills the Combobox with the following text:
System.Linq.Enumerable+<DistinctIterator>d__64`1[System.Char]

I have the following code and am using an access database with generated datasets.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Linq.Expressions;

namespace Generator
{
        private void matGroupBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.matGroupBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.matGroupDataSet);
        }
        private void frmImport_Load(object sender, EventArgs e)
        {
            this.matGroupTableAdapter.Fill(this.materialGroupDataSet.MatGroup);

            //Distinct
            var BaseM = materialGroupDataSet.MatGroup.Select(row => row["BaseMs"].ToString().Distinct());
            foreach (var BaseMs in BaseM)
            {
               cmbBaseMat.Items.Add(BaseMs);
            }

        }

I have 3 Comboboxes that I want to fill with data from the database. The ComboBox1 is filled with data and then it removes the duplicates correctly.
However, when I select a value from the ComboBox1, it will update the ComboBox2 with the possible choices based on the ComboBox1 and if I select a value from the ComboBox2 it fills the ComboBox3 with resulting data.
I'm now first trying to filter out the duplicates.

A: Here is the solution i found.

cmbBaseMat.DataSource = materialGroupDataSet.MatGroup.Select(x => x.BaseMs).Distinct().ToList();

If anyone has a better solution please post it.


text:
Q: Does Solr 7.x have support for Java 11? Currently our applications runs with Spring Data Solr + Apache Solr 5.3 + Java 8
We are upgrading our systems to Java 11. Does Spring Data Solr & Apache Solr latest version support Java 11 ?

A: Solr 7.6 supports "Java 8 or greater". However . . . .

*

*As per the Solr News it looks like 10 is tested and supported

*Java is generally backwards compatible although Java 11 release notes might suggest has some backwards compatibility issues that might trip folks up in general

*This ticket  in the Solr Apache JIRA indicates that "Upgrading to a more recent Java (JDK 11?)" is open and unresolved

*More definitively: As of late 2018, Java 11 was not yet recommended according to the good folks at LucidWorks. "The recommendation is to stay with JDK-8 until the Apache project officially supports JDK-11."

Based on the above it sounds like Java 8 is the safe bet, 10 might work but is risky and 11 is "right out" (h/t to Monty Python and the Holy Grail)


text:
Q: Autorelease in Objective C and Convenience Methods So I am a bit confused on when objects are autoreleased. I understand so far that if I am not the "owner", it will do so. But in which cases would I not be the owner? When I create an object using a convenience method? I don't understand where all these convenience methods are coming from and how would you create them.

A: You generally use alloc + an initializer to create objects that will not be autoreleased. Instead you use static methods to get autoreleased instances. Example:
NSString* string1;
NSString* string2;
@autoreleasepool{
    string1= [NSString stringWithString: @"Hello"];
    string2= [[NSString alloc] initWithString: @"Hello"];
}
// string1 isn't alive, string2 is alive

You must also pay attention to singletons. In case of singletons, they're not autoreleased but you don't own them. Often you understand from the name of the method is it returns a singleton or not (eg: something like sharedInstance or mainThread).


text:
Q: A residue formula Does anybody know of a succint way to compute the residue of $f(z)=z^m/(1-e^{-z})^{n+1}$ at $z=0$? I am only interested in the nontrivial case $m<n$.
Induction seems complicated/inefficient, so I am looking for a "trick", perhaps with Lagrange inversion?

A: You can use Taylor series for denominator and then divide them to obtain the residue. The process is like division of polynomials. Of course you should be aware whether $m\le n$ or $m\ge n$.

A: Notice that (use L'Hospital)
$$\lim_{z\to0}\frac{z^m}{(1-e^{-z})^n}=0\ \forall\ m>n$$
$$\lim_{z\to0}\frac{z^m}{(1-e^{-z})^n}=1\ \forall\ m=n$$
and thus the residue is $0$ in these cases.
Whenever $m<n$, I think you would have to use a series method with long division and such.


text:
Q: Run build and tests in dockerfile vs on CI? the fastest way to run tests on CI is ./gradlew test or ./gradle build. it will download all the necessary dependencies (which can be somehow cached on CI), run tests and produce artifact (jar file)
i also want to build a docker image. some of the options i considered:

*

*build docker image on CI and assume that artifact is already there. it's the fastest way but ties the building process to CI. it can't be just build manually with 1 command (docker build)

*run tests as part of docker build. on CI it takes more time before i get info about failing test (as it has to download image, dependencies etc). but it allows to easily build the docker locally (probably rarely used functionality but useful for local docker-compose for tests)

*parameterized build to disable / enable tests by default
what's the standard way of handling those requirements? any best practices?

A: Build the application you want to deploy in your Dockerfile.  Don't include test-only dependencies, IDEs, source control tools, or anything else: include the minimum set of things you need to actually run your application and nothing more.  Don't bother trying to run tests in the Dockerfile: it is only a packaging step, and you should have run tests prior to this point.
Write good local tests (in Java land, for instance, using JUnit) and make sure they pass.  If you need "white-box" integration tests that both depend on code details and external services, run them locally or in your CI system, but outside of Docker.
Minimize the differences between "production" and "developer" setups.  Ideally there are no code changes at all, and the only configuration changes are things like database hostnames.
Run full end-to-end tests using your Docker-based setup.  This step might involve running Docker Compose in Jenkins (slightly hairy).  It is a "black-box" test that communicates only with the service's UI or external APIs.  The tests may or may not live in the source tree, but they aren't built into the Docker container.  It might be easier to launch tools like Selenium outside of Docker space too, judging from the number of SO questions on getting that set up.


text:
Q: Symmetric BCS state The ground state wavefunction for the BCS can be written $$|\Psi_{G}\rangle\equiv\prod_{\textbf{k}}[u_{k}+v_{k}c_{\textbf{k}1}^{+}c_{\textbf{-k}-1}^{+}]|\phi_{0}\rangle,$$ where $|\phi\rangle$ denotes the vacuum, $|u_{k}|^{2}+|v_{k}|^{2}=1$ and $c,c^{+}$ are the usual creation and annihilation operators in second quantization. Also, $1\equiv$ up spin, and $-1\equiv$ down spin. This wavefunction is not manifestly invariant under rotation of spin. However, we know we must be able to write it that way, in singlet form, for instance. Is there a convenient way to arrive to such an expression?

A: Choose a single value of $\mathbf{k}$, and consider the product of the $\mathbf{k}$ and $-\mathbf{k}$ factors. (All of the factors in the product can be paired this way.) The linear-in-$v$ term involves
$$
 c^+_{\mathbf{k},1}c^+_{-\mathbf{k},-1}
 +
 c^+_{-\mathbf{k},1}c^+_{\mathbf{k},-1}.
$$
Use the fact that the creation operators anticommute to rewrite this as
$$
 c^+_{\mathbf{k},1}c^+_{-\mathbf{k},-1}
 -
 c^+_{\mathbf{k},-1}c^+_{-\mathbf{k},1},
$$
which is manifestly invariant under rotation of spin because it's antisymmetric under the exchange of spins $1$ and $-1$. The $v^2$ term involves
$$
 c^+_{\mathbf{k},1}c^+_{-\mathbf{k},-1}
 c^+_{-\mathbf{k},1}c^+_{\mathbf{k},-1}.
$$
Use the fact that the creation operators anticommute to see that this is proportional to
$$
 (c^+_{\mathbf{k},1}
 c^+_{\mathbf{k},-1})
 (c^+_{-\mathbf{k},1}
 c^+_{-\mathbf{k},-1}).
$$
Each factor in parentheses is antisymmetric under the exchange of spins $1$ and $-1$, so this is again manifestly invariant under rotation of spin. The $u^2$ term doesn't involve spin at all, so we're done.


text:
Q: Strange output when using SemaphoreSlim to lock the method I have a pretty simple console application to test the feature of SemaphoreSlim .
class Program
{
    private static readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
    private static int _counter = 0;
    static async Task Main(string[] args)
    {
        var tasks = new List<Task>();
        for (var i = 1; i <= 1000; i++)
        {
            tasks.Add(Task.Factory.StartNew(async () => await IncCountWithDictLock("10"))); ;
        }
        await Task.WhenAll(tasks);
        Console.WriteLine(_counter);
    }

    public static async Task IncCountWithDictLock(string userId)
    {
        _locks.TryAdd(userId, new SemaphoreSlim(1, 1));
        var l = _locks[userId];
        var acuireLockRequire = await l.WaitAsync(TimeSpan.FromSeconds(5));
        if (acuireLockRequire)
        {
            _counter++;
            l.Release();
        }
        else
        {
            Console.WriteLine("unable acquire the lock");
        }

    }
}

I expect the result of counter is 1000 while it is randomly. Did I miss anything when using the SemaphoreSlim?

A:
The lambda in the Task.Factory.StartNew is actually not being awaited.
  See details

You may replace the calling method
tasks.Add(Task.Factory.StartNew(async () => await IncCountWithDictLock("10")))

with
tasks.Add(Task.Run(async () => await IncCountWithDictLock("10")));


text:
Q: list index out of range.split on input? i'm running into "out of range" while hitting enter and imputing single words. I understand why they are out of range, i just can't find how to fix the issue. this is my code:
commands = {
'help': help,
'exit': exit,
'look': look,
'stats': thePlayer.printStats,
's':thePlayer.move_South}

def runCmd(cmd, args, player):
    commands[cmd](args, player)

def help(args):
    print(commands)

def play():
    main1()
    World.loadTiles()
    #These lines load the starting room and display the text
    room = World.tileExists(player.locationX, player.locationY)
    print(room.introText())
    while player.isAlive():
        room = World.tileExists(player.locationX, player.locationY)
        room.modifyPlayer(player)
        # Check again since the room could have changed the player's state
        if player.isAlive():
            print("\nHp:%d\%d  Mp:%d\%d\n"%(player.hp,player.maxHp,player.mp,player.maxMp))
            print(room.printEnemy())
            availableActions = room.availableActions()
            for action in availableActions:
                print(action)
            actionInput = input('Action: ')
            action = actionInput.lower()
            action = action.split()
            print(action)
        if action[0] in commands:
            runCmd(action[0],action[1], player)

i realize i'm not passing an "action[1]" and that just hitting enter isn't in "commands" causing my error. i'm new to coding so creating a game is how i'm teaching myself.
i'm trying to get to where i can type:   enter, single word (help, stats), double words (look rat), other things with more words ( buy big sword) and so on. any help on how i can code this correctly?

A: How about testing
len(action)

before calling runCmd? Thus, you can know if there are one word, two words, or more than two words.
If there is only one word, you can call:
runCmd(action[0], None, player)

If there are two words, you can call your current function. If there are more  than two words, it's a bit tricky. You can pass the whole action variable. Then, the called function has to know how many parameters it needs.


text:
Q: What is the conventional way of defining macros in main.c that are needed in other header files? For example I have a can.h header file that contains
   #ifdef MC
    extern int speed;
    // many more variables and function prototypes
   #endif

EDIT: I would want an option for the user to define MC that enables such variable and function prototypes. It is to be defined in C main alongside include directives (e.g. #define MC) however, other header files cannot link to main.c. Instead, i ended up defining such macros in can.h header itself. All i can think is writing a main.h too where can.h will include main.h. are there other ways to go around this problem?

A: It's not entirely clear to me what you are trying to do, but perhaps you want this:
/* in file can.h */
extern int speed;

and then
/* in file main.c */
#include "can.h"

int speed;

The header can.h just declares the existence of speed so that other modules can refer to it as an external symbol. The storage for this object is then allocated in main.c, when you write the the definition of speed.

A: You can either create a configuration header that has all the macros that you want defined and #include it in every header, or you can define configuration macros on the command line.

A: Use #include - Then you get those bits that you require

A: Inclusion is simply file content insertion by the preprocessor, anything declared or defined prior to inclusion will be defined in the include file.  So:
#define MC
#include "can.h"

While that achieves what you have asked, I would not necessarily recommend it however, and might question the design.

A: You can have such macro added at your project level.
Such macro are also known as Preprocessor definitions. Visual studio provides such definition in project settings/configurations..
So you can have it added there and compile the solution for including mentioned declarations or remove it if you don't want to include it.
Adding the screen shot.


text:
Q: Apply a limit on joining table in mysql I have two tables users and queries. users can post multiple queries.
MySQL Table Schema :-
CREATE TABLE `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `email` varchar(100) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `queries` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `address` text,
  `city` varchar(100) NOT NULL,
  `state` varchar(100) NOT NULL,
  `zipcode` int(11) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

I want to apply limit on it that query fetch 5 queries from queries table for each user.
How should I write query for this?

A: try it-
SELECT x.*
FROM (SELECT t.user_id,t.id,
               CASE
                 WHEN @category != t.user_id THEN @rownum := 1
                 ELSE @rownum := @rownum + 1
               END AS rank,
               @category := t.user_id AS var_category
          FROM queries t
          JOIN (SELECT @rownum := NULL, @category := '') r
      ORDER BY t.user_id,t.id) X
      WHERE x.rank<=5


text:
Q: PHP Generated CSV File filled with html crap from webhost instead of data? I am using PHP to generate a csv file with a first name and second name.
On my local XAMPP server it works fine and generate this output.
Andy,Murray
Sarah,Palin
Bob,Saget

However on this 000webhost.com free webhosting site I get the following output.

PHP Error Message

Warning:  array_walk() [function.array-walk]: The argument should be an array in /home/a2806375/public_html/csv.php on line 15

Free Web Hosting

This is my code:
function outputCSV($data)
        {
            $outstream = fopen("php://output", "w");

            function __outputCSV(&$vals, $key, $filehandler)
            {
                fputcsv($filehandler, $vals); // add parameters if you want
            }
            array_walk($data, "__outputCSV", $outstream);
            fclose($outstream);
        }

        $result = $db->fetch_array($result);

        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=guestlist.csv");
        header("Pragma: no-cache");
        header("Expires: 0");

        outputCSV($result);

Why is it doing this?
Is it because its a free hosting site and they are trying to put advertising in a CSV file?
How do I work around, I am a bit low on money atm so I cant afford a paid server.
Thanks

A: Disable the insertion of their analytics code from their control panel:
http://members.000webhost.com/analytics.php
From: http://www.000webhost.com/forum/faq/7894-faq-frequent-ask-questions-guide.html


text:
Q: MySQL Foreign Key constraint error - Failed to add foreign key constraint - error 1822 Any help would be greatly appreciated.
I have two tables, "Employee" and "EventPlan".
For the Create table EventPlan table, when I try to create the table, it is giving me an error in MySQL workbench:

Error 1822 - Failed to add the foreign key constraint. Missing index
  for constraint "EmpNo" in the referenced table "employee".

You will see in both tables "EmpNo" is included. But I cannot see what I am doing wrong. Please see code below.
I cannot execute or create the "EventPlan" in My SQL workbench.
I have reviewed both tables, also made the coloumns unique, but cannot find the issue.
EVENT PLAN TABLE
CREATE TABLE Eventplan
( PlanNo VARCHAR(8) NOT NULL,
EventNo VARCHAR(8) UNIQUE NOT NULL,
Workdate DATE,
Notes VARCHAR(8),
EmpNo VARCHAR(8) ,
CONSTRAINT PK_PlanNo PRIMARY KEY(PlanNo),
CONSTRAINT EventNo FOREIGN KEY (EventNo)
REFERENCES Eventrequest(EventNo),
CONSTRAINT EmpNo FOREIGN KEY (EmpNo)
REFERENCES Employee(EmpNo)
);

EMPLOYEE TABLE
CREATE TABLE Employee
(EmpNo VARCHAR(200) UNIQUE NOT NULL,
EmpName VARCHAR(200) NOT NULL,
Department VARCHAR(50) NOT NULL,
Email VARCHAR(20) NOT NULL,
Phone VARCHAR(20) NOT NULL,
CONSTRAINT PKEmployee PRIMARY KEY(EmpNo)
);

A: Your code works fine
MariaDB [test]> drop table if exists employee;
Query OK, 0 rows affected (0.04 sec)

MariaDB [test]> CREATE TABLE Employee
    -> (EmpNo VARCHAR(200) UNIQUE NOT NULL,
    -> EmpName VARCHAR(200) NOT NULL,
    -> Department VARCHAR(50) NOT NULL,
    -> Email VARCHAR(20) NOT NULL,
    -> Phone VARCHAR(20) NOT NULL,
    -> CONSTRAINT PKEmployee PRIMARY KEY(EmpNo)
    -> );
Query OK, 0 rows affected (0.09 sec)

MariaDB [test]> CREATE TABLE Eventplan
    -> ( PlanNo VARCHAR(8) NOT NULL,
    -> EventNo VARCHAR(8) UNIQUE NOT NULL,
    -> Workdate DATE,
    -> Notes VARCHAR(8),
    -> EmpNo VARCHAR(8) ,
    -> CONSTRAINT PK_PlanNo PRIMARY KEY(PlanNo),
    -> #CONSTRAINT EventNo FOREIGN KEY (EventNo)
    -> #REFERENCES Eventrequest(EventNo),
    -> CONSTRAINT EmpNo FOREIGN KEY (EmpNo)
    -> REFERENCES Employee(EmpNo)
    -> );
Query OK, 0 rows affected (0.13 sec)

MariaDB [test]> select table_name from information_schema.tables where table_name in('employee','eventplan') and table_schema = 'test';
+------------+
| table_name |
+------------+
| employee   |
| eventplan  |
+------------+
2 rows in set (0.02 sec)

If you are still having errors then it's not from here.


text:
Q: Swift segue from CollectionViewCell failing to display new view I'm trying to simply load up a new view when a cell in my CollectionView is selected.
Everywhere online says it's as simple as registering a new view and a navigation controller in the storyboard, and then Ctrl + click dragging from my CollectionViewCell to the new view.
Having done this, the code compiles and runs, but no new view appears when I click on my cells. What have I missed?
The storyboard says there is a segue from CollectionView to my next view (identified with the correct name and all), so I'm a bit confused...
Edit: here is my CollectionView controller code, in case I've done something in here that's causing the problem. It's a calendar page (as you can probably tell from the code):
IBOutlet weak var calendarCollection: UICollectionView!
var collectionView: UICollectionView?
let calendarCellIdentifier: String = "calendarCell"

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 50, left: 10, bottom: 10, right: 10)
    layout.itemSize = CGSize(width: 60, height: 60)
    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView!.dataSource = self
    collectionView!.delegate = self
    collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: calendarCellIdentifier)
    collectionView!.backgroundColor = UIColor.blackColor()
    self.view.addSubview(collectionView!)
}

// Return the collectionView cell at IndexPath
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(calendarCellIdentifier, forIndexPath: indexPath) as UICollectionViewCell
    cell.backgroundColor = UIColor.blueColor()
    return cell
}

func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return challengeDurationDays
}

A: I had similar troubles with a CollectionView (using Xcode 6.1.1 for an iOS 8 app).  I setup a segue in my storyboard from the selection of the CollectionViewCell to another ViewController, but it would not work automatically when the cell was touched.  Further, I subclassed the CollectionViewCell, set the class of the cell in my storyboard to my custom class (MazeCollectionViewCell), and established IBOutlets in my class connected to an image and a label I placed in the storyboard cell.  However, when I tried to access the image and/or label in the collectionView cellForItemAtIndexPath method, they were nil.
All my problems were solved when I removed the registerClass call from my viewDidLoad method [in my case, I removed collectionView!.registerClass(MazeCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)].  That's it!
My guess is that the registerClass call caused the CollectionViewController to create a blank copy of the class I specified and to ignore the template in the storyboard (thus my segue and my outlet connections were not valid in the cells being created for the collection).
If anyone has further insight, I'd love to hear it, but that's the solution that worked for me.

A: For anyone with similar problems, I solved this by manually triggering the segue using the didSelectItemAtIndexPath method.  I don't think I should have had to do this, but perhaps I misunderstood.  Either that or it's a bug.  The method I added to CollectionViewController in the end looks like this:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    performSegueWithIdentifier("dayViewSegue", sender: calendarCollection)
}


text:
Q: SQL Server CE error - only on compiled code I have a strange error which causes my application to crash. It only happens when compiled and installed via a click-once and not when debugging in Visual Studio.
Viewing the event log gives me this:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Windows Error Reporting" />
    <EventID Qualifiers="0">1001</EventID>
    <Level>4</Level>
    <Task>0</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2015-04-27T14:51:30.000000000Z" />
    <EventRecordID>6471</EventRecordID>
    <Channel>Application</Channel>
    <Computer>me.local</Computer>
    <Security />
  </System>
- <EventData>
    <Data />
    <Data>0</Data>
    <Data>CLR20r3</Data>
    <Data>Not available</Data>
    <Data>0</Data>
    <Data>calibration certificate builder</Data>
    <Data>1.0.0.0</Data>
    <Data>553e4aaa</Data>
    <Data>System.Data.SqlServerCe</Data>
    <Data>3.5.8080.0</Data>
    <Data>4b743b2d</Data>
    <Data>e3</Data>
    <Data>0</Data>
    <Data>System.ArgumentNullException</Data>
    <Data />
    <Data>C:\Users\me\AppData\Local\Temp\WER80E0.tmp.WERInternalMetadata.xml</Data>
    <Data>C:\Users\me\AppData\Local\Microsoft\Windows\WER\ReportArchive\AppCrash_pick_cert_e053eebdc3d787d726058a9b0d3405c6f279444_3b258dcb</Data>
    <Data />
    <Data>0</Data>
    <Data>e12fbed6-ecec-11e4-b276-24fd52358985</Data>
    <Data>65</Data>
  </EventData>
</Event>

I am unsure how to handle this. I have looked through my code and it does not appear to be an issue there. It does seem to be within the SQL Server CE code somewhere but I have been unable to find it.
I also pushed the event.ExceptionObject string to a text file and got this:

System.ArgumentNullException: Value cannot be null.
         at System.Threading.Monitor.Enter(Object obj)
         at System.Data.SqlServerCe.SqlCeCommand.Dispose(Boolean disposing)
         at System.Data.SqlServerCe.SqlCeCommand.Finalize()

Can anyone help me interpret this?
I have removed the use of the SQL CE services from other threads. I also removed the disposing of the SQL CE connection and also the finally blocks but the error logs remain the same.
Is the disposal of the connection causing an issue?

A: I am guessing that you are trying to connect with SQL database using windows authentication connection string and that person does not have access to sql database. Try to change the connection string with an user ID and password. Change from "Data Source=URDATABASE;Initial Catalog=MYDATABASE;Integrated Security=True" to "Data Source=URDATABASE;Initial Catalog=MYDATABASE;Uid=UrUserID;Pwd=MyPassWord;"


text:
Q: SQLSTATE[HY000]: General error:Can't create table I am using Laravel 8.21.0  on a CentOS 8 server. I am using mariaDB. I have 3 tables: tests, students and grades.
I am trying to set foreign key of tests and students on  the grades table.
However, when I run my migrations, I get errorno 150: Foreign key constraint is incorrectly formed.
Here are my migrations:
Grades table:
class CreateGradesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('grades', function (Blueprint $table) {

           $table->id('id')->unique();
           $table->unsignedInteger('student_id');
           $table->string('test_id');

           $table->foreign('test_id')->references('id')->on('tests');
           $table->foreign('student_id')->references('id')->on('students');

           $table->date('testDate');
           $table->integer('testCount');
           $table->integer('vocabScore');
           $table->integer('readingScore');
           $table->integer('listeningScore');
           $table->integer('rawTotal');
           $table->integer('adjustVocabScore');
           $table->integer('adjustReadingScore');
           $table->integer('adjustlisteningScore');
           $table->integer('adjustTotal');
           $table->string('passOrfail');
           $table->timestamps();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('grades');
    }
}

Student Table migrations:
class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {

            $table->integer('id')->unique();
            $table->string('name');
            $table->date('DOE');
            $table->string('belongsTo');
            $table->string('country');
            $table->string('level');
            $table->string('year');
            $table->timestamps();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}

Test table:
class CreateTestsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tests', function (Blueprint $table) {

            $table->string('id')->unique();
            $table->string('testName');
            $table->string('level');
            $table->integer('vocabFullScore');
            $table->integer('readingFullScore');
            $table->integer('listeningFullScore');
            $table->integer('totalFullScore');
            $table->integer('vocabPassScore');
            $table->integer('readingPassScore');
            $table->integer('listeningPassScore');
            $table->integer('totalPassScore');
            $table->timestamps();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tests');
    }
}

The bizzare thing is that the migrations table gets created successfully when I run it on localhost WAMP server but it throws me an error on CENTOS server. Does anyone have any idea on how to solve this?
Things that I have tried doing but did not work:
・Changed database to InnoDB  by specifying 'engine' => 'InnoDB' on each model.
・Made sure that the order of migration is correct. First migrated student table, then tests and lastly grades.
・Ensure that the data type of the foreign key is correct on grades table.

Any ideas would be greatly appreciated. :'(
Edit: I set the foreign key type of student_id as integer.
In grades table migration:
$table->integer('student_id');
$table->foreign('student_id')->references('id')->on('students');

In students table migration:
$table->integer('id')->unique();

After doing this  I am getting a new error:
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for right syntax to use near ')' at line 1 (SQL: alter table 'grades' add constraint 'grades_test_id_foreign' foreign key ('test_id') references 'tests' ())

at vendor/laravel/framework/src/Illuminate/Database/Connection.php:678
catch(Exception $e){
 throw new QueryException(
  $query, $this->prepareBindings($bindings),$e
);
}
+9 vendor frames
database/migrations/2021_01_13_064711_create_grades_table.php:54
Illuminate\Support\Facades\Facade::__callStatic()

+32 vendor frames
artisan:37
Illuminate\Foundation\Console\Kernel::handle()

A: Change
$table->unsignedInteger('student_id');
to
$table->integer('student_id');
in grades table to match the datatypes to form a constraint.


text:
Q: pgfplots very small Y values I need to plot the following function: http://www.wolframalpha.com/input/?i=sqrt%281%2Bx%2F5%29+-+%280.997475+%2B0.1+x-0.00499923+x%5E2%2B0.000499811+x%5E3-0.0000645293+x%5E4%2B9.12394x10%5E-6+x%5E5%29+in+%5B-1%2C1%5D
When I pick certain function values for the Y dimensions I got the known dimension too large error:
\begin{tikzpicture}[>=stealth]

    \begin{axis}[
        height=\textwidth,
        width=\textwidth,
        xmin=-1.05,xmax=1.05,
        %ymin=0.002524,ymax=0.002525,
        ymin=-1,ymax=1,
        axis x line=middle,
        axis y line=middle,
        axis line style=<->,
        xlabel={$x$},
        ylabel={$y$},
        xtick={-1,-0.5,0,0.5, 1},
        scaled y ticks = false,
        y tick label style={/pgf/number format/sci},
        ]

        \addplot[no marks,blue,line width=1pt] expression[domain=-1:1,samples=200]{sqrt(1+x/5) - (0.997475+0.1 * x-0.00499923 *x^2+0.000499811 * x^3-0.0000645293 * x^4+9.12394*10^-6 * x^5)}
            ;

    \end{axis}

\end{tikzpicture}

But I don't understand why I'm receiving a dimension too large error on this interval y = [-1,1]...
When I change the interval to y = [0.002524, 0.002525], I've got an output on the wrong interval:

Anyone who can point me in the right direction to fix this?

A: The PGF math engine is just not precise enough for these kinds of ranges. If you use gnuplot to do the calculations instead (by replacing expression by gnuplot in your code), you get the correct output:

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}[>=stealth]

    \begin{axis}[
        height=\textwidth,
        width=\textwidth,
        axis lines=middle,
        axis line style=<->,
        xlabel={$x$},
        ylabel={$y$},
        xtick={-1,-0.5,0,0.5, 1},
        scaled y ticks = false,
        y tick label style={/pgf/number format/fixed, /pgf/number format/fixed zerofill, /pgf/number format/precision=8},
        ]

        \addplot[no marks,blue,line width=1pt] gnuplot [domain=-1:1,samples=200]{sqrt(1+x/5) - (0.997475+0.1 * x-0.00499923 *x^2+0.000499811 * x^3-0.0000645293 * x^4+9.12394*10^-6 * x^5)}
            ;

    \end{axis}

\end{tikzpicture}
\end{document}


text:
Q: Order by a sub-classes field with Doctrine Got a basic Discrimination map going on in Doctrine
We have a base "Post" Entity, which maps various other Post types via a Category like scenario. This was done because each category has a wildly different unique data structure to it, but shares a few columns of similarity to every post.
My problem is that a specific couple of pages want to display the results of only a few categories, and some of the ordering on a specific post type is messing up.
The problem is, that the way they want this to organize, is by the common dateAdded field in the base Post entity, but for a specific post type to INSTEAD use a different field ONLY AVAILABLE to it via a field in it's own schema. This field is called releasedDate
So I tried this out:
public function postsByType($types = [], $limit = null, $onlyPublished = true)
{
    $qb = $this->getEntityManager()->createQueryBuilder();
    $qb->select('p')->from($this->getEntityName(), 'p');

    // Query for types. Without types, gets all types
    $instances = $qb->expr()->orX();
    foreach($types as $key=>$advtype){
        $instances->add("p INSTANCE OF :type_$key");
        $qb->setParameter("type_$key", $this->getEntityManager()->getClassMetadata('CommonBundle\Entity\\'.$advtype));
    }

    if($instances->count())
        $qb->andWhere($instances);

    if($onlyPublished)
        $qb->andWhere('p.published = :published')->setParameter('published', true);

    $qb->addOrderBy('p.releaseDate', 'DESC')
       ->addOrderBy('p.dateAdded', 'DESC');

    if($limit)
        $qb->setMaxResults($limit);

    $query = $qb->getQuery();
    $results = $query->getResult();

    return $results;
}

But naturally this produces the error:
[Semantical Error] line 0, col 211 near 'releaseDate': Error: Class CommonBundle\Entity\Post has no field or association named releaseDate

Aside from fetching all posts and running a custom quick sort through them and returning back the results requested, I'm not entirely sure what else to do..


text:
Q: Pushing files to avd using adb, changes are not saved When I'm using Genymotion, whatever changes I do to the android vd  (eg change apps layout, push files, etc)- the android vd saves its state, so when I quit and start over again- it'll show the same app layout and the files I pushed will be there.
However, when using the android emulator, I've created an android x86 device, started it, changing the app layout and I'm using adb to push files to the avd. But when I quit the android emulator, I lose all the changes I made- any app layout cange or any file I pushed, will no longer be there when I re-open the same avd.
I made sure all of the avd files are chmodded to 777 (I'm on mac osx)
How do I keep all the changes to the avd persistent to the disk, in the same way it happens in genymotion?

A: It's possible to keep a snapshot of your emulator like this:
Go to your AVD manager, upon Create... make sure you tick Snapshot under Emulation Options (can be done as well on existing ones using edit).
Then when you click Start.. you'll be given the following options:

*

*Save to snapshot - when you'll quit the vm a snapshot will be saved.

*Launch from snapshot - will load the latest saved snapshot.

Good luck, though I must say the whole snapshot thing did not go great for me, which made me switch to Genymotion.


text:
Q: Split on spaces not inside parentheses in Python I have a several strings that I want to split by spaces when not inside parentheses.
For example
sentence = "blah (blah2 (blah3))|blah4 blah5"

should produce
["blah", "(blah2 (blah3))|blah4", "blah5"]

I've tried:
re.split(r"\s+(?=[^()]*(?:\(|$))", sentence)

but it produces:
['blah', '(blah2', '(blah3))|blah4', 'blah5']

A: As said in the comments, it's impossible to process that using regex because of parenthesis nesting.
An alternative would be some good old string processing with nesting count on parentheses:
def parenthesis_split(sentence,separator=" ",lparen="(",rparen=")"):
    nb_brackets=0
    sentence = sentence.strip(separator) # get rid of leading/trailing seps

    l=[0]
    for i,c in enumerate(sentence):
        if c==lparen:
            nb_brackets+=1
        elif c==rparen:
            nb_brackets-=1
        elif c==separator and nb_brackets==0:
            l.append(i)
        # handle malformed string
        if nb_brackets<0:
            raise Exception("Syntax error")

    l.append(len(sentence))
    # handle missing closing parentheses
    if nb_brackets>0:
        raise Exception("Syntax error")

    return([sentence[i:j].strip(separator) for i,j in zip(l,l[1:])])

print(parenthesis_split("blah (blah2 (blah3))|blah4 blah5"))

result:
['blah', '(blah2 (blah3))|blah4', 'blah5']

l contains the indexes of the string where a non-paren protected space occurs. In the end, generate the array by slicing the list.
note the strip() in the end to handle multiple separator occurrences, and at the start to remove leading/trailing separators which would create empty items in the returned list.

A: While it is true that the re module cannot handle recursion, the PyPi regex  module can (to some extent). Just to show how advanced regex can work, here is the 2-regex approach: one validates the balanced parentheses and the second extracts the tokens:
>>> import regex
>>> sentence = "blah (blah2 (blah3))|blah4 blah5"
>>> reg_extract = regex.compile(r'(?:(\((?>[^()]+|(?1))*\))|\S)+')
>>> reg_validate = regex.compile(r'^[^()]*(\((?>[^()]+|(?1))*\)[^()]*)+$')
>>> res = []
>>> if reg_validate.fullmatch(sentence):
    res = [x.group() for x in reg_extract.finditer(sentence)]

>>> print(res)
['blah', '(blah2 (blah3))|blah4', 'blah5']

Extraction regex details: matches 1 or more occurrences of

*

*(\((?>[^()]+|(?1))*\)) - Capturing group 1 matching either 1+ chars other than ( and ) (with [^()]+) or (|) (?1) recurses the whole capturing group 1 pattern (recursion occurs)

*|  - or

*\S - a non-whitespace char

Validation regex details:

*

*^ - start of string

*[^()]* - 0+ chars other than ( and )

*( - Group 1 capturing 1 or more occurrences of:

*

*\( - opening ( symbol

*(?>[^()]+|(?1))* - 0+ occurrences of

*

*[^()]+ - 1+ chars other than ( and )

*| - or

*(?1) - Subroutine call recursing Group 1 subpattern (recursion)

*\) - a closing )

*[^()]* - 0+ chars other than ( and )

*)+  - end of Group 1

*$ - end of string


text:
Q: How can I make this regular expression work in Java to grab filename out of Linux 'ls -lrt' output? I'm trying to do this in Java:
    String patternStr = "\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+(.*)";
    Pattern pattern = Pattern.compile(patternStr);

Example 'ls -lrt' output:
drwxrwxr-x    2 bhannan  bhannan      4096 Jun  2 11:27 HelloWorld.xml

But it is not picking up the filename from the first group. However, this same regular expression works on regex101.com:
https://regex101.com/r/mR4rH1/2
What am I doing wrong in Java?
And actually if I could get this to work that would be even better:
https://regex101.com/r/mR4rH1/1

A: I suggest doing this in Java:
str = str.replaceFirst("^.*\\d{2}:\\d{2}\\s+", "");

where str represents each line of ls -la output.
RegEx Demo

A: Hint ... don't do this. Don't write up such an really really ugly regular expression that doesn't resemble to anything that a human being is able to read and understand. I am pretty sure: the next time you open up this file in your IDE in order to make a subtle change to the regular expression, you will find yourself spending another significant amount of time to get it working.
Meaning: why this way? Why doing a "ls -a"; to then make your regex  ignore most of that output? Wouldn't it make more sense to instruct ls to exactly print that one information you are looking for instead?

A: This should work for you :
public static void main(String[] args) {
    String s = "drwxrwxr-x    2 bhannan  bhannan      4096 Jun  2 11:27 HelloWorld.xml";
    System.out.println(s.replaceAll(".*\\s+(\\S+)","$1"));
}

O/P :
HelloWorld.xml

A: BTW the initial regexp works for me. Do you sure you use Pattern/Matcher properly?
Pattern p = Pattern.compile("\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+(.*)");
Matcher m = p.matcher("drwxrwxr-x    2 bhannan  bhannan      4096 Jun  2 11:27 HelloWorld.xml");
if (m.find()) {
    String filename = m.group(1);   // HelloWorld.xml
}

A: I would suggest using a split instead :
public static void main( String args[] ) {
    String str = "drwxrwxr-x    2 bhannan  bhannan      4096 Jun  2 11:27 HelloWorld.xml";

    List list = Arrays.asList( str.split( "\\s+" ) );
    System.out.println( list.get( list.size() - 1 ) );
}

It outputs:
HelloWorld.xml


text:
Q: Can someone help me with this React tutorial syntax error? Hi guys I've been trying to learn React with their tutorial online. I copy and pasted the code into Visual Studio Code and when ever I run demo.html, the page is blank. I got to the console and find that their is a syntax error " Uncaught SyntaxError: expected expression, got '<' " How can this be if I've just done a copy and paste job? I don't know if it could be something to do with the javascript being in a separate file?
I get the concepts behind this code but I can't see to figure out why it's working.
Any help if much appreciated!
Here is the script called test.js
function Welcome(props) {  return
 Hello {props.name}
;
}

const element = <Welcome name="Sara" />;ReactDOM.render(
element,
document.getElementById('root')
);

And here is demo.html
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>

A:
If you are developing React project. It is always a best practice and recommended by React team to
use CLI and get rid of all these script tags inclusion. Read React docs

You have to set Babel also to compile JSX. For that, you have to include it

and add type attribute to the script tag
type="text/babel"

HTML
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Add React in One Minute</title>

A: React uses a special file type called JSX which allows you to include HTML like syntax in Javascript. In order to parse JSX files you need to setup a react project.
The simplest way to do so is to use the Javascript library Create React App.
To use that install NodeJS and then execute npx create-react-app my-app to get some boiler plate code.
You can then navigate into the newly created react project using cd my-app and start it using npm start. This will start a server on port 3000. You can then navigate to http://localhost:3000 to view your react application.
You can configure the react project to start and debug it through VSCode as outlined here Configure the debugger.


text:
Q: Xdebug And Netbeans Problem Im trying to configure xdebug to work with Netbeans 6.9 and php 5.3
As far as i concern i have setup xdebug properly.
I can see xdebug extension from phpinfo page.
I have read other post and tried their suggestion but up to no avail
When i hit the debug button, it straight open the page in the browser and i can see message 'Waiting for connection' in the bottom pane of netbeans
Here my setting in php.ini
zend_extension = /usr/lib/php5/20090626+lfs/xdebug.so
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.idekey="netbeans-xdebug"

Any help would be appreciated

A: For me it was changing
;xdebug.remote_enable = 0 (default value in clean XAMPP installation)

to
xdebug.remote_enable = 1

did the trick

A: First, check that it isn't actually working for you, and you don't notice. I've done this...convinced it's not working I wasted a chunk of time trying to get it to work, only to find that everything was OK.
Look at your NetBeans status bar. If you see "netbeans-xdebug" and "running" then it is actually working just fine. You probably have the "Stop at first line" option turned off and you didn't hit any breakpoints you set (if any) yet. That would be a reason you are seeing the page with little or no indication that the debugger is actually connected.
If you instead see "Waiting for Connection (netbeans-xdebug)" and the progress bar is cycling, then you are indeed not connected. Open Tools|Options, and go to the PHP page. On the general tab, make sure that the "Debugger port" is 9000 and the "Session ID" is "netbeans-xdebug". You may want to have "Stop at First Line" checked. I don't, as I find it a bit annoying. I would definitely ensure that "Watches and Balloon Evaluation" is not checked. This option causes NetBeans and the debugger to destabilize. If you need a watch, hack a local variable into the PHP code where you need it, and you'll see it on the "Variables" tab when the debugger is running. Also, confirm that file (index.php) is specified in the project's Run Configuration > Index File.
Since you see xdebug in phpinfo(), that end of it is fine. Just make sure that all of the values look reasonable, and that there is some reference to a cookie "XDEBUG_SESSION=netbeans-xdebug" somewhere on that page. (Make sure that you don't have cookies turned off on the browser!)
The only other thing to check is to see if some firewall/security program is running that would be blocking TCP/UDP locally (which would be super-odd, but not out of the realm of possibility), or that port 9000 isn't already used by another application. I am using a different port number in my local setup for some reason. I don't remember changing it, but I am sure that the only reason I would have is if I had hit a port conflict with something else.
One last thing... We've been assuming that you are running NetBeans and the web server on the same computer. That's a common configuration, but not the only one. If your web server is on a different computer, then change the localhost in xdebug.remote_host=localhost to the IP address of the computer on which NetBeans is running.
Another last thing: When cycling through frustrating iterations, until you see xdebug info in phpinfo(), restart apache/php. Once there, still restart NetBeans between iterations. And believe it or not, restart your browser.

A: Adding an index.php did the trick for me.

A: I couldn't figure out why some of my projects would connect to the debugger and others wouldn't.  Then I realized that the ones that wouldn't connect started with index.html.  Once I renamed these files to index.php, the debugger connected with no problem.

A: I solved this using a windows -> remote LAMP server config after reading the following post, leaving the link in case anyone finds it handy:
http://stuporglue.org/setting-up-xdebug-with-netbeans-on-windows-with-a-remote-apache-server/comment-page-1/#comment-6227

A: Having just upgraded to the new Ubuntu 14.4 my NetBeans Xdebug stopped working.  I've followed all the answers above to date to no avail.
I found a NetBeans Ubuntu statement that the /etc/php5/cli/conf.d/xdebug.ini file should have xdebug.remote_enable=on.  When I checked the /etc/php5/cli/conf.d directory, I found no xdebug.ini file.  However there was a link to /etc/php5/mods-available/xdebug.ini there.
Subsequent adding the xdebug.remote_enable=on to that file fixed the problem.
PS - This works on NetBeans 8.0.1

A: When I tried to debug the Yeoman WebApps powered by PHP backend in Netbeans, the status keep showing 'Waiting for connection'. There's probably because the index.html has nothing to do with php at all. It's only when I've triggered the ajax which needed PHP processing, the connection with xdebug immediately connected and debug as usual. Hope this give another perspective to someone as I have stumbled to 'think' there is a problem and trying to fix the ini.

A: An alternative is the Dephpugger project. Is like ipdb in python or byebug in Ruby.
https://github.com/tacnoman/dephpugger
Is very easy to use.


text:
Q: Signature of method that returns a LinkedHashMap Consider that I want method foo to return a LinkedHashMap(data is ordered by insertion order). The reason being that this Map will be populated by a database and I want it to reflect the order that is returned from the query. What would be the correct way of defining the signature of the method?

*

*public LinkedHashMap<String, String> foo()

*public Map<String, String> foo()
The first would have the advantage of advertising to clients that the map is ordered, while the second would be more general.

A: Definitely the second one - you should prefer interfaces and hide implementation - if you will decide in the future to use another implementation of Map you won't need to change anything in another method using this code
Also notice that you are not allowed to overload methods by return type so using general type seems to be appropriate

A: It depends on how this method is going to be used/specialized. However, I would recommend the second appoach.
Consider a scenario where this method needs to be overridden to return let's say sorted values (i.e. TreeMap) or unsorted/unordered values (HashMap). In this case, we won't be able to override this method and will have to create another method(s).


text:
Q: Android public key encryption My Android app implements RSA encryption, however the backend can not decrypt the token generated by the app. Here is the code, the beginning and end lines of the public key have been removed before making the calls, what could be the problem?
String encryptedToken = Base64.encodeToString(encrypt(publicKey, "4111111111111111"), Base64.NO_WRAP);

public static byte[] encrypt(String publicKey, String data) {
        if (TextUtils.isEmpty(publicKey) || TextUtils.isEmpty(data)) {
            return null;
        }
        try {
            // Decode the modified public key into a byte[]
            byte[] publicKeyByteArray = Base64.decode(publicKey.getBytes("UTF-8"),Base64.NO_WRAP);

            Cipher mCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyByteArray);
            Key key = keyFactory.generatePublic(x509KeySpec);
            mCipher.init(Cipher.ENCRYPT_MODE, key);
            return mCipher.doFinal(data.getBytes("UTF-8"));
        }
        catch (UnsupportedEncodingException e) {
            Log.e("RSAKEY", e.getMessage());
        }
        catch (NoSuchPaddingException e) {
            Log.e("RSAKEY", e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            Log.e("RSAKEY", e.getMessage());
        } catch (InvalidKeyException e) {
            Log.e("RSAKEY", e.getMessage());
        } catch (InvalidKeySpecException e) {
            Log.e("RSAKEY", e.getMessage());
        } catch (IllegalBlockSizeException e) {
            Log.e("RSAKEY", e.getMessage());
        } catch (BadPaddingException e) {
            Log.e("RSAKEY", e.getMessage());
        }
        return null;
    }

The backend team provided the below sample code that works, but it is for desktop java. Android library does not have the Base64.getEncoder method. it is very similar to what I wrote but mine just does not work.
 // Decode the modified public key into a byte[]
            byte[] publicKeyByteArray = Base64.getDecoder().decode(publicKey.getBytes(StandardCharsets.UTF_8));

            // Create a PublicKey from the byte array
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyByteArray);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey pubKey = keyFactory.generatePublic(keySpec);

            // Get an instance of the Cipher and perform the encryption
            Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            byte[] cipherText = cipher.doFinal(ccNum.getBytes(StandardCharsets.UTF_8));

            // Get the encrypted value as a Base64-encoded String
            String encodeToStr = Base64.getEncoder().encodeToString(cipherText);

            // Print out the encoded, encrypted string
            System.out.println("Encrypted and Encoded String: " + encodeToStr);

I compared the byte array values at every step. The desktop cipher and android cipher got exactly the same inputs. However the results from the Android code cipher.doFinal can not be decrypted by the backend. If I put the desktop results to the REST call body they work fine, so it is not something caused by REST call.
I also tried to create a public/private key pair on Android, and use the generated public key to encrypt instead of using the public key from our backend, and decrypt using the private key and it works. So the cipher is also working, just somehow the backend is expecting something different

A: Finally someone in the team cracked this.
The reason is because the Android OS uses Bouncy castle, the backend uses Sun as the provider, this caused the backend throwing a BadPaddingException.
To make it work, the cipher needs to be initialized this way on Android:
 mCipher.init(Cipher.ENCRYPT_MODE, key, new
                    OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA1,
                    PSource.PSpecified.DEFAULT));

Check for more details in this post:
http://bouncy-castle.1462172.n4.nabble.com/Problems-with-OAEP-SHA-256-hash-crypto-td1466852.html


text:
Q: duplicate keys on multiple drop down buttons I have a search functionality where I have to give the user the leverage to dynamically add search parameters that are in a drop down box.This i am doing using a jquery clone.
Now I also have to make sure that the user does not select the same search criteria twice and hence to prevent that, I have to disable the selected options.
My attempt to do this fails when there are more than two dropdowns
http://jsfiddle.net/V8uFE/
Any help is greatly appreciated.
Thanks in advance,
Raj

A: instead you can use multiple select in single list itself..But if you want to do that you can use AJAX for this.

A: check this Fiddle.
coloring works. but not disabled property. you have to investigate that.
you can use like this instead of change coloring.
if(flag)
    $(this).css('display','none');
else
    $(this).css('display', 'block');

i think disabled property also triggers change event. i am not sure about that. but it is not working.

A: Try the code, i think ishould help you in some way!!

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>

   <select  onchange="return disableValue(this.value)">
<option selected="selected">-Search Parameters-</option>
<option value="1" class="go1">1</option>
<option value="2" class="go2">2</option>
<option value="3" class="go3">3</option>
</select>

<select onchange="return disableValue(this.value)">
<option selected="selected">-Search Parameters-</option>
<option value="1" class="go1">1</option>
<option value="2" class="go2">2</option>
<option value="3" class="go3">3</option>
</select>

<select onchange="return disableValue(this.value)">
<option selected="selected">-Search Parameters-</option>
<option value="1" class="go1">1</option>
<option value="2" class="go2">2</option>
<option value="3" class="go3">3</option>
</select>


text:
Q: PHP / TCPDF library - Size an image in a PDF to a specific number of inches? Does anyone know how to get TCPDF to output a .GIF file with a specific number of inches width x height?
I am trying to get a GIF embedded in a PDF so that it will print at exactly 4x6 inches. I tried this:
$this->setpageUnit('in');
$this->Image($tmp, 0, 0, 4, 6, 'gif', '', '', true);

But that only seemed to result in a blank page. Any ideas?

A: I think it's happen because you are not using a capital "P"
$this->setpageUnit('in');

maybe is should be :
$this->setPageUnit('in');

A: I think you'll need to figure out how many pixel's per inch and then use the method setImageScale(float $scale);
For example:
$this->setImageScale(24.5);

Then your code should work, after setting the scale:
$this->Image($tmp, 0, 0, 4, 6, 'gif', '', '', true);


text:
Q: removing tag outline from  tag in html I have a  tag on an html page, inside the  tag I have an img tag, when I click an image a image scroller pops up and when i close the scroller the image now has an outline on it, which i can remove by pressing tab or clicking elsewhere, is there anyway to remove this outline?
Thanks,

A: write this:
a{
 outline:none;
}

A: Some CSS will do it:
.group1 {
  outline: none;
}

A: CSS:
a.group1 {
    outline: none;
    border:none;
}


text:
Q: Switching between light and dark theme I am following an article to implement light and dark theme for one of my apps. The article can be found here. In this article, an interesting approach is used to edit all colors at once so there is no need to change all labels, backgrounds, ... separately. The new theme is set like this:
private func setNewTheme(_ newTheme: AppTheme) {
    let window = UIApplication.shared.delegate!.window!!
    UIView.transition(
        with: window,
        duration: 0.3,
        options: [.transitionCrossDissolve],
        animations: {
            self.theme.value = newTheme
        },
        completion: nil
    )
}

I suggest to read the article to understand the entire working of this mechanism. This works great and changes my backgrounds, colors of the UITabBar, colors of the UINavigationController etc. However, in some of my UIViewControllers, there is a UICollectionView which I would like to update as well. The colors remain the same, but I guess I need to reload the data in order for it to work?
My question is; how could I implement a functionality where my UICollectionViews would be reloaded when the other theme is set?
If the article I am mentioning is not best practice, please guide me towards the best way to implement this feature.

A: Look at here.
I think this repo can give u some suggestion.


text:
Q: ExtJs , How to create Tracking/Steps Bar I want to create steps or tracking bar in Sencha ExtJS Classic as the following images
what is the best way to implement this in ExtJS Classic?
each step have to be clickable

A: You can start with:
@example: https://fiddle.sencha.com/#view/editor&fiddle/274i
Or you start your own like this:
xtype: breadcrumb

example: https://fiddle.sencha.com/#view/editor&fiddle/31vu
Other than that you can also start with the segmentedbutton and use css ::after to add the colored line.
In the past I did this one time and it turned out to be a lot of work. We used layout: 'hbox' and used buttons.
The main problem was to add the logic to allow step back still keeping information, add logic after each step separately and make this a full "wizzard-component".


text:
Q: How to organize App.config files? I have console application and want to organize App.config files for different builds in such a way when particular build has been created, the appropriate config file should be copied to its folder.
There's a build named - ReleaseProduction. I've created the three with a main App.config file as a root and App.ReleaseProduction.config file as a subtype.
The App.ReleaseProduction.config file looks as following:
<?xml version="1.0"?>
<configuration  xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings>
    ...
  </appSettings>
</configuration>

There's a section in project's csproj file that looks as following:
<ItemGroup>
  <None Include="App.config">
    <SubType>Designer</SubType>
  </None>
  <None Include="App.ReleaseProduction.config">
    <DependentUpon>App.config</DependentUpon>
    <SubType>Designer</SubType>
  </None>
</ItemGroup>
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterCompile" Condition="Exists('App.$(Configuration).config')">
  <TransformXml Source="App.config" Transform="App.$(Configuration).config" Destination="App.config" StackTrace="true" />
</Target>

But, I've got this error message:
Exception: Не удалось записать конечный файл: Процесс не может получить доступ к файлу "D:\SVN\Concert\trunk\SitemapBuilder\App.config", так как этот файл используется другим процессом.
   в Microsoft.Web.Publishing.Tasks.TransformXml.SaveTransformedFile(XmlTransformableDocument document, String destinationFile)
   в Microsoft.Web.Publishing.Tasks.TransformXml.Execute()
IOException: Процесс не может получить доступ к файлу "D:\SVN\Concert\trunk\SitemapBuilder\App.config", так как этот файл используется другим процессом.
   в System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   в System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   в System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   в System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
   в System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
   в System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
   в Microsoft.Web.Publishing.Tasks.XmlAttributePreservingWriter..ctor(String fileName, Encoding encoding)
   в Microsoft.Web.Publishing.Tasks.XmlFileInfoDocument.Save(String filename)
   в Microsoft.Web.Publishing.Tasks.TransformXml.SaveTransformedFile(XmlTransformableDocument document, String destinationFile)
    D:\SVN\Concert\trunk\SitemapBuilder\ConcertRu.SitemapBuilder.csproj 116 5   ConcertRu.SitemapBuilder

Which means the process cannot get access to this file "D:\SVN\Concert\trunk\SitemapBuilder\App.config" because it's used by another process.
How to overcome this issue?


text:
Q: How to fill 2 text boxes by changing dropdownlist? I have tried to fill 2 text boxes when a DropdownList changed.

The text in text box 1 is Name of ID_1.
The text in text box 2 is Age of ID_1

And if I choose another choices in the dropdownlist, the text in text box 1 and text 2 will be changed.

For example,

+----+-----------+--------------+--------------+
| Dropdownlist   | TextBox1     | TextBox2     |
+----------------+--------------+--------------+
| 1              | John         | 23           |
+----------------+--------------+--------------+
| 2              | Vivian       | 43           |
+----------------+--------------+--------------+

This is my database.
+----+-----------+--------------+
| id | Name      | Age          |
+----+-----------+--------------+
| 1  | John      | 23           |
+----+-----------+--------------+
| 2  | Vivian    | 43           |
+----+-----------+--------------+

My code from .aspx

$('#<%:DropDownA.ClientID%>').change(function () {
  changeData();
});

function changeData() {
  var txt1 = $('#<%:DropDownA.ClientID%>').val();
  var txt2 = $('#<%:DropDownA.ClientID%>').val();
  $('input[id="TextBox1"]').val(txt1);
  $('input[id="TextBox2"]').val(txt2);
};

changeData();
<asp:DropDownList ID="DropDownA" runat="server" CssClass="form-control" DataSourceID="SqlDataFromDatabase" DataTextField="id" DataValueField="name"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataFromDatabase" runat="server" ConnectionString="<%$ ConnectionStrings:asrsDBConnectionString %>" SelectCommand="SELECT * FROM [table]"></asp:SqlDataSource>

<input class="form-control" id="TextBox1" value="xxxx" type="text" style="color: green;" disabled>
<input class="form-control" id="TextBox2" value="xxxx" type="text" style="color: green;" disabled>

 Thank you in advance for giving me the solution or suggestion.

The Solution.

  ** Please follow this link for checking how to split the data: **

How to split the string using jQuery or JavaScript?

$('#<%:DropDownA.ClientID%>').change(function () {
  changeData();
});

function changeData() {
  var data1 = $('#<%:DropDownA.ClientID%>').val();
  var arr = data1.split(';');
  $('input[id="TextBox1"]').val(arr[0]);
  $('input[id="TextBox2"]').val(arr[1]);
};

changeData();
<asp:DropDownList ID="DropDownA" runat="server" CssClass="form-control" DataSourceID="SqlDataFromDatabase" DataTextField="id" DataValueField="name"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataFromDatabase" runat="server" ConnectionString="<%$ ConnectionStrings:asrsDBConnectionString %>" SelectCommand="Select (Name + ';' + Age) NameAge, id from [table]"></asp:SqlDataSource>

<input class="form-control" id="TextBox1" value="xxxx" type="text" style="color: green;" disabled>
<input class="form-control" id="TextBox2" value="xxxx" type="text" style="color: green;" disabled>

A: Solution #1: Drop-Down List Value
This solution would require you to store the pertinent information in the Value & Key attributes of the Drop Down List.  So your SQL statement would need to look like this: Select (Name + ';' + age) NameAge, Id from [table]
With this SQL Statement, you could then change your DropDownList DataValueField field to NameAge and split the key-value pair on SelectIndexChanged event to fill the two associated TextBoxe, when the PostBack occurs
Solution #2: Hidden reference values
Less ideal but will depend on your situation.
Basically, you have a Hidden Input field that holds ALL possible meta-data for the DropDown List and based on selection the pertinent information is extracted for further use in other locations.  Think of this like a Flat-file style storage mechanism.
This solution usually will require jquery/javascript to perform, as the data would generally be stored as json.  Although, you could do a hierarchical CSV type design.


text:
Q: Understanding modeling of recursive closures in compilers I'm given the description of two ways to model recursive closures for a lisp-like language. Assume I have the following code:
(letrec ((f (fun (l) … (map f l) …)))) …)

For the closure corresponding to f I could:

*

*Treat f as a free variable, and put it in its own environment which leads to a cyclic closure.

*With flat closures, the environment is the closure, and can be reused directly.

I'm using the concept of flat closure  that stores in its first cell a pointer to the function and in the rest the free variables. But I get confused with the second option because it seems to me that the first and the second call receive different parameters. How is it possible then that they get the same closure and there is no need to include the recursive call as a free variable to differentiate them?
Maybe you can explain how this is solved in future steps of a typical compiler?

A: Each invocation of f will create a new closure with a new value for l (assuming lexical scoping). The closure in the body of f generally won't contain f, but the parent will, so you'll end up doing a lookup up the call stack.
I wrote a post going into this a bit more: http://cinigl.io/posts/nested-variable-scoping


text:
Q: Any way I can make this code cleaner/more efficient? (C#/LINQ-to-SQL) I've been putting together an auditing solution for a program I am developing, where I am using LINQ for my update/insert operations. I have come up with the following solution (this is the snippet for inserting) (Note the Tables variable contains a list of all the tables that have been modified - I add these to the list manually and call this method):
 BindingFlags b = BindingFlags.Instance | BindingFlags.Public;
        LINQDataContext dc = new LINQDataContext();
        foreach (object Table in Tables)
        {
            string TableName = Table.ToString().Replace("Project.", "");

            switch (TableName)
            {
                case "Job":
                    string NewJobString = null;
                    Job JobDetails = (Job)Table;
                    var prpsJob = typeof(Job).GetProperties(b);
                    foreach (var p in prpsJob)
                    {
                        object x = p.GetGetMethod().Invoke(JobDetails, null);
                        x = StripDate(x);
                        NewJobString += p.Name + ": " + x + Environment.NewLine;
                    }
                    Audit(JobID, NewJobString, "New Job created", SourceID, "", JobDetails.JobID);
                    break;

                case "Estimation":
                    string NewEstimationsString = null;
                    Estimation EstimationDetails = (Estimation)Table;
                    var prpsEstimations = typeof(Estimation).GetProperties(b);
                    foreach (var p in prpsEstimations)
                    {
                        object x = p.GetGetMethod().Invoke(EstimationDetails, null);
                        x = StripDate(x);
                        NewEstimationsString += p.Name + ": " + x + Environment.NewLine;
                    }
                    Audit(JobID, NewEstimationsString, "New Estimation created", SourceID, "", EstimationDetails.EstimationID);
                    break;

And the code goes on for each possible tablename. The code works fine, but it seems fairly inefficient - having a nearly identical block for each case. Is there a more efficient way?

A: You should be able to use Lambdas to cover the type-specific parts of the repeated code.  This is some almost pseudo-code I hacked together....
void TableIsJob(Job j, BindingFlags b) {
   HandleTable("Job", j.JobID, typeof(Job).GetProperties(b),
               p=>p.GetGetMethod().Invoke(j, null));
}

void TableIsEstimation(Estimation e, BindingFlags b) {
   HandleTable("Estimation", e.EstimationID, typeof(Estimation).GetProperties(b),
       p => p.GetGetMethod().Invoke(e, null));
}

void HandleTable(string nm, int ID, PropertyInfo [] props, Func<PropertyInf, Object> i) {
       string desc = string.Join(Environment.NewLine, props.Select(p=>{
                       return string.Format("{0}: {1}", p.Name,
                                    StripDate(i(p)));
               }).ToArray());
       Audit(JobID, desc, string.Format("New {0} created", nm),
             SourceID, "", id);
}

And then you can replace your huge for loop and switch case with...
Tables.Select(t =>
{
   switch (t.ToString().Replace("Project.", ""))
   {
       case "Job":
           TableIsJob((Job)t, b);
           break;
       case "Estimation":
           TableIsEstimation((Estimation)t, b);
           break;
   }
});

This is all assuming that "efficient" means in terms of code volume, not in execution time.

A: Well you can certainly pull out the below code into a method:
 string NewJobString = null;
    Job JobDetails = (Job)Table;
    var prpsJob = typeof(Job).GetProperties(b);
    foreach (var p in prpsJob)
    {
           object x = p.GetGetMethod().Invoke(Table, null);
           x = StripDate(x);
           NewJobString += p.Name + ": " + x + Environment.NewLine;
    }

public string GetProperties(Type t, BindingFlags b)
{
     StringBuilder sb = new StringBuilder();
     var prpsJob = typeof(t).GetProperties(b);
     foreach (var p in prpsJob)
     {
          object x = p.GetMethod().Invoke(Table, null);
          x = StripDate(x);
          sb.Append(p.Name + ": " + x + Environment.NewLine);
     }
     return sb.ToString()
}

And have something like
 case "Job":

   Audit(JobID, GetProperties(typeof(Job),b), "New Job created", SourceID, "", JobDetails.JobID);
   break;

A: From what I can gather, most of the duplicated code is dumping the value of the objects into a string.
You could use a helper method to do this:
public static string DumpObject<T>(T obj)
{
    StringBuilder sb = new StringBuilder();

    var properties = typeof(T).GetProperties(
                     BindingFlags.Instance | BindingFlags.Public);

    foreach (var p in properties)
    {
        object x = p.GetGetMethod().Invoke(obj, null);
        x = StripDate(x);
        sb.Append(p.Name).Append(": ").Append(x).AppendLine();
    }

    return sb.ToString();
}

This would still not be very efficient code in terms of execution time, but it would reduce the code duplication. I've also changed the string appending to using a StringBuilder. It's just good practice in cases like this.
By the way, it is convention to use camel case for local variables and parameters:
switch (tableName)
{
    case "Job":
        Job jobDetails = (Job)table;
        Audit(jobID, DumpObject(jobDetails), "New Job created",
              sourceID, "", jobDetails.JobID);
        break;
    // ...
 }

A: I suggest you use T4 templates to generate your LINQ to SQL classes by using LINQ to SQL templates for T4. Then add an interface on the tables that have special needs.
public interface IHaveEstimation {
   DateTime GetEstimationDate();
}

In your LINQDataContext.tt file, you can add some additional T4 generation code that detects the table and add the interface to that Object:
<#
  string markerInterface = String.Empty;

  if (class1.Name == "Estimation")
  {
     markerInterface = "IHaveEstimation";
  }
#>

<#=code.Format(class1.TypeAttributes)#>partial class <#=class1.Name#>
<#=String.IsNullOrEmpty(markerInterface) ? String.Empty : String.Format(" : {0}", markerInterface) #>
{ ... }

In your LINQDataContext.cs file, you can do something like this:
/// <summary>
/// When the database context is submitted.
/// </summary>
/// <param name="failureMode">
/// the submit failure mode
/// </param>
public override void SubmitChanges(ConflictMode failureMode)
{
  foreach (var insert in changeSet.Inserts.OfType<IHaveEstimation>())
  {
    var estimtation = insert.GetEstimationDate();
    // handle auditing, etc.
  }

  // do same for update and delete change sets
}

A: You should really use this answers from SO quesetion
And In case You do not want to serialize all properties I STRONGLY advise creating a custom attribute and filtering the list based on it (of course decorating the properties before). Messing with IL is dirty at the beggining but it is THE most performant way to do it. Hand's down.
luke


text:
Q: PHP session is coming back null I am trying to come up with a session timeout (first time).  When ever I am calling the if statement it is getting a null for the $_SESSION variable.  I have the session start in the header.php file at the top.  When the user logs in it creates the session with this code:
public static function create_session($values) {
    foreach ( $values as $key => $value ) {
        if ($key != "password") {
            $_SESSION[$key] = $value;
        }
    }

    $_SESSION["timestamp"] = time();
}

It then redirects to an index page wich only contains:
<?php
  echo "<pre>";
  print_r($_SESSION);
  echo "</pre>";
?>

This works, it prints all the session variables on the page just fine.
This is what prints out in the index.php file with the above code.
Array
(
  [id] => 33
  [first_name] => removed to not show name
  [last_name] => removed to not show name
  [email] => test@test.com
  [timestamp] => 1437486426
)

In my footer.php file I have some jquery running a timed function every 5 seconds calling the timeout.php file.
(function poll() {
   setTimeout(function() {
       $.ajax({ url: "timeout.php", success: function(data) {
            console.log(data);
       }, dataType: "json", complete: poll });
    }, 5000);
})();

The timeout php file only has this code in it:
if (isset($_SESSION)) {
    if ($_SESSION['timestamp'] + 10 * 60 < time()) {
        // session timed out
        echo json_encode(array('session' => $_SESSION, 'session_timestamp' => $_SESSION['timestamp'], 'timestamp_calculation' => $_SESSION['timestamp'] + 10 * 60, 'timeoutstatus' => 'timed out'));
    } else {
        // session ok
        echo json_encode(array('session' => $_SESSION, 'session_timestamp' => $_SESSION['timestamp'], 'timestamp_calculation' => $_SESSION['timestamp'] + 10 * 60, 'timeoutstatus' => 'not timed out'));
    }
} else {
    echo json_encode(array('session' => 'Session does not exits'));
}

For some reason I am getting the session does not exist.  If I remove that part of the if statement and just test the timeout all the json array variables that call $_SESSION return null.  I have no idea why this is.  I appreciate your help.
In response to this being a duplicate.  The original thought was that session_start() wasn't called.  I had mentioned it was called in the first paragraph and it comes before all other php code.  I have also confirmed that I can call the $_SESSION variable within the index page just fine.  I am only getting an issue when trying to read it through my ajax function which is being called from my footer.php.

A: You have not start session in timeout.php file and/or not include your header.php in to this file so session will never start in timeout.php. That's y session is undefine in timeout.php file.
You can add condition in timeout.php like :
if(!isset($_SESSION)) session_start();


text:
Q: I am trying to query two tables in my laravel database I am trying to query two tables in a database but its returning this error.
I am trying to implement a search through multiple tables. The project is an online store with 3 distinctive tables, Products, Categories and Brands. I can only search through the Products table but can't seem to get the same search field from my blade file to search either the categories or the brands and return results of the associated products.
QLSTATE[23000]: Integrity constraint violation: 1052 Column 'status' in where clause is ambiguous (SQL: select * from `categories` inner join `products` on `products`.`category_id` = `categories`.`id` where `name` LIKE %Television% and `status` = 1)

My Search function
public function searchProducts(Request $request) {
        $product = $request->input('product');

        $categories = Category::with('categories')->where(['parent_id' => 0])->get();

        $productsAll = Category::query()->join('products', 'products.category_id', '=', 'categories.id')
                                    ->where('name', 'LIKE', "%{$product}%")
                                    ->where('status', 1)->get();

        $breadcrumb = "Home / ".$product;

        return view('pages.results')->with(compact('categories','productsAll','product','breadcrumb'));

    }

My Category Model
class Category extends Model implements Searchable
{
    protected $table = 'categories';
    protected $fillable = [
        'name'
    ];
    public function categories(){
        return $this->hasMany('App\Category','id');
    }

    public function products(){
        return $this->hasMany('App\Product','id');
    }
}

My Products Model
class Product extends Model implements Searchable
{

    public function category() {
        return $this->hasMany('App\Category', 'id') ;
    }

    public function attributes(){
        return $this->hasMany('App\Product','id');
    }
}

A: You have status column in more than one table.
Change this
->where('status', 1)->get();

to this
->where('products.status', 1)->get();

A: I was able to solve it by modifying my search function as follows.
public function searchProducts(Request $request) {
        $product = $request->input('product');

        $categories = Category::with('categories')->where(['parent_id' => 0])->get();

        $productsAll = Category::query()->join('products', 'products.category_id', '=', 'categories.id')
                                    ->where('categories.name', 'LIKE', "%{$product}%")
                                    ->orWhere('products.product_name', 'LIKE', "%{$product}%")
                                    ->where('products.status', 1)->get();

        $breadcrumb = "Home / ".$product;

        return view('pages.results')->with(compact('categories','productsAll','product','breadcrumb'));

    }


text:
Q: Block that stay in line no matter the size of the screen I have a row that does not stay in line when the window get very narrow.
the green block goes under the other block, is this normal behavior?
I mean I though that because it is in a "row" class and because I use xs column that add up to 12 it should stay in line whatever the size of the screen.
Here my code (or you can go to bootply)

What I expect from my code (working fine if window not too narrow)

What I get if window is narrowed

A: I think is a problem of the default paddings in the divs. When the resolution is smallest than the sum of all paddings it broken. In your code there are 4 divs, with 30 pixels of padding, and when it is so fit, it broken. I put paddings to zero value and it works
See this: http://www.bootply.com/jaSQxxUZuD#
The only change in css is
  .row > div { padding: 0 }

If you need to conserve theese paddings, you can prevent broken line:
  .row { white-space: nowrap; }

EDIT
If you need to conserve these paddings, it's better make the innerbox
  .row > div { box-sizing: border-box; }

With this last class, you preserve paddings, but the width will not be incremented like without paddings.

A: col-xs-1 has a padding-left and padding-right of 15px, this means that the size of the gray bar is bigger than 8.333% of the width when the screen width goes below 330px.
Set padding to 0 to avoid the problem.

A: There are different possibilities to solve this.
Adding this to the css should at least do it:
.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-6{
    padding:0px;
}


text:
Q: Community Builder Page Invalid when Passing Parameter I have a custom Community Builder page that is a custom "Standard Detail" page called "TransactionDetail" (i.e. a detail, list, and related list page were each created).  I have a component I added to the page that takes a recordId in the design file, which I set to {!recordId} in the community builder.
When I try to navigate to this page, and pass an Id, the page shows Invalid Page and does not load anything.  When I remove the parameter, and just navigate to /s/transactiondetail, the header for the page shows up as expected.
Here's what I'm using to navigate to the page (the URL ends up looking exactly how I want it to):
    var navEvt = $A.get("e.force:navigateToURL");
    navEvt.setParams({
        "url" : "/transactiondetail/"+srcId,
        "isredirect" :false
    });
    navEvt.fire();

The URL I end up navigating to looks like "/s/transactiondetail/[recordid]" just as I would expect, however it just shows Invalid Page.  I commented out all of the custom code and just have "test" displaying in the component itself, so there's no code causing an error in the component itself.
I also tried creating a non-standard custom community page and adding the component, it gives the same result.  Any help would be appreciated.

A: Disregard, I found that it was profile access issues.  When accessing a detail page override, the logged in user's profile is checked before attempting to load any data or elements into the view.


text:
Q: Paperclip Issue - can't update and create CONTROLLER
CREATE
  def create
    set_cache_buster
    @court_agency = CourtAgency.new(court_agency_params)
    @court_agency.created_by = current_user
    @court_agency.updated_by = current_user
    binding.pry
    respond_to do |format|
      if @court_agency.save
        flash[:success] = 'Court was successfully created.'
        format.html do
          redirect_to court_agencies_path
        end
        format.js { render :js => "window.location = '#{court_agencies_path}'" }
      else
        format.json { render json: @court_agency.errors, status: :unprocessable_entity }
      end
    end
  end

UPDATE
  def update
    set_cache_buster
    @court_agency = CourtAgency.find(params[:id])
    @court_agency.updated_by = current_user
    respond_to do |format|
      if @court_agency.update_attributes(court_agency_params)
        flash[:success] = 'Court was successfully updated.'
        format.html do
          redirect_to court_agencies_path
        end
        format.js { render :js => "window.location = '#{court_agencies_path}'" }
      else
        format.json { render json: @court_agency.errors, status: :unprocessable_entity }
      end
    end
  end

STRONG PARAMETER
  def court_agency_params
    params.require(:court_agency).permit(
      :type,
      :subtype,
      :division,
      :associate_justice,
      :presiding_justice,
      :map,
      :landmark_image,
      ]
    ) if params[:court_agency]
  end

MY VIEW
= form_for(@court_agency, remote: true, html: { :multipart => true, class: 'form-horizontal ajax-form', style: 'margin-bottom: 0;', 'data-model-name' => 'court_agency'}) do |f|
    .form-group
      = f.label :landmark_image, 'Landmark', class: 'control-label'
      %br/
      = f.file_field :landmark_image, class: 'btn btn-warning'
      - if @court_agency.map.present?
        = image_tag @court_agency.map.url(:small), class: 'img-responsive img-thumbnail'
    .form-group
      = f.label :map, 'Map', class: 'control-label'
      %br/
      = f.file_field :map, class: 'btn btn-warning'
      - if @court_agency.map.present?
        = image_tag @court_agency.map.url(:small), class: 'img-responsive img-thumbnail'

MODEL
  #Paperclip
  has_attached_file :map,
                    :styles => { :large => "900x900>", :medium => "300x300>", :thumb => "196x196>", :small => '50x50>' },
                    :default_url => ActionController::Base.helpers.asset_path('missing.png'),
                    :url => "/assets/court_agencies/:id/:style/:basename.:extension",
                    :path => ":rails_root/public/assets/court_agencies/:id/:style/:basename.:extension"
  validates_attachment_content_type :map, :content_type => /\Aimage\/.*\Z/
  has_attached_file :landmark_image,
                    :styles => { :large => "900x900>", :medium => "300x300>", :thumb => "196x196>", :small => '50x50>' },
                    :default_url => ActionController::Base.helpers.asset_path('missing.png'),
                    :url => "/assets/court_agencies/:id/:style/:basename.:extension",
                    :path => ":rails_root/public/assets/court_agencies/:id/:style/:basename.:extension"
  validates_attachment_content_type :landmark_image, :content_type => /\Aimage\/.*\Z/

Ok here's the problem:
When I create without file upload, it works. But when I attach file, params not working and it leaves blank. So when I binding.pry:
[1] pry(#<CourtAgenciesController>)> params
=> {"action"=>"create", "controller"=>"court_agencies"}

Params is missing.

When I update without file upload, it works. But when I attach file, the error is:
Started POST "/court_agencies/53" for 127.0.0.1 at 2015-04-08 16:03:21 +0800

ActionController::RoutingError (No route matches [POST] "/court_agencies/53"):

or just like
Routing Error
No route matches [POST] "/court_agencies/53"

on browser.
I have remotipart installed.
Also Paperclip.
Please help. Need it badly.
UPDATE:

ROUTES:
  #COURT AGENCY
  resources :court_agencies do
    member do
      get 'list'
      put 'update_uin'
    end
    collection do
      get 'get_court_agency_list'
      get 'court_agency_list'
      get 'add'
      get 'get_uin'
    end
  end

This issue is about remote: true. How is it possible to create/update submitting via ajax with file upload?

A: do you have defined attr_accessible in your model...i didnt see that in your model
attr_accessible: :type,:subtype,:division,:associate_justice,:presiding_justice,:map,:landmark_image,


text:
Q: Does a New Who Doctor use the "Broken Plate" analogy? I saw someone post the "Broken Plate Analogy" on Facebook yesterday:

Grab a plate and throw it on the ground.
  -Ok, Done.
  Did it break?
  -Yes.
  Now say sorry to it.
  -Sorry.
  Did it go back to the way it was before?
  -No
  Do you understand?

I immediately thought "oh that's from Doctor Who!"  I went to post as such, but then could not remember the scene exactly, and preferred to be sure before making myself look stupid.  However, I could not find the scene after spending some time searching Google.
My memory is of the 12th Doctor doing it to Clara, perhaps in "Dark Water".  Is this a real thing that happened in an episode of New Who?

A: No.
At least I don't think so.
I searched the Chakoteya transcripts for all mentions of "plate", and the only results which came up in New Who were The Empty Child (Series 1 Episode 9), The Rebel Flesh (Series 6 Episode 5), The Angels Take Manhattan (Series 7 Episode 5), and Robot of Sherwood (Series 8 Episode 3). As you can see by searching for "plate" on the above-linked pages, the only mentions even there are in 'stage directions' and not in actual lines of dialogue.


text:
Q: Unable to install pycrypto on ubuntu 14.04 with python3 I'm trying to install stream package with pip install stream_django which has pycrypto dependency. So while installing pycrypto dependecy it returns me RuntimeError: autoconf error error.
How can i install pycrypto on ubuntu 14.04 with python3

A: I had a other error with pycrypto, so I used pycryptodome.
It basicly is the same. You can install it by typing:
pip install pycryptodome


text:
Q: WordPress - How to concatenate variable with Timber (TWIG) in a loop I use Timber (TWIG) with WordPress.
I'm trying to create a tab system with two differents list of posts. I'm trying to get the number of post for each list (custom post type video and custom post type podcast).
Example : videos (3) / podcasts (12)
I created a loop to get a list of posts for each custom post type (video and podcast).
category.php
    $object_category = get_queried_object();
    $current_category = $object_category->term_id;

    $posts_types_selected = array('videos', 'podcasts');
    $context['posts_types_selected'] = $posts_types_selected;

    foreach ($posts_types_selected as $post_type_selected) {
        $context['posts_'.$post_type_selected] = Timber::get_posts(array(
            'post_type' => array($post_type_selected),
            'post_status' => 'publish',
            'category__in' => array($current_category),
            'posts_per_page' => 10,
            'paged' => 1,
            'has_password' => FALSE
        ));
    }

category.twig

    {% for item in posts_types_selected %}

{{ item }} ({{ 'posts_' ~ item|length }})

    {% endfor %}

I'm trying to have something like that for each li

{{ item }} ({{ posts_videos|length }})

{{ item }} ({{ posts_podcasts|length }})

How to concatenate value in my array $posts_types_selected with posts_
UPDATE
I tried solution here : How to access dynamic variable names in twig?
{% for item in posts_types_selected %}

{{ item }} ({{ _context['posts_' ~ item] }})

{% endfor %}

But I got : Notice: Array to string conversion
I tried this too :
{% for item in posts_types_selected %}

{{ item }} ({{ 'posts_' ~ item }})

{% endfor %}

I got : videos (posts_videos) / podacasts (posts_podcasts)
But it's interpreted as strings and not as variables.
Thank you