text:
Q: Postgres select query runs slow when using JDBC but quick when running it in PSQL from the same server I have the following, pretty simple, query that I am running using JDBC that is taking an excessive amount of time to run. The database is an AWS RDS server. The rt2 table has about 600K entries and the CM2 table about 300K.  The query returns 11230 rows.
SELECT cm2.target
from sysmgmt.sys_root rt2
   join cmgmt.member cm2 on cm2.cmid = rt2.cmid and cm2.version=rt2.work_version_id
where rt2.tid=1001
  and rt2.proj='d791194b-f2b7-42a7-aba7-f879e052e59d'::uuid
  and rt2.deleted = false
  and cm2.tid=1001 and cm2.proj = 'd791194b-f2b7-42a7-aba7-f879e052e59d'::uuid;

When I run this query with the JDBC call it takes 40 seconds!  However, if I run this exact same query in a PSQL command line on the same machine it is almost instantaneous.
Running EXPLAIN ANALYZE shows the following plan.
Nested Loop  (cost=0.85..7.77 rows=1 width=176) (actual time=0.030..36.067 rows=11230 loops=1)
->  Index Scan using m_cell_tid_proj_version_idx on member cm2  (cost=0.42..3.32 rows=1 width=197) (actual time=0.020..2.988 rows=11230 loops=1)
    Index Cond: ((tid = '1001'::numeric) AND (proj = 'ed1a7c79-a3a1-4d8e-815b-0fbbcbd7bf4b'::uuid))
->  Index Scan using sys_root_cmid_workversion_idx on sys_root rt2  (cost=0.42..4.45 rows=1 width=21) (actual time=0.002..0.002 rows=1 loops=11230)
    Index Cond: ((cmid = cm2.cmid) AND (work_version_id = cm2.version))
    Filter: ((NOT deleted) AND (tid = '1001'::numeric) AND (proj = 'ed1a7c79-a3a1-4d8e-815b-0fbbcbd7bf4b'::uuid))
Planning Time: 0.374 ms
Execution Time: 36.499 ms

Some things I have tried to speed it up.

*

*rearrange the query

*Adding indexes that match better

