text:
Q: SWT browser not rendering until shell resize on mac I have a problem with the SWT browser. I am using Mac OS X Yosemite.
The browser is deeply placed in a composite hierarchy. i.e., The shell has say composite A, and composite A has composite B, and composite B has composite C and the Browser is placed inside this composite C. I've added location listeners and progress listeners for the browser.

GridDataFactory, GridLayoutFactory are from org.eclipse.jface.layout package.

Composite compositeC= new Composite(compositeB, SWT.BORDER);

GridLayoutFactory.fillDefaults().numColumns(1).applyTo(compositeC);
GridDataFactory.fillDefaults().grab(true, true).applyTo(compositeC);

Browser browser = new Browser(compositeC, SWT.None);
GridDataFactory.fillDefaults().grab(true, true).applyTo(browser);

browser.addLocationListener(new LocationListener() {
            @Override
            public void changing(LocationEvent event) {

            }

            @Override
            public void changed(LocationEvent event) {

            }

        });

        browser.addListener(SWT.Resize, new Listener() {
            @Override
            public void handleEvent(Event e) {

            }
        });

        browser.addProgressListener(new ProgressListener() {

            @Override
            public void completed(ProgressEvent event) {
                browser.layout(true, true);

            }

            @Override
            public void changed(ProgressEvent event) {

            }
        });

        browser.setUrl("http://eclipse.org");

        compositeC.layout(true);
        compositeC.redraw();

But the page that loads in the browser is not visible until I resize the Shell. I tried redrawing the shell in the completed() method of Progress Listener. But nothing seems to be working.
The same code works perfectly fine in Windows. Is there something I am doing wrong here or some issue with the Webkit rendered on MAC.


text:
Q: Can't render image from the project folder I can't render the image which I have in my project directory src/images/.
I tried to add image-loader to the project but even this doesn't help.

Here's part of my code:
    import React from 'react';
import './styles/styles.scss';

const App = () =>

@kkdimaa

export default App;

full repo: https://github.com/dimakononenko/react-drafts

A: Try this,
    `import img from './src/images/img.jpg'` (check the path)

and in the return function,
    ``

redpajama_set_name: RedPajamaStackExchange


text:
Q: Horn-Schunck Optical Flow (Averaging Velocity) I'm currently trying to implement the HS-method for optical flow but my u and v always seem to have only zeros in them. I can't seem to figure out my error in here:
vid=VideoReader('outback.AVI');
vid.CurrentTime = 1.5;

alpha=1;
iterations=10;

frame_one = readFrame(vid);
vid.CurrentTime = 1.6;
frame_two = readFrame(vid);

% convert to grayscale

fone_gr = rgb2gray(frame_one);
ftwo_gr = rgb2gray(frame_two);

% construct  for each image
sobelx=[-1 -2 -1; 0 0 0; 1 2 1];
sobely=sobelx';
time=[-1 1];

fx_fone=imfilter(fone_gr, sobelx);
fy_fone=imfilter(fone_gr, sobely);
ft_fone=imfilter(fone_gr, time);

fx_ftwo=imfilter(ftwo_gr, sobelx);
fy_ftwo=imfilter(ftwo_gr, sobely);
ft_ftwo=imfilter(ftwo_gr, time);

Ix=double(fx_fone+fx_ftwo);
Iy=double(fy_fone+fy_ftwo);
It=double(ft_fone+ft_ftwo);

% flow-variables (velocity = 0 assumption)
velocity_kernel=[0 1 0; 1 0 1; 0 1 0];

u = double(0);
v = double(0);

% iteratively solve for u and v
for i=1:iterations
    neighborhood_average_u=conv2(u, velocity_kernel, 'same');
    neighborhood_average_v=conv2(v, velocity_kernel, 'same');

    data_term = (Ix .* neighborhood_average_u + Iy .* neighborhood_average_v + It);
    smoothness_term = alpha^2 + (Ix).^2 + (Iy).^2;

    numerator_u = Ix .* data_term;
    numerator_v = Iy .* data_term;

    u = neighborhood_average_u - ( numerator_u ./ smoothness_term );
    v = neighborhood_average_v - ( numerator_v ./ smoothness_term );
end

u(isnan(u))=0;
v(isnan(v))=0;

figure
imshow(frame_one); hold on;
quiver(u, v, 5, 'color', 'b', 'linewidth', 2);
set(gca, 'YDir', 'reverse');

The only thing I'm not really confident about is the computation of the neighborhood average:
velocity_kernel=[0 1 0; 1 0 1; 0 1 0];

u = double(0);
v = double(0);

[..]
neighborhood_average_u=conv2(u, velocity_kernel, 'same');
neighborhood_average_v=conv2(v, velocity_kernel, 'same');

Wouldn't that always result in a convolution matrix with only zeros?
I thought about changing it to the following, since I need to compute the average velocity using the velocity kernel on each pixel of my images:
velocity_kernel=[0 1 0; 1 0 1; 0 1 0];
u = double(0);
v = double(0);

[..]
neighborhood_average_u=conv2(Ix, velocity_kernel, 'same');
neighborhood_average_v=conv2(Iy, velocity_kernel, 'same');

But I still don't know if that would be the correct way. I followed the instructions on the bottom of this MATLAB page:
http://de.mathworks.com/help/vision/ref/opticalflowhs-class.html

A: I found this paper with some further explanations and also some matlab code.
They compute the average of u and v as follows:
% initial values
u = 0; v = 0;

% weighted average kernel
kernel = [1/12 1/6 1/12; 1/6 0 1/6; 1/12 1/6 1/12];

for i = 1:iterations
  uAvg = conv2( u, kernel 'same' );
  vAvg = conv2( v, kernel 'same' );
  ...
end


text:
Q: Authorization in ASP.NET 4 I have a site which is running in ASP.NET 4.0, on Windows 7 Ultimate.
It is using FormsAuthentication, with a nice little logon page, all of which is fine so far as logging in and authenticating.
What is NOT working okay though is directory authorization overriding in sub-directories.
I want both authenticated and non-authenticated users to have access to the inc and images directories, so that the login page can be properly CSS-styled and have the logo and such on the top.
Okay, easy enough, right? I tried allowing anonymous access to these folders both by a <location> tag in the root web.config as so:
<location path="images">
    <system.web>
        <authorization>
            <allow users="*,?" />
        </authorization>
    </system.web>
</location>

as well as individual web.config file in the target directories as so:
<?xml version="1.0"?>
<configuration>
    <system.web>
        <authorization>
            <allow users="*,?" />
        </authorization>
    </system.web>
</configuration>

but for some reason it is not allowing the anonymous user into those directories. I've verified it has to do with authorization by trying to go directly to one of the image's URLs and it fails. But after logging in I can pull it up just fine.
Was something changed in .NET 4.0 with regards to authorization that this would not be working? I've done the same exact thing in 2.0 and 3.5 sites with no problem.

A: Figured this out. I had moved my web site directory from the default. And although IIS had given the IIS_IUSERS group permission to that directory it for some reason did not give the IUSR user rights to the directory. Added him on manually, and BOOM, it worked!


text:
Q: How do I change the password for an NNTP server in Thunderbird? Running Thunderbird 8.0 on Windows 7 Pro 64 bit.
I have an NNTP server that has public and private forums on it.  I thus have two accounts set up, one for NNTP with no credentials, and one with a username/password set.
This works fine, when I first set it up.  But I have about 40 newsgroups subscribed, with up to date read stats on them.
Now, they have changed the username and password on me.
I figured out, in right click Settings on the account Server Settings tab, I can untick Always request authentication when connecting to this server and it will prompt for the password again.
But this time they changed the user name as well on me, and there is no where in the UI to set the username!
I know if I delete and recreate it I can get back in, but that is astonishingly painful, so I would prefer not too.
Any ideas?

A: While I was writing this, I think I figured it out, so I will answer my own question for two reasons.  To share (since I could not find this via Google) and because next year when it happens again I will forget how.
If you look at the Properties of the Account, Server Settings tab, you can get the newsrc path, look two directories higher to get the Profile directory path.
In there, I found a text file, signons.txt (and if you have more than one account they are numbered in order) that holds the base64 encoded usernames AND passwords.  That kind of really sucks as base64 won't stop anything.
The format of the file is:
#2e
.
news://news.server.com (news://news.server.com/#password)

~
*
~aG9xxyz==

---
.
news://news.server.com (news://news.server.com/#username)

~
*
~bab2djIwMTE=

---
.

Names and servers changed to protect the innocent.
Anyway, if you edit this file, (I tried putting in base 64 encoded proper values for username and password) on the next login it prompts you for the username and password again.  So maybe I should have just deleted it, but this seems to be the key file.


text:
Q: Problems with a web based browser I want to develop an asp.net website which gets an address as an input and fetches all contents of the website and changes links and js path and css paths which causes the content to be displayed correctly, and then Response.Write all of this content to my website.
My question is that what's problems with this work, I mean about security. Isn't it dangerous when I write direct content to my page?
meanwhile, I want to change for example any css link like:
http://www.targetdomain.com/style.css

to
http://www.mydomain.com/GetContent.aspx?url=http://www.targetdomain.com/style.css

Thank you.

A: What you want is called a 'proxy' server.
Unfortunately, there's no easy way to get an entire webpage - and all associated content - and feed it back to the requester as a single blob.  You'd have to feed each of the individual pieces back to the requester, modifying links inside the code as necessary to keep them pointing at the right stuff.  This is not an easy task.
Given your location, I'm going to guess that you want this set up quickly.  You might be better off downloading any one of the many, many proxy software packages out there and installing it, rather than trying to write it yourself.
Good luck.


text:
Q: Accessing a samba share, a symlink, on host, to a folder, appears as an empty folder In a server, with Debian 10 and Samba 4.9, there are 2 HDs with this mount points:
/hd1
/hd2

In /hd1 there is a folder that is Samba shared.
/hd1/share

Inside the share I decide to move a folder to /hd2
/hd2/afolder

and create a symlink to it
ln -s /hd2/bigfolder /hd1/share/bigfolder

At server
ls /hd1/share/bigfolder

shows
file1
file2

Accessing the share from a client (Ubuntu 18.04)
smb://server/share/bigfolder

it seams like an empty folder.
I need to see and work in the files (file1 and file2)

A: Solved using the following settings as mentioned here already.
In the "global" section:
allow insecure wide links = yes

In the Share section in question:
follow symlinks = yes
wide links = yes


