text:
Q: Why does Post action work in Postman, not in C# I am trying to execute a GET command so I get can get data from a server. The Curl below works in Postman.
$ curl -X GET -H "Authorization: {SESSION_ID}" \
https://{server}/api/{version}/metadata/vobjects

While running my code, I am able to get the session ID. The next step is to get the data. But when I execute the GET, I don't get any response. Instead a I get an error as follows: "Specified value has invalid HTTP Header characters. (Parameter 'name')"
Below is the C# code I am trying to execute
public static void getObjects(string sessionID)
        {
            var client = new RestClient("https://generic-server.com/api/v20.3/metadata/vobjects/");
            client.Timeout = -1;
            var request = new RestRequest(Method.GET);
            request.AddHeader("Authorization:", sessionID);
            IRestResponse response = client.Execute(request);
            Console.WriteLine("Here's the response: "  + response.Content + " " + response.Content.Length);
            Console.WriteLine("Here's the error message: " + response.ErrorMessage);
        }

Problem: I get no response from the server and the response length is zero.

Here's the response:  0

response.ErrorMessage gives the following:

Here's the error message: Specified value has invalid HTTP Header characters. (Parameter 'name')

Note: When I leave the colon out of of the header, then I get the following response from the server:

{"responseStatus":"FAILURE","errors":[{"type":"INVALID_DATA","message":"Invalid http header [Accept: application/json, text/json, text/x-json, text/javascript, application/xml, text/xml]"}]} 190

A: Have you tried ("Authorization", $"Bearer {sessionID"});


text:
Q: Difficulty porting raw PCM output code from Java to Android AudioTrack API I'm attempting to port an application that plays chiptunes (NSF, SPC, etc) music files from Java SE to Android. The Android API seems to lack the javax multimedia classes that this application uses to output raw PCM audio. The closest analog I've found in the API is AudioTrack and so I've been wrestling with that.
However, when I try to run one of my sample music files through my port-in-progress, all I get back is static. My suspicion is that it's the AudioTrack I've setup which is at fault. I've tried various different constructors but it all just outputs static in the end.
The DataLine setup in the original code is something like:
AudioFormat audioFormat = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED,
                44100, 16, 2, 4, 44100, true );
DataLine.Info lineInfo = new DataLine.Info( SourceDataLine.class, audioFormat );
DataLine line = (SourceDataLine)AudioSystem.getLine( lineInfo );

The constructor I'm using right now is:
AudioTrack = new AudioTrack( AudioManager.STREAM_MUSIC,
        44100,
        AudioFormat.CHANNEL_CONFIGURATION_STEREO,
        AudioFormat.ENCODING_PCM_16BIT,
        AudioTrack.getMinBufferSize( 44100,
                AudioFormat.CHANNEL_CONFIGURATION_STEREO,
                AudioFormat.ENCODING_PCM_16BIT ),
        AudioTrack.MODE_STREAM );

I've replaced constants and variables in those so they make sense as concisely as possible, but my basic question is if there are any obvious problems in the assumptions I made when going from one format to the other.

A: So I had a little time to look at this further today, and I think I've nailed it down. The AudioFormat declaration in the first code sample above has the big endian parameter set to "true", but the Android AudioTrack expects PCM data to be in little endian format.
So I wrote a quick little loop to test out my hunch like so:
 for( int i = 0; i + LEN_PCM_SAMPLE_BYTES < LEN_PCM_BUFFER; i += LEN_PCM_SAMPLE_BYTES ) {
    // Really rude endian conversion.
    byte bytTemp = a_bytBuffer[i];
    a_bytBuffer[i] = a_bytBuffer[i + 1];
    a_bytBuffer[i + 1] = bytTemp;
 }

Basically, this loop flips the bytes of every (16-bit) sample in the buffer. This works great, except it's a little choppy since it's terribly inefficient. I tried using a ByteBuffer but that doesn't seem to flip the bytes in the individual samples.
I'll figure something even better out going forward, but the basic problem here is solved. Hope someone else finds this useful!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I save from VI to a pipe? I've seen lots of ways to redirect input from stdin to VI, but I'd like to redirect VI to save to a pipe rather than a file. For example, I'd like to pipe VI's entire pipe buffer to another text editing program, such as kate. Is this possible?

A: I'm not sure about plain vi. But in Vim, you can write a buffer (or portions of a buffer) to an arbitrary external command via stdin, like :w !my_external_command
The help does not mention this being a Vim-specific command, so it may also be available in vi. If you're actually using Vim after all and not just vi, then see :help :w_c for details.


text:
Q: Best practice for separating configure and algorithm code I'm writing some code to do scientific computing in c++, and I need to do some calculation on a custom structure foo. To make the whole thing more easy to maintain in the future, I want to separate the code that sets up structure such as foo.bar=1; etc in a separate file. How to achieve that? The structure uses the armadillo library to support matrix/linear algebra. I already wrote the header file f.hpp like:
#include <armadillo>
#include <complex>
using namespace arma;

#ifndef __fn__
#define __fn__

struct foo
{
    cx_mat a;
    mat b;
    cx_cube c;
    complex<double> d;
    string desc;
};

#endif

A: Adding it to a source-code file will require you to compile it every-time you wish to change the values. And this is a bad practice, especially if your compilation time is 'long'.
The recommended way is to have config file say 'foo.ini'. You could have a flexible config file, if you use a third-party/open-source library such as https://code.google.com/p/inih/ or http://www.hyperrealm.com/libconfig/.
But, if you want to keep is simple, try this convention:
Config file with alternate line of key-value pairs, with a fixed expected order. For example:
# foo.bar
42
# foo.pub
You're awesome
# foo.club
24/06/2015
# tab.a
64

Note that the order of the values are important and that will make it easy for us to parse using simple C++ code. Just open the file and call getLine() repeatedly, ignore every other line and parse the second line to store it into the structure.
If you want to store a complicated structure such-as a matrix, you can device a simple strategy to store such structures, as the parsing function is also written by us:
# Foo matrix rows
100
# Foo matrix cols
50
# Foo matrix elements, row-by-row:
0.5 3 5 23 ... ... 100
4 5 5 34 1 ... ... 100
.
.
3 33 33 2 ...  ... 100

# Diagonal Matrix rows-cols
20
# Diagonal Values, row-by-row others 0
45
22
92
.
.
20

