text:
Q: Error while connecting to Oracle Server from Instant client through CMD prompt, but SQL Developer connects? I am using Client provided laptop (windows XP professional 2002)  and do not have administrative privileges (hence cannot st any required environment variables as well):
SQL Developer is provided and I am able to access the oracle server xaal5@:1521/ from SQL developer,
I need to use SQL LOADER to perform some heavy loading. I decided to download the instant client to see if I can save some time while my oracle client installation requests takes ages to go through approvals.
I went to the link: http://www.oracle.com/technetwork/topics/winsoft-085727.html
for Windows  and downloaded the following Instant Client Downloads for Microsoft Windows (32-bit)
Version 10.2.0.4
Instant Client Package - Basic: All files required to run OCI, OCCI, and JDBC-OCI applications
Download instantclient-basic-win32-10.2.0.4.zip (34,742,358 bytes)
*Instant Client Package - SQL*Plus: Additional libraries and executable for running SQL*Plus with Instant Client
Download instantclient-sqlplus-win32-10.2.0.4.zip (725,418 bytes)
Extracted these two zip files into C:\instantclient-win32 folder, got the following files (Yes there is no SQL LOADER in it , but i decided to first set the oracle client up and then look for SQL LDR)
sqlplus.exe
oci.dll
ocijdbc10.dll
ociw32.dll
orannzsbb10.dll
oraocci10.dll
oraociei10.dll
Orasqlplusic10.dll
classes12.jar
ojdbc14.jar
glogin.sql
I Ran the following CMD prompt of windows machine:
sqlplus xaal5@:1521/SID
and got the following error :
ERROR:
ORA-12514: TNS:listener does not currently know of service requested in connect
descriptor

I created a tnsnames.ora file with following entry:
PLMS =  (DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = XXXXXX)(PORT = 1521))
 (CONNECT_DATA =
  (SID = sblcusdv)
 ))

and set up a USER VARIABLES to point to the path of tnsnames.ora file (in the Environment variables window) , as i cannot create a system variable.
$TNS_ADMIN=C:\instantclient-win32
I Ran the following CMD prompt again:
sqlplus xaal5@:1521/SID
and got the following error, again :
ERROR:
ORA-12514: TNS:listener does not currently know of service requested in connect
descriptor

What am i doing wrong !! or is there another way to get SQL loader working on my system considering the constraints (long wait for approvals for oracle client installation).

A: When you use this format:
sqlplus xaal5@HOST:1521/SID

... you're using the 'easy connect' syntax, bypassing the tnsnames.ora and connecting to the service name SID - I assume you're actually using the SID from your TNS file, /sblcusdv. The SID and service name are not always the same thing, and the error indicates they are different in this environment.
To use your tnsnames.ora entry, use this syntax:
sqlplus xaal5@PLMS

That is, with the TNS alias you defined. If you don't want to use that file you need to know the service name. From the server you can use lsnrctl services to see which service names are registered, but you might not have access. If you have permissions you can do show parameters service_names from SQL*Plus (while connected via TNS), or you can query the performance views to get that information. But your account may not have access to that information either. In which case you'd need to ask your DBA. (I'm also assuming SQL Developer is connecting by SID, but it's possible it is using the service name, so you can just copy that).
sqlplus xaal5@//HOST:1521/SERVICE_NAME

You can't use SQL*Loader from the imstant client though, so you still have to wait for the full client to be installed. You might want to look at external tables as an alternative to SQL*Loader; then you could stick to instant client (or indeed SQL Developer). But you'd need to be able to get the data files into a DB-recognised directory on the server, which might haveits own issues.

A: You have to use the Description as stated.
sqlplus Username/Password@description

In your case:
sqlplus Username/Password@PLMS

This should be sufficient, no need to mention hostname or Port.
In case it doesn't work, check if your System variable PATH contain the oracle installation folder at first place. And when you have Oracle DB and Oracle Client installed on same machine, look if both TNSNAMES have the connection you looking for.


text:
Q: Difference between char and char* I am teaching myself C++ by doing microcontroller projects.  My current project is using a pair or Adafruit Feather packet radios.  The library functions for the radio packets require a C-style string (I believe) which I understand to be an array of char's.
I have already set up an enum to reflect the various actions of the receiver and would like to send that status back to the transmitter.  So I want to turn an enum into an array of char's.
In googling ways to convert enum to array of chars, the easiest (for me to understand) was passing the enum variable to a function with a switch statement that would return a char string.  But when I try to put the return into my char array, I get the error "invalid conversion from 'char*' to 'char' [-fpermisive]".  I've also been struggling to get my head around arrays and pointers to arrays which is still pretty fuzzy in my head.
Here are some snippets of my code which I hope will show enough of what I'm trying to do.
...from my main function
  BLINKING_RIGHT, //0
  BLINKING_LEFT,  //1
  FLASHING,       //2
  SHOWING_BATTERY,//3
  NONE            //4
};

...and the two functions that process the enum to send
void SendStatus()
{
  char data[20] {EnumToString(currentAction)};     //This is the line showing the error
  //itoa (data,static_cast<int>(currentAction),10);
  //data[0]=static_cast<uint8_t>(currentAction);
  //data[1]=0;
  rf69.send(data, sizeof(data));
  rf69.waitPacketSent();
  Serial.println("Sent a reply");
}//end_function SendStatus()

char* EnumToString(CurrentAction inputEnum)
{
  char *statusString;
  switch(inputEnum)
  {
    case 0:
      statusString = "BLINKING_RIGHT"; //0
      return statusString;
      break;
    case 1:
      statusString = "BLINKING_LEFT";  //1
      return statusString;
      break;
    case 2:
      statusString = "FLASHING";       //2
      return statusString;
      break;
    case 3:
      statusString = "SHOWING_BATTERY";//3
    case 4:
      statusString = "NONE";           //4
      return statusString;
      break;
    default:
      return "EnumToString: Invalid enum";
  }
}

I would like help fixing the problem, and, more importantly, help understanding the difference between the type char* and the type char.

A: This line:
char data[20] {EnumToString(currentAction)};

Is wrong because it uses array-initialization to initialize the first element of the array of char (first element which is of type char) with a string (char*). What you want to do is something like this:
char data[20];
strcpy(data, EnumToString(currentAction));

Or simply:
char *data = EnumToString(currentAction);

The latter doesn't involve any kind of copying, and efficiency is important on a micro-controller.
While we're on the point of efficiency, the canonical way of mapping sequential enum values to strings is using an array, which is orders of magnitude more efficient than repeated branching:
// stored as read-only data in the .hex file
static char *names[] = { "BLINKING_RIGHT", "BLINKING_LEFT", "FLASHING", "SHOWING_BATTERY", "NONE" };

// later
const char *data = names[currentAction];

A:
Difference between char and char*

char is a character object. Characters are numbers. The number value encodes some textual character (in fixed width character encodings; A C++ character represents one "code unit" in variable width unicode encoding).
char* is a pointer object. It is specifically a pointer to a char object. A pointer object points to another object in memory - or points to nothing if null or points to memory where an object was if the pointer is invalid. Pointers are also iterators, and incrementing a pointer makes it point to a successive element of an array.

char data[20] {EnumToString(currentAction)};     //This is the line showing the error

data is an array of 20 objects of type char. {expr} initialises the first element of the array with the expression. In your case, the expression is a call to EnumToString. Thus, you're attempting to initialise a char object using the char* object returned by the function. The type system of C++ protects you from this obvious mistake.
Assuming you have the option of sending less than 20 bytes, a potential simple solution is to avoid using the local array entirely:
std::string_view str = EnumToString(currentAction);
rf69.send(str.data(), str.size());

char *statusString;
statusString = "BLINKING_RIGHT"; //0

This is ill-formed in C++. String literals are arrays of const char, and they are not convertible to pointer to non-const char (since C++11).
As simple fix is to change the variable and the return type to be const char*. That said, using std::string_view may be even more preferable because that way the caller doesn't need to calculate the length of the string at runtime by searching for the null terminator.

A: char (or any T) is a value.
char* (or any T*) is a pointer (a value poining to another value, i.e. address).
Keep in mind what arrays (char[] or any T[]) presented by pointer to 0-th element. Variable of char* can point to an element of an array (to the first element in a special case).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fieldset not rendering correctly under Twitter Bootstrap I'm trying to use a Fieldset on a page in a responsive site that uses Bootstrap.  Actually, I'm trying to use an ASP.NET Panel control with the GroupingText property set - but that actually renders as a fieldset with the legend set so same difference.  The page isn't rendering the fieldset correctly. Normally, with a fieldset you get a border around your content with the legend embedded in the border such as below (same site without Bootstrap):

But here's what it looks like if I include Bootstrap:

I've looked to see what the bootstrap css is doing with fieldsets but can't figure out what's causing it. Anyone else have problems using fieldsets (or ASP.NET Panels with GroupingText populated) in conjunction with Bootstrap? Anyone know how to get Bootstrap to render fieldsets normally?

A: This will undoutably not be the answer you were hoping for, but I can think of only one option that will help render the fieldset and legend elements as you want when you're including bootstrap in your project:
There is a CSS property call all that has several values that you can set on it. You can read up on it here. The value you'd be interested in though is initial. So a class with a property all: initial; will reset all of the selected element's properties to their initial values as defined in the CSS spec. After that you would have to style the legend and fieldset elements to how you want them rendered. I've provided some working code that will get you started. You can see it in action here. Please note bootstrap is in this environment if you delete all of the CSS, you'll see bootstraps styling rendered.
Sample HTML:
<fieldset class="reset-this redo-fieldset" style="margin-left: 10px;">
    <legend class="reset-this redo-legend">Name</legend>
    First Name: <input type="text">

    Last Name: <input type="text">

</fieldset>

Sample CSS:
.reset-this {
  all: initial;
}

.redo-fieldset {
  border: 1px solid black;
  padding : 10px;
}

.redo-legend {
  color: black;
}


text:
Q: How to get an error message instead of an integer in MQL5? I am trying to get the error message using OpenCl in MQL5.
int     cl_ctx;
if (  ( cl_ctx = CLContextCreate( CL_USE_ANY ) ) == INVALID_HANDLE )
{
      Print( "OpenCL not found: ", GetLastError() );

      float pr  = 2.0 / ( period + 1.0 );
      result[0] = (float)price[position] * pr + prev_value * ( 1 - pr );

      Print(  result[0] );
      return( result[0] );
}

I am getting the message as:
OpenCL not found: 5113

Now I do not know what this 5113 means. How I can get the message in human readable format that will help me debug my program effectively?

A: In case your code received _LastError == 5113:
the documented human-readable explanation is this one:

ERR_OPENCL_TOO_MANY_OBJECTS     5113    Too many OpenCL objects

Next time, better present a few "surrounding" lines via a copy/paste from the MT5-log, there are more details surrounding the Runtime Error incident.
All error-code definitions and explanations are kept both in documentation and in < stderror.mqh > file since ever.
Also may re-read the online documentation aids.
Lastl, but not least, always pre-clear _LastError state with a call to ResetLastError()