*Change fillfactor (didn't seem to have any effect)

*VACUUM

None of these seem to have any effect.  The java code is pretty straight forward, run the query and then iterate over the results.  The timing is taken just before executeQuery and just after it.
  Took :[40644.067138] Comment:found 11230 SQL Query:[SELECT cm2.target from sysmgmt.sys_root rt2 join mgmt.member cm2 on cm2.cmid = rt2.cmid and cm2.version=rt2.work_version_id where rt2.tid=1001 and rt2.proj='ed1a7c79-a3a1-4d8e-815b-0fbbcbd7bf4b'::uuid and cm2.tid=1001 and cm2.proj = 'ed1a7c79-a3a1-4d8e-815b-0fbbcbd7bf4b'::uuid and rt2.deleted = false]

There are about 5 to 10 other queries that are running in the same transaction, is it possible that the other queries cause an issue downstream to when it gets to this query?
If anyone has any ideas on what might be the problem, I would appreciate some insight.

A: It turns out that the Explain Analyze plan was different when it was being run in in the context of the activity.  Turning up the auto_explain parameters and having it log to the postgres log files showed that the plan was different than when I ran it as a standalone request.  The question then became "how to get it to do the right thing?".  The answer to that was to turn up the default_statistics_target to 200 from 100 and run ANALYZE on the database. I also rearranged the join table order.  In doing both of these, the problem has gone away (for good hopefully).  This wiki https://wiki.postgresql.org/wiki/Performance_Optimization also proved to be a great resource.


text:
Q: How to mock a constant that is a dependency of the service under test? I am testing a file called connect-key.js. It has a dependency called keyvault-emulator.
File #1:
// connect-key.js file
const { save, retrieve, init  } = require('./keyvault-emulator')
....
....
....
// SOME TESTS

File #2:
// The keyvault-emulator.js file
const { storageConnectionString } = require('../config')

Now, how can I mock the value of storageConnectionString from my test file connect-key.spec.js?
I envision something like this:
// The connect-key.spec.js file
const keyvault_emulator = require('../keyvault-emulator');
const spy = jest.spyOn(keyvault_emulator, 'storageConnectionString');
spy.mockReturnValue('');

And this is the config file:
// config.js file
module.exports = {
  storageConnectionString: process.env.STORAGE_CONNECTION_STRING || process.env.Storage,
  keyVaultName: process.env.KEY_VAULT
}

Is this the proper way to do this? What is the best way to accomplish this?

A: Mocking Internal Dependency
Before mocking internal dependency, the question needs to clarify what's the point of it; because Jest's mocking ability is somewhat limited. Since it was not mentioned in the question, I've personally picked some best possible cases with examples.
To make it easier to understand, let's say there is an imaginary function called testFunction(); it is a function that returns the storageConnectionString mentioned earlier.
1. for only specific function in test scope, nothing else.
// key.spec.js
const keyvault_emulator = require('../keyvault-emulator');
js.mock('../keyvault-emulator', () => ({
  // everything is original, except testFunction
  ...jest.requireActual('../keyvault-emulator'),
  // this supposed to return () => storageConnectionString but it's mocked here.
  testFunction: jest.fn(() => 'mocked')
})

// ✅ it works
expect(keyvault_emulator.testFunction()).toEqual('mocked')
// ❌ this fails!
expect(keyvault_emulator.otherFunctionUsingStorageConnectionString())
  .toEqual('mocked')

2. for everything inside the module
Jest can only replace a function or module. It can not re-evaluate the codes. In this case, the dependency of config.js and keyvault-emulator.js has to be decoupled from the source to ease the testing process.
2-1. hard decoupling from the source itself.
// keyvault-emulator.js
// KeyValue emulator has to be restructured to have constructor, or init function
class KeyValueEmulator {
  constructor(config) {
    this.config = config;
  }
  testFunction() {
    // do something with this.config
    return this.config;
  }
}

// key.spec.js
const mockedConfig = { storageConnectionConfig: 'mocked' }
const keyValueEmulator = new KeyValueEmulator(mockedConfig);
// ✅ it works
expect(keyValueEmulator.testFunction()).toEqual('mocked')

2-2. soft decoupling with jest's internal module mocking.
working codes at Github
// key.spec.js
import config from "./config";
jest.mock("./config", () => ({ default: { storageConnectionString: "mocked" } }));
import { storageConnectionString, testFunction } from "./index";

describe("config mocking", () => {
  it("value is mocked", () => {
    // ✅ it works
    expect(config.storageConnectionString).toEqual("mocked");
    expect(testFunction()).toEqual("mocked");
  });
});

3. mocking a single variable
As already explained in case 2, it is the impossible case. Jest just cannot mock a single variable; it is probably closest to the code mentioned in the question, and this is why clarification is needed.
// same as code in the question. the test code should be fixed to work,
// but let's say it's working as you've intended.
// key.spec.js
const keyvault_emulator = require('../keyvault-emulator');
const spy = jest.spyOn(keyvault_emulator, 'storageConnectionString');
spy.mockReturnValue('mocked');
// ✅ it may work...but
expect(keyvault_emulator.storageConnectionString).toEqual('mocked')
// ❌ this fails!
expect(keyvault_emulator.testFunction()).toEqual('mocked')

So, what's the best way?

Is this the proper way to do this? What is the best way to accomplish this?

Like many cases in the world of devs, it depends on the case. Personally I'd pick a hard-decoupling method mentioned in 2-1 for general usage but there are many cases where it doesn't fit perfectly. Pick the one that best fits to your case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: using variables assingned in the script inside the proc in TCL i want to use the variable assigned outside  (proc) to be used inside the proc . For example i tried the following thing
set a 10
proc myproc { } {
puts $a
}
myproc

I am expecting the above script to print 10 . But the above script is erroring out "can't read "a": no such variable"
I cannot pass $a as argument to script because i have lot such variables i want to use inside my proc inside my script . Could you please help me to solve this problem ?
Your help is appreciated

A: If the variable is declared at the same stack level as the call to myproc then you can do following in your proc:
upvar a a

like this:
set a 10
proc myproc { } {
    upvar a a
    puts $a
}
myproc

and then you can use $a locally in the procedure. The upvar command "links" a variable declared somewhere in the stack with a local variable. If the variable is declared more than 1 level deeper in the stack, thn you need to pass "2" to upvar, so it knows where to look for the variable:
upvar 2 a a

If you don't pass the "2" (or other value), the upvar assumes default lookup depth of 1.
You can read more details about upvar in Tcl documentation for that command.
If the variable a is always a global variable (declared at the script top level), then you can use:
global a

in your procedure, instead of upvar.

A: If you have namespaces you could always assign it there :
namespace eval blah {
    variable a 10
}

proc blah::myproc { } {
    variable a
    puts $a
}
blah::myproc

This way you can avoid potential collisions with other global variables


text:
Q: Perl regular expression named groups array I'm trying to capture named groups in an array.
use strict;
use warnings;
use Data::Dumper;

my $text = 'My aunt is on vacation and eating some apples and banana';
$text =~ m/(?<Letter>A.)/img ;
print Dumper(%-) ;

output is
$VAR1 = 'Letter';
$VAR2 = [
          'au'
        ];

but I would expect or actually was hoping that any occurrence will appear in the array.
$VAR1 = 'Letter';
$VAR2 = [
          'au',
          'ac',
          'at',
          'an',
          'at',
          'an'
        ];

Any chance to get all groups in one array?

A: You can either run the m//g in list context to get all the matching substrings (but without the capture names), or you need to match in a loop:
my @matches = $text =~ m/(?<Letter>A.)/img ;
print Dumper(\@matches) ;

or
while ($text =~ m/(?<Letter>A.)/img) {
       print Dumper(\%+) ;
}


text:
Q: Difference between OTP Token and CSRF Token I'm searching for Preventing from URL Forgery.
Like example below
http://www.test.com/tranfer-money.do?value=1000000

If I could obtain any victim's session, I could send money what I want much.
I happened to find CSRF Technology
and I happend to find OTP Technology too.
I think they are exactly the same algorithm.
OTP is like it name says "One Time Password"
and Anti-CSRF is just one of a samples of OTP Architecture"
Isn't it?
The Algorithm is "Server gives to a client an un-predictable token, and Client will request with this token, and Server will verify"
Why I think like this is below Two Reason.
Independent Object issue a token.
At OTP perspective, Hardware or Application issue a unique(unpredictable) token
At Anti-CSRF perspective, WAS Server issue a unique(unpredictable) token
Whatever Issuer they are, The Important thing is The Independent Object from the Client Object issue a token.
The Independent Issuer Object issue a token once at a time.
At OTP, Hardware or Application issue a token just before a user's request for senstive information at Once.
At Anti-CSRF, WAS Server issue a token After user's login at Once too.
(We could make WAS Server issue token everytime. That's upon WAS Server Configuration. If I configure the server to work like this, Can you say that This WAS isn't Anti-CSRF Sever?)
What I want to know is What's the difference between CSRF Token and OTP Token.

A: OTP (One Time Password) and CSRF (Cross-Site Request Forgery) are different things.
OTP is an authentication mechanism. Some kind of application or hardware token is generating a string you can use to authenticate in a application. Famous example are the RSA tokens which implemented a time-based one time password protocol.

CSRF is a weakness of web applications which fail to verify if the user intentionally sent the request. When we speak about CSRF protection, we usually mean protection with anti-CSRF tokens. These tokens are generated by the server and passed by the client in every request that changes the state of the system. All requests without this token are rejected by the server.


text:
Q: How to schedule an R Script Cronjob in a linux server? I am trying to schedule a cronjob to execute an R Script in a linux server. I have achieved to type the commands in the server manually and it works. To do so i have to type the following commands:

*

*root@debian:~# cd /home/script2

*root@debian:/home/script2# Rscript scriptSecos.R

How can i specify a cronjob that will execute the previous commands, once a day?
Thank you.

A: The following cron job will run Rscript scriptSecos.R from the path /home/script2, once a day, at 0:00 (midnight).
0 0 * * * cd /home/script2; Rscript scriptSecos.R >/dev/null 2>&1

If you want to save the output of the script to a file, change >/dev/null with >/path/to/file.
You can copy and paste this cronjob in your crontab file (You can open the file by using command crontab –e)

A: The following site provides useful reference information for crontab
http://www.adminschoice.com/crontab-quick-reference
With your example, the following will run the job at 3 am everyday.
00      03      *       *       *       Rscript /home/script2/scriptSecos.R

A: add cron as below.
eg:
15 23 * * * Rscript /home/script2/scriptSecos.R  >/dev/null 2>&1

you have to mention running script type.Then allow cron logs and check its running or not


text:
Q: Installing Ms-Access 2003 standalone? Anyone knows if it is possible to install Access 2003 standalone without the rest of the Office 2003? I seem not to locate my installation disks to test this out, but thought someone might have an answer...

A: I believe so, when you install Office and choose custom install, you can deselect everything except Access.

A: You can do a custom install and then deselect everything.
You will basically get all the MS Office run-time and shared components with only the Access application available to run.
Note: I don't use the access run-time any more, but do use it regularly for the Excel and/or Word applications.


text:
Q: Blocking direct URL access in JSF web application In my project, I want to restrict direct URL access in my JSF web application. Although I found it on the web that give suggestions to configure security constraints in web.xml.
   <security-constraint>
    <display-name>Restrict raw XHTML Documents</display-name>
    <web-resource-collection>
        <web-resource-name>XHTML</web-resource-name>
        <url-pattern>/manage/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint />
    <user-data-constraint>
        <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
</security-constraint>

So that, I can restrict direct URL access to /manage/*.jsp. But I have many folders to restrict such as /view/*.jsp, /others/*.jsp, etc. And I want to show error page when occur.

A: You probably would have figured out the solution by now but thought of answering it.
Way to achieve the restriction is by having all the url-patterns as part of web-resource-collection. And you can define one another security-constraint without auth-constraint to allow direct access like below.
    <security-constraint>
        <display-name>Restrict raw XHTML Documents</display-name>
        <web-resource-collection>
            <web-resource-name>XHTML</web-resource-name>
            <url-pattern>/manage/*</url-pattern>
            <url-pattern>/view/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint />
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

<security-constraint>
    <display-name>Allow login pages</display-name>
    <web-resource-collection>
        <web-resource-name>Seam</web-resource-name>
        <url-pattern>*.seam</url-pattern>
        ...<!-- You can define all the url-patterns you want to allow direct access to -->

    </web-resource-collection>

</security-constraint>

You are using empty auth-constraint which means regardless of authentication, it blocks direct access to all the URL patterns listed. You will get 403 error and you can define a page for it with error page tag
<error-page>
    <error-code>403</error-code>
    <location>/path/to/error.jsp</location>
    </error-page>

Otherwise, you can use error-page tags to define error jsps.
<error-page>
<exception-type>anyexception class name</exception-type>
<location>/path/to/error.jsp</location>
</error-page>

A: one way would be to move the jsp files inside the web-inf directory which will block direct url accesss


text:
Q: Return Different Data Types in C Function I am having the following situation:
void func ()
{
    TEST_MACRO(....., ret_type)
    ..........
}

some_ptr* func2()
{
    TEST_MACRO(....., ret_type)
    ..........
}

int func3()
{
    TEST_MACRO(....., ret_type)
    ..........
}

I am having 3 types of functions. In each function, I have to do a range check for the same variable (local variable).
Depending upon the SUCCESS/FAILURE, I have to do the error handling in the Macro:
TEST_MACRO()
{
 // FAILURE
 if (ret_val == VOID_TYPE)
 {
    return;
 }
 else if (ret_val == RET_PTR)
 {
    return NULL;
 }
 else /* ret_val = INT */
 {
    return FAILURE;
 }
}

but ultimately, all the preprocessor code will land up into the same function.
Problem:

int func3 ()
{
  // Entire Error Handling
  if (..)
    return;
  else if(..)
    return NULL;
  else
    return FAILURE;
}

This is NOT possible, but to implement the SAME FUNCTIONALITY, i.e. doing a range check on the SIMILAR local variable, using 3 different Macros (one for each return type) doesn't seem to be a clean way.
Can somebody suggest me some good way of handling such a situation?

A: Flow-control macros notoriously evil. Instead make your macro yield a boolean value, and respond to that within your function. It's much clearer this way:
void func ()
{
    if(!TEST_MACRO(.....))
         return;
    ..........
}

int func ()
{
    if(!TEST_MACRO(.....))
         return FAILURE;
    ..........
}


text:
Q: SSRS Date Parameter auto postback I have created .rdl file with two date parameter. The report is working fine in local. But I am facing some difficulties after I integrated the rdl file into ASP.NET MVC application.
The problem is Date Parameter performs postback once I select the date. So I need to wait for some time to go with another parameter and  The performance of report is good  when  test it in local and Database.
Please share me if you have any solution.
Thanks.
Jay


text:
Q: Image gallery with max items and pagination with javascript This is my situation:
I have a image gallery with 10 images visible on the main page and a pagination bar. The images came from a for loop iteration over a json file. That's no problem, they are just there ;-)
Something like:
for i=0; i <10; i++
create div with styles and images[i].image;
My question is:
I want to display the next 10 images on page 2, so when you click on page 2, it counts from 11 to 20.
I found the jQuery 'Jpaginate'-plugin...
Can i accomplish that with this plugin?
Could someone explain me in the way i have to thing with Vars, Counts, Objects??
Thanks and kind regards,
Mike

A: You can create your own pagination  plugin.
You must store current page somewhere and modify your factory.
Something like: for i=current_page * count_per_page; i < count_per_page * (current_page + 1); i++ create div with styles and images[i].image;

A: I have made you an example on how you can approach this. I'm not saying it is bugproof, but it's the concept that matters. You might find some inspiration and maybe reach your goal.

var imgSrc = "https://s-media-cache-ak0.pinimg.com/236x/36/a5/7b/36a57b0f0ab16e885fcc230addb695c2.jpg";
var json = [];
for (var i = 0; i < 36; i++)
  json.push({
    Title: "Title " + (i + 1),
    Source: imgSrc
  });

/*
Just for ease, I'm creating an array with 36 objects (3x3 gallery)
so 9 images per page
*/

var pageLimit = 9;
var page = 1;

showImages();

$("#btnPrevious").click(function() {
  if (pageLimit <= 9) {
    pageLimit = 9;
    page = 1;
  } else {
    page--;
    pageLimit -= 9;
  }
  showImages();
});

$("#btnNext").click(function() {
  if (pageLimit >= json.length) {
    pageLimit = json.length;
  } else {
    page++;
    pageLimit += 9;
  }
  showImages();
});

function showImages() {
  $(".images").empty();
  for (var i = pageLimit - 9; i < pageLimit; i++) {
    var template = $("

").addClass("template");

    var img = $("");
    img.attr("src", json[i].Source);
    img.attr("alt", json[i].Title);

    var br = $("
");

    var title = $("").html(json[i].Title);

    template.append(img).append(br).append(title);

    $(".images").append(template);
  }
  $("#page").html("Page " + page);
}
.gallery {
  width: 100%;
  height: 500px;
  border: 1px solid black;
  background-color: lightgray;
  text-align: center;
}
.images {
  width: 90%;
  margin: 0 auto;
  height: 100%;
  margin-bottom: 15px;
}
img {
  height: auto;
  width: 33%;
  margin: 20px 5px;
}
.template {
  float: left;
}

  <button id="btnPrevious">
    < Previous
  </button>

  <button id="btnNext">
    > Next
  </button>

Don't mind the CSS, because I suck at that (lol). It was based on the space I had on jsFiddle, but looking at it now (on full page or just the area the snippet provides) it looks awful. If a CSS guru could fix this .. Question in a question?


text:
Q: React Js server start failed I am trying to start React Js server by using command "npm start" but it is showing following error on console:
prateek@localhost:~/WebstormProjects/untitled> npm start

> untitled@0.1.0 start /home/prateek/WebstormProjects/untitled
> react-scripts start

Could not find an open port at localhost.localdomain.
Network error message: getaddrinfo ENOTFOUND localhost.localdomain

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! untitled@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the untitled@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output     above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/prateek/.npm/_logs/2017-09-29T05_33_18_507Z-debug.log

I am using npm 5.3.0 and node 8.4.0 on Linux.
The npm log file below:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node8', '/usr/bin/npm-default', 'start' ]
2 info using npm@5.3.0
3 info using node@v8.4.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle untitled@0.1.0~prestart: untitled@0.1.0
6 info lifecycle untitled@0.1.0~start: untitled@0.1.0
7 verbose lifecycle untitled@0.1.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle untitled@0.1.0~start: PATH: /usr/lib64/node_modules/npm8/bin/node-gyp-bin:/home/prateek/WebstormProjects/untitled/node_modules/.bin:/usr/lib64/mpi/gcc/openmpi/bin:/usr/local/bin:/usr/bin:/bin:/usr/lib/mit/bin:/usr/lib/mit/sbin
9 verbose lifecycle untitled@0.1.0~start: CWD: /home/prateek/WebstormProjects/untitled
10 silly lifecycle untitled@0.1.0~start: Args: [ '-c', 'react-scripts start' ]
11 silly lifecycle untitled@0.1.0~start: Returned: code: 1  signal: null
12 info lifecycle untitled@0.1.0~start: Failed to exec start script
13 verbose stack Error: untitled@0.1.0 start: `react-scripts start`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib64/node_modules/npm8/lib/utils/lifecycle.js:289:16)
13 verbose stack     at emitTwo (events.js:125:13)
13 verbose stack     at EventEmitter.emit (events.js:213:7)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib64/node_modules/npm8/lib/utils/spawn.js:40:14)
13 verbose stack     at emitTwo (events.js:125:13)
13 verbose stack     at ChildProcess.emit (events.js:213:7)
13 verbose stack     at maybeClose (internal/child_process.js:927:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
14 verbose pkgid untitled@0.1.0
15 verbose cwd /home/prateek/WebstormProjects/untitled
16 verbose Linux 4.11.8-2-default
17 verbose argv "/usr/bin/node8" "/usr/bin/npm-default" "start"
18 verbose node v8.4.0
19 verbose npm  v5.3.0
20 error code ELIFECYCLE
21 error errno 1
22 error untitled@0.1.0 start: `react-scripts start`
22 error Exit status 1
23 error Failed at the untitled@0.1.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

Can someone please tell me that how can I fix this error?

A: It appears like something else is running on the development port for react (port 3000). Run the command sudo lsof -n -i :3000 | grep LISTEN and then either close the program that is using the port or use sudo kill {PID} (replace {PID} with the PID found using the first command).


text:
Q: Automate AutoCAD 3D model generation I want to use AutoCAD to generate a 3D model which is composed of many basic 3D geometries such as sphere, cube, etc.
I have the dimensions and the origin and orientation of the local coordinate system of the basic geometries. The data are stored in an Excel file. Each row of the excel data corresponds to one geometry and the columns are for dimensions, origin coordinates, and orientations. The data format is defined for each type of geometry.
I wanted to use AutoLisp or VBA or some other macro tool for AutoCAD to automate this process so that when the data is changed, I just need to run the macro to read the data and regenerate the AutoCAD 3D model.
What is the best solution?

A: There is no "best" solution for the general case. If you have experience with AutoLISP, use AutoLISP. If you have and use Visual Studio, use the ObjectARX .NET API. You could also write an Excel macro that generates a simple script file, use VBA inside AutoCAD, or drive AutoCAD from within Excel. The "best" way in your case is whichever way you feel most comfortable with.


text:
Q: Putting orphaned text into tags with HTMLAgilityPack How do I convert the syntax of a piece of html like this

     some text

     goes in here

     with only br tags

     to separate it

to this

some text

goes in here

with only br tags

to separate it

using HTML Agility Pack in c#?

A: One possible way :
var html = @"

     some text

     goes in here

     with only br tags

     to separate it

";
var doc = new HtmlDocument();
doc.LoadHtml(html);
var div = doc.DocumentNode.SelectSingleNode("div");
//select all non-empty text nodes within

var texts = div.SelectNodes("./text()[normalize-space()]");
foreach (var text in texts)
{
    //remove current text node
    text.Remove();
    //replace with :
current text node content

    var p = doc.CreateElement("p");
    p.AppendChild(doc.CreateTextNode(text.InnerText));
    div.PrependChild(p);
}
//remove all
 tags within

foreach (var selectNode in div.SelectNodes("./br"))
{
    selectNode.Remove();
}
//print result
Console.WriteLine(doc.DocumentNode.OuterHtml);

A: I took a slightly different approach, treating the innerHTML of the div as text, I split it using
. It's a bit of a hack but it works.
var html = @"

     some text

     goes in here

     with only br tags

     to separate it

";

var doc = new HtmlDocument();
doc.LoadHtml(html);

var divs = doc.DocumentNode.Descendants("div");
//select all non-empty text nodes within

foreach (var div in divs)
{
    // create a list of p nodes
    var ps = new List<HtmlNode>();

    // split text by "
"
    var texts = div.InnerHtml.Split(new string[]{ "
" }, StringSplitOptions.None);

    // iterate over split text
    foreach (var text in texts)
    {
        // if the line is not empty, add it to the collection
        if (!string.IsNullOrEmpty(text.Trim()))
        {
            var p = doc.CreateElement("p");
            p.AppendChild(doc.CreateTextNode(text));
            ps.Add(p);
        }
    }

    // join the p collection and paste it into the div
    div.InnerHtml = string.Join("", ps.Select(x => x.OuterHtml));
}


text:
Q: Python take screenshot and display image in html tag I'm trying show a screenshot .png, take it with my python script in the browser. But i don't know why but i can't see the image!
Script Located at /var/www/cgi-bin/web.py
from selenium import webdriver

self.driver = webdriver.Phantomjs()

self.driver.get("http://www.google.com")

try:
    # print "Take a picture"
    picture = (''.join(random.choice(string.letters + string.digits) for n in xrange(10)))
    self.driver.save_screenshot((picture) + '.png')
    print "Content-type:text/html\r\n\r\n"
    print ""
    print ""
    print "<title>%s</title>" % self.driver.title
    print ""
    print ""
    print "
ScreenShot: %s.png
" % (picture)
    print "" % (picture)
    print ""
    print ""
except IOError:
    print "Error take a picture!"
    pass

But a can't show the image on my browser the message error is:
(13)Permission denied: exec of '/var/www/cgi-bin/fBgshhFbuJ.png'

What's wrong with my script?

Let me explain a little more what i trying do.
I've a form html what a send two strings to my python script and it take a screenshot, in the /var/www/cgi-bin folder. I wish to display the png file in a container or div html but inside the another html file specifically.
So is it possible?
I change the permission of folder /var and others subfolder, but i recieve the same error message.
Thanks

A: You don't have access to write in the folder /var/www/cgi-bin/ probably more specifically the /var/ folder. If you change your script location to somewhere that you can have permission to write to, or the download location of your picture, then your program should work fine.
Edit
if you delete IOError from your except, you should be able to print the message and pass the error


text:
Q: How do I check if a list of strings is in another list of strings? Example
description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel']

my_list = ['travel','fire']

I would like to check if ANY of the words on my_list is in description, if so don't do anything. If my_list is not in description I would like to return the string 'Keywords not found'.
How would I go about writing this code?

A: You can use all with a double list comprehension:
description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel']
my_list = ['travel','fire']
def response():
   return "found" if any(i in b for i in my_list for b in description) else "Keywords not found"

A: Save words in a set and check whether a word in my_list is in the set. This only works when there is no phrases in my_list. i.e. all words in my_list is a unigram.
description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel']
my_list = ['travel','fire']
set_words_in_description = set()
for s in description:
    # add new words in set_words_in_description
    set_words_in_description.update(set(w for w in s.split()))

Using isdisjoint
def find_word_method_disjoint(my_list, set_words_in_description):
    # check if my_list is disjoint with set_wrods_in_description
    return not set_words_in_description.isdisjoint(my_list)

%timeit find_word_method_disjoint(my_list, set_words_in_description)
189 ns ± 1.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit response()  # function given by the accepted answer.
572 ns ± 9.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

A: You could use re.findall() to extract all the words from the sentences in description, and check if any of the words from my_list exist in it:
import re

def find_words(words, text):
    desc_words = re.findall(r'[^\s,.]+', "".join(text))

    for word in words:
        if word in desc_words:
            return "found"

    return "Keywords not found"

Which outputs:
>>> description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel']
>>> my_list = ['travel','fire']
>>> find_words(my_list, description)
found

Or you could use this set() approach:
def find_words(words, text):
    return "found" if set(words).intersection(re.findall(r'[^\s,.]+', "".join(text))) else "Keywords not found"

Note: You will have to update your regular expression if you come across sentences with different punctuation other than ,..

A: You can try set something like this ?
description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel']

my_list = ['travel','fire']

flat=[k for i in description for k in i.split()]

print(any({i}.issubset(set(flat))for i in my_list))

output:
True


text:
Q: Views in list are not at the corrects size I have a list view and an adapter. My problem is that the rows in the list are always "wrap content" even though I specifically stated the height as "150dp".
This is my adapter:
private class LiveEventsAdapter extends BaseAdapter {

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View contentView = convertView;
        if (contentView == null) {
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            contentView = inflater.inflate(R.layout.live_match_row, null);
            TypefaceManager.getInstance(LiveMatchActivity.this).assignTypeface(contentView);
        }

        if (events != null) {
            Event event = events.getEventsList().get(position);

            TypefaceManager typefaceManager = TypefaceManager.getInstance(LiveMatchActivity.this);
            TextView eventText;
            TextView minute;
            ImageView eventIcon;

            minute = (TextView) contentView.findViewById(R.id.live_match_minute);
            if (event.getOrientation().equals("home")) {
                eventText = (TextView) contentView.findViewById(R.id.home_team_event_text);
                eventIcon = (ImageView) contentView.findViewById(R.id.home_team_event_img);
            } else {
                eventText = (TextView) contentView.findViewById(R.id.away_team_event_text);
                eventIcon = (ImageView) contentView.findViewById(R.id.away_team_event_img);
            }
            minute.setText(event.getMinute() + "\'");
            eventText.setText(event.getDescription());
            minute.setTypeface(typefaceManager.getTypeface("bold"));
            eventText.setTypeface(typefaceManager.getTypeface("bold"));
        }
}

That's how I "setadapter":
ListView eventsListView = (ListView) findViewById(R.id.live_match_list);
        eventsListView.setAdapter(new LiveEventsAdapter());

and that's my rows layout:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="@drawable/background_button" >

<TextView
    android:id="@+id/live_match_minute"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="82'" />

<TextView
    android:id="@+id/home_team_event_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="false"
    android:layout_alignRight="@+id/home_team_event_img"
    android:layout_centerVertical="true"
    android:paddingLeft="4dp"
    android:paddingRight="4dp" />

<ImageView
    android:id="@+id/home_team_event_img"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="4dp"
    android:layout_toLeftOf="@+id/live_match_minute" />

<ImageView
    android:id="@+id/away_team_event_img"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="false"
    android:layout_centerVertical="true"
    android:layout_marginLeft="4dp"
    android:layout_toRightOf="@+id/live_match_minute" />

<TextView
    android:id="@+id/away_team_event_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="false"
    android:layout_centerVertical="true"
    android:layout_toRightOf="@+id/away_team_event_img"
    android:paddingLeft="4dp"
    android:paddingRight="4dp" />

Why is it that the rows in my list are always set on the same size, no matter what I put in?

A: This will NOT work.
This is what you should do.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:background="@drawable/background_button" >

        <TextView
            android:id="@+id/live_match_minute"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="82'" />

    </RelativeLayout>
</RelativeLayout>

Basically, add another layout and specify the height to that layout.
When working with adapter views specifying a height for the root layout doesn't work.


text:
Q: Git fetch hangs I have my working copy of git repository (not bare repo). I also setup local jenkins and my jobs were pointing to this repo. Everything worked fine. I think I've updated jenkins yesterday and this morning I discovered that my jobs started failing. Because they can not fetch source from my repo (it gets timeout).
So I started investigation. I decided to repeat git command lines in terminal to check if I can report the issue. Here is what I'm doing:
git config remote.origin.url file:///Users/eugenmartynov/Development/source/company/app-android
git fetch origin

And it hangs. And I don't have a clue what to check else.
I have git version 2.8.3. But it doesn't matter because I see same behaviour with using default version from Xcode tools
This is what I see if I try turn git trace logging:
git fetch origin
14:25:53.549772 git.c:350               trace: built-in: git 'fetch' 'origin'
14:25:53.553987 run-command.c:336       trace: run_command: 'git-upload-pack '\''/Users/eugenmartynov/Development/source/company/app-android/.git'\'''
14:25:53.554490 run-command.c:195       trace: exec: '/bin/sh' '-c' 'git-upload-pack '\''/Users/eugenmartynov/Development/source/company/app-android/.git'\''' 'git-upload-pack '\''/Users/eugenmartynov/Development/source/company/app-android/.git'\'''
14:25:53.570196 run-command.c:336       trace: run_command: 'rev-list' '--objects' '--stdin' '--not' '--all' '--quiet'

Here is log for past success job:
Started by an SCM change
Building in workspace /Users/eugenmartynov/.jenkins/workspace/android-feature-lov-563-general-cards
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url file:///Users/eugenmartynov/Development/source/company/app-android/.git # timeout=10
Fetching upstream changes from file:///Users/eugenmartynov/Development/source/company/app-android/.git
 > git --version # timeout=10
 > git -c core.askpass=true fetch --tags --progress file:///Users/eugenmartynov/Development/source/company/app-android/.git +refs/heads/*:refs/remotes/origin/*
 > git rev-parse refs/remotes/origin/feature/lov-563-general-cards^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/feature/lov-563-general-cards^{commit} # timeout=10
Checking out Revision 932fc80699e765c1854c52051e0605698196d707 (refs/remotes/origin/feature/lov-563-general-cards)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 932fc80699e765c1854c52051e0605698196d707
 > git rev-list d35e0f1cee060b91366840296efc08854a8257b0 # timeout=10
 ....

Here is log for first failed job:
Started by an SCM change
Building in workspace /Users/eugenmartynov/.jenkins/workspace/android-feature-lov-563-general-cards
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url file:///Users/eugenmartynov/Development/source/company/app-android/.git # timeout=10
Fetching upstream changes from file:///Users/eugenmartynov/Development/source/company/app-android/.git
 > git --version # timeout=10
 > git -c core.askpass=true fetch --tags --progress file:///Users/eugenmartynov/Development/source/company/app-android/.git +refs/heads/*:refs/remotes/origin/*
ERROR: Timeout after 10 minutes
ERROR: Error fetching remote repo 'origin'
hudson.plugins.git.GitException: Failed to fetch from file:///Users/eugenmartynov/Development/source/company/app-android/.git
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:810)
    at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1066)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1097)
    at hudson.scm.SCM.checkout(SCM.java:485)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1269)
    at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:604)
    at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:529)
    at hudson.model.Run.execute(Run.java:1741)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:410)
