text:
Q: Python automation: file manager I create a script to auto-sort my download directory. Basically I want this to run on background, sort every file I download and move it in the correct folder.
The issue is that when the script is running, the download always fails. I think this might be because when chrome starts the download, it creates a temporary file. And only show the entire file when the download is done. I have added the condition to exclude 'crdownload' files. But still, when I try to download files, it goes until the end and fails.
How can I solve this?
This is the script:
#!/bin/python2.7

# pip install watchdog fro theses package to work
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

import os
import json
import time
import datetime

ROOT_DIR = '/home/xxx/Downloads/'
assertMsg = ''' File \'%s\' don\'t exists. Abord ... ''' % (ROOT_DIR)

# make sure directory exists before starting the application
assert os.path.exists(ROOT_DIR), assertMsg
# + datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S_")

# /home/xxx/Downloads

# chrome Unconfirmed 332952.crdownload

class MyHandler(FileSystemEventHandler):
  def on_modified(self, event):
    today_date = datetime.datetime.now().strftime("%Y-%m-%d")
    files = [f for f in os.listdir(ROOT_DIR) if os.path.isfile(ROOT_DIR + f)]
    for filename in files:
      name, ext = os.path.splitext(filename) # get file extention
      if ext == 'crdownload':
        continue
      if not ext:
        ext = 'others'
      ext = ext.strip('.')
      ext = ext.lower()

      source_file = ROOT_DIR + filename
      new_destination = ROOT_DIR + ext +  "/" + today_date + "/" + filename

      if not os.path.exists(ROOT_DIR + ext):
        os.mkdir(ROOT_DIR + ext)
        os.mkdir(ROOT_DIR + ext + "/" + today_date)
      else:
        if not  os.path.exists(ROOT_DIR + ext + "/" + today_date):
          os.mkdir(ROOT_DIR + ext + "/" + today_date)

      os.rename(source_file, new_destination)

folder_to_track = ROOT_DIR
folder_destination = ROOT_DIR

event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, folder_to_track, recursive=True)
observer.start()

try:
  while True:
    time.sleep(60)
except KeyboardInterrupt:
  observer.stop()
observer.join()

observer.join()

Downloads fail:

A: Ok I reproduced and found out what is happening. Actually your if ext == 'crdownload': is never met. You should either change that to
if ext == '.crdownload':

or change this :
name, ext = filename.split('.')

You were checking if ext was equal to crdownload but your ext was .crdownload. You should have imagined that while your script was creating a folder named crdownload meaning it didn't pass this step.


text:
Q: Format for sending location data in body I'm coding in React-Native.
Glympse docs says that location data should be sent in a delta-compressed array. I don't really know what that means. I think I get the idea of each element being the amount of change (delta) from the previous element, but I still don't have a clear picture of how the body should look when I make the POST request.
Can anyone show an example of this process?

A: Examples of location arrays that are compressed can be found here https://developer.glympse.com/docs/core/api/reference/objects/location-points#examples
The idea behind this format is that the first item in the array contains specific values for each parameter, but each item that comes after that only contains the change (or delta) from the previous point.
[
  [1339989715000, 37123450, -112123450, 18000, 55, null, 2, 4],
  [1000, 1000000, 1000000, 0, null, 1000, 1, -1],
  [1000, 0, 0, 0, 1, 0, 0, 0],
  [1000, 0, 0, 0, 0, 0, 0, 0],
  [1000, 0, 0, 0, 0, 0, 0, 0]
]

The first parameter is the timestamp, so if we look at the second item it shows 1000 which means it's the first timestamp + 1000ms.
The second parameter is latitude * 10^6. The first item shows latitude 37.123450, and the second item in the array has the value 1000000 which represents 37123450 + 1000000 or the latitude 38.123450. Not likely to have something moving that fast in real data, but that's the idea of how this format works.
Timestamp, latitude, and longitude are the only required fields. A POST body with only the required fields would look like this.
[
  [1339989715000, 37123450, -112123450],
  [1000, 1000000, 1000000],
  [1000, 0, 0],
  [1000, 0, 0],
]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error in accept: Bad file descriptor -- mysql error After working for years on Ubuntu 14.04 (on OpenVZ) without any problem, I installed a new Ubuntu 16.04.01 LTS running on OpenVZ.
I set it up as a LEMP stack.
The problem is that after a while (hours), mysqld starts consuming 100% CPU and the error log is filled with strange 'Error in accept: Bad file descriptor' errors, over and over again, the err file quicly became 4Gb large.
MySql needs to be setup for replication. With replication enabled, the bin.err file is written in the same way.
I just can't figure out what happens and why. The only thing I did out of the ordinary was to set 'mysqld: ALL' in hosts.deny and 'ALL: LOCAL' and a specific IP in hosts.allow, to allow the replication.
Any idea about what's happening?


text:
Q: Air flow speed and penetration abilities As I understand, two fans with the same diameter and with the same rotor speed(usually measured in RPM) can have different air pressure(usually measured in mmH2O) and air speed(usually measured in CFM) because of fan blades design. Higher air flow speed should provide worse penetration(for example, penetration to radiator with thin fin gaps) abilities. However, it is counterintuitive to imagine that air molecules with higher speed have smaller penetration ability than the ones with lower speed. Why is that so? Or is it because of complexity of air flow dynamics and air flow with slower speed has indeed for some (weird) reason better penetration abilities? At least I know that this is not because of Bernoulli's principle because this should apply only for tubes.

A: The most likely explanation is that at lower speeds you get a more laminar flow. To quote the wiki article:

At low velocities, the fluid tends to flow without lateral mixing, and
  adjacent layers slide past one another like playing cards. There are
  no cross-currents perpendicular to the direction of flow, nor eddies
  or swirls of fluids.[2] In laminar flow, the motion of the particles
  of the fluid is very orderly with all particles moving in straight
  lines parallel to the pipe walls.[3] Laminar flow is a flow regime
  characterized by high momentum diffusion and low momentum convection.

A: Background
The issue of higher speeds having smaller penetration results from the ram pressure, which scales as:
$$
P = \frac{1}{2} \rho \ v^{2}
$$
where $\rho$ is the mass density and $v$ is the flow speed.  Even if you have thin fins in a radiator, they can start to "look like" sails to the incident flow if the flow moves fast enough causing the drag to increase.
You can see a similar effect if you watch pine trees under different wind conditions compared to deciduous trees (i.e., leafy trees).  At low wind speeds, many types of pine trees will show little movement because the air can easily pass between the needles.  At higher speeds, suddenly they begin to sway/move just like the deciduous trees.  I noticed this when I saw that a small pine tree had been uprooted during a tornado during graduate school.  I was initially puzzled how the wind had enough force to actually accomplish such a feat (since it was a weak, F0, tornado).
I then recalled that ram pressure is $\propto \ v^{2}$ and that the Reynolds number scales as:
$$
Re = \frac{ v \ L }{ \nu }
$$
where $L$ is linear the scale size of the obstacle and $\nu$ is the kinematic viscosity.  The easy way to think about $Re$ is that for large values (i.e., $> 10^{3}$) the flow can become rather turbulent downstream of the obstacle.
So for your radiator fins, after a certain inflow speed the air flow over the fins will start to become unstable at the immediate downstream edge.  This will start to cause a kind of "pile up" that will disrupt the incident flow and impede the penetration depth of the air.
Answer
So the answer is that the lower penetration depth of air flow for higher inflow speeds is a combination of the effects of ram pressure an increasing Reynolds number.

A:
However, it is counterintuitive to imagine that air molecules with higher speed have smaller penetration ability than the ones with lower speed. Why is that so?

The velocity has an influence, but it is almost purely an issue of the shape of object which it needs to "penetrate". This influence is not even linear, but can even decrease when the velocity increases. It's all well educated in this old video; Fluid Dynamic of Drag, (Part I) At 8 min it's well shown.

Or is it because of complexity of air flow dynamics and air flow with
  slower speed has indeed for some (weird) reason better penetration
  abilities?

The decreased penetration ability comes mainly from so called "separation of the boudary layer", which shortly said simply causes a reduction for the open area of flow.

At least I know that this is not because of Bernoulli's principle
  because this should apply only for tubes.

Bernoulli apply everywhere.
ANSWER: Higher air speed $V$ always provides more "penetration" as this penetration is simply flow amount $Q$ through Area $A$, and $V/A=Q$.
This "penetration"/flow might be really unefficient, the efficiency can be seen from the rise in the pressure. And basically the pressure generally rises along the velocity. But there is an optimum point. In water flow this is defined as a Froude number. At certain airspeed the area might be blocked because of separation, and if there is possibility to bypass flow, then the "penetration" is reduced.
It's not reasonable to answer more broadly to a question in this level; here's some material to study further;

*

*Fluid Dynamics of Drag (Part II)

*Fluid Dynamics of Drag (Part III)

*Fluid Dynamics of Drag (Part IV)


text:
Q: Pandas: how to identify columns with dtype object but mixed-type items? In a pandas dataframe, a column with dtype = object can, in fact, contain items of mixed types, eg integers and strings.
In this example, column a is dtype object, but the first item is string while all the others are int:
import numpy as np, pandas as pd
df=pd.DataFrame()
df['a']=np.arange(0,9)
df.iloc[0,0]='test'
print(df.dtypes)
print(type(df.iloc[0,0]))
print(type(df.iloc[1,0]))

My question is: is there a quick way to identify which columns with dtype=object contain, in fact, mixed types like above? Since pandas does not have a dtype = str, this is not immediately apparent.
However, I have had situations where, importing a large csv file into pandas, I would get a warning like:
sys:1: DtypeWarning: Columns (15,16) have mixed types. Specify dtype option on import or set low_memory=False

Is there an easy way to replicate that and explicitly list the columns with mixed types? Or do I manually have to go through them one by one, see if I can convert them to string, etc?
The background is that I am trying to export a dataframe to a Microsoft SQL Server using DataFrame.to_sql and SQLAlchemy. I get an
OverflowError: int too big to convert