text:
Q: php session is not working on subdomains My session code was working before, however now all of a sudden it is not working, and also, if I call set_session.php from www.domain.com, then I call test_session.php from domain.com, it produces nothing. No session variable is set, and it only produces output if I call test_session.php from www.domain.com. When I call set_session from domain.com or www.domain.com, calling test_session.php from other subdomains(i.e sub.domain.com), the session also does not show up. Even though I already used session_set_cookie_params(0, '/', '.domain.com'). What is the correct way to do this ?
set_session.php
<?php
session_name('mysession');
session_set_cookie_params(0, '/', '.domain.com');
session_start();
$_SESSION['test'] = 'Session is set';
echo $_SESSION['test'];
?>

test_session.php
<?php
session_name('mysession');
session_set_cookie_params(0, '/', '.domain.com');
session_start();
echo $_SESSION['test'];
?>

All answers and suggestions are greatly welcomed and appreciated. Thank you in advance.

A: A cookie lifetime of 0 might be a bit too short:
session_set_cookie_params(30*60, '/', '.domain.com');

EDIT
additionally, I would check whether a cookie named mysession is actually set in the browser.
Furthermore, check your logs: one of the reasons might be that the session store (which usually is file based) isn't writable or disk is full i.e.


text:
Q: uml use case scenario needed Does anyone know where to get sort off a basic use case scenario for an auction site or a site like this one.
my site has to be more off an auction site then a q and answer site.
Basicly, from my ~limited~ understanding, when you start a project, you start with usecases and from there you are going to determine/build an objectmodel.
I would like to hear from someone, that has already got some higher level experience.
I would like to see some examples, but advice is ok, also.
Maybe, someone can provide some usefull links?
Starting from scratch is ok, but since there are already so many sites alike outthere
Thanks, Richard

A: In my opinion, use cases are one possible way to get a clear understanding of your requirements. So, as ChrisBD already stated, there won't be a diagram out there that suites your needs and, most importantly, even if it were, this is not desirable.
It's important to know that the valuable part of creating use cases is not the creation of a UML diagram(altough they are helpful for getting an overview of a system). The much more valuable process is writing the textual description of a use case.
There are various templates which guide you through the process (e.g., by Alistair Cockburn [1] or others [2,3] ). If you are interested in the subject, I can recommed the book "Writing Effective Use Cases"[4] by Cockburn.
[1] http://alistair.cockburn.us/Basic+use+case+template (great resources for use case in general)
[2] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.255 (easy for starters)
[3] http://hcid.soi.city.ac.uk/research/Rescue.html (uc embedded in requirements engineering)
[4] http://www.amazon.com/Writing-Effective-Cases-Alistair-Cockburn/dp/0201702258/ref=sr_1_1?s=gateway&ie=UTF8&qid=1285833847&sr=8-1

A: It sounds to me as if you don't have any experience of UML at all.
UML at its simplest is a graphical means of describing a system, much the same as you may scribble something on a piece of paper or white board in order to show someone an idea or knowledge that you have.
As such there are very few hard and fast rules as to precisely what must be in any given diagram.
Most importantly diagrams should be meaningful and easily understood by those looking at them.
I doubt that you'll find any predrawn UML for the system that you're after.
Use cases just describe how you interact with a  system or part thereof and how it interacts with everything else.
You should have one diagram for each use case e.g. User login use case; bid process etc.
Have a look here and here they may be of help to you.

A: Thank you Markus, I have problably seen, read all the links you provided above.
I already wrote the use-cases.
The real challenge is to get an overall picture on how the system should work.
The flow, the database design and how to separate the bussiness logic so that changes can be made more eassaley. What language to use and what kind off framework in regards to speed, scalability, etc.
I need to have a somewhat broad understanding off it all, sothat I can go to some webdeveloper well prepared and not get into a situation where the developer is faced with the same questions, but does it on my time. I already had contact with one, and it sounded like he was going to have major coping problems. And then you hear, well sir, this is going to run in the papers. That does not sound very convincing.
I try'd reverse engineer a website but it only get's you sofar.
Should this be a very hard case?
->
You can auction your items, and you can get biddings, but there it stops. I mean that there is no auctioneer in the system that is telling who has won. It does not go that far.
It just has to manage the information. Connect the seller info to the buyer info.
I have been fishing around on what is out there what I can use to get a better understanding and especcially to keep the startingcosts low.
Anyone, who has any input, suggestions, please make a comment.