Caused by: hudson.plugins.git.GitException: Command "git -c core.askpass=true fetch --tags --progress file:///Users/eugenmartynov/Development/source/company/app-android/.git +refs/heads/*:refs/remotes/origin/*" returned status code 141:
stdout:
stderr:
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1719)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1463)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:63)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:314)
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:808)
    ... 11 more
ERROR: null

A: I guess you are using wrong url. For a local path you just use the path. Your url looks like an UNC path, i.e. Users is a host name and the rest is shared directory. So, it tries to resolve a host name which could take some time.
Your url is missing disk name. I guess it is Windows.
So, you could just provide full path, I guess git remote set-url origin c:/Users/eugenmartynov/Development/source/company/app-android. Or if I am right, you could put more slashes: file://///c:/....
BTW, git fetch could accept URLs, not necessary to add remotes.


text:
Q: Count unique occurrences of factor levels and numeric values with dplyr, on data in a long format I have data on repeated measurements of 8 patients, each with varying amount of repeated measurements on the same variables. The measured variables are sex, blood pressure (sys_bp), and how many CT scans a person underwent:
library(dplyr)
library(magrittr)

questiondata <- structure(list(id = c(2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4,
4, 7, 7, 8, 8, 8, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 20,
20, 20), time = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 5L,
1L, 2L, 3L, 4L, 5L, 1L, 6L, 1L, 2L, 5L, 1L, 2L, 3L, 4L, 5L, 1L,
2L, 3L, 4L, 5L, 1L, 2L, 4L), .Label = c("T0", "T1M0", "T1M6",
"T1M12", "T2M0", "FU1"), class = "factor"), sys_bp = c(116, 125.8,
NA, NA, NA, 113.2, NA, NA, NA, NA, 146, NA, NA, NA, NA, NA, NA,
125, NA, NA, 164.5, NA, NA, NA, NA, 150.5, NA, NA, NA, NA, 158,
NA), sex = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 1L, 1L, 1L), .Label = c("female", "male"), class = "factor"),
    ct_amount = c(4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
    5L, 5L, 5L, 2L, 2L, 3L, 3L, 3L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
    5L, 5L, 5L, 3L, 3L, 3L)), row.names = c(NA, -32L), class = c("tbl_df",
"tbl", "data.frame"))