text:
Q: I am not able to route to a template from the first "/". How can I solve this? My client side code is
Router.configure({layoutTemplate:'layout',loadingTemplate:'loading'});

    Router.route('/thread/:_id',{
name: 'individualthread',
template: 'individualthread',
  waitOn:function(){
  return Meteor.subscribe('forumQuotes',this.params._id)
  },
data: function(){
  var currentThreadRoute=this.params._id;
  return forumQuotesList.findOne({_id:currentThreadRoute});
  }
});

  Router.route('MyHome',{name: 'myHome'});

So when I click on an individual thread, it goes to the thread and the url becomes suppose "localhost:3000/thread/5v6pJSuxvsJyhAA7G".
Then if I click on 'MyHome' href, the  url becomes "localhost:3000/thread/MyHome" and the correct template is not routed to.
I want the url to become "localhost:3000/MyHome".
Can anyone help me on this?
Thanking you all.

A: Router.route('MyHome',{name: 'myHome'});
You can use ../ before Myhome to solve this.
Router.route('../MyHome',{name: 'myHome'});
I hope that this solve your problem. This is my first answer.

A: It's good practice to use pathFor in your HTML for links. This makes your code much easier to manage as routes change.
MyHome

A: This probably has more to do with how you're rendering your links than your router configuration.
You likely have links that look like this:
MyHome

Change them to this:
MyHome


text:
Q: Unable to create dynamic terraform outputs for use in terraform_remote_state I have the following code block for creating various IAM groups
resource "aws_iam_group" "environment-access" {
  count = "${length(var.environments)}"
  name = "access-${element(var.environments, count.index)}"
}

variable "environments" {
  default = ["production", "non-production"]
  type = "list"
}

I want to write the outputs of the IAM groups created in order to grab the ARN of each group to use as data via terraform_remote_state where it would look something like the following
Outputs:

access-production = arn:aws:iam::XXXXXXX:group/basepath/access-production
access-non-production = arn:aws:iam::XXXXXXX:group/basepath/access-non-production

I am having trouble creating the dynamic outputs as I am unsure how to dynamically create the output stanzas based on the the resource originally created as using the below code yields an error referencing unknown resource 'aws_iam_group.access-production' referenced.
output "access-production" {
  value = "${aws_iam_group.access-production.arn}"
}

output "access-non-production" {
  value = "${aws_iam_group.access-non-production.arn}"
}

A: An initial problem with this requirement is that it calls for having a single dynamic list of environments but multiple separate output values. In order to make this work, you'll need to either make the environment inputs separate values or produce a single output value describing the environments.
# Variant with a fixed set of environments (v0.11 syntax)

variable "production_environment_name" {
  type    = "string"
  default = "production"
}

variable "non_production_environment_name" {
  type    = "string"
  default = "non-production"
}

resource "aws_iam_group" "production_access" {
  name = "access-${var.production_environment_name}"
}

resource "aws_iam_group" "non_production_access" {
  name = "access-${var.non_production_environment_name}"
}

output "access_production" {
  value = "aws_iam_group.production_access.arn"
}

output "access_non_production" {
  value = "aws_iam_group.non_production_access.arn"
}

# Variant with dynamic set of environments (v0.11 syntax)

variable "environments" {
  type    = "list"
  default = ["production", "non_production"]
}

resource "aws_iam_group" "access" {
  count = "${length(var.environments)}"

  name = "access-${var.environments[count.index]}"
}

output "access" {
  value = "${aws_iam_group.access.*.arn}"
}

The key here is that the input variable and the output value must have the same form, so that we can make all of the necessary references between the objects. In the second example, the environment names are provided as a list, and the group ARNs are also provided as a list such that the indices correspond between the two.
You can also use a variant of the output "access" expression to combine the two with zipmap and get a map keyed by the environment names, which will probably be more convenient for the caller to use:
output "access" {
  value = "${zipmap(var.environments, aws_iam_group.access.*.arn)}"
}

The new features in Terraform 0.12 allow tidying this up a bit. Here's an idiomatic Terraform 0.12 equivalent of the version that produces a map as a result:
# Variant with dynamic set of environments (v0.12 syntax)

variable "environments" {
  type    = set(string)
  default = ["production", "non_production"]
}

resource "aws_iam_group" "access" {
  for_each = var.environments

  name = "access-${each.key}"
}

output "access" {
  value = { for env, group in aws_iam_group.access : env => group.arn }
}

As well as having some slightly different syntax patterns, this 0.12 example has an additional practical advantage: Terraform will track those IAM groups with addresses like aws_iam_group.access["production"] and aws_iam_group.access["non_production"], so the positions of the environment names in the var.environments list are not important and it's possible to add and remove environments without potentially disturbing the groups from other environments due to the list element renumbering.
It achieves that by using resource for_each, which makes aws_iam_group.access appear as a map of objects where the environment names are keys, whereas count makes it a list of objects.


text:
Q: SQL - create relation to echo data from two tables I made some researchs but couldnt find yet the exact concept needed to achieve this:
::: EDIT ::: my initial request wasnt clear so here I try again
I have two tables,
table_01 with four columns: id / name / address / id_cat
AND
table_02 with two columns: id_cat / category
id_cat in table_01 and table_02 is just an INT(10), while category is a VARCHAR supposed to contain the exact name of the category (which is quite long). What I am trying to do is, when a query is made on table_01, the echo shows rows of table_01 as result, but instead of showing id_cat as a number, it shows the text from table_02 category.
The result shows as I am expecting it, but, if for example in table_02, I have a rowid_cat = 1 , category = AAAAA, I would like to echo the id_cat from table_01 as the category from table_02, so still for example, 002 | standon | 125 market street | AAAAA instead of what I get now, which is 002 | standon | 125 market street | 1.
I didnt create relation between both tables yet.

A: If I understand what you are after, your query for the data would just need to be something like:
select t1.id as id, t2.category as category from tab_01 as t1
left join tab_02 as t2 on t1.id_cat = t2.id_cat where t1.id = '5';

The 5 is obviously the id you are looking for in tab_01.

A: I am not fully clear about your question. But I think this will help you.
Right now you have created one-to-many relationship between this two tables. This means one category (tab_02) can have multiple tab_01 data.
You can try this query:
SELECT t1.id_cat AS id_cat_number, t2.*
FROM tab_02 t2
INNER JOIN tab_01 t1 ON t1.id_cat = t2.id_cat
WHERE t2.category = XXXXXXXX


text:
Q: Login fetch data fast using linq I have two table UserTable and DeviceTable, whenever user register devcieUUID store in DeviceTable. In UserTable DeviceId primary key of DeviceTable store in UserTable. I want to check deviceUUID is exsit in DeviceTable and bring particular UserId assign in deviceId using linq and in fastest way.

UserTable

 userId userName deviceId
  1       xx1       2
  2       dd2       3
  3       cc3       4

DeviceTable

 deviceId deviceUUID
  1       xx1
  2       dd2
  3       cc3

A: _context.DeviceTable.where(dt=>dt.deviceUUID == @deviceUUID).select(dt=>dt.deviceId).FirstOrDefault();

Note: Replace @deviceUUID by UUID with which you want to compare and if exist in DeviceTable then deviceId will be returned from DB else default 0 will be returned.


text:
Q: SQL update with two tables I have 2 tables, 1 is current and 1 is log.
If current have any changed, will update the state from 0 to 1 and copy whole table to log table.
May I know the update statements?
<CURRENT>
Date            Name          Money  Currency       Money_Change     Currency_Change
10/1/2014       ABC           14       HKD            0  -> 1              0
10/1/2014       BCD           11       USD            0                    0  -> 1
10/1/2014       DCE           18       RMB            0  -> 1              0  -> 1

<LOG>
Date            Name          Money   Currency
7/1/2014        ABC           2         HKD
7/1/2014        BCD           11        EUR
7/1/2014        DCE           16        CAD
2/1/2014        ABC           10        HKD
2/1/2014        BCD           12        RMB
2/1/2014        DCE           1         CAD
1/1/2014        ABC           10        HKD
1/1/2014        BCD           12        RMB
1/1/2014        DCE           16        USD

A: This is a very weird way to log changes. your log table will grow immensely. Do you want to insert changes before or after change? If after change do it like this:
UPDATE CURRENT SET MONEY=1
INSERT INTO LOGS
SELECT * from CURRENT


text:
Q: How can I insert large files in MySQL db using PHP? I want to upload a large file of maximum size 10MB to my MySQL database. Using .htaccess I changed PHP's own file upload limit to "10485760" = 10MB. I am able to upload files up to 10MB without any problem.
But I can not insert the file in the database if it is more that 1 MB in size.
I am using file_get_contents to read all file data and pass it to the insert query as a string to be inserted into a LONGBLOB field.
But files bigger than 1 MB are not added to the database, although I can use print_r($_FILES) to make sure that the file is uploaded correctly. Any help will be appreciated and I will need it within the next 6 hours. So, please help!

A: As far as I know it's generally quicker and better practice not to store the file in the db as it will get massive very quickly and slow it down. It's best to make a way of storing the file in a directory and then just store the location of the file in the db.
We do it for images/pdfs/mpegs etc in the CMS we have at work by creating a folder for the file named from the url-safe filename and storing the folder name in the db. It's easy just to write out the url of it in the presentation layer then.

A: Some PHP extensions for MySQL have issues with LONGBLOB and LONGTEXT data types.  The extensions may not support blob streaming (posting the blob one segment at a time), so they have to post the entire object in one go.
So if PHP's memory limit or MySQL's packet size limit restrict the size of an object you can post to the database, you may need to change some configuration on either PHP or MySQL to allow this.
You didn't say which PHP extension you're using (there are at least three for MySQL), and you didn't show any of the code you're using to post the blob to the database.

A: The best answer is to use an implementation that is better and also works around that issue.
You can read an article here.  Store 10MB, 1000MB, doesn't matter.  The implementation chunks/cuts the file into many smaller pieces and stores them in multiple rows.. This helps with load and fetching so memory doesn't also become an issue.

A: You could use MySQL's LOAD_FILE function to store the file, but you still have to obey the max_allowed_packet value and the fact that the file must be on the same server as the MySQL instance.

A: You will want to check the MySQL configuration value "max_allowed_packet", which might be set too small, preventing the INSERT (which is large itself) from happening.
Run the following from a mysql command prompt:
mysql> show variables like 'max_allowed_packet';

Make sure its large enough. For more information on this config option see
MySQL max_allowed_packet
This also impacts mysql_escape_string() and mysql_real_escape_string() in PHP limiting the size of the string creation.

A: You don't say what error you're getting (use mysql_error() to find out), but I suspect you may be hitting the maximum packet size.
If this is the case, you'd need to change your MySQL configuration max_allowed_packet

