text:
Q: Lucene or Solr for indexing MySQL db data, some of which cannot be made public I have a MySQL database with a PHP front-end.  I would like to implement a search function but I have a somewhat unique situation and need some advice before proceeding.
My employer has a large collection of archival research materials.  Some of the collections have metadata and data available in a digital format, however, not all of the digital data is allowed to be accessible via the internet due to donor agreements or copyright issues.  In the cases where the digital data is not allowed on the internet, people may physically visit our building and view the information.  Right now each digital collection has its own database but we are in the process of consolidating everything into a single db so that patrons can search across all collections at the same time.
It is my understanding that if I use Solr to index and search, the info is transmitted over HTTP between the Solr instance running on Tomcat to the client and that could potentially expose data that is not supposed to be public.  To avoid this problem, I thought perhaps it would be a better idea to use Lucene directly on the server to generate the index and then somehow access it from PHP directly on the same server.  My questions are (1) does my assessment of the situation sound correct; and (2) if not, how does it actually work?  I do know Java.  Thank you.

A: Transmitting data over HTTP and having public access to that data are two entirely different concerns. You can have a Solr server running on a physically different machine halfway across the globe and still configure it so it can only be accessed from one particular machine which you explicitly allow. Usually though you may have the Solr server running on the same machine that your app is running on and configure the server's firewall/port/routing settings to only allow public access to your application, not the Solr server. This really is not a concern over choosing one or the other, just a matter of configuration.

A: If you are concerned about transmitting data from Solr to MySQL you can simply make fields only "indexed" but not "stored". This way you can query them, but not read their content, additionally as was suggested allow access to Solr only from trusted machines (PHP client).
Solr is not very good in producing big XML or JSON responses with field content, so ask (and store) only what you really need (i.e. only id of DB record, and get the rest from DB itself).
This way you will have fast response, it will be useless for others (in case of the information leak) and the index will be smaller.


text:
Q: Keeping a terminal window open after running script from crontab I have this script
#!/bin/sh
curl -4 http://wttr.in/Colorado\ Springs

that I want to automatically execute each morning. I have my crontab entry as
* 7 * * * (path to script)

But either the script doesnt run, or it runs and then immediately closes the shell. I know that my cronjobs are running as I have other scripts for backups that run on an hourly basis but cant figure out what detail I am missing here. I found one suggestion to include $SHELL in the script but that made no difference. Any suggestions?

A: Usually when I have to keep the terminal open I would exec bash as my last command. I do that when I write installer script which would open terminal; do the job and get lost after that. But if there is an error then I want the terminal to stay there so that I can read the error.
exec is used to replace the current program with argument which we provide to exec.

A: Actually, I don't know what are you trying to achieve with this call in your crontab. Do you want to see the weather report on your terminal? Do you want to save the weather report in the file? Get it in your emails?
If you do no redirections, you'll get the report in your mail.
If you want to have it in a file, just do:
curl wttr.in/Colorado+Springs > file

If you want to have it on you terminals do
curl wttr.in/Colorado+Springs | wall

Please note that you don't need -4, http:// and you can replace \space with +.
(DISCLAIMER: I'm the author of wttr.in)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows 8.1 Powershell Set-DisplayResolution I found a technet article to set the display resolution using powershell and Windows Server Core Cmdlets.  http://technet.microsoft.com/en-us/library/jj603036.aspx
However when I try to run the cmd PS C:\> Set-DisplayResolution -Width 1920 -Height 1200 I get an error saying the Set-DisplayResoluton is a unknown cmd.  I know this cmd is for administering server core functionlaity but can it be used in Windows 8.1.  And if so, how do I load the cmdlet in Powershell?

A: Are you trying to run this on Windows 8.1? It looks like the command might only be available on Windows Server 2012 R2 Server Core. I understand that the article says otherwise, but I just checked on my Windows 8.1 computers, and do not have the command in the session.
Get-Command -Name *resolu*;


text:
Q: Firebase Firestore - get additional data for each document on collection I have this list of messages objects, with a message, a user_id and a date. I actually want to retrieve user informations together with each message.
return new Promise<any>((resolve, reject) => {
  this.afs.collection('/messages").snapshotChanges()
    .subscribe(snapshots => {
      resolve(snapshots)
    })
})

I don't think iterating on the messages to get users is what I want to do - there should be a much better way. I'm also not sure about the recommandations I read at some places about storing the whole user data for each location where you could need it... I don't like it.
Is there a better way ?

A: This question is answered here by Frank from Firebase here in relation to the Realtime Database. This will most likely be applicable to your use case as well. There is also a great little support document listing out the advantages of the different approaches with Firestore here.
Depending on your specific use case, it might or might not be tenable to store user data in your message object. You might have heard of data duplication and de-normalisation  which is a common practice in NoSQL databases.
Without knowing too much about your use case, I would store user_id's on the message object and fetch them if and when they are needed.


text:
Q: Get chunked-encoded url I need to get a webpage (by url) with chunked-encoding in C#. There are some topics (on SO too, this Chunked Encoding Implementation in .NET (or at least pseudo code) for ex) about it, but I can't figure out how to do this in plain C#. Please help me with code :)

A: Figured this out. My actually problem was in gzip :)
For the future reference about subject
If you need implementation of chunked-encoded request see this Mono sources: http://www.koders.com/csharp/fid20277378DA3C2E68BAB2BC30A899CA45CFE0C150.aspx?s=webclient.cs

A: Watchout you can also get gZip and Chunked
My un-chunk code was a lot smaller then shown in the link but it was not always perfect for some reason or another.
It would be nice to somehow stream data from a socket into a httprequest and then let that deal with gzip, deflate and chunks but i don't know how to force feed a request stream from a socket.
Click my name if you want a simple .aspx page that realys results from google with 100 results at a time and also removes mouseover and spyware scripts


text:
Q: ddev exec: command not found (.bash_aliases) In a local ddev instance, I have added a few aliases and functions to .ddev/homeadditions/bash_aliases.
For example: alias ll="ls -lhA"
While ddev ssh and then ll will work, ddev exec ll returns
bash: ll: command not found
Failed to execute command ll: exit status 127

Why?

A: It's really about how bash works, not about how ddev works. The .bashrc (and thus .bash_aliases, which gets loaded by .bashrc) is only loaded by interactive shells (contexts like ddev ssh). Here'a an Stack Overflow answer on it: Why aliases in a non-interactive Bash shell do not work
ddev exec just does a bash -c "<your command>", and bash -c is noninteractive by design.
You might consider adding ddev custom web commands for things you can't live without.
A ddev ll custom command could work like this. Create a file named "ll" in .ddev/commands/web with the contents
#!/bin/bash

## Description: Run ls -l inside web container
## Usage: ll [flags] [arguments]
## Example: "ddev ll"  or `ddev ll /tmp`

ls -l $@

A: Here's an example of my setup (actually, I have scripts more than just ll)
.ddev/docker-compose.env.yaml
version: '3.6'

services:
  web:
    environment:
    - PROD_USER=foo
    - PROD_SERVER=bar.com
    - PROD_ROOT=path/to/root
    - LOCAL_ROOT=that/path/to/root
    - ASSET_DIRS=bi ba bu

.ddev/commands/web/sync_down_files
#!/bin/bash

# rsync prod assets to local

# download all assets
for directory in ${ASSET_DIRS} ; do
    rsync -zra \
        --delete \
        --exclude='.env' \
        ${PROD_USER}@${PROD_SERVER}:/home/${PROD_USER}/${PROD_ROOT}/$directory \
        ${LOCAL_ROOT};
done

Now I do ddev sync_down_files and get all remote assets into the local site. Same for the db.


text:
Q: file_get_contents authentication gives '401 Access Denied Error' I am trying to create a database in cpanel using the folowing comment
$result =file_get_contents("http://$cpanel_user:$cpanel_password@$cpanel_host:2082/frontend/$cpanel_skin/sql/adddb.html?db=$db_name")

echo $result;
this command gives me HTTP request failed! HTTP/1.1 401 Access Denied error. I have used the correct password and username for connecting. And i am able to create the database when i give this url(url in this format) in a browsers url field.
Can someone explain what seems to be the problem?

A: That is not the correct way to create databases using cPanel. I believe you are trying to replicate the form inside cPanel to create databases, which is not correct.
Also, you will not be able to create databases using your cPanel username and password. I think you should refer to this thread to resolve your issue.


text:
Q: Is it possible to emulate printing to a specific printer? I'm developing a Windows application that should support printing to a group of specific printers (for instance, Bixolon SRP-350, etc.) Those are special printers with special paper dimensions, etc. I need to test my software with them. Obviously one solution would be to buy each of those printers, so before I jump into doing that, I'm curious, is there such thing as printer emulation or a virtual printer available?
Here's what I need. You know when you install a PDF printer, it prints into a pdf file instead of the paper, right. So if there's a software that would allow me to see how my print would look for a specific printer by outputting the result to PDF or anything on the screen with a ruler on the side for dimensions, that's what I'm looking for. At this point I'm just checking if such solution even exists?

A: Yes, you can install the needed printer without having it connected, then use the "Print to file" option in the standard "Print" dialog box.
(Someone who actually has tried this please expand... I just know it's possible.)


text:
Q: Highlighting a specific bar with a specific value in ggplot I am currently working on the dataset "diamond", which is included in R. Specifically, I am trying to highlight the diamond price of 605, which occurs most frequently (132 times)
My code is the following:
library(ggplot2)

ggplot(diamonds) +
geom_histogram(aes(x=price),
             binwidth = 10,
             breaks = seq(250, 1000, 10),
             color = "black") +
scale_fill_manual(values = c("[250,590]" = "#FF0000", "[600,610]" = "#FF9999", "[620,1000]" = "#FF0000"))

I seemed to get everything right, besides filling in the specific intervals.
I really, would appreciate the help. Thanks!

A: You could use cut
#Use cut to divide price into groups and table to count frequency of each group
temp = data.frame(table(cut(x = diamonds$price, breaks = seq(250, 1000, 10))))
ggplot(diamonds) +
    geom_histogram(
        aes(x = price),
        binwidth = 10,
        breaks = seq(250, 1000, 10),
        color = "black",
        #For the group with maximum value, assign red, otherwise assign black
        fill = replace(rep("black", NROW(temp)), which.max(temp$Freq), "red"))


text:
Q: How to keep the same speed of object when number of object increase? Im doing a game and I'm using SurfaceView. In the game I have 25 small dots that are moving around. The goal is to make a game where the player draw a circle around some of the dots with the same color. My problem is that while I draw this circle and after I have lift my finger from the screen, all the dots are moving very, very slow! I guess the reason for this is all the line segmets that are being drawn constantly together with all the dots.
Is it possible to have the same moving speed of the dots all the time? I tested with SystemClock.Sleep(1) but it didn't helped much.
// Method to draw objects
private void drawObjects(Canvas canvas) {
    SystemClock.sleep(1);
    synchronized (this) {

    // Clear screen with black color
    canvas.drawRGB(0, 0, 0);

    // Draw line
    if(startDrawLine) {
        // Set properties to Paint object
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(5);
        paint.setStyle(Paint.Style.STROKE);
        paint.setAntiAlias(true);
        // Draw path
        path.moveTo(touchDownX, touchDownY);
        for(Point point: points) {
            path.lineTo(point.x, point.y);
            canvas.drawPath(path, paint);
        }
        path.reset();
    }
}
    // Call method draw() in CircleManager to draw all circles in list
    circleManager.drawCirclesInList(canvas);
}

A: Slow drawing is caused by to many points in your path.
If you are handling Touch event, you can expect hundreds and thousands of touches (your points) in short period of time.

*

*You need to interpolate your points somehow - take averages, ignore same and close points or something else.

*When you animate the "dots" your ANIMATION MUST BE BASED ON TIME, and not on the actual speed of the drawing on hardware.

To base your animation on time, you should calculate time passed since previous frame and use this time in function which calculates new position of the dot.
Here is a great article on the subject:
http://www.koonsolo.com/news/dewitters-gameloop/
EDIT - Response to a comment:
Suppose that your "dot" (I will call it a ball) needs to move horizontally (by X) from left to right at a constant speed of 100 units per second.
If you are doing your calculation WITH ASSUMPTION that your game will be running at 25 FPS, you simply add 4 to X on each frame.
The problem with this approach is that getting constant FPS is very hard to achieve.
On the fast hardware you will be sacrificing smoothness by limiting FPS,
on slow hardware you will be forced to skip drawing (drop) some frames (which can be jumpy with constant FPS).
Timer in Android is not very precise and also thread sleep functions are inaccurate.
In your case, instead of trying to force the constant FPS or calculate current FPS, try to wrap your head around and rethink of your problem
in a context of time.

When you think about time, it does not matter how fast is the game
  running (how many FPS) and what happened before.
You just need to ask a question "Where the ball should be in this
  moment, right now?"

If you, for example, know that ball movement stared at origin position X0 at origin time T0 then at the current moment TC ball position should be X = (TC - T0) * 100
Second approach is to measure time passed TD since last ball position update. Then the ball position should be updated like this: X = X + TD * 100
Once you get used to this approach, you will see that vast majority of animations is really trivial to implement with a great level of accuracy.


text:
Q: webpack dev server does not show the content I have the following problem when running the webpack dev server:
when I run npm start, it show the following:

➜  directory git:(staging) ✗ npm start
directory @1.0.0 start directory
  BUILD_DEV=1 BUILD_STAGING=1 ./node_modules/webpack-dev-server/bin/webpack-dev-server.js
http://localhost:8080/
webpack result is served from /undefined/
content is served from
directory
  404s will fallback to /index.html
Hash: 75773622412153d5f921
Version: webpack 1.12.11
Time: 43330ms

I guess the problem might because the following line:
webpack result is served from /undefined/
When I open the browser at http://localhost:8080/, it appear as follow:

Cannot GET /

and there is no thing in the console.
Do you have any ideas for this problem ?
UPDATE: WEBPACK CONFIG FILE
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');

const deps = [
  'moment/min/moment.min.js',
  'underscore/underscore-min.js',
];

/* Include SASS path here if you want to this in your sass files:
 *   @import 'bourbon';
 */
const bourbon = require('node-bourbon').includePaths;

const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = path.resolve(__dirname);
const SASS_DEPS = [bourbon].toString();

const BUILD_NUMBER = process.env.CI_BUILD_NUMBER;

const common = {
  entry: path.resolve(ROOT_PATH, 'app/index.js'),
  output: {
    filename: BUILD_NUMBER + '-[hash].js',
    path: path.resolve(ROOT_PATH, 'build'),
    publicPath: `/${BUILD_NUMBER}/`,
  },
  module: {
    loaders: [
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'sass?includePaths[]=' + SASS_DEPS],
        include: path.resolve(ROOT_PATH, 'app'),
      },
      {
        test: /\.css$/,
        loaders: [
          'style',
          'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
          'sass?includePaths[]=' + SASS_DEPS,
          'postcss'
        ],
        include: path.resolve(ROOT_PATH),
        exclude: /(pure\/grids|Grids).*\.css$/,
      },
      {
        test: /(pure\/grids|Grids).*\.css$/,
        loaders: [
          'style',
          'css',
          'sass?includePaths[]=' + SASS_DEPS,
        ],
        include: path.resolve(ROOT_PATH),
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000&minetype=application/font-woff',
      },
      { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader',
      },
      {
        test: /\.json$/,
        loader: 'json',
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'My App',
      template: path.resolve(ROOT_PATH, 'app/index.html'),
      inject: 'body',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
      },
    }),
    new webpack.DefinePlugin({
      __DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false')),
      __STAGING__: JSON.stringify(JSON.parse(process.env.BUILD_STAGING || 'false')),
      __API_HOST__: JSON.stringify(process.env.BUILD_STAGING ? 'my.api' : 'my.api'),
    }),
  ],
  resolve: {
    alias: {
      'styles': path.resolve(ROOT_PATH, 'app/styles'),
    },
    extensions: ['', '.js', '.jsx', '.json'],
  },
  postcss: function() {
    return [
      require('postcss-import'),
      require('autoprefixer'),
      require('postcss-cssnext'),
    ]
  }
};