questiondata

      id time  sys_bp sex    ct_amount
   <dbl> <fct>  <dbl> <fct>      <int>
 1     2 T0      116  female         4
 2     2 T1M0    126. female         4
 3     2 T1M6     NA  female         4
 4     2 T1M12    NA  female         4
 5     3 T0       NA  female         5
 6     3 T1M0    113. female         5
 7     3 T1M6     NA  female         5
 8     3 T1M12    NA  female         5
 9     3 T2M0     NA  female         5
10     4 T0       NA  male           5
11     4 T1M0    146  male           5
12     4 T1M6     NA  male           5
13     4 T1M12    NA  male           5
14     4 T2M0     NA  male           5
15     7 T0       NA  female         2
16     7 FU1      NA  female         2
17     8 T0       NA  female         3
18     8 T1M0    125  female         3
19     8 T2M0     NA  female         3
20    13 T0       NA  female         5
21    13 T1M0    164. female         5
22    13 T1M6     NA  female         5
23    13 T1M12    NA  female         5
24    13 T2M0     NA  female         5
25    14 T0       NA  male           5
26    14 T1M0    150. male           5
27    14 T1M6     NA  male           5
28    14 T1M12    NA  male           5
29    14 T2M0     NA  male           5
30    20 T0       NA  female         3
31    20 T1M0    158  female         3
32    20 T1M12    NA  female         3

I am trying to count the number of persons that (1) is male/female (2) has 1/2/3/4/5 CT scans.
So the output would be that there are (1) 6 females and 2 males, and (2) 1 person with 2 CTs, 2 persons with 3 CTs, 1 person with 4 CTs and 4 persons with 5 CTs.
I've tried many combinations of group_by and summarise and count, but can't seem to get it right. Any help?

A: You can first keep only the unique rows for each id. Then use count to get the output.
library(dplyr)

unique_data <- questiondata %>% distinct(id, .keep_all = TRUE)

unique_data %>% count(sex)
# A tibble: 2 x 2
#  sex        n
#  <fct>  <int>
#1 female     6
#2 male       2

unique_data %>% count(ct_amount)

# A tibble: 4 x 2
#  ct_amount     n
#      <int> <int>
#1         2     1
#2         3     2
#3         4     1
#4         5     4

A: We could use duplicated with filter
library(dplyr)
questiondata %>%
     filter(!duplicated(id)) %>%
     count(ct_amount)
# A tibble: 4 x 2
  ct_amount     n
      <int> <int>
1         2     1
2         3     2
3         4     1
4         5     4


text:
Q: javascript should open a random page after 7 seconds, but how? I have this html page, with javascript code, but I can not get the code to open one of the cases 3 pages, the settimeout works, but to connect the random selected page work, I have enclosed the code cf. below, if I am some skilled javascript people who can tell what needs to be done to make it work I would be grateful.
the browser open this up
http://localhost:62206/'sitelist[ran]'
my html and javascript code below here

    <meta charset="utf-8" />
    <title></title>

Hello World!