Also note that libconfig (http://www.hyperrealm.com/libconfig/) allows you to store and represent such complex data-structures, using array and Json like text. You can use that if you would like a full-fledged 'config-language' to start with.
And you save a lot of compilation time. Just update the config file and re-run the program. That way, other programs could feed-in the config-values.

A: Another possibility, quite common in scentific HPC, it to embed some scripting language in your application.
You could embed a Lua or Guile (or Ocaml) interpreter in your application, and have it interpret some initialization script before running your complex computation. That user provided script could do some simple interpreted computation to initialize your data. You just need to provide some scripting primitives to manipulate (& create) your data that the user would combine with his scripts.
You could also make your application an extension (or plugin) of some existing framework like Scilab, Octave, R, Python, NekoVM
BTW, your program could also read some simple data (perhaps using textual serialization formats like Json) and your users would themselves write some other script or program to feed yours (e.g. using Unix pipelines).
Another way might be to initialize your thing in C++, which might be generated (perhaps even by your program from some higher-level input), and compile that C++ code at runtime and then dynamically load it as a plugin using dlopen(3) (I am doing such things in MELT...).
Be aware that embedding or integrating some interpreter is a major software architectural design choice, and you should make that choice early.


text:
Q: Understanding react-native init template and files: What are all these files? Today I started to play around with a fresh React Native project. I ran the basic react-native init command and got the sample project littered with all these weird files. Are all of these necessary and what are they?

.buckconfig
This seems to be related to a RN build tool called "Buck" made by Facebook. Is this used by default in the freshly initialise project? How can I check what builder is being used?

.flowconfig
Never heard of this before. Short googling gave me the understanding that this is some sort of type checker for JS. I am using TypeScript, so I think there's no need for this config file to be present?

.watchmanconfig
Empty watchmanconfig in the project root? Why? What's the point in having this there?
Edit: Apparently it is safe to delete from the project as long as it is not too large
Do I need to keep .watchmanconfig file in react-native project?

babel.config.json
Then probably the most confusing of them all for me was surprisingly Babel config. Babel has been present in many projects I have been working on. Always they have been some already initialised projects and I have never needed to pay much attention to the configuration details - hence this post. If using TypeScript and tsc, what do we need Babel for? Isn't tsc already transpiling the TypeScript code?

For a test I deleted all of the above files from my test project and it still seems to build and work just fine. I am now thinking that could this lead to some problems later in the development?
I like to keep my projects as clean as possible from all trash, so they are nicer to develop and easier to understand as there are less random stuff floating around.

A: .watchmanconfig - Used by Watchman, a file-watching service that can be used by React Native's development server to detect changes to your code and automatically reload your app. The .watchmanconfig file is used to configure how Watchman should watch your files and directories.
babel.config.js -Used by Babel, a JavaScript compiler that converts modern JavaScript code into an older version of JavaScript that can run on more devices. In a React Native project, Babel is used to transform your code so that it can be run on iOS and Android devices. The babel.config.js file is used to configure Babel's plugins and presets, which control how your code is transformed.
metro.config.js - Used by Metro, which is the JavaScript bundler used by React Native to package your code for distribution. The metro.config.js file is used to configure Metro's behavior, such as which files to include or exclude from the bundle, how to handle different types of assets, and so on.
tsconfig.js - Used by TypeScript is a file that used to configure the TypeScript compiler's behavior, such as which files to include or exclude from the build, how to handle different types of modules, and so on.
.eslintrc.js - Used by ESLint, a JavaScript linter that can be used to find and fix common errors and coding style issues in your code. The .eslintrc.js file is used to configure ESLint's rules, which control what issues it reports and how it reports them.


text:
Q: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO I've looked through all the other StackOverflow (and google) posts with the same problem, but none seemed to address my problem.
I am using PDO and PHP.
My code:
$vals = array(
   ':from'    => $email,
   ':to'      => $recipient,
   ':name'    => $name,
   ':subject' => $subject,
   ':message' = >$message
);
print_r($vals);
try {
   $pdo = new PDOConfig();
   $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $sql = "SELECT * FROM messages WHERE `message` LIKE :message";
   $q = $pdo->prepare($sql);
   $q->execute(array(':message' => $vals[':message']));
   $resp = $q->fetchAll();

   foreach ($resp as $row) {
      throw new Exception('Please do not post the same message twice!');
   }

   $sql = "INSERT INTO messages (from, to, name, subject, message) VALUES (:from, :to, :name, :subject, :message)";
   $q = $pdo->prepare($sql);
   $q->execute($vals);
}
catch(PDOException $e) {
   echo $e->getMessage();
}

and the first print_r gives
Array ( [:from]    => abc@gmail.com
        [:to]      => lala@me.com
        [:name]    => abc
        [:subject] => abc
        [:message] => abc )

which is expected (none are null)
but it outputs the error

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from, to, name, subject, message) VALUES ('abc@gmail.com', 'lala@me.com' at line 1

No idea how to fix this. any ideas?

A: I've got this exact error, but in my case I was binding values for the LIMIT clause without specifying the type. I'm just dropping this here in case somebody gets this error for the same reason. Without specifying the type LIMIT :limit OFFSET :offset; resulted in LIMIT '10' OFFSET '1'; instead of LIMIT 10 OFFSET 1;. What helps to correct that is the following:
$stmt->bindParam(':limit', intval($limit, 10), \PDO::PARAM_INT);
$stmt->bindParam(':offset', intval($offset, 10), \PDO::PARAM_INT);

A: ALTER TABLE `{$installer->getTable('sales/quote_payment')}`
ADD `custom_field_one` VARCHAR( 255 ) NOT NULL,
    ADD `custom_field_two` VARCHAR( 255 ) NOT NULL;

Add backtick i.e. " ` " properly. Write your getTable name and column name between backtick.

A: from is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`.
Personally, I wouldn't bother; I'd just rename the column.
PS. as pointed out in the comments, to is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.

A: Same pdo error in sql query while trying to insert into database value from multidimential array:
$sql = "UPDATE test SET field=arr[$s][a] WHERE id = $id";
$sth = $db->prepare($sql);
$sth->execute();

Extracting array arr[$s][a] from sql query, using instead variable containing it fixes the problem.


text:
Q: How to create a private message system with Laravel I am implementing simple private messaging application without any package.
Message table have following columns
id, from_id, to_id, message, created_at
I want user to show messages like below example-
User1: Hi
User2: Hello
User1: How are you?
User1: Whats going on?
User2: Fine.

A: It's many to many relationship. You should create pivot table with two keys pointed to id in users table:
Schema::create('messages_pivot', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('from_id')->unsigned();
    $table->integer('to_id')->unsigned();
    $table->string('message');
    $table->timestamps();
});

Schema::table('messages_pivot', function (Blueprint $table) {
    $table->foreign('from_id')->references('id')->on('users')->onDelete('cascade');
    $table->foreign('to_id')->references('id')->on('users')->onDelete('cascade');
});

You can use relations to work with this pivot table or you could create a model for it.

A: Create Both tables Conversations and Messages use conversation_id between users if exists then add message and store who sent the message using user_id in messages table.
class CreateMessagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('messages', function (Blueprint $table) {
            $table->increments('id');
            $table->text('message');
            $table->boolean('is_seen')->default(0);
            $table->boolean('deleted_from_sender')->default(0);
            $table->boolean('deleted_from_receiver')->default(0);
            $table->integer('user_id');
            $table->integer('conversation_id');
            $table->timestamps();
        });
    }

class CreateConversationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('conversations', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_one');
            $table->integer('user_two');
            $table->boolean('status')->default(1);
            $table->timestamps();
        });
    }


text:
Q: Are the Javascript and Java Image objects compatible? Sorry if this is a newbie question but if I create and image object in Javascript and send it to a Java applet with an Image argument, will the types still match? A quick example would be
 var image = new image();
 image.src = "pic.gif";
 app.example(image);

for the Javascript, and
public void example(Image n){
}

for the Java code. If they aren't compatible, would the File object be?


text:
Q: how do you pick certain lines from a log file with R there is a log file like this and it has many entries in them:
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3

Report Job information
Job ID : 12345
Job name : Background Execution
Job priority : 5
Job group : normal
Report group : General
Job description : Brief
User : user01
Report : General101
Modified user : 12
Modified date : 2016-09-16 15:18:52.08
Report mode : Simple

2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3

Report Job information
Job ID : 12367
Job name : Background Execution
Job priority : 5
Job group : normal
Report group : General1
Job description : Brief
User : user01
Report : General101
Modified user : 12
Modified date : 2016-09-16 15:45:52.08
Report mode : Simple

I need to be able to extract this part from the log and put in a data frame format. The log will have many entries like this, every time the script see this set up entries in the log, it should append to the data frame.
    Report Job information
    Job ID : 12367
    Job name : Background Execution
    Job priority : 5
    Job group : normal
    Report group : General1
    Job description : Brief
    User : user01
    Report : General101
    Modified user : 12
    Modified date : 2016-09-16 15:45:52.08
    Report mode : Simple

I've tried this:
  i<-c("app.log")
    xx <- readLines(i)
    ii <- 10 + grep("Report Job information",xx, fixed=TRUE)[1]
    line_count <- Filter(function(v) v!="", strsplit(xx[ii]," ")[[2]])

Any ideas how could do this?
Given this data:
Job ID : 12345
Job name : Background Execution
Job priority : 5
Job group : normal
Report group : General
Job description : Brief
User : user01
Report : General101
Modified user : 12
Modified date : 2016-09-16 15:18:52.08
Report mode : Simple

Each set of entry need to be one row. For example:
title=Report Job information,jobid=12345, JobName=Background Execution, job priority=5,jobgroup=normal, reportgroup=General,ModifiedDate=2016-09-16 15:18:52.08 etc

A: Here are the data, read in (note, using dplyr/magrittr pipe):
inData <-
"2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3

Report Job information
Job ID : 12345
Job name : Background Execution
Job priority : 5
Job group : normal
Report group : General
Job description : Brief
User : user01
Report : General101
Modified user : 12
Modified date : 2016-09-16 15:18:52.08
Report mode : Simple

2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3
2016-09-16 15:18:52,555 DEBUG Thread-3

Report Job information
Job ID : 12367
Job name : Background Execution
Job priority : 5
Job group : normal
Report group : General1
Job description : Brief
User : user01
Report : General101
Modified user : 12
Modified date : 2016-09-16 15:45:52.08
Report mode : Simple" %>%
  strsplit("\\n") %>%
  unlist

I think that the easiest is to first find all of the starting positions. Here, I assume that "Report Job Information" is at the top of each report (but that it does not need to be included in the data.frame, so I start one after it).
reportStarts <-
  grep("Report Job information", inData) + 1

Next, I find where the reports end. Not knowing more about the structure, I am assuming that "Report mode" is the last thing reported. If, instead, it is a set number of lines, or some other break indicator, you may need to modify this step.
reportStops <-
  grep("Report mode", inData)

Next, I loop through each of the reports (using idx to indicate which report I am working on). the approach first limits to the lines in this report, then splits each by " : " which appears to be the field indicator, and uses the part before the " : " to name the output (I use paste as a defense in case the value also includes a " : "). Finally, I stitch each into a data.frame, then bind the rows with bind_rows to ensure that it appropriately handles any extra columns that may be present in some reports.
lapply(1:length(reportStarts), function(idx){

  inData[reportStarts[idx]:reportStops[idx]] %>%
    strsplit(" : ") %>%
    sapply(function(thisField){
      setNames(paste(thisField[-1]
                     , collapse = " : ")
               , thisField[1])
    }) %>%
    rbind %>%
    data.frame()

}) %>%
  bind_rows()

Outputs this data.frame:
  Job.ID             Job.name Job.priority Job.group Report.group Job.description   User     Report Modified.user          Modified.date Report.mode
1  12345 Background Execution            5    normal      General           Brief user01 General101            12 2016-09-16 15:18:52.08      Simple
2  12367 Background Execution            5    normal     General1           Brief user01 General101            12 2016-09-16 15:45:52.08      Simple

A: You can try:
library(stringr)

foo <- function(x, y){
  tmp <- y[c(x:(x+11))] # extract
  tmp <- str_split(tmp, ": ") # split and optimize
  unlist(lapply(tmp, tail, 1)) # unlist and output last element
  }

data.frame(t(cbind(sapply(i, foo, xx))))
                      X1    X2                   X3 X4     X5       X6    X7     X8         X9 X10
1 Report Job information 12345 Background Execution  5 normal  General Brief user01 General101  12
2 Report Job information 12367 Background Execution  5 normal General1 Brief user01 General101  12
                     X11    X12
1 2016-09-16 15:18:52.08 Simple
2 2016-09-16 15:45:52.08 Simple


text:
Q: forensically deleting/updating data I have a need to forensically remove data from oracle. If I just delete it, my understanding is the data will still actually be in the data file until that space is reused. I'm not concerned about the redo/archive/undo space, those will age out reasonable quickly.
Is there any methods for ensuring data is actually removed from a data file?

A: This is an interesting question: When does Oracle really delete data physically ?
The unit of data in Oracle is a block. Let's see what happens when we delete a row.
Here's an example with a simple table on 11gR2 (see "How to dump Oracle Data Block?"):
CREATE TABLE test_delete_data(id NUMBER,data VARCHAR2(100));
INSERT INTO test_delete_data VALUES (1, rpad('1', 100, '1'));
INSERT INTO test_delete_data VALUES (2, rpad('2', 100, '2'));
INSERT INTO test_delete_data VALUES (3, rpad('3', 100, '3'));
COMMIT;

SELECT dbms_rowid.rowid_to_absolute_fno(rowid, user, 'TEST_DELETE_DATA') fileno,
       dbms_rowid.rowid_block_number(rowid) blockno
  FROM test_delete_data;

-- replace with values from query
alter system dump datafile 4 block 16573;

You should get something like this at the end of the file created in your user_dump_dest directory:
data_block_dump,data header at 0x8b02264
===============
[...]
block_row_dump:
tab 0, row 0, @0x1f2d
tl: 107 fb: --H-FL-- lb: 0x1  cc: 2
col  0: [ 2]  c1 02
col  1: [100]
 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31
 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31
 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31
 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31
tab 0, row 1, @0x1ec2
tl: 107 fb: --H-FL-- lb: 0x1  cc: 2
col  0: [ 2]  c1 03
col  1: [100]
 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
tab 0, row 2, @0x1e57
tl: 107 fb: --H-FL-- lb: 0x1  cc: 2
col  0: [ 2]  c1 04
col  1: [100]
 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
end_of_block_dump

If I delete the second row, commit and dump the same block, I will get something like this:
block_row_dump:
tab 0, row 0, @0x1f2d
tl: 107 fb: --H-FL-- lb: 0x0  cc: 2
col  0: [ 2]  c1 02
col  1: [100]
 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31
 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31
 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31
 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31
tab 0, row 1, @0x1ec2
tl: 2 fb: --HDFL-- lb: 0x2
tab 0, row 2, @0x1e57
tl: 107 fb: --H-FL-- lb: 0x0  cc: 2
col  0: [ 2]  c1 04
col  1: [100]
 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
end_of_block_dump

The record is still there (with a D flag set). If we look at the actual binary data (just before the block header dump section, we see that the data has not yet been overwritten:
8B040C0 33336404 33333333 33333333 33333333  [.d33333333333333]
8B040D0 33333333 33333333 33333333 33333333  [3333333333333333]
        Repeat 4 times
8B04120 33333333 023C3333 03C10202 32323264  [333333<.....d222]
8B04130 32323232 32323232 32323232 32323232  [2222222222222222]
        Repeat 5 times
8B04190 02002C32 6402C102 31313131 31313131  [2,.....d11111111]
8B041A0 31313131 31313131 31313131 31313131  [1111111111111111]
        Repeat 4 times
8B041F0 31313131 31313131 31313131 30A30602  [111111111111...0]

One way to force data to actually be overwritten would be to update it to a meaningless value before deleting the row. This wouldn't work with indexes since updates are translated to delete+insert in a b*tree index.

A: I don't think data persists after a delete but you're correct that the space will be kept in use by that table until it has been refilled. The top space usage in a table is known as the high water mark. Tom Kyte has a really good (unsurprisingly) post about it.
You reduce the high water mark by rebuilding the table:
alter table my_table_name move

or by truncating it; though in an active table this is obviously not an option.


text:
Q: writing and formatting datetime.date objects using xlwt I'm having some trouble with this bit of code
#data_list = some data
wb = xlwt.Workbook()
s = wb.add_sheet("Test Sheet")
for c, data in enumerate(data_list):
        xf=None
        if isinstance(data, datetime.time):
                xf = xlwt.easyxf(num_format_str='HH:MM:SS') #works
        elif isinstance(data, datetime.date):
                xf = xlwt.easyxf(num_format_str='MM/DD/YYYY') #doesn't work
        if xf:
                sheet.write(r+1,c,data, xf)
        else:
                sheet.write(r+1,c,data)

In the output, the dates all appear as "#####" initially. I can get excel to format them properly by interacting with a cell in each column, but it's time consuming. I'm tried playing with the num_format_str a little, but no luck so far.

A: Just thinking about this some more, if your problem is that the columns are too narrow, you can fix it by setting the column width explicitly in your script.
for c, data in enumerate(data_list):
    xf=None
    sheet.col(c).width = len(str(data))*256
    if isinstance(data, datetime.time):

The width in xlwt is set in units of 1/256 the width of the 0 character in the default font.


text:
Q: MouseDragged works OR mouseMoved works, but not both I am currently working on an assignment.  I have to display a set of coordinates in relation to the mouse on the frame.  I am not allowed to use Swing components.  When the mouse is used without clicking, the text should be red.  Once the mouse is clicked and dragged, the text should be black.  In both cases, the text should follow the mouse.  I can get the text to change color, I can get it to display the appropriate information.  When I try to setlocation of the label in both the MouseMoved, and the MousedDragged,it won't recognize when I drag.  If I take out one or the other setlocations for the label, the other works just fine. What am I doing wrong?  I'm working on a runner class, I'll include it.  The main class just instantiates an object of my runner class.
import java.awt.Button;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.*;
import java.awt.Rectangle ;
import java.awt.Label;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

class Proj06Runner extends Frame
{

  //Proj06Runner Constructor
  public Proj06Runner() {

System.out.println("Proj06");
System.out.println("I certify that this program is my own work and is not the work of others. ");
System.out.println("I agree not to share my solution with others.");
System.out.println("Eric Jackson.");

GUI gui = new GUI();//instantiate a GUI
  }}
//End Proj06Runner Class
//________________________________________________________________________

class GUI extends Frame {

  public GUI()//constructor
  {

Rectangle bounds = this.getBounds();

   //Create Frame
    Frame displayWindow = new Frame("Eric Jackson");
//Set size of Frame
displayWindow.setSize(300,200);
displayWindow.setLayout(null);
displayWindow.setLocation(30 + bounds.x, 30 + bounds.y);

//Create Top button
Button TopButton = new Button("This Button does nothing");
TopButton.setBounds(7+bounds.x,30+bounds.y,285,25);
displayWindow.add(TopButton);

//Create Left button
Button LeftButton = new Button("Button");
LeftButton.setBounds(7+bounds.x,54+bounds.y,50,122);
displayWindow.add(LeftButton);

//Create Textfield
TextField myTextField=new TextField("This TextField does nothing");
myTextField.setBounds(7+bounds.x,175+bounds.y,285,22);
displayWindow.add(myTextField);

//Create Label to display coord text
Label myLabel=new Label();
myLabel.setBounds(50,50,100,20);
myLabel.setForeground(Color.red);
myLabel.setText(" ");
displayWindow.add(myLabel);

displayWindow.addWindowListener( new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
  System.exit(0);
}
} );

displayWindow.addMouseMotionListener(new MyMouseMotionProcessor(myLabel));
displayWindow.addMouseListener(new MyMouseProcessor(myLabel));

displayWindow.setVisible(true);
  }
    }
//End GUI Definition
    //=========================================================

//=========================================================
//This class recognizes mousePressed(). This method is
// used to determine the starting position of the mouse
// pointer.
class MyMouseProcessor extends MouseAdapter{

Label theLabel;
int MouseX, MouseY;
//Constructor
MyMouseProcessor( Label inLabel){
 //save references to the input objects
 theLabel = inLabel;
 }//end constructor

public void mousePressed(MouseEvent e){
}//end mousePressed()
 }//end MyMouseProcessor
     //=======================================================

 class MyMouseMotionProcessor extends MouseMotionAdapter{

Label theLabel;
int MouseX, MouseY;

//Constructor
MyMouseMotionProcessor(Label inLabel){
 //save incoming object reference
 theLabel = inLabel;
}// end constructor

public void mouseDragged(MouseEvent e){
System.out.println("Drag = " + e);
  MouseX= e.getX()-2;
  if (MouseX<0)
  {
   MouseX=0;
  }
  MouseY= e.getY()-15;
  if (MouseY <0)
  {
    MouseY=0;
  }
 //move label to the new location

 theLabel.setLocation(MouseX,MouseY);

theLabel.setForeground(Color.black);
String coordtextClick = MouseX+" , " + MouseY;
 theLabel.setText(coordtextClick);

}//end mouseDragged()

public void mouseMoved(MouseEvent e){
  System.out.println("Move = " + e);
  theLabel.setForeground(Color.red);
  MouseX= e.getX()-2;
  if (MouseX<0)
  {
   MouseX=0;
  }
  MouseY= e.getY()-4;
  if (MouseY <0)
  {
    MouseY=0;
  }
  String coordtext = MouseX+" , " + MouseY;
 theLabel.setLocation(MouseX,MouseY);
 theLabel.setText(coordtext);

}//

}//end class MyMouseMotionProcessor

A: There is not a problem with using mouseDragged and mouseMoved together. They are working just fine. The problem is with the location you are setting to the theLabel.
Problem:
The problem is that when you are setting the location of theLabel in the mouseMoved method, theLabel is being located just under the mouse pointer. So you cannot create a healthy mouseDrag gesture which should happen on your displayWindow component. In other word your mouseDrag is being applied to the theLabel itself rather than displayWindow, since theLabel is located under the mouse pointer on top of the displayWindow.
How did I find out? I just used an old trick! I've just set a background color to theLabel:
myLabel.setBackground(Color.lightGray);

This helped me see where the myLabel is being located so the problem solved!
Solution:
The solution is to set a location for theLabel which is not located just under the mouse pointer. This will help with starting a healthy mouseDrag from the mouse location. Something like this:
public void mouseDragged(MouseEvent e) {
    System.out.println("Drag = " + e);
    MouseX = e.getX() + 5; // <- note here
    if (MouseX < 0) {
        MouseX = 0;
    }
    MouseY = e.getY() - 15; // <- note here
    if (MouseY < 0) {
        MouseY = 0;
    }
    // move label to the new location

    theLabel.setLocation(MouseX, MouseY);

    theLabel.setForeground(Color.black);
    String coordtextClick = MouseX + " , " + MouseY;
    theLabel.setText(coordtextClick);
}// end mouseDragged()

public void mouseMoved(MouseEvent e) {
    System.out.println("Move = " + e);
    theLabel.setForeground(Color.red);
    MouseX = e.getX() + 5; // <- note here
    if (MouseX < 0) {
        MouseX = 0;
    }
    MouseY = e.getY() - 15; // <- note here
    if (MouseY < 0) {
        MouseY = 0;
    }
    String coordtext = MouseX + " , " + MouseY;
    theLabel.setLocation(MouseX, MouseY);
    theLabel.setText(coordtext);
}//

Hope this helps!


text:
Q: lualatex not available in Debian Wheezy I want to use lualatexfor compiling Latex document based on Luatex. I have installed those packages: luatex, texlive-binaries, texlive-luatex …but no lualatexbinary can be found. What did I miss?

A: I raised this also  the same on Unix StackExchange, the missing key is installation of texlive-latex-base package.
All in all, I had to install packages in total worth several hundreds of MByte just for successfully compiling a test Latex document with LuaLatex, unfortunately LuaLatex does not leave a smaller footprint on one's system.


text:
Q: Bulk flow interviews not interacting with one another My goal is to run a flow in bulk and not create duplicates. First thing that happens is I lookup colCustomObject. The first interview loops through colCustomObject, determines that a new record needs to be created. Define the sobject variable and add it to colCustomObject and colCustomObjectForCreation. I expect the second interview (which would otherwise create a duplicate) to see the new value in colCustomObject, but it never does. Can collections be modified and the modifications visible in different interviews in the same transaction?
The weirdest part is I have something very similar working perfectly in a different org, but cannot seem to duplicate it here.

A: The Flows that you have running in parallel will not see changes made by one another to their flow variables, including collection variables. Those values are private to the Flow interview. I'm not seeing a way that your parallel flows could be running inside the same transaction context, either.
The new records you're creating are only visible once they've been persisted to the database through a Record Create or other DML element. At that point, other processes of all types will be able to query them.
Note that this is true of both Apex and Flow. No transaction can see what's going on in any other transaction. If you're creating a lot of duplicates in parallel imports, you'll need to either fix your input process to dedupe up front, or clean up on the back end.
However, each running import process (again, either Apex or Flow) can see everything that's already been committed as a result of other transactions. The issue that you're observing should only be the case when duplicate records are being processed in parallel transactions simultaneously. Otherwise, a properly bulkified query for duplicate records should locate them.


text:
Q: Implementing virtual concepts in rails my question is more of a general nature.
I know about scopes in rails but i am running into a concept that i am not able to wrap my my head around
I have a few tables in the db - like customers, products, sales etc. And i have various sales persons who are logging in to view their sales, etc. I want to implement a concept of "My" so when a sales person comes in they are only able to see their sales, their customers, the products they sold etc. So something like my.customers or my.sales or my.territories etc.
How can i implement this? how can i prefix "my" onto customers, sales etc to achieve this elegantly ?
Guidance is appreciated.
Thanks,

A: You should take a look at:
http://guides.rubyonrails.org/active_record_querying.html
This is what you use to associate and manage what the user sees, and how you access it in your controllers/views. For example:
class Client < ActiveRecord::Base
  has_many :sales
end

class Sale < ActiveRecord::Base
  belongs_to :client
end

This would make it so that a client has many sales, and you can access it using Client.first.sales... for example.
To make it my instead of User.first, you can use:
private

def my
  User.first
end


text:
Q: Why do major compilers use typedef for stdint.h but use #define for stdbool.h? I just noticed that gcc and clang both appear to use typedefs for stdint.h but #define for stdbool.h.
example: clang's stdint.h
 #ifdef __INT8_TYPE__
 #ifndef __int8_t_defined  /* glibc sys/types.h also defines int8_t*/
 typedef __INT8_TYPE__ int8_t;
 #endif /* __int8_t_defined */
 typedef __UINT8_TYPE__ uint8_t;
 # define __int_least8_t int8_t
 # define __uint_least8_t uint8_t
 #endif /* __INT8_TYPE__ */

clang's stdbool.h
#ifndef __cplusplus
#define bool _Bool
#define true 1
#define false 0
#elif defined(__GNUC__) && !defined(__STRICT_ANSI__)
/* Define _Bool, bool, false, true as a GNU extension. */
#define _Bool bool
#define bool  bool
#define false false
#define true  true
#endif

Why isn't it typedef _Bool bool; ?
(gcc stdint.h and stdbool.h)

A: stdbool.h defines bool as a macro because the C standard (section 7.18) says bool shall be defined as a macro, and stdint.h defines intN_t etc as typedefs because the C standard (section 7.20) says intN_t etc shall be defined as typedefs.
Okay, why does the C standard say these things?  I cannot tell you for sure, but a clue is in section 7.18 paragraph 4:

Notwithstanding the provisions of 7.1.3, a program may undefine and perhaps then redefine the macros bool, true, and false.

If bool were a typedef and true and false were, I don't know, enum constants, they couldn't have allowed you to do that, as there is no way to undo those kinds of declarations.
Okay, why does the C committee want to allow you to do that?  This is even more speculative, but probably for the same reason they added stdbool.h and _Bool instead of making bool, true, and false keywords as they are in C++: they wanted to preserve compatibility with old programs that defined bool, true, and false themselves, even if those programs use third-party headers that include stdbool.h...
No such backward compatibility concerns apply to the types defined by stdint.h; some systems provided (some) of them as extensions, but they were always typedefs.

A: I think this is just part of the standard.
If you go to page 253, under "7.16 Boolean type and values ", it clearly says:

1) The header <stdbool.h> defines four macros.
2) The macro
bool
expands to _Bool.


text:
Q: How do I override WPF DataGrid behaviour to implement Drag and Drop to an external application? I have a WPF DataGrid with the following definition.
<DataGrid Name="DataGridFoo"
  AutoGenerateColumns="False"
  ItemsSource="{Binding GridData}"
  IsReadOnly="True"
  SelectionMode="Extended"
  SelectionUnit="CellOrRowHeader">

This allows me to have the user selected a "region" of cells. The DataGrid is bound to an observable collection. The XAML column definitions have some columns hidden, some visible like this:
<DataGridTextColumn Binding="{Binding InvoiceID}"
   Header="Invoice ID"
   Visibility="Hidden"
   Width="Auto"/>
<DataGridTextColumn Binding="{Binding InvoiceNumber}"
   Header="Invoice Number"
   Visibility="Visible"
   Width="Auto"/>
<DataGridTextColumn
   Binding="{Binding InvoiceDate, StringFormat=\{0:MM/dd/yy\}}"
   Header="Invoice Date"
   Visibility="Visible"
   Width="Auto"/>

I also have a Right Mouse Button context menu defined for the DataGrid:
<DataGrid.ContextMenu>
  <ContextMenu FontSize="16"  Background="#FFE6E9EC">
    <MenuItem Header="Contact" Click="Contact_Click" />
    <Separator  />
    <MenuItem Header="Copy" Command="Copy" />
  </ContextMenu>
</DataGrid.ContextMenu>

I would like to be able to Click, Drag and Drop a copy of the currently selected cells into an external application. I was thinking of using the combination of pressing the "Alt Key" and Left Mouse Button click to initiate the DragDrop operation.
For example, consider the "irregular" selection of cells in the DataGrid:

I am unclear on how to proceed and have several questions regarding this:
1) What events do I override so that the /Left Mouse click do not affect the currently selected cells?
2) How do I determine whether the Left Mouse Button click is occurring within a region of selected cells? How do I handle the data piece?
3) Once I've determined the above, what is the next step? Do copy data into the clipboard for use on the external drop?
4) What events (if any) do I need to override on the DataGrid in order for this to work?
Thanks

A: the basic events to drag and drop are:
events to drag and drop
Specially the DragLeave and Drop to do what you want. Then you need to control (delete/add) the GridData property from your VM to search and move the values.
I strongly recommend 3rd party like Telerik to do it.

A: Here is your complete answer I believe.
    private void dataGridMaster_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        if(Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift) & e.ChangedButton == MouseButton.Left)
        {
            DataGrid grid = e.Source as DataGrid;
            DataGridCell cell = GetParent<DataGridCell>(e.OriginalSource as DependencyObject);
            if(grid != null && cell != null && cell.IsSelected)
            {
                e.Handled = true;
                StartDragAndDrop(grid);
            }
        }
    }

    private T GetParent<T>(DependencyObject d) where T:class
    {
        while (d != null && !(d is T))
        {
            d = VisualTreeHelper.GetParent(d);
        }
        return d as T;

    }

    private void StartDragAndDrop(DataGrid grid)
    {
        StringBuilder sb = new StringBuilder();
        DataRow row = null;
        foreach(DataGridCellInfo ci in grid.SelectedCells)
        {
            DataRowView drv = ci.Item as DataRowView;
            string column = ci.Column.Header as string;
            if(drv != null && column != null)
            {
                if(drv.Row != row && row != null)
                {
                    sb.Length--;
                    sb.AppendLine();
                    row = drv.Row;
                }
                else if(row == null)
                {
                    row = drv.Row;
                }
                sb.Append(drv[column].ToString() + "\t");
            }
        }
        if (sb.Length > 0)
        {
            sb.Length--;
            sb.AppendLine();
        }
        DragDrop.DoDragDrop(grid, sb.ToString(), DragDropEffects.Copy);
    }

Here you need to have the shift key down to signal the drag.  This is needed to disambiguate the click and drag that is used in the DataGrid to select cells.  You might use some other mechanism such as context menu item.
The clipboard is key to any drag and drop operation.  What you are doing is putting data on the clipboard in various formats that the target of the drop will recognize.  In this example only plain text is used.  But you might want to create rich text or HTML or any number of other formats.
The external application you are dropping on must be registered as a drop target.  You cannot force the other app to respond to the drop...it must be listening for it.  So this example will work with Word and Excel.  It will not work with Notepad.
I believe all 4 items are satisfied:

*

*Override the preview mouse down event.

*The original source of the mouse event comes from the data grid cell.  If the cell is selected then you are within the block of cells that is selected.

*For the selected cells, gather the data from the bindings and organize into a grid.  As a baseline use plain text but optionally add other formats as well.  Use the DragDrop class to actually implement the drag and drop.

*Override preview mouse down.


text:
Q: Getting an exception when recording audio in J2me I am getting a exception when I am recording a audio in Nokia C1. Below is the following exception I am getting:
Error2:
javax.microediting.media.MediaException: MUS

Can anyone help me in removing this exception or where am I going wrong?
Below, I am providing my code in which I am getting this exception:
package video;

import javax.microedition.midlet.*;

import java.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;

public class VoiceRecordMidlet extends MIDlet {

    private Display display;

    public void startApp() {
        display = Display.getDisplay(this);
        display.setCurrent(new VoiceRecordForm());
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }
}

class VoiceRecordForm extends Form implements CommandListener {

    private StringItem message;
    private StringItem errormessage;
    private final Command record, play, end;
    private Player player;
    private byte[] recordedAudioArray = null;
    private RecordControl rc;
    private ByteArrayOutputStream output;

    public VoiceRecordForm() {
        super("Recording Audio");
        message = new StringItem("", "Select Record to start recording.");
        this.append(message);
        errormessage = new StringItem("", "");
        this.append(errormessage);
        record = new Command("Record", Command.SCREEN, 0);
        this.addCommand(record);
        play = new Command("Play", Command.SCREEN, 0);
        end = new Command("End", Command.SCREEN, 0);
        this.setCommandListener(this);
    }

    public void commandAction(Command comm, Displayable disp) {
        if (comm == record) {
            Thread t = new Thread() {

                public void run() {
                    try {

                        player = Manager.createPlayer("capture://audio");

                        player.realize();
                        rc = (RecordControl) player.getControl("RecordControl");
                        output = new ByteArrayOutputStream();
                        rc.setRecordStream(output);
                        rc.startRecord();
                        player.start();
                        removeCommand(record);
                        addCommand(end);

                    } catch (Exception e) {
                        errormessage.setLabel("Error1");
                        errormessage.setText(e.toString());
                    }
                }
            };

            t.start();

        } else if (comm == play) {
            try {

                ByteArrayInputStream recordedInputStream = new ByteArrayInputStream(recordedAudioArray);

                Player p2 = Manager.createPlayer(recordedInputStream, "audio/basic");

                **p2.prefetch();

                p2.start();**

            } catch (Exception e) {
                errormessage.setLabel("Error2");
                errormessage.setText(e.toString());
            }
        } else if (comm == end) {
            try {
                rc.stopRecord();
                removeCommand(end);
                addCommand(play);
                                rc.commit();
                recordedAudioArray = output.toByteArray();

                player.close();

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

A: The only difference I can spot when comparing the recording part of your code with the recording part of one of my projects, is that I call player.start() before I call recordControl.startRecord()
player = Manager.createPlayer("capture://audio");
player.realize();
player.start();
recordControl = (RecordControl) player.getControl("RecordControl");
bos = new ByteArrayOutputStream();
recordControl.setRecordStream(bos);
recordControl.startRecord();

That works for me on Sony Ericsson phones.
I don't playback the audio though, so I don't know if that part of your code is causing the problem.


text:
Q: Google Data Studio custom fields in schema object I'm trying to keep up to date with changes in Data Studio Connectors development. A few months ago, they've announced the Data Studio Apps Script Service, and recommended to use the new DataStudioApp class in order to create config and schema objects.
Actually, I'm obtaining not only "data" from my servers, but also config and schema objects, because we use the same connector to access different databases according to the user identification.
So, my approach is to keep obtaining the json objects from my servers and then parse them to create config and schema objects via DataStudioApp.createCommunityConnector().
My problem is that I've put a "custom field" in schema metric object and have no method to declare it in DataStudioApp class.
this is one of my schema metric object:
[...]
  {
    "name" : "cantid",
    "label" : "Cantidad",
    "dataType" : "NUMBER",
    "isDefault " : true,
    "semantics" : {
      "conceptType" : "METRIC",
      "semanticGroup" : "NUMERIC",
      "isReaggregatable" : true
    },
    "sqlname" :  "sum(cantid) as cantid"
  },
[...]

sqlname is my custom field.
Is there a way to declare this?.

A: Not sure if you solved this already, but ran into the almost same situation. The solution for me was to write a function that will look at my schema later using the field name as the reference point for the lookup in my JSON schema. This allowed me to use custom fields as needed, but not have to rely on google data studio supporting them.
Know its quite awhile later, but hope it helps you or someone else!


text:
Q: linux mount shared over samba I'm new to the world of linux andI have mounted a hard drive on my linux system as such:
mount /dev/sdb1 /opt/backup

I have my samba share pointing to the folder /opt/backup.
When /dev/sdb1 is not mounted I can access the folder called backup but when I try accessing the same folder when the drive (sdb1) is mounted I get an error that I don't have permissions to use this network resources.
I'm using MS Windows 7 to access the Samba share.

A: I resolve the issue by adding the mount to fstab and setting the permissions of the folder as followed:
chmod -R 777 /opt/backup
chown nobody:nobody /opt/backup


text:
Q: how does the skipper-client help app get their streamDeploymentProperties? wanna know how skipper help the application installed by it get their properties?
for example, i depoly a stream in scdf by using http | log and i've config http with server.port=8088, how does it get this property?

A: SCDF sends the StreamDeployment properties as specific app deployment properties set for each app that gets deployed for the Stream.
At the Skipper side, the app deployment properties are set in the Spec of the application getting deployed.


text:
Q: Change state in multiply SO I made this report that is called from an action in a tree view of SO.
So i can select few reports and print them out.
The thing is that i want to change state in Sale Orders that I selected and printed out the reports. State should change from "draft" to "sent". How can I do this?
<data>

    <report
        id="report_het_sale_order"
        string="Het Sale Order Pdf"
        model="sale.order"
        name="het.het_sale_order"
        rml="config_het/report/het_sale_order.ods"
        menu="True"
    />

    <record model="ir.actions.report.xml" id="report_hetl_sale_order">
        <field name="report_type">aeroo</field>
        <field name="parser_loc">config_het/report/het_sale_order.pyc</field>
        <field name="tml_Source">file</field>
        <field name="parser_state">loc</field>
        <field name="out_format" ref="report_aeroo.report_mimetypes_pdf_odt"/>
        <field name="in_format">oo-ods</field>
        <field name="auto" eval="True" />
    </record>

A: You can do it by modifying AbstractModel
For example:
<report
            id="agedpartnerbalance_template"
            string="Aged Partner Template"
            model="account.move"
            report_type="qweb-pdf"
            file="account.report_agedpartnerbalance"
            name="account.report_agedpartnerbalance"
        />

    class ReportAgedPartnerBalance(models.AbstractModel):

        _name = 'report.account.report_agedpartnerbalance'

        @api.model
        def render_html(self, docids, data=None):
            *****
            Your Logic
            docs = self.env[model].browse(self.env.context.get('active_id'))
            for doc in docs:
                doc.state = 'sent'
            *****
            docargs = {
                'doc_ids': self.ids,
                'doc_model': model,
                'data': data['form'],
                'docs': docs,
                'time': time,
                'get_partner_lines': movelines,
                'get_direction': total,
            }
            return self.env['report'].render('account.report_agedpartnerbalance', docargs)


text:
Q: How dependency parse tree is used for sentiment analysis? With the announcement from Google on release of Parsey McParseface syntaxnet
which is claimed to be the most accurate dependency parser. I want to understand how this parser can be used for more accurate sentiment analysis ? If someone can share some blogs or research papers or tutorials which can help me understand the overall flow.

A: Good question, Im not expert, in fact I got intrigued when you asked the question.
td;lr; more accurate dependency parsers would in allow one propagate sentiment through a graph and thus better determine sentiment polarity, at least in theory.
It seems from my reading that sentiment analysis using dependency tree graphs propagate the independent (prior -- sentiment you might get from a lexicon) sentiment of words to compose overall sentiment polarity of the text.
This approach uses the composition of language (its grammatical structure) to determine sentiment. This is somewhat* opposed to a statistical (naives bayes, logistics regression, neural networks) approach to understanding sentiment.
Here's the paper I scanned:
http://www.aaai.org/ocs/index.php/FLAIRS/FLAIRS14/paper/viewFile/7869/7837
For a deeper exploration of whats possible, this might help:
https://arxiv.org/pdf/1401.6330.pdf
A more through introduction to dependency parsing if you're interested might be https://web.stanford.edu/~jurafsky/slp3/14.pdf
*somewhat in the sense that (in particular) convolution networks do learn a certain composition of language so do rnns.


text:
Q: RPC_E_SERVERFAULT In my asp.net application I am calling one com component method using Interop dll. This is working fine in normal condition but In production sometimes its throwing below exception
System.Runtime.InteropServices.COMException (0x80010105): The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))
I am suspecting that this is happening when large number of users are accessing same page simultaneously.
Is somebody know solution or steps to debug this issue.
I have another question. while searching on internet I came across this aspcompact attribute  and MTA vs STA  thread model related to com components . Is this aspcompact  attribute is applicable in case of interop dll(Runtime callable wrappers). Will adding this attribute will solve my problem?

A: RPC_E_SERVERFAULT means that the out-of-process COM server threw a structured (Win32)exception, which could be all sorts of things, such as an Access Violation, Divide by Zero, etc. In other words, there's a bug in the COM server's implementation and there's nothing you can do in your calling application to cure this (unless you can find out what the bug is and can design a way to call the COM component which doesn't execute the buggy code).
You need to find whichever of your colleagues is responsible for the COM server, get him/her to use the debugger to capture a crash dump when the exception occurs, then do post-mortem debugging on the dump to diagnose the problem and fix it.

A: Monitor your site to capture exception when it raise.
Use Debug Diagnostics Tool v1.2
With the generated dump is easier to identify the point of failure.

A: Also could mean the COM object crashed. Try to rerun the application represented by the COM object by itself and see if it crashes or produces some error.

A: I had the same problem, but I got it to work by adding a [STAThread] attribute to the Main function.
[STAThread]
static void Main(string[] args)

A: I'm running Powershell scripts that use the MS Office 2010 Excel COM objects and started receiving this error. The culprit was the latest MS Office patches. Sorry, I can't specify exactly which one caused the error (I uninstalled a bunch at time), but uninstalling one of them solved the issues. The updates were installed on 7/18/2016.


text:
Q: Search file system with Xcode Mac application my uncle challenged me to make an application in which you can search the file system of a Mac. I've never actually had to do this yet in my programming experience, but I think it would be good to know as well. I have a search field, and a button that says search. Does anybody know how I can make that search the file system, and display the results? Thanks in advance!

A: this should help: http://macdevcenter.com/pub/a/mac/2005/07/12/spotlight.html?page=1


text:
Q: Floating point calculation being too exact In Java, I've run this method:
private static void floatAddition() {
    float a = 0.1F, b = 0.2F, c = a+b;
    System.out.println(a + " + " + b + " = " + c);
}

and the result is 0.3 for floatAddition. I'm now trying to get behind why it is adding to a round result, and not to something slightly off due to floating points.
I've manually transformed 0.1 and 0.2 into binary 32-Bit system with IEEE 754 standard, this is what I got:
0.1 (decimal) = 0 01111011 10011001100110011001101 (binary)
0.2 (decimal) = 0 01111100 10011001100110011001101 (binary)

I now add these two together. Since the exponents are different, I have to bring them both to the bigger one (2^-3) so I'm unnormalizing 0.1.
0.1 (decimal) = 0.11001100110011001100111 * 2-3 (binary)
0.2 (decimal) = 1.10011001100110011001101 * 2-3 (binary)
This is the manual addition result:
0.1 (decimal) + 0.2 (decimal) = 10.01100110011001100110100 * 2-3 (binary)
In IEEE 754 standard, this would be
0 01111101 00110011001100110011010

Now for checking whether or not I'm correct, I've used this IEEE 754 Converter: http://www.h-schmidt.net/FloatConverter/IEEE754.html
According to this site, my result should've been 0.30000001192092896.
Why is my floating point calculation more exact than it should be?

A: Lets look at some quick code:
public class Floats {
    public static void main(String[] args) {
        float a = 0.1F;
        float b = 0.2F;
        float c = a+b;
        System.out.println(a + " + " + b + " = " + c);

        System.out.printf("0x%8x", Float.floatToIntBits(c));
    }
}

The output of this code is:
0.1 + 0.2 = 0.3
0x3e99999a

That last line is the hexadecimal representation of the value that is being rendered as 0.3.
So, lets look what C does.
#include <stdio.h>
int main (int argc, char* argv[]) {
    float a = 0.1F;
    float b = 0.2F;
    float c = a + b;
    printf("%f + %f = %f\n", a, b, c);
    printf("0x%8x\n", *(unsigned int*)&c);
}

And this produces the output:
0.100000 + 0.200000 = 0.300000
0x3e99999a

You will note that the representation of the float value is equivalent.
I am certain that the code is properly following the specification.  You may be confused at the float to string conversion, but that is something to be done with various formatting or other libraries to display what you want.
But the underlying floating point representation is exactly what it should be.
As an aside, the difference between the C and the Java can be seen by switching to printf where one is expected to be a bit more precise with the values:
public class Floats {
    public static void main(String[] args) {
        float a = 0.1F;
        float b = 0.2F;
        float c = a+b;
        System.out.println(a + " + " + b + " = " + c);
        System.out.printf("%f + %f = %f\n", a, b, c);

        System.out.printf("0x%8x", Float.floatToIntBits(c));
    }
}

prints out:
0.1 + 0.2 = 0.3
0.100000 + 0.200000 = 0.300000
0x3e99999a

Note the printf in Java matches the printf in C.
Digging into the JLS we find in section 5.1.11,

If T is float, then use new Float(x).

Digging through this, one gets to sun.misc.FloatingDecimal which when created with FloatingDecimal(float f) which goes through a fair bit of calculations to try to figure out what to display.  Java8 changes this a little bit to do the BinaryToAsciiConverter, but the idea is still the same.

A: Probably because 0.3f = 0.30000001192092896.
0.3f is the single precision floating point number closest to the real number 0.3. The real number 0.3 cannot be represented exactly as a single precision floating point number (or as any binary floating point number), therefore 0.3f must be slightly different from the real number 0.3.
Single precision floating point has a 24 bit mantissa. For 0.3, the highest bit of the mantissa has a value of 0.25 = 2^-2, the lowest bit has a value of 2^-25, and you'd have to expect a rounding error up to
2^-26 = 0.000 000 014 901 161
Actually, 0.3f was rounded up by
0.000 000 011 920 928 96
which is entirely in the range that you would expect.


text:
Q: How to get current touch coordinates of PanResponder relative to parent view? Using React-Native, I'm trying to capture swipe events on a list view item. Everything works well but i'm having difficulties acquiring the current coordinate of the touch gesture, relative to the list view item.
In my _handlePanResponderMove, I use the following snippet:
let relativeY = event.nativeEvent.locationY;
Unfortunately, the Y coordinate I'm getting is relative to the "child view" the swipe occurred on, and not relative to the list view item (as I was expecting, since I attached the PanResponder to the list view item)
How can I get the gestures' Y coordinate relative to the list view parent?

A: Try to add a ref to the child and then measure its relative distances. This code represents the wrapper with a widget (child component). It works for me!
Notice that this.refs.self.measure is trigger after a setTimeout, it was not working without it. Could be a bug of measure or that the references are not updated after an instant.
import React, { Component } from 'react'
import TimerMixin from 'react-timer-mixin'
import {
  StyleSheet,
  View,
  TouchableHighlight,
  Text,
  Alert,
  PanResponder,
  Animated,
  Dimensions } from 'react-native'
import BulbWidget from './bulb-widget'

const COLUMNS = 3

export default class Widget extends Component {
  constructor (props) {
    super()
    this.state = {
      pan: new Animated.ValueXY(),
      touches: 1
    }
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([null, {
        dx: this.state.pan.x,
        dy: this.state.pan.y
      }]),
      onPanResponderRelease: (e, gesture) => {
        this.state.pan.flattenOffset()
        this._setPosition(gesture)
        Animated.spring(
          this.state.pan,
          {toValue: {x: 0, y: 0}}
        ).start()
      },
      onPanResponderGrant: (e, gestureState) => {
        this.state.pan.setOffset({x: this.state.pan.x._value, y: this.state.pan.y._value})
        this.state.pan.setValue({x: 0, y: 0})
        this._onPressWidget()
      }
    })
  }

  render () {
    let styleWidget = {}
    this.props.type === 'L' ? styleWidget = styles.widgetL : styleWidget = styles.widget

    return (
      <View ref='self' style={this.state.placed}>
        <Animated.View {...this.panResponder.panHandlers}
          style={[this.state.pan.getLayout(), styleWidget]} >
            <BulbWidget ref='child'/>
        </Animated.View>
      </View>
    )
  }

  componentDidMount () {
    // Print component dimensions to console
    setTimeout(() => {
      this.refs.self.measure((fx, fy, width, height, px, py) => {
        console.log('Component width is: ' + width)
        console.log('Component height is: ' + height)
        console.log('X offset to frame: ' + fx)
        console.log('Y offset to frame: ' + fy)
        this.offset = { fx, fy, width, height }
      })
    }, 0)
  }

  _onPressWidget () {
    this.refs.child.onPressAction()
    this.setState({touches: this.state.touches + 1})
    TimerMixin.setTimeout(() => {
      this.setState({ touches: 1 })
      console.log('Reset')
    }, 1000)

    if (this.state.touches === 2) {
      this.setState({touches: 1})
    }
  }

  _setPosition (gesture) {
    const dx = gesture.moveX - gesture.x0
    const dy = gesture.moveY - gesture.y0

    const { width, height } = this.offset
    const x = Math.abs(this.offset.fx + dx)
    const y = Math.abs(this.offset.fy + dy)

    const idTo = (Math.floor(x / width) + Math.floor(y / height) * COLUMNS)
    this.props.setPosition(gesture, this.props.idx, idTo)
  }
}

A: Set the child view to pointerEvents="none" like so:
  <View pointerEvents="none">
        ...
  </View>

That way, the event you receive on your event.nativeEvent.locationY will not take into account the child view coordinates at all, and that will do exactly what you want.


text:
Q: Perl regex - read java file and match entire text of a function in file I am trying to read a .java file into a perl variable, and I want to match a function, say for instance:
public String example(){

return "hello";

}

What would the regex patter for this look like?
Current Attempt:
use strict;
use warnings;

open ( FILE, "example.java" ) || die "can't open file!";
my @lines = <FILE>;
close (FILE);

my $line;

foreach $line (@lines) {
 if($line =~ /String example(.*)}/s){
    print $line;
 }
}

A: **Adopted from this answer
Regex:
^\s*([\w\s]+\(.*\)\s*(\{((?>"(?:[^"\\]*+|\\.)*"|'(?:[^'\\]*+|\\.)*'|//.*$|/\*[\s\S]*?\*/(\w+)["']?[^;]+\4;$|[^{}<'"/]++|[^{}]++|(?2))*)}))

Breakdown:
^ \s*
(                             # (1 start)
  [\w\s]+ \( .* \) \s*                 # How it matches a function definition
  (                             # (2 start)
      \{                                     # Opening curly bracket
      (                             # (3 start)
           (?>                               # Atomic grouping (for its non-capturing purpose only)
                "(?: [^"\\]*+ | \\ . )*"     # Double quoted strings
             |  '(?: [^'\\]*+ | \\ . )*'     # Single quoted strings
             |  // .* $                      # A comment block starting with //
             |  /\* [\s\S]*? \*/             # A multi-line comment block /*...*/
                ( \w+ )                      # (4) ^
                ["']? [^;]+ \4 ; $           # ^
             |  [^{}<'"/]++                  # Force engine to backtrack if it encounters special characters (possessive)
             |  [^{}]++                      # Default matching behavior (possessive)
             |  (?2)                         # Recurs 2nd capturing group
           )*                                # Zero to many times of atomic group
      )                             # (3 end)
      }                                      # Closing curly bracket
  )                             # (2 end)
)                             # (1 end)

A: Revo's regex is the Right Way To Do it (as much as a regex ever can be!).
But sometimes you just need something quick, to manipulate a file you have control over. I find, when using regexes, that it's often important to define "Good enough".
So, it may be "good enough" to assume the indentation is correct. In that case, you can just detect the start of the fn, then read until you find the next closing curly with the same indentation:
(               # Capture \1.
    ^([\t ])+   # Match and capture leading whitespace to \2.
    (?:\w+\s*)? # Privacy specifier, if any.
    \w+\s*\(    # Name and opening round brace: is a function.
    .*?         # Need Dot-matches-newline, to match fn body.
    \n\2}       # Curly brace is as indented as start of fn.
)               # End capture of \1.

Should work on clean code that you wrote yourself, code you can pass through an auto-formatter first, etc.
Will work with K&R, Hortmann and Allman indent styles.
Will fail with one-line and in-line functions, and indent styles like GNU, Whitesmiths, Pico, Ratliff and Pico - things which Rico's answer handles with no problems at all.
Also fails on lambdas, nested functions, and functions which use generics, but even Revo's doesn't recognize those, and they're not that common.
And neither of our regexes capture the comments preceding a function, which is pretty sinful.


text:
Q: Jquery: Removing dynamically generated element when modal confirmation button is clicked For example:

Are you sure you want to remove?

        <input type="hidden" id= "removeItemIdModalInput">
        <button type="button">Cancel</button>
        <button type="button" id="remove-confirm-btn">Confirm</button>

When clicked on the remove-item class a modal will be shown with two button Confirm and Cancel when  user clicks on confirm, remove the whole (parent) item. How can i achieve this??
Here's what i did:
$(document).on("click",".remove-item", function (e) {

        var removeProductId = $(this).closest(".item").attr("id");

        // Setting the value in modal's hidden input
        $("#removeItemIdModalInput").val(removeProductId);

        $("removeItemModal").modal('toggle');

    });

$(document).on("click","#remove-confirm-btn", function (e) {

        var removeProductId = $("#removeItemIdModalInput").val();

        $("removeItemModal").modal('toggle');

        // Removing the container div/item
        $(removeProductId).fadeOut(300,function () { $(this).remove();});

    });

But It's not working. Why? Is there a better approach?

A: [EDIT]
TS wants a modal window, this answer provides an alternative

Instead of a modal window, you can use confirm() too.
If that is confirmed, you select the parent of the span, by using parent(), fade that element out, and remove. Just like you already had.
Also note that you use remove-item and remove_item both, I changed it all to remove_item

$(document).on("click", ".remove_item", function(e) {
  if(confirm("Do you want to remove this box")) {
    $(this).parent().fadeOut(300, function () { $(this).remove();});
  }
  return;
});
#item_1, #item_2 {
  border: 1px solid black;
  margin: 2em;
}

.remove_item {
  background: red;
}

  Item 1
    remove

  Item 2
    remove

A: Here's what solved my problem:
$(document).on("click","#remove-confirm-btn", function (e) {

        var removeProductId = $("#removeItemIdModalInput").val();

        $("removeItemModal").modal('toggle');

        // Changed here
        $("body").find(removeProductId).fadeOut(300,function () { $(this).remove();});

    });


text:
Q: how to solve the problem Promise {  } I'm new in next JS, when I am trying to display my data in a particular route , its not showing , can anyone tell me why its not showing, if you have any query regarding my question please free fell to ask.

import { getDataFromSheets } from "../../libs/sheets";

export default function handler(req, res) {

    const sheet =  getDataFromSheets();

    console.log(sheet)

    res.status(200).json(sheet);

}

A: import { getDataFromSheets } from "../../libs/sheets";

export default async function handler(req, res) {
  const sheet = await getDataFromSheets();
  console.log(sheet);
  res.status(200).json(sheet);
}

A: Use can solve this in a couple of ways,
Using async/await
import { getDataFromSheets } from "../../libs/sheets";

export default async function handler(req, res) {
    const sheet =  await getDataFromSheets();
    console.log(sheet)
    res.status(200).json(sheet);
}

Using .then(), .catch()
import { getDataFromSheets } from "../../libs/sheets";

export default function handler(req, res) {
    getDataFromSheets()
      .then(sheet=> res.status(200).json(sheet))
      .catch(err=> console.log(err))
}


text:
Q: Why ip_forward is disable by default? any side effect? I need to forward an interface and I wonder why is disable by default? Is there any security issue when I enable it? Is there any side effect when I enable it?

A: ip_forward is only useful on multihomed systems (i.e. more than one network interface) and makes routing of network packets between those interfaces possible. By enabling ip_forward your box essentially becomes a router.
Routing is an optional network function and as such disabled by default.
As for the downside/possible risks: when one of those interfaces is facing a public subnet (WAN/internet or possible hostile LAN), routing makes attacks possible. That's why you need to address those potential security issues with a firewall.
There is an excellent answer at What is kernel ip forwarding? with more information on the subject.


text:
Q: bootstrap modal on top fixed positioned div it seems my popup modal is not on top of everything. There is a div with fixed position. How can I make modal appear on top of fixed positioned div?
Fixed positioned div (header):

header

 Home

 Contact us

Modal:

        I am pop up


text:
Q: os x terminal command Does anyone know how can i remove '@2x~ipad' string from all files name in a directory
do that a file named: image@2x~ipad.png will be renamed to: image.png
I need to rename all files in a certain directory
Can I do it with a loop from terminal? any idea?

A: Using bash (in the terminal):
for file in *2x~ipad.png; do
  mv $file ${file%%\@2x~ipad.png}.png
done


text:
Q: nginx proxy_pass exact route to remote server I'm currently trying to setup a proxy_pass to a remote server for an exact route with nginx. I've done this numerous times for sub-domains without any issues but can't get it to work for an exact route.
#sites-available/default:

server {
    root /dir;
    index index.html index.htm;
    server_name staging.domain.co;
    listen 80;

    location / {
       try_files $uri $uri/ /index.html;
    }

    location = /sitemap {
        proxy_pass http://45.77.0.0:3334;
    }
}

When I go to http://staging.domain.co/sitemap I get the "Cannot GET /sitemap" error rendered in the browser, with a 404 showing in the dev tools and no request reaches the remote server. The remote server works as expected and returns what it's supposed too. Also, there is no logged error in /var/log/nginx/error.log. Does anybody have an idea what could be causing this?


text:
Q: CSV remove column without header name I'm having trouble to select specific column from CSV file. I need to select only 2 column :
1002     2019-02-01 00:03:07
Here is my example:
(Get-Content c:\Users\file.csv)  -replace ',', "`t" -replace '/', '-'  |
  foreach { $_ + "`t 1 `t 255 `t 1 `t 0" } |
  Select -Skip 1 |
  Set-Content C:\Users\outfile.csv

My Output right now:
1002    Hafiz   New Organization    9-6-2019 13:57  Check In    'Main1_Door1_Entrance Card Reader1  Main1_Door1_Entrance Card Reader1    1   255     1   0
1002    Hafiz   New Organization    9-6-2019 15:44  Check In    'Main1_Door1_Entrance Card Reader1  Main1_Door1_Entrance Card Reader1    1   255     1   0

End Result:
 3006   2019-02-01 00:03:07     1   255 1   0
 1005   2019-02-01 06:44:31     1   255 1   0

A: PowerShell has a built-in Import-Csv command. This avoids the need to manually parse CSV files yourself. You could do something like this:
Import-Csv -Path c:\Users\file.csv | Select-Object -Property Column1, Column2


text:
Q: Train a huge model inception with keras I need to train an inception model with more than 400 000 images.
I know I can't load it all on the memory, since it's too big.
So, I will certainly train it over batch, instead than epoch (And so generate load every batch from the disk)
But, it will be very slow, no ?
Do you know if there is a different way of doing it ?
I also want to apply different and aleatory transformations to my images during the training.
I looked over the dataimagegenerator class, but, it's incompatible with all the images I have.
So, there is a way to do that without the generator ?
Thanks to you!

A: You can use the fit_generator method (https://keras.io/models/model/#fit_generator) of the model. This still loads images from memory, however this is done in parallel and has less overhead. You can write your own generator to apply the transformations you want to (https://wiki.python.org/moin/Generators).
If you need faster memory access you can take a look at hdf5. You can store the images in hdf5 to provide faster indexing and loading for your program. (http://www.h5py.org/)


text:
Q: Google Cloud Storage quota hit - how? When my app is trying to access files in a bucket using a SignedURL, a 429 response is received:
<Error>
    InsufficientQuota
    <Message>
        The App Engine application does not have enough quota.
    </Message>
    App s~[myappname] not have enough quota
</Error>

This error continues until the end of the day, when the quota is apparently reset, then I can use storage again. It's only a small app and does not have much usage. The project that contains the storage is set up to use billing. The files are being accessed from another project, which is also set up to use billing.
I'm not aware that Google Cloud Storage has any quotas that could be hit in this fashion. The only ones I know of are the ones here: https://cloud.google.com/storage/quotas but as far as I am aware, none of them apply.

*

*Buckets are not being created or destroyed.

*Updates are not being made to buckets.

*There are only a couple of IAM identities.

*There are no Pub/Sub notifications.

*Objects stored in the buckets are small.
Is there any way I can find out why the quota is being exceeded?

A: It turns out it was because of a spending limit I had set on app engine. I didn't think those spending limits applied any more, but it turns out that's for new projects. Spending limits that have already been set on existing projects are effective, and I can personally attest that they do work!
Thanks for the comments @KevinQuinzel and @gso_gabriel.


text:
Q: Issues with CSS and HTML - Border Radius and Background Color I have a small issue with some design. Problem is that the background colour of a row at the top or the bottom of the table seems to be "hanging over" the edges. I think that the background colour is still applying the table style, but cannot figure this out for the life of me (I'm not a designer!). Jfiddle here:
http://jsfiddle.net/UFcqB/
HTML:

                ID
                Name
                Contact Person
                Contact Number
                Email Address
                Status
                Location
                Options

                1
                Test Agency cc.	John Doe
                0112131232
                jd@testagency.co.za
                Active
                Hatfield

CSS:
table {
    background: none repeat scroll 0 0 #FFFFFF;
    border: 1px solid #E2E2E2;
    border-collapse: separate;
    border-radius: 20px 20px 20px 20px;
    moz-border-radius: 20px 20px 20px 20px;
    box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.1);
    line-height: 1;
    font-size: 12px;
    width: 100%;
}

th {
    padding: 5px 10px 5px 10px;
}

td {
    padding: 5px 10px 5px 10px;
    text-align: left;
}

.tablehead {
    background-color: #E9E9EA;
    color: #747070;
    text-align: left;
}

.second_row {
    background-color: #DFEFFC;
}

Thanks for any help!

A: If you add:
 overflow: hidden;

to the CSS of table, it will hide the corners of the rows.

A: Check here:
http://jsfiddle.net/balintbako/UAVxB/
You have to add the border-radius to the s and s on the corner.
There is a quite long conversation here (I copied the css from here to the fiddle): CSS3's border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?

A: It's because the table top border has a radius factor while the first row still has the sharp border on its top and they override with each other. If you don't want to use overflow for some reason, you can put radius element under both the table and that exact tr, and remember to put the radius on a fixed number like 5px, instead of a ratio like 2%, this way both borders will be the same shape and you won't have that problem.


text:
Q: How to get a summary statistics of a table from a semi-aggregated table? R I have this table I am working with.
rent_data <- data.frame(id = c(123,124,125,126,127,128,129,123),
            desc = c("Rent Payment", "Rent Payment", "Late Fee", "Pet Fee", "Rent Payment", "Late Fee", "Pet Fee", "Rent Payment" ),
            units = c(1,2,1,2,4,1,1,2),
            total_dol = c(500,1000,250,600,2000,250,300,500))

> print(rent_data)
   id         desc units total_dol
1 123 Rent Payment     1       500
2 124 Rent Payment     2      1000
3 125     Late Fee     1       250
4 126      Pet Fee     2       600
5 127 Rent Payment     4      2000
6 128     Late Fee     1       250
7 129      Pet Fee     1       300
8 123 Rent Payment     2       500

My goal is to get a frequency table that shows me the sum of units and total_dol broken down by 'desc' column. I'm hoping to get a solution with dplyr/tidyverse.
My desired output. Thank you.


text:
Q: How to use Applet getParamter in Eclipse I have a simple Java Applet (SE 7) with an HTML file containing Applet and Param elements.
GetParameter() works fine hitting the HTML page with a browser or using appletviewer, but when I run the app in Eclipse (Juno Build id: 20130225-0426) the debugger shows GetParamter() returns null for every call.
The class and html files are in the bin directory of the project.  Should this just work or is there some configuration I need to make when setting this up or launching in Eclipse.
Thanks in advance for your help.

A: Well I've found one approach that seems to work (from the Eclipse site).
Select the Applet -> run configurations -Parameters and manually enter the parameter names and values.
It works but this doesn't appear to exercise the getParameter() HTML interaction using Eclipse.  SO I'm back to appletviewer to ensure my HTML works properly with my Java class from what I can tell.


text:
Q: Não consigo listar uma tabela em php Não consigo listar uma simples tabela em php... Não vejo o que há de mal com o código, quando executo este código php apenas me mostra uma página em branco... O que estou a fazer de mal?

    <title>Listar Alunos</alunos>

    <?php

     //Conecta ao servidor e escolhe a base de dados
     mysql_connect("localhost", "root", "");
     mysql_select_db("login");

     $query = "SELECT * FROM alunos";

     if ($resposta = mysql_query($query)){
         echo
         '

Primeiro Nome
         Último Nome
         Email
         Rua
         Cidade
         Telemóvel
         Data de Nascimento
         Sexo

         ';

         while($row = mysql_fetch_array($resposta)){
             echo '
' .
             $row['primeiro_nome'] . '	' .
             $row['ultimo_nome'] . '	' .
             $row['email'] . '	' .
             $row['rua'] . '	' .
             $row['cidade'] . '	' .
             $row['telemovel'] . '	' .
             $row['data_aniversario'] . '	' .
             $row['sexo'] . '	' ;

             echo '
';
         }
         echo '
';

         } else{
            echo "Não foi possível listar os alunos. ".mysql_error();
         }

    ?>

A: Tem bastante coisa errada nesse seu código meu amigo, um deles é lá no seu <title>:
<title>Listar Alunos</alunos>

Você está fechando a tag <title> com </alunos>, então tudo que você faz depois disso, vai ficar no seu título. Pode colocar o mouse em cima da sua aba e ver que toda a sua sintaxe está ali. Mude para:
<title>Listar Alunos</title>

E outra, o mysql está obsoleto, mude para o mysqli, é mais fácil você adaptar a ele do que para o PDO.
Posso lhe ajudar a migrar seu código para o mysqli (adicione um i) e você cria um arquivo conexao.php e antes do seu $resposta = mysql_query($query) você irá colocar:
$resposta = mysqli_query($conn, $query)

E outra, não use um array aqui:
$row = mysql_fetch_array($resposta)

Use um assoc:
$row = mysqli_fetch_assoc($resposta)

De resto acho que não muda muito a não ser adicionar um i no seu mysql.
Segue um arquivo conexao.php:
<?php
  $servidor = "localhost";
  $usuario = "root";
  $senha = "123";
  $dbname = "teste";

  //Criar Conexão
  $conn = mysqli_connect($servidor, $usuario, $senha, $dbname);

?>

E na sua página index.php, logo após você abrir a tag PHP, coloque:
include_once("conexao.php")

E então consegue colocar o $conn no mysqli_query.


text:
Q: Calculating a Point that lies on an Ellipse given an Angle I need to find a point (A on this diagram) given the center point of the ellipse as well as an angle. I've been melting my brain all day (as well as searching through questions here) testing out different equations. What's the best way to do this?

I intend to grab point A at $225^o$ as well as another point at approximately $250^o$ using the same math. These need to be fetched regardless of elliptic width and height.

A: If the ellipse is centered at $(0,0)$, $2a$ wide in the $x$-direction, $2b$ tall in the $y$-direction, and the angle you want is $\theta$ from the positive $x$-axis, the coordinates of the point of intersection are
$$\left(\frac{a b}{\sqrt{b^2+a^2\tan^2(\theta)}},\frac{a b \tan(\theta)}{\sqrt{b^2 + a^2\tan^2(\theta)}}\right) \text{ if }0\le\theta< 90°\text{ or }270°<\theta\le360°$$
or
$$\left(-\frac{a b}{\sqrt{b^2+a^2\tan^2(\theta)}},-\frac{a b \tan(\theta)}{\sqrt{b^2 + a^2\tan^2(\theta)}}\right) \text{ if }90°<\theta< 270°.$$

A: I've been working on this one for a while now because I was trying to test a coordinate for overlap with an ellipse, and I came up with something much easier to find the point on an ellipse given an angle from the center. If you use a general first degree equation for the line and substitute into the equation for an ellipse then you can solve for x and y (the points where the line intercepts the ellipse).
To find the general first degree equation of a line, you can use this formula :
 $$(y_1 - y_2)*x + (x_2 - x_1)*y + (x_1*y_2 - x_2*y_1) = 0$$
Since the ellipse is centered on the origin and the line passes through it as well, you can simplify the equation for the line by substituting $x_1 = 0$ and $y_1 = 0$ and you come up with :
$$-y_2*x + x_2*y = 0$$
Solve for x and y and you get $$x = \frac{x_2*y}{y_2} , y = \frac{y_2*x}{x_2}$$
Next use the equation for an ellipse $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$$
and substitute in x and y and solve for $y^2$ and $x^2$ respectively. You come up with these two equations :
$$y^2 = \frac{a^2*b^2*y_2^2}{(b^2*x_2^2 + a^2*y_2^2)} , x^2 = \frac{a^2*b^2*x_2^2}{b^2*x_2^2 + a^2*y_2^2}$$
If you know the point on the line you can substitute in $x_2$ and $y_2$, but since all we have is an angle, we'll have to re-derive our line equation. It's not hard though. To find the x and y coordinates of a point using a radius (which we won't need) and an angle, you just use a little trigonometry. The x value of the triangle is $r*\cos{\theta}$ and the y value is $r*\sin{\theta}$. Substitute these in for $x_2$ and $y_2$ above and you get $-r\sin{\theta}*x + r\cos{\theta}*y = 0$. Notice you can divide by the radius now to remove it from the equation, leaving us with $-\sin{\theta}*x + \cos{\theta}*y = 0$. Re-substitute into the earlier equation and you get $y = \sin{\theta}$ and $x = \cos{\theta}$. Substitute these into the equations for $y^2$ and $x^2$ and you come up with the following equations.
$$y = \pm\frac{ab\sin{\theta}}{\sqrt{(b\cos{\theta})^2 + (a\sin{\theta})^2}} , x = \pm\frac{ab\cos{\theta}}{\sqrt{(b\cos{\theta})^2 + (a\sin{\theta})^2}}$$
You now know another formula to find the coordinates of a point on an ellipse given only an angle from the center, or to determine whether a point is inside an ellipse or not by comparing radii. ;)

A: If the ellipse is centered at the origin, the equation of the ellipse is $\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$.  The equation of the line is $y=x\tan \theta $  So you have $\frac{x^2}{a^2}+\frac{(x\tan \theta )^2}{b^2}=1$ or $x=\pm \frac{ab}{\sqrt{b^2+a^2(\tan \theta)^2}}$ where the sign is + if $ -\pi/2 \lt \theta \lt \pi/2$

A: You can also use parametric equations:
$$x=a\cos(\theta)$$
$$y=b\sin(\theta)$$
Where $a$ is the radius on the horizontal axis, and $b$ is the radius on the vertical axis.

A: The equation of an ellipse in its origin centered form is:
$(\frac{cos \theta} {a})^2 +  (\frac{sin \theta} {b})^2=(\frac{1}{ r})^2 $.
Hope you take it from there.

A: I think there might be an alternative that doesn't need to define a piecewise function and we don't have problems in handling some angles:
$x(\theta) = r(\theta)cos(\theta)$
$y(\theta) =r(\theta)sin(\theta)$
where $r(\theta)$ is the radius of the ellipse given $\theta$ and is given by $r(\theta)=\frac{ab}{\sqrt{a^2sin^2(\theta)+b^2cos^2(\theta)}}$, see here.
N.B.: This works as well for an ellipse tilded by an angle of $\phi$ and the parametrisation is
$\begin{bmatrix}x(\theta)\\y(\theta)\end{bmatrix} = \begin{bmatrix}cos(\phi)&-sin(\phi)\\sin(\phi)&cos(\phi)\end{bmatrix}\begin{bmatrix}r(\theta-\phi)cos(\theta-\phi)\\r(\theta-\phi)sin(\theta-\phi)\end{bmatrix}$


text:
Q: Saving JPEG metada using OpenCV Is there any way I could save some JPEG metadata (like Exposure Time) using OpenCV 2.4.2?
Any help would be appreciated.

A: You can use VideoCapture properties to retrieve information from images (frames).
I use pyexiv2 to create exif tags and write the retrieved info to those images.


text:
Q: Crawl NodeJs and AngularJs sites with scrapy python I am trying crawl websites with scrapy python, most of sites done successfully but most of sites are giving tough time, because they are running on Nodejs and angularjs framework or other java frameworks, scrapy crawler is unable to get the details from the pages. please here i need your kind attention. looking forward to your earliest help.
here you can find the code that initially i am using for test base.
import scrapy
from selenium import webdriver
from scrapy.http import TextResponse

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = ['https://en-ae.wadi.com/home_entertainment-televisions/?ref=navigation']

    def parse(self, response):
        self.log('i have just visited the ' + response.url)
        yield{
            'product_name'  : response.css('p.description.ng-binding > span::text').extract_first(),
        }

Thanks in advance.

A: Check out splash: that will allow you to crawl javascript based web sites.
You can also create your own downloader middleware and use Selenium: How to write customize Downloader Middleware for selenium and Scrapy?
Hope this helps.