if (TARGET === 'start' || !TARGET) {
  module.exports = merge(common, {
    output: {
      filename: '[hash].js',
      path: path.resolve(ROOT_PATH, 'build'),
      publicPath: '/',
    },
    devtool: 'eval-source-map',
    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          loaders: [
            'react-hot',
            'babel-loader'
          ],
          include: path.resolve(ROOT_PATH, 'app'),
        },
      ],
    },
    devServer: {
      colors: true,
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
    ],
  });
} else if (TARGET === 'build' || TARGET === 'builds') {
  const config = {
    resolve: {
      alias: {},
    },
    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          loader: 'babel-loader',
          include: path.resolve(ROOT_PATH, 'app'),
        },
      ],
      noParse: [],
    },
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        minimize: true,
        compressor: {
          screw_ie8: true,
          warnings: false,
        },
        compress: {
          warnings: false,
        },
        output: {
          comments: false,
        },
      }),
      new webpack.optimize.DedupePlugin(),
      new webpack.DefinePlugin({
        'process.env': { 'NODE_ENV': JSON.stringify(process.env.NODE_ENV) },
      }),
    ],
  };
  deps.forEach((dep) => {
    const depPath = path.resolve(nodeModulesDir, dep);
    config.resolve.alias[dep.split(path.sep)[0]] = depPath;
    config.module.noParse.push(depPath);
  });
  module.exports = merge(common, config);
}

A: Same problem occurred to me when i started using babel-loader > 6.
It was fixed by adding contentBase in webpack dev server configuration.
In my case it looked like this
new WebPackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    historyApiFallback: true,
    contentBase: __dirname + '/public'
}).listen(3000, 'localhost')

A: I would be great to see your webpack config file to pin point the exact problem, but from the error message, there could be multiple problem

*

*Make sure you are on the right port

*Make sure your webpack config has
path and public path setup

*Make sure you have contentBase setup as
well

Without seeing your webpack file and more concrete detail, it is quite hard to pinpoint the issue. But you can always go to https://webpack.github.io/docs/webpack-dev-server.html  for information on how to set it up.


text:
Q: How to cascade @OneToOne removal? I want to create a @OneToOne mapping where the root entity has a reference to a sub entity by foreign key contraint.
@Entity
public class MainEntity {
    @Id private long id;

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "fk_sheet_id", foreignKey = @ForeignKey(name = "fk_sheet"))
    private SheetEntity sheet;
}

@Entity
public class Sheet {
    @Id private long id;
    //...

    @OneToOne(mappedBy = "sheet")
    private GiataHotelEntity mainEntity;
}

Problem: when I go to the database and chose truncate cascade on the MainEntity, then the assiciated @OneToOne Sheet is not removed.
If I reverse the mapping and make Sheet the owning-side, then this cascaded delete would work! But I want the MainEntity to be the owning side.
What might I be doing wrong here?

A: When you run truncate MainEntity cascade, it is supposed to truncate the MainEntity table and any tables which are using MainEntity as foreign key    which is NOT the case here. In your case - the foreign key is with MainEntity (column fk_sheet_id). Had the relationship would have been created by having foreign key (referring to primary key in MainEntity) in Sheet table - your truncate script would work.

A:
CASCADE Automatically truncate all tables that have foreign-key
  references to any of the named tables, or to any tables added to the
  group due to CASCADE.

http://www.postgresql.org/docs/9.4/static/sql-truncate.html
Seeing your naming like fk_sheet_id, I suppose there is foreign key in MainEntity to Sheet in database, but not vice versa.
So it is right that Sheet is not affected by truncate on MainEntity, because Sheet has no foreign key to MainEntity. May be you need apply truncate cascade on Sheet?
In the second case, when you change the owner, it seems like hibernate generates a foreign key for you in Sheet table.

When the ConstraintMode value is CONSTRAINT, but the
  foreignKeyDefinition element is not specified, the provider will
  generate foreign key constraints whose update and delete actions it
  determines most appropriate for the join column(s) to which the
  foreign key annotation is applied.

http://docs.oracle.com/javaee/7/api/javax/persistence/ForeignKey.html

A: If MainEntity is the owner of the relationship it means it depends on Sheet. If it is important for the delete on MainEntity - ran outside Hibernate - to propagate and also delete the associated Sheet, you should declare the Sheet as the owner of the relationship.
Also, JPA does not specify how and if the cascades should be delegated to the DDL.
If it is important for you to have this cascade defined at db level, you can use
a Hibernate specific annotation: @OnDelete.
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "fk_sheet_id", foreignKey = @ForeignKey(name = "fk_sheet"))
@OnDelete(action = OnDeleteAction.CASCADE)
private MainEntity mainEntity;


text: Q: Написать post запрос, который возвращает короткий url страницы Всем доброго времени суток! Начинаю изучать rails с помощью туториала (http://rusrails.ru/getting-started-with-rails) и столкнулся вот с какой проблемой: не понимаю как реализовать post запрос. Если я правильно понял, то get-запрос реализуется через routes.rb, но про post не нашел ничего. Подскажите, пожалуйста, где нарыть информацию про реализацию post запросов в rails ;(


text:
Q: How to store regex or search terms in Postgres database and evaluate in Rails Query? I am having trouble with a DB query in a Rails app. I want to store various search terms (say 100 of them) and then evaluate against a value dynamically. All the examples of SIMILAR TO or ~ (regex) in Postgres I can find use a fixed string within the query, while I want to look the query up from a row.
Example:
Table: Post
column term varchar(256)
(plus regular id, Rails stuff etc)

input = "Foo bar"
Post.where("term ~* ?", input)

So term is VARCHAR column name containing the data of at least one row with the value:
^foo*$

Unless I put an exact match (e.g. "Foo bar" in term) this never returns a result.
I would also like to ideally use expressions like
(^foo.*$|^second.*$)

i.e. multiple search terms as well, so it would match with 'Foo Bar' or 'Search Example'.
I think this is to do with Ruby or ActiveRecord stripping down something? Or I'm on the wrong track and can't use regex or SIMILAR TO with row data values like this?
Alternative suggestions on how to do this also appreciated.

A: The Postgres regular expression match operators have the regex on the right and the string on the left. See the examples: https://www.postgresql.org/docs/9.3/static/functions-matching.html#FUNCTIONS-POSIX-TABLE
But in your query you're treating term as the string and the 'Foo bar' as the regex (you've swapped them). That's why the only term that matches is the exact match. Try:
Post.where("? ~* term", input)