A:
You don't say what error you're getting (use mysql_error() to find out), but I suspect you may be hitting the maximum packet size.
If this is the case, you'd need to change your MySQL configuration max_allowed_packet

Well I have the same problem. And data cannot be entered in the mysql database chunck by chunck in a "io mode"
loop for :
   read $data from file,
   write $data to blob
end loop
close file
close blob

A solution seems to create a table with multi-part blobs like
create table data_details
(
id int pk auto_increment,
chunck_number int not null,
dataPart blob
);
???


text:
Q: Array to string conversion error PHP array(2) {
[0]=> object(stdClass)#460 (1) { ["deskripsi"]=> string(14) "Embedded teeth" }
[1]=> object(stdClass)#461 (1) { ["deskripsi"]=> string(14) "Impacted teeth" }
}

That is my array result after I vardump from database query.
Then I want to get text Embedded teeth and Impacted teeth
Can someone please help me?

A: You have an array of objects, the code below should help point you in the right direction
$objects = $myObj;
foreach($objects as $object){
    echo $object->deskripsi;
}


text:
Q: Summation of trig functions I am having difficulty performing the following summation. I think there might be simple sum, but i am unable to see how to get there. Any help would be much appreciated.
$$\sum_{m=1}^{N-1} \frac{sin\left(\frac{\pi m}{N}\right)sin\left(\frac{\pi n m}{N}\right)}{sin^2\left(\frac{\pi m}{2N}\right)}$$
Note that n and N are positive integers.
Many thanks
Lee


text:
Q: Java-8 stream - cast list of sub types to list of super types I have the following stream:
final List<List<ScheduleContainer>> scheduleIntervalContainerOfCurrentDay = new ArrayList<>(
        unconfirmedScheduleIntervalContainersOfWeeks.stream()
            .sorted(Comparator.comparing(ScheduleIntervalContainer::getStartDate).reversed())
            .filter(s -> s.getStartDate().withTimeAtStartOfDay().isEqual(today.withTimeAtStartOfDay()))
            .collect(Collectors.groupingBy(ScheduleIntervalContainer::getStartDate, LinkedHashMap::new, Collectors.toList())).values());

and at the end I will cast from List of type List<ScheduleIntervalContainer> to List of type List<ScheduleContainer> (ScheduleIntervalContainer is a subtype of ScheduleContainer). Is there a way of doing this?

A: You can collect the items into lists of the more general type by specifying the type parameter to use for toList:
Collectors.<ScheduleContainer>toList()


text:
Q: Problema con redux-saga y firebase al ejecutar un actions Estoy intentando activar un action en la ejecución de una saga, el problema es que el Action nunca se activa, este es el código:
import firebase from 'react-native-firebase';

function authorize(query) {
  console.log(query.size);
  if(query.size){
    query.forEach(doc => {
      console.log(doc.data());
      put(loginActions.setLoginSuccess(doc.data()));
    });
  } else {
    put(loginActions.setError({ error: 'El usuario no existe' })); //Nunca se ejecuta esta acción
    return undefined;
  }
}

export function* loginFlow() {
  while (true) {
    const {username, password} = yield take(actions.LOGIN_ACTION);
    const ref = firebase.firestore().collection('usuarios');
    ref
    .where('email', "==", username)
    .where('contrasena', "==", password)
    .onSnapshot(authorize);
  }
}

La ejecución se lleva perfectamente hasta que llega el LoginAction.setError, no se ejecuta correctamente he hecho un console.log en el reducer, pero nunca entra. Supongo que debe haber otra forma de implementar y ejecutar el onSnapshot. Agradesco de antemano.


text:
Q: RESTORE detected an error on page (0:0) in database  as read from the backup set I'm attempting to restore a SQL Server 2012 .BAK file to my local server. I've successfully restored this .BAK file before. However now, when I try, I get the following error:
RESTORE detected an error on page (0:0) in database 'databasename' as read from the backup set.
Running the following command works:
RESTORE HEADERONLY FROM DISK = 'D:\database.bak'

However, running the following:
RESTORE VERIFYONLY FROM DISK = 'D:\database.bak'

Returns the following error:
Msg 3203, Level 16, State 1, Line 1
Read on "D:\database.bak" failed: 13(The data is invalid.)
Msg 3013, Level 16, State 1, Line 1
VERIFY DATABASE is terminating abnormally.

I downloaded the .BAK file from an FTP server again this morning and got the same error. I asked someone else with access to the same backup file and they can restore it with no issues at all. Any ideas?

A: Check that you are downloading with binary transfer mode using FTP.  Most clients will try to autodetect, then fall back to binary.  .bak may not be recognized as binary, and may therefore have all \n's translated to \r\n, corrupting the data.
If that is not the case, make sure the server version you are attempting to restore with is newer or equal to the server version the original backup was taken with.  See SELECT @@VERSION for an easy to compare check.
Beyond that, assuming the original backup works fine elsewhere, do a binary checksum of both files... perhaps some disk error or other transfer is causing corruption.  You can use fciv.exe -add c:\database.bak or a similar utility to calculate the checksum.
It is also possible to take a good backup of a corrupt database.  The original database could be corrupt -  I don't know why it would have restored successfully elsewhere, but it could happen.  You can verify the original database by running DBCC CHECKDB('DatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS on the server the backup was taken on.


text:
Q: WindowManagerBadTokenException for AccessibilityService Overlay I am creating an accessibility service using Xamarin and Visual Studio, following this Codelab (Java + Android SDK): https://codelabs.developers.google.com/codelabs/developing-android-a11y-service/#0
The accessibility service is up and running with it being found in Settings > Accessibility in my android device.
Service:
    [Service(Label = "Input Utility", Permission = Manifest.Permission.BindAccessibilityService)]
    [IntentFilter(new string[] { "android.accessibilityservice.AccessibilityService" })]
    [MetaData("android.accessibilityservice", Resource = "@xml/config")]
    public class TapService : AccessibilityService
    {
        FrameLayout mLayout;
        public override void OnAccessibilityEvent(AccessibilityEvent e)
        {

        }

        public override void OnInterrupt()
        {

        }

        public override bool OnUnbind(Intent intent)
        {
            return base.OnUnbind(intent);
        }

        protected override void OnServiceConnected()
        {

            base.OnServiceConnected();

            IWindowManager wm = Application.Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
            mLayout = new FrameLayout(this);
            WindowManagerLayoutParams lp = new WindowManagerLayoutParams();
            lp.Type = WindowManagerTypes.AccessibilityOverlay;
            lp.Format = Format.Translucent;
            lp.Flags |= WindowManagerFlags.NotFocusable;
            lp.Width = WindowManagerLayoutParams.WrapContent;
            lp.Height = WindowManagerLayoutParams.WrapContent;
            lp.Gravity = GravityFlags.Top;
            LayoutInflater inflater = (LayoutInflater)Application.Context.GetSystemService(Context.LayoutInflaterService);
            inflater.Inflate(Resource.Layout.InputBar, mLayout);
            wm.AddView(mLayout, lp);

        }
    }

Layout File(InputBar.xml):
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/power"
        android:text="Power"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/volume_up"
        android:text="Volume"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/scroll"
        android:text="Scroll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/swipe"
        android:text="Swipe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

Metadata file (config.xml):
<?xml version="1.0" encoding="utf-8" ?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
   android:settingsActivity="true"
   android:accessibilityFeedbackType="feedbackGeneric"
   android:accessibilityFlags="flagDefault"
   android:canPerformGestures="true"
   android:canRetrieveWindowContent="true" />

However I am getting an error when I try to add the overlay to the screen at wm.AddView(mLayout, lp);, it gives me this error: Android.Views.WindowManagerBadTokenException Message=Unable to add window -- token null is not valid; is your activity running?.
I understand that in the official codelab it tells me to launch like so:

I suspect this may be the source of the error I'm getting, however I am not on android studio, I am using Visual Studio and do not know what to do with this.
To reproduce my error simply clone my github repository, run it, then while it is running, go to the Settings > Accessibility of your android emulator and enable the "Input Service" accessibility service.
Github Repository: https://github.com/tatapuchi/XamarinAccessibilityService

A: To test this function, please mark sure the Settings.CanDrawOverlays has been enabled. Try detect the status before starting the service.
using Android.Provider;
...

if (!Settings.CanDrawOverlays(this))
{
    StartActivityForResult(new Intent(Settings.ActionManageOverlayPermission, Android.Net.Uri.Parse("package:" + PackageName)), 0);
}
else
{
    StartService(new Intent(this, typeof(DemoService)));
}

...
public override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);

    if (requestCode == 0)
    {
        if (!Settings.CanDrawOverlays(this))
        {
        }
        else
        {
            StartService(new Intent(this, typeof(DemoService)));
        }
    }
}

Update:
Here is the related code about the sample:
public class MainActivity : AppCompatActivity
{
    public AccessibilityServiceBinder binder;
    public AccessibilityServiceConnection accessibilityServiceConnection;
    public bool isBound = false;
    bool isBoundAC = false;
    Intent ServiceIntent;

    protected override void OnStart()
    {
        base.OnStart();
        if (!isBoundAC)
        {
            accessibilityServiceConnection = new AccessibilityServiceConnection(this);
            isBoundAC = BindService(ServiceIntent, accessibilityServiceConnection, Bind.AutoCreate);
            if (isBoundAC)
            {
                Toast.MakeText(this, "AccessibilityService is Bound", ToastLength.Long);
            }
        }
    }

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        SetContentView(Resource.Layout.activity_main);

        ServiceIntent = new Intent(this, typeof(TapService));
        ServiceIntent.SetPackage("com.companyname.app19_3_1");

        FindViewById<Button>(Resource.Id.btn).Click += async delegate
        {
            if (!Settings.CanDrawOverlays(this))
            {
                StartActivityForResult(new Intent(Settings.ActionManageOverlayPermission, Android.Net.Uri.Parse("package:" + PackageName)), 0);
            }
        };
    }
}

public class AccessibilityServiceBinder : Binder
{
    TapService service;
    public AccessibilityServiceBinder(TapService service)
    {
        this.service = service;
    }
    public TapService GetAccessibilityService()
    {
        return service;
    }
}