`

A: It is Array() not array.
And you wrapped the sitelist[ran] in "' '" for some reason, remove that.
When you use quotes, you create a string, but I don't think that's what you want to do there.

A: or you can just declare it as simple as that
var sitelist = [];

A: hope you doing well, here are some minor changes to your code to solve your problems, i'll answer to questions if necessary.

    <meta charset="utf-8" />
    <title></title>

Hello World!


text:
Q: Magento 2.3 : Use a dropdown select for the shipping address on the Onepage Checkout select the shipping address with a dropdown, similar to how you can if you choose to change the billing address.

I would like it to work similarly to when you change the billing address, with a dropdown:

A: Have you got any further with this?
You could update checkout/shipping-address/list.html

 1)">
    <select class="select" name="shipping_address_id" data-bind="
        options: shippingAddressOptions,
        optionsText: shippingaddressOptionsText,
        value: selectedShippingAddress,
        event: {change: onShippingAddressChange(selectedShippingAddress())};
    "></select>

Then can have your custom shipping.js Update from 'use strict' of the current
'use strict';

        var popUp = null,

        newShippingAddressOption = {
            getAddressInline: function () {
                return $t('New Address');
            },
            customerAddressId: null
        },

        shippingAddressOptions = addressList().filter(function (address) {
            return address.getType() == 'customer-address';
        });

        shippingAddressOptions.push(newShippingAddressOption);

    return Component.extend(
        {
            defaults: {
                template: 'Magento_Checkout/shipping'
            },
            visible: ko.observable(!quote.isVirtual()),
            errorValidationMessage: ko.observable(false),
            isCustomerLoggedIn: customer.isLoggedIn,
            isFormPopUpVisible: formPopUpState.isVisible,
            isFormInline: addressList().length == 0,
            isNewAddressAdded: ko.observable(false),
            saveInAddressBook: 1,
            quoteIsVirtual: quote.isVirtual(),
            currentShippingAddress: quote.shippingAddress,
            shippingAddressOptions: shippingAddressOptions,
            customerHasShippinhAddresses: shippingAddressOptions.length > 1,

Then add to the file
/**
             * @return {exports.initObservable}
             */
            initObservable: function () {
                this._super()
                    .observe({
                        selectedShippingAddress: null,
                        isShippingAddressDetailsVisible: quote.shippingAddress() != null,
                        isShippingAddressFormVisible: !customer.isLoggedIn() || shippingAddressOptions.length === 1,
                        saveInAddressBook: 1
                    });

                quote.shippingAddress.subscribe(function (newShippingAddress) {
                    if (newShippingAddress != null && newShippingAddress.saveInAddressBook !== undefined) {
                        this.saveInAddressBook(newShippingAddress.saveInAddressBook);
                    } else {
                        this.saveInAddressBook(1);
                    }
                    this.isShippingAddressDetailsVisible(true);
                }, this);

                return this;
            },

            /**
             * @param {Object} address
             * @return {*}
             */
            shippingaddressOptionsText: function (address) {
                return address.getAddressInline();
            },

            /**
             * @param {Object} address
             */
            onShippingAddressChange: function (address) {
                this.isShippingAddressFormVisible(address == newShippingAddressOption); //eslint-disable-line eqeqeq
            },

            /**
             * Update address action
             */
            updateAddress: function () {

                var addressData, newShippingAddress;

                if (this.selectedShippingAddress() && this.selectedShippingAddress() != newShippingAddressOption) { //eslint-disable-line eqeqeq
                    selectShippingAddress(this.selectedShippingAddress());
                    checkoutData.setSelectedShipppingAddress(this.selectedShippingAddress().getKey());
                } else {
                    this.source.set('params.invalid', false);
                    this.source.trigger(this.dataScopePrefix + '.data.validate');

                    if (this.source.get(this.dataScopePrefix + '.custom_attributes')) {
                        this.source.trigger(this.dataScopePrefix + '.custom_attributes.data.validate');
                    }

                    if (!this.source.get('params.invalid')) {
                        addressData = this.source.get(this.dataScopePrefix);

                        if (customer.isLoggedIn() && !this.customerHasAddresses) { //eslint-disable-line max-depth
                            this.saveInAddressBook(1);
                        }
                        addressData['save_in_address_book'] = this.saveInAddressBook() ? 1 : 0;
                        newShippingAddress = createShippingAddress(addressData);

                        // New address must be selected as a billing address
                        selectedShippingAddress(newShippinhAddress);
                        checkoutData.setSelectedShippingAddress(newShippingAddress.getKey());
                        checkoutData.setNewCustomerShippingAddress(addressData);
                    }
                }
                this.updateShippingAddresses();
            },

            /**
             * Trigger action to update shipping and billing addresses
             */
            updateShippingAddresses: function () {
                setShippingAddressAction(globalMessageList);
            },

This will get you to where I'm at. Which is - how do we get this to continue onwards

A: The templates for shipping address section are here :
vendor/magento/module-checkout/view/frontend/web/template/shipping-address/list.html

and
vendor/magento/module-checkout/view/frontend/web/template/shipping-address/address-renderer/default.html

You can override the same in your theme like this app/design/frontend/Vendor/theme/Magento_Checkout/web/template/shipping-address/list.html
As you wish to list the addresses in select dropdown you need to change the code like this:

        <select class="select" name="shipping_address_id" data-bind="
        options: addressOptions,
        optionsText: addressOptionsText,
        optionsValue: addressOptionsValue,
        value: selectedAddress,
        selectedOptions: selectedAddress,
        event: {change: selectAddress(selectedAddress())};
    "></select>

The js files are located here:
vendor/magento/module-checkout/view/frontend/web/js/view/shipping-address/list.js

and
vendor/magento/module-checkout/view/frontend/web/js/view/shipping-address/address-renderer/default.js

You can override the same like this: app/design/frontend/Vendor/theme/Magento_Checkout/web/js/view/shipping-address/list.js
You can refer to this file vendor/magento/module-checkout/view/frontend/web/js/view/billing-address.js for writing functions like addressOptions, addressOptionsText etc.


text:
Q: How to populate data from three nested foreach loops sequentialy? I have 3 tables "Questions", "Answers", & "Results". I want to fetch multiple rows from 3 tables, one by one and display it sequentialy.
PROGRAM
$questions = Questions::find_by_qpno($qpno);
$answers = Answers::find_by_apno($apno);
$results = Results::find_by_rno($rno);

foreach($questions as $question) {
  echo "Question";
  echo $question->question;
}

foreach($answers as $answer) {
  echo "Answer";
  echo $answer->answer;
}

foreach($results as $result) {
  echo "Result";
  echo $result->remark;
}

OUTPUT
Question
What is software engineering?
Question
What are SDLC models available?

Answer
Software engineering is making softwares
Answer
Waterfall , spiral etc

Remark
It is correct Software engineering is making softwares.
Remark
good Waterfall , spiral etc correct

WANT
Question 1
Answer 1
Remark 1

Question 2
Answer 2
Remark 2

Need a Simple way to nest 3 foreach loops so that I get it in the order Question - Answer - Remark ?
note: I know I could count objects from the SQL query. put $count = count($questions). and use a for loop for($i=1 ; i<=$count ; $i++) and iterate through these three sequentialy. but it looks ugly.
What is the best way to do this ?


text:
Q: i want the data that is in form component to be shown when pickup button is clicked i want the data that is in form component to be shown when pickup button is clicked. the data from myvehicles to be entered inside the pickup component, when the yes or no button is clicked. i have tried like this but it doesnot work.
import React,{ useState } from 'react'
import './Pickup.css'
import logo from './images/logo.png'
import { Link, useHistory } from "react-router-dom";
import InfoYes from './InfoYes'
import InfoNo from './InfoNo'

function Pickup() {
    const [showInfoYes, setShowInfoYes] = useState(false);
    const [showInfoNo, setShowInfoNo] = useState(false);
    const history = useHistory()

    return (

<Link to="/" className="header__link">

</Link>

<button className="navbar__button" onClick={() => history.push('/')}>Logout</button>

do you want bluebook pickup service?

            <button className="yes__button" onClick={() => setShowInfoYes(!showInfoYes)}>yes</button>
            <button className="no__button" onClick={() => setShowInfoNo(!showInfoNo)}>no</button>

            {showInfoYes && <InfoYes setShowInfoYes={setShowInfoYes} />}

            {showInfoNo && <InfoNo setShowInfoNo={setShowInfoNo} />}

    )
}

export default Pickup

A: I think you may be able to achieve this through conditional rendering.
Which involves if statements and true & false conditions.
Please look at this documentation to see how this works. Documentation
(Reactjs.org has really great documentation, I really encourage you go through it.)
No where in your code, I see your state to be set TRUE for it to render.
You'll need to create an onClick handler to set this to true or false.
A quick example would be:
    const [userClicked, setUserClicked] = useState(false);

    { userClicked ?

    ( <button onClick={() => setUserClicked(false)> No </button>

   ) : (

     <button onClick={() => setUserClicked(true)> Yes </button>

    )}

This is a shorthand of a ternary operator to produce an if/then statement in react.
It would be the easiest to accomplish your goal, although I do suggest that you research a little bit more on it!
{userClicked ? ( ) : ( ) }
You could also take out:
const [showInfoYes, setShowInfoYes] = useState(false);
const [showInfoNo, setShowInfoNo] = useState(false);

It's a bit redundant as you're trying to achieve something that could be done in a singular state.


text:
Q: Make sure the broker holds messages until at least one consumer gets it I am begining to implement an ActiveMQ based messaging service to send worker tasks to various servers, however I am noticing that in the default mode, if no one is "listening" to a producer's topic, any message from that producer will be lost.
I.e.,

*

*If Producer Senders Message with a live broker

*But No Consumer is there to listen

*Message goes no where

I would like instead for the Broker to hold on to messages until at least one listener receives it.
I am trying a couple ways of implementing this, but not sure on the most optimal/right way way:

*

*Implement a Message Acknowledgement feature

*(Caveat to this is I need the producer to wait on its listener after every message which seems very, very clunky and last resort...)

*Implement the Session Transaction

*(I am having trouble with this one, it sounds like the right thing to use here because of the word transaction, but I think it has more to do with the producer-broker interaction, not the producer-consumer)

Ideally, there is a mode to send a (or a set of) messages, and after sending a Boolean is returned stating if the message(s) were listened by at least one consumer.

A: Transactions and acknowlegdement conflict somehow with the general idea of a JMS topic.
Just use a queue instead of a topic. Access this queue using CLIENT_ACKNOWLEDGE or a transacted session. A worker task is to be processed by one worker only anyway, so the queue solves another problem.

If there was a special reason to use topics, you could consider a message driven bean (MDB) on the same host like the JMS provider (you could achieve this by using JBoss with its integrated HornetQ for example), but this is still not really correct.
Another possibility is to have both a topic and a queue. The latter is only for guaranteed delivery of each message.

A: This isn't really a typical messaging pattern.  Typically, you have one receiver and a durable queue or multiple receivers with durable subscriptions to a topic.  in either situation, each receiver will always receive the message.  i don't really understand a use case where "at least one" receiver should receive it.
and yes, transactions only deal with the interactions between client and broker, not between client and eventual receiver(s).


text:
Q: undefined method `encrypted_password=' for # I have got this error NoMethodError in Devise::RegistrationsController#create and i don´t knew how i fixed it. If i try make new regisration, the server loading long time and after this i see this error.
My migration looks like this:
class DeviseCreateRegistrationsControllers < ActiveRecord::Migration
  def change
    create_table(:registrations_controllers) do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""
       #t.string :encrypted_password, :null => false, :default => ""
      t.database_authenticatable :null => false
      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      t.timestamps null: false
    end

    add_index :registrations_controllers, :email,                unique: true
    add_index :registrations_controllers, :reset_password_token, unique: true
    # add_index :registrations_controllers, :confirmation_token,   unique: true
    # add_index :registrations_controllers, :unlock_token,         unique: true
  end