text:
Q: Java - Priority Queue comparator comparing negative numbers My understanding is that the natural ordering for a priority queue is least to greatest. So it's expected that the least negative numbers come first before positive numbers.
PriorityQueue<Integer> q = new PriorityQueue<>();
q.add(-5);
q.add(10);
q.add(-5);

This yields a result [-5, 10, -5] which is not what I expect. Should be [-5, -5, 10]. However if I add a third -5, it then sorts it correctly [-5, -5, -5, 10]
If we want to be reversed (greatest positive numbers to least negative numbers):
PriorityQueue q = new PriorityQueue<>((a,b) -> Integer.compare(b,a))
q.add(-5);
q.add(10);
q.add(-3);

This yields a result [10, -5, -3] but it should be [10, -3, -5].
Can anyone explain this occurrence to me? And if there is a comparator that can actually correctly do what I want it to do? Do I have to write a customized approach to dealing with negative numbers?


text:
Q: Issues with OpenNI - Kinect and Ubuntu I have spent the afternoon fiddling with a fresh ubuntu install, on a virtual machine (Running through vmware player on win 8) using an xbox kinect (360 version, designed for windows) trying to get OpenNI to work, (and plan on using pointcloud library with this installation).
After much searching I managed to find several resources that pointed me in the right direction (as most of the OpenNI links are dead these days?)
I fear I may have installed deprecated versions of everything, however I have been able to get images out of the RGB camera, see below:

Now,  as you can see the RGB image is very scrambled, and I am getting no depth data whatsoever.
(Note the green text at the bottom, perhaps this may be important, I dont know..)
It may also be worth noting that the on the windows machine I appear to be having some form of driver discrepancies on the camera, and audio, as aswell as no information on the depth camera (I am unsure if this is bundled with the normal camera) see below:

I also am only able to get this information from the camera if the device is plugged into a USB 3.0 port, if plugged into any of the 2.0 ports, I am hit with a PrimeSense:(Device not connected) error.
Hopefully someone else has overcome these issues and would be willing to help me with this solution, apologies if this question is not seen as off topic for stackoverflow, If someone can suggest a better place to post this, I will happily move it there (However I felt this may be a little too specific for a general ubuntu site)
Cheers.


text:
Q: NSString to PDF file - Format contents I want to write several fields which are present in my iPad application to a PDF file.
e.g.
First Name, Last Name, Date of birth, Emplyoment Date, Employer, Address, etc...
I am able to capture all the fields in one of the NSString (I am appending each fields separated by new line \r\n).
But when the content is written to file, it is not proper.
Is it possible to somehow capture all the Titles and their values in a columns and write the same to PDF file?
regards,
Nirav


text:
Q: Read clipboard data with GWT I have this code that I have made to handle the CTRL+V from the browser, works fine however I need to get the clipboard data like this:
    Event.addNativePreviewHandler(new Event.NativePreviewHandler() {
        @Override
        public void onPreviewNativeEvent(Event.NativePreviewEvent event)
        {
            NativeEvent ne = event.getNativeEvent();
            // When CTRL + V is pressed
            if (event.getNativeEvent().getKeyCode() == 86 && // 'V'
                    event.getNativeEvent().getCtrlKey() == true) {
                // need to get the clipboard data
            }
        }
    });

A: JavaScript per se does not allow to simply read the system clipboard as this would be a huge security risk. Most browsers do, however, provide the means to achieve this (although it has to be enabled by the user). The API is, thus, browser dependend. For Firefox have a look at https://developer.mozilla.org/en-US/docs/Using_the_Clipboard.
To the best of my knowledge there is na GWT specific wrapper of this functionality. Thus, you need to work with GWT JSNI (http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html)

A: Although I'm the one that marked this question as a duplicate, I think the answers in that question may be bit out of date.  When I google, I find this discussion.  The answers in there solve the problem with JSNI but they remark that it doesn't work in FF because FF requires manually enabling restrictions.  If this doesn't help, you may have to use the answers in the duplicate.


text:
Q: The import com.android.internal.R cannot be resolved Hi i am working with Gestures and i need to import but i m getting error
com.android.internal.R;

The import com.android.internal.R cannot be resolved
kindly help me , please

A: I have a couple suggestions:
1) Make sure you don't have any other errors other than the R-related errors. Right-click your project folder in Eclipse, Android Tools -> Fix Project Properties.
2) Check to make sure you have the correct R imported. Sometimes the default Android.R can be imported.

A: You don't say why you need access to com.android.internal.R, but the sad fact is that you simply cannot import it (the "internal" is a clue that it's not part of the public API). Google doesn't expose this because it is subject to change.
It is possible to get to the internal resources by calling Resources.getSystem(). To get the  value of a particular resource identifier, you have to know its name and then use code like the following to find the value:
Resources res = Resources.getSystem();
int id = res.getIdentifier("resource name", "resource type", "android");

Be aware that any name that you use could disappear in future versions of Android.

A: Yes you can use the internal R with some dirty trick (dirty trick = Java reflection).
Just an example:
Class clasz = Class.forName("com.android.internal.R$styleable")
Field field = clasz.getDeclaredField("TextAppearance");
field.setAccessible(true);
int[] textAppearanceStyleArr = (int[])field.get(null);

field = clasz.getDeclaredField("TextAppearance_textSize");
field.setAccessible(true);
int textSizeStyle = (Integer)field.get(null);

A: First of all, what is Gestures ?
Do you have a package named com.android.internal in your gen folder ? Doest it contain R.java ?
If not, try Project->Clean in Eclipse. If it still doesn't work, you may have an error in your XML layout files.


text:
Q: What is nokogiri % encoding $ character Why do I get:
Nokogiri::HTML('test').to_html

=> "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\ntest\n"

I thought $ symbol was valid in the url?
Followup:
Why do browsers handle this differently. E.g. In the page: http://www.pmlive.com/pharma_news/its_on_shire_and_abbvie_agree_32bn_takeover_586969
The link: http://www.pmlive.com/pharma_news/mylan_buys_abbotts_non-us_generics_in_$5.3bn_deal_585883 works.
But nokogiri would parse this link as:
http://www.pmlive.com/pharma_news/mylan_buys_abbotts_non-us_generics_in_%245.3bn_deal_585883 which does not work (returns 404).
Are they making the decision that $ is actually safe and a better choice?

A: There's this RFC3986 here which lists the dollar sign as a reserved sub-delimiter (page 12).

reserved    = gen-delims / sub-delims
gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims  = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

It also recommends how reserved characters should be handle:

2.2.  Reserved Characters
URIs include components and subcomponents that are delimited by
characters in the "reserved" set.  These characters are called
"reserved" because they may (or may not) be defined as delimiters by
the generic syntax, by each scheme-specific syntax, or by the
implementation-specific syntax of a URI's dereferencing algorithm.
If data for a URI component would conflict with a reserved
character's purpose as a delimiter, then the conflicting data must be
percent-encoded before the URI is formed.

The authors of Nokogiri liked decided that since their library may be used by anyone for any purpose, there is no way to automatically determine whether a reserved character would conflict or not, and therefore the "safest" way to handle it (short of testing a URI directly) would be to escape it as per the recommendation.


text:
Q: Python Time Module-import timex2? I am newbie about python and I didnt understand some place from datatime topic.
import time
from time import time as my_timer

Can u explain me why we use 2 time kind of import here?

A: import time

time

<module 'time' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/time.so'>

dir(time)

['__doc__', '__file__', '__name__', '__package__', 'accept2dyear', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset']

This will import the entire module which include time that you imported with the other approach and whole lot of other built in functions that are part of the time module.
from time import time as my_timer

time

<built-in function time>

This is just a function

In short if you do
import time

you are importing entire module
from time import time as my_time

you are importing just the time function inside time module.

A: As you can see in the docs, the time module (which gets imported with the first import time) contains a function called time. After the first import this function would be accessible through time.time().
The second line imports the time function from the time module and renames it to my_timer. If you want only this one function, then you actually don't need the first line. But with these two lines you can:
Access any function from the time module as:
time.<function name>

And call the time.time() function by its new name:
my_timer()


text:
Q: linearGravityField() is not affecting physics bodies in the scene SceneKit I'm trying to use a SCNPhysicsField.linearGravityField object to affect only specific objects in my scene.  The problem is, that I can't seem to get it to affect anything.  Here's a sample of my code in Swift:
let downGravityCatagory = 1 << 0
let fieldDown = SCNPhysicsField.linearGravityField()
let fieldUp = SCNPhysicsField.linearGravityField()
let fieldNode = SCNNode()

let sceneView = view as! SCNView
sceneView.scene = scene
sceneView.scene!.physicsWorld.gravity = SCNVector3(x: 0, y: 0, z: 0)

fieldDown.categoryBitMask = downGravityCatagory
fieldDown.active = true
fieldDown.strength = 3
fieldNode.physicsField = fieldDown
scene.rootNode.addChildNode(fieldNode)

var dice = SCNNode()
//I then attach geometry here
dice.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Dynamic, shape: SCNPhysicsShape(geometry: dice.geometry!, options: nil))
dice.physicsBody?.categoryBitMask = downGravityCatagory
scene.rootNode.addChildNode(dice)

Even though the Physics Bodies are assigned the same catagoryBitMask as the gravity field, they just float there in zero G, only affected by the physicsworld gravity.

A: Set the "downGravityCatagory" bit mask on the node:
dice.categoryBitMask = downGravityCatagory;

the physics's categoryBitMask is for physics collisions only.

A: I am trying to get my ball to fall faster. Right now it falls really slowly. I tried using this answer. I think I am close, but I do not really know. The code:
import Cocoa
import SceneKit