public class AccessibilityServiceConnection : Java.Lang.Object, IServiceConnection
{
    MainActivity activity;
    AccessibilityServiceBinder binder;
    public AccessibilityServiceBinder Binder
    {
        get
        {
            return (AccessibilityServiceBinder)binder;
        }
    }
    public AccessibilityServiceConnection(MainActivity activity)
    {
        this.activity = activity;
    }
    public void OnServiceConnected(ComponentName name, IBinder service)
    {
        var accessibilityServiceBinder = service as AccessibilityServiceBinder;
        if (accessibilityServiceBinder != null)
        {
            activity.binder = accessibilityServiceBinder;
            activity.isBound = true;
            this.binder = accessibilityServiceBinder;
        }
    }
    public void OnServiceDisconnected(ComponentName name)
    {
        activity.isBound = false;
    }
}

[Service(Label = "Input Utility", Permission = Manifest.Permission.BindAccessibilityService, Enabled = true)]
[IntentFilter(new string[] { "android.accessibilityservice.AccessibilityService" })]
[MetaData("android.accessibilityservice", Resource = "@xml/config")]
public class TapService : AccessibilityService
{
    FrameLayout mLayout;
    ...
    protected override void OnServiceConnected()
    {
        base.OnServiceConnected();

        IWindowManager wm = GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
        WindowManagerLayoutParams lp = new WindowManagerLayoutParams();
        lp.Type = WindowManagerTypes.AccessibilityOverlay;
        lp.Format = Format.Translucent;
        lp.Flags |= WindowManagerFlags.NotFocusable;
        lp.Width = WindowManagerLayoutParams.WrapContent;
        lp.Height = WindowManagerLayoutParams.WrapContent;
        lp.Gravity = GravityFlags.Top;
        LayoutInflater inflater = (LayoutInflater)GetSystemService(Context.LayoutInflaterService);
        View view = inflater.Inflate(Resource.Layout.layoutfloat, null);
        wm.AddView(view, lp);
    }
}


text:
Q: How do I carry search parameter values on another page in PHP I've got an advanced parameterized query, the user sets the parameters and accordingly the query is build. I point the action of the form to a result page and on that page I fetch values using $_POST.
I get these values correctly but the moment I refresh the page I lose the values of $_POST. Do I need to use $_SESSION for this? Because I don't want so many sessions, then I had to unset all once the user has used them, so how do I do it?
Form
<form action="result.php?script_id=3&sub_script_id=1">
Search For
<select id="search_for" name="contact_first_name">
<?php
    while($throw_names = mysqli_fetch_array($fetch_advance_param_values)) {
?>
    <option value="<?php echo $throw_names['contact_first_name']; ?>"><?php echo $throw_names['contact_first_name']; ?></option>
<?php
    }
?>
</select>

</form>

results.php
<?php
$fetch_results = mysqli_query($running_db,
"SELECT rec_num, record_locked, contact_first_name, contact_last_name,
contact_mobile_no, contact_office_no FROM tbl_contacts WHERE
contact_first_name = '{$_POST['contact_first_name']}'
AND group_id_entry={$_SESSION['user_group_id']}
ORDER BY $sort_column_name $sort_order $limit_records");
?>

Don't worry, right now am directly using $_POST['contact_first_name'] in my query, this is just for test purpose, later I'll use mysqli_real_escape_string()

A: I don't get why you are concerned about using sessions or GET parameters. A search form is usually implemented with GET anyways.
But there is another option: save the search itself in the database (then a POST form actually makes sense):

*

*search form gets submitted

*save search query as new row in a searches table

*redirect to something like /searches/?id=1234

*on that page, rebuild the search query from the searches table and execute it

At first glance this solution looks a bit overkill but it offers new possibilities like caching a search result or offer the user to save favorite searches. So there are scenarios where this approach makes sense.

A: In the first page where the post is sent to:
setcookie('searchquery','I want cookies');

in page 2
if(isset($_COOKIE['searchquery']))
    {
    $search = mysqli_real_escape_string($link,$_COOKIE['searchquery']);
    }


text:
Q: read file using javascript I'm trying to read and parse a text file using JQuery and the code I'm using seems to error out.
//Attempt 6
alert("Test Alert 9"); //js file does load into index.html
$.get( "exchanges.txt",
    function( data ) {
        //idk what the following two lines do, I got them from:
        //http://api.jquery.com/jquery.get/
  $( ".result" ).html( data );
  alert("check it");
    })
    //should execute if works?
    .done(function() {
        alert( "second success" );
    })
    //should execute if any error
    .fail(function() {
        alert( "error" );
    })
    .always(function() {
        alert( "finished" );
    });

The following alerts print:

*

*"Test Alert 9"

*"error"

*"finished"

My question:
Is there a way to check what the error is?
And/or does anyone know what the error might be?
Edit: for clarification, the exchanges.txt file is located in the same folder as the js file
Edit: Updated to throw error to console. Error prints:
 XMLHttpRequest cannot load      file:///C:/Users/Invictus/Documents/GitHub/BTCExchangesMaterialize/exchanges.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Fixed this error by moving the exchanges.txt to the main folder instead of the js/ folder.
New error:
    XMLHttpRequest cannot load
file:///C:/Users/Invictus/Documents/GitHub/BTCExchangesMaterialize/exchanges.txt.
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.jquery-2.1.1.min.js:4 n.ajaxTransport.k.cors.a.crossDomain.sendjquery-2.1.1.min.js:4 n.extend.ajaxjquery-2.1.1.min.js:4 n.each.n.(anonymous function)exchangesParser.js:3 (anonymous function)

A: in your fail function, pass the response. Then you can play with the response object. Inspect your browser's console(developer tools)
 .fail(function( response) {
        console.log("my error response is",response);
        alert( "error" );
    })

A: $.get is a shorcut for $.ajax with some settings pre-enabled.
Signature of $.get is:
$.get([String] url, [Object|String] urlparams, [Closure] callback);

callback is excecuted AFTER AJAX QUERY HAD SUCCESS.

If you plan to use jQuery promises way, you omit the success callback, and use its promises methods, .done(), .fail() and .always()
Success Callback Way
$.get( "exchanges.txt", function( data ) {
    $( ".result" ).html( data );
    alert("checked it");
});

Promises Way
$.get( "exchanges.txt")
.done(function( data ) {
    $( ".result" ).html( data );
    alert("checked it");
})
.fail(function() {
    alert( "error" );
})
.always(function() {
    alert( "finished" );
});

As can be seen, promises way its more specific on handlers, since you can call a function an more points that get, this is because $.get (as I mentioned before) is a shorcut for $.ajax. Take a look of $.get call expanded to $.ajax:
$.ajax Way
$.ajax({
    url: "exchances.txt",
    success: function(data){
        $(".result").html(data);
        alert("checked it");
    },
    error: function(response){
        alert("error");
    },
    complete: function(response){
        alert("done");
    },
});

Just keep in mind that AJAX Request CAN NOT BE DONE to local files when referencing it with file:// you should access them through http (apache, node), ftp or whatever other protocol u want, but never under file://
Read more:
jQuery promises
jQuery ajax


text:
Q: htaccess why is site redirecting to // In my htaccess I am redirecting all non https to https.
It works, but its also adding in an extra '/', so the url is
'https: //www.[MY SITE URL].co.uk//'
Why is this? To be honest, I don't really know what all this in my htaccess is doing, its copied from googling answers to 'redirect all requests to https'
My htaccess:
Options -MultiViews
RewriteEngine On    # Turn on the rewriting engine

RewriteBase /

#RewriteCond %{HTTP_HOST} ^(www\.)?jobooz\.com  [NC]
#RewriteRule ^(.*)$  https://www.jobooz.co.uk/$1     [R=301,L,NC]

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI}/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}/$1

RewriteRule    ^/?$    /php/index.php    [NC,L]    # Home page

I've also noticed any deeper urls like '/search-jobs/jobs-near-me' that I add to the url then get duplicated too, to '/search-jobs/jobs-near-me/search-jobs/jobs-near-me' when redirected to https.
All urls work fine if I go directly to the https version.
Any help appreciated, thanks.

A: The following rewrite rule has a problem:
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI}/$1 [R=301,L]

The gist of why you are seeing repeated fragments in the rewritten URL is that (.*) matches everything, and that already includes the host and URI.  Instead, you can try redirecting any incoming request on port 80 to HTTPS.
RewriteCond     %{SERVER_PORT} ^80$
RewriteRule     ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]


text:
Q: Oracle cloud Infrastructure - what is equivalent component of AWS CloudFormation template What is the equivalent component of AWS CloudFormation Template in Oracle Cloud?
I see Oracle Cloud Stack Manager and corresponding templates. However, I don't find them very useful for the scenarios where to launch infrastructure component stack (e.g., with few instances behind a load balancer and with some specific security groups created and attached to them. load balancer listening to specific ports). Oracle cloud stack elements are based on Platform services like Database, Java etc.,
However I tried to edit existing template and didn't find all the resource types for my specific scenario.
https://docs.oracle.com/en/cloud/paas/cloud-stack-manager/csmug/list-resource-types.html
Thank you in advance!

A: The Best option would be to use Terraform. Terraform is an infrastructure as a code tool with similar or I'd say even better capabilities than Cloud Formation.
Try this link to get an idea about working with Terraform and Oracle Cloud.


text:
Q: ffmpeg not opening in Windows 10 I downloaded ffmpeg from https://www.gyan.dev/ffmpeg/builds/
ffmpeg-release-full.7z

I have extracted it in C: drive. I can see ffmpeg in bin folder of extracted zip.
When I try to run it using command prompt in Windows 10,

it says:

This app can't run on your PC
I also tried setting compatibility mode to Windows 7 for this program through properties, but still same problem.
Output of SET PROC command:


text:
Q: how to export a specific category mysql so I have 8 category's with products and now I wanna build a website on a specific category I have in the big database 7500 products and I want to export only products with a specific category
database looks like this
id , productid, category, description, price, rating

and now I want to export only products from category 1
So I have to
SELECT category=2 from dbtable where rating=1

and then I want to export  .. this is not working .. I'm not good in to SQL .. so I need
advice - thank you !

A: The single solution I found till now is this
  MANUAL on PHPMyAdmin
Go to database select table > Search > Category LIKE 2 go down to options Number of rows per page to display 500 click on Go after that will result the first page with the 500 products , select all and click export - and I think i have to do this untill i finish to export all db
SELECT * FROM dbtable WHERE category LIKE '2'

A: why not just do
SELECT * FROM dbtable WHERE category = 2 AND rating = 1;

that will get you all of the rows with category = 2
am I missing something or is that all you wanted??