end

my registration controller looks like this:
class RegistrationsController < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  t.string :encrypted_password, :null => false, :default => ""
end

and my views/devise/registration/new.html.erb look like this

Register

  <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
    <%= devise_error_messages! %>

<%= f.email_field :email, autofocus: true, placeholder: "Email", class: "radius" %>

<%= f.password_field :password, autocomplete: "off", placeholder: "Password", class: "radius" %>

<%= f.password_field :password_confirmation, autocomplete: "off", placeholder: "Confirm password", class: "radius" %>

<%= f.submit "Let's Go", class: "button" %>

  <% end %>
  <%= render "devise/shared/links" %>

Please help, thanks.

A: Everything looks like a mess. RegistrationsController should be model User instead because it extends ActiveRecord::Base and those lines:
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

are also from devise for User model.
Why you have t.string :encrypted_password, :null => false, :default => "" in your RegistrationsController(actually it should be model I mentioned above) ?
It must be copy paste fault somewhere. Please check the whole project again or re-create new Rails application then install Devise from clean project.


text:
Q: Query to insert row after a specific amount of time I am working on customized shopping cart application.
It have a hits table:
id            int
product_id    int
hit_time      datetime
session_id    varchar

Now when someone views a product, I record a hit.
I need a query such that, record should be inserted only if hit_time has a difference of 30 mins (for same product_id, and session_id)
For example:
When recording first hit
id             product_id             hit_time                session_id
------------------------------------------------------------------------
1                  1                  2011-01-01 06:30:00      abcxyzmno
2                  5                  2011-01-01 06:32:00      abcxyzmno

Now, if visitor with same session_id, visit product page with product_id =1 in less than 30 mins, then data should not be inserted
So below row should not be inserted (because there is difference of 5 mins only)
3                  1                  2011-01-01 06:35:00      abcxyzmno

But if visitor visit after 30 mins, for same product, it should be recorded
3                  1                  2011-01-01 07:01:15      abcxyzmno

I want single insert query
I DON'T want 2 query, first to select max-time from table, and then insert it
Any help?

A: Are you looking for something like this?
INSERT INTO hits (product_id, hit_time, session_id)
SELECT $product_id, current_timestamp, $session_id
FROM hits
WHERE NOT EXISTS (
        SELECT id
        FROM hits
        WHERE product_id = $product_id
          AND session_id = $session_id
   )
   OR (
            product_id = $product_id
        AND session_id = $session_id
        AND hit_time   < current_timestamp - 30*60
   )
LIMIT 1

Where $product_id and $session_id are the product and session IDs.
The NOT EXISTS part takes care of the case where (product_id,session_id) hasn't been recorded yet and the second part takes care of the case where (product_id,session_id) is there but it was longer than 30 minutes ago. And, of course, the LIMIT 1 in case (product_id,session_id) is there and older than 30 minutes ago and appears multiple times.


text:
Q: Render Bootstrap modal from partial in rails I am attempting to clean up my code a bit by placing my modal code inside of a partial, however I am encountering problems when trying to call the modal.
I tried the solution provided by How to show twitter bootstrap modal via JS request in rails?, but if I understand correctly I have to add code to a particular controller to display the modal. That would be fine however I would like to display the modal regardless of the controller/view it is in. Is this possible?
What I have (completely from the above question):
current link (views/static_pages)
<%= link_to "ModalTest", 'shared/testmodal', {:remote => true, 'data-toggle' => 'modal', 'data-target' => "testmodal" }%>

show.js.erb
$('.modal-body').html('<%= escape_javascript(render :partial => 'shared/testmodal'%>');
$('.modal-header').remove();

previous attempt:
<%= link_to "ModalTest", render(:partial => 'shared/testmodal') %>

A: You can include the modal contents you put in the partial, in any view you need or in your application.html, with:
<%= render "shared/testmodal" %>

And toggle it with:
<%= link_to "ModalTest", "#testModal", "data-toggle" => "modal" %>

Where #testModal is your modal id.


text:
Q: data-target not working -- React-bootstrap I have a simple sidebar with dropdowns. I want the dropdowns to be toggled on click. I used data-target property for this. But its not working as expected.

    Toggle Dropdown

Options

How do i accomplish this in react js??

A: If you are using react-bootstrap as you mentioned in title and also added the tag, then this is the way you can achieve the drop-down.
<DropdownButton title="Dropdown" id="bg-vertical-dropdown-1">
   <MenuItem eventKey="1">Dropdown link</MenuItem>
   <MenuItem eventKey="2">Dropdown link</MenuItem>
</DropdownButton>

A: Data attributes should work normally. You have error in your syntax because you are using class attribute on all the elements except the first span, instead of className.


text:
Q: How does an instruction decoder tell the difference between a prefix and a primary opcode? I'm trying to wrap my head around the x86 instruction encoding format. All the sources that I read still make the subject confusing. I'm starting to understand it a little bit but one thing that I'm having trouble with understanding is how the CPU instruction decoder differentiates an opcode prefix from an opcode.
I'm aware that the whole format of the instruction basically depends on the opcode (with extra bit fields defined in the opcode of course).  Sometimes the instruction doesn't have a prefix and the opcode is the first byte. How would the decoder know?
I'm assuming that the instruction decoder would be able to tell the difference because opcode bytes and prefix bytes would not share the same binary values. So the decoder can tell if the unique binary number in the byte is an instruction or a prefix. For example (In this example we will stick to single byte opcodes) a REX or LOCK prefix would not share the same byte value as any opcode in the architecture's instruction set.