class AppController : NSObject {

@IBOutlet weak var _sceneView: SCNView!

@IBOutlet weak var _pushButton: NSButton!

@IBOutlet weak var _resetButton: NSButton!

private let _mySphereNode = SCNNode()

private let _gravityFieldNode = SCNNode()

private let downGravityCategory = 1 << 0

private func setupScene() {

    // setup ambient light source
    let ambientLightNode = SCNNode()
    ambientLightNode.light = SCNLight()
    ambientLightNode.light!.type = SCNLightTypeAmbient
    ambientLightNode.light!.color = NSColor(white: 0.35, alpha: 1.0).CGColor
    // add ambient light the scene
    _sceneView.scene!.rootNode.addChildNode(ambientLightNode)

    // setup onmidirectional light
    let omniLightNode = SCNNode()
    omniLightNode.light = SCNLight()
    omniLightNode.light!.type = SCNLightTypeOmni
    omniLightNode.light!.color = NSColor(white: 0.56, alpha: 1.0).CGColor
    omniLightNode.position = SCNVector3Make(0.0, 200.0, 0.0)
    _sceneView.scene!.rootNode.addChildNode(omniLightNode)

    // add plane
    let myPlane = SCNPlane(width: 125.0, height: 2000.0)
    myPlane.widthSegmentCount = 10
    myPlane.heightSegmentCount = 10
    myPlane.firstMaterial!.diffuse.contents = NSColor.orangeColor().CGColor
    myPlane.firstMaterial!.specular.contents = NSColor.whiteColor().CGColor
    let planeNode = SCNNode()
    planeNode.geometry = myPlane
    // rotote -90.0 degrees about the y-axis, then rotate -90.0 about the x-axis
    var rotMat = SCNMatrix4MakeRotation(-3.14/2.0, 0.0, 1.0, 0.0)
    rotMat = SCNMatrix4Rotate(rotMat, -3.14/2.0, 1.0, 0.0, 0.0)
    planeNode.transform = rotMat
    planeNode.position = SCNVector3Make(0.0, 0.0, 0.0)
    // add physcis to plane
    planeNode.physicsBody = SCNPhysicsBody.staticBody()
    // add plane to scene
    _sceneView.scene!.rootNode.addChildNode(planeNode)

    // gravity folks...
    // first, set the position for field effect
    let gravityField = SCNPhysicsField.linearGravityField()
    gravityField.categoryBitMask = downGravityCategory
    gravityField.active = true
    gravityField.strength = 3.0
    gravityField.exclusive = true
    _gravityFieldNode.physicsField = gravityField
    _sceneView.scene!.rootNode.addChildNode(_gravityFieldNode)
    // attach the sphere node to the scene's root node
    _mySphereNode.categoryBitMask = downGravityCategory
    _sceneView.scene!.rootNode.addChildNode(_mySphereNode)
}

private func setupBall() {

    let radius = 25.0

    // sphere geometry
    let mySphere = SCNSphere(radius: CGFloat(radius))
    mySphere.geodesic = true
    mySphere.segmentCount = 50
    mySphere.firstMaterial!.diffuse.contents = NSColor.purpleColor().CGColor
    mySphere.firstMaterial!.specular.contents = NSColor.whiteColor().CGColor

    // position sphere geometry, add it to node
    _mySphereNode.position = SCNVector3(0.0, CGFloat(radius), 0.0)
    _mySphereNode.geometry = mySphere

    // physics body and shape
    _mySphereNode.physicsBody = SCNPhysicsBody(type: .Dynamic, shape: SCNPhysicsShape(geometry: mySphere, options: nil))
    _mySphereNode.physicsBody!.mass = 0.125
}

private func stopBall() {

    _mySphereNode.geometry = nil
    _mySphereNode.physicsBody = nil
}

override func awakeFromNib() {

    // assign empty scene
    _sceneView.scene = SCNScene()

    setupScene()

    setupBall()
}

@IBAction func moveBall(sender: AnyObject) {

    let forceApplied = SCNVector3Make(35.0, 0.0, 0.0)

    if _mySphereNode.physicsBody?.isResting == true {

        _mySphereNode.physicsBody!.applyForce(forceApplied, impulse: true)
    }
    else if _mySphereNode.physicsBody?.isResting == false {
        print("ball not at rest...")
    }
    else {
        print("No physics associated with the node...")
    }

}

@IBAction func resetBall(sender: AnyObject) {

    // remove the ball from the sphere node
    stopBall()

    // reset the ball
    setupBall()
}
}

Is there some trick to get "real-world" type gravity?

A: Based on what @tedesignz suggested, here is the slightly modified working code:
import Cocoa
import SceneKit

class AppController : NSObject, SCNPhysicsContactDelegate {

@IBOutlet weak var _sceneView: SCNView!

@IBOutlet weak var _pushButton: NSButton!

@IBOutlet weak var _resetButton: NSButton!

private let _mySphereNode = SCNNode()

private let _myPlaneNode = SCNNode()

private let _gravityFieldNode = SCNNode()

private let BallType = 1
private let PlaneType = 2
private let GravityType = 3

private func setupScene() {

    // setup ambient light source
    let ambientLightNode = SCNNode()
    ambientLightNode.light = SCNLight()
    ambientLightNode.light!.type = SCNLightTypeAmbient
    ambientLightNode.light!.color = NSColor(white: 0.35, alpha: 1.0).CGColor
    // add ambient light the scene
    _sceneView.scene!.rootNode.addChildNode(ambientLightNode)

    // setup onmidirectional light
    let omniLightNode = SCNNode()
    omniLightNode.light = SCNLight()
    omniLightNode.light!.type = SCNLightTypeOmni
    omniLightNode.light!.color = NSColor(white: 0.56, alpha: 1.0).CGColor
    omniLightNode.position = SCNVector3Make(0.0, 200.0, 0.0)
    _sceneView.scene!.rootNode.addChildNode(omniLightNode)

    // add plane
    let myPlane = SCNPlane(width: 125.0, height: 150.0)
    myPlane.widthSegmentCount = 10
    myPlane.heightSegmentCount = 10
    myPlane.firstMaterial!.diffuse.contents = NSColor.orangeColor().CGColor
    myPlane.firstMaterial!.specular.contents = NSColor.whiteColor().CGColor
    _myPlaneNode.geometry = myPlane
    // rotote -90.0 degrees about the y-axis, then rotate -90.0 about the x-axis
    var rotMat = SCNMatrix4MakeRotation(-3.14/2.0, 0.0, 1.0, 0.0)
    rotMat = SCNMatrix4Rotate(rotMat, -3.14/2.0, 1.0, 0.0, 0.0)
    _myPlaneNode.transform = rotMat
    _myPlaneNode.position = SCNVector3Make(0.0, 0.0, 0.0)

    // add physcis to plane
    _myPlaneNode.physicsBody = SCNPhysicsBody(type: .Static, shape: SCNPhysicsShape(geometry: myPlane, options: nil))
    // configure physics body
    _myPlaneNode.physicsBody!.contactTestBitMask = BallType
    _myPlaneNode.physicsBody!.collisionBitMask = BallType
    _myPlaneNode.physicsBody!.categoryBitMask = PlaneType

    // add plane to scene
    _sceneView.scene!.rootNode.addChildNode(_myPlaneNode)
    // add sphere node
    _sceneView.scene!.rootNode.addChildNode(_mySphereNode)

    // gravity folks...
    // first, set the position for field effect
    let gravityField = SCNPhysicsField.linearGravityField()
    gravityField.categoryBitMask = GravityType
    gravityField.active = true
    gravityField.direction = SCNVector3(0.0, -9.81, 0.0)
    print(gravityField.direction)
    gravityField.strength = 10.0
    gravityField.exclusive = true
    _gravityFieldNode.physicsField = gravityField
    _sceneView.scene!.rootNode.addChildNode(_gravityFieldNode)

    // set the default gravity to zero vector
    _sceneView.scene!.physicsWorld.gravity = SCNVector3(0.0, 0.0, 0.0)
}

private func setupBall() {

    let radius = 25.0

    // sphere geometry
    let mySphere = SCNSphere(radius: CGFloat(radius))
    mySphere.geodesic = true
    mySphere.segmentCount = 50
    mySphere.firstMaterial!.diffuse.contents = NSColor.purpleColor().CGColor
    mySphere.firstMaterial!.specular.contents = NSColor.whiteColor().CGColor

    // position sphere geometry, add it to node
    _mySphereNode.position = SCNVector3(0.0, CGFloat(radius), 0.0)
    _mySphereNode.geometry = mySphere

    // physics body and shape
    _mySphereNode.physicsBody = SCNPhysicsBody(type: .Dynamic, shape: SCNPhysicsShape(geometry: mySphere, options: nil))
    _mySphereNode.physicsBody!.mass = 0.125
    _mySphereNode.physicsBody!.contactTestBitMask = PlaneType
    _mySphereNode.physicsBody!.collisionBitMask = PlaneType
    _mySphereNode.physicsBody!.categoryBitMask = (BallType | GravityType)

}

private func stopBall() {

    _mySphereNode.geometry = nil
    _mySphereNode.physicsBody = nil
}

override func awakeFromNib() {

    // assign empty scene
    _sceneView.scene = SCNScene()
    // contact delegate
    _sceneView.scene!.physicsWorld.contactDelegate = self

    setupScene()

    setupBall()
}

@IBAction func moveBall(sender: AnyObject) {

    let forceApplied = SCNVector3Make(5.0, 0.0, 0.0)

    if _mySphereNode.physicsBody?.isResting == true {

        _mySphereNode.physicsBody!.applyForce(forceApplied, impulse: true)
    }
    else if _mySphereNode.physicsBody?.isResting == false {
        print("ball not at rest...")
    }
    else {
        print("No physics associated with the node...")
    }

}

@IBAction func resetBall(sender: AnyObject) {

    // remove the ball from the sphere node
    stopBall()

    // reset the ball
    setupBall()
}

/*** SCENEKIT DELEGATE METHODS ***/
func physicsWorld(world: SCNPhysicsWorld, didBeginContact contact: SCNPhysicsContact) {

    print("we have contact...")

}

func physicsWorld(world: SCNPhysicsWorld, didEndContact contact: SCNPhysicsContact) {

    print("No longer touching...")

}

}


text:
Q: How to make flash synth multiple sounds at the same time I would like to know how I can do THIS:
http://wonderfl.net/c/jcyp
For now, all I could reach in coding is this:
http://wonderfl.net/c/jcyp
When I try to synth multiple strings at the same time it doesn't work.


text:
Q: Invariance of Minkowski sum of sets Given an euclidean space $E$, two sets $A,B\subset E$ and the action on $E$ of two groups $G_A,G_B$ such that $G_A A=A$ and $G_B B=B$, it is possible to generate a group that leaves invariant $A\oplus B$, the Minkowski sum of $A$ and $B$, from the groups $G_A$ and $G_B$?

A: Suppose $A$ and $B$ are compact, then we can assume both groups $G_A$ and $G_B$ fix the origin.
In this case, $A+B$ is invariant for $G_A\cap G_B$.
It is easy to construct example when $G_A\cap G_B$ includes all the symmetries of $A+B$, but in general this group might be much larger.
For example, a round disc is a sum of two Reuleaux triangles.


text:
Q: 3DLBP and GLBP detectors for Depth images Implementation I'm interessting on features extraction from depth images. I have found 3DLBP and GLBP detectors. But i can not found there implementation (Matlab, opencv,...)
I would like to know, if there is any implementation for LBP descriptor for depth images in opencv or c++.
The referenced works are:
3DLBP: Huang, Y., Wang, Y., Tan, T.: Combining statistics of geometrical and correlativefeatures for 3D face recognition.
And Gradient LBP: Tri Huynh, Rui Min, Jean-Luc Dugelay, "An Efficient LBP-based Descriptor for Facial Depth Images applied to Gender Recognition using RGB-D Face Data," in ACCV Workshop on Computer Vision with Local Binary Pattern Variants 2012, Daejeon, Korea, November 2012.
If any one can help me and answer me.
many thanks


