text:
Q: How do I map a property with no setter and no backing property fluently with NHibernate? Let's say I have the following entity:
public class CalculationInfo
{
    public virtual Int64 Id { get; set; }

    public virtual decimal Amount { get; set; }

    public virtual decimal SomeVariable { get; set; }

    public virtual decimal SomeOtherVariable { get; set; }

    public virtual decimal CalculatedAmount
    {
        get
        {
            decimal result;

            // do crazy stuff with Amount, SomeVariable and SomeOtherVariable

            return result;
        }
    }
}

Basically I want to read and write all of the fields to my database with NHibernate with the exception of CalculatedAmount, which I simply want to write and not read back in.
Every similar issue and corresponding answer has dealt with specifying a backing store for the value, which I won't have in this scenario.
How can I accomplish this using Fluent NHibernate?
Thanks!
UPDATE:  Here's what I've tried, and the error it leads to:
Here's my mapping for the property...
Map(x => x.CalculatedAmount)
      .ReadOnly();

And the exception it yields...
Could not find a setter for property 'CalculatedAmount' in class 'xxx.CalculationInfo'

A: I figured out that the way get this mapping working in Fluent NHibernate is to simply add the Access Property:
Map(x => x.CalculatedAmount).Access.ReadOnly();

A: I don't use Fluent, but in the mapping a persisted property with no setter is mapped with access="readonly", so look for something like .Readonly()
(Readonly is from the model perspective; the value is written to the DB and used in dirty checks)

A: Looks like it's a calculated value. If you can calculate this value at any given time, then why store it at all?


text:
Q: Curly brackets not getting replaced on xargs command I've been trying to run this command. However, I'm getting some rather unexpected results.
It seems that it's an obvious overlook on my part, but I can't figure it out.
Here's what I tried:
Given that I have a file.txt on the current directory:
find ./ -name *.txt -print0 | xargs --null -I {} echo {}

This successfully returns:
./file.txt

However, if I modify it to echo to a file, like so:
find ./ -name *.txt -print0 | xargs --null -I {} echo 'some string' > {}.alt

The results are not what I would expect:
-rw-r--r-- 1 User 197121     5 Mar  5 20:33 {}
-rw-r--r-- 1 User 197121   908 Mar  5 04:32 file.txt

The desired output would be to have a file named file.txt.alt with some string as content.
If someone could lend a hand, that would be much appreciated.

A: The shell sets up the redirection before your pipeline is run. Instead, you could use something like
find ./ -name '*.txt' -exec sh -c 'for f; do echo "some string" > "$f".alt; done' sh {} +

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL localhost / 127.0.0.1 problem I have a local web server running on my macbook and I've come across a strange problem.  I can access MySQL just fine using a program like Sequel Pro, password works and life is great.
Within PHP, if I have the db server as 127.0.0.1, everything works as well.
However, if I change the db server to localhost, I get access denied for 'root'@'localhost' errors.  I've made sure the MySQL socket is setup correctly, but still cannot use localhost.
Any insight would be awesome.  Thanks!

A: Besides Michael's words,
there's another link: http://dev.mysql.com/doc/refman/5.1/en/connecting.html, it says:

On Unix, MySQL programs treat the host name localhost specially, in a
  way that is likely different from what you expect compared to other
  network-based programs. For connections to localhost, MySQL programs
  attempt to connect to the local server by using a Unix socket file.
  This occurs even if a --port or -P option is given to specify a port
  number.

it's not a typical tcp/ip connection. if u have local port forwarding from 127.0.0.1:3306 to 192.168.1.2:3306, "mysql -h localhost" will try to connect to local unix socket file.
it's not specific to your question(since u're running php), but hope it helps anyway.

A: From here.
Set the initial password for the root user on localhost.
SET PASSWORD FOR root@localhost=PASSWORD('new_password');
FLUSH PRIVILEGES;

A: In your my.cnf file, either change your bind-address to localhost or remove the bind-address setting entirely (which will make mysql listen on all IP's).
The my.cnf file is usually in /etc or /etc/mysql.

A: This is what fixed it for me. PHP.INI defaults to a different location than MySQL for the default socket. To fix, just run these two commands to add an alias (no restart needed):
mkdir /var/mysql
ln -s /tmp/mysql.sock /var/mysql/mysql.sock

Source


text:
Q: Prove or Disprove - power series Let $f(x)$ be a differentiable function for all order $n$ in $\Bbb R$.
Let $R_n(x)$ be McLaurin's remainder of order $n$ of $f(x)$.

Prove or disprove the following statement:
if $$\lim\limits_{x \to 0} \frac{R_n(x)}{x^n}=0$$ for all $n$ then the radius of convergence of the power series $$\Sigma_{n=0}^\infty \frac{f^{(n)} (0)}{n!}\cdot x^n$$ is greater than $\frac{1}{2}$

I think the statement is correct, but I have no idea how to prove it. Couldn't find a counter example.
Thanks!

A: Fix $n\in\Bbb N.$ We have $$R_n(x)=\frac{f^{(n)}(c_x)}{n!}x^n,$$ so $$\frac{R_n(x)}{x^n}=\frac{f^{(n)}(c_x)}{n!}.$$ Now let $x\to 0.$ Since $0\le c_x\le|x|$ we infer that $c_x\to 0$. All derivatives $f^{(k)}$ are continuous, then $f^{(n)}(c_x)\to f^{(n)}(0).$ Dividing by $n!$ we obtain that $f^{(n)}(0)=0$ for all $n$. Now our function is constant under assupmtion that $f$ is equal to its McLaurin's expansion.


text:
Q: Retrieve images from asset folder? In activity class i did this coding...I have few images in assets/folder1/hello.png,hi.png,love.png..i want to retrieve the path of the each image file ??
final String ASSETS_URI ="file:///android_asset";
final String[] IMAGE_IDS =new String[] {ASSETS_URI+"/"+"one.png",ASSETS_URI+"/"+"two.png",ASSETS_URI+"/"+"three.png"};

iv=(ImageView)findViewById(R.id.iv);
if(i>=0 & i< IMAGE_IDS.length-1)
   i=i+1;
else if(i==IMAGE_IDS.length-1)
   i=0;

iv.setImageURI(Uri.parse(IMAGE_IDS[i]));

A: Try Below code:
       AssetManager manager = getAssets();

        try {
            InputStream open = manager.open("one.png");
            Bitmap bitmap = BitmapFactory.decodeStream(open);
            // Assign the bitmap to an ImageView in this layout
            ImageView view = (ImageView) findViewById(R.id.ImageView01);
            view.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }


text:
Q: Why am I getting an undefined error with my xml? I was trying to follow the answer from here: Create XML in Javascript
I am getting an error in the console "undefined is not a function" for the 2nd line here:
var mat = document.createElement("mat");
imgsource = mat.createAttribute("imgsrc");
imgsource.nodeValue = default_matte_source;

total_size = mat.createAttribute("total_size");
total_size.nodeValue = 7.5;

cpu = mat.createAttribute("cpu");
cpu.nodeValue = 12;

cid = mat.createAttribute("cid");
cid.nodeValue = default_matte_cid;

A: createAttribute() is a method of document, not of individual nodes. You'll want something like:
imgsource = document.createAttribute('imgsrc');
imgsource.nodeValue = default_matte_source;
mat.setAttributeNode(imgsource);


text:
Q: Sequelize and MySQL associations I'm working with Sequelize, MySQL and NodeJS. I'm trying to have 3 tables associated which are laid out as follows:
products
product_id
name
description

product_tags
product_id
tag_id

tag_names
tag_id
tag_name

I want to associate products with the tags table and then from there whatever the tag name is associated with the tag_id. Like the following:
SELECT
name,
a.product_id,
group_concat(b.tag_id) as tags,
group_concat(tag_name) as tagName
FROM products a
JOIN product_tags b on b.product_id = a.product_id
JOIN tag_names c on c.tag_id = b.tag_id
WHERE name

Which would then return the product name, tags etc.
I'm just struggling to understand how this works regarding hasMany, belongsTo etc.
My current code is:
db.products.hasMany(db.product_tags, {foreignKey: 'product_id'});

db.product_tags.belongsTo(db.products, {foreignKey: 'product_id'});
db.product_tags.hasMany(db.tag_names, {foreignKey: 'tag_id'});

db.tag_names.belongsTo(db.product_tags, {foreignKey: 'tag_id'});

Which seems to return the correctly laid out tables, but I can't insert a new tag into the tag_name table without it throwing a foreign key error. Any help would be appreciated.

Thanks,
Danny

A: If anyone stumbles upon this answer with the same question I figured it out:
db.products.belongsToMany(db.tag_names, { through: 'product_tags',  as: "tags", foreignKey: 'product_id'});
db.tag_names.belongsToMany(db.products, {through: 'product_tags',  as: "products", foreignKey: 'tag_id'});

Solves the problem.


text:
Q: Using an array of deffered with jQuery.when() I'm using $.when to run 2 functions prior to some other logic. Now, in several cases I need to run a different set of functions prior to doing that same logic, so I wanted to pass an array of the functions to $.when, but couldn't make it run.
Something like:
function funcA(){
    console.log("funcA");
}
function funcB(){
    console.log("funcB")
}
var funcArr = [funcA, funcB];

$.when(funcArr).then(function(){
    console.log("DONE!");
});

But this doesn't work and the only thing written to the console is "DONE!".
I read the following How do you work with an array of jQuery Deferreds?, but the following behaves the same:
$.when.apply($, funcArr).then(function(){
    console.log("DONE!")
});

What's wrong there?
Thanks.

A: Your inputs to $.when aren't of type Deferred, which is the expected input type for the function - http://api.jquery.com/jQuery.when/
At the simplest level, you could construct Deferred types with your functions as the beforeStart construction parameters. Like:
var funcArr = [$.Deferred(funcA), $.Deferred(funcB)];

Here's a working fiddle: http://jsfiddle.net/6MeM5/
Additionally:
If you're just trying to execute each function in an array of functions, you don't need to get Deferred involved. Just iterate the array using $.each, like:
$.each(funcArr, function(){
    this();
});


text:
Q: Not able to center D3 pie chart I'm trying to draw a circle with different data values as angles but for some reason, it's only the last data point that gets the color and display. I've tried to translate the svg but it seems not to budge.
I'm fairly new to D3 so I'm sure I've done something less intelligent without realizing it. As far I could tell, the angles in the g and path elements are as supposed to.
var height = 400, width = 600, radius = Math.min(height, width) / 2;
var colors = ["#red", "pink", "green", "yellow", "blue","magent","brown","olive","orange"];
var data = [1,2,1,2,1,2,1,3,1];

var chart = d3.select("#chart").append("svg")
  .attr("width", width).attr("height", height);
chart.append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var pie = d3.layout.pie().sort(null).value(function (d) { return d; });
var arc = d3.svg.arc().startAngle(0).innerRadius(0).outerRadius(radius);

var grx = chart.selectAll(".sector").data(pie(data))
  .enter().append("g").attr("class", "sector");

grx.append("path")
  .attr("d", arc)
  .style("fill", function (d, i) {
    console.log(d);
    return colors[i];
  });

A: The problem is that you're appending all the sectors of the pie to the svg node when they should be appended to the translated g node, you have two options to solve this problem

*

*make chart equal to the translated g node

*select g before all the .sectors and store that in grx
The first solution is simpler e.g.
var chart = d3.select("#chart").append("svg")
  .attr("width", width).attr("height", height);
  .append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

demo


text:
Q: React.js, adding event listeners in App.js that tie to .jsx pages I am creating an app using react.js and socket.io, I want to add event listeners into my app.js that tie to the html components in my index.jsx file.
Here is my code for App.js

import React, { Component } from 'react';
import io from 'socket.io-client';

import{
  BrowserRouter as Router,
  Route,
  Switch,
  Link,
  Redirect
} from "react-router-dom";

//pages
import MainPage from "./pages/index"

const socket = io.connect('http://localhost:4000');

class App extends Component{
  render(){
    return <Router>
      <Switch>
        <Route exact path="/" component={MainPage}
    </Router>
  }
}

export default App;

here is my code for index.jsx

import React from 'react';
import { Link } from 'react-router-dom';

const MainPage = () => {
    return(

In main page

            <button id="button">
                SPOMBER
            </button>

    );
}

export default MainPage;

Normally, you would just reference a piece of the html code by adding and event listener in a


text:
Q: Pop up not working after using cookies with the popup After several question on Stack Overflow to get my jQuery popup to store cookies and not show again, I'm left with a box on my webpage above the rest of the site in the header which is pushing the site down the page. I can't seem to figure out why its not showing as a pop up over the page, before implementing the use of cookies it would overlay over the page and stop the user from interacting with the page.

function setCookie(cname, cvalue) {
  window.document.cookie = cname + "=" + cvalue;
}

function getCookie(cname) {
  var ca = decodeURIComponent(document.cookie).split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i].trim().split('=');
    if (cname == c[0] && c.length > 1) {
      return c[1];
    }
  }
  return "";
}