A: Traditional (single-byte) prefixes are different from opcode bytes like you said, so a state machine can just remember which prefixes it's seen until it gets to an opcode byte.
The 0f escape byte for 2-byte opcodes is not really a prefix.  It has to be contiguous with the 2nd opcode byte.  Thus, following a 0f, any byte is an opcode, even if it's something like f2 that would otherwise be a prefix.  (This also applies following 0f 3a or 0f 38 2-byte escapes for SSSE3 and later, or VEX/EVEX prefixes that encode one of those escape sequences).
If you look at an opcode map, there are no entries that are ambiguous between single-byte prefix and opcode.  (e.g. http://ref.x86asm.net/coder64.html, and notice how the 2-byte 0F .. opcodes are listed separately).

The decoders do have to know the current mode for this (and other things); for example x86-64 removed the 1-byte inc/dec reg opcodes for use as REX prefixes.  (x86 32 bit opcodes that differ in x86-x64 or entirely removed).  We can even use this difference to write polyglot machine code that runs differently when decoded in 32-bit vs. 64-bit mode, or even distinguish all 3 mode sizes.
x86 machine code is a byte stream that's not self-synchronizing (e.g. a ModRM or an immediate can be any byte).  The CPU always knows where to start decoding from, either a jump target or the byte after the end of a previous instruction.  That's the start of the instruction (including prefixes).
Bytes in memory are just bytes, only becoming instructions when they're decoded by the CPU.  (Although in normal programs, simply disassembling from the top of the .text section does give you the program's instructions.  Self-modifying and obfuscated code are not normal.)
AVX / AVX-512: multi-byte prefixes that overlap with opcodes
Multi-byte VEX and EVEX prefixes aren't that simple in 32-bit mode. For example VEX prefixes overlap with invalid encodings of LES and LDS in modes other than 64-bit.  (The c4 and c5 opcodes for LES and LDS are always invalid in 64-bit mode, except as VEX prefixes.)  https://wiki.osdev.org/X86-64_Instruction_Encoding#VEX.2FXOP_opcodes
In legacy / compat modes, there weren't any free bytes left that weren't already opcodes or prefixes when AVX (VEX prefixes) and AVX-512 (EVEX prefix), so the only room for extensions was as encodings for opcodes that are only valid with a limited set of ModRM bytes. (e.g. LES / LDS require a memory source, not register - this is why some bits are inverted in VEX prefixes, so the top 2 bits of the byte after c4 or c5 will always be 1 in 32-bit mode instead of 0.
That's the "mode" field in ModRM, and 11 means register).
(Fun fact: VEX prefixes are not recognized in 16-bit real mode, apparently because some software used the same invalid encodings of LES / LDS as intentional traps, to be sorted out in the #UD exception handler.  VEX prefixes are recognized in 16-bit protected mode, though.)

AMD64 freed up several bytes by removing instructions like AAM, as well as LES/LDS (and the one-byte inc/dec reg encodings for use as REX prefixes), but CPU vendors have continued to care about 32-bit mode and not added any extensions that are only available in 64-bit mode which could simply take advantage of those free opcode bytes.  This means finding ways to cram new instruction encodings into increasingly small gaps in 32-bit machine code.  (Often via mandatory prefixes, e.g. rep bsr = lzcnt on CPUs with that feature, which gives different results.)
So the decoders in modern CPUs that support AVX / BMI1/2 have to look at multiple bytes to decide whether this is a prefix for a valid AVX or other VEX-encoded instruction, or in 32-bit mode if it should decode as LES or LDS.  (And I guess look at the rest of the instruction to decide if it should #UD).
But modern CPUs are looking at 16 or 32 bytes at a time anyway to find instruction boundaries in parallel.  (And then later feed those groups of instruction bytes to actual decoders, again in parallel.)  https://www.realworldtech.com/sandy-bridge/4/
Same goes for the prefix scheme used by AMD XOP, which is a lot like VEX.
Agner Fog's blog article Stop the instruction set war from 2009 (soon after AVX was announced, before the first hardware supporting it) has a table of remaining unused coding space for future extensions, and some notes about it being "assigned" to AMD, Intel, or Via.
Related / examples

*

*How to tell the length of an x86 instruction? (including my answer) has some more details about x86 machine code.

*https://codegolf.stackexchange.com/questions/133486/find-an-illegal-string/133622#133622 (on codegolf.SE - the shortest sequence of bytes that will definitely #UD fault if it's not jumped over.  It has to be long enough that it can't be consumed by the CPU as the immediate for a mov r64, imm64 for example.)

*Why does x/i on gdb give different results then disassemble? - an example of starting decode in the wrong place and decoding the middle of another instruction as something else.

Machine code tricks: decoding the same byte multiple ways
(This is not really related to prefixes, but in general seeing how the rules apply to weird cases can help understand exactly things work.)
A software disassembler does need to know a start point. This can be problematic if obfuscated code mixes code and data, and actual execution jumps to places you wouldn't get if you just assume that you can decode in order without following jumps.
Fortunately compiler-generated code doesn't do that so naive static disassembly (e.g. by objdump -d or ndisasm, as opposed to IDA) finds the same instruction boundaries that actually running the program will.
This is not a problem for running obfuscated machine code; the CPU just does what it's told, and never cares about bytes before the place you tell it to jump to.  Disassembling without running / single-stepping the program is the hard thing, especially with the possibility of self-modifying code and jumps to what a naive disassembler would think was the middle of an earlier instruction.
Obfuscated machine code can even have an instruction decode one way, then jump back into what was the middle of that instruction, for a later byte to be the opcode (or prefix + opcode).  Modern CPUs with uop caches or that mark instruction boundaries in I-cache run slow (but correctly) if you do this, so it's more of a fun code-golf trick (extreme code-size optimization at the expense of speed) or obfuscation technique.
For an example of this, see my codegolf.SE x86 machine code answer to Golf a Custom Fibonacci Sequence.  I'll excerpt the disassembly that lines up with what the CPU sees after looping back to cfib.loop, but note that the first iteration decodes differently.  So I'm using just 1 byte outside the loop instead of 2 to effectively jump into the middle for the start of the first iteration.  See the linked answer for a full description and the other disassembly.
0000000000401070 <cfib>:
  401070:       eb                      .byte 0xeb      # jmp rel8 consuming the 01 add opcode as a rel8
0000000000401071 <cfib.loop>:
  401071:       01 d0                   add    eax,edx
# loop entry point on first iteration, jumping over the ModRM byte (D0) of the ADD
    (entry on first iteration):
  401073:       92                      xchg   edx,eax
  401074:       e2 fb                   loop   401071 <cfib.loop>
  401076:       c3                      ret

You can do this with opcodes that consume more later bytes, like 3D <dword>    cmp eax, imm32.  When the CPU sees a 3D opcode byte, it will grab the next 4 bytes as the immediate.  If you later jump into those 4 bytes, they'll be considered as prefix/opcodes and everything will work (except for performance problems) the same regardless of how those bytes had previously been decoded as a different part of an instruction.  The CPU has to maintain the illusion of decoding and executing 1 instruction at a time, other than performance.
I learned of this trick from @Ira Baxter's answer on  Can assembled ASM code result in more than a single possible way (except for offset values)?


text:
Q: Plink from Windows service cannot find Pageant I have one windows service which will use plink.exe for SSH connection and I found that Plink cannot find the running Pageant.
Here is the steps I have done so far.

*

*Install Windows service to run as particular user

*Before starting Windows service, I log in as that user and start Pageant with PuTTY generated key.

*Then I start the Windows service (but I can't manage to make it work since Plink cannot find Pageant and server reply as No supported authentication methods available.)

Note: If I run Windows service as console application with that user, everything is working fine.

A: PLink will be run in Service session (Session\0) while pageant runs in user session (Session\1). Plink uses some interprocess communication which, as it looks from your problem, doesn't work across sessions. Most likely there's MMF communication inside and objects are created without prefix, i.e. they become session-only (not global). You would need to build custom version of plink to solve the problem.

A: Pageant explicitly allows feeding keys to an application (PuTTY, PSFTP, PSCP, WinSCP, FileZilla) running in the same Windows session only. This is obviously for security reasons, not to allow a different user on the same machine hijack private keys loaded by another users. And even for convenience (ironically), so that you do not inadvertently use keys of a different user (leading possibly to having your account locked due to invalid login attempts).
Also note that the Pageant is not intended for an automation anyway. For the automation, use the private key explicitly, using the -i command-line parameter.
See https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-identity
Such private key have to be unencrypted. Note that this imposes security risk, if someone gains access to the key. You should consider restricting an access to the unprotected private key file to the local account that runs the script only (using Windows file system permissions).

A: As @Eugene point out, it is Session 0 Isolation.
I managed to solve the issue by not using agent but directly passed the private key and password to plink.exe. By doing that, I'm able to run without using pageant.
To start plink.exe without agent;
plink.exe -noagent -i private_key.ppk -pw mypassword -P 1234 user@host.com


text:
Q: Annoying css problems in IE7 It works fine in FF, Opera and Chrome. But of cours it's not working ok in IE7.
I have list items which is 73px high, with a red border (a total of 75 px in height).
But I get an unwanted space between each list item. I've tride setting padding and margin to 0 for both
 and
, but to no wain.
Here you see the result.
css f** up in IE http://stiengenterprises.com/download/tmp/css_stuff.jpg
And here is my CSS:
//

#articleRotatorList {
    width: 250px;
    float: left;
    background: #f1f1f1 url(/img/bg/bg_articleRotatorStripe.png) repeat-y left;
}

#articleRotatorList li {
    height: 73px;
    font-size: 0.90em;
    border: 1px solid red;
}

How can I remove the space between the list items?
UPDATED
Added HTML source code:

Svangerskap

                        Lorem Ipsum is simply dummy text of the printing a...

Første leveår

                        Lorem Ipsum is simply dummy text of the printing a...

Barnesykdommer

                        Lorem Ipsum is simply dummy text of the printing a...

and here is the css for the border / content divs:
#articleRotatorList .border {
    width: 20px;
    height: 100%;
    float: left;
}

#articleRotatorList .content {
    width: 210px;
    height: 65px;
    padding: 5px 5px 5px 10px;
    float: left;
}

A: This is caused by the font-size being smaller than 1em. You need to increase the line-height a bit. Start with 1.10em:
#articleRotatorList li {
    height: 73px;
    font-size: 0.90em;
    line-height: 1.10em;
    border: 1px solid red;
}

A: As BalusC suggested, this is most likely a font-size/line-height issue, however I believe you may find success by setting both to 0 on the ul tag, and re-initializing them on the li tag. Yes, it sucks.


text:
Q: How to configure the google api api_key on Android Using an example, I found the android:name attribute for the maps api
<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="your_api_key"/>

Now I am trying to use the calandar api, and I have been unsuccessful so far.. I am unsure as to the android:name value I should be using here.
<meta-data
    android:name="com.google.android.calendar.v3.API_KEY"<!-- the value ?-->
    android:value="your_api_key"/>

The response:
"code": 403,
"errors": [
{
"domain": "usageLimits",
"message": "Access Not Configured",
"reason": "accessNotConfigured"
}
],
"message": "Access Not Configured"
}

Anyone know what else I need to do to configure this properly?
call google api:CalendarList feed = client.calendarList().list().setFields(CalendarInfo.FEED_FIELDS).execute();
//Traffic Reports for API Project
Total requests
2
Requests/day
2 peak 0.07 average
Start Date
Jun 12, 2013

resolve it:
The Manifest.xml
<application ... >

    <meta-data
        android:name="com.google.android.calendar.v3.API_KEY"
        android:value="your api key"/>
....
</application>

Google API Access:https://code.google.com/apis/console
 1. if you debug,need add a application,Client ID for installed
    applications: Certificate fingerprint (SHA1):「keytool -list -v
    -keystore ~/.android/debug.keystore  Input the password:android」
 2. Application type:   Android
 3. find API KEY:Simple API Access-->Key for browser apps (with
    referers)-->API key: dhjkl..hjkl
 4. find Product name:  Branding information-->Product name
Then call the API:
final HttpTransport transport = AndroidHttp.newCompatibleTransport();

final JsonFactory jsonFactory = new GsonFactory();

GoogleAccountCredential credential;

credential =
GoogleAccountCredential.usingOAuth2(getActivity(),
        Collections.singleton(CalendarScopes.CALENDAR_READONLY));
credential.setSelectedAccountName("myAccount");
client = new com.google.api.services.calendar.Calendar.Builder(
        transport, jsonFactory, credential).setApplicationName("myAppName")
        .build();
...
checkGooglePlayStatus()
...
...
//doInBackground()
CalendarList feed = client.calendarList().list().setFields(CalendarInfo.FEED_FIELDS).execute();
...