text:
Q: Import flink-scala api cause error I am trying import flink scala api on build.sbt as following:
name := "flink_stream"

version := "0.1"

scalaVersion := "2.12.4"

// https://mvnrepository.com/artifact/org.apache.flink/flink-scala
libraryDependencies += "org.apache.flink" %% "flink-scala" % "1.4.0"

and it complains:
sbt.librarymanagement.ResolveException: unresolved dependency: org.apache.flink#flink-scala_2.12;1.4.0: not found

at sbt.internal.librarymanagement.IvyActions$.resolveAndRetrieve(IvyActions.scala:331)

at sbt.internal.librarymanagement.IvyActions$.$anonfun$updateEither$1(IvyActions.scala:205)

at sbt.internal.librarymanagement.IvySbt$Module.$anonfun$withModule$1(Ivy.scala:243)

at sbt.internal.librarymanagement.IvySbt.$anonfun$withIvy$1(Ivy.scala:204)

at sbt.internal.librarymanagement.IvySbt.sbt$internal$librarymanagement$IvySbt$$action$1(Ivy.scala:70)

at sbt.internal.librarymanagement.IvySbt$$anon$3.call(Ivy.scala:77)

at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:93)

at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:78)

at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:97)

at xsbt.boot.Using$.withResource(Using.scala:10)

at xsbt.boot.Using$.apply(Using.scala:9)

at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:58)

at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:48)

at xsbt.boot.Locks$.apply0(Locks.scala:31)

at xsbt.boot.Locks$.apply(Locks.scala:28)

at sbt.internal.librarymanagement.IvySbt.withDefaultLogger(Ivy.scala:77)

at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:199)

at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:196)

at sbt.internal.librarymanagement.IvySbt$Module.withModule(Ivy.scala:242)

at sbt.internal.librarymanagement.IvyActions$.updateEither(IvyActions.scala:190)

at sbt.librarymanagement.ivy.IvyDependencyResolution.update(IvyDependencyResolution.scala:20)

at sbt.librarymanagement.DependencyResolution.update(DependencyResolution.scala:56)

at sbt.internal.LibraryManagement$.resolve$1(LibraryManagement.scala:46)

at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$12(LibraryManagement.scala:99)

at sbt.util.Tracked$.$anonfun$lastOutput$1(Tracked.scala:68)

at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$19(LibraryManagement.scala:112)

at scala.util.control.Exception$Catch.apply(Exception.scala:224)

at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11(LibraryManagement.scala:112)

at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11$adapted(LibraryManagement.scala:95)

at sbt.util.Tracked$.$anonfun$inputChanged$1(Tracked.scala:149)

at sbt.internal.LibraryManagement$.cachedUpdate(LibraryManagement.scala:126)

at sbt.Classpaths$.$anonfun$updateTask$5(Defaults.scala:2381)

at scala.Function1.$anonfun$compose$1(Function1.scala:44)

at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:39)

at sbt.std.Transform$$anon$4.work(System.scala:66)

at sbt.Execute.$anonfun$submit$2(Execute.scala:262)

at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)

at sbt.Execute.work(Execute.scala:271)

at sbt.Execute.$anonfun$submit$1(Execute.scala:262)

at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:174)

at sbt.CompletionService$$anon$2.call(CompletionService.scala:36)

at java.util.concurrent.FutureTask.run(FutureTask.java:266)

at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)

at java.util.concurrent.FutureTask.run(FutureTask.java:266)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)

at java.lang.Thread.run(Thread.java:748)

sbt.librarymanagement.ResolveException: unresolved dependency: org.apache.flink#flink-scala_2.12;1.4.0: not found

at sbt.internal.librarymanagement.IvyActions$.resolveAndRetrieve(IvyActions.scala:331)

at sbt.internal.librarymanagement.IvyActions$.$anonfun$updateEither$1(IvyActions.scala:205)

at sbt.internal.librarymanagement.IvySbt$Module.$anonfun$withModule$1(Ivy.scala:243)

at sbt.internal.librarymanagement.IvySbt.$anonfun$withIvy$1(Ivy.scala:204)

at sbt.internal.librarymanagement.IvySbt.sbt$internal$librarymanagement$IvySbt$$action$1(Ivy.scala:70)

at sbt.internal.librarymanagement.IvySbt$$anon$3.call(Ivy.scala:77)

at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:93)

at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:78)

at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:97)

at xsbt.boot.Using$.withResource(Using.scala:10)

at xsbt.boot.Using$.apply(Using.scala:9)

at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:58)

at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:48)

at xsbt.boot.Locks$.apply0(Locks.scala:31)

at xsbt.boot.Locks$.apply(Locks.scala:28)

at sbt.internal.librarymanagement.IvySbt.withDefaultLogger(Ivy.scala:77)

at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:199)

at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:196)

at sbt.internal.librarymanagement.IvySbt$Module.withModule(Ivy.scala:242)

at sbt.internal.librarymanagement.IvyActions$.updateEither(IvyActions.scala:190)

at sbt.librarymanagement.ivy.IvyDependencyResolution.update(IvyDependencyResolution.scala:20)

at sbt.librarymanagement.DependencyResolution.update(DependencyResolution.scala:56)

at sbt.internal.LibraryManagement$.resolve$1(LibraryManagement.scala:46)

at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$12(LibraryManagement.scala:99)

at sbt.util.Tracked$.$anonfun$lastOutput$1(Tracked.scala:68)

at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$19(LibraryManagement.scala:112)

at scala.util.control.Exception$Catch.apply(Exception.scala:224)

at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11(LibraryManagement.scala:112)

at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11$adapted(LibraryManagement.scala:95)

at sbt.util.Tracked$.$anonfun$inputChanged$1(Tracked.scala:149)

at sbt.internal.LibraryManagement$.cachedUpdate(LibraryManagement.scala:126)

at sbt.Classpaths$.$anonfun$updateTask$5(Defaults.scala:2381)

at scala.Function1.$anonfun$compose$1(Function1.scala:44)

at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:39)

at sbt.std.Transform$$anon$4.work(System.scala:66)

at sbt.Execute.$anonfun$submit$2(Execute.scala:262)

at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)

at sbt.Execute.work(Execute.scala:271)

at sbt.Execute.$anonfun$submit$1(Execute.scala:262)

at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:174)

at sbt.CompletionService$$anon$2.call(CompletionService.scala:36)

at java.util.concurrent.FutureTask.run(FutureTask.java:266)

at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)

at java.util.concurrent.FutureTask.run(FutureTask.java:266)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)

at java.lang.Thread.run(Thread.java:748)

(update) sbt.librarymanagement.ResolveException: unresolved dependency: org.apache.flink#flink-scala_2.12;1.4.0: not found

(ssExtractDependencies) sbt.librarymanagement.ResolveException: unresolved dependency: org.apache.flink#flink-scala_2.12;1.4.0: not found

Total time: 2 s, completed Jan 27, 2018 11:52:30 PM

The project setting is:

What am I doing wrong?

A: As the documentation states, Flink's Scala API depends on Scala 2.11; Scala 2.12 is not supported as of Flink 1.4.0. Change your Scala version to a 2.11 release:
scalaVersion := "2.11.12"


text:
Q: How to append authorized_keys on the remote server with id_rsa.pub key How to append authorized_keys on the remote server with id_rsa.pub key from the local machine with a single command?