but my dataframe does not contain columns with dtype int - only object and float64. I'm guessing this is because one of the object columns must have both strings and integers.

A: Setup
df = pd.DataFrame(np.ones((3, 3)), columns=list('WXY')).assign(Z='c')
df.iloc[0, 0] = 'a'
df.iloc[1, 2] = 'b'

df

   W    X  Y  Z
0  a  1.0  1  c
1  1  1.0  b  c
2  1  1.0  1  c

Solution
Find all types and count how many unique ones per column.
df.loc[:, df.applymap(type).nunique().gt(1)]

   W  Y
0  a  1
1  1  b
2  1  1


text:
Q: Responsive Android App Design My android app is almost done!
But now, I need to have a responsive design.
I've read the android developers pages about that, but on my samsung note 2 the responsive design doesn't work...
I've got 4 folders for the layout: small, normal, large, xlarge.
Also I've got the tags in the manifest which are described at the developers page.
Is this maybe only by the samsung note 2 or by every device?
Hope you can help!
Thanks!

A: To design responsive application is some what difficult. Please follow the below instructions.

*

*Don't specify width and height in dps in layout.

*Design your layout by using weights.

*Maintain icons in different folder.

*Finally design each layout carefully with check in all screens.

Please find the sample link for your reference.
Responsive Android app design
Hope this  will helpful.

A: Have you used Fragment to make your app responsive to all type of device? As my experience, for big screen devices like Note 2 or Tab you have to use fragment and  you have to make an extra layout for those devices. In case of me same problem happened and only padding margin responsiveness doesn't work all time at reality though they show on emulators.
You can know about using Fragment to make applications responsive for all devices from here:
Building a Dynamic UI with Fragments


text:
Q: Linear Algebra Notation of a Vector Space $$O(3) = \{A \in M |  A^\top A = I\}$$
Ok, so the first part I know means that $A$ is a subset/element of $M$. Does the second part mean that the transpose of $A$ multiplied by itself is always the identity matrix, and if that is not the case, it is not part of the subset. Is my understanding of this correct.

A: You've understood the definition correctly.  One usually reads it off as follows:
$$
\overbrace{\{ }^{\text{the set of}} \overbrace{A \in M}^{\text{(matrices) $A$ in $M$}} \overbrace{\mid}^{\text{such that}} A^TA = I\}
$$


text:
Q: PHP MySQLi Pagination LIMIT, WHERE and ORDER BY `date` DESC problems I am creating project not for profit and have problems with pagination. First idea was "Load more" <- but it's in dreams only. Maybe MySQL syntax is wrong. How to fix this code? Maybe there's a better solution? I tried all combinations "..",'..', ``. This can also be exploited by using SQL injections?
  MySQLi connection:

$mysqli = new mysqli('localhost','root','','tablename');
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
/* Change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
}

  Paggination:

  $items_per_page = 5;
  $login = $_SESSION['login'];
  $per_page = $items_per_page;
  if (isset($_GET['page'])) {
  $page = $_GET['page'];
  }else {
  $page = 1;
  }
  $start_from = ($page-1) * $per_page;
  //Selecting the data from db
  $date = $mysqli->query("SELECT post_id FROM posts WHERE posts_author = '.$login.' ORDER BY `date` DESC LIMIT $start_from, $per_page");
  while($row = $date->fetch_array()){
  echo $row["post_id"];
  }
  //

  //Select all from DB
  $query = $mysqli->query("SELECT post_id FROM posts WHERE posts_author='$login' ORDER BY date DESC");
  $result = mysqli_query($mysqli, $query);
  $total_records = mysqli_num_rows($result);
  $total_pages = ceil($total_records / $per_page);
  //Going to first page
  echo 'first page ';
  for ($i=1; $i<=$total_pages; $i++){
  echo ''.$i.' ';
  };
  // Going to last page
  echo 'last page ';

A: Your code can be exploited,
you should consider of using mysqli_real_escape_string: http://php.net/manual/en/mysqli.real-escape-string.php
For bugs, i see it here:
//Selecting the data from db
  $date = $mysqli->query("SELECT post_id FROM posts WHERE posts_author = '.$login.' ORDER BY `date` DESC LIMIT $start_from, $per_page");
  while($row = $date->fetch_array()){
  echo $row["post_id"];
  }

You were used single quotes with dots for '.$login.' instead of using double quotes and your query should execute fine.
If you got some other problems, update answer where did you stuck, what's not working and what have you tried.


text:
Q: na.omit not removing NA (data is numerical) I have just merged two data frames and am trying to remove rows with a NA in the value column. As of now I have..
t.dup.rights <- merge(dataframe1, dataframe2, by = "ID", all = T)
na.omit(tdup.rights$value)

The value column has either a 1 or NA. I used
is.numeric(t.dup.rights$value)

to double check that r doesn't think it's a factor. After I run the na.omit function the data frame appears to remain unchanged. I am working with a particularly large data set (200K obs). I am also using the dplyr package.

A: You can use tidyr::drop_na
library(dplyr)
library(tidyr)

df <- data_frame(
  x = sample(c(NA, 1, 2), 10, replace = TRUE),
  y = sample(c(NA, 1, 2), 10, replace = TRUE)
)

df

#> # A tibble: 10 x 2
#>        x     y
#>    <dbl> <dbl>
#> 1     NA    NA
#> 2      1     2
#> 3      2     2
#> 4     NA     1
#> 5      2    NA
#> 6      1    NA
#> 7     NA    NA
#> 8      2     2
#> 9      1    NA
#> 10    NA     2

drop_na(df, x)

#> # A tibble: 6 x 2
#>       x     y
#>   <dbl> <dbl>
#> 1     1     2
#> 2     2     2
#> 3     2    NA
#> 4     1    NA
#> 5     2     2
#> 6     1    NA


text:
Q: C# MS VS WebReference type of variable I would like to read a values from one webservice (here is WSDL).
My code is here:
protected void Button1_Click(object sender, EventArgs e)
{
    var ahoj = new string[] { 28156609.ToString() };
    InformaceOPlatciType[] platceinfo;

    mfcrDPH.rozhraniCRPDPH srv = new mfcrDPH.rozhraniCRPDPH();
    StatusType status = srv.getStatusNespolehlivyPlatce(ahoj, out platceinfo);

    for (int i = 0; i < platceinfo.Length; i++)
   {
        mfcrDPH.InformaceOPlatciType info = platceinfo[i];
        Label1.Text = info.dic;
        Label2.Text = info.nespolehlivyPlatce;
   }
}

mfcrDPH is WebReference inside MS Visual Studio.
Problem is with value info.nespolehlivyPlatce. Value info.dic works fine. I don´t understand how to fix it, because inside WSDL I see that both variabels are principali same - type of both is simple.
For label2.Text I got an error:

Error 3   Cannot implicitly convert type
  'mfcrDPH.NespolehlivyPlatceType' to
  'string'  D:\Tvorba\vs2010\WebTelefony\DPH\DHP_Dash2.aspx.cs  27  27  WebTelefony

Here is picture with graphical information: Picture1
Is possible to help me resolve why I got this type of error message?

A: Read the error and try to understand it. This code:
Label2.Text = info.nespolehlivyPlatce;

Tries to assign an object of type NespolehlivyPlatceType to a property of type string, which are incompatible. So that's not going to work.
You need to find a property on the NespolehlivyPlatceType type which you can use. Expand the simpleType in your XSD/WSDL, use IntelliSense or check the Object Browser to see which properties are available on that class that are strings, or convertable to it. For example:
Label2.Text = info.nespolehlivyPlatce.ID;

A: The error message is being generate by a type mismatch. In the Wsdl the document is using tns (this name space) referring to a type other than a string. This is why in your code you see a type conversion error. You either need to change your type from a string to match the wsql type or you need to do some casting or conversion of type


text:
Q: Vue Router: Load routes based on user role I'd like to use the same route path /dashboard to load slightly different views for my users based on their user role.
Previously, I've loaded in different routes based on the current domain:
import MarketingSiteRoutes from './marketingSiteRoutes'
import DashboardRoutes from './dashboardRoutes'
import CampusRoutes from './campusRoutes'

Vue.use(VueRouter)

const host = window.location.host
const parts = host.split('.')

let routes

if (parts.length === 3) {
  const subdomain = parts[0]

  switch (subdomain) {
    case 'dashboard':
      routes = DashboardRoutes
      break
    case 'demo':
      routes = CampusRoutes
      break
    default:
  }
} else {
  routes = MarketingSiteRoutes
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

This approach only relies on subdomain, which is available on creation, so everything can be synchronous. I would have to authenticate the user, load in the correct routes based on their role, and then export the router to initialize the vue app.
Ideally, I could load in ...adminRoutes, ...parentRoutes, ...childRoutes based on the user's role, which could contain all the route definitions for the role.
I'm using Feathers-vuex, but I can't seem to await the user and then export the router. Any way to do this?

A: I would use a main Dashboard component, that checks the user role, and then shows the correct child component.
<template>
  <div>
    <dashboard-admin v-if="isAdmin" />
    <dashboard-standard v-if="isStandard" />
  </div>
</template>

<script>
export default {
  data () {
    return {
      isAdmin: false,
      isStandard: false
    }
  },
  components: {
    DashboardAdmin: () => import('./DashboardAdmin.vue'),
    DashboardStandard: () => import('./DashboardStandard.vue')
  },
  created () {
    // Check user role and set one to true.
  }
}
</script>


text:
Q: Servlet pure forwarding issue Is it possible to fully forward a request from a servlet to an external resource?
For example:
A web has a video component with src = ip-server/servletName
The servlet catches the GET request for that component, validates some cookie parameters and after that processes directly (forward, not redirect) an external resource present in http://localhost/resource.mp4
Is that possible using Java + Servlets or I must use other technologies¿?
Thanks!


text:
Q: How do I get data out of a firebase snapshot in Swift using a function in a struct? I'm getting data from Cloud Firestore to populate a ListView. I've managed to get the data into an array, but when I return the array, it shows up empty.
//Edit
I've implemented a completion handler, works perfectly for 'Test Code', but when called in 'func industryPosts' and passed into 'myArray', it returns nil. While 'Test Code' returns data. I'm new to completion handlers, and Swift in general. Kindly let me know what I'm missing. Thanks.
//Edit
I was not able to return the values, but calling industryPosts where I needed to use it worked!
import Foundation
import SwiftUI

class IndustryData {

    var _snapshotArray : Array<Any>?

    func getSnapshotArray(collectionRef: String, completionHandler: @escaping (Array<Any>?, NSError?) -> ()){

        if let snapArray = self._snapshotArray {
            completionHandler(snapArray, nil)
        } else {

            var snapArray : Array<Any> = []

            db.collection(collectionRef).getDocuments { (snapshot, error) in
                guard let snapshot = snapshot else {
                    print("Error - > \(String(describing: error))")
                    return
                }

                for document in snapshot.documents {
                    let item = Industry(avatar: document.get("avatar") as! String, name:document.documentID, tags: document.get("tags") as! String)
                    snapArray.append(item)
                }
                self._snapshotArray = snapArray
                completionHandler(snapArray, error as NSError?)
            }
        }
    }
}

Then calling the below function where needed
func getposts()-> [Industry] {
        let data = IndustryData()
        data.getSnapshotArray(collectionRef: "industry") { (snapshotArray, error) in
            if snapshotArray != nil {
                self.myArray = snapshotArray!
            }
        }
        return myArray as! [Industry]
    }

myArray returned Industry Array!


text:
Q: Is hasRemaining method really necessary while reading from the source channel of Pipe object? The hasRemaining method of the ByteBuffer class in Java.NIO package returns whether there are any elements between the current position and the limit.
At the same time, the documentation of the write method of FileChannel class says "An attempt is made to write up to r bytes to the channel, where r is the number of bytes remaining in the buffer, that is, src.remaining(), at the moment this method is invoked"
This is my main method code where I am using the sink channel and source channel of pipes in java NIO :
try {
            Pipe pipe = Pipe.open();
            Runnable writer = () -> {
                try {
                    Pipe.SinkChannel sinkChannel = pipe.sink();
                    ByteBuffer writeBuffer = ByteBuffer.allocate(100);

                    for (int i = 0; i < 10; i++) {
                        String currentTime = "The current time is " + System.currentTimeMillis();
                        writeBuffer.put(currentTime.getBytes());
                        writeBuffer.flip();

                        while (writeBuffer.hasRemaining()) {
                            int writtenBytes = sinkChannel.write(writeBuffer);
                            System.out.println("Channel is writing " + writtenBytes + " bytes");
                        }

                        writeBuffer.flip();
                        Thread.sleep(150);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            };

            Runnable reader = () -> {
                try {
                    Pipe.SourceChannel sourceChannel = pipe.source();
                    ByteBuffer readBuffer = ByteBuffer.allocate(100);

                    for (int i = 0; i < 10; i++) {
                        int bytesRead = sourceChannel.read(readBuffer);
                        byte[] stringRead = new byte[bytesRead];

                        readBuffer.flip();
                        readBuffer.get(stringRead);
                        readBuffer.flip();

                        System.out.println("Buffer reading '" + new String(stringRead) + "'");
                        Thread.sleep(150);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };

            new Thread(writer).start();
            new Thread(reader).start();

} catch (IOException e) {
            e.printStackTrace();
        }

I would like to know if the hasRemaining is really mandatory or not and when should I use it.

A: After investigating a little deeper I found that the abstract class SinkChannel that is a part of the class Pipe is implemented by a class named SinkChannelImpl.
In the latter class, a SocketChannel object is used as a channel, and the write method is implemented in the SocketChannelImpl class since
SocketChannel is an abstract class too.
Bottom line is that when I call the write method of the SinkChannel I am actually calling the write method of the SocketChannelImpl class.
Unfortunately, the documentation does not really specify if all of the remaining bytes will be written to the channel or not, quote: "Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all", also the code is obfuscated and will take some time to know how it works.
So I will be using the compact method after the write so in case some of the bytes are not written they will be moved to the beginning of the buffer.


text:
Q: Network Output Buffering How can I hold the packets generated from a server until an external signal is delievered. On receiving the signal the host hosting the server should release the packets?
I think it can be done with qdisc module in kernel but i don't know how to use it specifically for this case. a simple working example is required.
Any other way is also fine.


text:
Q: How to add quotes in the file I have file below
123,PEN BOOK
124,BALL
125,BOOK
126,PENCIL BOOK

I need to add quotes
Expected out
"123","PEN BOOK"
"124","BALL"
"125","BOOK"
"126","PENCIL BOOK"

A: Assume you have a file test.txt with the following content:
123,PEN
124,BALL
125,BOOK
126,PENCIL

You can use a code like the following, to create a temp file with the content with quotes and replace the original file:
import os
with open("test.txt") as i: # open file for reading, i = input file
  with open("temp.txt", "w") as o: # open temp file in write mode, o = output
     for l in i: # read each line
        o.write('"{}","{}"\n'.format(l.split(',')[0],l.split(',')[1].split('\n')[0]))

os.remove('test.txt')                    # remove the old file
os.rename('temp.txt','test.txt')         # resave the temp file as the new file

Output:
"123","PEN"
"124","BALL"
"125","BOOK"
"126","PENCIL"

A: I've updated my answer to cover additional case of text containing spaces.
Seeing as you have a regex tag in your question, you can use something like this:
import re

text = """123,PEN
124,BALL
125,BOOK
126,PENCIL
123,PEN BOOK"""

new_text = re.sub(r'(\d+),([\w\s]+)$', r'"\1","\2"', text, flags=re.M)


text:
Q: Minecraft Classic freezes at "switching applet" When I try to play Minecraft Classic it gives me some security warnings. That is normal, but when it reaches switching applet, it freezes. how do I fix this? I have newest Java and I've tried it on 2 different Windows computers with 3 different web browsers (Internet Explorer (version 9 and 11), Mozilla Firefox and Google Chrome.

A: The short answer is, you fix this by using a virtual machine.  It's an extreme approach, but if your computer is powerful enough it will get you Minecraft Classic, playable in-browser.  A virtual machine is basically a computer that runs on your computer.
For a little more detail, you can get software called VirtualBox, which is used to run virtual machines, here.  You will need to have some operating system to install on your virtual machine, like an old copy of Windows XP or some free Linux distribution.  In the manual for VirtualBox the instructions you'll be interested in start on the 16th page, which show you how to start VirtualBox and set up a virtual machine.
Once you have your virtual machine running, you'll have to install a browser on it if it doesn't already have one, and install Java 6.  You can download Java 6 (Java SE Runtime Environment 6u45 to be more specific) here, although you'll have to create an Oracle account to get it...I haven't a clue why, it's just annoying.
If you manage to get to this point, the last step is to start your virtual machine, and then disable mouse integration.  In VirtualBox, this can be done by choosing "Disable Mouse Integration" under the "Machine" menu.  Disabling this fixes a problem with mousing in Minecraft where your cursor doesn't center automatically, making it nearly unplayable.
If you manage to do all of the above, you should be able to boot up your browser and head over to Minecraft Classic.

A: Sorry to say this, but unless you play minecraft classic though the time machine in the new launcher, the latest version of Java is not compatible with the browser-based minecraft classic.


text:
Q: MongoJS: size() method or length not available I just installed the latest versions of node.js and MongoDB and a driver for node.js: MongoJS
Now I tried to find out (with good performance due a high load app) if a record exists in the database. I tried this query but all I get is an error:
var query = db.users.find({ nickname: 'test' }).limit(1);
console.log(query.size());
// or also
// console.log(query.length);
// => undefinied

Error:
TypeError: Object [object Object] has no method 'size'

Via console.log(typeof query) I just get object.
If I just log query I get this:
{ _readableState:
    { highWaterMark: 16384,
      buffer: [],
      length: 0,
      pipes: null,
      pipesCount: 0,
      flowing: false,
      ended: false,
      endEmitted: false,
      reading: false,
      calledRead: false,
      sync: true,
      needReadable: false,
      emittedReadable: false,
      readableListening: false,
      objectMode: true,
      ranOut: false,
      awaitDrain: 0,
      readingMore: false,
      decoder: null }
  readable: true,
  domain: null,
  _events: {},
  _maxListeners: 10,
  _get: [Function] }

I get all the time this as result, even if the item exists or not.

A: I don't see any mention of a size method in the current docs.  Instead, while count would also work here, you could use findOne to do this:
db.users.findOne({ nickname: 'test' }, function(err, doc) {
    if (doc) {
        // At least one matching doc exists
    } else {
        // No match found
    }
});


text:
Q: Having trouble with edges in an undirected graph for adjacency list C I've been trying to create an Adjancey List with an undirected graph. Everything is going smoothly, except for when I need to have a Node(or vertex as in my code) have multiple edges connected to it.
I have 6 vertexs A,B,C,D,E,F
and there's only edges from A to B, A to C, A to D
this is what it looks like conceptually.
I've been trying over and over to come up with an algorithm to connect more than one edge together, I can't figure it out. Here is my structures for reference, and where my else statement is where I need to walk through to the end of the linked edges and attach the new edge.
typedef struct
{
    char c;
    bool isVisited;
    struct EDGETAG* p;
} VERTEX;

typedef struct EDGETAG
{
    VERTEX* v;
    struct EDGETAG* next;
} EDGE;

//~~~~~~~~
while( fgets(data,sizeof(data),filePtr) && elements < 50)
    {
        startPtr = data;
        EDGE* e  = (EDGE*)malloc(sizeof(EDGE));
        //first character
        int breakLogic = 0;
        int i;

        for( i = 0; i < 50; i++)
        {
            if(map[i].c == *startPtr)
            {
                elements = i;
                break;
            }
        }
        //first character
        map[elements].c = *startPtr;
        printf("%i %c\n",elements,map[elements].c);
        //point first character to edge
        if(map[elements].p == NULL)
        {
            map[elements].p = e;
        }
        else
        {
             /*Here is where I need help*/
        }

        startPtr += 2;

        for( i = 0; i < 50; i++)
        {
            if(map[i].c == *startPtr)
            {
                elements = i;
                breakLogic = 1;
                break;

            }

        }
        if( breakLogic == 0)
        {
            elements++;
        }
        //second character
        map[elements].c = *startPtr;
        printf("%i %c\n",elements,map[elements].c);
        //point edge to second character
        e -> v = &map[elements];
        e -> next = NULL;
        //loops at the newline

        elements++;
    }

}