A: You don't have to provide anything in manifest that's just for Google Maps for Android.
If you are trying to use Calendar API v3 (https://developers.google.com/google-apps/calendar/) then first you need to authenticate using OAuth 2.
Here's an example on Google website of how to use Calendar API v3 on Android https://code.google.com/p/google-api-java-client/wiki/OAuth2#Android


text:
Q: Porque Microsoft Edge me devuelve una pagina en blanco XML-XSL Estoy usando XML Copy Editor para trabajar con XML y XSL pero al momento de abrir con el navegador me arroja una pagina en blanco.

Y, al hacerlo con otro navegador (Firefox) me sale solo el contenido sin mostrar los estilos que he puesto.

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

        <title>Ejercicio Librería</title>

Librería

          ISBN
          Título
          Autor
          Precio

        <xsl:for-each select="/libreria/libro">
          <xsl:if test="/titulo[starts-with(text(), 'P']">

                  <xsl:value-of select="isbn"/>
                  <xsl:value-of select="titulo"/>
                  <xsl:value-of select="autor"/>
                  <xsl:value-of select="precio"/>

        </xsl:if>
        </xsl:for-each>

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

A: Si tienes google chrome puedes realizarlo para Windows debes de ir a propiedades de google.
Pincha con el botón derecho en el Chrome/Propiedades añadir comillas doble a la ruta de esta manera "turutadegoogle" y le añades al final esto --allow-file-access-from-files
Quedaria algo asi en mi caso.
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files
Donde esta el cuadrado azul, pues lo añades al final y solucionado, deberás reiniciar el equipo y abrirlo desde el escritorio o donde tengas el icono si no deseas ponerlo modificando las propiedades de google, puedes abrir un terminal con permisos de administrador y poner "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files.

Nota Importante : Esta configuración lo he probado con Google Chrome, Opera y Opera GX siguiendo el mismo paso, con Firefox no se si funciona pero creo que si.


text:
Q: Hibernate Strange "ORA-01400: cannot insert NULL into" Error there is a strange error ocurring to me. I'm working with Hibernate, I have mapped class called Widget, which has a Parameter class, but when I try to insert I get
"ORA-01400: cannot insert NULL into..."
The mapping is properly done as:
<bag cascade="none" inverse="true" lazy="false" name="parameters" table="PARAMS" >
  <key column="WIDGET_ID" foreign-key="FK_PARAMS" not-null="true"/>
  <one-to-many class="Parameter"/>
</bag>

The wierd thing is that the not-null property is setted to "true" which forces to insert the ID value of the Widget Object.
Thanks in advance

A: Did you solved the problem? I think I had the same problem
ORA-01400: Cannot insert null into (TABLE.COLUMN) (Hibernate)
In my case I solved modifying Db, making foreign keys also primary keys


text:
Q: jQuery backstretch image auto-moving and back I use backstretch on my website. Now trying to move the backgroudn automatically from left to right and back. But til now, it just moves in one direction. I'm lookig for a continous loop of that moving image.
How can I reset / move back the image??
backstretch.js: http://dev.disaster-kfw.com/fileadmin/template/js/slidebackground.js
some more javascript for moving-effect & initialisation
var images = ['fileadmin/template/gfx/background02-03.jpg'];
        jQuery.backstretch( images[Math.floor(Math.random() * images.length)] );
        jQuery(function($){
            (function swoop(element) {
                element
                    .animate({'margin-left':'-=5px'}, 100, function(){
                        setTimeout(function(){
                            swoop(element);
                        }, 0);
                    });
            })($('#backstretch img'));
        });

resulting this HTML output

sorry for posting the html code a littlt bit ugly, don't know to do it right...
EDIT:
Thanks a lot, but I think that's not what I need.
I think I need a calculation about image-width and margin-left to switch from moving-left to moving-right and back.
So I tried to calculate width of my image, but
iWidth = jQuery("#backstretch img").width();

is always NULL.
And
iWidth = $("#backstretch img").width();

breaks the whole javascript.
I thought it could be a solution to write a second function called backswoop for counting up the margin-left. And then do a condition about margin-left and image-width.
iWidth = jQuery('#backstretch img').width();
jQuery(function($){
  (function swoop(element) {
    element.animate({'margin-left':'-=5px'}, 50, function(){
        setTimeout(function(){
           if(element.css('margin-left')*-1 <= iWidth){
             swoop(element);
           }else{
             backswoop(element);
           }
        }, 0);
    });
  })($('#backstretch img'));
  (function backswoop(element) {
    element.animate({'margin-left':'+=5px'}, 50, function(){
        setTimeout(function(){
           if(element.css('margin-left') >= 0){
             swoop(element);
           }else{
             backswoop(element);
           }
        }, 0);
    });
  })($('#backstretch img'));
});

But, because I'm not great with javascript, it does not work :-(

A: Before you move the element, use jQuery .data() to store the original margin.  That way when you want to reset you can animate the margin to that value.
This code isn't perfect.  It's just to give you an idea of what you can do.
//I would avoid global variables, but I don't know enough of your code.
swoopingElement =  $('#backstretch img');
swoopingElement.data("startingmargin", $('#backstretch img').css('marginLeft'));

(function swoop(element) {
  element
    .animate({'margin-left':'-=5px'}, 100, function(){
      swoopingElement.data("timer", setTimeout(function(){
        swoop(element);
      }, 0));
    });
})($('#backstretch img'));

function resetElement(element){
  //First shut down any remaining animation
  element.stop();
  clearTimeout(element.data("timer"));  //even though it's zero...  it might be active.
  //Send element back
  element.animate({'margin-left':element.data("startingmargin")}, 100);
  //Or for instant return.
  // element.css({'margin-left':element.data("startingmargin")});
};

https://api.jquery.com/jquery.data/


text:
Q: Complete Newbie: Axiom of Foundation Exercise No other axioms. There are $3$ sets such that:
$x\in y$;
$y\in z$;
$z\in x$;
These sets violate foundation.
I don't get it... For $x$, $z\in x$, so z must be the $\epsilon$-minimal member but the only member of $z$ is $y$.
$z \cap x = \{y\}\cap\{z\} = \emptyset$. None of the members of $z$ (only $y$) are members of $x$ so doesn't that satisfy definition of Foundation?
Please help this noob, thanks

A: Hint: Try to find an $\epsilon$-minimal member of set $\{x,y,z\}$.
edit: the comment of Asaf on your question made me decide to undelete this answer.

A: Your argument is correct: these sets do not violate Foundation, if you have no other assumptions about the sets that exist and no other axioms.
 Probably whoever posed the problem intended you to assume additional axioms so that you can say $\{x,y,z\}$ is a set as well which then has no $\in$-minimal element.


text:
Q: Android Programming with Camera framework API New to android programming, writing an application that continuously streams image from camera and do some operation on and post the result on screen. My camera class is separate from the main activity class. I have a queue for captured images, two threads that reads and writes to the queue. I am having problems possibly with the initializations. I am not sure if I am using the CameraPreview correctly.
Here is my code.
public class Goggle extends Activity{

    ImageQueue imageQueue = new ImageQueue();
    ImageCapture capture;

    private ThreadProcess thread;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.video);

        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);

        ......

        capture  = new ImageCapture(this,imageQueue);
        capture.start();

        thread = new ThreadProcess();
        thread.start();

    }

    private class ThreadProcess extends Thread {
    ...
    }
}

public class ImageCapture extends Thread implements Camera.PreviewCallback{
    private ImageQueue imageQueue;
    private ImageUInt8 image;

    private Activity   parent;

    private CameraPreview mPreview;
    private Camera        mCamera;

    public ImageCapture (Activity parnt, ImageQueue queue) {
        this.parent = parnt;
        this.imageQueue = queue;
        mPreview = new CameraPreview(parent,this,true);

        FrameLayout preview = (FrameLayout) parent.findViewById(R.id.camera_preview);
        preview.addView(mPreview);

        setUpAndConfigureCamera();
    }

    /**
     * Called each time a new image arrives in the data stream.
     */
    @Override
    public void onPreviewFrame(byte[] bytes, Camera camera) {

        // convert from NV21 format into gray scale
        synchronized (lockImage) {
            ConvertNV21.nv21ToGray(bytes,image.width,image.height,image);
        }
    }

    @Override
    public void run() {
        while (true) {
            synchronized (lockImage) {
                ImageData imageData = new ImageData(image);
                imageQueue.pushImage(imageData);
            }
            notifyAll();
        }
    }

}


text:
Q: Turtle creates an extra screen (unwanted) I made screen has a canvas, that got some drawings in it. I also made a function that makes a turtle and moves it. The problem is when the turtle is created, it also creates a new window in which the turtle moves. I don't want that second window. Is there a way to move a turtle and make it appear on the canvas without creating a second window?
Here's the function:
def Mueve_Carro(type):

    color = StringVar

    if tipoCarro == 1:
        type = "blue"
    elif tipoCarro == 2:
        type = "orange"
    elif tipoCarro == 3:
        type = "brown"

    ball = Turtle()
    ball.penup()
    ball.shape("circle")
    ball.shapesize(1,1,1)
    ball.color(type)
    ball.goto(-60,22)

A: The Turtle() class you are using will always automatically create a new canvas. You have to use RawTurtle(canvas) where that canvas variable is the screen you created outside this function (so you also need to pass it as parameter)
So basically
def Mueve_Carro(type, canvas):

    #...

    ball = RawTurtle(canvas)

    #...

Despite what the name may suggest, there are no other differences between RawTurtle and Turtle aside from the creation of the canvas.


text:
Q: android - open activity after countdown In my new game you have to press a button to get points. The player has to press the button within 5 seconds - if it takes more time, the GameOverScreen will be opened. Otherwise the countdown should restart. I tried to put the gameover(); method in the finish() method of the countdown, but it seems possible that the finish method is always started and won't be cancelled. How can I stop the countdown to do that?
public class GameScreen extends Activity {
    public int score = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        Button count = (Button) findViewById(R.id.button1);
        text = (TextView) this.findViewById(R.id.textView3);
        tvscore = (TextView) findViewById(R.id.score);

        timer();
    }

    public void gameover() {
        Intent intent = new Intent(this, GameOverScreen.class);
        startActivity(intent);
    }

    public void onClick (View view) {
        score++;
        tvscore.setText(String.valueOf(score));
        timer();
    }

    public void timer(){
        new CountDownTimer(5000, 10) {
            public void onTick(long millisUntilFinished) {
                text.setText(""+String.format("%02d:%03d",
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)),
                        TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished))
                        ));
                if(animationRunning) {
                    cancel();
                }
            }
            public void onFinish() {
                text.setText("Too slow.");
                gameover();
            }
        }.start();
    }
}

A: Here is the Simple and sophisticated way to achieve what you want.
Define a object of CountDownTimer at global level
CountDownTimer  mCountDownTimer  ;

Inside your onCreateView:
mCountDownTimer = new CountDownTimer(5000, 10) {
        public void onTick(long millisUntilFinished) {
           text.setText(""+String.format("%02d:%03d",
           TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)),
           TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished));
           }

         @Override
         public void onFinish() {
            text.setText("Too slow.");
            gameover();
         }
     };
 mCountDownTimer.start();

In onClick()
  public void onClick (View view)
    {
        mCountDownTimer.cancel();
        score++;
        tvscore.setText(String.valueOf(score));
        mCountDownTimer.start();

    }

A: update your timer code like this:
private boolean isTimerCanceled = false;

public void timer(){
        new CountDownTimer(5000, 10) {
            public void onTick(long millisUntilFinished) {
                text.setText(""+String.format("%02d:%03d",
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)),
                        TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished))
                        ));
                if(animationRunning)
                {
                    isTimerCanceled  = true;
                    cancel();
                } else{
                   isTimerCanceled = false;
                }
            }
            public void onFinish()
            {
                if (!isTimerCanceled){
                text.setText("Too slow.");
                gameover();
               }
            }
         }.start();
 }