A: Adding an authorized key could be one-lined this way (use double-quotes so it's interpreted before sent):
ssh user@server "echo \"`cat ~/.ssh/id_rsa.pub`\" >> .ssh/authorized_keys"

A: You can avoid some of the quoting with:
ssh user@host tee -a .ssh/authorized_keys < ~/.ssh/id_rsa.pub

A: This does the trick:
cat ~/.ssh/id_rsa.pub | (ssh user@host "cat >> ~/.ssh/authorized_keys")

Appends the local public key the remote authorized_keys file.

A: The ssh-copy-id program is the standard way but the key can be appended manually to the ~/.ssh/authorized_keys file:
cat ~/.ssh/id_rsa.pub | ssh username@host "mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys"

This does not check if the key already exists and can lead to duplicates.

A: The most convenient option is the ssh-copy-id command. It can append the public key to ~/.ssh/authorized_keys. For example:
ssh-copy-id -f -i id_rsa.pub username@host

Where:

*

*-f: force mode -- copy keys without trying to check if they are already installed

*-i: [identity_file]

A: ssh-copy-id user@remote_server
http://linux.die.net/man/1/ssh-copy-id


text:
Q: UnknownAttributeError in Controller With the help of @Sasha i created an nested form for treatments in patients:
Now i get this error:
UnknownAttributeError in PatientsController#update

unknown attribute: treatment

My patients update controller actually looks like this:
def update
  @patient = Patient.find(params[:id])

  respond_to do |format|
    if @patient.update_attributes(params[:patient])
      format.html { redirect_to @patient, notice: 'Patient was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: "edit" }
      format.json { render json: @patient.errors, status: :unprocessable_entity }
    end
  end
end

And the form like this:
<%= form_for @patient do |f| %>
  <%= f.fields_for ([@patient, @patient.treatments.build]) do |tf| %>
    <%= render 'treatment_form', form: tf  %>
  <% end %>
  <%= f.fields_for ([@patient, @patient.treatments.build]) do |tf| %>
    <%= render 'treatment_form', form: tf  %>
  <% end %>
  <%= f.submit %>
<% end %>

So i have no clue what i have to add to my patients controller?
I changed my code like @JimLim recomended, but i get the same error:
 ActiveRecord::UnknownAttributeError in PatientsController#update

 unknown attribute: treatment

{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"OPuS9Mmk3guiV20nkw5OaPUFyjVow49H+MMxY37O0r0=",
 "patient"=>{"treatment"=>{"category_id"=>"9",
 "content"=>"dsfsdf",
"day"=>"2013-07-21"}},
"commit"=>"Update Patient",
 "id"=>"9"}

A: The parameters include a treatment key that is not an attribute in your Patient model. If that is the case, you need to

*

*change the form such that the key is treatments instead of treatment, and

*add #accepts_nested_attribute_for in your Patient model.

For example,
<%= f.fields_for :treatments, @patient.treatments.build do |tf| %>
  <%= render 'treatment_form', form: tf  %>
<% end %>

class Patient
  accepts_nested_attributes_for :treatments
end

A more detailed explanation is available in the documentation for fields_for.


text:
Q: integrating a shopping cart, not the other way around ZEN Cart seems to be able to do anything I could possibly ever want, but seems a bit bloated (for me) and more importantly - it's design process seems unbearable. I don't want to have reform a default design, I have my website design completed other than the shopping cart related items. I want to be able to add them in, working the shopping cart into my site, rather than the other way around.  I need a shopping cart that can handle discounts and inventories and such, and of course as small as possible.  Can anyone help recommend an OS cart that will allow this?
Thank so much for your time and suggestions!!

A: You didn't ask for any platform/languages in particular, so.
If you're using Django, then Satchmo looks to be an attractive option.  Even if you're not, it might be fairly trivial to mash in, depending on how your site is set up.

A: You could consider using the cart that Google Checkout provides — is a JS system , easily themed with CSS (if you can learn to accept the !important tag), but SimpleCartJs is as easy as it comes, and it's for PayPal. Re-styles easily and it's pretty elegant.


text:
Q: CSS: Absolute Position Issue In fact I am much familiar with HTML and CSS but when it comes to setup multiple hierarchical div with relative and absolute position giving me damn trouble.
What I have is below

Now I want to align most div on absolute position so I set position relative to #firstdiv now set position absolute to #secdiv and all is going well
Now I want to set my #forthdiv absolute to #thirddiv and so I set #thirddiv to position relative and #forthdiv to position absolute and hear I am getting trouble.
#forthdiv is not considering parent (#thriddiv) relation but it is considering #firstdiv relation and  getting position according to #firstdiv.
Now how to set this all so absolute position div only consider its own parent and not root

A: Try something like this
http://jsfiddle.net/Mcp6L/


text:
Q: Issue with the performance of the query I have two tables tab1 and tab2 each are having two columns acc_num and prod_code. I need to update prod_code in tab2 from tab1. Below is the sample data in both the tables:
TAB1

acnum      Prod
-------------------
1            A
2            B
2            C
3            X
3            X

Tab2

acnum        Prod
-------------------
1            null
2            null
2            null
3            null
3            null

And for the 2nd table after update all the distinct codes should be concatenated. Below is the sample output.
Tab2

acnum       Prod
-------------------
1            A
2            B|C
2            B|C
3            X
3            X

I am able to achieve this through PL/SQL, but it's taking ages to complete. (Actual tables are having millions of records). Below is the code I am using.
DECLARE
  l_acnum dbms_sql.varchar2a;
  l_prod dbms_sql.varchar2a;
  l_prod2 VARCHAR2(10):= NULL;
  l_count NUMBER      := 0;
  CURSOR cr_acnum
  IS
    SELECT DISTINCT(acnum) FROM tab1;
  CURSOR cr_prod(l_acnum_dum IN VARCHAR2)
  IS
    SELECT prod FROM tab1 WHERE acnum = l_acnum_dum;
BEGIN
  OPEN cr_acnum;
  FETCH cr_acnum bulk collect INTO l_acnum;
  CLOSE cr_acnum;
  FOR i IN l_acnum.first .. l_acnum.last
  LOOP
    OPEN cr_prod(l_acnum(i));
    FETCH cr_prod bulk collect INTO l_prod;
    CLOSE cr_prod;
    FOR m IN l_prod.first .. l_prod.last
    LOOP
      IF m          <> 1 THEN
        IF l_prod(m) = l_prod(m-1) THEN
          l_prod2   := l_prod(m);
        ELSE
          l_prod2 := l_prod2||'|'||l_prod(m);
        END IF;
      ELSE
        l_prod2 := l_prod(m);
      END IF;
    END LOOP;
    UPDATE tab2 SET prod = l_prod2 WHERE acnum = l_acnum(i);
  END LOOP;
END;

This pl/sql block is taking ages to complete. Is there anyway I can achieve the same through query rather than PL/SQL or may be by efficient PL/SQL. I tried BULK COLLECT also but of no use. Data is in Oracle DB. Thanks a lot for your time.

A: This will concatenate those values as long as they don't exceed a certain total length.  You may also want to do a subquery to dedupe them if there are any dupes.
Update: here is with LISTAGG
update table2 set Prod = (
SELECT LISTAGG(t1.Prod, ', ') WITHIN GROUP (ORDER BY t1.Prod) "Prod"
  FROM Table1 t1
where t1.acnum = table2.acnum)

A: Thanks everyone for your input. I achived the same using your inputs. I used 2 step solution:
Step 1) Create a lookup table for product and account no.
create table lkup_tbl
as SELECT  acnum, LISTAGG(Prod, '|') WITHIN GROUP (ORDER BY Prod) product
FROM (select distinct acnum, Prod from  tab1) tab
GROUP BY acnum;

Step 2) Now update all the tables by joining this lookup table.
update  tab2 t1
set (t1.Prod)  = (select product from  lkup_tbl t2
where t2.acnum = t1.acnum
);


text:
Q: Simple messaging application...getting errno 14: bad address I am writing a simple messaging application in C using sockets. When I use function recvfrom, it returns -1 and sets errno = 14 which is Bad address (which I am printing at the end).
The strange thing is that it still reads from the socket and gets the correct message. That is, the application is working perfectly and as expected except for that error.
My question is this: Why do you think I am getting this error? I cannot think of any reason. I was using inet_pton to set peer->sin_addr but I was getting the same error.
// socket file descriptor to send data through
int recv_sock_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);

// fill in the peer's address, loopback in this case
struct sockaddr_in *peer = malloc(sizeof(struct sockaddr_in));
peer->sin_family = AF_INET;
peer->sin_port   = htons(11110);
char *new = &(peer->sin_addr);
new[0] = 127;
new[1] = 0;
new[2] = 0;
new[3] = 1;
for (int i = 0; i < 8; i++) {
    peer->sin_zero[i] = NULL;
}

bind(recv_sock_fd, peer, sizeof(struct sockaddr_in));

// check to see if the socket has any data...code removed

char buff[32] = {0};
errno = 0;
int bytes_received = recvfrom(recv_sock_fd, buff, sizeof(buff), NULL, (struct sockaddr *)peer, sizeof(struct sockaddr_in));

printf("Bytes recieved: %d: %d : %s\n", bytes_received, errno, strerror(errno));

A: Look at the signature of recvfrom(2):
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
                 struct sockaddr *src_addr, socklen_t *addrlen);

Last argument is an address, while you are giving it a plain integer.
Then you're building of the IP address is wrong. Do use inet_pton(3), that's what it's for. Also check the return value of the bind(2), it's surely failing now.


text:
Q: Using python to access Excel file in Sharepoint I'm currently trying to access files inside a company Sharepoint (of which I'm the administrator) using Python, but I'm running into some issues.
The first thing I've done was create credentials with tenant permissions using the following tutorial: https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs.
With this, I generated a pair of Client ID and Client Secret, which I would then use to connect to Sharepoint with my Python code.
However, when running my code, I'm getting the following error message:
File "...\office365\runtime\auth\providers\saml_token_provider.py", line 211, in _process_service_token_response
    raise ValueError(self.error)
ValueError: Cannot get binary security token for from https://login.microsoftonline.com/extSTS.srf

Can anybody please tell me if I'm doing something wrong, and what would be the best solution for the problem?
The code I'm currently using is available below.
# Import all the libraries
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
import io
import pandas as pd

# Target url taken from sharepoint and credentials
url = 'https://ORGANIZATION.sharepoint.com/:x:/g/personal/USER/xxxxxxxxxxxxxxxxx'
Client_ID = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
Client_Secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(Client_ID, Client_Secret):
  ctx = ClientContext(url, ctx_auth)
  web = ctx.web
  ctx.load(web)
  ctx.execute_query()
  print("Authentication successful")

response = File.open_binary(ctx, url)

# Save data to BytesIO stream
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0) #set file object to start

# Read excel file and each sheet into pandas dataframe
df = pd.read_excel(bytes_file_obj, sheet_name=None)


text:
Q: I need to include two header files to each other not using forward declaration cause get "incomplete type" error I need to include two header files to each other but I have trouble doing this. Is there any way except using forward declaration and template to do this ? or I'm not allowed to do it in c++?
here is what I want to do:
// A.hpp file
#ifndef H_A_H
#define H_A_H
#include "B.hpp"
class A {
private:
  vector<B*> b;
public:
  void function() {
  // using methods of B
  }
};
#endif

// B.hpp file
#ifndef H_B_H
#define H_B_H
#include "A.hpp"
class B {
private:
  vector<A*> a;
public:
  void function() {
  // using methods of A
  }
};
#endif

A: You can't include two header files to each other. There should be forward declaration in one of the files and function definition has to be pushed to .cpp file where you can include the header file.
// HeaderA.h file
#ifndef H_A_H
#define H_A_H
#include "HeaderB.h"
class A {
private:
  int b;
public:
  void function() {
  // using methods of B
      B b;
      b.function();
  }
};
#endif

// HeaderB.h file
#ifndef H_B_H
#define H_B_H

class A;

class B {
private:
  int a;
public:
  void function();
};
#endif

// Main.cpp
#include "HeaderA.h"
#include "HeaderB.h"

 void B::function()
 {
  // using methods of A
      A a;
      a.function();
 }

int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}

A: You have a cyclic dependency. This answer explains how to deal with them via forward declarations.
This article also deals with cyclic dependencies.
If you 100% don't want to use forward declarations and it is possible you can split logic in a different class and use composition.
// SomeLogic.h
class SomeLogic
{
};

// A.h
#include "SomeLogic.h"
class A
{
    SomeLogic someLogic;
};

// B.h
#include "SomeLogic.h"
class B
{
    SomeLogic someLogic;
};


text:
Q: Tenancy for Laravel - tinker throws up migration files when creating a new tenant I've taken over a project from a prev dev, and I'm trying to understand the tenancy for laravel package, we've past the point of no return on the project to use a new package and to be fair the package and domain is working well for the created subdomain put in by the previous dev, but when I use tinker to create a new tenant and domain, as described in the quick start doc, tinker creates the db, creates the domain and tenant but it seems to fetch a migration file from one of the subdomains too?  Anyone every came across this before?

A: Some of your migration files have the same class name, which is not allowed.
Try using anonymous classes instead and you won't run into this problem. This is possible since laravel 8.37
Instead of
class CreateAgreementSubTypesTable extends Migration { ... }

write
return new class extends Migration { ... }; // semi colon is important.


text:
Q: How to display a Labels 'Error on ErrorProvider1' Goal
I want to display the text that I put in the Label's "Error on ErrorProvider1" attribute whenever I get an error. See the following label's attributes below.

I try to display the text in the red rectangle into my ErrorProvider1 SetError(control, value) function.
 If TextBox1.Text.Trim.Contains("'") Then
    ErrorProvider1.SetError(lblErr, ErrorProvider1.GetError(lblErr))
Else
    ErrorProvider1.SetError(lblErr, "")
End If

How can I retrieve the 'Error on ErrorProvider1' text from the lblErr to display it in the ErrorProvider1 SetError value?

A: The ErrorProvider component is very awkward to use effectively.  It is fixable however, I'll give an example in C# that extends the component with some new capabilities:

*

*ShowError(Control ctl, bool enable) displays the text that you entered at design-time when the enable argument is true.  The easier-to-use version of SetError().

*HasErrors returns true if the any active warning icons are displayed.  Handy in your OK button's Click event handler.

*FocusError() sets the focus to the first control that has a warning icon, if any.  It returns false if no warnings are remaining.

*SetError() is a replacement of ErrorProvider.SetError().  You only need it if you add any controls after the form's Load event fired or if you need to modify the warning text.

Add a new class to your project and paste the code shown below.  Compile.  Drop it from the top of the toolbox onto the form.  The design-time behavior is identical.  Modestly tested.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.ComponentModel.Design;