A: I also found some other solution to get that products if u have a bigger database and u need to exclude some categories ..
be aware that before to back-up your database cos we will delete from database
here it is
DELETE FROM dbtable WHERE category LIKE '1';
DELETE FROM dbtable WHERE category LIKE '2';
DELETE FROM dbtable WHERE category LIKE '3';
DELETE FROM dbtable WHERE category LIKE '4';
DELETE FROM dbtable WHERE category LIKE '5';
DELETE FROM dbtable WHERE category LIKE '6';
DELETE FROM dbtable WHERE category LIKE '7';

and u get result of category 8 only - my case :)


text:
Q: How To Use AFNetworking On Background Thread? I have an app currently using AFNetworking 1.0 to sync data from a REST Web Service.
When the sync occurs currently by tapping a button on the UI it blocks the UI.
I'm upgrading the app to use AFNetworking 2.0.
How can I make the sync happen on a background thread so the UI does not stall?

A: Did you try this:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://gowalla.com/users/mattt.json"]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"Name: %@ %@", [JSON valueForKeyPath:@"first_name"], [JSON valueForKeyPath:@"last_name"]);
} failure:nil];

Check the following link
https://github.com/AFNetworking/AFNetworking/wiki/Introduction-to-AFNetworking


text:
Q: Re-using Yii Framework CValidator Rules on Client Side I'm trying to figure out a way to re-use the validation rules of Yii's CValidator classes, for example CStringValidator (http://www.yiiframework.com/doc/api/1.1/CStringValidator).
I'm thinking if I can get the rules in JSON-format, I can pass the json to the javascript and build a validator function to enforce them (or build the javascript on the PHP side and send the script down to the client).
Does Yii provide anyway serialize-type method to take a validator such as CString and dump out the "rules" it uses to do validation? (something like /[\d\w]+/, just to give a simplistic example)?
Due to the nature of this project we're not able to use CActiveForm (which provides built-in client-side form validation).

A: You could write an action that would return the rules in JSON pretty easily.
public function actionGetRules()
{
    echo CJSON::encode(Model::rules());
}


text:
Q: causal effects when y is continuous and discontinuous over time I am interested in estimating the causal effects of A(treatment) on Y(outcome). Here treatment is a binary variables (yes vs no). Outcome is a continuous variable(weight), and this is normalized to Z scores. The main issues is outcome , not measured at all time intervals. When the time range spans is from 1994-2019. Outcome is measured between 1994-1999 and 2002-2019. Outcome is not measured between 1999-2002. My question is , how do I analyze data where y is discontinuous in time. What are the precautions necessary before fitting linear or any suitable models for this type of data ? Thanks in advance.

A: From the plot you provide I do not see a significant trend of body weight over time.
You can try to fit a regression to see if the coefficient of time is significant statistically (p value) or practically (effect size compared to outcome scale). My guess is it won't be, so you can just proceed to calculate average treatment effect.
If your no-treatment group is not randomly assigned, and it's not a good natural experiment setting to begin with, you should consider using causal inference techniques such as propensity score matching to reduce the bias from the assignment mechanism.


text:
Q: Generalized linear mixed-effects model and Interaction of Continuous and Dummy Categorical variable Standardised vs Non-Standardised? I have run a GLMER on some data and I have 3 random variables (Year,Patient and Group) and I have an interaction that exists between a continuous(days) and dummy categorical variable (0-Disease absent and 1-Disease present). But when I have not standardised the continuous I get a different outcome,I was expecting this in terms of estimates changing but there is also a change in terms of P value of the disease variable when the continuous variable is standardised vs when it is not.
Both converge and have the same AIC and BIC so which is better to use for interpretation. If I use the non-standardised varible I get a very high estimate for disease and the P value is significant but the estimate drops and also becomes not significant for disease when the continuous variable is standardised.
I am assuming the standardised output is what I interpret but I am not sure?
Code
Model <- glmer(Test ~ (1|Group) + (1|Year) + (1|Patient.ID) +
                   Days*Disease,
                   data=DF1, family = "binomial")

Non-standardised output;
 AIC      BIC   logLik deviance df.resid
  2399.9   2445.4  -1192.9   2385.9     4945

Scaled residuals:
    Min      1Q  Median      3Q     Max
-1.3797 -0.2916 -0.2183 -0.1685  8.5600

Random effects:
 Groups     Name        Variance Std.Dev.
 Patient.ID (Intercept) 0.04472  0.2115
 Group      (Intercept) 0.21043  0.4587
 Year       (Intercept) 0.39095  0.6253

Fixed effects:
              Estimate Std. Error z value Pr(>|z|)
(Intercept)  -1.521091   0.397524  -3.826 0.000130 ***
Days         -0.022762   0.004669  -4.876 1.09e-06 ***
Disease       4.273912   1.292344   3.307 0.000943 ***
Days:Disease -0.076111   0.031543  -2.413 0.015824 *

Correlation of Fixed Effects:
            (Intr) Days   Disease
Days        -0.530
Disease     -0.112  0.157
Days:Diseas  0.092 -0.141 -0.964

Standardised Ouput;
 AIC      BIC   logLik deviance df.resid
  2399.9   2445.4  -1192.9   2385.9     4945

Scaled residuals:
    Min      1Q  Median      3Q     Max
-1.3797 -0.2916 -0.2183 -0.1685  8.5601

Random effects:
 Groups     Name        Variance Std.Dev.
 Patient.ID (Intercept) 0.04471  0.2114
 Group      (Intercept) 0.21044  0.4587
 Year       (Intercept) 0.39093  0.6252

Fixed effects:
                   Estimate Std. Error z value Pr(>|z|)
(Intercept)        -2.65754    0.33783  -7.866 3.65e-15 ***
Stand.Days         -0.31035    0.06366  -4.875 1.09e-06 ***
Disease             0.47383    0.47393   1.000    0.317
Stand.Days:Disease -1.03778    0.43075  -2.409    0.016 *

Correlation of Fixed Effects:
            (Intr) Stnd.D Diseas
Stand.Days   0.066
Disease     -0.028 -0.040
Stnd.Dys:Ds  0.011 -0.141  0.693

A: Notice that the interaction remains consistent across the two models, as it should. The problem is with the main effects. The main effects for variables that are also interacted in a model have a localized rather than marginal interpretation. In the unstandardized model, the disease main-effect is the effect of disease when days is equal to zero. This is unlikely to be of any interest. Similarly, the days main-effect is the effect if days when disease is equal to zero. Also unlikely to be of interest. In the standardized model, the main effects have a more meaningful interpretation given that the data are centered. Now each main effect is the effect at the mean of the other variable that is part of the interaction. For example, in the standardized model, the disease main effect is the standardized effect of disease at the mean of days. This is why it is recommended to center variables if you are creating interactions. Centered variables will give you a model that is consistent with your standardized model but with unstandardized coefficients.


text:
Q: How to get gmail contact without oauth dialogue? I am working on windows application. I get gmail contact using following code.
But in this case I must login and accept permission from browser form(GoogleLoginForm).
I want to skip this "oauth dialog".
I have referred almost link of stack overflow and google developer. But I don't get much help regarding to this. Is there anyway to skip the permission from browser?
Please suggest.
This is my main form.
string SCOPE = "https://www.google.com/m8/feeds/ https://apps-apis.google.com/a/feeds/groups/";
string REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.ClientId = CLIENT_ID;
parameters.ClientSecret = CLIENT_SECRET;
parameters.RedirectUri = REDIRECT_URI;
parameters.Scope = SCOPE;

string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
Uri loginUri = new Uri(url);

GoogleLoginForm objForm = new GoogleLoginForm(loginUri);
DialogResult result= objForm.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
     parameters.AccessCode = objForm._OAuthVerifierToken;
}

OAuthUtil.GetAccessToken(parameters);
RequestSettings reqSettings = new RequestSettings("myapplication", parameters) { AutoPaging = true };
ContactsRequest contReq = new ContactsRequest(reqSettings);
Feed<Google.Contacts.Contact> Contacts = contReq.GetContacts();

I get AccessCode by following code.
    public GoogleLoginForm(Uri url)
    {
        InitializeComponent();
        _loginUri = url;
    }

    public GoogleLoginForm(Uri loginUri)
    {
        // TODO: Complete member initialization
        this._loginUri = loginUri;
    }
    private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
    {
        string fullPath = e.Url.ToString();
        WebBrowser control = sender as WebBrowser;
        if (control != null && !string.IsNullOrEmpty(control.DocumentTitle) && control.DocumentTitle.Contains("Success code"))
        {
            _OAuthVerifierToken = control.DocumentTitle.Replace("Success code=", "");
            DialogResult = DialogResult.OK;
        }
    }

    private void GoogleLoginForm_Load(object sender, EventArgs e)
    {
        webBrowser1.Url = _loginUri;
    }


text:
Q: Protege - DL Query and subclasses I'm using protege to test OWL Ontologies for my program.
Is there a way to ask in the DL Query tab if an entity is a subclass of another entity?
The autocomplete tab does not suggest the keyword subclass.

A: There is no concept of ASK queries in the DL Query Tab. The idea is to write Class Expressions and then do inferences based on what you selected in the check box section.
Thus, to check if a class A is a subclass of a class B, the idea would be to use A and then compute the super classes and check if B is contained in the result.
See the documentation
An alternative query language would be SPARQL.

A: Protégé 5.5. :
In the DL query window :

*

*enter the entity name

In the "Query for"

*

*check "Subclasses"

Press execute


text:
Q: Using default application timezone with DateTime.strptime in Rails 5 I read similar questions but did not find a solution.
My Rails 5 App is in

'America/Sao_Paulo'

time zone but saves all times in UTC to the database.
When saving a datetime

'2017-01-01 19:00:00'

to my database it will convert it to UTC and save the UTS time to the database.
Now I need to convert a string to datetime using:
DateTime.strptime(date + ' ' + time, '%d/%m/%Y %H:%M:%S')

And this will take the date and time values as they are and save them to the database without converting to UTC. How can I let my app know that my the datetime is not in UTC yet?

A: ActiveRecord (by default) will save any datetime to UTC. So, in my opinion you don't need to worry if the time in the database isn't yet in UTC, because ActiveRecord will convert it to UTC.
So, when saving to database, ActiveRecord will always convert it to UTC (whether it is in UTC or not).
And when fetching from database, it follows your configuration in config/application.rb
You can find in the file config.time_zone = 'YOUR_TIMEZONE'.
Reference:
http://api.rubyonrails.org/classes/ActiveRecord/Timestamp.html
Hope it helps, cheers!


text:
Q: Do I need unencrypted files underneath encrypted overmount? I have unencrypted files in my /home/user dir (likely fallout from moving my home dir to a different partition).
/dev/sda1             440G  137G  282G  33% /home
/home/user/.Private  440G  137G  282G  33% /home/user