function checkCookie() {
  if (getCookie("ageverification") == "") {
    $('#popup, #overlay').show();
    $('#popup a.close').click(function(event) {
      event.preventDefault();
      $('#popup').hide();
      setCookie("ageverification", 'true');
    });
    $('#popup a.goBack').click(function(event) {
      event.preventDefault();
      goBack();
    });
  } else {
    return null;
  }
}

function goBack() {
  window.history.go(-2);
}
$(function() {
  checkCookie();
});
#overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  filter: alpha(opacity=70);
  -moz-opacity: 0.7;
  -khtml-opacity: 0.7;
  opacity: 0.7;
  z-index: 100;
  display: none;
}

.cnt223 a {
  text-decoration: none;
}

.popup {
  width: 100%;
  margin: 0 auto;
  display: none;
  position: fixed;
  z-index: 101;
}

.cnt223 {
  min-width: 300px;
  width: 300px;
  min-height: 150px;
  margin: 100px auto;
  background: #f3f3f3;
  position: relative;
  z-index: 103;
  padding: 15px 35px;
  border-radius: 5px;
  box-shadow: 0 2px 5px #000;
}

.cnt223 p {
  clear: both;
  color: #555555;
  /* text-align: justify; */
  font-size: 20px;
  font-family: sans-serif;
}

.cnt223 p a {
  color: #d91900;
  font-weight: bold;
}

.cnt223 .x {
  float: right;
  height: 35px;
  left: 22px;
  position: relative;
  top: -25px;
  width: 34px;
}

.cnt223 .x:hover {
  cursor: pointer;
}

Important Notice

      You must be over 18 to purchase products containing nicotene, or nicotene related products!

      I am 18+
      I am under 18

A: You want to show message only once.
You need to use javascript sessionStorage function to get this done.

The localStorage and sessionStorage properties allow to save key/value
  pairs in a web browser.
The sessionStorage object stores data for only one session (the data
  is deleted when the browser tab is closed).

Here is the example:

$(function () {
    if (!sessionStorage.getItem('firstVisit') == "1") {
        $("#popup").show();
        sessionStorage.setItem('firstVisit', '1');
    }

    $('#popup a.close').click(function (event) {
        $('#popup').hide();
    });
});

function goBack() {
    window.history.go(-2);
}

#overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  filter: alpha(opacity=70);
  -moz-opacity: 0.7;
  -khtml-opacity: 0.7;
  opacity: 0.7;
  z-index: 100;
  display: none;
}

.cnt223 a {
  text-decoration: none;
}

.popup {
  width: 100%;
  margin: 0 auto;
  display: none;
  position: fixed;
  z-index: 101;
}

.cnt223 {
  min-width: 300px;
  width: 300px;
  min-height: 150px;
  margin: 100px auto;
  background: #f3f3f3;
  position: relative;
  z-index: 103;
  padding: 15px 35px;
  border-radius: 5px;
  box-shadow: 0 2px 5px #000;
}

.cnt223 p {
  clear: both;
  color: #555555;
  /* text-align: justify; */
  font-size: 20px;
  font-family: sans-serif;
}

.cnt223 p a {
  color: #d91900;
  font-weight: bold;
}

.cnt223 .x {
  float: right;
  height: 35px;
  left: 22px;
  position: relative;
  top: -25px;
  width: 34px;
}

.cnt223 .x:hover {
  cursor: pointer;
}

Important Notice

      You must be over 18 to purchase products containing nicotene, or nicotene related products!

      I am 18+
      I am under 18


text:
Q: dropdownlist in asp.net changes the value after post back i have tow dropdownlists in formview when i select from the first dropdownlist i take the value and postback to the same page with this line
response.redirect("addtabs.aspx?SECID="+dropdownlist1.selected value.tostring())
and thi second dropdownlist take th SECID and fill it self with sqldatasource with this parameter every thing ok
but when post back the first dropdownlist doesn't select my choise but select the first item in it
how can i make it still select my selection

A: Are you populating the dropdownlists in the Page_Load method?  If so, then you'll want to wrap that logic in a conditional such as if (!IsPostBack).  Page_Load gets executed on a postback before the event being fired gets executed (such as the button_click handler).  So it would over-write the selected value when it re-populates the dropdownlist.


text:
Q: MySQL Clustered vs Non Clustered Index Performance I'm running a couple tests on MySQL Clustered vs Non Clustered indexes where I have a table 100gb_table which contains ~60 million rows:
100gb_table schema:
CREATE TABLE 100gb_table (
    id int PRIMARY KEY NOT NULL AUTO_INCREMENT,
    c1 int,
    c2 text,
    c3 text,
    c4 blob NOT NULL,
    c5 text,
    c6 text,
    ts timestamp NOT NULL default(CURRENT_TIMESTAMP)
);

and I'm executing a query that only reads the clustered index:
SELECT id FROM 100gb_table ORDER BY id;

I'm seeing that it takes almost an ~55 min for this query to complete which is strangely slow. I modified the table by adding another index on top of the Primary Key column and ran the following query which forces the non-clustered index to be used:
SELECT id FROM 100gb_table USE INDEX (non_clustered_key) ORDER BY id;

This finished in <10 minutes, much faster than reading with the clustered index. Why is there such a large discrepancy between these two? My understanding is that both indexes store the index column's values in a tree structure, except the clustered index contains table data in the leaf nodes so I would expect both queries to be similarly performant. Could the BLOB column possibly be distorting the clustered index structure?

A: The answer comes in how the data is laid out.
The PRIMARY KEY is "clustered" with the data; that is, the data is order ed by the PK in a B+Tree structure.  To read all of the ids, the entire BTree must be read.
Any secondary index is also in a B+Tree structure, but it contains (1) the columns of the index, and (2) any other columns in the PK.
In your example (with lots of [presumably] bulky columns), the data BTree is a lot bigger than the secondary index (on just id).  Either test probably required reading all the relevant blocks from the disk.
A side note...  This is not as bad as it could be.  There is a limit of about 8KB on how big a row can be.  TEXT and BLOB columns, when short enough, are included in that 8KB.  But when one is bulky, it is put in another place, leaving behind a 'pointer' to the text/blob.  Hence, the main part of the data BTree is smaller than it might be if all the text/blob data were included directly.
Since SELECT id FROM tbl is a mostly unnecessary query, the design of InnoDB does not worry about the inefficiency you discovered.
Tack on ORDER BY or WHERE, etc, and there are many different optimizations that could into play.  You might even find that INDEX(c1) will let your query run in not much more than 10 minutes.  (I think I have given you all the clues for 'why'.)
Also, if you had done SELECT * FROM tbl, it might have taken much longer than 55 minutes.  This is because of having extra [random] fetches to get the texts/blobs from the "off-record" storage.  And from the network time to shovel far more data.


text:
Q: Как настроить django рядом с gitlab? На сервере установлен gitlab висит он на субдомене git.domain.com, мне нужно что бы сайт висел на domain.com, при попытке перейти по этому домену браузер ругается на отсутствие ssl, я пробовал нагуглить у меня получился вот такой конфиг
# the upstream component nginx needs to connect to
upstream django {
    server unix:///home/web/project/uwsgi_nginx.sock; # for a file socket
    # server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
    # the port your site will be served on
    listen      8001;

    listen 444 ssl http2 default_server;
    listen [::]:444 ssl http2 default_server;
    server_name domain.com;

    ssl_certificate /etc/gitlab/ssl/domain.com.crt;
    ssl_certificate_key /etc/gitlab/ssl/domain.com.key;

    # the domain name it will serve for
    server_name domain.com www.domain.com; # substitute your machine's IP address or FQDN
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    # Django media
    location /media  {
    alias /home/web/project/media;  # your Django project's media files - amend as required
    }

    location /static {
    alias /home/web/project/static; # your Django project's static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
    uwsgi_pass  django;
    include     /home/web/project/deployment/uwsgi_params; # the uwsgi_params file you installed
    }
}

Но результат тот же, браузер ругается на отсутствие ssl.
Я пробовал выключить letsencrypt letsencrypt['enable'] = false  в настройках гитлаб /etc/gitlab/gitlab.rb
после чего я выполнил команду sudo gitlab-ctl reconfigure но gitlab все равно использует ssl.
Я не понимаю как настроить nginx что бы заработал мой сайт