class MyErrorProvider : ErrorProvider {
    public void ShowError(Control ctl, bool enable) {
        // Easy to use version of SetError(), uses design-time text
        if (!enable) base.SetError(ctl, "");
        else {
            if (errors.ContainsKey(ctl)) base.SetError(ctl, errors[ctl]);
            else base.SetError(ctl, "No error text available");
        }
    }

    public bool HasErrors {
        // True if any errors are present
        get {
            foreach (var err in errors)
                if (!string.IsNullOrEmpty(base.GetError(err.Key))) return true;
            return false;
        }
    }

    public bool FocusError() {
        // Set the focus to the first control with an active error
        foreach (var err in errors) {
            if (!string.IsNullOrEmpty(base.GetError(err.Key))) {
                err.Key.Focus();
                return true;
            }
        }
        return false;
    }

    public new void SetError(Control ctl, string text) {
        // Use this only to add/modify error text after the form's Load event
        if (!string.IsNullOrEmpty(text)) {
            if (errors.ContainsKey(ctl)) errors[ctl] = text;
            else errors.Add(ctl, text);
        }
        base.SetError(ctl, text);
    }

    private void initialize(object sender, EventArgs e) {
        // Preserve error text
        copyErrors(((Form)sender).Controls);
    }
    private void copyErrors(Control.ControlCollection ctls) {
        foreach (Control ctl in ctls) {
            var text = this.GetError(ctl);
            if (!string.IsNullOrEmpty(text)) {
                errors.Add(ctl, text);
                base.SetError(ctl, "");
            }
            copyErrors(ctl.Controls);
        }
    }

    private Dictionary<Control, string> errors = new Dictionary<Control, string>();

    // Plumbing to hook the form's Load event
    [Browsable(false)]
    public new ContainerControl ContainerControl {
        get { return base.ContainerControl; }
        set {
            if (base.ContainerControl == null) {
                var form = value.FindForm();
                if (form != null) form.Load += initialize;
            }
            base.ContainerControl = value;
        }
    }

    public override ISite Site {
        set {
            // Runs at design time, ensures designer initializes ContainerControl
            base.Site = value;
            if (value == null) return;
            IDesignerHost service = value.GetService(typeof(IDesignerHost)) as IDesignerHost;
            if (service == null) return;
            IComponent rootComponent = service.RootComponent;
            this.ContainerControl = rootComponent as ContainerControl;
        }
    }
}

A: Your issue is that you are replacing the error message when nothing is wrong. As noted in your comment below, you are storing the localized error message in the label's Tag, so you can do the following:
If TextBox1.Text.Trim.Contains("'") Then
    ErrorProvider1.SetError(lblErr, lblErr.Tag)
Else
    ErrorProvider1.SetError(lblErr, "")
End If

You were correct to use ErrorProvider1.GetError(Control) to get the value. It's just that you're more than likely replacing it with an empty string before you were retrieving it.


text:
Q: Realm Swift returning objects with all nil values I am using ObjectMapper to parse JSON objects into Realm.
My class Trip looks like this:
class Trip: Object, Mappable {
    dynamic var Id : String? = nil
    dynamic var CreatedOn : String? = nil
    dynamic var LastModified : String? = nil

    required convenience init?(_ map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        Id <- map["Id"];
        CreatedOn <- map["CreatedOn"];
        LastModified <- map["LastModified"];
    }
}

I am calling a web service request using Alamofire:
Alamofire.request(.GET, path, headers: ["Token" : auth_token]).responseJSON { response in

    let dict : NSDictionary? = response.result.value as? NSDictionary

    let test = Mapper<Trip>().map(dict!)
    let realm = try! Realm()
    realm.beginWrite()
    realm.add(test!)
    try! realm.commitWrite()

    let alltrips : Results<Trip> = realm.objects(Trip)
    let firstTrip = alltrips.first
}

In the above code, when I print test, I get:
(AwesomeApp.Trip?) test = 0x0000000154e8f0d0 {
  RealmSwift.Object = {
    Realm.RLMObjectBase = {
      ObjectiveC.NSObject = {}
    }
  }
  Id = "47d86d34-b6f2-4a9f-9e31-30c81a915492"
  CreatedOn = "2016-01-20T23:39:41.995Z"
  LastModified = "2016-01-20T23:44:39.363Z"
}

When I print, firstTrip, I get
(AwesomeApp.Trip?) firstTrip = 0x0000000154f1f370 {
  RealmSwift.Object = {
    Realm.RLMObjectBase = {
      ObjectiveC.NSObject = {}
    }
  }
  Id = nil
  CreatedOn = nil
  LastModified = nil
}

I used the Realm Browser and it looks like the values have been written to the database correctly. However, reading the values returns a trip object with all nil values. Why is this ?
EDIT: I printed allTrips using print (allTrips) and this printed out:
Results<Trip> (
    [0] Trip {
        Id = 47d86d34-b6f2-4a9f-9e31-30c81a915492;
        CreatedOn = 2016-01-20T23:39:41.995Z;
        LastModified = 2016-01-20T23:44:39.363Z;
    }
 )

A: The instance variables of a Realm Object subclass are only used for objects that have not yet been added to a Realm. After an object has been added to a Realm, or for an object that was retrieved from a Realm, the objects getters and setters access data directly from the Realm without the use of the instance variables. This is why the instance variables do not have the values you expect.


text:
Q: how to fix "helm go pkg: err: context deadline exceeded" I'm trying helm go pkg, below error seen when run the code:

2019/04/01 02:30:31 err: context deadline exceeded exit status 1

Helm Version:
# helm version
Client: &version.Version{SemVer:"v2.13.0-rc.2", GitCommit:"b0d4c9eb82e036c52d130fcb031e788dffe5a5dd", GitTreeState:"clean"}
Server: &version.Version{SemVer:"v2.13.0-rc.2", GitCommit:"b0d4c9eb82e036c52d130fcb031e788dffe5a5dd", GitTreeState:"clean"}

K8s version:
kubectl version
Client Version: version.Info{Major:"1", Minor:"10", GitVersion:"v1.10.4", GitCommit:"5ca598b4ba5abb89bb773071ce452e33fb66339d", GitTreeState:"clean", BuildDate:"2018-06-06T08:13:03Z", GoVersion:"go1.9.3", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"10", GitVersion:"v1.10.4", GitCommit:"5ca598b4ba5abb89bb773071ce452e33fb66339d", GitTreeState:"clean", BuildDate:"2018-06-06T08:00:59Z", GoVersion:"go1.9.3", Compiler:"gc", Platform:"linux/amd64"}

package main

import (
    "log"
    "k8s.io/helm/pkg/helm"
)

const (
    tillerHost = "127.0.0.1:44134"
)

func main() {
    helmClient := helm.NewClient(helm.Host(tillerHost), helm.ConnectTimeout(30))
    _, err := helmClient.GetVersion()
    if err != nil {
        log.Fatalf("err: %v", err)
    }
}


text:
Q: i have two fields named as created_at and updated_at(timestamps) and i want to search between these dates in my where clause i want to take input date as a parameter and search between the dates that are given in input.
Theses are the timestamps() provided by laravel to create the two fields as created_at and upated_at.I want to search between these dates that are given in created_at and updated_at but unable to find the data between these dates.
Following is the code that i have create
` $startDate = $request->input('created_at');
  $endDate   = $request->input('updated_at');

->select()
->whereBetween('created_at','updated_at',[$startDate,$endDate])
->get();`

A: I think whereBetween only accepts 2 parameters. The first being the column name and the second the array with values to test. Check: https://laravel.com/docs/5.5/queries#where-clauses
You would want something like:
->whereBetween('created_at', [$startDate,$endDate])
->whereBetween('updated_at', [$startDate,$endDate])

A: The error:

Argument 2 passed to Illuminate\Database\Query\Builder::whereBetween()
  must be of the type array

is because the second parameter of whereBetween() is an array, and you pass a string 'updated_at' here. So change it to like:
->whereBetween('created_at', [$startDate,$endDate])
->whereBetween('updated_at', [$startDate,$endDate])

Reference


text:
Q: Why is there no sizeof in Java? For what design reason is there no sizeof operator in Java? Knowing that it is very useful in C++ and C#, how can you get the size of a certain type if needed?

A: In c is useful only because you have to manually allocate and free memory. However, since in java there is automatic garbage collection, this is not necessary.

A: Because the size of primitive types is explicitly mandated by the Java language.  There is no variance between JVM implementations.
Moreover, since allocation is done by the new operator depending on its argument there is no need to specify the amount of memory needed.
It would sure be convenient sometimes to know how much memory an object will take so you could estimate things like max heap size requirements but I suppose the Java Language/Platform designers did not think it was a critical aspect.

A: In java, you don't work directly with memory, so sizeof is usually not needed, if you still want to determine the size of an object, check out this question.

A: Memory management is done by the VM in Java, perhaps this might help you: http://www.javamex.com/java_equivalents/memory_management.shtml

A: C needed sizeof because the size of ints and longs varied depending on the OS and compiler.  Or at least it used to.  :-)  In Java all sizes, bit configurations (e.g. IEEE 754) are better defined.
EDIT - I see that @Maerics provided a link to the Java specs in his answer.

A: Size of operator present in c/c++ and c/c++ is machine dependent langauge so different data types might have different size on different machine so programmes need to know how big those data types while performing operation that are sensitive to size.
Eg:one machine might have 32 bit integer while another machine might have 16 bit integer.
But Java is machine independent langauge and all the data types are the same size on all machine so no need to find size of data types it is pre defined in Java.


text:
Q: Complex differentiable function Let $U$ be an open set in $\mathbb{C}$ and $f$ differentiable in the real sense. Prove that if $c$ is such that the following limit exists:
$$\lim_{h→0}=\frac{|f(c+h)−f(c)|}{|h|}$$
Then $f$ is differentiable in the complex sense or $\bar{f}$ is differentiable in the complex sense.
$h$ is a complex number.


text:
Q: Disabling reviews in django-oscar Is it possible to completely disable functionality of 'oscar.apps.catalogue.reviews' app in "django-oscar"?
As I see it's used in many places, so simple removal from INSTALLED_APPS doesn't work and perhaps simplest way is to just hide it in templates. Is there better solution?

A: As of version 0.5, there isn't a single setting that will turn reviews on and off: you'll need to perform a few steps.

*

*Remove any references from the templates (as you mentioned).

*Remove the reviews URLs.  This requires you to provide your own app.py for the catalogue app which doesn't link to the reviews app.py.  See http://django-oscar.readthedocs.org/en/releases-0.5/howto/how_to_disable_an_app.html
This is probably more difficult than it should be.  I'll look into providing a setting that disables reviews for 0.6.  Ticket here:
https://github.com/tangentlabs/django-oscar/issues/673


text:
Q: Best architecture for a system calling external slow response API I would like to request some guidelines and advice about a problem being faced.
This is the structure of the system:

*

*Client Desktop Application

*Web Api 1

*Web Api 2