If I ls /home/user while logged on as a different user, I see older contents of that dir since the encrypted file isn't mounted.
Do I need those files?  And if not, what is a safe way to delete them?

A: Looking at the unmounted encrypted home directory of a non-logged-in user, I see some unencrypted files (well they're really directories and links):
$ /bin/ls -la /home/walt
total 12
dr-x------  3 w3   walt 4096 Apr  9 22:12 .
drwxr-xr-x 13 root root 4096 Sep  1  2015 ..
lrwxrwxrwx  1 walt walt   56 Oct 22  2011 Access-Your-Private-Data.desktop -> /usr/share/ecryptfs-utils/ecryptfs-mount-private.desktop
drwx------  7 walt walt 4096 Jan 16  2013 .cache
lrwxrwxrwx  1 walt walt   30 Oct 22  2011 .ecryptfs -> /home/.ecryptfs/walt/.ecryptfs
lrwxrwxrwx  1 walt walt   29 Oct 22  2011 .Private -> /home/.ecryptfs/walt/.Private
lrwxrwxrwx  1 walt walt   52 Oct 22  2011 README.txt -> /usr/share/ecryptfs-utils/ecryptfs-mount-private.txt

You don't need any other files. You could delete the files with something like find /home/user -maxdepth 1 \( \! -type l -a -type d \) -exec echo rm {} \;, remove the echo when you are thrilled with the results of the find


text:
Q: Convert IDictionary> to IObservable> I have a function to replace a single entity in a repository (e.g. a database) with another entity. This returns a Task, the result of which indicates if a replacement was successful.
// Single Replace
Task<bool> Replace(Entity e, Entity Other);

Now say I want to create the same function, but allowing to replace several entities. My idea for a function signature was:
// Multiple Replace
IObservable<KeyValuePair<Entity, bool>> Replace(IDictionary<Entity, Entity> Map);

Map contains a dictionary whose keys are the entities which shall be replaced, and its values are the new entities that shall replace the old ones.
Each KeyValuePair of this Map dictionary should return a KeyValuePair< Entity, bool >, where the key corresponds to Map.Key (= the Entitiy which shall be replaced), and Value is a bool that indicates whether the replacement was successful or not.
I'd like to return this as a stream, hence I chose IObservable< KeyValuePair< Entity,bool > >, pushing out a KeyValuePair< Entity,bool > for each result that becomes available.
For now, I'd just like to have the "Multiple Replace" function use the "Single Replace" function to convert; but how can I make these calls and return the result in the required format?
Task<bool> Replace(Entity e, Entity Other)
{
  // ... do the work ...
}

IObservable<KeyValuePair<Entity, bool>> Replace(IDictionary<Entity, Entity> Map)
{
  // How this should work:
  // for each KeyValuePair in Map, call the Single Replace function
  // and - once available - return its result (bool) mapped to the Entity in the
  // resulting Observable stream

  IDictionary<Entity, Task<bool>> dict = Map.ToDictionary(x => x.Key, x => Replace(x.Key, x.Value));

  // .. now what? How can I now convert the dict into an IObservable<KeyValuePair<Entity,bool>> ?

}

Would appreciate any pointers!

A: Without seeing a good Minimal, Complete, and Verifiable example that clearly shows what you're doing, and especially how you intend to implement the IObservable<T> object returned from your method, it's impossible to offer specific advice. However, I can provide some suggestions that should at least point you in a useful direction.
First, I will suggest that it is more useful to have a Task<Tuple<Entity, bool>> (or Task<KeyValuePair<Entity, bool>>, though I am not very fond of using dictionary-related types for non-dictionary-dependent code…i.e. where you're really just pairing things rather than having a true key/value pairing). That way, when the task completes, you know from the task itself all of the information you need.
This can be accomplished with a simple helper method, e.g.:
async Task<Tuple<Entity, bool>> ReplaceAsync(Entity e, Entity other)
{
    return Tuple.Create(e, await Replace(e, other));
}

I used Tuple here, but of course you may create a named type for the purpose, and doing so may in fact help readability of the code.
Having done that, you can then just enumerate all of the items in your input dictionary (or other more appropriate collection :) ), and then use Task.WhenAny() to iteratively remove and publish each completed item as they occur:
IObservable<Tuple<Entity, bool>> Replace(IDictionary<Entity, Entity> Map)
{
    Task<Tuple<Entity, bool>>[] tasks = new Task<Tuple<Entity, bool>>(Map.Count);
    int i = 0;

    foreach (var kvp in Map)
    {
        tasks[i++] = ReplaceAsync(kvp.Key, kvp.Value);
    }

    // Create the IObservable object somehow. Make sure it has the
    // array of tasks in it. E.g. (see below for TaskObservable example)

    TaskObservable<Tuple<Entity, bool>> observable =
        new TaskObservable<Tuple<Entity, bool>>(tasks);

    // Now, start running the observable object. Note: not really all that great
    // to ignore the returned Task object but without more context in your question
    // I can't offer anything more specific. You will probably want to store the
    // Task object *somewhere*, await it, wrap all that in try/catch, etc. to
    // make sure you are correctly monitoring the progress of the task.
    var _ = observable.Run();

    return observable;
}

The IObservable<T> might look something like:
class TaskObservable<T> : IObservable<T>
{
    private class ObserverItem : IDisposable
    {
        public readonly IObserver<T> Observer;
        public readonly TaskObservable<T> Owner;

        public ObserverItem(IObserver<T> observer, TaskObservable<T> owner)
        {
            Observer = observer;
            Owner = owner;
        }

        public void Dispose()
        {
            if (!Owner._observerItems.Contains(this))
            {
                throw new InvalidOperationException(
                    "This observer is no longer subscribed");
            }

            Owner._observerItems.Remove(this);
        }
    }

    private readonly Task<T>[] _tasks;
    private readonly List<ObserverItem> _observerItems = new List<ObserverItem>();

    public TaskObservable(Task<T>[] tasks)
    {
        _tasks = tasks;
    }

    public IDisposable Subscribe(IObserver<T> observer)
    {
        ObserverItem item = new ObserverItem(observer, this);

        _observerItems.Add(item);
        return item;
    }

    private void Publish(T t)
    {
        foreach (ObserverItem item in _observerItems)
        {
            item.Observer.OnNext(t);
        }
    }

    private void Complete()
    {
        foreach (ObserverItem item in _observerItems)
        {
            item.Observer.OnCompleted();
        }
    }

    async Task Run()
    {
        for (int i = 0; i < _tasks.Length; i++)
        {
            Task<T> completedTask = await Task.WhenAny(tasks);

            Publish(completedTask.Result);
        }

        Complete();
    }
}

A: based on Peter's solution, a little modification that leverages Task.ToObservable:
    IObservable<Tuple<Entity, bool>> Replace(IDictionary<Entity, Entity> Map)
    {
        Task<Tuple<Entity, bool>>[] tasks = new Task<Tuple<Entity, bool>>(Map.Count);
        int i = 0;

        foreach (var kvp in Map)
        {
            tasks[i++] = ReplaceAsync(kvp.Key, kvp.Value);
        }

        return tasks
            .Select(x => x.ToObservable())
            .Merge();   // or use .Concat for sequential execution
    }

Seems to work fine, does anyone spot any potential issues?
Using .Merge gives an IObservable that starts the tasks in parallel, providing results as they finish, and completes when all tasks are done.
Alternatively I can use .Concat() to execute them sequentially, i.e. start the first task first, wait for it to finish, then start the second task, etc.
Nice thing is that error handling comes for free I believe, so whenever any of the tasks throws an Exception, OnError of the IObservable is auomatically called.

A: I'm not sure if I've missed anything, but I think this might work for you:
public IObservable<KeyValuePair<T, bool>> Convert<T>(IDictionary<T, Task<bool>> source)
{
    return
        Observable
            .Create<KeyValuePair<T, bool>>(o =>
                (
                    from s in source.ToObservable()
                    from v in s.Value.ToObservable()
                    select new KeyValuePair<T, bool>(s.Key, v)
                ).Subscribe(o));
}


text:
Q: Javascript's onclick event causes the page to reload in IE8, but not in Firefox, Safari,Chrome and Opera? I have an onclick event attached to a button.
Clicking the button adds a text box to the target div.
The code is:
onclick="return addBlank("param1","param2");

The function addBlank does not have a return statement.
Clicking on the button behaves as intended in Firefox, Opera, Chrome and Safari - i.e., an empty text box is added to the target div and page is not reloaded.
Clicking on the button in IE8 forces a page reload and doesn't add anything to the target div.
Is there an onclick incompatibility that I'm missing here?
I appreciate your taking the time to read this doubt!

A: Why not add
return false;

to the end of the function then? It should prevent anything happening as a result of the onclick event.

A: IE is treating the button as a submit actor (i.e., clicking it submits the form)
The click handler needs to return false; to prevent this.
function addBlank( p1, p2 )
{
  // stuff
  return false;
}


text:
Q: Derivative of a function of two variables Let $f:\mathbb R^2\rightarrow \mathbb R $ be defined by
$f(x,y)=\exp(-\frac{1}{x^2+y^2})$ if $(x,y)\neq(0,0)$ and $f(0,0)=0$. Check whether $f$ is differentiate at (0,0) or not.
I have checked that $f$ is continuous at (0,0) and both partial derivatives of $f$ exists at (0,0) and both equals to 0. But how do I check the differentiability?

A: Using the definition of differentiability, just evaluate the limit $$\begin{align} \lim_{(h,k)\to(0,0)} \frac{f(h,k)-f(0,0)-f_x(0,0)h-f_y(0,0)k}{\sqrt{h^2+k^2}}&=\lim_{(h,k)\to(0,0)}\frac{e^{-1/(h^2+k^2)}}{\sqrt{h^2+k^2}}\\\\
&=\lim_{r\to 0}\frac{e^{-1/r^2}}{r}\end{align}$$

A: Hint: you should check if
$$\frac{\exp(-\frac{1}{x^2+y^2})}{\sqrt{x^2+y^2}} \to 0$$
when $$(x,y) \to (0,0)$$
For this most simple, imho, is consider functions $z=x^2+y^2$ and $t=\frac{\exp(-\frac{1}{z})}{\sqrt{z}}$ and take limit on their composition.


text:
Q: Why can I not reuse temp tables in T-SQL? Here's some sample code:
if object_id('tempdb..#TempList') is not null drop table #TempList

create table #TempList (
   ID int,
   Name varchar(20)
)