A: Ответ алгоритм решения Вашей задачи. Пишу по памяти - о настройке gitlab и nginx, если что то непонятно - спрашивайте в комментариях.

*

*Проверить, что гитлаб нормально работает на домене  git.domain.com по https и что его порты, по которым он "торчит наружу" какие нибудь нестандартные, типа 1080 и 1443. Это можно поправить в конфигах гиталаба. Как прикрытить к гитлабу letsencrypt - сертификат - так это каждый школьник знает.

*Проверить, что "сайт" (как я понимаю, под "сайтом" понимается ) какой то сайт "на django" тоже нормально работает по протоколу https и тоже на нестандартном порту.

*Все, теперь осталось настроить nginx так, чтобы он принимал запросы на стандартных портах и работал "регулировщиком", направляя запрос то на "сайт", то на на gitlab.
Как я понимаю, чтобы выполнить 3-й пункт - надо настраивать nginx примерно по такой инструкции: настройка nginx с самого начала
То есть, что я делаю: я убираю всю сложность из конфига nginx, перенося его роль тупо на "разруливателя виртуальных хостов"


text:
Q: Application of first isomorphism theorem Let $G$ and $K$ be groups and let $G\times K$ be the direct product of these two groups. Find a normal subgroup $N$ such that $(G\times K)/N\cong G.$
I think I need to use the first isomorphisms theorem, stating that if $\varphi \colon G\rightarrow H$ is a homomorphism then $G/\ker(\varphi)\cong$ im$(\varphi).$
I'm don't really know where to go from this point though.

A: Consider the canonical projection $G \times K \to G$.
Prove that this is a surjective homomorphism and compute its kernel.

A: You can define $\phi:G\times K\to G\;,\;\;\phi(g,k):=g\;$ . This is homomorphism surjective, and check that $$\ker\phi=\{1\}\times K=N$$
and now use first isomorphism theorem


text:
Q: Quartz default JobFactory implementation do not call setters According to Quratz documentation2.x Here

If you add setter methods to your job class that correspond to the names of keys in the JobDataMap (such as a setJobSays(String val) method for the data in the example above), then Quartz's default JobFactory implementation will automatically call those setters when the job is instantiated, thus preventing the need to explicitly get the values out of the map within your execute method.

Now in my case the setters are not automatically called although my all values are primitives. Also in execute method i am able to get values from jobDataMap.
i am using Quartz 2.2.1 and here is my sample code.what should i do ? thanks in advance.
Here is my Job class.
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class Db2Db implements Job {

  public static final String SOURCE_HOST = "sourceHost";
  public static final String DESTINATION_HOST = "destinationHost";

  protected String sourceHost;
  protected String destinationHost;

  public Db2Db() {
    System.out.println("created object of job");
  }

  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
  //sourceHost is still null
    system.out.println(sourceHost);

  }

  public void setSourceHost(String sourceHost) {
    this.sourceHost = sourceHost;
  }

  public void setDestinationHost(String destinationHost) {
    this.destinationHost= destinationHost;
  }

}

and Here is my main method
  public class JobDriver {

  public static void main(String[] args) throws SchedulerException {

    /*Starting quartz server remotely*/
    QuartzServer server = QuartzServer.getInstance();
    server.start();

    JobDetail job = newJob(Db2Db.class)
        .usingJobData(SOURCE_HOST, "132.168.0.12")
        .usingJobData(DESTINATION_HOST, "localhost")
        .withIdentity("DailyRead91", "group1")
        .build();

    Trigger trigger = newTrigger().withIdentity("DailyTrigger91", "group1").startNow()
        .withSchedule(simpleSchedule().withIntervalInSeconds(10).repeatForever()).build();

    //Quartz Server Properties
    Properties prop = new Properties();
    prop.put("org.quartz.scheduler.rmi.proxy", "true");
    prop.put("org.quartz.scheduler.rmi.registryHost", "localhost");
    prop.put("org.quartz.scheduler.rmi.registryPort", "1099");
    prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
    prop.put("org.quartz.threadPool.threadCount", "10");

    Scheduler scheduler = new StdSchedulerFactory(prop).getScheduler();
    scheduler.scheduleJob(job, trigger);
  }

}


text:
Q: Designing a parking lot Description:
Given a parking lot containing multiple levels and each level containing multiple rows and each row in turn containing multiple spots. The questions is to determine if there are enough spots to check if a vehicle can be parked.
Which object is responsible to determine if there is enough spots, I mean its the parking lot object which is supposed to receive the first query but ultimately it should be either level or row to implement the actual algorithm, right?
Its not about a single class but system as a whole.
Requirement:

*

*The parking lot has multiple levels. Each level has multiple rows of spots.

*The parking lot can park motorcycles, cars, and buses.

*The parking lot has motorcycle spots, compact spots, and large spots.

*A motorcycle can park in any spot.

*A car can park in either a single compact spot or a single large spot.

*A bus can park in five large spots that are consecutive and within the same row. It cannot park in small spots.
The question is that the given system should be able to given answer to the queries like:
Given a car the system should be able to tell if there is a spot for car or not, if yes the answer should be something like:
There is a spot on level x row y and spot z

The issues I face while solving such problems is where to start and how to find correct objects which should represent the domain correctly.
I did try to start somewhere and below is my code:
Enum Size {
  SMALL,
  COMPACT,
  LARGE
}

private class Spot {
  private boolean empty;
  private int number;
  private Size size;

  Spot(Size size, int number) {
    this.size = size;
  }

  full() {
    this.empty = false;
  }

  empty() {
    this.empty = true;
  }

  status() {
    return this.empty;
  }

  boolean canPark(Vehicle vehicle) {
    return false;
  }
}

class LargeSpot extends Spot {
  boolean canPark(Vehicle vehicle) {
    return
      vehicle.size() == Size.LARGE ||
      vehicle.size() == Size.COMPACT ||
      vehicle.size() == Size.SMALL;
  }
}

class CompactSpot extends Spot {
  boolean canPark(Vehicle vehicle) {
    return
      vehicle.size() == Size.COMPACT ||
      vehicle.size() == Size.SMALL;
  }
}

class SmallSpot extends Spot {
  boolean canPark(Vehicle vehicle) {
    return vehicle.size() == Size.SMALL;
  }
}

private class Row {
  private ArrayList<Spot> spots;

  Row(List<Spot> spots) {
    this.spots = spots;
  }

  void spot(Spot spot) {
    this.spots.add(spot);
  }

  List<Spot> getSpots(Vehicle vehicle) {
    List<Spot> emptySpots = new ArrayList<>();
    if (vehicle.size() == Size.LARGE) {
      // five consecutive large spots
      int length = spots.size();
      for (int i = 0; i < length; i++) {
        int j = 0;
        for (; j < 5; j++) {
          if (!spot.canPark(vehicle)) break; // break out of inner loop
        }
        if (j == 5) { // found five spots
          for (int k = i; k < i + j; k++) {
            emptySpots.add(spot);
          }
          i += j;
        }
      }
    } else {
      for (Spot spot : spots) {
        if (spot.canPark(vehicle)) {
          emptySpots.add(spot);
        }
      }
    }

    return emptySpots;
  }
}

private class Level {
  private final int number;
  private final ArrayList<Row> rows;

  Level(number, rows) {
    this.number = number;
    this.rows = rows;
  }
}

class ParkingLot {
  private List<Level> levels;

  ParkingLot(List<Level> levels) {
    this.levels = levels;
  }

  public String status(Vehicle vehicle) {
    List<Spot> emptySpots = new ArrayList<>();
    for (Level level : levels) {
      for (Row : level.rows()) {
        if (row.canPark(vehicle)) {
          emptySpots.addAll(row.getSpots(vehicle));
        }
      }
    }
    return emptySpots;
  }
}

public class Main {
  private final List<Level> floors = new ArrayList<>();
  floors.add(
    new Level(
      0,
      new Row[4]{new SmallSpotSpot(), new CarSpot(), new CarSpot()}));

  floors.add(
    new Level(
      1,
      new Row[4]{
        new LargeSpot(), new LargeSpot(), new LargeSpot(), new LargeSpot()}));

  private final Lot lot = new ParkingLot(floors);
  private final Car car = new Car(Size.Compact);

  System.out.println(lot.status(car));
}

The code definitely broken at many places but the readers can get the faint idea what I am trying to achieve. Also, it can be seen parking Large vehicle is one of the pain points in designing a good solution.

A: You're question is about what to model.
On the one hand, there is an obvious structure to the real-world situation: a lot, having levels, having rows, and ultimately having spots.  So, one approach would be to model all of those items as entities, many of them as collections, e.g. in a hierarchy of objects.
However, in creating an application, you don't necessarily have to model everything that is in the real world, and, the things you do model don't all have to be first-class entities.
What I'm getting at is that you can model all the spots with a single table having primary key as: lot, level, row, spot, and then with attributes type/size (e.g. compact, handicapped, boat/rv), free/occupied.
A search for an available spot is a query against the table, and an update that marks a spot as free/occupied is a simple transaction.
There are lots of other options: in OOP, you can maintain two simple lists: occupied and non-occupied.  The non-occupied list can be broken out into multiple lists by categtories, or maybe even sorted.  The manager holding the collection of spots could search and move items between the lists.
In summary, you should study the domain queries and commands beyond the obvious real-world structure of the real-world parking lot.  It could be that this extra structure (e.g levels, rows) provides almost no real domain value other than simply identifying where the free spot is.  So, there is little reason to organize into multiple tables, and/or, perhaps there is no reason to model a "level" itself as an entity when the level can be captured as a simple (value) attribute.