Desktop client calls(HttpPost) => Web API 1 (HttpPost) => Web API 2
Web API 1 is internal and we can control/update it.
Web API 2 is external and we cannot update/improve it.
Client Desktop app is sending a very big amount of data in JSON format and hundreds of requests every day. The data is sent and received to populate local Database in Client Desktop scope.
The bottleneck we have is at Web API 2 , it is very slow and each request sent takes a very long time to be completed. So usually, Web API 1 gets timeouts, and the desktop client also gets timeouts and keeps loading forever. Sometimes the process can take days.
The client desktop is calling via HttpClient to Web API 1.
The approach I see there, is to create an intermediate DB/table at Web Api 1 level, that stores the data that should be sent to Web API 2. We will receive this data from desktop client and then store it in a DB inmediately. Then a process/scheduled job could run to read new records in this intermediate DB/Table and send the data to Web API 2. This process could execute retry logic in case of timeouts or store the data for each request to have a report available to see the progress and the number of errors.
In this case the tables structure could be like Job(JobId/Progress/Status) = > Data Items (Data/AddedDate/Status/ErrorMessage)
To add this intermediate database in the process flow makes sense to you?
Would you recommend other performance-oriented options to solve this scenario? Such as Queues, Cache, No-SQL storage?
Any suggestion or architecture guideline will be appreciated, I am not an architect or expert but I would like to identify what road and approaches can be taken. I think this is a common problem in Data Systems that process high data volumen.

A: Your thoughts regarding architecture are a good starting point.
Client <-> Internal WebApi
So, when the Client sends requests to internal WebAPI then that should be considered as an "ingestion service". It accepts the requests, stores it in intermediate persistent storage and acknowledges back that fact to the client.
HTTP Status Code 202 (Accepted) is usually used for these situations when the request received, accepted but not processed.
The response can (not mandatory) contain an identifier for the request. This can be used to retrieve the processing status:

*

*Internal WebApi might expose a GET endpoint (like /{id}/status)

*

*Client can issue requests based on user demand or can long-poll them in the background

*Or you can use WebSocket between the Client and Internal WebApi, so the service can inform the client about request status changes

Internal WebApi <-> External WebApi
As it was said the internal WebApi acts as an ingestion service. It has a local (in case of High Availability a replicated) storage. If you want to have robust solution (so pending requests can survive service crash) then the storage should be persistent not ephemeral.
The chose of storage depends on a lots of thing like

*

*the payload size,

*retention policy,

*ordering of the requests

*number of consumers

*etc.

So, without knowing the exact requirements and circumstances it is impossible to propose a good solution.
Here I want to emphasize one thing regarding retry. Do not blindly apply retry logic for any request. In order to perform retry logic the following preconditions should be met:

*

*The potentially introduced observable impact is acceptable

*The operation can be redone without any irreversible side effect

*The introduced complexity is negligible compared to the promised reliability

For further details please check out my article regarding retry policy in general.


text:
Q: Iterate to check if column name is equal to another column's value Is there a way to iterate across a dataframe where if a column name is equal to another column's value to input a '1' into that specific cell.
For example:
[A]  [B]  [C]
D
E
B
C

would translate to:
[A] [B] [C]
D
E
B   1
C       1

The null values in B and c would simply be NaN.

A: This will do
df.fillna('').apply(lambda x : x.index==x.name).astype(int).replace(0,"")
Out[563]:
      A  B  C
index
D
E
B        1
C           1


text:
Q: How to let touch events pass through to view below ScrollView I am trying to place a map under another view, so that it can be revealed by scrolling the view on top up. This gif should demonstrate:

This implementation is done with a spacer below the actual content:
var body: some View {
        ZStack {
            //i want to tap this view...
            BackgroundMapCONTENTVIEW()
                .onTapGesture {
                    print("i wish i could be tapped")
                }
            //...but this ScrollView is getting all the user input
            GeometryReader { proxy in
                ScrollView {
                    ZStack {
                        Rectangle()
                            .accentColor(Color.white)
                            .foregroundColor(Color.white)
                            .frame(width: proxy.size.width, height: proxy.size.height, alignment: .top)
                            .allowsHitTesting(false)
                        CompassCONTENTVIEW()
                            .frame(width: proxy.size.width, height: proxy.size.height, alignment: .top)
                    }
                    Spacer()
                        .frame(height: 450.0)
                        .opacity(0.0)
                        .disabled(true)
                        .allowsHitTesting(false)
                }
            }
        }
    }

As you can see I have tried .allowsHitTesting(false) and .disabled(true). But the ScrollView is currently getting all the touch events.
What do I do?


text:
Q: Styles disappear on page reload using GatsbyJS and Material-UI On page reload, styles disappear. On the first load, everything appears normal. This issue does not happen on the local development environment. I'm using GatsbyJS and Material-UI. I have tried placing the plugins in a different order, I have tried changing the styles in my components. I don't understand why it would work in the local development environment but on the cloud it breaks.
In gatsby-config I have Material-UI set up as such:
{
      resolve: `gatsby-plugin-material-ui`,
      options: {
        stylesProvider: {
          injectFirst: true,
        },
      },
    },

gatsby-browser and gatsby-ssr both have this in them:
import React from 'react'
import ThemeProvider from '@material-ui/styles/ThemeProvider'
import theme from './src/components/ui/Theme'
import GlobalContextProvider from './src/context/GlobalContext'
import CartContextProvider from './src/context/CartContext'
import './src/components/layout.css'

export const wrapRootElement = ({ element }) => {
  return (
    <ThemeProvider theme={theme}>
      <CartContextProvider>
        <GlobalContextProvider>{element}</GlobalContextProvider>
      </CartContextProvider>
    </ThemeProvider>
  )
}

require('typeface-roboto')

Here is the website. Even if I link it here, the hero section on the homepage doesn't load, but if you click away (anywhere on the nav) and come back it's there. If you reload, it disappears again but if you click away and come back, it reappears. This is happening on all pages. Why are the styles vanishing?

A: I found the answer. This is currently a known issue from within Gatsby. Hopefully this issue can be resolved quickly because this seems to be a huge problem with Gatsby.
https://github.com/gatsbyjs/gatsby/issues/25729
The workaround for this is to use this code in gatsby-browser.js at the cost of performance:
import ReactDOM from 'react-dom'

export function replaceHydrateFunction() {
  return (element, container, callback) => {
    ReactDOM.render(element, container, callback)
  }
}


text:
Q: Reactjs routing to home page after login success I have created a login page and after successful login I want to move to home page.
I have created a Router in App.js file
class App extends Component {
  render() {
    return (
      <div>
      <Header />
      <BrowserRouter>
      <Switch>
      <Route path="/" component={ Login } exact/>
      <Route path="/login" component={ Home }/>
      <Route component={ Error }/>
      </Switch>
      </BrowserRouter>
      <Footer />
      </div>
    );
  }
}

then in UserLogin component I am using fetch method for login after success response
return fetch('http://localhost:6020/login',
       {
           headers:{
               "Accept": "application/json",
               "Content-Type": "application/json"
           },
           method:'POST',
           body:JSON.stringify(user)
       }
       ).then(response => response.json())
        .then(function(data){
       console.log(data.error);
       if(data.error===null){
        return <Redirect to='/login' />
       }
       else{
           console.log("not working");
       }
    });

In above code I user <Redirect to='/login' /> by importing Redirect from react-router-dom still does nothing no error log nothing.
I just want to show home page after success login

A: try
if(data.error===null){
    window.location.href = '/login'
}

A: if (!data.error){
    this.props.history.push('/')
}

Does this work?

A: you can use redirection inside login page
class Login extends Component{
...
this.state={
   loginSuccess:false
}

inside the the authenticate response
    .then(function(data){
       console.log(data.error);
       if(data.error===null){
        setState({
        loginSuccess:true
})
       }

add the code below in render as
{ this.state.loginSuccess && <Redirect to="/" /> }


text:
Q: Spring Configuration Properties Nested Custom Validation I have nested properties class:
@ConfigurationProperties(prefix = "myapp", ignoreUnknownFields = false)
public class MyAppProperties implements Validator {

    @Valid
    private List<Server> servers = new ArrayList();

    public MyAppProperties() {
    }

    public List<Server> getServers() {
        return this.servers;
    }

    public void setServers(List<Server> servers) {
        this.servers = servers;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return MyAppProperties.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        MyAppProperties properties = (MyAppProperties) target;

        if (isEmpty(properties.getServers())) {
            errors.rejectValue("servers", "myapp.servers", "Servers not provided");
        }
    }

    public static class Server implements Validator {

        private String name;
        private String url;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        @Override
        public boolean supports(Class<?> clazz) {
            return Server.class.isAssignableFrom(clazz);
        }

        @Override
        public void validate(Object target, Errors errors) {
            Server server = (Server) target;

            if (StringUtils.isBlank(server.getName())) {
                errors.rejectValue("name", "server.name", "Server name not provided");
            }

            if (StringUtils.isBlank(server.getUrl())) {
                errors.rejectValue("url", "server.url", "Server url not provided");
            }
        }
    }
}

Now i want the validation to fire for both classes, but when i run with invalid values, the validation fires only for MyAppProperties but not for the list of Servers.
Am i doing something wrong, i'm not able to make this work. I want to use custom validator for both. Can anybody please help me make this work.
The invalid values that i pass are:
myapp.servers[0].name=
myapp.servers[0].url=

But this runs without any error


text:
Q: How to back up your internal hard drive OS before instaling Ubuntu Hi I was wondering how to back up my computer OS and my stuff before formating the hard drive and instaling Ubuntu because I do not want to lose my stuff and my OS. Also I do not want to buy a new hard drive

A: You should back up your hard drive before you install Ubuntu just like you back up your hard drive all the other times you regularly back up your hard drive. If you don't regularly back up, this is a great time to start, whether you continue and install Ubuntu or not. To do this, you need a second hard drive, because you need someplace to copy your files to, someplace off your computer's hard drive for the copies to sit, safe from any disaster that might befall your computer or its hard drive. There is really no other way, short of subscribing to a cloud backup service.
Assuming you're going on to install Ubuntu and keep your current OS (Windows? I can't tell because you talk of saving your OS and formatting your hard drive. You wouldn't want to do both.), you should find a Windows backup solution that works for you. There are lots of programs available to make a copy of your entire hard disk or parts of it to a USB drive. You have to have the USB drive. Buying anything smaller than 2TB is a waste.
Your next problem, assuming you want to save your current OS and install Ubuntu is deciding if you're up to creating a separate partition for your user data so it can be available to you when you boot to your old OS or your new Ubuntu OS. You'll need to look up "ubuntu dual boot" on Google and research your options and see what fits your needs and your skills.

A: i say you should use crashplan so that you can move your files then to linux but the only issue with crashplan is that its a little complex to setup
here it is: http://www.crashplan.com/consumer/crashplan.html
(its a full version if you use it with local and friend computers so dont worry its no virus, if your unsure i made a virus scan here: https://www.virustotal.com/ca/file/5fde5ce803958764f09e21e9bc7a0404a8cfe7dfe74c9d7f374f239d291b4e92/analysis/ (virus total scan))