insert into #TempList values (1, 'Alpha')
insert into #TempList values (2, 'Beta')
insert into #TempList values (3, 'Gamma')
insert into #TempList values (4, 'Delta')
insert into #TempList values (5, 'Omega')

select * from #TempList

if object_id('tempdb..#TempList') is not null drop table #TempList
drop table #TempList

create table #TempList (
   ID_New int,
   AnotherID int,
   Name_New varchar(40)
)

insert into #TempList values (100, 110, 'Orange')
insert into #TempList values (101, 111, 'Red')
insert into #TempList values (102, 112, 'Purple')
insert into #TempList values (103, 113, 'Blue')
insert into #TempList values (104, 114, 'Green')

select * from #TempList

This yields the following error:
Msg 2714, Level 16, State 1, Line 19
There is already an object named '#TempList' in the database.

Am I not able to re-use the same temp table name within the same SQL script?  Is there a way to re-use the same temp table name?
Thanks.

A: Change
if object_id('tempdb..#TempList') is not null drop table #TempList
drop table #TempList

create table #TempList (

to
if object_id('tempdb..#TempList') is not null drop table #TempList
drop table #TempList

GO;

create table #TempList (

SQL Server query optimizer gets confused.
It sees that you create the same table second time.
Note that table drop (as well as create) has probabilistic outcome,
the result will be known only at run-time
(not upon syntax control or query exec plan creation aka "compilation" in jargon of SQL Server)

A: Seems like a parser error to me.  I'm betting it sees the two create table statements creating the same table and throws the error, regardless of the drop statement.  Breaking it up with a go statement works fine though.
create table #Temp (ID int)
insert into #Temp (ID)
select 1 union all select 2

select ID from #Temp

drop table #Temp
go
create table #Temp (ID int)

insert into #Temp (ID)
select 10 union all select 11

select ID from #Temp

drop table #Temp

A: It's an issue with scoping and #temp tables.  Since you can have two connections with the same named #temp table, the metadata doesn't directly refer to it by the name you specify.
The behavior is explained in this blog post pretty thoroughly.
You need to run a different query using a LIKE comparison to remove the #temp table:
IF EXISTS (
SELECT *
FROM sys.tables
WHERE name LIKE '#templist%')
DROP TABLE #templist
CREATE TABLE #templist...

A: Yes. Drop the table when you are done using it. :)


text:
Q: Output loop result into a list Someone please help me with this code:
agerlist = for agern in anime.info['Genres']:
      print agern['name']

Is there any way to save the output into one variable? An example would be: alist = agern in anime.info ?

A: You mean like this?
alist = [ x['name'] for x in anime.info['Genre']]

A: Create an empty list and then append the results of for loop to that list or you could use list comprehension.
l = []
for agern in anime.info['Genres']:
    l.append(agern['name'])
print l

A: you could also store that into a generator function, something like this:
for agern in anime.info['Genres']:
    yield agern['name']

so that you will actually compute this thing only on request, i.e. during a for cycle, so you will not store in memory each agern['name'] two times.


text:
Q: Awk command with regex in it does not work properly Well here is my folder structure

And here is my problem

I would like to know how is that possible that when the find command does research in f_ignore2 .. the awk command is able to grep those files (file(b|c))  out of output which are located in the dir directory, but when the find command does research in f_ignore2/dir it does not work. It's weird and i don't know what to do .. do you have any idea guys ?

A: Why dont you use this awk instead?
awk -F/ '!/\/file[bc]/'

print all lines except lines which has string /fileb or /filec.


text:
Q: Solving PDE by using laplace transformation Partial Differential Equation is:
$$\frac{∂u}{∂t} = \frac{∂^2u}{∂x^2}$$
Where $t>0$, and $0<x<1$.
With the boundary conditions:
$$u(0,t)=1$$
$$u(1,t) = 1$$
and the initial conditions:
$$u(x,0) = 1+\sin{(πx)}$$
I'm trying to solve this by using Laplace transform but I couldn't.

A: You haven't even bothered to ask a question. Good effort.
Here is a list of examples for your problem. Example 3 is something very similar to what you are trying to do. If I was you - Be able to understand all three examples before trying the one you've posted, otherwise you won't get it. Good Luck! Post your attempts if you get stuck and we can help.


text:
Q: what is meant by normalization in huge pointers I have a lot of confusion on understanding the difference between a "far" pointer and "huge" pointer, searched for it all over in google for a solution, couldnot find one. Can any one explain me the difference between the two. Also, what is the exact normalization concept related to huge pointers.
Please donot give me the following or any similar answers:

"The only difference between a far pointer and a huge pointer is that a huge pointer is normalized by the compiler. A normalized pointer is one that has as much of the address as possible in the segment, meaning that the offset is never larger than 15. A huge pointer is normalized only when pointer arithmetic is performed on it. It is not normalized when an assignment is made. You can cause it to be normalized without changing the value by incrementing and then decrementing it. The offset must be less than 16 because the segment can represent any value greater than or equal to 16 (e.g. Absolute address 0x17 in a normalized form would be 0001:0001. While a far pointer could address the absolute address 0x17 with 0000:0017, this is not a valid huge (normalized) pointer because the offset is greater than 0000F.). Huge pointers can also be incremented and decremented using arithmetic operators, but since they are normalized they will not wrap like far pointers."

Here the normalization concept is not very well explained, or may be I'm unable to understand it very well.
Can anyone try explaining this concept from a beginners point of view.
Thanks,
Rahamath

A: In the beginning 8086 was an extension of the 8 bit processor 8085. The 8085 could only address 65536 bytes with its 16 bit address bus. When Intel developed the 8086 they wanted the software to be as compatible as possible to the old 8 bit processors, so they introduced the concept of segmented memory addressing. This allowed to run 8 bit software to live in the bigger address range without noticing. The 8086 had a 20 bit address bus and could thus handle up to 1 MB of memory (2^20). Unfortunatly it could not address this memory directly, it had to use the segment registers to do that. The real address was calculated by adding the 16 bit segment value shifted by 4 to the left added to the 16 bit offset.
Example:
Segment  0x1234   Offset 0x5678 will give the real address
   0x 1234
  +0x  5678
  ---------
  =0x 179B8

As you will have noticed, this operation is not bijective, meaning you can generate the real address with other combinations of segment and offset.
   0x 1264               0x 1111
  +0x  5378             +0x  68A8
  ---------             ---------     etc.
  =0x 179B8             =0x 179B8

There are in fact 4096 different combinations possible, because of the 3 overlapping nibbles (3*4 = 12 bits, 2^12 = 4096) .
The normalized combination is the only one in 4096 possible values that will have the 3 high nibbles of the offset to zero. In our example it will be:
   0x 179B
  +0x  0008
  ---------
  =0x 179B8

The difference between a far and a huge pointer is not in the normalisation, you can have non normalised huge pointer, it's absolutly allowed. The difference is in the code generated when performing pointer arithmetic. With far pointers when incrementing or adding values to the pointer there will be no overflow handling and you will be only able to handle 64K of memory.
char far *p = (char far *)0x1000FFFF;
p++;
printf("p=%p\n");

will print 1000:0000
For huge pointers the compiler will generate the code necessary to handle the carry over.
char huge *p = (char huge *)0x1000FFFF;
p++;
printf("p=%p\n");

will print 2000:0000
This means you have to be careful when using far or huge pointers as the cost of the arithmetic with them is different.
One should also not forget that most 16 bit compilers had libraries that didn't handle these cases correctly giving sometimes buggy software.
Microsofts real mode compiler didn't handle huge pointers on all its string functions. Borland was even worse as even the mem functions (memcpy, memset, etc.) didn't handle offset overflows. That was the reason why it was a good idea to use normalised pointers with these library functions, the likelyhood of offset overflows was lower with them.

A: First thing to understand is how a segmented pointer is converted into a linear address.  For the example you have, the conversion is:
linear = segment * 16 + offset;

Because of that, it turns out there there the same linear address can be expressed using different segment/offset combinations.  For example, the following segment/offset combinations all refer to the same linear address:
0004:0000
0003:0010
0002:0020
0001:0030
0000:0040

The problem with this is that if you have ptr1 with a segmented address of 0100:0000 and ptr2 with a segmented address of 0010:0020, a simple comparison will determine that ptr1 != ptr2 even though they actually point to the same address.
Normalization is the process by which you convert an address to a form such that if two non-normalized pointers refer to the same linear address, they will both be converted to the same normalized form.

A: As I recall, it's something like this:

*

*Near pointers point to memory in the same segment (as the pointer).

*Far pointers point to memory in another segment.

*Huge pointers let you point to memory that's larger than a segment (so you can have a block >64k and do arithmetic on your pointer, and what Samuel said).

If you're a beginner, it's probably best to forget that you heard about Near/Far/Huge. They only have meaning in the old 16-bit segmented memory model commonly seen on early Intel 80x86's. In 32- and 64-bit land (i.e., everything since 1994), memory is just a big contiguous block, so a pointer is just a pointer (as far as a single application is concerned).


text:
Q: How to convert the filetype from .png to .mha? I am doing brain tumor segmentation with the BTATS2013. I have gotten the test result with the testing dataset of BRATS 2013 which don't have ground truth, so I can't get the Dice, PPV, Sensitivity directly. I want to use the online platform to evaluate the segmentations, it requires the filetype of input is .mha, but the filetype of segmentations that I get is .png. I don't know how to convert the .png to .mha. Is there anyone can help me to solve the problem, or can you give me some advice of getting the indicators of segmentation? Thanks.

A: Load your data in 3DSlicer,
You can load Png files there.
Then store it in mha format:


text:
Q: Updating windows forms panel with progress message during execution I am trying to show the progress of my windows form application in a panel within the form. However, all the messages show together at the end of when the application completes executing. Is there a way to display the messages as the code - execution "progress" through these messages - just the way it would in an interpreted language?
PS: I am adding the message as a label control to the panel at different points within the code.
Thank you.

A: You have to invalidate the label every time you change the message:
label1.Text = "Initializing...";
label1.Refresh();

// Do Stuff

label1.Text = "Working...";
label1.Refresh();

// Do Stuff

label1.Text = "Completed.";
label1.Refresh();

A: Or, it may be worth using a backgroundWorker (or another thread). Whats happening now is that the main thread (the one that also draws the UI) is too busy doing the processing to update the UI.
I'm not sure what language you're using, but Ill assume C#. In that case, create a BackgroundWorker that reports progress. Call the Background worker asynchronously so that it does the processing and use the Reports_Progress event to set the label. You cant set the label in the main Backgroundworker do_work procedure since the label was created by another thread. See this example, it may help (admittedly he sets a progress-bar value but you can just as easily set label text - http://www.dotnetperls.com/progressbar)
If you dont have the Backgroundworker class, you can implement the same logic, just using a different thread.
If you need some more info, let me know.