(There is no way that a parking lot of even tens of thousands of spots would tax a modern computer system, so almost any approach would work.  In such case do the simplest as @DocBrown is suggesting.  Now, if you were doing hotels, you might reach internet scale, and then eventually you'd have some scaling things to deal with.)

We can never model everything, thus, modeling, by definition, is abstraction, in the sense of hiding irrelevant detail so we can focus on what is truly relevant.
Identify the use cases that are relevant to the domain; from those identify the queries and commands to modify the model — starting with noting well the inputs/givens & outputs/desired results — and from those identify what to model along with the actual queries and commands. With this level of understanding, you will begin to see which modeled entities have what responsibilities and which are merely value attributes.  If we model more than necessary, we may loose clarity.

Update for your update:  Don't model more than you need.  Don't use subclasses when value attributes will do.  Don't use object hierarchy when attributes will do.
For example, you're showing modeling the size of the spot using subclassing.  What happens when a particular spot is a handicapped spot?  Now you need a subclass for each handicapped spot size (e.g. class RVHandicappedSpot).  This is class explosion, and a code smell when using classes for modeling things that could otherwise be modeled with attributes.
Further, using attributes you can have numeric ranges rather than only enums, e.g. for the length of a spot.  When we model using classes, it constrains us to distinct values more like the equivalent of enums (compared to numbers).

Regarding the bus parking on multiple spots:
Essentially there are two separate problems: identifying the bus parking spots, and allocating them.  These can be performed at different times; they do not need to be done together.
I'd suggest you model all potential bus parking spots in advance, as spots that themselves are a collection of other spots. Then, you can determine which of the potential bus parking spots are fully unoccupied, and hand them out as needed.  There are a number of considerations here, such as not carelessly hampering bus parking by handing out random car parking spots that belong to the bus parking.
I see the bus parking operations as mostly algorithmic, rather than something solved by a complex data structure.  It is similar to register allocation in compiler technology (e.g. graph coloring) when the processor has register pairs, and such.

There are probably three options for checking whether a spot and vehicle match: the Spot can check if a Vehicle fits in it, or a Vehicle can check if a Spot fits it, or a manager (the Lot or even some third party) can check for the match.
Which is best for your domain is a good question to ask.
Some of the criteria for trade offs involve: do either spot or vehicle have specialization (subclasses) to whom question should be delegated.  If so they should be consulted.  Do either the spot or vehicle have private data that influences matching that cannot be see by the other?  If so, they should be given a chance to approve/deny the match.
I might make the bus parking spots a spot subclass that is a collection of spots.  In that case, there would be some class hierarchy among kinds of spots, but it is not clear to me whether the generic spot algorithm (based on spot size) is sufficient or a specializing override would be needed for the subclass.
Also, we want a stable interface for the outside consuming clients to use.
So, my first take on that would be that I would have that be the manager's (the Lot's) responsibility so that from an external interface point of view the consuming client code only has to deal with the manager, even as the code evolves internally.
However, the manager may simply choose to delegate to the spot or to the vehicle or both (e.g. both have to say yes, then it is a match).
class ParkingLot {
    boolean Matches(Spot spot, Vehicle vehicle) {
        return spot.Matches(vehicle) && vehicle.Matches(spot);
    }
}

A: A first look at the requirements
When you enter a parking lot, and have to drive around to find a free place, the responsibility is not in the spot, nor in the row, nor in the lot, but the driver's. The lot's responsibility is only to count the places that should be free and let you enter if there's place left.
But your case suggest a much more intelligent approach:

*

*being able to determine the spot to be used, depending on the size of the vehicle, requires to know the characteristics and state of each spot.

*being able to determine consecutive spots for a bus, involves the aggregate above the spot.

*answering the request for a new car requires the parking lot to find the place and chose the optimal one in order to maximize the yield (i.e. not wasting a large spot for a motorcycle if it could be avoided, which implies to  allocate motorcycle spots in priority to motorcycles; or allocate isolated free spots to cars, in order to save consecutive free spots for busses).

So clearly, the responsibility will be shared between several objects.
Your model, with a naive approach
Your parking lot looks like a constrained composite:  the parking spot would be a leaf, the row and the lot would be non leaf composites.
At first sight, the prime responsibility would go to the composite, who would pass it down the chain until the first matching element is found. A kind of recursive responsibility...
However the fact that there is a higher level optimisation, i.e. a higher level element making the choice of the best matching place (e.g. if a motorcycle arrives, favor a free motorcycle spot and only if none is available shoulda compact place be envisaged), to split the responsibility between the leaf (i.e.  tell if it's free), the row (i.e. tell the nearest matching free spot), and the parking lot (i.e. chose the row in which there are the most cars, in order to keep contiguous free area for the buses).
Your model with a better approach
The responsibility to chose the best places is in reality not a responsibility of the parking, but a responsibility of an assignment authority. Nevertheless, the interaction between the car and the parking lot requires to give a partial responsibility to the lot:
  Car ---<request>--->  Parking lot ---<request>---> Allocator
      <---<answer>----              <---<choice>----

If the parking lot is a kind of composite, the allocator could be implemented as a visitor, i.e. a separate object that explores the composite, and constructs some aggregation (e.g. an ordered list of potential free spots). The composite has to collaborate with the visitor.
To make it even more flexible and powerful, the visitor could use a strategy for ordering the potential free spaces to be given for a specific size of vehicle, and implementing different kind of allocation heuristics.
Is this overengineered ?  Link to the real world
There are a couple of airports in my area, where a detector on each spot displays a red line if it's taken and a green light if it's free (we are at leaf level, for the state of the spot). In front on each row, there's a sign that shows how many free spots there are in the row, and at the entry, there's the number of free spots in the lot.  THere is no allocation responsibility, but clearly, each of your identified object would be somehow involved in the overall responsibility.
So, no, I don't think this is over-engineered in an aera of smart parkings and smart cities ;-)

A: For simple systems, as yours appears to be, the easiest way to determine responsibilities is to simply write a quicky use-case. From that, draw a sequence diagram. Once you learn how to write a use-case at the appropriate level of abstraction you are working at then it tends to become fairly trivial.
Use-Case: Find Parking Spot
1 - Operator requests to find parking spot for vehicle from system.
2 - System requests that Parking lot find a parking spot that vehicle can fit in.
3 - Parking lot returns parking spot to operator.
4 - Operator reports location of parking spot.
From this you can infer that you have an 'Operator' subsystem (the UI). ParkingLot and ParkingSpot subsystems.  A System subsystem (usually just the subsystem that sequences the use-case processing steps. I tend to call them Operation classes).  'Vehicle' can be modeled as a subsystem or just a parameter to the 'FindParkingSpot' operation; sometimes one approach works better than the other.
Usually drawing the corresponding sequence diagram makes the responsibilities obvious. Which in this case would be the ParkingLot knows how to search ParkingSpots to determine where to park.
How ParkingLot makes that determination would depend entirely on the next level of design where obsessing over 'which object is responsible' is usually pointless as it tends to boil down to meeting some nebulous idea of 'good' the designer has in their mind that in practicality is generally pretty arbitrary.
Since it seems like you are still in the OOP learning process there's no reason to worry about anything other than turning the identified subsystems directly into classes. As you advance then there will be other issues that you may be concerned about which causes those subsystems to possibly turn into a number of classes. But, that isn't worth worrying about because without the necessary experience, attempting to apply more advanced concepts is almost certainly going to result in a much worse design than simply converting the subsystems directly to classes. You will get a very usable design if you simply do a good job of assigning responsibilities to subsystems.
It is also worth pointing out that Row and Level are simply attributes of a parking spot, so they wouldn't have any responsibilities.


text:
Q: Xpath query for same level tags..? I have an XML file -
<Books>
  <Book>
    <PubDetails>
       <Pub Name="ABC"/>
       <Year Y="1999"/>
    </PubDetails>
    <Book Subject="Computers">XPath 2.0</Book>
  </Book>
  <Book>
    <PubDetails>
       <Pub Name="ABC"/>
       <Year Y="1999"/>
    </PubDetails>
    <Book Subject="Management">Financial Management</Book>
  </Book>
</Books>

I want to retrieve the Subject when Y is passes as parameter.
For Ex: If I pass 1999, then I should get Computers, Management as output.
What will be the XPath 1.0 query?

A: Consider that the parameter year contains the value.
//Book[PubDetails/Year/@Y = $year]/Book/@Subject


text:
Q: How to use string, switch, case and bufferedreader? I got question if how can i use the string, switch, case and the bufferedreader?
In my situation, the output should be ->
Choose your password:
A.Thepasskey
B.12345
C.54321
Then if i choose "thepasskey" it appears
"the passkey you entered is thepasskey".
Then if i entered the wrong password that not on the choicelist, the appearance will be
"error! Check your data!".
Can anybody answer?

A:     public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Choose your password:");
    System.out.println("A. Thepasskey");
    System.out.println("B. 12345");
    System.out.println("C. 54321");
    String line = br.readLine();
    switch (line) {
        case "A"://if one type A as choice
            System.out.println("Thepasskey");
            break;
        case "B":
            System.out.println("12345");
            break;
        case "C":
            System.out.println("54321");
            break;
        default:
            System.out.println("error! Check your data");
            break;
    }
}


text:
Q: How to extract source from website as we see in inspect element I would like to extract the complete html source of website as we get it on chrome inspect element.
I am trying to the scrap the comments of disqus from http://bossip.com/1190557/cops-kill-people-mississippi-cop-under-investigation-for-strangling-unarmed-black-man-jonathan-sanders-to-death-43081/
Initially I tried with java and Jsoup but I am unable to extract the complete html source.
Then as suggested in How to get html that I see in inspect element? I tried using HTML Unit but unfortunately HTML unit also did not extract as i expected.
Is there any solution around for this problem?

A: In Chrome,

*

*in normal browser document: right-click on element, select "Inspect Element" from pop-up menu. You will go to the "developer tools" window.

*in developer tools window: right-click on the HTML element and select "Edit as HTML" from pop-up menu.

*select all HTML text in the editor (press CTRL-A) and copy to clipboard (press CTRL-C)


text:
Q: How to get a product collection which have 'feature' attribute = Yes? I created a Yes or No attribute called 'feature'. I have a Product Tab slider on the home page. On that tab it had Best Seller, Latest Product and Latest Deal. I want to add Feature Product (product is 'feature' attribute is set to "Yes") also on that tab.

<?php
/**
 * Tab Links
 */
$class = $_compareUrl = $currentDate = '';
?>

<?php echo Mage::helper('marketplace')->__('Bestsellers'); ?>

<?php echo Mage::helper('marketplace')->__('Latest Products'); ?>