text:
Q: Averaging electret microphones' inputs I have 4 electret microphones for a project, each going to an AC channel. On the general case each mic has to be processed individually but in one particular case, I would like to have an image of a sound being made in front of all the microphones, as faithfully as possible.
Would it make sense in this latter scenario to average electrically the amplified output of all the 4 mics, to reduce the noise of each of them (at least white noise, I'm not talking about for example crosstalk from the ADC clock or this kind of correlated noise)?
Something like that for example :

simulate this circuit – Schematic created using CircuitLab

A: The output of an electret microphone element is a small (millivolts) AC voltage riding on a large (volts) DC voltage.  Because no two elements have the exact same DC rest voltage value, a better way is to capacitor-couple each of the three signals to a 2-resistor voltage divider between Vcc and GND.  This is then connected to the ADC input.  In this way the three signals are summed to a single signal that is the algebraic average, and that signal is biased to the middle of the ADC input voltage range.
Are the microphone elements 2-lead or 3-lead?

A: Electret microphone capsules in 2-wire configuration are current sources, so just wire all of them in parallel and adapt the bias resistor to a 1/4 of the value for a single mic.  Your output current will not be an average as much as a sum of the partial currents, so expect the output voltage to be comparable in spite of the quite higher load.
As long as you stay in the saturation region of the capsule FETs (namely within the specified operating voltage range), the main sources of sample variation (quiescent current, pinchoff voltage) of the capsule FETs don't come into play and the principal variable is its transmittance factor.  But that's directly responsible for capsule sensitivity, so for identical capsule types (which tend to use selected FETs) you cannot really do better even with more complicated circuitry.


text:
Q: Are there any performance disadvantages of using .if and .elseif in assembly? I was wondering if the .if and the .elseif directives had any performance disadvantages when compared to using a series of cmp and jmp statements.
Thanks!
Devjeet

A: In general, there is no performance disadvantage.
However, if you decide to use them all the time, you should probably check the assembler generated every once in a while to better understand what they are doing to your code. There may be rare instances the produced code is slightly less efficient.

A: You are more probable to write a worse .if yourself actually. For instance, ".IF eax==0" is evaluated as :
test    eax,eax
jnz     label

it can't get better than this.


text:
Q: BDD Step already Bound and mapped I will appreciate if someone help that how to handle such situation.
I have a Scenario:
 Scenario Outline:Modify Account Details
    Given AccountID is selected in The Quick Search
    When user enter the <AccountID> in search field
    And Click on Quick Search button
    And Close the Alerts
    And Click on Edit Link
    When Enter the <Email>
    And Click on Commit button
Examples:
   | AccountID | Email               |
   | 116999    | test3@domain.co.uk |

In the same project when I add an other scenario for different module like
Feature: Create a new Ticket
Background:
Given I have entered the CRM URL
And AccountID is selected in The Quick Search
@mytag
Scenario Outline: Add a new Ticket
    Given user perform a quick search for <AccountID>
    When User click on Add New link on Ticket Section
    And Select the <Department> and <SubTeam> from the list
    And Enter the <Subject> of the ticket
    And Select the <Product>
    And Select the <TicketCategory> and <TicketSubCategory>
    And Enter the <Comments> and <PersonSpokeTo>
    And Click on Finish
    Then A new Ticket is created

Examples:
| AccountID | Department        |SubTeam| Subject     | Product        | TicketCategory     | TicketSubCategory | Comments      |
| 116999    | Customer Services | Contract Enquiries | Test Ticket | Home Insurance | Account Management | Customer Zone     | Test Comments |

For Step When Enter the <Email> in Scenario 1 I have the below Implementation
[When(@"Enter the (.*)")]
        public void WhenEnterTheEmail(string email)
        {
            try
            {
                Helper.ExplicitWait(_driver, AccountDetailsEdit.xPathtxtEmailBilling, 90);
                AccountDetailsEdit.txtEmailBilling.Clear();
                Helper.EnterTextValue(AccountDetailsEdit.txtEmailBilling, email);

            }
            catch (Exception e)
            {
                Console.WriteLine("No Such element found -{0}",e);
                _driver.Quit();
                throw;
            }

        }

But When I try to generate the Step Definition for 2nd Scenario I am unable to generate for the following steps
  And Enter the <Subject> of the ticket
  And Enter the <Comments> and <PersonSpokeTo>

And Got the message that All steps are bound. These step mapped with my method mentioned earlier
[When(@"Enter the (.*)")]
            public void WhenEnterTheEmail(string email)

I tried to google to get some help but unable to find. Any help will be highly appreciated.

A: Steps in SpecFlow are not specific to a feature. They are global for a test project. You can only have one definition per step.
If you need more than one definition per step consider adding more parameters to the step, or phrase the step so it is more specific to a use case in the application.


text:
Q: Selecting descendant based on classes Element type descendant selection works:
form * div {...}

but I find that using classes does not:
.my-class1 * .my-class2 {...}

I.e. I expect a few elements to be selected by the "class descendant" selection form, but none are.
In my page I have two very similar DOM sub-structures generated by third party code that needs different styling, and I don't want my CSS to relying on that third party DOM structure.
What is the best way to style these two parts of the DOM?

A: You can use .my-class1 > .my-class2 to direct descendants.
Or you can use .my-class1 .my-class2 for any .my-class2 that is descendant of .my-class1.


text:
Q: how to make the the elements follow the text below I have a problem, I am confused about how to make the label always follow the text below it, initially I used absolute position and the label followed the text, but the text did not always dock at the bottom of the div, then I used this code to finally succeed. but the label does not follow the text below. Do you have a way?

img {width:100%;}
a{color:white;}
.post-thumb{position: relative;}
.post-title {
   position: absolute;
   bottom: 0;
   left: 0;
   margin:25px
   }
.label-info {
   position: absolute;
   bottom: 35px;
   left: 0;
   margin:25px;
   background:red;
   padding:10px;
   }

Neque porro quisquam est qui dolorem...

Military

A: You can do this by manipulating your HTML structure. So you need to wrap your text and button into the same parent div then reorder the label-info and post-title and then assign all post-title style to new parent div and get rid of label-info positioning.
So it will be something like this:

img {
  width: 100%;
}

a {
  color: white;
}

.post-thumb {
  position: relative;
}

.post-info {
  position: absolute;
  bottom: 0;
  left: 0;
  margin: 25px
}

.label-info {
  background: red;
  padding: 10px;
}

Military

      Neque porro quisquam est qui dolorem
    Neque porro quisquam est qui dolorem
    Neque porro quisquam est qui dolorem...

A: When you are using absolute positioning, the elements wont care if something is in the way and just appear on top of each other.
Put both the elements into a div like so:

    Military

        Neque porro quisquam est qui doloremdasdaskl;djawildjaskl...

Change your post-title and label-info classes like this:
.post-title {
   margin:25px
   }
.label-info {
   margin:25px;
   background:red;
   padding:10px;
   }

Then add the post-info-container class:
.post-info-container {
        position: absolute;
        bottom:0;
        left:0;
    }

A: https://jsfiddle.net/udn7jpfL/ here is a solution.
Wrap .post-title, .label-info inside of div with position:absolute.

    Military

    Neque porro quisquam est qui dolorem...
Neque porro quisquam est qui dolorem...

.info {
   position: absolute;
   bottom: 0;
   left: 0;
   padding-bottom:25px;
}

.label-info {
   background:red;
   padding:10px;
   }

   .post-title, .label-info{
     display:block;
     float:left;
     margin:0 25px 25px 25px;
   }

   .clear{
     clear:both;
   }

A: In cases like this, I normally try to use a wrapper. In this example, I switched the label and the title in the HTML, so they just use normal flow.

            Military

            Lorem ipsum dolor sit, amet consectetur adipisicing elit. Possimus minus nostrum tempora hic exercitationem temporibus voluptatum dolores laboriosam nihil. Nihil at necessitatibus voluptate? Sed, sunt voluptates odit atque repellendus perspiciatis!

img {width:100%;}
a{color:white;}
.post-thumb{position: relative;}
.post-title {
   margin:25px
}

.label-info {
   margin:25px;
   background:red;
   padding:10px;
}

.label-wrapper {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: fit-content;
}


text:
Q: Customize citation style Is it possible to customize citation styles? I'm not talking about the bibliography, but the appearance of the optional argument in \cite[Theorem $4$]{Pitagora}.
Usually it is rendered as [Pit03, Theorem 4], but one may want to have [Pit03], Theorem 4 or Theorem 4 - [Pit03] or whatever. Does the bibliography style change this?

A: One way might be something like this.
For your specific example, you could also just define your own command
\newcommand{\mycite}[2]{\cite{#1},~#2}

And then cite it using \mycite{Pitagora}{Theorem~4}. I would not put $ in the reference, since the 4 is not a mathematical formula and should be treated as text.


text:
Q: Symlink in VBox Shared Folder are not properly formatted I have my c:\ partition shared to VM using Virtual Box Shared Folder. It is currently mounted as /c on the Ubuntu guest.
Lets suppose c:\html points to c:\Server\html on the Windows host. When I try cd /c/html on the VM, it doesn't work.
ls -alh /c says html -> C:/Server/html instead of /c/Server/html on the VM. How can I make it work?


text:
Q: How can I select an object type to deserialize using Json.Net based on property values in the data I need to deserialize json like this (it's as defined in DICOM - an international standard, so I can't change the format!)
{
....
"00080060": {
  "Value": [
    "US"
  ],
  "vr": "CS"
},
"00080070": {
  "Value": [
    "ACME Products"
  ],
  "vr": "LO"
},
"00080090": {
  "Value": [
    {
      "AlphabeticName": "Better^Make^U.^MD"
    }
  ],
  "vr": "PN"
},
"00081110": {
  "Value": [
    {
      "00080008": {
        "Value": [
          "XX_0",
          "OIU",
          null,
          "PPP"
        ],
        "vr": "CS"
      }
    },
    {},
    {
      "00080008": {
        "Value": [
          "XX_2",
          "OIU",
          null,
          "PPP"
        ],
        "vr": "CS"
      }
    }
  ],
  "vr": "SQ"
},

Each property (in a long list!) has a name (0008XXXX in example above), and has sub-properties "vr" and Value.  In most cases, Value is simply an array of objects (string or number) and that's fine, but for 2 special cases (PN and SQ as above) it needs special handling, and in the case of SQ it is actually an array of the top level object again (which can be nested recursively ad infinitum...)
So - what I need is a simple method, during deserialization to inspect the "vr" value and to give json.net the type it should use for the associated "Value" - is there a simple means to do that?  Of course, the fact that vr could come before or after Value (depending on remote implementation) might complicate things further...
I've looked at json.net's ContractResolver and JsonConverter mechanisms, but ContractResolver seems not to give me access to the data being read in order to allow to make the choice, and JsonConverter derived classes would seem to leave me having to re-implement most of what json.net is dong (otherwise so well!) for me already :-(
Am I missing some obvious and simple solution here?

A: Ugh, this is a difficult format to work with.  However, it should be possible to make sense of it using a custom JsonConverter.  Using a JObject inside the converter will shield us from most of the heavy lifting.  But first, we need to define a couple of classes to deserialize the data into.
The first class I'll call Node; this will contain the Value list and vr.
class Node
{
    public IList Value { get; set; }
    public string vr { get; set; }
}

The second class is needed for holding the items for the "PN" case.
class PnItem
{
    public string AlphabeticName { get; set; }
}

Here is the code for the converter.  The converter can look at the vr property and use that information to create the correct type of list for the Value.
class NodeConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Node));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        Node node = new Node();
        node.vr = (string)jo["vr"];
        if (node.vr == "PN")
        {
            node.Value = jo["Value"].ToObject<List<PnItem>>(serializer);
        }
        else if (node.vr == "SQ")
        {
            node.Value = jo["Value"].ToObject<List<Dictionary<string, Node>>>(serializer);
        }
        else
        {
            node.Value = jo["Value"].ToObject<List<string>>(serializer);
        }
        return node;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Notice that for the "SQ" case we are deserializing a List<Dictionary<string, Node>>.  This covers the recursive structure.  Whenever Json.Net tries to deserialize a Node, it will call back into the converter.  We use a Dictionary to handle the fact that the property names can vary (e.g. "00080070", "00080090", etc.).  At the root, we must also deserialize to a Dictionary<string, Node> for the same reason.
So, to tie it all together, here is how you would deserialize your JSON:
var dict = JsonConvert.DeserializeObject<Dictionary<string, Node>>(json,
                                                            new NodeConverter());

Here is a demo: https://dotnetfiddle.net/hsFlxU


text:
Q: Diffraction: What actually happens in the slit I'm not a physicist but a curious reader, and I'm trying to understand the slit experiment it all makes sense if I accept that the slit itself has no active affect ... can any one explain what actually happens in the slit, given that even if it is only one atom thick it still has a material presence?
Really appreciate any help in understanding this
Thank you
Frances

A: The best way to imagine it without getting too deep into mathematics is as Solomon's comment suggests. Imagine a pond with a wall through the middle, and imagine that the wall has a slit in the middle. If there are waves with wavefronts parallel to the wall hitting the wall from one side, some of the wave will get through and form a more circular wave.

In the slit experiment, of course, light waves are used in stead of water waves, so the behaviour will be slightly different. For example the width of the slit will determine which wavelengths of light will be diffracted. Say the slit has width $d$, then light with wavelength $\lambda\approx d$ will be diffracted. This can also be illustrated in a pond:

If the slit is larger than the wavelength, the waves will behave as in the 'large gap' image above. As the gap becomes larger, the wavefronts to the right of the gap will become closer and closer to being parallel to the wavefronts left of the gap (an thus not being diffracted). So in the case of light, a slit of only one atom thick will show its presence when light with wavelength around the size of an atom ($\sim10^2\text{pm}$) is sent through the slit it will be diffracted.

A: A photon is a wave in the EM field that has defined electric and magnetic components.
Photons can also be scattered (direction change) by an interaction with electrons in matter and this is the main reason for diffraction.  (Also photons are only created by electrons (mostly in atoms) and are only absorbed by electrons in atoms).
The interaction of photons with matter is governed by Maxwell's and Fresnel's equations, which govern the reflection, transmission, and deflection of light rays using the magnetic and electric susceptibility factors of any given material and the EM variables of the light.
Which photons and how strong they interact as they pass through the aperture is also due to probability (Quantum Mechanics) or, when there are many photons, they can be modelled classically (on average).
Any aperture (even a hula-hoop) will effect light passing through it, and you can see wiki about the Airy disk for a circular aperture.
What is interesting about an aperture is not only this "scattering" of light but the fact that "interference" patterns are also formed when the photons are viewed on a screen.  This "interference" can be viewed with older classical theory as photons cancelling each other in the dark areas ( but violation of energy conservation) or can be viewed quantum mechanically (wave function of light) where the dark areas have been shown to be where no photons fall.
In the QM "photon wave function" explanation light must travel a path that is a multiple of its wavelength (Feynman), thus certain paths are not possible (dark areas - no photons) and the bright areas contain all the photons.  This is similar to how light behaves in a laser cavity for example.


text:
Q: Manejar errores en bash Estoy programando un script en bash para rescatar unos querytxt de la base de datos en Redshift. El problema es que para sacar esos querytxt, hay que ordenar las secuencias previamente para sacarlo correctamente.
En total son 5250 queries, de las cuales ya tengo su QueryID y así filtrarlas correctamente. Este es mi script actualmente:
RUTA=/monitoring/recreacion_ra3

contador=1
bloque=1

while read query
do
        if [[ $contador%250 -ne 0 ]]
        then
                LC_ALL=en_US.UTF-8 LD_LIBRARY_PATH=/usr/lib/ psql -h ${RSHOST} -p 5439 -U ${RSUID} ${RSDB} -t -A -c "select listagg(text) within group (order by sequence) as fullquery from stl_querytext where query = $query;" >> $RUTA/lista_query_${bloque}.csv
                contador=$((contador+1))
        else
                bloque=$((bloque+1))
        fi

done < $RUTA/listado_idquery.txt

Como se puede observar, la query que rescata el querytxt y los ordena es:
select listagg(text) within group (order by sequence) as fullquery from stl_querytext where query = $query;

La ejecución ha ido bien hasta que ha llegado a la query nº 248, cuyo error me ha arrojado lo siguiente:
ERROR:  Result size exceeds LISTAGG limit
DETAIL:
  -----------------------------------------------
  error:  Result size exceeds LISTAGG limit
  code:      8001
  context:   LISTAGG limit: 65535
  query:     59919376
  location:  _rds_bin_padb.1.0.22169_data_exec_72_3578893640_3e87a9c5c65d0636877214dd854e3a6255978936_0.cpp:150
  process:   query0_799_59919376 [pid=105429]
  -----------------------------------------------

Al parecer, listagg tiene un tamaño máximo y si se sobrepasa, da error. Esto no me preocupa porque perder algunas queries de las 5250 necesarias no es problema. La cuestión es que al dar ese error, el script se para.
¿Cómo puedo controlar los errores en tiempo de ejecución para que si alguna query no se puede rescatar, pase a la siguiente sin problemas?

A: No sé si hay alguna manera más eficiente de manejar errores en bash, pero de momento me está funcionando esta solución:
LC_ALL=en_US.UTF-8 LD_LIBRARY_PATH=/usr/lib/ psql -h ${RSHOST} -p 5439 -U ${RSUID} ${RSDB} -t -A -c "select listagg(text) within group (order by sequence) as fullquery from stl_querytext where query = $query;" >> $RUTA/bloque_${bloque}/${contador}_${query}.txt

error_code=$?
if [[ $error_code -ne 0 ]]
then
   continue
fi

Es decir, después de la consulta recojo con $? si el anterior comando ha terminado con éxito. En caso contrario ($error_code es distinto de 0), hago un continue.
Aún así, agradecería si alguien aporta alguna variante más óptima para manejar errores.


text:
Q: Question about implicit operator overloading in c# MyClass c = 10;

Is there any way to make this code work? I know that through the implicit operator overloading you can get the opposite to work:
int i = instanceOfMyClass;

Thanks

A: Sure...
class MyClass
{
    public static implicit operator MyClass(int value) { /* your code */ }
}


text:
Q: Varying size container gets over-taken by footer I have a checkout system I am designing and I cannot get the footer to not eat the bottom div I have setup, unless I continually adjust the margin-bottom figure.
I have three divs nested into one. These nested divs show/hide as I proceed to the next one. The only one I will ever have an issue with is the last one because it will never be static. I use it to show a customers order, so if they have 10 different products then 10 images, name, price, etc show.
Every other area of my site that gets new things added to it, the footer responds and continuously goes down.
My fiddle isn't the best and my issue is really hard to generate as it isn't a static issue. Two products could be added and it would be fine.
https://jsfiddle.net/pfar54/rc5yffy7/
    .footerOut {
    width: 100%;
    background-color: #202020;
    position: relative;
    padding-top: 30px;
    left: 0px;
    right: 0;
    margin-bottom: 0px;
    bottom: 0px;
    clear: both;
}
.footer {
    height: 420px;
    width: 960px;
}
/*----------Main div for Checkout Process--------*/
.checkoutprocess {
    margin-bottom: 150px;
    display: relative;
}

I have set everything to relative...added padding: bottom (took it out because it didn't do anything). Everything I try doesn't help.
The height of the container and border are irrelevant as I am just using those to test.
Anyone see why?

A: I guess Your problem is footer is overlapped with content, And I found some Html Dom Structure issues ans css property Mistakes, I have cleaned up your code please verify this link below in comment


text:
Q: Overriding RestTemplateCustomizer applied to RestTemplate I am using RestTemplateCustomizer to configure common configuration for RestTemplate for one of  my app. But now in one of my client class I need to override one of the custom Interceptor that I have with a different one.
I can get instance of RestTemplate without using RestTemplateBuilder and add all my configuration here and that should work, but i really don't want this approach.
The way I am thinking to solve this is get all interceptors attached to RestTemplate, find my custom Interceptor 1, remove it and add new custom Interceptor 2.
 public MyRestClient( RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
        for(int i=0 ;i<this.restTemplate.getInterceptors().size();i++) {
            if(this.restTemplate.getInterceptors().get(i).getClass().getSimpleName().equalsIgnoreCase("MyCustomInterceptor1")){
                this.restTemplate.getInterceptors().remove(i);
            }

        }

        this.restTemplate.getInterceptors().add(new MyCustomInterceptor2());
    }

It seems work fine but is there a better way to do this?


text:
Q: Why is "lately" usually used in a perfect tense sentence? When you look up "lately tense", google gives the top result from oxfordlearnersdictionaries.

I haven't heard from him lately.
Lately is usually used with a perfect tense of the verb.Look also at
  the idioms be too late (at the adjective) and too late (at the
  adverb).

But I want to know why?

A: The present perfect tense can be used when we describe our experience up to the present.  Examples:

I have eaten raw fish.
I have been to France.

"Lately" is normally used with these kind of sentences, to talk about recent experience:

Have you eaten raw fish lately?
Have you been to France lately?
She hasn't been coming in to work on time lately. I wonder what's wrong?

It is possible to use "lately" with the simple present or simple past, but it feels more natural to use it with the present perfect, to suggest the experience could have happened any time up to the present moment.


text:
Q: Pandas: how to convert an index of int64 epoc seconds to datetime I have some timezone information stored in a variable called tz_pytz -- I get that form a hdf5 file along with the dataframe but this is not important right now.
I have an int64 index representing second values since epoch that I want to treat as a timestamp with time zone information:
>>> df = pd.DataFrame(h5file['time']).sec
Int64Index([0, ...], dtype='int64')
>>> dt = pd.to_datetime(df, unit='s')
>>> type(dt[0])
pandas.tslib.Timestamp
>>> dt[0].tz is None
True
>>> dt
0    2015-05-29 07:18:22
1    2015-05-29 07:18:23
...
4478   2015-05-29 08:33:06
4479   2015-05-29 08:33:07
Name: sec, Length: 4480, dtype: datetime64[ns]

This works fine but the data is not time zone aware (tz is None). How do I make it time zone aware based on the time zone I have in py_pytz?

A: Use .tz_localize to add timezone to your datetime column:
In [12]:
df = pd.DataFrame(index=np.arange(10))
df['timestamp'] = pd.to_datetime(df.index, unit='s')
df['timestamp'] = df['timestamp'].dt.tz_localize('Asia/Hong_Kong')
df['timestamp']

Out[12]:
0   1970-01-01 00:00:00+08:00
1   1970-01-01 00:00:01+08:00
2   1970-01-01 00:00:02+08:00
3   1970-01-01 00:00:03+08:00
4   1970-01-01 00:00:04+08:00
5   1970-01-01 00:00:05+08:00
6   1970-01-01 00:00:06+08:00
7   1970-01-01 00:00:07+08:00
8   1970-01-01 00:00:08+08:00
9   1970-01-01 00:00:09+08:00
Name: timestamp, dtype: datetime64[ns, Asia/Hong_Kong]

This will add/remove tz information to your timestamp column, it accepts string, pytz or dateutil.tz.tzfile


text:
Q: If $V$ is a vector space with inner product and $v\in\Lambda^p V$ and $w\in\Lambda^q V$, then $|v\wedge w|\le|v||w|$ Suppose we give $V$ an orthonormal basis $e_1,\ldots,e_n$, and let $v=\sum_I v_I e_I $ and $w=\sum_J w_J e_J$, then
\begin{align}
|v\wedge w|^2& =\left| \sum_{I,J}v_I w_J e_I\wedge e_J\right |^2
=\left| \sum_K \sum_{K=I\sqcup J} (\pm1)v_I w_J e_K\right |^2 \\
&\le \sum_K \left| \sum_{K=I\sqcup J} |v_I w_J| \right|^2 \\
&\le \sum_K\left( \sum_{I\subset K} |v_I|^2\right)
\left( \sum_{J\subset K} |w_J|^2\right)
\end{align}
which is unfortunately more than $|v|^2|w|^2$. Is there any way the statement can be salvaged?


text:
Q: Roots of equation involving both polynomials and trigonometric functions I have to determine for which values of $x$ that the velocity vector is orthogonal to the acceleration vector, the position is given by:
$(3 \cos(t), - \sin(3t), 2t^3 - t^2)$,
I then use that $u \cdot v = 0$ if $u$ and $v$ is orthogonal. The dot product of the acceleration and velocity gives the following equation (if I have done the differentiation correctly):
$9\sin\left(t\right)\cos\left(t\right)-27\cos\left(3t\right)\sin\left(3t\right)+4t\left(18t^2-9t+1\right) = 0$.
$t = 0$ (or position $x = (3,0,0)$) is clearly a root but i can't find the other two. Is there a general way of computing roots of this sort of function analytically?


text:
Q: Binding any field prefix to an action parameter in C# MVC 4/5 I'm using C# ASP.Net MVC 4 and MVC 5.
I use an aggregate model VmVehicleGroup which looks little bit like:
public class VmVehicleGroup {
    public VehicleTypeEnum Type { get; set; }
    public List<VmVehicle> Vehicles { get; set; }
    public VmVehicle Editable { get; set;}
}

The master view has partials for each each group, for example,
@Html.Partial(x => x.Cars, "_VehicleEditor")

@Html.Partial(x => x.Bus, "_VehicleEditor")

@Html.Partial(x => x.Truck, "_VehicleEditor")

Each group partial displays Model.Vehicles and presents an editor template for the Model.Editable
My problem comes from the ModelState. Each partial will render the same input field name/ids for Model.Editable. When there are ModelState validation errors, the validation error for say the 'Car' partial, will appear on all the other forms, not just Car. I've worked around this by prefixing the models in the editor paritial, eg:
ViewData.TemplateInfo.HtmlFieldPrefix = Model.Type.ToString(); // VehicleTypeEnum

The Add/Edit form will now submit Model.Editable with field post data prefixes, ie: Car.Reg, Car.Name, Car.Type and Car.Id. My problem arises on the MVC action. My action currently looks like this:
[ValidateAntiForgeryToken]
[AcceptVerbs(HttpVerbs.Post)]
[Route("Edit", Name = "EditVehicle")]
public ActionResult Edit([Bind(Prefix = "Car")] VmVehicle car, [Bind(Prefix = "Bus")] VmVehicle bus, [Bind(Prefix = "Truck")] VmVehicle truck, ....)
{
    var model = car ?? bus ?? truck;

    ...
}

My problem is that this is maintanence nightmare - for each VehicleTypeEnum I need to add extra bind parameters. I can't have a single action for a prefixed model.
I've tried using public ActionResult Edit(VmVehicle model) {}, but the prefix hinders the MVC binding. Unfortunately it appears MVC also doesn't let you bind a wildcard or comman separated prefix, ie: *.Car or Car,Bus,Truck.
Is it possible to encourage the MVC action to accept any prefix, while maintaining the prefix for ModelState validation errors?

A: I see that in your view you have different partials for the different kind of vehicles. That means that you know beforehand what are the different vehicle types.
As you know it before hand, you simply have to make the separation of groups when you create the viewmodel. I.e. create a viewmodel with the different lists for cars, trucks, buses... In this way you'll have the required prefixes in the client side.
An what about the post action? Well, instead of receiving the list as individual parameters, just receive a class similar to the one you use to render the editor, i.e.
Use a class that has this properties to create the editor (use it as your view model):
public class VehiclesViewModel
{
  public List<Vehicle> Cars { get; set;}
  public List<Vehicle> Buses { get; set;}
  // other stuff here!
}

If you use a class like, this, that also has the cars, buses, etc. lists, the data will be bound automatically, i.e. insetad of using:
public ActionResult Edit([Bind(Prefix = "Car")] VmVehicle car,
     [Bind(Prefix = "Bus")] VmVehicle bus, ...)

use an Action like this:
public ActionResult Edit(VehiclesViewModel vehicles)

and the model binder will handle the prefixes for you, and bind each vehicle to its corresponding list.
Display and edit templates
However, if you use different classes for each type of vehivle, you can use custom Display and Edit templates, that can make your lief easier. I.e. you can define display and edit templates that apply to a given data type. So, if you have a different class for each kind of vehicle you can use display and edit templates for each different class, and using ´DisplayFor´ or EditorFor you'll get automatically the required view. Some samples in this links:

*

*Exploring Display and Editor Templates in ASP.NET MVC3/4

*ASP.NET MVC DisplayTemplate and EditorTemplates for Entity Framework DbGeography Spatial Types

*ASP.NET MVC display and editor templates
(I don't understand what you're exactly doing, so I can give a more concrete explanation for this)
Model binding a list of complex objects
Another classical problem which peoplefind with MVC is that, when they want to bind a list of complex objects that have to be edited, they don't know how to do it so that they get the list of objects back in the server in the post action.
This explanation by Phil Haack is one of the best that you can find.


text:
Q: Do λ-terms form a group with composition? Consider obviously as composition the well known combinator $\circ := \lambda f g.\lambda x.f(g x)$. It is easy to see that it associates ($\circ(\circ f g)h \equiv \circ f(\circ g h)$), and that it does have an identity element ($1 := \lambda x.x$), is there some reason why every λ-term should have an inverse? Intuitively one may think no, but being λ-calculus this magical place where every term has a fixed point, and being Google quite silent about, I'd rather ask.

A: It's easy to see that there are lambda terms that are not invertible.
let $f=\lambda x.(\lambda y.y)$. We then have $f(1)=id$ and $f(2)=id$
so $f^{-1}(id)$ can't exist


text:
Q: ¿Cómo muestro una imagen desde MySQL en PHP? Tengo el código para insertar, pero lo que quiero es mostrar una imagen por medio del id, ¿cómo lo puedo hacer?.
Tengo una consulta pero me da NOID. Se las muestra y si me pueden orientar por favor. Saludos, les dejo mi código.
<?php
if(isset($_GET['id'])){
    $id = $_GET['id'];
    $link = mysql_connect("localhost", "root", "") or die ("ERROR AL CONECTAR");
    $db_select = mysql_select_db("imagen") or die ("ERROR AL SELECCIONAR DB");

    $q = "SELECT * FROM tabla_imagen WHERE id = '$id'";
    $result = mysql_query($q, $link) or die ("Error al consultar");

    while ($row = mysql_fetch_assoc($result)) {
    echo $row["imagen"];
    }

    mysql_free_result($result);
    } else {
        echo 'NO ID';
        }
?>

A: El mensaje NO ID te aparecerá únicamente si no llamas a tu URL agregando la ID en la URL de la siguiente manera: http://tu_url/tu_php.php?id=...
Podemos arreglar un poco tu código para que muestre información más precisa y, además, protegerla contra los nefastos efectos de la inyección SQL haciendo uso de mysql_real_escape_string():
<?php
/* Comprobamos si se envió por GET en la URL el campo "id" */
if(isset($_GET['id'])) {
  /* Escapamos el contenido de "id" (estaría bien comprobar
      que su contenido es adecuado) */
  $id = mysql_real_escape_string($_GET['id']);
  $link = mysql_connect(
    "localhost",
    "root",
    ""
  ) or die ("ERROR AL CONECTAR: " . mysql_error());
  $db_select = mysql_select_db(
    "imagen"
  ) or die ("ERROR AL SELECCIONAR DB: " . mysql_error());
  $q = "SELECT * FROM tabla_imagen WHERE id = '$id'";
  $result = mysql_query(
    $q,
    $link
  ) or die ("Error al consultar: " . mysql_error());
  while ($row = mysql_fetch_assoc($result)) {
    echo $row["imagen"];
  }
  mysql_free_result($result);
} else {
  /* En caso de no agregar el campo "id" a la URL mostramos
      una información más detallada del problema */
  echo '"ID" no introducida. Use "', $_SERVER['PHP_SELF'] ,'?id=N"';
}

Como último consejo: Usa consultas preparadas con mysqli o PDO/mysql. Abandona el uso de las funciones mysql_*. Están marcadas como obsoletas en PHP 5.5 y eliminadas completamente de PHP en la versión 7.0.


text:
Q: Asymptotic growth I am given a list of functions and I am asked to order them in accordance with their asymptotic growth; Here I would just like to verify that my approach is valid.
In the case of comparing:
$\log \log \sqrt{n}$ and $\sqrt{n}$, taking the limit as $n$ tends to infinity of $\frac{\log \log \sqrt{n}}{\sqrt{n}}$ gives $0$, which I then use to say $\log \log \sqrt{n} = O(\sqrt{n})$.
In the case of comparing $n^{\log n}$ and $2^{n\sqrt{\log n}}$ the limit is not obvious (to me at least); What approach should I take here?
More generally speaking, in cases where directly computing the limit is not feasible, how would you compare the asymptotic growth of two functions?
Thanks for any help or clarification.

A: Write (I assume your logarithms are base 2, but it doesn't really matter)
$$n^{\log n}=2^{\log n\cdot\log n}=2^{(\log n)^2}$$
so now you have to compare the growth of $(\log n)^2$ and $n\sqrt{\log n}$. Of course, $\log$ grows slower than any power of $n$. In particular, $\log n<n^{1/2}$ for large enough $n$, so that
$$(\log n)^2<n<n\sqrt{\log n}.$$

A: Since $\log n \leq n$ and $n \sqrt{\log n} \geq n$ for $n$ large, you can conclude that
$$
\frac{n^{\log n}}{2^{n\sqrt{\log n}}} \leq \frac{n}{2^n} = o(1).
$$
If you cannot compute the limit of the quotient, and if you cannot estimate this quotient in any way, you are in trouble. Laundau's symbols are defined in terms of limits; if you cant handle these limits, you'll get nowhere.


text:
Q: Why does the googledrive library in R identifies more than one file with only one file in the Drive folder? I am trying to download a .tif file from my Google Drive folder (which is exported to it via Google Earth Engine), using the googledrive library. However, when calling the map function, I get the following error:
Error: 'file' identifies more than one Drive file.

I have already managed to download other .tif files with this code, which worked without any error. Why do I get this error, and how do I resolve it? As you can see in the Drive folder (it's public), the folder contains only one file, so why does 'file' identify more than one Drive file?
Code:
library(googledrive)
library(purrr)

## Store the URL to the folder
folder_url <- "https://drive.google.com/drive/folders/1Qdp0GN7_BZoU70OrpbEL-vIBBxBa1_Db"

## Identify this folder on Google Drive
## let googledrive know this is a file ID or URL, as opposed to file name
folder <- drive_get(as_id(folder_url))

## Identify files in the folder
files <- drive_ls(folder, pattern = "*.tif")

# Download all files in folder
map(files$name, overwrite = T, drive_download)

A: Google Drive API's method Files: list returns you by default an array
Even if the results contain only one file, or no files at all - it will still be an array.
All you need to do is to retrieve the first (0) element of this array. You can verify it by testing with the Try this API.
I expect the correct syntax in R to be something like
files[0]$name to retrieve the name of the first (even if it is the only) file.

Also: You should implement some condition statement to verify that the
  list of files is not empty before you retrieve the file name.

A: Google Drive allows for multiple files with the exact same name in the same folder. The googledrive library does not accept this and thus will throw an error. However, even after deleting "double" files, the error wasn't solved. It seems that Google Drive also keeps some kind of hidden record/cache of the files, even when there are deleted. Only by deleting the entire folder and recreating it, I was able to solve the error.


text:
Q: Why initState dont work after url changes on WebView? I am new in flutter and am trying to block the phone back button, it works when the app starts but when i search something in google for example and the URL changes the button keeps working
I ve tried WillPopScope but never worked for me
here is my app
    import 'dart:io';
    import 'package:flutter/material.dart';
    import 'package:flutter_statusbar_manager/flutter_statusbar_manager.dart';
    import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
    import 'package:back_button_interceptor/back_button_interceptor.dart';

    String mainURL = "http://google.com";
    void main() async {
      await FlutterStatusbarManager.setHidden(true, animation:StatusBarAnimation.SLIDE);
      runApp(MaterialApp(home: App()));
    }

    class App extends StatefulWidget {
      @override
      AppState createState() => new AppState();
    }

    class AppState extends State<App> {
      @override
      void initState() {
        super.initState();
        BackButtonInterceptor.add(btnInterceptor);
        final fWPlugin = new FlutterWebviewPlugin();

        fWPlugin.onDestroy.listen((_) => exit(0));

        fWPlugin.onUrlChanged.listen((String url) {
          print("URL: " + url);
        });
      }

      @override
      void dispose() {
        BackButtonInterceptor.remove(btnInterceptor);
        super.dispose();
      }

      bool btnInterceptor(bool stopDefaultButtonEvent) {
        return true;
      }

      @override
      Widget build(BuildContext context) {
        return MaterialApp(
              title: "Webview",
              theme: ThemeData.dark(),
              routes: {
                "/": (_) =>
                    WebviewScaffold(
                      url: mainURL,
                      withLocalUrl: true,
                      withJavascript: true,
                      withLocalStorage: true,
                      clearCache: false,
                      clearCookies: false,
                      withZoom: false,
                      enableAppScheme: true,
                    )
              });
      }
    }

I want that when you search something in the explorer the back button still be blocked`

A: That did not work for me neither. But I suggest you go to https://github.com/fluttercommunity/flutter_webview_plugin/issues and file an issue report.


text:
Q: ConvertTo-XML doesn't display as expected In a foreach loop, I am trying to gather information about a number of objects, and concatenate them all in one XML file.
foreach($Task in $Tasks) {
    $OutputObj = New-Object -TypeName PSobject
    $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer

    # does not work, $s contains '#document'
    $s = ConvertTo-XML -InputObject $OutputObj
    Write-Host $s
    # works as expected
    $OutputObj | Export-CliXML $OutPath
}

What am I doing wrong with ConvertTo-XML?  How can I get it to produce the output that Export-CliXML? To be clear, I want to convert each $outputobj and append it to the output file.

A: Try this:
($Tasks | ForEach-Object {
    $OutputObj = New-Object -TypeName PSObject
    $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer
    Write-Output $OutputObj
} | ConvertTo-XML -NoTypeInformation).Save($OutPath)

or this:
$combined = @()
foreach($Task in $Tasks) {
    $OutputObj = New-Object -TypeName PSobject
    $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer

    $combined += $OutputObj
}
$combined | Export-CliXML $OutPath

What a result do you want to see?
To learn more about ConvertTo-XML read the article "Dress Up Your XML Output with the ConvertTo-XML Cmdlet" http://technet.microsoft.com/en-us/library/ff730921.aspx

A: Instead of
$s = ConvertTo-XML -InputObject $OutputObj

Try
$s = $OutputObj | ConvertTo-XML

I have the same problem with ConvertTo-CSV.  The -InputObject parameter is not working as I expect.  But piping the object(s) to the ConvertTo-CSV works as expected.


text:
Q: How to add to devise model? I create a user model via command rails generate devise Users.
I want my Users model to stay the same however I want to add more columns but I'm not sure how and I am still a bit confused at the moment. I am pretty new to Ruby on Rails. I am not sure what command I am supposed you run after these changes are made as well. I think it is rake db:migrate in order to update the database.
I want to be able to add
name - string
address - string
username - string ..

According to this example in the documentation,
class AddDetailsToProducts < ActiveRecord::Migration
  def change
    add_column :products, :part_number, :string
    add_column :products, :price, :decimal
  end
end

Inside the change method, add columns part_number (string) and price (decimal) to the products table
Would this
file: 20141011161019_devise_create_users.rb
class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## 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.inet     :current_sign_in_ip
      t.inet     :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
    end

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

A: First, run rake db:migrate. This will run the migration prepared by devise on your database.
After that, just add more fields to your model, just the same as you would if you'd never installed devise. The first step is to generate a new migration. Run this at the command line:
bin/rails generate migration AddNameAddressUsernameToUsers name:string address:string username:string
This will create a new migration file. You should then run that migration file on your database, with rake db:migrate again. After that, you should be able to refer to those new model fields in your controller and views.
While you could do it all in a single migration, it's generally better to keep your migrations small and discrete. This makes it easier to resolve issues if anything goes wrong.

A: Don't change the existing migration. You want to create a new migration with the command rails generate migration MigrationName, and then follow the Active Record Migrations Rails Guide, which gives lots of examples on how to add database columns.


text:
Q: TypeError: Cannot read property 'id' of undefined when map over two arrays i'm trying to load 4 random cities every time the main page loads using useEffect() hook and i am subtracting the items i already found to avoid duplications so i wrote this function :
const cities = [
  { id: "0", name: "New York" },
  { id: "1", name: "California" },
  { id: "2", name: "Tokyo" },
  { id: "3", name: "Paris" },
  { id: "4", name: "Oran" },
  { id: "5", name: "roma" },
  { id: "6", name: "dubai" },
  { id: "7", name: "madrid" },
  { id: "8", name: "beijing" },
  { id: "9", name: "montreal" }
];

const randomCitiesLoader = () => {
  let randomCities = [];
  randomCities.push(cities[Math.floor(Math.random() * cities.length - 1)]);
  for (let i = 0; i < 3; i++) {
    let queryCities = cities.filter(city => {
      return !randomCities.find(item => {
        return item.id === city.id;
      });
    });
    randomCities.push(
      queryCities[Math.floor(Math.random() * queryCities.length - 1)]
    );
  }
  return randomCities;
};

but i'm getting this error :

can someone please help

A: Math.floor(Math.random()*cities.length-1) can be -1 so you can push undefined to resulting array because cities[-1] is undefined.
You best option would be to use array[Math.floor(Math.random()*array.length)] to pick random element from array.


text:
Q: Validation on each class jQuery I'm trying to achieve the validation on each class.
This is my code
jQuery(function ($){
  $(".thevoornaam, .date_of_birt, .livingkid, .right, .limitSelected, .pijlers, .total_pijlers").bind("keyup change", function() {
      if ($(".thevoornaam").val().length > 1 && $('.date_of_birth').val().length == 10  && $(".livingkid").is(':checked') && $(".right").is(':checked') && $(".limitSelected:checked").val() == "1" && $(".pijlers").val() != null && $(".total_pijlers").val() != null)   {
          $("#stepbirth").removeClass("disabled");
      }
      else if ($(".thevoornaam").val().length > 1 && $('.date_of_birth').val().length == 10  && $(".livingkid").is(':checked') && $(".right").is(':checked') && $(".limitSelected:checked").val() == "0")   {
        $("#stepbirth").removeClass("disabled");
      }
      else {
           $("#stepbirth").addClass("disabled");
      }
    });
  });

This is working fine, how can i this code to be work on each class element.
Thank in advance


text:
Q: MacBook Pro: 2017 Unable to connect to Dell U2713HM with USB-C to DisplayPort cable I am trying to connect my MBP 2017 to a Dell U2713HM with a USB-C to DisplayPort cable (Part No ELUCDP-01) made by Alogic.
When I plug in the cable to the USB-C port, the monitor will say there is 'No DisplayPort cable' and then show 'Entering power saving mode'.
The main monitor on the other hand will dim for a moment and the keyboard will become unresponsive for a moment.
Anyone know how I can fix the issue?
Error messages in log:

ColorSync: ColorSyncProfileCreateWithDisplayID failed to get profile for kColorSyncDisplayDeviceClass

It seems to me the monitor can be recognised by the MBP. Here is a screenshot of ColorSync:

A: Upgrade to High Sierra (Version 10.13, build 17A405) allows the monitor to display again.
The picture quality is blurry. It is as if I am using the HDMI input.
It turns out there was issue with the Alogic cable.
At the end I purchased a new set of cables (Konix) and the problem is resolved.


text:
Q: WSS to WS in traefik fails with phantombot image I am trying to serve a dockerized version of phantombot with traefik and let traefik handle the certificates for ssl.
Since phantombot uses a websocket, the websocket itself can only be accessed via wss when connecting externally but on the internal network it is listet as ws since phantombot runs in http mode.
I have tried to create an entrypoint at port 82 for wss which looks like this in the toml:
[entryPoints.panel]
 adress = ":82"
 [entryPoints.panel.tls]
 [[entryPoints.panel.tls.certificates]]
  certFile = "/cert.pem"
  keyFile = "/privkey.pem"

And the corresponding labels in the bot's docker-compose:
  - traefik.panel.frontend.rule=Host:my.domain.com
  - traefik.panel.frontend.entryPoints=panel
  - traefik.panel.frontend.protocol=ws
  - traefik.panel.port=82

Exposed ports on the container for the bot:
expose:
  - 80
  - 81
  - 82

I have tried changing the protocols, making a catchall but nothing seems to work. Everytime I try to connect, I get an error-message in the browser stating that wss://my.domain.com:82/ is not answering and a HTTP(500): Broken Pipe in the bot's interface.
I am at my wits' end.
It would be nice if someone could help me :)
Edit: docker-compose of traefik
version: '3'

services:

  traefik:
    image: traefik:latest
    container_name: traefik
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
      - "81:81"
      - "82:82"
    networks:
      - web
    volumes:
      - ./traefik.toml:/etc/traefik/traefik.toml
      - ./traefik.log:/etc/traefik/traefik.log
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - /etc/letsencrypt/live/my.domain.com/cert.pem:/cert.pem
      - /etc/letsencrypt/live/my.domain.com/privkey.pem:/privkey.pem

    labels:
      - traefik.frontend.rule=Host:monitor.my.domain.com
      - traefik.port=8080
      - traefik.docker.network=web
      - traefik.enable=true
      - traefik.frontend.auth.basic.users=user:pass

networks:
  web:
    external: true

Traefik Toml:
# uncomment this line to get debug info with "docker logs":
#debug = true

defaultEntryPoints = ["https","http"]
[traefikLog]
  filePath = "/etc/traefik/traefik.log"
  format   = "json"

# The syntax is somewhat esoteric so this is mostly copy-paste
[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    entryPoint = "https"
  [entryPoints.https]
  address = ":443"
  [entryPoints.https.tls]
      [[entryPoints.https.tls.certificates]]
      certFile = "/cert.pem"
      keyFile = "/privkey.pem"
  [entryPoints.ytplayer]
     adress = ":81"
     [entryPoints.ytplayer.tls]
        minVersion = "VersionTLS12"
        cipherSuites = [
           "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
           "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
           "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
        ]
        sniStrict = true
        OSCPMustStaple = true
       [[entryPoints.ytplayer.tls.certificates]]
          certFile = "/cert.pem"
          keyFile = "/privkey.pem"
  [entryPoints.panel]
     adress = ":82"
     [entryPoints.panel.tls]
        minVersion = "VersionTLS12"
        cipherSuites = [
           "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
           "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
           "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
        ]
     sniStrict = true
     OSCPMustStaple = true
     [[entryPoints.panel.tls.certificates]]
      certFile = "/cert.pem"
      keyFile = "/privkey.pem"

[docker]
    endpoint = "unix:///var/run/docker.sock"
    domain = "morellenoir.de"
    watch = true
    exposedbydefault = false

# enable web configuration backend.
[web]

# Web administration port, proxied in docker-compose.yml
address = ":8080"

A: #traefik configuration
defaultEntryPoints = ["https","http"]
[api]
  entryPoint = "traefik"
  dashboard = true
  address = ":8080"

[entryPoints]
  [entryPoints.http]
  address = ":80"
  compress = true


text:
Q: High CPU usage when sending data using SOAP We wrote in C# some webservice that sends and receives data from remote clients. It works fine. Few days ago we found that when sending back to client array of bytes CPU usage increases from about 2% to almost 30% on IIS worker process. During debugging we found that this CPU usage peak occurs after our webmethod ended, so probably this is nothing in our code. Is there something that we don't know that could cause such CPU usage? When we sends only an error code there is no such peak...
This CPU usage occurs when there is only one client connected. When we had 4-5 clients connected CPU was used in 100%!

A: With so little to go on, I'm assuming you will only get (educated) guesses.
Here's mine: Check if the GC was active (You can do this in PerfMon). If it was, are you allocating/deallocating lots of memory? Do you have long running transactions?
Maybe of Interest:

*

*Optimizing WCF Web Service Performance

*.NET Debugging Demos Lab 4: High CPU hang


text:
Q: java android return method within listener? I am kind of new in Java Android, and Im facing this problem and i don't know what it's called, here is my code:
public boolean msgBox(String title, String text) {
    boolean bReturn = false;
    AlertDialog.Builder adb = new AlertDialog.Builder(this);

    adb.setCancelable(false);
    adb.setTitle(title);
    adb.setMessage(text);
    adb.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            //this suppose tell msgBox return true
        }
    });

    adb.setNegativeButton("Yes", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            //this suppose tell msgBox return false
        }
    });

    adb.show();

    return bReturn;
}

Now how do I tell msgBox to return true / false when user clicked positive / negative button? thanks before

A: This is not possible, because the method will end after the Dialog is opened. The Dialog will continue to be open after the method is finished.
In order to return information back to your msgBox caller, you will need to provide a callback function.
You can create an interface, pass that into msgBox, and call it in your Dialog button.
public interface OnDialogButtonClickedCallback {
    public void onDialogButtonClicked(boolean wasPositive);
}

Pass it in like this:
public boolean msgBox(String title, String text, final OnDialogButtonClickedCallback callback)

Use it in the button like this:
@Override
public void onClick(DialogInterface dialog, int which) {
    if(callback != null) {
        callback.onDialogButtonClicked(true);
    }
}

A:     @Override
    public void onClick(DialogInterface dialog, int which) {
        if(which == 1) {
           bReturn = true or false;//yes or no
        }
        //this suppose tell msgBox return false
    }

In the function above you determine which button was clicked by variable int which (f.e.: Yes is first, No is second).
bReturn should be global.
Since you are doing separate listeners for each button, you don't even have to distinguish, since those are separate listeners.


text:
Q: Content versioning - auto save is not compatible with event sourcing I'd like to version some articles so the authors will be able to restore previous versions if they want. The articles contain additional contents, for example images which I don't want to version, just save on the server. I'd like to have drafts, which can be overridden and I'd like to have a commit system. So if a draft is committed, then a new content version should be created on the server. I'd like to auto-save these drafts on the server, so they can be synchronized between clients. How should I solve auto-saving without polluting the event storage with a huge amount of draft auto-save events?
I guess I'll need some GC logic for the event storage to invalidate previous draft auto-saves after saving a new one. Is there an already existing solution for that, or should I code this for myself?

A: There should be two separate bounded contexts: Editing bounded context and Content bounded context (names may differ, please adapt to your domain).
In the Editing BC you should not use Event sourcing as the persistence mechanism of the drafts. Instead you could use simple CRUD entities and publish an infrastructure event (i.e. DraftUpdated(id, timestamp)) every time the Draft is persisted (i.e. auto-save). Then, an event listener should forward that event to the connected clients so that they update their version of the draft. This infrastructure event should not be persisted, it's just a transient event. You could use any transport mechanism available like SSE or RabbitMQ.


text:
Q: Fill combobox without duplicates from stored procedure I'm trying to fill a combobox with data I get from a stored procedure. But it shows duplicates of everything.
Anyway to leave out these doubles and just show everything once?
stored procedure:
SELECT *
FROM Personeel
LEFT JOIN Afdeling ON Afdeling.AfdelingID = Personeel.AfdelingID

Changed stored procedure:
SELECT distinct *
FROM Personeel
LEFT JOIN Afdeling ON Afdeling.AfdelingID = Personeel.AfdelingID

See image: http://i.stack.imgur.com/l1YaW.png
Data when stored procedure is executed: http://i.stack.imgur.com/KNBvY.png
I can make a new stored procedure. But then why would I if I can use one I already have?
Help? Thanks in advance

A: You need to clear it of all items before populating it again. You've added all items once, and then again; each item has been added twice.

A: SELECT DISTINCT *
FROM Personeel
Distinct will return only one


text:
Q: Issue while printing flow document: "the calling thread cannot access this object as a differnt thread owns it" The code below keeps giving me the following error: The calling thread cannot access this object as a differnt thread owns it
I tried using:

*

*SynchronizationContext

*Application.Current.Dispatcher

*Windows.Threading.Dispatcher

private void PrintDocument()
    {
        PrintQueue printQueue = null;
        using (var worker = new BackgroundWorker())
        {
            worker.WorkerSupportsCancellation = true;
            try
            {
                worker.DoWork += (s, e) =>
                {
                    string actualServerHostName = "\\\\" + Dns.GetHostEntry(Config.Default.printer.printServer.TrimStart('\\')).HostName;
                    var printServer = new PrintServer(actualServerHostName);
                    printQueue = printServer.GetPrintQueue(Config.Default.printer.defaultPrinterName);
                    printQueue.UserPrintTicket = printDlg.PrintTicket;
                    e.Result = printQueue;
                };
                worker.RunWorkerCompleted += (s, e) =>
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        printQueue = e.Result as PrintQueue;
                        var flowDocument = CreateFlowDocument();
                        PrintFlowDocument(printQueue, flowDocument.DocumentPaginator);
                    }, DispatcherPriority.Send);

                    InProgress = false;
                };
                InProgress = true;
                worker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                worker.CancelAsync();
                throw ex;
            }
        }
    }

private XpsDocumentWriter GetPrintXpsDocumentWriter(PrintQueue printQueue)
    {
        XpsDocumentWriter xpsWriter = PrintQueue.CreateXpsDocumentWriter(printQueue);
        return xpsWriter;
    }

    public void PrintFlowDocument(PrintQueue printQueue, DocumentPaginator document)
    {
        XpsDocumentWriter xpsDocumentWriter = GetPrintXpsDocumentWriter(printQueue);
        PrintDocumentPaginator(xpsDocumentWriter, document);
    }

    private void PrintDocumentPaginator(XpsDocumentWriter xpsDocumentWriter, DocumentPaginator document)
    {
        try
        {
            xpsDocumentWriter.WriteAsync(document);
        }
        catch (Exception ex)
        {
            _dialogService.ShowErrorAsync("Error occured: ", ex.Message);
        }
    }

    private IDocumentPaginatorSource CreateFlowDocument()
    {
        FlowDocument doc = (FlowDocument)Application.LoadComponent(new Uri(@"/[assembly];component/Controls/PrintTicketControl.xaml", UriKind.RelativeOrAbsolute));
        doc.DataContext = this;
        return doc;
    }

It fails when calling xpsDocumentWriter.WriteAsync(document); in the PrintDocumentPaginator method.
Having a look at the stack trace it seems like the PrintQueue is blowing up.
I also checked the threads on which the controls are created and that I am successfully back on the Main thread when calling the PrintDocument function.
Any ideas?
Thanks


text:
Q: Intermittent wireless connection while on battery On my HP m6-k015dx Sleekbook, the internet connection works perfect on AC power, but when I unplug, it keeps disconnecting.
How I verified
I do a ping test
ping -t google.com

When on AC power there is no disconnection, but when on battery I get the following repeating pattern:
Reply from 74.125.68.139: bytes=32 time=150ms TTL=44
Reply from 74.125.68.139: bytes=32 time=150ms TTL=44
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Reply from 74.125.68.139: bytes=32 time=300ms TTL=44
Reply from 74.125.68.139: bytes=32 time=142ms TTL=44
Reply from 74.125.68.139: bytes=32 time=166ms TTL=44
Reply from 74.125.68.139: bytes=32 time=152ms TTL=44
Reply from 74.125.68.139: bytes=32 time=258ms TTL=44
Reply from 74.125.68.139: bytes=32 time=172ms TTL=44
Reply from 74.125.68.139: bytes=32 time=183ms TTL=44
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Request timed out.

What I have tried
I have Windows 10 (Upgraded 2 months back. It has been working fine.) and have tried the updated drivers from HP's official website but it didn't work. I have been seeing this issue for 2 days. Don't remember if I dropped or knocked it somewhere.
My Questions
Is it a hardware issue?
Will downgrading to Windows 8 help?

A: Go to Control Panel\Hardware and Sound\Power Options, click on Change plan settings for your selected plan, then Change advanced power settings and under Wireless Adapter Settings you can set it to Maximum Performance


text:
Q: ASP .NET and ArcGIS API for Javascript : FeatureTable won't show up I"m a newbie with the ASP .NET, a have an issue. I want to show up a feature table in a viewer but I don"t get any results.
I think I"m missing something?
Here is example that I took from the ArcGIS API example and include it in my project :
    <link rel="stylesheet" href="https://js.arcgis.com/3.20/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="https://js.arcgis.com/3.20/esri/css/esri.css">

The FeatureTable.


text:
Q: Can't set up profile with latest version of RSelenium for firefox this code ran for last version I used in July:
fprof <- getFirefoxProfile("c:/Users/cp/AppData/Roaming/Mozilla/Firefox/Profiles/j7a5lq0r.selenium", useBase = T)
rS <- rsDriver(browser = "firefox", port = 4567L, extraCapabilities = fprof)

but now the output is:
[1] "Connecting to remote server"
$`moz:profile

[1] "C:\\Users\\cp\\AppData\\Local\\Temp\\rust_mozprofile.7n9y6eVCqnpt"

so it creates some temporary profile not loading the set one. Anyone knows what's the issue? This profile is valid and is ok while start FF manually.


text:
Q: Exactly same size for all screens physically in Android
how is it possible that dimensions of any object physically same size on all screens?

A: From the android developer's documentation:

To preserve the visible size of your UI on screens with different
  densities, you must design your UI using density-independent pixels
  (dp) as your unit of measurement. One dp is a virtual pixel unit
  that's roughly equal to one pixel on a medium-density screen (160dpi;
  the "baseline" density). Android translates this value to the
  appropriate number of real pixels for each other density.
For example, consider the two devices in figure 1. If you were to
  define a view to be "100px" wide, it will appear much larger on the
  device on the left. So you must instead use "100dp" to ensure it
  appears the same size on both screens.

So, what you are trying to achieve is possible using dp as the unit for the height and width properties of the object.


text:
Q: Iterating though a list issues I am trying to take a list grocery list and checks it against things you already have and puts it in a new list. I am learning how to iterate though lists and cannot figure out why I am getting the output that I am. I want the output to be a list of things that where not found in the list of things you already have. The output at the moment prints out what I need but multiple times. Not sure why. Thanks

let groceryList = ['Bread', 'Cereal', 'Bagels', 'Water', 'Apple'];
let currentGrocery = ['Eggs', 'Lettuce', 'Milk', 'Cheese','Bread','Water','Oil'];
let newList = [];

for (let i = 0; i < groceryList.length; i++) {
    for (let j = 0; j < currentGrocery.length; j++){
        if (groceryList[i] !== currentGrocery[j]){
            newList.push(groceryList[i]);
        }
    }
}

console.log(newList);

A: let groceryList = ['Bread', 'Cereal', 'Bagels', 'Water', 'Apple'];
let currentGrocery = ['Eggs', 'Lettuce', 'Milk', 'Cheese','Bread','Water','Oil'];
let newList = [];

currentGrocery.forEach(item =>{
     if (!groceryList.includes(item)) newList.push(item);
})

console.log(newList);

A: You oculd filter the array.

const
    groceryList = ['Bread', 'Cereal', 'Bagels', 'Water', 'Apple'],
    currentGrocery = ['Eggs', 'Lettuce', 'Milk', 'Cheese', 'Bread', 'Water', 'Oil'],
    newList = currentGrocery.filter(item => !groceryList.includes(item));

console.log(...newList);

A: You push the item from your grocery list for every non-matching current grocery. What you want to do is to only push to the new list if there are no current grocery matches.
In a naive way, this could be achieved via
let found = false;
for (let i = 0; i < groceryList.length; i++) {
    for (let j = 0; j < currentGrocery.length; j++){
        if (groceryList[i] == currentGrocery[j]){
            found = true;
            break;
        }
    }
    if (found) {
        newList.push(groceryList[i]);
        found = false;
    }
}

A more readable approach makes use of the filter() and includes() functions:
let newlist = groceryList.filter(item => !currentGrocery.includes(item));
console.log(newlist);


text:
Q: Objective C - Best practice for Unit Testing with multiple test inputs I'm writing unit test codes for an existing project. The project is in Objective-C and I have to test few functions with a number of inputs to the test cases. For example, I have a test case to test a function calculator where two parameters are inputted. Currently I create array to store the set of input values to run the test. The code used are as follows:
- (void)setUp {
    [super setUp];
    self.vcToTest = [[BodyMassIndexVC alloc] init];
    input1 = [[NSMutableArray alloc] initWithObjects:@"193", @"192", @"192", @"165", @"155", @"154", nil];
    input2 = [[NSMutableArray alloc] initWithObjects:@"37", @"37", @"36", @"80",@"120", @"120", nil];
}

- (void)testCalculatorSuccess {
    for (int i=0; i<input1.count; i++) {
        NSArray *expectedResult = [[NSArray alloc] initWithObjects: @"9.93", @"10.04", @"9.77", @"29.38", @"49.95", @"50.60", nil];
        NSString *actualResult = [self.vcToTest calculateResult:input1[i] andInput2:input2[i]];
        XCTAssertEqualObjects(actualResult, expectedResult[i]);
    }

}

I searched for best practices online but was not able to find any. Can someone help me with this? Am I running the test in the right way? What is the best practice to be followed in such cases? Should I create a test case for every set of input?

A: Your test class should be targeting one specific thing to test which is the sut (system under test). In your case the sut variable should be your vcToTest. The way I would go about testing is by dependency injection rather than storing all the arrays you are testing as instance variables. So you would create a test method that takes in the parameters that you want to test. This way you don't need to keep creating instance variables, you only create local variables that are relevant to the test method.
- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
    self.sut = [[BodyMassIndexVC alloc] init];
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    self.sut = nil;
    [super tearDown];
}

- (void)testBMIFormulaInCmAndKgSuccess {
    // local variables that are only seen in this method
    NSArray *heightsInMetres = [[NSMutableArray alloc] initWithObjects:@"193", @"192", @"192", @"165", @"155", @"154", nil];
    NSArray *weightsInKg = [[NSMutableArray alloc] initWithObjects:@"37", @"37", @"36", @"80",@"120", @"120", nil];
    NSArray *expectedResults = [[NSArray alloc] initWithObjects: @"9.93", @"10.04", @"9.77", @"29.38", @"49.95", @"50.60", nil];
    for (int i=0; i<heightsInMetres.count; i++) {
        [self xTestHeightInMeters:heightsInMetres[i] weightInKg:weightsInKg[i] expecting:expectedResults[i]];
    }
}

// the variables that are used to test are injected into this method
- (void)xTestHeightInMeters:(NSString *)height weightInKg:(NSString *)weight expecting:(NSString *)expectedResult {
    NSString *result = [self.sut calculateBMIforHeight:height andWeight:weight];
    XCTAssertEqual(result, expectedResult);
}

If I was you I wouldn't create arrays to run the tests. Arrays are messy and become hard to understand what is going on, and easy to make mistakes. I would create specific test methods that test one thing to make sure the sut is working properly. For example in TDD you create a test method that will fail, then modify your sut to fix this failure in the most simple way. Usually this means your fix will just return exactly what you are expecting. Then you make another test that tests the exact same thing with a different value, it should now fail because your sut is simply returning what they previous test was looking for. Now you modify your sut again to make both tests pass. After this in most situations you won't need any addition tests since it has proven to work in two unique ways.
I know you said you are testing software that was written already, but I strongly recommend you check out Test Driven Development. Even if you don't actually apply TDD, you will learn how to create meaningful tests. This helped me learn tdd

A: In my experience, the key consideration should be how easy it will be to maintain the test suite over time. Your current approach will cause problems down the road in two ways:

*

*If you want to use different numbers for you BMI calculation you need to use a different test class (because you're locking in the values in the setup method).

*If you ever decide to use different math or multiple BMI equations you'll have to update the arrays anywhere you're checking those values.
What I would suggest is to instead create a CSV or plain text file that has the height, weight, and expected BMI values in it. That keeps the test data together. Then in your test methods, load the file and check your actual BMI against the expected BMI.
You have the flexibility here to mix and match test data, or use different test files for different BMI equations. Personally, I also like the fact that you can keep old data files around as you change things, in case you ever want to rollback or add legacy algorithm support.
A quick and dirty version would look something like this:
- (NSArray *)dataFromFileNamed:(NSString *)filename {
    NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:filename ofType:nil];
    // load the data however its formatted
    // return the data as an array
    return loadedData;
}

- (void)testBMIFormulaInCmAndKgSuccess {
    NSArray *testData = [self dataFromFileNamed:@"BMI_data_01.txt"];
    for (int i=0; i < testData.count; i++) {
        NSArray *dataSet = testData[i];
        CGFloat height = dataSet[0];
        CGFloat weight = dataSet[1];
        CGFloat expectedBMI = dataSet[2];
        NSString *actualResult = [self.vcToTest calculateBMIforHeight:height andWeight:weight];
        XCTAssertEqual(actualResult, expectedBMI);
    }
}

A: It's usually best to avoid for-loops in unit test code. This rule usually leads to separate assertions.
But in your case, you want to exercise a function with various inputs. Your approach is not bad at all. We can simplify the arrays by using literals:
NSArray<NSString *> *heightsInMetres = @[ @"193",   @"192",  @"192",   @"165",   @"155",   @"154"];
NSArray<NSString *> *weightsInKg =     @[  @"37",    @"37",   @"36",    @"80",   @"120",   @"120"];
NSArray<NSString *> *expectedResults = @[@"9.93", @"10.04", @"9.77", @"29.38", @"49.95", @"50.60"];

I also normally avoid funny formatting. But aligning the columns helps us see the values in a table-like format.
Finally, I wouldn't put these values in setUp unless they're used across multiple tests.
If you need many tests like this, it may be worth exploring a test format that uses actual tables, like Fitnesse. Table data could be in spreadsheets or in wiki format, driving tests.


text:
Q: Optimal bandwidth for a Gaussian filter I have an $n \times n$ image $A$, and an $m\times m$ image $B$, where $n>m$. As the smaller image looks like a lower-resolution version of the larger one, I'm interested in the relative loss, computed as follows:

*

*

*

*use a Gaussian filter to low-pass $A$

*

*downsample the filtered $A$ to the size of $B$

*

*take the difference with $B$.

Specifically, let $f_\sigma$ be the Gaussian filter with bandwidth $\sigma$, and $\Phi(\cdot)$ be the function that downsamples every $n//m$ pixels along row and column. I want to compute
$$\ell_\sigma = \lVert\Phi(f_\sigma \ast A) - B\rVert_F^2.$$
Here $\lVert\cdot\rVert_F$ is the Frobenius norm. $\ast$ is 2D convolution. I use subscript $\sigma$ because obviously the loss value depends on what bandwidth $\sigma$ we adopt.
I calculated the $\ell_\sigma$ for a range of $\sigma$'s. It seems $\ell_\sigma$ is a convex function of $\sigma$. Is that true for every $A$ and $B$? Is it possible to prove it?


text:
Q: Python 3.x: How to save and load data from within a class I would like a class that in its initialize checks if filename exists. If it does it should initialize itself with filename, otherwise it should run init. At a later point I can then run a save method, saving the entire object.
A sketch of what I want:
class data(object):
    def __init__(self, filename):
        if does_not_exist(filename): # create new
             [... expensive computations]
             self.save(filename)
        else: # load existing
            with open(filename,'rb') as fp:
                self = pickle.load(fp)

    def save(self, filename):
        with open(filename,'wb') as fp:
        pickle.dump(self, fp)

When loading I know that I can do something like
tmp = pickle.load(fp)
    self.a = tmp.a
    self.b = tmb.b
    ...

But I hope that there is a better way

I assume this question has been asked before, but couldn't find it :/

A: Assigning to self within __init__ is meaningless, since you're not modifying the object that self points to -- you're just binding the variable name self in the function to a different object.
What you can do instead is use a staticmethod or classmethod to perform the optional loading from cache:
class Data(object):
    @classmethod
    def init_cached(cls, filename):
        if not os.path.exists(filename):  # create new
            result = cls(filename)
            result.save(filename)
            return result
        else:
            with open(filename, 'rb') as fp:
                return pickle.load(fp)

    def __init__(self, filename):
        pass  # [... expensive computations]

Now, use Data.init_cached() instead of Data() to initialize your object.

A more fancy approach would involve overriding Data.__new__() to achieve the same thing, but where initialization with Data() transparently checks if a cached version exists:
class Data(object):
    def __new__(cls, filename):
        if not os.path.exists(filename):  # create new
            return super(Data, cls).__new__(cls, filename, _save=True)
        else:
            with open(filename, 'rb') as fp:
                return pickle.load(fp)

    def __init__(self, filename, _save=False):
        # [... expensive computations]
        if _save:
            self.save(filename)

Further reading: Python's use of __new__ and __init__?


text:
Q: Custom script / code not working in combination with other code in YooTheme I'm using a few custom scripts in the custom code section in a template (YooTheme), but when I add the following code to the other nothing work anymore.
UIkit.icon.add('spotify','<svg enable-background="new 0 0 512 512"
style="width:20px;" id="Layer_1" version="1.1" viewBox="0 0 512 512"
xml:space="preserve" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"><g>
<path d="M507,257c0,3.8-0.1,7.7,0,11.5c0.9,31.2-7.5,60.5-19.7,88.7c-18.7,43.1-47.8,77.9-86.1,104.7
c-29.1,20.4-61.4,33.7-96.4,40.4c-21.8,4.1-43.7,4.9-65.6,3.5
c-34.1-2.3-66.4-11.6-96.7-27.7c-38.9-20.6-70.4-49.4-94.3-86.4
c-18.7-29-30.6-60.7-36.3-94.8c-3.3-19.7-4-39.5-2.5-59.2c3.8-48.6,20.2-92.7,49.9-131.4c36.6-47.7,84-79.5,142.8-92.6
c77.7-17.3,148.7-1.3,211.7,47.6c37.9,29.4,64.5,67.4,80.5,112.6C503.8,200.7,509.3,228.3,507,257z M221.1,139.1
c-13.2,0-26.3,0.9-39.4,1.8c-24.9,1.8-49.5,5.8-73.6,12.3c-5.1,1.4-10.3,2.9-14.4,6.6c-8.1,7.4-10.1,19.2-4.9,28.7
c5.3,9.7,16.2,14.3,27.3,11.1c33.9-9.9,68.7-13.3,103.9-13.7c8.3-0.1,16.6,0.4,24.9,0.7c16.1,0.5,32.2,2,48.1,4.6
c40,6.4,78.6,17,113.9,37.6c11.3,6.6,25.4,2.3,31.6-8.8c6.3-11.3,2.5-25.3-8.9-32c-16.6-9.7-34-17.5-52.1-23.9
C326.8,146.3,274.5,139.5,221.1,139.1z
M406.2,289.4c0.5-8.8-4.2-14.3-11.3-18.4c-22.8-13.4-46.9-23.5-72.3-30.9
c-31-9-62.6-13.6-94.8-14.8c-15.8-0.6-31.6,0.2-47.4,1.7c-21.4,2-42.4,6-63,12.2c-11.3,3.4-16.6,13.9-13.7,24.6
c2.3,8.4,13.3,16.6,25.1,12.8c29.1-9.3,59.2-12.2,89.5-12.3c15.9,0,31.8,1.1,47.6,3.6c20.6,3.2,40.8,7.7,60.5,14.5
  c17.7,6.1,34.5,13.9,50.7,23.4C390.3,313.7,406.1,304.7,406.2,289.4z M223.6,306.9c-17.6,0.1-31.4,0.5-45.2,2.1
c-18,2.1-35.9,5-53.5,9.2c-8.4,2-13.2,10.3-11.3,18.3c2.2,9,10,13.9,18.8,12c18-4,36.1-7.1,54.5-8.8
c24.3-2.3,48.4-2.2,72.6,1
c32.8,4.4,63.4,14.6,91.7,31.7c8,4.9,17.3,2.6,21.8-5c4.5-7.6,2.2-16.7-5.6-21.7c-10.3-6.5-21.2-12-32.4-16.7
C298.2,313.3,259.7,306.3,223.6,306.9z" fill="#A7A7A7"/></g></svg>');

jQuery(function($) {
$('a[href*="https://www.spotify.com"].uk-icon').attr('uk-icon','spotify');
});

The other custom script I use is:
<script type="application/javascript" src="https://app.usercentrics.eu/latest/main.js" id="NHkicYTON"></script>

Thanks for your help!