text:
Q: Only doctests on immediate module If I have three modules:
-- A.hs
module A where
-- $
-- >>> True
-- True

-- B.hs
module B where
import A
-- $
-- >>> True
-- True

-- C.hs
module C where
import B
-- $
-- >>> True
-- True

Running doctest C.hs will run all the doctests in all three files.
$ doctest C.hs
Examples: 3  Tried: 3  Errors: 0  Failures: 0

Is there a way to run doctest on only the top-level module - that is, have it not recursively search for tests in included modules?


text:
Q: How to avoid duplicating layout and style XML in various EditText fields? I'm new in Android and i want learn more about layouts based on XML.
My problem is follow:
<EditText
    android:text="33"
    android:textSize="12dp"
    android:inputType="numberDecimal"
    android:layout_width="41dp"
    android:layout_height="39dp"
    android:layout_marginTop="24dp"
    android:layout_marginLeft="41dp"
    android:id="@+id/math1"     />

<EditText...>
<EditText...>
<EditText...>
<EditText...>
<EditText...>
<EditText...>
<EditText...>

I want to edit all the "EditText" that appear in the code without applying controls to each.
Is there any way to do that?
I do not know if I explain. (Excuseme for my english, I am Chilean).

A: If the question is how to avoid duplicating layout attributes, you can use a style. For example:
In a res/values/whatever.xml file:
<style name="YourEditTextStyle">
    <item name="android:textSize">12dp</item>
    <item name="android:inputType">numberDecimal</item>
    <!-- and so on -->
</style>

Apply in layout xml:
<EditText
    style="@style/YourEditTextStyle"
    android:id="@+id/math1"
    .../>

<EditText
    style="@style/YourEditTextStyle"
    android:id="@+id/math2"

...

So when you need to modify the styling of your edittexts, you need to do it only once in the style resource.

A: No, you have to access all the  EditText & set them manually !!


text:
Q: Parse.com - Static files vs Dynamic URLs order I'm trying to execute cloud code first, before looking for files in the /public directory on Parse.com Cloud code.
Reading ExpressJS documentation, I've found that you can change the precedence using
app.use(app.router);
app.use(express.static(__dirname + '/public'));

the problem is when I try to deploy to parse, I get the following error

Update failed with Could not load triggers.  The error was
  ReferenceError: __dirname is not defined

is __dirname supported ?

A: It would just be express.static('public');  however, this probably won't work.  Parse Hosting may completely skip touching/looking at cloud code for URLs under the public folder (in fact, I'm 99% sure it does.)


text:
Q: Windows TCP redirection On my Windows PC (192.168.1.123) , I have an application that connects to 1.2.3.4 on port 3333 by default, I would like to redirect the traffic to 127.0.0.1 port 2222.
Under Linux, this can be accomplished by entering this on my PC.
iptables -t nat -A OUTPUT -s 192.168.1.123 -p tcp -d 1.2.3.4 --dport 3333 -j DNAT --to-destination 127.0.0.1:2222

Is there a way to do the above on Windows?

A: on linux this is possible with nc like nc -l 1234 | nc 1.2.3.4 5678 and you can get nc on windows with cygwin
An alternative to nc is in windows with the netsh  command
it's mentioned here
https://stackoverflow.com/questions/11525703/port-forwarding-in-windows
netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33


text:
Q: Eclipse update site freezes I'm trying to install Aptana plugin with the update site. The problem is it freezes in "Calculating requirements and dependences.".
I checked the error log in eclipse and there's nothing.

*

*Eclipse Java EE x64

*Ubuntu 12.04 x64

A: Check whether your proxy settings are correct. Take a look at this answer. I was thinking that the plugin installation may freeze if your eclipse cannot connect to the internet. If you open up Eclipse' internal browser can you browse to sites ?
Sometimes, the plugin installation has hung for me and I have been able to get by after un-checking the option to Contact all update sites like so:

Also, take a look at the Error Log and see whether you get any error there when Eclipse freezes. The Eclipse error log is located at WORKSPACE_HOME/.metadata/.log


text:
Q: After upgrading PrimeFaces 3.5 to 4.0, p:fileUpload throws exception I have a code that make the upload perfectly using primefaces 3.5, but I update the primefaces lib in my project to 4.0 and it doesn´t work any more. Here is the code:
web.xml
 <filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class> org.primefaces.webapp.filter.FileUploadFilter</filter-class>
 </filter>
 <filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
 </filter-mapping>

xhtml page
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://xmlns.jcp.org/jsf/html"
  xmlns:p="http://primefaces.org/ui">
<h:head>
    <title>Facelet Title</title>
</h:head>
<h:body>
    <h:form enctype="multipart/form-data">
        <p:fileUpload fileUploadListener="#{siteBean.fileUploadAction}" />
    </h:form>
</h:body>
</html>

SiteBean.java
@ManagedBean
@ViewScoped
public class SiteBean{
public void fileUploadAction(FileUploadEvent event) {
    try {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

        FacesContext aFacesContext = FacesContext.getCurrentInstance();
        ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();

        String realPath = context.getRealPath("/");

        File folder = new File(realPath + "/img/sites/");
        folder.mkdirs();

        byte[] file = event.getFile().getContents();
        String path = realPath + "/img/sites/" + event.getFile().getFileName();

        FileOutputStream fos = new FileOutputStream(path);
        fos.write(file);
        fos.close();
    }
    catch (Exception ex) {
        System.out.println("Error: " + ex.getMessage());
    }
}
}

When I try to upload a file it shows me exception message.
Here is the exception:
SEVERE:   java.lang.NullPointerException
at java.io.FileOutputStream.write(FileOutputStream.java:305)
at managedBean.SiteBean.fileUploadAction(SiteBean.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.el.parser.AstValue.invoke(AstValue.java:275)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at org.primefaces.component.fileupload.FileUpload.broadcast(FileUpload.java:290)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:755)
at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:931)
at    com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:70)
at         org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at  org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)

I´m using Netbeans 7.4, primefaces 4.0, common io 2.4, common file upload 1.3 and jsf 2.2.

A: The datas are in the inputStream
Try something like this :
// write the inputStream to a FileOutputStream
OutputStream out = null;
InputStream in = event.getFile().getInputStream();
try
{
    out = new FileOutputStream(new File(dirPath, fileName));
    int read = 0;
    byte[] bytes = new byte[1024];

    while ((read = in.read(bytes)) != -1)
    {
        out.write(bytes, 0, read);
    }
    out.flush();

} catch (IOException e) {

}
 finally
{
    out.close();
}


text:
Q: How to transfer data from one table to another I have two tables,  I want to transfer all data from the first table to the second table in case of this data is not exits i nthe second table. how to do it using MS-sql server query ?

A: it could be something like:
INSERT INTO tableB(FieldA, FieldB, FieldC)
SELECT a.FieldA, a.FieldB, a.FieldC
FROM tableA a
WHERE NOT EXISTS
 (
    SELECT *
    FROM tableB b

    /* Primary key field(s)*/
    WHERE b.FieldA =a.FieldA
 )

A: in ms-sql you could do something like this:
INSERT INTO mytable(column1, column2) select value1, value2 from mytable2;

but you must make sure that the column1 and value1 have the same datatype same with column2.
Hope it helps. ;)

A: If the table doesn't exixst you can
SELECT * INTO SECOND_TABLE
FROM FIRST_TABLE;

If you want it to run even if table exists you can preceed this query with:
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[YOUR_SCHEMA].[SECOND_TABLE]') AND type in (N'U'))
DROP TABLE [YOUR_SCHEMA].[SECOND_TABLE];


text:
Q: Packing an int into a bitfield in C++ I'm converting some code from ASM to C++, the ASM simply looks like so:
mov dword ptr miscStruct, eax

the Struct looks like:
struct miscStruct_s {
  uLong brandID     : 8,
  chunks            : 8,
  //etc
} miscStruct;

Is there an easy one-two line way to fill the struct in C++?
So far I am using:
miscStruct.brandID = Info[0] & 0xff; //Info[0] has the same data as eax in the ASM sample.
miscStruct.chunks = ((Info[0] >> 8) & 0xff);

That works fine and all, but I have to fill some 9-10 of these bitfield structs, some of them have 30 odd fields. So doing it this way ends up turning 10 lines of code into 100+ which obviously is not so great.
So is there a simple, clean way of replicating the ASM in C++?
I of course tried "miscStruct = CPUInfo[0];" but C++ doesn't like that unfortunately. :(
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int'

..And I can't edit the struct.

A: memcpy (&miscStruct, &CPUInfo[0], sizeof (struct miscStruct_s));
should help.
or simply
int *temp = &miscStruct;
*temp = CPUInfo[0];

Here i have assumed that the type of CPUInfo is int  . You need to adjust the temp pointer type with the datatype of the CPUInfo array. Simply typecast the memory address for the structure to the type of the array and assign the value into there using the pointer.

A: The literal translation of the assembler instruction is this:
miscStruct=*(miscStruct_s *)&Info[0];

The casts are needed because C++ is a type-safe language, whereas assembler isn't, but the copying semantics are identical.


text:
Q: matching two lists of words and return the matched words I want to loop through a list of string to another list
cutter_Ch <- c('happy','birthday','Lucia')
pos <- c('Lucia','today')

one way I can do it is with lapply
pos.matches = lapply(cutter_Ch, pmatch, pos)

[[1]]
[1] NA

[[2]]
[1] NA

[[3]]
[1] 1

However, I want the function return the matched string instead of NA and number of times matched, like this
[[1]]
[1] NA

[[2]]
[1] NA

[[3]]
[1] Lucia

A: We need to use the index to subset the 'pos'
lapply(cutter_Ch, function(x) pos[pmatch(x, pos)])

It is not clear whether this example is simplified version of something more complex.  Anyway, with str_extract we can get the same output in a vector
library(stringr)
str_extract(cutter_Ch, paste(pos, collapse="|"))
#[1] NA      NA      "Lucia"


text:
Q: How do you call a "union or group of memories" in a single word? A memory is a representation of the brain about something.
How do you call a union of those representations in a single word?
A union or group of memories is? A scene?

A: Engram

An engram is a unit of cognitive information inside the brain, theorized to be the means by which memories are stored as biophysical or biochemical changes in the brain (and other neural tissue) in response to external stimuli.

(Source: Engram (neuropsychology), Wikipedia)