<?php echo Mage::helper('marketplace')->__('Latest Deal'); ?>

    <?php
    /**
     * Best seller products
     */?>

         <?php $bestSellingCollection = $this->bestSellerCollection ();
                $categoryCount = count ( $bestSellingCollection );
                if ($categoryCount >= 1) { ?>

                <div class="products-grid <?php if($categoryCount>4){ echo 'slider-carousel'; } else { echo 'no-slider'; } ?>">
                    <?php $increment =1;
                    foreach ( $bestSellingCollection as $_bestSellingCollection ) { ?>
                        <div class="slider <?php if($increment==4) { echo 'last';} ?>">

                              <?php
                                /**
                                 * Display product image
                                 */
                                ?>
                                 <a href="<?php echo $_bestSellingCollection->getProductUrl() ?>" title="<?php echo $this->escapeHtml($_bestSellingCollection->getName()) ?>" class="product-image">
                                    <?php $_imgSize = 260; ?>
                                    <img src="<?php echo $this->helper('catalog/image')->init($_bestSellingCollection, 'small_image')->resize($_imgSize); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($_bestSellingCollection, 'small_image'), null, true) ?>" />

                            <a href="<?php echo $_bestSellingCollection->getProductUrl(); ?>">
                               <?php $prName = $_bestSellingCollection->getName ();
                                    $lenPrName = strlen ( $_bestSellingCollection->getName () );
                                    $subPrName = substr ( $prName, 0, 26 );
                                    if ($lenPrName >= 26) {
                                        $prNameFix = $subPrName . "...";
                                    } else {
                                        $prNameFix = $prName;
                                    }
                                    echo $prNameFix;?>

                                <?php
                                    /**
                                     * Display Product Price
                                     */
                        $newPrice = $_bestSellingCollection->getPrice ();
                        $newSplPrice = $_bestSellingCollection->getSpecialPrice ();
                        $newDealExpireDate = $_bestSellingCollection->getspecial_to_date ();
                        if (! empty ( $newSplPrice ) && ($newDealExpireDate != '') && ($newDealExpireDate >= $currentDate)) {
                            echo Mage::helper ( 'core' )->currency ( $newSplPrice, true, false );
                        } else {
                            echo Mage::helper ( 'core' )->currency ( $newPrice, true, false );
                        }
                        ?>

                        <?php
                        /**
                         * Display Add to cart, add to wishlist and compare
                         */
                        ?>

                                    <a  href="<?php echo $this->helper('wishlist')->getAddUrl($_bestSellingCollection) ?>"  title="<?php echo $this->__('Add to Wishlist') ?>"  class="link-wishlist <?php echo $class; ?>">
                                        <?php echo $this->__('Add to Wishlist') ?>

                                    |

                                    <a href="<?php
                                    echo Mage::helper('catalog/product_compare')->getAddUrl($_bestSellingCollection);
                                    ?>" class="link-compare" title="<?php echo $this->__('Add to Compare') ?>">

                                        <?php echo $this->__('Add to Compare') ?>

                                 <?php if($_bestSellingCollection->isSaleable()){ ?>
                                    <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo Mage::helper('checkout/cart')->getAddUrl($_bestSellingCollection) ?>')">
                                        <?php echo $this->__('Add to Cart') ?>
                                    </button>
                                <?php } else {?>

                                        <?php echo $this->__('Out of stock') ?>

                                <?php } ?>

                        <?php
                        /**
                         * Check product is set as new or not
                         */
                        ?>
                    <?php echo $this->helper('marketplace/marketplace')->getLabel($_bestSellingCollection);  ?>

                    <?php $increment++; } ?>

                <?php }
                else {
                    echo $this->__("No bestselling product[s] available to show");
                }?>

                    <?php $newProducts = $this->getNewproduct ();
                    $newCount = count ( $newProducts );
                    if ($newCount >= 1) {?>

                    <div class="products-grid <?php if($newCount>4){ echo 'slider-carousel'; } else { echo 'no-slider'; } ?>">
                    <?php $increment =1;
                    foreach ( $newProducts as $new ) {      ?>
                             <div class="slider <?php if($increment==4) { echo 'last';} ?>">

                            <?php   $newproduct = $this->helper ( 'catalog/image' )->init ( $new, 'small_image' )->constrainOnly ( TRUE )->keepAspectRatio ( FALSE )->keepFrame ( FALSE )->resize ( 226, 226 );?>
                            <?php
                            /**
                             * Display New Products of this seller
                             */
                            ?>

                        <a href="<?php echo $new->getProductUrl() ?>" title="<?php echo $this->escapeHtml($new->getName()) ?>" class="product-image">
                                    <?php $_imgSize = 260; ?>
                                    <img src="<?php echo $this->helper('catalog/image')->init($new, 'small_image')->resize($_imgSize); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($new, 'small_image'), null, true) ?>" />

                                <a href="<?php echo $new->getProductUrl(); ?>">
                                            <?php
                            $newProductName = $new->getName ();
                            $newLengthProductName = strlen ( $new->getName () );
                            $newSubProductName = substr ( $newProductName, 0, 26 );
                            if ($newLengthProductName >= 26) {
                                $newProductNameFix = $newSubProductName . "...";
                            } else {
                                $newProductNameFix = $newProductName;
                            }
                            echo $newProductNameFix;
                            ?>

                                                <?php
                            /**
                             * Display Product Price
                             */
                            $newPrice = $new->getPrice ();
                            $newSplPrice = $new->getSpecialPrice ();
                            $newDealExpireDate = $new->getspecial_to_date ();
                            if (! empty ( $newSplPrice ) && ($newDealExpireDate != '') && ($newDealExpireDate >= $currentDate)) {

                                echo Mage::helper ( 'core' )->currency ( $newSplPrice, true, false );
                            } else {
                                echo Mage::helper ( 'core' )->currency ( $newPrice, true, false );
                            }
                            ?>

                                <?php
                            /**
                             * Display Add to cart, add to wishlist and compare
                             */
                            ?>

<a
                                href="<?php echo $this->helper('wishlist')->getAddUrl($new) ?>"
                                title="<?php echo $this->__('Add to Wishlist') ?>"
                                class="link-wishlist <?php echo $class; ?>"><?php echo $this->__('Add to Wishlist') ?>

| <a
                                href="<?php echo Mage::helper('catalog/product_compare')->getAddUrl($new);  ?>" class="link-compare" title="<?php echo $this->__('Add to Compare') ?>"><?php echo $this->__('Add to Compare') ?>

                       <?php if($new->isSaleable()): ?>
                        <button type="button"
                            title="<?php echo $this->__('Add to Cart') ?>"
                            class="button btn-cart"
                            onclick="setLocation('<?php echo Mage::helper('checkout/cart')->getAddUrl($new) ?>')">
                            <?php echo $this->__('Add to Cart') ?>
                        </button>
                    <?php else: ?>

                            <?php echo $this->__('Out of stock') ?>

                    <?php endif; ?>

                    <?php
                            /**
                             * Check product is set as new or not
                             */
                            ?>
                    <?php echo $this->helper('marketplace/marketplace')->getLabel($new);  ?>

                        <?php $increment++; } ?>

          <?php }
          else {

                echo $this->__("No new product[s] available to show");
                }?>

<?php $products = $this->getProductCollection()->setPageSize(100);
$coreHelper = $this->helper('core');
$class = '';
 if (count($products) > 0){ ?>

<div class="products-grid <?php if(count($products)>4){ echo 'slider-carousel-deal'; } else { echo 'no-slider'; } ?>">
    <?php $i = 1;
    foreach ($products as $item){ ?>
                <div class="slider <?php if($i==4) { echo 'last';} ?>">
                    <?php
                    $originalPrice = $item->getPrice();
                    $discountPrice = $item->getSpecialPrice();
                    $savings = $originalPrice - $discountPrice;
                    $savingsPercentage = round(($savings / $originalPrice) * 100, 0);
                    for ($increment = 0; $increment < 1; $increment++) { ?>

                          <?php
                          /**
                           * Display product image
                           */
                          ?>
                            <a class="product-image" href="<?php echo $item->getProductUrl() ?>" >
                               <?php $_imgSize = 260; ?>
                                    <img src="<?php echo $this->helper('catalog/image')->init($item, 'small_image')->resize($_imgSize); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($item, 'small_image'), null, true) ?>" />

                        <a href="<?php echo $item->getProductUrl(); ?>">
                           <?php
                           $prName = $item->getName();
                           $lenPrName = strlen($item->getName());
                           $subPrName = substr($prName, 0, 26);
                            if ($lenPrName >= 26) {
                               $prNameFix = $subPrName . "...";
                            } else {
                               $prNameFix = $prName;
                            }
                               echo $prNameFix;
                            ?>

                <?php
                    /**
                     * Display of price details
                     */
                    ?>

                            <?php if($item->getPrice() > $item->getSpecialPrice()){ ?>

                                    <?php echo $coreHelper->currency($item->getPrice(), true, false); ?>

                                    <?php echo $coreHelper->currency($item->getSpecialPrice(), true, false); ?>

                                     <?php echo $this->__('Discount: ') ?>

                                <span class="discount_price" <?php echo $this->getIdSuffix() ?>>
                                      <?php echo $savingsPercentage, '%';?>
                                      <?php echo $this->__('Off');
                                      ?>

                                <?php }else{ ?>

                                    <?php echo $coreHelper->currency($item->getPrice(), true, false); ?>

                                <?php } ?>

                            <?php
                            /**
                             * Display Add to cart, add to wishlist and compare
                             */
                            ?>

<a href="<?php echo $this->helper('wishlist')->getAddUrl($item) ?>" title="<?php echo $this->__('Add to Wishlist') ?>" class="link-wishlist <?php echo $class; ?>"><?php echo $this->__('Add to Wishlist') ?>

| <a href="<?php
                            $_compareUrl = Mage::helper('catalog/product_compare')->getAddUrl($item);
                            echo $_compareUrl ?>" class="link-compare" title="<?php echo $this->__('Add to Compare') ?>"><?php echo $this->__('Add to Compare') ?>

                       <?php if($item->isSaleable()): ?>
                        <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo Mage::helper('checkout/cart')->getAddUrl($item) ?>')"><?php echo $this->__('Add to Cart') ?></button>
                    <?php else: ?>

<?php echo $this->__('Out of stock') ?>

                    <?php endif; ?>

                    <?php
                    /**
                     * Check product is set as new or not
                     */
                    ?>
                    <?php echo $this->helper('marketplace/marketplace')->getLabel($item);  ?>

                    <?php } ?>

                    <?php $i++; } ?>

 <?php } ?>

A: You can add addAttributeToFilter to the collection for feature attribute like
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('feature', array('eq' => 'Yes')); // or 0 or 1 iff you are using Boolean values

foreach ($collection as $product) {
    //var_dump($product);
    var_dump($product->getData());
}


text:
Q: How to remove an item after mutation from Apollo Cache? I have a mutation which removes item from the database. I know that one of the possible ways to update the Apollo Cache is to specify an update function which will be called after success response. I also know that there're couple of ways to do it by using cache.modify and cache.readQuery/cache.writeQuery functions.
Examples provided by the Apollo documentations shows how to remove an item from a list. Unfortunately, provided example in an article shows how to update a nested property instead of removing entire object.
Could you help me please to understand how to correctly remove an entire item from the cache?
I use Apollo-Client v3+
This is my part of the code
export const REMOVE_ITEM_MUTATION = gql`
  mutation RemoveItem($itemId: String!) {
    removeItem(input: {
      itemId: $itemId
    }) {
      itemId # Returns an id of successfully deleted object
    }
  }
`