text:
Q: Get tag attribute for matching inner word in regex I need to get a particular attribute value from a tag whose inner word matches my query word. For example, consider a target html-
other_word
word_to_match
some_other_word

Now, I need to get the 'required' value from the data-attr attribute for the tag where the inner word(in this case word_to_match) matches my query word.
The problem is that the regexes that I'm writing are returning the other spans as well. I haven't been able to make a non greedy regex in this case.
If it helps, I'm doing this in python and kindly no "don't use regex here" solutions.

A: What about using string replace with regex and output group (javascript syntax, but I expect python has a similar function)?
str.replace(/data-attr="([^"]*)"[^>]*>[^<]*word_to_match</, '$1')

A: Parsing websites with regex is not a good idea. You may you use BeautifulSoup. It is reliable and efficient:
>>>from bs4 import BeautifulSoup

>>>soup = BeautifulSoup("""
    other_word
    word_to_match
    some_other_word""")

>>>[x.attrs['data-attr'] for x in soup.select('span') if 'word_to_match' in str(x)][0]
'required'


text:
Q: Adding Web API to existing asp.net web forms Application My team wants to upgrade from WCF to Web API. We have a working asp.net web form application, that we have imported to VS2012 from VS2010. So far so good.
But now as I try to make a separate Web API project, I see that there is no Web API template available. The closest thing that I can find is by creating an MVC 4 application and setting the Project Template as WebAPI.  I followed this way and everything falls in perfectly. I have the working API with a sample controller that I can invoke by making calls from the browser.
The only downside to this is that, this particular method brings in its own baggage. The MVC 4 project I created has JQUERY and other libraries included, plus some other folders that I probably don't need. What I want is the Web API structure only - and not the extra baggage.
I tried finding a template using online search but the package I found does not work properly and as very poor rating.
I hope I have illustrated my problem properly. I am looking forward for some feedback now :) Thanks.

A: In Visual Studio 2013

*

*Right-click on the ASP.NET Web Forms project.

*Add -> Add Scaffolded Item... or New Scaffolded Item...

*Under Installed/Common/MVC/Web API choose the scaffold type you wish
to use.

*Follow the instructions for the scaffold template. For example, when you choose "Web API 2 Controller with read/write actions" or "Web API 2 Controller - Empty", you are prompted for a controller name

*You will then need to move the recently created controller into the recently created Controllers folder.

Results
From what I can see, Visual Studio does the following:

*

*"App_Start/WebApiConfig2.cs" is created.

*Controllers folder is created.

*Web.config is edited to add "handlers" element with content in "system.webServer".

*The following references are added:

*System.Net.Http

*System.Net.Http.Formatting

*System.Web.Extensions

*System.Web.Http

*System.Web.Http.WebHost

*packages.config is updated to include:

*"Microsoft.AspNet.WebApi"

*"Microsoft.AspNet.WebApi.Client"

*"Microsoft.AspNet.WebApi.Core"

*"Microsoft.AspNet.WebApi.WebHost"

Notes
Subsequently, I recommend following the same steps, starting with right-clicking on the Controllers folder instead of the project. This will put the new controller in the Controllers folder instead of at the root level.
Readme from Visual Studio after following the above steps:

Visual Studio has added the full set of dependencies for ASP.NET Web API 2 to project 'RowersCode.Web'.

The Global.asax.cs file in the project may require additional changes to enable ASP.NET Web API.

*

*Add the following namespace references:

*

*using System.Web.Http;

*using System.Web.Routing;

*If the code does not already define an Application_Start method, add the following method:

protected void Application_Start()

{

}

*Add the following lines to the beginning of the Application_Start method:

GlobalConfiguration.Configure(WebApiConfig2.Register);

A: After much research I have been able to come up with a solution to this problem. Let me illustrate my solution with respect to the Visual Studio Version.
VS 2012
As I mentioned in the question, there is no definite way to create the Web API project in VS2012. You are gonna have to do it by creating an MVC 4 application and setting the Project Template as WebAPI. Then once you have done this and you have your Web API functional, you can safely delete the extra baggage like the Jquery libraries and other stuff, because these things are absolutely of no use here in your project.
VS 2013
In VS2013 there is however a better approach followed to add and manage the Web API projects. Currently I am using VS2013 for the Web API and all things have fallen into place just as I wanted. Kindly see this link and you will get a better idea
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
I hope this information will help all those new to Web API. Especially for those who want to upgrade to Web API or add Web API to existing projects.


text:
Q: How to do group using table component, not fields? The goal is to make something like that using groups

The problem is that I can construct it using fields, but when I export the report constructed from fields (like in most of tutorials) to Excel, it becomes a mess.
I want to use table component, maybe partly, just for the parts where row1, row2... etc are located, because tables are exported rather decently.
Is that possible at all?
If I add a table component into the details band, it shows the whole table for each group (all rows 1-9 are in each group, so I have no grouping at all), like here:

This is my XML file:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report1" language="groovy" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="8075ffe7-6e3e-430c-9792-0842e1047ee7">
    <style name="table">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
        <conditionalStyle>
            <conditionExpression><![CDATA[new Boolean($V{REPORT_COUNT}.intValue()%2==0)]]></conditionExpression>
            <style backcolor="#EFF7FF"/>
        </conditionalStyle>
    </style>
    <style name="table 1">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 1_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 1_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 1_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
        <conditionalStyle>
            <conditionExpression><![CDATA[new Boolean($V{REPORT_COUNT}.intValue()%2==0)]]></conditionExpression>
            <style backcolor="#EFF7FF"/>
        </conditionalStyle>
    </style>
    <subDataset name="New Dataset 1" uuid="6d70e59b-520c-4c3a-b122-fc299a1e36f3">
        <queryString language="SQL">
            <![CDATA[select * from test_table]]>
        </queryString>
        <field name="COLUMN1" class="java.lang.String"/>
        <field name="INITIATOR" class="java.lang.String"/>
        <field name="ID" class="java.lang.String"/>
        <field name="URL" class="java.lang.String"/>
        <field name="DOMAIN" class="java.lang.String"/>
    </subDataset>
    <queryString>
        <![CDATA[select * from test_table]]>
    </queryString>
    <field name="COLUMN1" class="java.lang.String"/>
    <field name="INITIATOR" class="java.lang.String"/>
    <field name="ID" class="java.lang.String"/>
    <field name="URL" class="java.lang.String"/>
    <field name="DOMAIN" class="java.lang.String"/>
    <group name="USER">
        <groupExpression><![CDATA[$F{INITIATOR}]]></groupExpression>
        <groupHeader>
            <band height="20">
                <textField>
                    <reportElement x="0" y="0" width="100" height="20" uuid="f3c7aeda-d5fc-4745-aa57-6b86527bca7d"/>
                    <textFieldExpression><![CDATA[$F{INITIATOR}]]></textFieldExpression>
                </textField>
            </band>
        </groupHeader>
    </group>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="79" splitType="Stretch"/>
    </title>
    <pageHeader>
        <band height="35" splitType="Stretch"/>
    </pageHeader>
    <columnHeader>
        <band height="61" splitType="Stretch"/>
    </columnHeader>
    <detail>
        <band height="82" splitType="Stretch">
            <componentElement>
                <reportElement key="table 1" style="table 1" x="0" y="0" width="802" height="80" uuid="1e1e5c70-7231-407c-8a21-8a8abe18004c"/>
                <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                    <datasetRun subDataset="New Dataset 1" uuid="c1fc144a-34ea-4a3c-bad5-979e248dbdd5">
                        <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                    </datasetRun>
                    <jr:column width="164" uuid="6fc1588c-ff53-457e-9ded-bf2ef1499ef9">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="164" height="30" uuid="37471666-30cf-4fba-a25a-2341517a9ff8"/>
                                <text><![CDATA[COLUMN1]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:columnFooter style="table 1_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement x="0" y="0" width="164" height="20" uuid="23a35d1a-1835-4f98-b948-2e20d170b7cb"/>
                                <textFieldExpression><![CDATA[$F{COLUMN1}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="143" uuid="3bb44350-b9a3-42f3-a4b4-24cc92c1ac7a">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="143" height="30" uuid="32882a4d-9af7-4d20-bffc-d97304f852ec"/>
                                <text><![CDATA[INITIATOR]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:columnFooter style="table 1_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement x="0" y="0" width="143" height="20" uuid="624c6056-9c8d-469d-834e-052e7ba64205"/>
                                <textFieldExpression><![CDATA[$F{INITIATOR}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="145" uuid="fdc25f77-cbf8-437b-9599-8dac13c231c7">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="145" height="30" uuid="9def11e0-f333-4af6-acd2-87693f546b94"/>
                                <text><![CDATA[ID]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:columnFooter style="table 1_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement x="0" y="0" width="145" height="20" uuid="bffecf39-515f-49fa-a2fd-dce3b899664a"/>
                                <textFieldExpression><![CDATA[$F{ID}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="215" uuid="ebcc9292-c0f8-45d7-acfb-a0cd07411c06">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="215" height="30" uuid="119558f5-9f63-408d-88fe-685bff93420c"/>
                                <text><![CDATA[URL]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:columnFooter style="table 1_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement x="0" y="0" width="215" height="20" uuid="57fb4ae3-2ef8-46f5-9078-189afba2cc6f"/>
                                <textFieldExpression><![CDATA[$F{URL}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="134" uuid="f241a40c-8426-4b4f-ad01-fcda25e3891c">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="134" height="30" uuid="d3015f10-9258-4ac9-8e95-a00f450b751e"/>
                                <text><![CDATA[DOMAIN]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:columnFooter style="table 1_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement x="0" y="0" width="134" height="20" uuid="fab1275a-7ae9-443b-8861-fa7c319e01b1"/>
                                <textFieldExpression><![CDATA[$F{DOMAIN}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
        </band>
    </detail>
    <columnFooter>
        <band height="45" splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="54" splitType="Stretch"/>
    </pageFooter>
    <summary>
        <band height="42" splitType="Stretch"/>
    </summary>
</jasperReport>

A: I have edited your jrxml. I passed id from the main query to the table component as parameter and used it in the query for where condition, so the table query will only return the rows which are related to the parent query id.
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report1" language="groovy" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="125"/>
    <style name="table">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
        <conditionalStyle>
            <conditionExpression><![CDATA[new Boolean($V{REPORT_COUNT}.intValue()%2==0)]]></conditionExpression>
            <style backcolor="#EFF7FF"/>
        </conditionalStyle>
    </style>
    <style name="table 1">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 1_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 1_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 1_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
        <conditionalStyle>
            <conditionExpression><![CDATA[new Boolean($V{REPORT_COUNT}.intValue()%2==0)]]></conditionExpression>
            <style backcolor="#EFF7FF"/>
        </conditionalStyle>
    </style>
    <subDataset name="New Dataset 1">
        <parameter name="id" class="java.lang.Integer">
            <defaultValueExpression><![CDATA[]]></defaultValueExpression>
        </parameter>
        <queryString>
            <![CDATA[select * from test_table where id = $P{id};]]>
        </queryString>
        <field name="COLUMN1" class="java.lang.String"/>
        <field name="INITIATOR" class="java.lang.String"/>
        <field name="ID" class="java.lang.String"/>
        <field name="URL" class="java.lang.String"/>
        <field name="DOMAIN" class="java.lang.String"/>
    </subDataset>
    <queryString>
        <![CDATA[select * from test_table;]]>
    </queryString>
    <field name="COLUMN1" class="java.lang.String"/>
    <field name="INITIATOR" class="java.lang.String"/>
    <field name="ID" class="java.lang.String"/>
    <field name="URL" class="java.lang.String"/>
    <field name="DOMAIN" class="java.lang.String"/>
    <group name="USER">
        <groupExpression><![CDATA[$F{INITIATOR}]]></groupExpression>
        <groupHeader>
            <band height="20">
                <textField>
                    <reportElement x="0" y="0" width="100" height="20"/>
                    <textFieldExpression><![CDATA[$F{INITIATOR}]]></textFieldExpression>
                </textField>
            </band>
        </groupHeader>
    </group>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="79" splitType="Stretch"/>
    </title>
    <pageHeader>
        <band height="35" splitType="Stretch"/>
    </pageHeader>
    <columnHeader>
        <band height="61" splitType="Stretch"/>
    </columnHeader>
    <detail>
        <band height="82" splitType="Stretch">
            <componentElement>
                <reportElement key="table 1" style="table 1" x="0" y="0" width="802" height="80"/>
                <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                    <datasetRun subDataset="New Dataset 1">
                        <datasetParameter name="id">
                            <datasetParameterExpression><![CDATA[$F{ID}]]></datasetParameterExpression>
                        </datasetParameter>
                        <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                    </datasetRun>
                    <jr:column width="164">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="164" height="30"/>
                                <text><![CDATA[COLUMN1]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:columnFooter style="table 1_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement x="0" y="0" width="164" height="20"/>
                                <textFieldExpression><![CDATA[$F{COLUMN1}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="143">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="143" height="30"/>
                                <text><![CDATA[INITIATOR]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:columnFooter style="table 1_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement x="0" y="0" width="143" height="20"/>
                                <textFieldExpression><![CDATA[$F{INITIATOR}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="145">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="145" height="30"/>
                                <text><![CDATA[ID]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:columnFooter style="table 1_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement x="0" y="0" width="145" height="20"/>
                                <textFieldExpression><![CDATA[$F{ID}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="215">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="215" height="30"/>
                                <text><![CDATA[URL]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:columnFooter style="table 1_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement x="0" y="0" width="215" height="20"/>
                                <textFieldExpression><![CDATA[$F{URL}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="134">
                        <jr:columnHeader style="table 1_CH" height="30" rowSpan="1">
                            <staticText>
                                <reportElement x="0" y="0" width="134" height="30"/>
                                <text><![CDATA[DOMAIN]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:columnFooter style="table 1_CH" height="30" rowSpan="1"/>
                        <jr:detailCell style="table 1_TD" height="20" rowSpan="1">
                            <textField>
                                <reportElement x="0" y="0" width="134" height="20"/>
                                <textFieldExpression><![CDATA[$F{DOMAIN}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
        </band>
    </detail>
    <columnFooter>
        <band height="45" splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="54" splitType="Stretch"/>
    </pageFooter>
    <summary>
        <band height="42" splitType="Stretch"/>
    </summary>
</jasperReport>


text:
Q: why do I get this attribute error? import teacherfunc

class Teacher:
    __name = ""
    __user = ""
    __class = ""
    __passwd = ""
    def __init__(self, name, user, clas, passwd):
        self.__name = name
        self.__user = user
        self.__class = clas
        self.__passwd = passwd

    def set_name(self, name):
        self.__name = name
    def get_name(self):
        return self.__name

    def set_user(self, user):
        self.__user = user
    def get_user(self):
        return self.__user

    def set_class(self, clas):
        self.__class = clas
    def get_class(self):
        return self.__class

    def set_passwd(self,passwd):
        self.__passwd = passwd
    def get_passwd(self):
        return self.__passwd

mrhall = Teacher("Stuart Hall", "halls", "Class_A", "passwd")
mrkasanda = Teacher("Kasanda", "kasandam", "Class_B", "passwd")
mrbeasley = Teacher("Bradley Beasley", "beasleyb", "Class_C", "passwd")

userinp = input("What teacher are you: ")

for field in [mrhall, mrkasanda, mrbeasley]:

    if field.__user == userinp.lower():
        usr = field

print("Welcome", usr.__passwd)
passinp = input("Enter your password to get class scores: ")
while passinp != usr.__passwd:
    passinp = input("Enter your password to get class scores: ")

teacherfunc.main(usr.__user)

the teacherfunc main() function is a function that allows the user to view data but is not the problem. it gives an attribute error saying that the class Teacher does not have an attribute named __user, but it quite obviously isn't.
I would be very grateful if you could help.
thanks.


text:
Q: Java: Make JTextArea scrollable This is my first post so please forgive me if I am not following the rules correctly.
I am trying to do something relatively simple in Java. I want to make a JTextArea scrollable.  I am aware this has been asked before (Java :Add scroll into text area).  However, when I follow this example by adding JTextArea to JScrollPane my JTextArea does not become scrollable.  What is it that I am missing?
Here is my code:
    import ...;

    public class MyControlPanel extends JPanel {

    //Declare variables
    private JComboBox accountsBox;
    private String[] accType = {"Current Account", "Savings Account"};
    private JLabel selAccType, initDeposit, logLabel, simLabel;
    private JTextField depositText;
    private JTextArea log;
    private JScrollPane scroll;
    private JButton createAccount, start, stop;
    private JPanel panel1, panel2, panel3, panel4, panel5, panel6;
    private Timer timer;
    private MyAccount theAccount;
    private Random randNum1, randNum2;
    private DecimalFormat df;

    //Constructor
    public MyControlPanel() {

        //Create instances:
        selAccType = new JLabel("Please select account type: "); //JLabel
        initDeposit = new JLabel("Input initial deposit: ");
        logLabel = new JLabel("Log:");
        simLabel = new JLabel();
        accountsBox = new JComboBox(accType); //JComboBox
        depositText = new JTextField("0"); // JTextField
        log = new JTextArea(); //JTextArea
        scroll = new JScrollPane(log); //JScrollPane
        createAccount = new JButton("Create Account"); //JButton
        start = new JButton("Start");
        stop = new JButton("Stop");
        panel1 = new JPanel(); //JPanel
        panel2 = new JPanel();
        panel3 = new JPanel();
        panel4 = new JPanel();
        panel5 = new JPanel();
        panel6 = new JPanel();
        timer = new Timer(); //Timer
        df = new DecimalFormat("#.00");

        //Add ActionListeners
        createAccount.addActionListener(new ActionListener() {...});

        start.addActionListener(new ActionListener() {...});

        stop.addActionListener(new ActionListener() {...});

        //Set JTextField size
        depositText.setColumns(5);

        //Set JTextArea size
        log.setPreferredSize(new Dimension(780, 150));

        //Set panel size
        panel1.setPreferredSize(new Dimension(500, 500));
        panel2.setPreferredSize(new Dimension(800, 50));
        panel3.setPreferredSize(new Dimension(500, 50));
        panel4.setPreferredSize(new Dimension(500, 50));
        panel5.setPreferredSize(new Dimension(800, 25));
        panel6.setPreferredSize(new Dimension(800, 200));

        //Set layout in panel5 to align left
        panel6.setLayout(new FlowLayout(FlowLayout.LEFT));

        //Add components to each panel
        addPanels();

        //Place objects in the framed window
        this.add(panel1);
        this.add(panel2);
        this.add(panel3);
        this.add(panel4);
        this.add(panel5);
        this.add(panel6);
    }

    public void addPanels() {...}

    public void removePanels() {...}

}

A: You need to change:
log.setPreferredSize(new Dimension(780, 150));

to:
scroll.setPreferredSize(new Dimension(780, 150));


text:
Q: Counting the occurence of substrings in matlab I have a cell, something like this P= {Face1 Face6 Scene6 Both9 Face9 Scene11 Both12  Face15}. I would like to count how many Face values, Scene values, Both values in P. I don't care about the numeric values after the string (i.e., Face1 and Face23 would be counted as two). I've tried the following (for the Face) but I got the error "If any of the input arguments are cell arrays, the first must be a cell array of strings and the second must be a character array".
strToSearch='Face';
numel(strfind(P,strToSearch));

Does anyone have any suggestion? Thank you!

A: Use regexp to find strings that start (^) with the desired text (such as 'Face'). The result will be a cell array, where each cell contains 1  if there is a match, or [] otherwise. So determine if each cell is nonempty (~cellfun('isempty', ...): will give a logical 1 for nonempty cells, and 0 for empty cells), and sum the results (sum):
>> P = {'Face1' 'Face6' 'Scene6' 'Both9' 'Face9' 'Scene11' 'Both12' 'Face15'};
>> sum(~cellfun('isempty', regexp(P, '^Face')))
ans =
     4

>> sum(~cellfun('isempty', regexp(P, '^Scene')))
ans =
     2

A: Your example should work with some small tweaks, provided all of P contains strings, but may give the error you get if there are any non-string values in the cell array.
P= {'Face1' 'Face6' 'Scene6' 'Both9' 'Face9' 'Scene11' 'Both12' 'Face15'};
strToSearch='Face';
n = strfind(P,strToSearch);
numel([n{:}])

(returns 4)


text:
Q: jquery ajax is showing not found error i am trying to use jquery ajax to pass data to server from client side.it should be super easy and it is.i added a static method in home.aspx and posted the data in there using ajax.but i have no idea why its always saying not found error.please any one can help me on that? here is my ajax code.
<script type="text/javascript">
   $(document).ready(function () {
       $('#form1home a').click(function () {
           var position = $(this).parent().attr("id");
           $.ajax({
               type: 'POST',
               url: 'home.aspx/clickaction',
               contentType: 'application/json',
               dataType: 'json',
               data:  JSON.stringify({ "position":position }),
               success: function () {
               },
               error: function (request, status, error) {
                   alert(request+" "+error);
               }
           });

       });

   });

i am also giving the static method thati used in c#.
[WebMethod]
public static void clickaction(string position)
{
    DataBaseClass db = new DataBaseClass();
    string qry = "select * from cms_tbl where position='" + position + "' and shopid='" + HttpContext.Current.Session["shopid"].ToString() + "'";
    DataTable dt = db.ConnectDataBaseReturnDT(qry);

    if (dt.Rows[0]["type"].ToString() == "product")
    {
        string path = "product.aspx?id=" + dt.Rows[0]["items"].ToString() + "&shop=" + HttpContext.Current.Session["shopid"].ToString();
        HttpContext.Current.Response.Redirect(path);
    }
    else if (dt.Rows[0]["type"].ToString() == "subcat")
    {
        string path = "productdisplay.aspx?id=" + dt.Rows[0]["items"].ToString() + "&sid=" + HttpContext.Current.Session["shopid"].ToString();
        HttpContext.Current.Response.Redirect(path);
    }
    else if (dt.Rows[0]["type"].ToString() == "brand")
    {
        string path = "productdisplay.aspx?bid=" + dt.Rows[0]["items"].ToString() + "&sid=" + HttpContext.Current.Session["shopid"].ToString();
        HttpContext.Current.Response.Redirect(path);
    }
}

A: the only thing I suggest you to check is the value of Position that you get from attribute of its parent
var position = $(this).parent().attr("id");

check it with an alert.


text:
Q: How to do a Proper Escape of this Function? I have a DIV tag generated from jQuery that goes like this:
$('#results')
 .append('

'
 + A.name
 + '

');

Firebug is giving me an error "missing ) argument after list" as it does not recognise the ) immediately after 'mouseover'.
Doing a \'mouseover\' produces a syntax error upon mouseover of the DIV. The syntax error reads: function(){google.maps.event.trigger(marker,
and a look at the generated DIV shows:

Doing a "mouseover" produces a blank document.
How do I do a proper escape for this function?
UPDATE:
This should work:
$('#results')
 .append('

'
 + A.name
 + '

');

I need to put escaped double quotes for the function and escaped single quotes for the argument.

A: You are putting data in JS in HTML in JS in HTML. Every level of encapsulation there requires a string escape, otherwise out-of-band characters will cause errors and possibly security holes. The human brain is not good at keeping track of multiple nested levels of string encapsulation.
So use jQuery's element creation shortcuts to set attributes on the new div, and the event handling features to add the listener to it, instead of messing around with ugly and unsafe HTML string hacking:
var div= $('
', {id: A.pid}).append($('
', {text: A.name}));
div.mouseover(function() {
    google.maps.event.trigger(marker, 'mouseover');
});
$('#results').append(div);

A: You need to put " around the values of your html attributes. Otherwise the browser thinks the attribute ends at the next whitespace and that is exactly right after the (marker, part.
$('#results')
 .append('

'
 + A.name
 + '

');


text:
Q: Why could not rollback after applying @transaction I add @Transactional in Service layer but it doesn't work.
*two action*

*

*queryResult = postMapper.insertPost(params);

*teamMemberMapper.insertTeamMember(captain);

@Transactional(noRollbackFor = Exception.class)
    @Override
    public boolean registerPost(PostDTO params, TeamMemberDTO captain) {
        int queryResult = 0;

        if (params.getPnum() == null) { //new post

            queryResult = postMapper.insertPost(params);
            long pnum = params.getPnum();

            TeamMemberDTO cap = captain;
            cap.setPnum(pnum);

            teamMemberMapper.insertTeamMember(captain);

        } else {

            queryResult = postMapper.updatePost(params);
        }

         return (queryResult == 1) ? true : false;
    }


text:
Q: Problemas com a criação de novos projetos Java no NetBeans
Nas opções para criação de novo projeto java não aparece a opção 'Java' propriamente dita.
A primeira opção é Java Whith Maven como podem ver.

Dentre as opções disponiveis ou selecionar Java Whith Maven não está disponivel a caixa de seleção para criação da classe principal.
Ja verifiquei e o java esta instalado em minha maquina! Inclusive a variavel JAVA_HOME está configurada.
Conhece alguma solução para esse problema??

A: Infelizmente o Netbeans não tem essa opção de projeto "básico" que já cria uma classe principal (com o método main).
Na segunda opção da sua segunda imagem será criada uma estrutura de projeto com um pacote padrão. Então, você poderá criar suas classes dentro do pacote e uma delas pode ser sua classe principal. Faça como a seguir:

Em seguida escolha o tipo de template de classe que você quer, no seu caso, Java Main Class:

Clique o botão "Next" e siga as instruções.

A: Diferente do que o colega respondeu, o NetBeans cria sim um projeto com a classe e método main prontos.
Basta clicar: Novo Projeto/Java with Ant/Java Application
Pronto! Já tem seu projeto com a classe (NomeDoProjeto) já criada como inicializadora e método main dentro dela prontos.
Veja o exemplo:
Criar Novo Projeto
Selecionar Java com Ant
Lembre-se de verificar ou editar a caixa de criação da classe main


text:
Q: Como saber se uma porta está aberta ou não no Linux Tenho um script PHP que atua como servidor de um chat (websocket) que tenho num determinado sistema. Percebo que as vezes inesperadamente esse serviço para de rodar. Ele é executado através do comando nohup.
Estou usando Linux.
Só percebo que o script do meu websocket para de funcionar quando vejo o erro do navegador:

WebSocket connection to 'wss://myserver:9001/chat' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

Bem, eu gostaria de saber detectar se realmente o meu script do servidor websocket parou de rodar, pois não sei se o erro do navegador sempre quer dizer que meu servidor "caiu".
Então, como é que posso detectar se determinada porta está em uso ou não?
Qual comando no Linux posso utilizar pra saber se uma porta está aberta ou não?

A: A forma mais simples para verificar isto seria usando o comando:
nmap -sT -O localhost

Como adicionado pelo Marco pode ser testado de um ponto externo:
telnet meudominio.com 443 (onde 443 é o número da sua porta)

Existe uma opção também seria utilizar o netstat:
# netstat -tl - lista as conexões abertas de tcp em modo de escuta
# netstat -t - lista as conexões tcp estabelecidas
# netstat -p - lista os programas que estão usando a conexão
# netstat --numeric-ports - não converte o número da porta para ser listado
# netstat --numeric-hosts - não converte o número de ip para nome do host

# netstat -t -l -p --numeric-ports

Ou ainda:
lsof -i tcp


text:
Q: php foreach from each item add tr I have data array products
i try view

<?php foreach($products as $object): ?>

        <?php echo $object->name;?>

        <?php if ($object->id%1 == 0):?>

                Count
                Price

        <?php endif; ?>

<?php endforeach;?>

but i want other output view like this:

I have regions array from database to

A: I don't really understand your question but here is my answer for what i think you are after
<?php

// IGNORE THIS IS JUST BUILDING PRODUCTS

$product = new stdclass();
$product->name = 'Product 1';
$product->id = 1;
$product->count = 3;
$product->price = 4;

$products[] = $product;

$product = new stdclass();
$product->name = 'Product 2';
$product->id = 2;
$product->count = 1;
$product->price = 7;

$products[] = $product;

$product = new stdclass();
$product->name = 'Product 3';
$product->id = 3;
$product->count = 5;
$product->price = 3;

$products[] = $product;

$region = new stdclass();
$region->name = 'Region 1';

$regions[] = $region;

$region = new stdclass();
$region->name = 'Region 2';

$regions[] = $region;
?>

Regions
<?php foreach( $products as $product ): ?>
<?php echo $product->name; ?>
<?php endforeach; ?>

<?php foreach( $products as $product ): ?>
Count	Price
<?php endforeach; ?>

<?php foreach( $regions as $region ): ?>

<?php echo $region->name; ?>
<?php foreach( $products as $product ): ?>
<?php echo $product->count; ?>	<?php echo $product->price; ?>
<?php endforeach; ?>

<?php endforeach; ?>

This will result with


text:
Q: PyGTK Glade File Manager I am trying to make a file manager in python that looks like GNOME default file manager (nautilus) Because I am developing a FilePane plugin for a python written text editor. I don't know if there is a widget to give me the same look of Nautilus. If not, what widgets can I use to get a nice looking file manager?

A: I searched GTK API and I found that GTK TreeView does what I want.


text:
Q: Does Dudley's theorem hold for nonseparable metric spaces? Dudley's theorem (1966) states that if $(X, d)$ is a metric space and if $X$ is separable and $\mu$, $\mu_i$ are Borel probability measures then $\mu_i \to \mu$ narrowly iff $d_{\text{BL}}(\mu_i, \mu) \to 0$ where $d_{\text{BL}}$ is the bounded Lipschitz metric.
Definitions:
$(\mu_i)$ converges narrowly to $\mu$ (where all measures are Borel probability measures) if
$$\int f \, d\mu_i \to \int f \, d\mu \text{ for all $f$ bounded and continuous on $X$}$$
The bounded Lipschitz metric is a metric on the space $\text{BL}(X,d) := \{f : X \to \mathbb{R} : f \text{ is bounded and Lipschitz} \}$. Then define
$$d_\text{BL}(\mu, \nu) := \sup \left \{ \left | \int f \, d\mu - \int f \, d\nu\, \right | : f \in \text{BL}(X,d), \|f\|_\text{BL} \leq 1 \right \}$$
where $\|f\|_{\text{BL}}$ is the sum of the Lipschitz-norm and the $\infty$-norm.
The proof uses Arzela-Ascoli, but I wonder what would be a counterexample if $X$ isn't separable? From right-to-left still works.

A: Let $X$ be a set with $2$-valued measurable cardinal.  (Real-valued measurable can also be done, but with some more complications, so I do not do that now.)  Give it the discrete metric.  Let $\mu$ be a countably-additive measure on the Borel sets (i.e., the power set) with values $0$ and $1$ such that each singleton has measure $0$ but $\mu(X) = 1$.  There is a net $\mu_i$ of point-masses converging to $\mu$ narrowly, but not in the BL metric.
A point-mass is a measure that assigns measure $1$ to a certain singleton, and measure $0$ to the complement.  As long as our net of point-masses is eventually outside each set of measure $0$, we have convergence to $\mu$ in the narrow topology.  But any point-mass $\mu_i$ at the point $a_i$ is far away from $\mu$ in the BL topology, since the indicator function of the singleton $a_i$ is a BL function with norm $2$.
Another note.  For any bounded function $f \colon X \to \mathbb{R}$, there is a set $F\subseteq X$ with $\mu(F)=1$ and $f$ is constant on $F$; the constant value there is the integral $\int f d\mu$.


text:
Q: Android - Set Clicked focus on Button I am having 4 buttons in my layout, now whenever i click any button, after the click event, button should be highlighed showing that it was clicked last.
For making such thing, i have tried the following:
code:
btn1.setOnClickListener(new button_click_listener());
btn2.setOnClickListener(new button_click_listener());

class button_click_listener implements Button.OnClickListener
{
    @Override
    public void onClick(View v)
    {
       if(v==btn1)
       {
            btn1.requestFocus();
       }

       if(v==btn2)
       {
            btn2.requestFocus();
       }
        .......
    }
}

XML Layout:
<Button
   android:text="Click 1"
   android:id="@+id/btnClick1"
   android:layout_width="70dp"
   android:layout_height="wrap_content"
   style="@android:style/Widget.Button.Small"
   android:padding="10dp"
   android:focusableInTouchMode="true">
</Button>

How do i show clicked highlight on the button that was clicked last?
Please, show me a way and give suggestions.
Update:
If i set android:focusable="true" then button is highlighted and focused, but then at the same time, i need to click twice on the button to perform the actual click event.

A: its easy buddy...just you have to set backgroundcolor of ur button on ur click event and each time any button clicked u have to set other buttons background color null

A: This functionality resembles RadioButtonGroup, customize RadioButtonGroup to your requirements.
Setting Style in RadioGroup by :
<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_window_focused="false"
        android:drawable="@drawable/radio_hover" />
    <item android:state_checked="false" android:state_window_focused="false"
        android:drawable="@drawable/radio_normal" />
    <item android:state_checked="true" android:state_pressed="true"
        android:drawable="@drawable/radio_active" />
    <item android:state_checked="false" android:state_pressed="true"
        android:drawable="@drawable/radio_active" />
    <item android:state_checked="true" android:state_focused="true"
        android:drawable="@drawable/radio_hover" />
    <item android:state_checked="false" android:state_focused="true"
        android:drawable="@drawable/radio_normal_off" />
    <item android:state_checked="false" android:drawable="@drawable/radio_normal" />
    <item android:state_checked="true" android:drawable="@drawable/radio_hover" />
    </selector>

Set this Selector to your Radio button.

A: The problem is that you need a new state. Follow the directions here and add a "state_highlighted", or whatever you'd like to call it:
How to add a custom button state


text:
Q: How to prove arguments with rules of inference? I have the following argument:
-∀x(P(x) ∨ Q(x))
∀x(¬P(x) ∧ Q(x)) → R(x)
___________________.
∴ ∀x(¬R(x) → P(x))
I don't want the answer. I just need some general tips to get there. I know I can use Universal Instantiation on the two arguments to remove $\forall$$x$, but that's about it. I can't see any other rules I could use.

A: You can rewrite the second sentence as:
$$\forall x (\neg R(x) \to \neg(\neg P(x) \wedge Q(x)))$$
by taking the contrapositive of the inner formula. That in turn is equivalent to:
$$\forall x (\neg R(x) \to P(x) \vee \neg Q(x))$$
(Here, we get rid of one pair of parentheses by using the convention that $\vee, \wedge$ bind more tightly than $\to$).
So temporarily instantiate the universally quantified x:
$$ (\neg R(a) \to P(a) \vee \neg Q(a))$$.
Suppose $$\neg R(a) \tag{not-R(a)}$$
Then:
$$ P(a) \vee \neg Q(a) \tag{PnotQ}$$
Instantiating the first sentence $\forall x (P(x) \vee Q(x))$ with $a$ gives:
$$P(a) \vee Q(a) \tag{PQ}$$
From (PnotQ) and (PQ) you can conclude:
$$P(a)$$
Here's why:  (PnotQ) is equivalent to $Q(a) \to P(a)$, and (PQ) is equivalent to $\neg Q(a) \to P(a)$. From these, we can conclude $Q(a) \vee \neg Q(a) \to P(a)$. But of course $Q(a) \vee \neg Q(a)$ is provable, so by modus ponens, $P(a)$.
Discharging the assumption (not-R(a)) gives:
$$\neg R(a) \to P(a)$$
Finally, $a$ was just temporary, so we can eliminate it and universally quantify:
$$ \forall x(\neg R(x) \to P(x))$$

A: In the second assumption you write that P(x) and Q(x) can't occur so by contraopistion of the second assumption combining with the first you the required result.


text:
Q: Swift: How to populate a UITableView I am trying to get the results from the function get() to the tableview. the result inside this function comes from Http post. So i am using nsmutableurl etc. i get the data n can see in my output console and now want it on my tableview. how can i do this?
I have this bunch of code, I managed to fetch the data (can see in my output console) and now I am trying to load these data on the table view. How can I pass this data inside the table?
    func get(){

        let request = NSMutableURLRequest(URL: NSURL(string: "http://myurl/somefile.php")!)
        request.HTTPMethod = "POST"
        let postString = "id=\(cate_Id)"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in

            guard error == nil && data != nil else {                                                          // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }

            let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")
        }
        task.resume()
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        i need the count of the rows here
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        land want to display the data inside each cell

    }

A: Since you're not providing any kind of information about your HTTP Request result, I'm trying to answer you in a "general way".
In general you get a response as an Array of Dictionaries of your desired data. To make it easy: Let's say you're requesting Strings, then you have to do it like this:
let myStringArray: [String] = []

Within your HTTP response block you take your response and please beware! This Code depends completely on YOUR response tree. I have no idea what your response it, since you haven't provided it.
        if let JSON = response.result.value {

            let myString = String((JSON.valueForKey("stringWithinMyResonseTree"))!)
            myStringArray.append(myString)

            self.tableView.reloadData()
        }

Then you have your numbers of rows with:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myStringArray.count
}

On the Cell it depends on what you want to do with it. If you have for example a Label within your Cell and want to display the value of your String on it, you would create a UITableViewCell subclass and call it for example MyCell. In MyCell you create an Outlet of your Label like this:
class MyCell: UITableViewCell {

    @IBOutlet weak var myLabel: UILabel!

Then you need to return your UITableView subclass and populate the Label with the desired String.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as! MyCell
        let string = myStringArray[indexPath.row]
        cell.myLabel.text = string

        return cell

}

Don't forget to set the Cell identifier within the Interface Builder properties.
Your request expects an Array of one Dictionary, but you cast it as a String. So instead of your get() func, please use the following:
func download() {
    let requestURL: NSURL = NSURL(string: "http://myurl/somefile.php")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest) {
        (data, response, error) -> Void in

        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode

        if (statusCode == 200) {
            print("Everyone is fine, file downloaded successfully.")

            do{

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                let grouID = String(json.valueForKey("group_id"))
                let name = String(json.valueForKey("NAME"))

                print("grouID = \(grouID)")
                print("name = \(name)")
                print("debug: this code is executed")

            }catch {
                print("Error with Json: \(error)")
            }

        }
    }

    task.resume()
}

To debug your problems, please create an exception breakpoint:


text:
Q: How to gather user input in a JSP so that it can be stored in database I dont know JSP. I have written the below Java JDBC code which must be integrated in JSP.
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
public class searchlink{
public static void main(String args[]) throws Exception {
    Connection con=null;
    Statement stmt=null;
    Statement stmtR=null;
    String link="http://www.topix.com/rss/city/ellensburgwa";
    String source="Sample";
    if(con==null){
            SQLConnection.setURL("jdbc:sqlserver://192.168.2.53\\SQL2005;user=sa;password=365media;DatabaseName=LN_ADWEEK");
            con=SQLConnection.getNewConnection();
            stmt=con.createStatement();
            stmtR=con.createStatement();
    }
    ResultSet rs;
    boolean hasRows=false;
    rs=stmt.executeQuery("select url from urls where url='"+link+"'");
    while(rs.next()){
        hasRows=true;
        //String mem=rs.getString(1);
        System.out.println("This URL already exists in DB");}
    if (!hasRows)
    {
        PreparedStatement insertUrlStatement = con.prepareStatement("INSERT INTO urls VALUES(?, ?, ?, ?, ?)");
        insertUrlStatement.setInt(1, 21211);
        insertUrlStatement.setString(2, link);
        insertUrlStatement.setString(3, source);
        insertUrlStatement.setInt(4, 1);
        insertUrlStatement.setInt(5, 0);
        insertUrlStatement.executeUpdate();
             }
           }
        }

Initially, my task is to create a text box and assign the value the user enters in it to the String named link which is in the code above.
Kindly advise how to build a JSP program for that. Also, please let me know whether any changes are to be made in the Java code above for integrating in JSP or I can just include the whole program inside <% content %>.

A: First of all, you should avoid writing Java code in a JSP file.
Here's a step by step:

*

*Learn at least HTTP and HTML. To the point, you need to understand what HTTP is all about and distinguish the "server side" and "client side" concepts. You also need to learn HTML as web markup language and the HTML forms to collect user input. This answer contains helpful links.

*Learn JSP and Servlets. You need to understand that JSP is a Java based view technology which provides a template to write HTML/CSS/JS in which in turn will be sent to the webbrowser. This answer contains helpful links.

*Having learnt 1 and 2, start creating a JSP file with a simple HTML form with the necessary input fields:
 <form action="servleturl" method="post">
     <input type="text" name="link">
     <input type="text" name="source">
     <input type="submit">
 </form>

*Then create a class which extendsHttpServlet which gathers those input parameters and saves in the database in the doPost() method:
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     String link = request.getParameter("link");
     String source = request.getParameter("source");
     LinkDAO dao = new LinkDAO();
     try {
         dao.save(link, source);
     } catch (SQLException e) {
         throw new ServletException("Saving in DB failed", e);
     }
     request.getRequestDispatcher("result.jsp").forward(request, response);
 }

Map this servlet in web.xml file on an url-pattern of servleturl (at least, it should be the same as where your <form action> is pointing to).

*Then create a DAO class which does the necessary JDBC stuff:
 public class LinkDAO {
     public void save(String link, String source) throws SQLException {
         // Your original code here. You should however modify it to make it
         // free of potential resource leaking.
     }
 }

To learn a bit more how to get started with the DAO pattern, you may find this article useful.

A: Time to go learn some basics:
The Model-View-Control (MVC) pattern would be a very good start. You are in luck - there are many implementations in Java:
http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller#Java

A: if you get past that hurdle id also suggest you use something like springs JdbcDaoSupport to manage your datasource connections. As well as cutting down the number of lines you'll need to write, it also helps with connection management


text:
Q: Can't configure WebMvcConfigurer for interceptors addition in spring boot 2 application I am trying to create an interceptor for the first time in my spring boot application, but somehow it is not created automatically, as described in the tutorials.
I've tried to create a WebConfig class that extends the WebMvcConfigurerAdapter class and annotated it as a @Component but it haven't worked. I also tried to create a WebConfig that implements the WebMvcConfigurer interface with @Configuration and @EnableWebMvc annotations but it hadn't worked either.
current WebConfig class:
@Configuration
@EnableWebMvc
@ComponentScan("com.*")
public class WebConfig implements WebMvcConfigurer {

    public WebConfig() {
        super();
    }

    @Autowired
    HandlerInterceptor headerModifierInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("------------------hi");
        registry.addInterceptor(headerModifierInterceptor);
    }

}

Application class
@SpringBootApplication
@EnableWebSecurity
@ComponentScan(basePackages = {"com.*"})
@EntityScan("com")
public class CoreRestAPIApplication {

    public static void main(String[] args) {

        SpringApplication.run(CoreRestAPIApplication.class, args);

    }
}

My interceptor class:
@Component
public class RestTemplateHeaderModifierInterceptor
        implements HandlerInterceptor {

    @Autowired
    AuthUtil authUtil;

    @Autowired
    JwtTokenProvider jwtTokenProvider;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String resolvedToken = jwtTokenProvider.resolveToken(request);
        if (!StringUtils.isEmpty(resolvedToken)) {
            String updatedToken = jwtTokenProvider.createToken(jwtTokenProvider.getUsername(resolvedToken), jwtTokenProvider.getAuthentication(resolvedToken).getAuthorities());
            response.addHeader(authUtil.AUTH_HEADER_NAME, updatedToken);
        }
    }
}

A: After some search, I've found that I have a registered WebMvcConfigurationSupport configuration. However, if someone is looking and wishes to modify headers using an interceptor, DO NOT use an interceptor for that, as for spring will not handle it well if you return a ResponseEntity or your controller method returns a @ResponseBody.
Instead(at least for my use which is filtering and renewing a token every time a valid request is received) use the doFilterInternal method to add the header to the response(or add a cookie if you wish..) here is an example of how I did it:
public class JwtTokenFilter extends OncePerRequestFilter {

  private JwtTokenProvider jwtTokenProvider;

  public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
    this.jwtTokenProvider = jwtTokenProvider;
  }

  @Override
  protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    String token = jwtTokenProvider.resolveToken(httpServletRequest);
    try {
      if (token != null && jwtTokenProvider.validateToken(token)) {
        Authentication auth = jwtTokenProvider.getAuthentication(token);
        SecurityContextHolder.getContext().setAuthentication(auth);
        if(!jwtTokenProvider.isExpired(token)) {
          httpServletResponse.setHeader("authKey", jwtTokenProvider.createToken(jwtTokenProvider.getUsername(token), auth.getAuthorities()));
        }
      }
    } catch (ClientErrorException ex) {
      //this is very important, since it guarantees the models is not authenticated at all
      SecurityContextHolder.clearContext();
      httpServletResponse.sendError(ex.getStatus().value(), ex.getMessage());
      return;
    }

    filterChain.doFilter(httpServletRequest, httpServletResponse);
  }

}


text:
Q: Databricks Koalas Column Assignment Based on Another COlumn Value Lambda Function Given a koalas Dataframe:
df = ks.DataFrame({"high_risk": [0, 1, 0, 1, 1],
                   "medium_risk": [1, 0, 0, 0, 0]
                   })

Running a lambda function to get a new column based on the existing column values:
df = df.assign(risk=lambda x: "High" if x.high_risk else ("Medium" if x.medium_risk else "Low"))
df
Out[72]:
   high_risk  medium_risk  risk
0          0            1  High
4          1            0  High
1          1            0  High
2          0            0  High
3          1            0  High

Expected return:
       high_risk  medium_risk  risk
    0          0            1  Medium
    4          1            0  High
    1          1            0  High
    2          0            0  Low
    3          1            0  High

Why does this assign "High" to each of the values. The intent is to operations on each row, is it looking at the whole column in the comparison?

A: Using assign on a koalas df seems not easy to me, but for your case, I would mul the column 'high_risk' by 2 then add the column 'medium_risk' and finally map the result to replace the 2 by 'high' (because you multiply the column by 2 before) 1 by 'medium' and 0 by 'low' such as:
df = df.assign(risk= df.high_risk.mul(2).add(df.medium_risk)
                       .map({0:'low', 1:'medium', 2:'high'}))
df
   high_risk  medium_risk    risk
0          0            1  medium
1          1            0    high
2          0            0     low
3          1            0    high
4          1            0    high

Note : this would fail if you have 1 in both high and medium risks column.


text:
Q: Python XML parinsg is seeing unexpected tag I'm trying to parse an XML which is including following code example:
<?xml version="1.0" encoding="UTF-8"?>
<ops:OPS xmlns:ops="http://www.si2.org/schemas/OPS"
         opsVersion="OPS_1.1">
    <ops:RulesSection>
        [...some stuff..]
    </ops:RulesSection>
</ops:OPS>

When I'm parsing this file and checking Elements value I'm expecting to find an element called "ops:RulesSection"
from xml.etree                  import ElementTree as ET
from xml.etree.ElementTree      import ElementTree, Elem
tree = ET.parse(OPSDRMFile)
root = tree.getroot()
for elem in root:
    print("!!!",elem)

However I am getting following results
!!! <Element '{http://www.si2.org/schemas/OPS}RulesSection' at 0x2b557da50f98>

it seems that "ops:" tag has been replaced by its value from the beginning of the file... can someone explain if this is expected behavior? Is there a way to NOT expand such parameter?
(as of now if I want to perform further parsing I need to transfrom "ops:NewTagToFind" as "{http://www.si2.org/schemas/OPS}NewTagToFind" when I using "findall" command.
Thanks,
Chris


text:
Q: How change legend icons size on leaflet map generated using QGIS2WEB plugin? I need to know how to change size of icons from the leaflet web map legend generated using qgis2web plugin. Is there any icon size information inside code which I can change to larger number? I have searched for it in the map folder, but with no success.

A: The exported images are in the legend folder in your export folder. The code which includes them is in index.html. Open that in a text editor, and find:

where LAYERNAME is the name of the layer this legend icon applies to. Add size info like this:

Width and height are in pixels.