const [removeItem, { loading }] = useMutation(
  REMOVE_ITEM_MUTATION,
  {
    update: (cache, result) => {
      // How to use cache.modify?
    },
    onError: (error) => { /*...*/ },
    onCompleted: (value) => { /*...*/ }
  }
)

P.S. I also confused if cahce.modify function can replace cache.readQuery and cache.writeQuery? I treat it like a new way of modifying the cache starting from Apollo Client 3. Am I right?


text:
Q: Visual Studio Vs Visual Web Developer I am trying to write a web application using ASP.NET MVC. I prefer C# as the programming language.
Which IDE is better to use for this purpose? Visual Studio or Visual Web Developer?
What are the features of the IDEs? What are the benefits of using one over the other?
Thanks in advance.

A: As far as I understand, Visual Web Developer (VWD) is simply a free version of the Visual Studio components necessary to develop web based solutions.
Here is a list of features missing from VWD that you get in a Professional edition of Visual Studio 2008 (VS2008). In short, VWD Express 2005

*

*is Not Extensibile with other add-ons or third party tools

*Only supports Web site projects (2005). You cannot add a Class
Library project or a Web Controls
Library project to the solution.
UPDATED - VWD 2008 SP1 also allows Web Application and Class Library Projects in the solution.

*Lacks the ability to combine Source Code Control

*has no Accessibility checker

*Lacks ability for automatic generation of resources for
localization

*Cannot attach debugger to a process

*has no Native code debugging

The obvious advantage of VWD over VS2008 is that it is free and if you can work smart with it given the missing features, it may be the more pragmatic option for you. If those are features that you can't live without, VS2008 may be a wise investment - you also get all of the features missing from other Express products (Visual Basic 2008, Visual C# 2008, etc).
Take a look at MSDN's comparison chart for Visual Studio 2005. I can't find 2008's but would suspect it to be very similar.

A: Visual Studio will allow you to integerate with Source control and attached debugging to IIS processes.
As a lone developer knocking up some pure ASP.NET-MVC application then Web Developer would do, for serious work you really need studio.

A: I think you also lack the ability to publish a site without visual studio, you can certainly run a website, but it won't build the binaries for release, with web developer you have to publish the source to iis.


text:
Q: Password Protect Mongrel in Development Mode I have a client who is concerned that someone may discover the IP of our development server and attempt to steal new features before we release them. (Because we have external links and embeds, it is possible to track back while testing). I was looking for a way to password protect the server ONLY in development mode (I don't want to have to change code before every deployment). I was thinking of doing super basic authentication through a controller like:
if RAILS_ENV == "development"
  collect = require_password #some action or method or something here... Figure it out later...
  if collect != "foobar"
    redirect_to "http://www.google.com"
  end
end

I feel like this is an oddly stupid way of doing this, however, it's not like we need epic security, just something to fumble people who might stumble across the site in development mode.

A: In your controller add the following lines
  USER_NAME, PASSWORD = "user", "password"
  before_filter :authenticate_testing

The code for before_filter looks like this
 def authenticate_testing
   if Rails.env.development?
    authenticate_or_request_with_http_basic do |user_name, password|
      user_name == USER_NAME && password == PASSWORD
    end
   end
 end


text:
Q: Customize Google Chart Column Filter I've been trying to figure out how to customize the column filter with my own style, but for some reason, Google have decided to put the rendered HTML at the bottom of the body-tag, in other words: the menu from column filter is attached to the DOM outside of the control itself at the bottom of the body-tag. Why on earth have they decided to put it there? This makes me a bit upset, because this is forcing me to put a lot of !important;after every new CSS rule I want.
I've also read about it in the Google Docs how to call the ui.cssClass, but this doesn't help me a bit. Is there anyone else who managed to fix this problem? Is it even possible to create your own markup for this?
Example here where you can see my point.
I will put some of my code below here so you can get a clear image on what's going on here.
JavaScript:
var columnFilterOptions = {
    filterColumnLabel: 'colLabel',
    ui: {
        caption: "Compare",
        label: false,
        allowTyping: false,
        allowMultiple: true,
        allowNone: false,
        selectedValuesLayout: 'below'
    }
};

HTML:

CSS/LESS:
.charts-menu-button-disabled {
    background: @grayLighter !important;
    opacity: 0.5 !important;
}

.charts-menu-button-outer-box {
    width: 100%;
    border: 0 !important;
}

.charts-menu-button {
    background: @grayLighter !important;
    margin: 0 !important;
    margin-bottom: @smallGutter !important;
}

.charts-menu-button-open {
    background: @blueLight !important;
}

.charts-menu-button,
.charts-menu-button-inner-box {
    color: @grayDark !important;
    width: 100%;
    line-height: 55px;
    border: 0 !important;
    padding: 0 !important;
}

.charts-menu-button:before,
.charts-menu-button-inner-box:before {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    width: 60px;
    height: 55px;
    overflow: hidden;
    background: @grayLight;
    text-align: center;
}

.charts-menu-button-open:focus:after {
    content: "";
    display: block;
    position: absolute;
    top: 17px;
    right: 27px;
    background: url(../../content/images/sprites.png);
    width: 7px;
    height: 19px;
    background-position: -31px -90px;
}

.charts-menu-button:after {
    content: "";
    display: block;
    position: absolute;
    top: 17px;
    right: 27px;
    background: url(../../content/images/sprites.png);
    width: 7px;
    height: 19px;
    background-position: -16px -110px;
}

.charts-menu-button-caption {
    .proxima-nova();
    padding-left: @smallGutter !important;
    font-size: 1.1em;
}

.charts-menu-button-dropdown {
    background: none !important;
}

.charts-menu,
.charts-menu-vertical {
    overflow: auto;
    width: auto !important;
    min-width: 11.19% !important;
    margin: 0;
    border: 0 !important;
    background: @grayLighter !important;
    border-top: 2px solid @green !important;
    padding-right: @smallGutter !important;
}

.charts-menuitem-content {
    width: 100%;
    color: @grayDark !important;
    .proxima-nova() !important;
    font-size: 16px !important;
    padding: 10px 0;
    display: block;
    border-top: 2px solid transparent;
}

.charts-menuitem-content:hover {
    color: @blue !important;
    border-top: 2px solid @blue;
}

.charts-menuitem-highlight {
    background: none !important;
    border: 0 !important;
    border-width: 0 !important;
    padding: 4px 0 4px 28px !important;
}
li.charts-container-horizontal {
    padding: 10px !important;
    border: 0 !important;
    border-radius: 0 !important;
    background: @grayLighter !important;
    .charts-link-button {
        .proxima-nova() !important;
        font-size: 1.1em !important;
        color: @grayDark !important;
    }
    .charts-control {
        .proxima-nova();
    }
}

A: You can use ui.cssClass in the ControlWrapper options, but you need to call up JQuery and embed it like this:
$(".columnFilter_class .charts-menu-button-caption").css({"color":"red"});
Doing that worked for me.


text:
Q: Gradle Multi-project build - project dependencies and build order I need to migrate a multi-project build from maven to gradle and maintain the way inter-project dependencies and build order work. I'd like to use the maven plugin in gradle and continue to publish artifacts to both local and remote maven repositories.
The multi-project structure is like so:
root/
--Project-A/
----Project-A1/
----Project-A2/
--Project-B/
----Project-B1/
----Project-B2/
In maven Project-A2 has a dependency on Project-A1. If I run mvn install_ from the Project-A2 directory it will only build/install that project and pull it's dependency on Project-A1 from the local/remote maven repository. If I run mvn install from Project-A it will build/install both Project-A1 and A2 and calculate the build order based on the above mentioned dependency. How can this same behavior be achieved in gradle?
Additionally, Project-B2 has a dependency on Project-A2. If I run mvn install from the Project-B2 or Project-B directories this dependency should be pulled from the local/remote maven repository. If I run mvn install from the root directory it should calculate the build order such that Project-A1 builds, Project-A2 builds, and then _Project-B2 builds.

A: That build order, as far as I know, isn't exactly possible with gradle. If you're building A2 and A1 has changed, gradle will build A1. If A1 hasn't changed then it won't be built. Same goes for the second scenario.


text:
Q: What's the proper way to set up an user pool on Angular with a serverless build I'm working on a POC application that is completely serverless. This application is written in Angular, the authentication system is built using AWS Cognito.
The user pool was already created so I had to take the approach of reusing an existing backend as provided by Amplify docs:
https://docs.amplify.aws/lib/auth/start/q/platform/js/#re-use-existing-authentication-resource
For this case, I'm not using the Hosted UI, but instead, I built my own and only consumed Amplify's methods for the whole flow.
The connection values to the user pool are in the main.ts file like this:
const userPoolConfig: CognitoConfig = {
  region: 'us-east-1',
  userPoolId: 'us-east-1_xxxxxxx',
  userPoolWebClientId: 'xxxxxxxxxxxxxxxxxx',
};

Amplify.configure(userPoolConfig);
Auth.configure(userPoolConfig);

However, I do have a concern about how to protect my user pool from being used by third-party entities if they get the userPoolId and userPoolWebClientId
What should be the right approach in this case if there's no backend on an application of the sort?
I could not find anything that answers that question on the AWS docs or Amplify.
What should be the best practice here?


text:
Q: Why is number().min() not working in Yup validation? Here is my Yup schema. The validation on asset works fine, but I'm not sure why it is not working on the amount?
  const validationSchema = Yup.object().shape({
      asset: Yup.string().required("Required!"),
      amount: Yup.number()
        .required()
        .min(5, "Must be more than 5")
        .positive(),
    });

A: You may add number.min(1, '') & number.max(1,'').
To specify the minimum and maximum quantity also

A: <Typography color="error.main">
   { errors?.bonus_add }
</Typography>

...
 bonus_add: yup.number()
    .test('numbers', 'Допустимы только цифры', value => !value || /^[0-9]+$/.test(value))
    .test('lessThanTen', 'Поле "Количество бонусов" должно содержать не более 9 символов', value => !value || value.toString().length < 10)
    .required('Обязательное поле'),


text:
Q: How to get repeating element in XSLT 2.0 I want to get the repeating "Author" element in the following XML structure against each product. How will i do it? I am using the following online tool for testing
http://xslttest.appspot.com/
XML
<OrderDocument>
  <OrderProduct>
    <Product>
      <ProductDescription>ProductDescription</ProductDescription>
      <Author>Author</Author>
      <Author>Author</Author>
    </Product>
   </OrderProduct>
   <OrderProduct>
    <Product>
      <ProductDescription>ProductDescription</ProductDescription>
      <Author>Author</Author>
      <Author>Author</Author>
    </Product>
   </OrderProduct>
   <OrderProduct>
    <Product>
      <ProductDescription>ProductDescription</ProductDescription>
      <Author>Author</Author>
      <Author>Author</Author>
    </Product>
   </OrderProduct>
</OrderDocument>

XSLT File:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  version="1.0">
  <xsl:template match="//OrderDocument">

   </xsl:template>
</xsl:stylesheet>

Output Required:
<Message>
 <Product>
           <Author>Author</Author>
          <Author>Author</Author>
 </Product>
  <Product>
           <Author>Author</Author>
          <Author>Author</Author>
 </Product>
</Message>

A: For a transformation where you are not changing the entire XML document, you usually start off with the XSLT identity template
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

Then you only need to write templates for the nodes you do wish to transform. Looking at your input and expected output, there are three things you need to do
Rename the OrderDocument element to Message
Remove the OrderProduct element, but keep processing its children
Remove the ProductDescription element entirely
Each of these can be achieve by a separate template. Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes" />

    <!-- Rename OrderDocument to Message -->
    <xsl:template match="OrderDocument">
        <Message>
            <xsl:apply-templates/>
        </Message>
    </xsl:template>

    <!-- Remove OrderProduct, but keep processing its children -->
    <xsl:template match="OrderProduct">
        <xsl:apply-templates/>
    </xsl:template>

    <!-- Remove ProductDescription entirely -->
    <xsl:template match="ProductDescription" />

    <!-- Identity Template for everything else -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>


text:
Q: Is there a way I can find a div element by both its css 'left' and 'top' attributes? I have a list of div that look like this below:

I have a bunch of these on a grid and as part of my floodfill algorithm, I want to select adjacent grids by left and top as my x and y coordinates. So far I can't seem to figure out how to get this to work. Does anyone have a recommendation as to how to accomplish this?
From a stackoverflow question I have tried the following selector:
$("div['style=left: 0px; top:0px;']");

I think this is close but I get this error:
jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: div['style=left: 0px; top:0px;']

A: how about something like:
$(".blockattribute").filter(function(ind,el){return $(el).offset().left == your_value && $(el).offset().top == your_value})

or if you are intent on using css values, you can do something like:
$(".blockattribute").filter(function(ind,el){return $(el).css("left") == your_value+"px" && $(el).css("top") == your_value2+"px"})

A: You're selecting it wrong. One way to achieve this is to iterate the divs and check its left and top value.

$(function() {
  var selectDiv = function(left, top) {
    var $arrDiv = [];
    $('div.blockattribute').each(function(i, v) {
      var $div = $(v);
      $arrDiv.push($div);
    });

    for (var i = 0; i < $arrDiv.length; i++) {
      var $div = $arrDiv[i];
      var offset = $div.offset();
      if (offset.left === left && offset.top === top) {
        return $div;
      }
    }

    return null;
  }

  var $selectedDiv = selectDiv(20, 20);
  console.log($selectedDiv.attr('id'));
});
.blockattribute {
  width: 20px;
  height: 20px;
  display: block;
  position: absolute;
}

Note: Check Evan's answer which has cleaner solution than this.

A: First off, your code $("div['style=left: 0px; top:0px;']"); is syntactically invalid. It needs quote around the attribute value only like this:
$('div[style="left: 0px; top:0px;"]');

That being said, it still won't get you the desired result since your inline style would have to match exactly.
To get a bit closer you can use wildcard attribute selector to get part of the inline style like this, though it's really going to be very finicky and so much as a single whitespace will cause this to fail.

$('div[style*="left: 0px; top: 0px"]').html('test345');

test 123

A bit more on this here: https://css-tricks.com/attribute-selectors/#rel-anywhere.


text:
Q: Personalize JComboBox Java I wanted to customize a JComboBox so I used a model with ListCellRenderer my goal was to change the background of an item by hovering to an orange and I got it.
Example of how it turned out:

But I change the style of the combo box slightly, it looks somewhat metallic, how could I make it look like the original, that the background color when passing the pointer is not blue but a type of orange, the color code I used was [255,142,0]
Example of the original:

Here I show the code that I use to customize the combo box:
public class PropertyCombo extends BasicComboBoxUI {

    Color c = new Color(255, 142, 0);

    public static ComboBoxUI createUI(JComponent com) {
        return new PropertyCombo();
    }

    @Override
    protected ListCellRenderer createRenderer() {
        return new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> jlist, Object o, int i, boolean bln, boolean bln1) {
                super.getListCellRendererComponent(jlist, o, i, bln, bln1);

                jlist.setSelectionBackground(c);

                return this;
            }
        };
    }
}

And the code to add this customization to the JComboBox is:
cbx_name.setUI(PropertyCombo.createUI(this));


text:
Q: Powershell "A positional parameter cannot be found that accepts argument" I'm getting this below error trying to run this code and I'm not sure how to resolve it. Anyone ideas?
$ChocoPackage = "packagename"
$localprograms = choco list --localonly
Start-Process -Wait -FilePath "C:\ProgramData\chocolatey\choco.exe" -ArgumentList "install $ChocoPackage -ia "'/D=C:\Program Files\packagename'" -y"

Start-Process : A positional parameter cannot be found that accepts argument '/D=C:\Program Files\packagename'.
At C:\Program Files\install.ps1:3 char:5
+     Start-Process -Wait -FilePath "C:\ProgramData\chocolatey\choco.ex ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Start-Process], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand

A: Note:

*

*As you point out in your own answer, special quoting requirements apply to choco.exe's /ia parameter.

*However, since you are using Start-Process, it is not the instructions from the linked page for PowerShell that apply in this case, but the ones for cmd.exe (even though there is no shell involved in this invocation; however, like cmd.exe, console applications themselves generally only understand "..." quoting); that is, your -ArgumentList string must end up containing the following verbatim, which is what the string passed to -ArgumentList below achieves via embedded " characters escaped as `" ("" would work too):
"/D=""C:\Program Files\packagename"""
Start-Process -Wait -FilePath "C:\ProgramData\chocolatey\choco.exe" `
  -ArgumentList "install $ChocoPackage -ia `"/D=`"`"C:\Program Files\packagename`"`"`" -y"

Only if you call choco.exe directly from PowerShell do the PowerShell instructions apply ('/D=""C:\Program Files\packagename""'):
& "C:\ProgramData\chocolatey\choco.exe" install $ChocoPackage -ia '/D=""C:\Program Files\packagename""' -y

As for what you tried:
What you passed to -ArgumentList was composed of three directly adjoining string literals in the form " a "' b '" c ", to use a simplified example (i.e., a double-quoted string right next to single-quoted string, right next to another double-quoted string).
However, PowerShell doesn't fully support implicit concatenation of directly adjoining string literals to form a single argument the way that POSIX-compatible shells such as bash do; doing so results in the strings being passed as separate arguments, which caused your problem (Start-Process saw extra positional parameters after -ArgumentList it didn't expect).
To demonstrate the original problem with the simplified example:
PS> Write-Output " a "' b '" c "
 a
 b
 c

That is, Write-Output received string literals " a ", ' b ', and " c " as 3 separate arguments (as implied by their appearing on their own line each).
Only if the first token is unquoted do you get a single string argument composed of it and subsequent quoted tokens:
# *Single* argument, because `a` is *unquoted*.
PS> Write-Output a' b '" c "
a b  c

The same applies even if that first unquoted token is a (non-expression) variable reference (e.g., Write-Output $HOME/'folder 1'/"and more"; see this answer for more information

If you do need to reliably form a single string argument from a mix of double-quoted (interpolating) and single-quoted (verbatim) string literals, use (...), the grouping operator, and the + operator for explicit string concatenation:
PS> Write-Output (" a " + ' b ' + " c ")
 a  b  c

A: Oh course I figured it out almost immediately after reading the official Chocolatey documentation. Since I'm using powershell you have to be very specific in how you wrap spaces in quotes.
-ia '/yo=""Spaces spaces""'

https://docs.chocolatey.org/en-us/choco/commands/#how-to-pass-options-switches

Pass quotes in arguments: When you need to pass quoted values to to something like a native installer, you are in for a world of fun. In cmd.exe you must pass it like this: -ia "/yo=""Spaces spaces""". In PowerShell.exe, you must pass it like this: -ia '/yo=""Spaces spaces""'. No other combination will work. In PowerShell.exe if you are on version v3+, you can try --% before -ia to just pass the args through as is, which means it should not require any special workarounds.


text:
Q: Can't write file to zip I try to put some file fileNamePath in zip archive (arguments are D:\text.txt D:\archive.zip):
  public static void main(String[] args) throws IOException {
    if (args.length==0) return;

    String fileNamePath = args[0];
    String zipPath = args[1];

    FileOutputStream outputStream = new FileOutputStream(zipPath);
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    zipOutputStream.putNextEntry(new ZipEntry(fileNamePath));

    File file = new File(fileNamePath);
    Files.copy(file.toPath(),zipOutputStream);

    zipOutputStream.closeEntry();
    zipOutputStream.close();

}

Archive is created but i don't see any file in it. Why?

A: That code is working perfectly:
zip.java
import java.io.*;
import java.nio.file.*;
import java.util.zip.*;

public class zip
{
public static void main(String[] args) throws IOException {
    if (args.length==0) return;

    String fileNamePath = args[0];
    String zipPath = args[1];

    FileOutputStream outputStream = new FileOutputStream(zipPath);
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    zipOutputStream.putNextEntry(new ZipEntry(fileNamePath));

    File file = new File(fileNamePath);
    Files.copy(file.toPath(),zipOutputStream);

    zipOutputStream.closeEntry();
    zipOutputStream.close();

}
}

I have compiled it under Debian 9 Stretch, OpenJDK 8
I have then created a sample txt file:
hello.txt
Hello World

I then compiled it:
javac zip.java

And finally run it:
java zip hello.txt hello.zip

I extract the .zip and open up hello.txt, returning Hello World
May it be that you have no permissions to read/write D:\?


text: Q: How to increase the number of items in %USERPROFILE%/AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets? I want to increase the number of items in %USERPROFILE%/AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets so that I can get more spotlight images. How do I do it?


text:
Q: Magento 2 - How to handle POST request with many parameters in Rest API? I'm confusing about the correct way to send parameter to POST request in Magento 2 API
For example, now I need to send a request body like this:
{
    "first_name":"test_first",
    "last_name":"test_last"
}

(it's just for example, in real situation, the number of key-value pair may be 20 or even 50)
Now I'm currently doing like this in the method declaration (in Api/NameRepositoryInterface.php, for instance)
/**
  * @param string $first_name
  * @param string $last_name
  * @return boolean
  */
public function createFullName($first_name, $last_name);

This approach is working fine, but what if there are 50 key-value pair in the request?
So I have to search for another approach, and it's here:
Now I can define Api/Data/NameInterface.php class like this
interface NameInterface
{
    const FIRST_NAME = 'first_name';
    const LAST_NAME = 'last_name';

    /**
     * @return string|null
     */
    public function getFirstName();

    /**
     * @param string $firstName
     * @return $this
     */
    public function setFirstName($firstName);

    /**
     * @return string|null
     */
    public function getLastName();

    /**
     * @param string $lastName
     * @return $this
     */
    public function setLastName($lastName);
}

And in in Api/NameRepositoryInterface.php class, I can make it like this:
/**
  * @param \Vendor\Module\Api\Data\NameInterface $name
  * @return boolean
  */
public function createFullName(\Vendor\Module\Api\Data\NameInterface $name);

It works well if in every request to this api, I always send both the first_name and last_name

The situation that I want to ask is:
What if in the request I only want to send the first_name as parameter (in real situation, it maybe 30/50 total key-value of NameInterface class)
How can we handle that case?
Do we have to create a new class called Api/Data/NameRequestInterface.php and copy again 30 fields?
I think there must be some better way for this situation, prevent us from repeating our code
Anyone has idea?
Thank you.

A: you can simply send array as json. Here is example..

Vendor/Module/Api/ServiceInterface.php

namespace Vendor\Module\Api;

interface ServiceInterface
{
    /**
     * @param mixed $services
     * @return void
     */
    public function saveInformation(
        $services
    );
}

Vendor/Module/Model/Service.php

namespace Vendor\Module\Model;

use Vendor\Module\Api\ServiceInterface;

class Service implements ServiceInterface
{
    /**
     * {@inheritDoc}
     */
    public function saveInformation(
        $services
    ) {
        //some logic
    }
}

Send request:
{
    "services": {
        "first_name":"test_first",
        "last_name":"test_last"
    }
}


text:
Q: Why in SOCI database type REAL is std::string when using SQLite3 as backend? I'm trying Object-Relational Mapping in C++ SOCI library with SQLite3 backend. But when I try to load from database REAL value as C++'s double the std::bad_cast is being thrown.
Full code:
#include <iostream>
#include <string>
#include <exception>
#include <soci/soci.h>
#include <soci/sqlite3/soci-sqlite3.h>

using namespace std;
using namespace soci;

struct Employee
{
    int id;
    std::string name;
    double salary;
};

ostream& operator<<(ostream& o, const Employee& employee)
{
    return o << "Employee(" << employee.id << "):" << employee.name << ", earns: " << employee.salary;
}

namespace soci
{
    template<>
    struct type_conversion<Employee>
    {
        typedef values base_type;

        static void from_base(const values & v, indicator /* ind */, Employee & employee)
        {
            employee.id = v.get<int>("ID");
            employee.name = v.get<std::string>("Name");
            cout << "Type: " << v.get_properties("Salary").get_data_type() << endl; // the output is 0, so the type is soci::dt_string but not soci::dt_double
            if (v.get_indicator("Salary") == i_ok)
                employee.salary = v.get<double>("Salary");
        }

        static void to_base(const Employee& employee, values& v, indicator& ind)
        {
            v.set("ID", employee.id);
            v.set("Name", employee.name);
            v.set("Salary", employee.salary, employee.salary == 0. ? i_null : i_ok);
            ind = i_ok;
        }
    };
}

int main()
{
    try
    {
        soci::session sql(sqlite3, "employees.db");
        sql << "CREATE TABLE IF NOT EXISTS Employees("  \
               "ID INT PRIMARY KEY     NOT NULL," \
               "Name           TEXT    NOT NULL," \
               "Salary         REAL);";
        sql << "INSERT INTO Employees (ID, Name, Salary) "  \
               "VALUES (1, 'Janusz Korwin-Mikke', 12000.01 ); ";

        Employee employee = {};
        sql << "SELECT * FROM Employees WHERE ID = 1;", into(employee);
        cout << employee << endl;
    }
    catch (const exception &e)
    {
        cerr << "Error: " << e.what() << endl;
    }
}

When I run the code I see the std::bad_cast exception thrown in line:
employee.salary = v.get<double>("Salary");

despite the fact that in database it is REAL type.
The code is working when I change the line into:
employee.salary = atof(v.get<std::string>("Salary").c_str());

I'm using SOCI-4.0.0 but the same problem was with previous version 3.2.3, I'm using SQLite3 on Windows 7 and MinGW compiler 7.3.0


text:
Q: Cyberpunk/Post-Apocalyptic Sci-Fi series from the 90s or 00s based in Manhattan A friend and I are trying to find an old book series, probably by a Christian author, that we read in the late 90s or early 2000s. It takes place after the "Water Wars," and fresh water is super scarce.  Manhattan has been turned into a giant prison/slum, all the metal has been stripped from crumbling buildings and they get a very small ration of water from the main land.  A guy convinces a board of trustees on the mainland to take a guy from the island to determine if they should continue to get water by testing his virtue and bravery.  He gets stuck in this cyber-world where he relives events in history from Egypt, Rome, the Crusades, etc. and eventually encounters Jesus or God (in the machine, literally).  We have no idea what the name of these books are except that we're pretty sure that the name "Cyber-" is in the title.  Also, if I remember rightly, each individual book is pretty thin (just a couple hundred pages) but the anthology is a pretty decent-sized novel.  Anyone have any thoughts?
EDIT: I am 28 (was 15 in 2000), but tend to read genre fic from above and below my reading level.  I feel like this series was about at my intended level (even though I was reading above it).

A: Just found it!  It's called "Cyberquest," by Sigmund Brouwer.
Apparently all I needed to do to find it was ask what it was...seriously, we started looking for this thing about a month ago...

A: You don't reveal your age, but a quick search revealed the youth book series by S. F. Black - the Cyber Zone series. They were published in the mid-to-late 1990's. You can find a quick list here: or here:. They seem a loose fit.

A: A second author, who in addition to youth scifi (Cyber Generation series), has a few Christian books is Edward Bolme:.
Actually the Cyber Generation series is a collaboration from a number of authors, of which Ed wrote only a couple. See Amazon


text:
Q: Having trouble adding wxListBox to frame I am trying to add a wxListBox to my frame, but I am having some difficulty.
This is my sample code
wx.Frame.__init__(self,parent,title=title,size=(750,690), style=wx.MINIMIZE_BOX|wx.SYSTEM_MENU|
              wx.CAPTION|wx.CLOSE_BOX|wx.CLIP_CHILDREN)

    splitter = wx.SplitterWindow(self)
    panel1 = panel1(splitter)
    panel2 = wx.Panel(splitter,style=wx.SUNKEN_BORDER)
    splitter.SplitHorizontally(panel1,panel2,470)
    listBox = wx.ListBox(splitter, -1, (20, 20), (80, 120), 0, wx.LB_SINGLE)

I am getting this error,
controls.ListBox_swiginit(self,controls.new_ListBox(*args, **kwargs))
TypeError: Sequence of strings expected.

A: Your line:
listBox = wx.ListBox(splitter, -1, (20, 20), (80, 120), 0, wx.LB_SINGLE)

should be something like:
listBox = wx.ListBox(panel1, -1, (20, 20), (80, 120), [a list of choices], wx.LB_SINGLE)

Instead of parenting it to the splitter use one of your panels or if you want it outside the splitter then use 'self' which is your frame here.
You are hardcoding sizes and positions, instead I suggest to look into using sizers.  see e.g. http://wiki.wxpython.org/UsingSizers or do a google search.


text:
Q: Removing file extension from URL with Godaddy via .htaccess I am trying to remove php extension from URL, the php is removed but then the all php codes/file are not read when code is executed. Below is the code
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php
[NC]
RewriteRule ^ %1 [R,L,NC]

# remove index
RewriteRule (.*)index$ $1 [R=301]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [NC,L]

A: Add below code in .htaccess file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*.php$ %{REQUEST_FILENAME}.php [QSA,L]
Note : On Godaddy servers, In order to remove the extensions you need to enable MultiViews before. Below is the code for the same
Options +MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*.php$ %{REQUEST_FILENAME}.php [QSA,L]


text:
Q: Why am I getting this error message: "'IMediaManager' does not contain a definition for 'MediaExtractor'" with xamarin.forms? I am developing an app that can also Livestream Video, but I am having some issues.
I have downloaded and installed Plugin.MediaManager.Forms (and also Plugin.MediaManager) via Nuget. I have also done the needful as you can see below:
In MainActivity.cs (I am referencing MediaManager & I also Initialized CrossMediaManager)
    using Android.App;
    using Android.Content.PM;
    using Android.Runtime;
    using Android.OS;
    using MediaManager;
    namespace Abuse_Alert.Droid
    {
       [Activity(Label = "Abuse_Alert", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]

   public class MainActivity :
   global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
   {
    protected override void OnCreate(Bundle savedInstanceState)
    {
        CrossMediaManager.Current.Init(this);

        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        LoadApplication(new App());
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
   }
    }

The XAml File looks like this:
<?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="AbuseAlert.Views.Page1"
         xmlns:mm="clr-namespace:MediaManager.Forms;assembly=MediaManager.Forms"
         x:Name="BrowseItemsPage">

<ContentPage.Content>
<mm:VideoView VerticalOptions="FillAndExpand"
              HorizontalOptions="FillAndExpand"
              BackgroundColor="Black"
              x:Name="mmVideoView"
              />
</ContentPage.Content>

</ContentPage>

In the code behind, this is what I have done:
    if (isHLS)
    {
      var item2 = await CrossMediaManager.Current.MediaExtractor.CreateMediaItem(URL);

      item2.MediaType = MediaManager.Media.MediaType.Hls;
      CrossMediaManager.Current.MediaPlayer.VideoView.ShowControls = false;

      await CrossMediaManager.Current.Play(item2);
   }
   else
   {
      await CrossMediaManager.Current.Play(URL);
   }

Nevertheless, these are the error messages I am getting in 3 above:

*

*The name 'isHLS' does not exist in the current context

*'IMediaManager' does not contain a definition for 'MediaExtractor' and no accessible
extension method 'MediaExtractor' accepting a first argument of type 'IMediaManager'
could be found (are you missing a using directive or an assembly reference?)

*The type or namespace name 'MediaType' does not exist in the namespace
'MediaManager.Media' (are you missing an assembly reference?)

*'IVideoView' does not contain a definition for 'ShowControls' and no accessible
extension method 'ShowControls' accepting a first argument of type 'IVideoView' could
be found (are you missing a using directive or an assembly reference?)
So, what am I supposed to have done that I have not done? I am using VS 2022 with xamarin.forms.