text:
Q: Most of the files on a NTFS Partition show zero bytes as size after chkdsk on Boot I was trying ubuntu from a bootable pen drive of ubuntu.
But Ubuntu was unable to access F: Drive, it was showing the following error message :

Error mounting /dev/sda2 at /media/ubuntu/New Volume: Command-line `mount -t >"ntfs" -o "uhelper=udisks2,nodev,nosuid,uid=999,gid=999,dmask=0077,fmask=0177" >"/dev/sda2" "/media/ubuntu/New Volume"' exited with non-zero exit status 12: >Failed to read last sector (231628799): Invalid argument
  HINTS: Either the volume is a RAID/LDM but it wasn't setup yet,
   or it was not setup correctly (e.g. by not using mdadm --build ...)
  or a wrong device is tried to be mounted,
  or the partition table is corrupt (partition is smaller than NTFS),
    or the NTFS boot sector is corrupt (NTFS size is not valid).
  Failed to mount '/dev/sda2': Invalid argument
  The device '/dev/sda2' doesn't seem to have a valid NTFS.
  Maybe the wrong device is used? Or the whole disk instead of a
  partition (e.g. /dev/sda, not /dev/sda1)? Or the other way around?

On one of the forums I found the following solution

Run the following command in ubuntu terminal
  sudo ntfsfix /dev/sda2

I did so, but the partition was still inaccessible But error code was different it was Error code 13
The I again logged on to windows, (Windows 7 Ultimate 64 bit)
While booting It asked for dskchk and I allowed, then it performed a long operations which included something like following:

Deleting corrupt attribute record (128, "")...
  and
  Inserting data attribute into file 36015...

After that
1. The drive size was somehow reduced to 52GB from 110GB
2. Although all files are being shown in the drive but most of the files have become zero size. Some files are ok.
3.The drive have now become accessible from ubuntu but there also the drive size is 52 GB and files are being shown zero bytes size.
What exactly is the problem?
If possible, how can I recover my data?
If data can not recovered should I format my F drive and will it make it normal ?
How to format the drive to restore it to its normal size 110 GB ?
Edit 1:
I tried

chkdsk F:/f

command in windows, it did not find any error with drive and also could not repair it.
I tried iRecover tool but it gets stuck after a certain time.


text:
Q: Why do mojo or pojo need to be downloaded first and read after it? Why do mojo or pojo need to be downloaded first and read after it? Why can't I just use it as an intermediate variable in Java?
I searched the examples and I found that all the examples are like this:
h2o.down_load(modelName);

URL mojoURL = MojoUtil.class.getResource(modelName);
 MojoReaderBackend reader = MojoReaderBackendFactory.createReaderBackend(mojoURL, MojoReaderBackendFactory.CachingStrategy.MEMORY);
 MojoModel model = ModelMojoReader.readFrom(reader);

Can I use some method like this:
String modelName = h2o.train_drf(param).getModelName();
MojoModel model = h2o.getMojoModel(modelName);

Furthermore, in document http://docs.h2o.ai/h2o/latest-stable/h2o-docs/save-and-load-model.html, there are only mentioned R and python of how to download mojo model: saving an H2O binary model with h2o.saveModel (R), h2o.save_model (Python).
How can I do it in java?

A: Why is the API done as two function calls?
I doubt there is a reason; just no-one particularly needed to reduce those two lines to one. (Or, maybe, whoever wrote them always envisaged having to specify the arguments.)
If you are always going to call those two functions in that way, and especially if it happens in more than one place in your code, it definitely makes sense to write the wrapper function you describe.
Why is there a download involved at all?
Remember that, even when using a Java client, H2O is running as two processes: the client and the server. So, even when the server part is running on localhost, they are still completely separate, with no shared memory.
Why is it a zip file
If you look inside a mojo file, you see lots of little binary files. That would be why it is a zip file: a simple container that can be easily moved around.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can i control if a column need to be shown inside New form based on Content Type I am working on an on-premises sharepoint 2013. now i know that i can hide certain columns from New list forms using this power-shell script:-
$web = Get-SPWeb http://*******/
$field = $web.Fields["Approve"]
$field.ShowInNewForm = $false
$field.update($true)

this will always hide the site column named "Approve" from the New list forms. but in my case i have 2 site content types, which are using the Approve site column.but i want the column to be shown inside the New form for Content Type A, while to be hidden inside the New form for Content Type B .. is this possible? or hiding/showing site columns based on the list form type (New,Edit,View), can only be achieved @ the site column itself? and not at the Content type level ? keeping in mind that in both cases i want the Approve site column, to be shown inside the Edit form..so hiding the column completely from the Content Type will not work...

A: You can use Client side rendering(jsLink) to control its display based on Content Type.
Just add the below jslink in your newform and editform, modify it to use your content type. Should work.
(function () {

    var overrideCtx = {};
    overrideCtx.Templates = {};
    overrideCtx.Templates.Fields = {
        "Approve": {
            "NewForm": hideField,
            "EditForm": hideField
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();

function hideField(ctx) {

    if(ctx.CurrentItem.ContentType == "Content Type B"){
        // get the span that represents the field's actual edit control
        var span = $get(ctx.FormUniqueId + ctx.FormContext.listAttributes.Id + ctx.CurrentFieldSchema.Name);

        // still need to go up two levels to hide the entire <tr>
        span.parentNode.parentNode.setAttribute("style", "display:none");
        return "";
    }else{
        return SPFieldBoolean_Edit(ctx);
    }
}

Here, i am assuming that Approve is a site column of boolean type.
Modified from - Hiding Forms; fields using standard jquery versus using JSlink. which approach is better


text:
Q: Access to protected method in java (android) I'm learning to do applications with android studio. I'm building a numberpicker programming. I want to resize my numberpiker.
To resize my numberpicker I have found a protected method called onMeasure in developer documentation.
https://developer.android.com/reference/android/widget/NumberPicker
NumberPicker p_myNumberPicker = new NumberPicker(this);
p_myNumberPicker.setMaxValue(150);
p_myNumberPicker.setMinValue(0);
p_myNumberPicker.onMeasure(100,100);
NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        p_number.setText(""+newVal);
    }

My problem is that I have an error message "onMeasure(int,int) has protected access in android.widget.NumberPicker".
How can I fix it?

A: Just read below the method documentation and you will find:

CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass' onMeasure(int, int) is a valid use.
The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should override onMeasure(int, int) to provide better measurements of their content.

A: just remove this line:
p_myNumberPicker.onMeasure(100,100);

because you are violating the access scope of the method, which is not meant to be called alike this. if you really want to call it, you have to use a CustomNumberPicker extends NumberPicker, and call this protected method from within it's scope. only then the access scope would match the definition.

A: That's not how you resize things.  In fact calling the onMeasure of a view incorrectly will severely break things.  Since you're making it a fixed size, just give it a fixed width and height in the xml that defines the widget.  Or if defining it in code, use a dixed width and height in its layout params.


text:
Q: How to add module to environment module? So I can load it using module load When I run module avail, I got:
--------------------------------- /usr/share/modules/modulefiles ---------------------------------
dot  module-git  module-info  modules  null  use.own

--------------------------------- /usr/share/modules/modulefiles ---------------------------------
dot  module-git  module-info  modules  null  use.own

And I notice people uses module to load gcc5 cuda10.0 by module load gcc5 cuda10.0 . Like this person did in:
Slurm sbatch for a PyTorch script draining node; gres/gpu: count changed for node node002 from 0 to 1
How do I add things like gcc5 and cuda10.0 to my modules?

A: You need to craft these modulefiles by hand if you manually install these specific software or the specific version of these software.
If you use a package manager like Spack or EasyBuild to build the software, those tools can also generate the corresponding modulefiles to use the software they built and install.


text:
Q: Delegate factory in Ninject Autofac got delegate factories, but I can't find any information about how to implement this in Ninject. The reason for me wanting to use this is to avoid referencing the container itself, but to be able to dynamically create new objects of the specified type.
Is there something similar I can do to achieve the same result?

A: I believe you are looking for the factory extension (link).


text:
Q: Parsing XML using T-SQL in SQL Server 2012 I've parsed XML using namespaces in SQL before but I'm having a real bear with this one. I'm trying to extract the ip addresses from the xml but having no luck.  I'm thinking it has something to do with the xsd namespace, but can't seem to find the right combination of namespace declaration and node pathing.
Here's a sample of the xml:
<obj xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:vim25" versionId="6.0" xsi:type="ArrayOfGuestStackInfo">
  <GuestStackInfo xsi:type="GuestStackInfo">
    <dnsConfig>
      <dhcp>false</dhcp>
      <hostName>SXVCUP05</hostName>
      <domainName>corp.dtcc.com</domainName>
      <ipAddress>172.18.18.13</ipAddress>
      <ipAddress>172.18.18.20</ipAddress>
      <ipAddress>172.22.43.132</ipAddress>
      <ipAddress>172.22.43.148</ipAddress>
      <ipAddress>172.22.37.68</ipAddress>
      <ipAddress>172.22.37.84</ipAddress>
      <searchDomain>corp.dtcc.com</searchDomain>
      <searchDomain>dtcc.com</searchDomain>
      <searchDomain>backup.dtcc.com</searchDomain>
    </dnsConfig>
    <ipRouteConfig>
      <ipRoute>
        <network>0.0.0.0</network>
        <prefixLength>0</prefixLength>
        <gateway>
          <ipAddress>172.28.224.1</ipAddress>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>172.18.8.133</network>
        <prefixLength>32</prefixLength>
        <gateway>
          <ipAddress>172.28.224.10</ipAddress>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>172.22.8.14</network>
        <prefixLength>32</prefixLength>
        <gateway>
          <ipAddress>172.28.224.10</ipAddress>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>172.28.224.0</network>
        <prefixLength>24</prefixLength>
        <gateway>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>172.28.224.112</network>
        <prefixLength>32</prefixLength>
        <gateway>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>172.28.224.255</network>
        <prefixLength>32</prefixLength>
        <gateway>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>224.0.0.0</network>
        <prefixLength>4</prefixLength>
        <gateway>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>255.255.255.255</network>
        <prefixLength>32</prefixLength>
        <gateway>
          <device>0</device>
        </gateway>
      </ipRoute>
    </ipRouteConfig>
  </GuestStackInfo>
</obj>

Using the following code to parse the xml
WITH XMLNAMESPACES ('http://www.w3.org/2001/XMLSchema' as xsd)
    SELECT a.b.value('ipAddress[1]', 'varchar(100)') AS ipaddress
    FROM @sam_xml.nodes('/obj/GuestStackInfo/dnsConfig') a(b)

Thanks!

A: The values you are looking for are living in the default namespace xmlns. This is the only namespace you need to declare:
DECLARE @sam_xml XML=
N'<obj xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:vim25" versionId="6.0" xsi:type="ArrayOfGuestStackInfo">
  <GuestStackInfo xsi:type="GuestStackInfo">
    <dnsConfig>
      <dhcp>false</dhcp>
      <hostName>SXVCUP05</hostName>
      <domainName>corp.dtcc.com</domainName>
      <ipAddress>172.18.18.13</ipAddress>
      <ipAddress>172.18.18.20</ipAddress>
      <ipAddress>172.22.43.132</ipAddress>
      <ipAddress>172.22.43.148</ipAddress>
      <ipAddress>172.22.37.68</ipAddress>
      <ipAddress>172.22.37.84</ipAddress>
      <searchDomain>corp.dtcc.com</searchDomain>
      <searchDomain>dtcc.com</searchDomain>
      <searchDomain>backup.dtcc.com</searchDomain>
    </dnsConfig>
    <ipRouteConfig>
      <ipRoute>
        <network>0.0.0.0</network>
        <prefixLength>0</prefixLength>
        <gateway>
          <ipAddress>172.28.224.1</ipAddress>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>172.18.8.133</network>
        <prefixLength>32</prefixLength>
        <gateway>
          <ipAddress>172.28.224.10</ipAddress>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>172.22.8.14</network>
        <prefixLength>32</prefixLength>
        <gateway>
          <ipAddress>172.28.224.10</ipAddress>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>172.28.224.0</network>
        <prefixLength>24</prefixLength>
        <gateway>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>172.28.224.112</network>
        <prefixLength>32</prefixLength>
        <gateway>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>172.28.224.255</network>
        <prefixLength>32</prefixLength>
        <gateway>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>224.0.0.0</network>
        <prefixLength>4</prefixLength>
        <gateway>
          <device>0</device>
        </gateway>
      </ipRoute>
      <ipRoute>
        <network>255.255.255.255</network>
        <prefixLength>32</prefixLength>
        <gateway>
          <device>0</device>
        </gateway>
      </ipRoute>
    </ipRouteConfig>
  </GuestStackInfo>
</obj>';

--the query will use .nodes() to dive one level deeper then your query in order to get all IP-addresses from within <dnsConfig>:
WITH XMLNAMESPACES(DEFAULT 'urn:vim25')
SELECT a.b.value('text()[1]', 'varchar(100)') as ipaddress
FROM @sam_xml.nodes('/obj/GuestStackInfo/dnsConfig/ipAddress') a(b)


text:
Q: libgdx input handling not working after backing from web page opened by clicking adView I am creating an android game with libGDX framework.
My setting screen is implemented with scene2d.
I handled back button click event by implementing a inputProcessorAdapter class. Add that and  Stage to InputMultiplexer for input handling.
Everything works well excepting after clicking adView on bottom of screen and then going back to the screen from google advertise web page. Back key no longer can be captured by inputProcessorAdapter. And keyboard is also no longer shown when Textfield of Stage is focused.
Below is my input handling code.
inputProcessor = new InputProcessorAdapter() {
    @Override
    public boolean keyDown(int keycode) {
        if (keycode == Input.Keys.BACK) {
            // Go back to main menu
            stage.unfocusAll();
            Gdx.input.setOnscreenKeyboardVisible(false);
            SettingScreen.this.game.setScreen(new MainMenuScreen(SettingScreen.this.game));
        }
        return false;
    }
};

InputMultiplexer multiplexer = new InputMultiplexer();
multiplexer.addProcessor(inputProcessor);
multiplexer.addProcessor(stage);
Gdx.input.setInputProcessor(multiplexer);

Waiting for your answer or advice.

A: Finally, I found solution inspired by a topic in official forum site.
Lifecicle messed up by Admob
Below is my solution code.
    adView.setAdListener(new AdListener() {
        @Override
        public void onAdClosed() {
            super.onAdClosed();
            gameView.requestFocus();
        }
    });

A: You should add
Gdx.input.setCatchBackKey(true);

after your setInputProcessor call so the whole code should look like
...
Gdx.input.setInputProcessor(multiplexer);
Gdx.input.setCatchBackKey(true);
...


text:
Q: neural network with mostly zero target I am very new to neural networks. I have a dataset that contains 16M records, in which only 70K are labeled 1 and the rest are 0 (even by setting some special restrictions the total would not be less than 2.5M records in which 58K is labeled 1, and the restriction is not fully logical as well). Is there any special practice to deal with this kind of data?
Now if I just write a function to always return 0, the accuracy would be 99.56% ! Is neural network an appropriate option at all? If no, what is my alternative and if yes, how should deal with it?
tnx

A: You can try to give a higher weight to samples labeled 1 or sample minibatches from both classes separately, such that the network is shown the same number of examples from both classes.
For the first method, frameworks such as Keras give an option to include a weight factor for every class:
class_weights = {
    0: 1.0,
    1: 43.0,
}

model.fit(X, y, ..., class_weight=class_weights)

scikit-learn has a method of computing the class weights automatically, as shown in this comment on Kaggle
Accuracy is not a good way to measure the performance of the network in this case. Precision, recall for the class 1 or similar measures might give a better understanding of the performance of the model.


text:
Q: How to reload page using Ajax I have function addFeaturesToScene which make a new URL using ajax.
After the function ends I need to go to the new site automatically
Here is code:
function addFeatureToScene(featureNid, sceneNid)
  {
  alert(featureNid + " -> " + sceneNid);

     $.ajax({
    type       : 'GET',
    url        : '/copy-feature-and-add-it-to-scene/' + featureNid + '/' + sceneNid,
    dataType   : 'json',
    async      : false,
    success    : function(reply) {

            //Code to open a page with a new url?

 }
 });

 }

A: You can use window.location
window.location.href = 'http://example.org';


text:
Q: Google Map is not working on the second tab of Tab Plugins I am using a postTabs plugin and Comprehensive Google Map Plugin, my problem was when I have my Google map on the second tab, the map is not loading as expected. But if I move it on the 1st tab it works really great.. Is there any way to make the map work on the second tab? Actually, whichever Tab plugin I use the map is not loading properly on the second tab.. Any suggestion is appreciated. Thanks :)

A: i was tested with Google Maps Embed plugin with PostTabs plugin. You can Insert the map in editor also.This is really works.
Please Check the screenshot for both tabs. :)

Admin Page:

A: Check your CSS if the map shows only one tile or fills in the canvas as a small edge and marker is not centered, when you place it in any other tab than the first.
Easiest solution after hours of searching high and low for a jQuery script to fix this I turned to the css, as none of those scripts worked.
.tab-content>.active {position:relative;left:0;display: block;}
.tab-content>.tab-pane{right:-1000px}

I had to set the tab pane self to position absolute as it dropped about 100 pixels to the bottom, after first changes.
.tab-pane {position: absolute;margin-left:0px;}
and voila no more gray parts - without additional scripting the map sits centered in the content part of the tab. bootstrap.css hides the panels - which does not work for Google maps.
As I use Pronamic Google maps I additionally had to position the .pgm class .
Piece of cake in retrospective.


text:
Q: How to force WebStorm to set public before implemented method? When I implement some public method(TypeScript) WebStorm doesn't set public before this method.
And I get foo() instead of public foo()
Can't find an answer how to force it to do it.

A: Please try enabling Use 'public' modifier in Settings (Preferences for MacOS) | Editor | Code Style | TypeScript > Code Generation


text:
Q: JQuery programming not Working? I made this program to hide and unhide a message on a webpage. It is hidding an unhiding the message but i also inted to chane the text on the button but it's not changing why.

The HTML Code:

<!DOCTYPE html>

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

    <input type="button" value="hide" id="toggle_message" />

You can see this paragraph

The jQuery Code:

$('#toggle_message').click(function() {

    var value = $('#toggle_message').attr('value');
    $('#message').toggle('fast');

    if (value=='Hide') {
        $('#toggle_message').attr('value', 'Show');
    } else if (value=='Show') {
        $('#toggle_message').attr('value', 'Hide');
    }

});

Sorry guys I found the problem the value for the button was not correct

A: $('#toggle_message').click(function() {

var value = $('#toggle_message').attr('value');
$('#message').toggle('fast');

if (this.value=="Hide") this.value = "Show";
else this.value = "Hide";

});

Fiddle
This should work for you. Fiddle can show it working :).


text:
Q: Can't bind to 'ngIf' since it isn't a known property of 'div' after imported BrowserModule Before marking this question as duplicate, I've read all related questions asked before, but my problem is still.

*

*I've 3 custom modules, all have CommonModule imported

*I've imported all my custom modules to app.module.ts

*I've imported BrowserModule in app.module.ts

*As optional, I've imported CommonModule to app.module.ts besides BrowserModule, but nothing changed

*I am using *ngIf, not *ngif

*I've rebuilt the project, restarted the IDE

It is still giving me Can't bind to 'ngIf' since it isn't a known property of 'div'. error.
//app.module.ts
imports: [
    AppRoutingModule,
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    FormsModule,
    SharedModule,
    CustomModule1,
    CustomModule2,
    CustomModule3
]

//custom1.module.ts
@NgModule({
  declarations: [
    HeaderComponent,
    FooterComponent,
    HomeComponent,
    RegisterComponent,
    LoginComponent,
    AboutUsComponent,
    ContactUsComponent
  ],
  imports: [
    CommonModule,
    PublicRoutingModule,
    FormsModule
  ],
  exports: [
    HeaderComponent,
    FooterComponent,
    RegisterComponent
  ]
})

//home.component.html

            <app-register (cancelRegister) = "cancelRegisterMode($event)"></app-register>


text:
Q: SQL Server EXECUTE AS impersonation as RBAC method I wrote a web application that is using AD authentication (Windows) and has it's own authorization module (like RBAC). Backend is SQL Server. A DBA in my team is not happy with us using a service account to talk to the database, he would rather have the actual user impersonated using EXECUTE AS at the database level. He would then use actual SQL roles mapped to lock down the access per user.
To me it sounds like a bad idea as I have to manage 100s of users at the SQL Server level and it just makes the attack surface bigger. What other arguments for or against this setup exist?

A: As a DBA by night, software developer by day, my preference is managing user security in the database (regardless if that's in addition to managing it elsewhere). SQL Server hooks directly into Windows Authentication and therefore supports both Active Directory User and Active Directory Group objects for security.
A lot of times its logical to map a specific AD Group to a specific database, schema, or subset of entities. E.g. you might use schemas to define related entities by application, and then grant read access to a certain AD Group and write access to another AD Group (with the respective SQL permissions) for one schema and visa versa for another schema as a way to separate users' data access across applications.
There's a lot of ways to splice how you can use security in SQL Server and again, coupled with AD Groups (or if AD groups aren't being used, then SQL roles can take their place) it becomes a lot more manageable than keeping track of individual permissions on each user.
Also from a security perspective, by having only one account that can access anything on the SQL Server you put yourself at higher risk because one account has more access than is needed and if became compromised would potentially be more damaging. One account being used in just as many instances as if you were using native Windows Authentication passed through to SQL Server is the same size of attack surface, and in fact even more risky assuming you're storing the dedicated account's password somewhere in the application. Whereas with Windows Authentication passed through to SQL Server, you don't need to store any credentials in the application.
Additional Info (from extended discussion):
Impersonation
Regarding Impersonation in ASP.NET Core, it is possible to still use legacy impersonation per Microsoft's docs (especially for connecting to a database): Configure Windows Authentication in ASP.NET Core (see the Impersonation section at the end)
Doing so is not really recommended for a few reasons, one being legacy security concerns, and another being it may limit your options in how you write your apps and the implementation is cumbersome in itself.
Alternative solutions for Impersonation are:

*

*Disabling "Windows Authentication" and re-enabling "Anonymous Authentication" in IIS, and then scaling out your own login page for authentication so you can get a handle on the user (using modern encryption standards on the password.)

*Implementing Token based authentication.

*Adding the Identity role for Entity Framework Core as seen in this Microsoft example: Create an ASP.NET Core web app with user data protected by authorization
One Dedicated User vs Multiple Users / Groups Database Permissions Security Analogy
Premise: A house that has 200 doors and 1 skeleton key under the mat that opens them all is less secure than 200 different keys which each open only their own subset of door(s) that are kept on the key ring of each user's pocket.
One Dedicated User: The 200 door house has one main door you have to go through first. 200 people each have their own key to get through that door. Once you get through that door, the skeleton key for all 200 other doors in the house is under the mat on the inside of that door.
Individual User / Group Permissions: If you get rid of that skeleton key (individual user) and give all 200 users their own unique key that only opens that front door and specific doors in the house, now you've limited the scope of access each user has to the house and theoretically reduced your attack vector. Basically, all you've done is map each user's key to a limited set of doors.
(You're no longer hiding a skeleton key under the mat.)
Think of Active Directory in the same way. Just because Active Directory stores a mapping of users to groups, doesn't mean there's an additional backdoor in your applications. The point of security threat is where your users actually authenticate which is at the application level. (Mapping permissions in SQL is almost exactly like mapping them in AD, except SQL can leverage the existing Groups in AD.)
Takeaway Point
While permission management can be a pain, it isn't any more complex to do it in the database if you're already doing it at the application level. This assumes the users have some sort of AD (or equivalent) permissions already implemented. If their permissions are already configured in AD then the heavy lifting is already done, it's just in the DBA's hands to map each relevant AD Group or set of Users to correlating SQL permissions, but it's really quite simple to do on the database side.


text:
Q: Where is the full Kubernetes YAML spec? There must be "full-configuration" and example templates of Kubernetes YAML configs somewhere with comments itemizing what parameters do what with runnable examples somewhere.
Does anyone know where something like this might be? Or where the "full API" of the most commonly used Kubernetes components are?

A: There is documentation for every k8s api version available, for example check this link.
The way I found what every key in yaml file represent and what does it mean is via kubectl explain command.
For example:
$kubectl explain deploy.spec

Trick I use while doing CKAD to see full list could be:
$kubectl explain deploy --recursive > deployment_spec.txt

This will list all available options for kubernetes deployment that could you use in yaml file.
To generate some template there is option to use --dry-run and -o yaml in kubectl command, for example to create template for CronJob:
$kubectl run cron_job_name --image=busybox --restart=OnFailure --schedule="*/1 * * * * " --dry-run -o yaml > cron_job_name.yaml


text:
Q: Iterate an array of dictionaries to get highest gpa Homework problem.
I need to iterate through an array of dictionaries to get the highest gpa and print the first and last name of the student. I'm having problems accessing the gpa field of the dictionary entries.
// Task 6
var highestGPA = 0.0
var students : [[String:Any]] =
    [["firstName": "John", "lastName": "Wilson", "gpa": 2.4],
     ["firstName": "Nancy", "lastName": "Smith", "gpa": 3.5],
     ["firstName": "Michael", "lastName": "Liu", "gpa": 3.1]]

for index in students   {
    if let val = (_,_,"gpa":key) {
        highestGPA = val
    }
}

Expected results would be that it iterates through the array of dictionaries and gets the highest gpa.
Actual result is a compilation error "Binary operator '>' cannot be applied to operands of type (,,String) and Double.
So it seems it is getting the string "gpa" rather than the value of gpa
EDIT: I've also tried the following code to get the value in the "gpa" field and cast to a double.
for index in students   {
    myGPA = Double(index["gpa"])
    if myGPA > highestGPA   {
        highestGPA = myGPA
    }
}

I get the compilation error: error: cannot invoke initializer for type 'Double' with an argument list of type '(Any?)'
    myGPA = Double(index["gpa"])

A: You can use the Array function max to determine to student with the highest GPA.
let student = students.max { $0["gpa"] as? Double ?? 0 < $1["gpa"] as? Double ?? 0 }

print(student?["firstName"]) // Nancy
print(student?["gpa"]) // 3.5

A: Because you have marked the values in your Dictionary as Any, when using it you must downcast it as? Double. The below code solves your problem.
var highestGpa = 0.0
var highestPerformingStudent = students[0]
for student in students {
    if let gpa = student["gpa"] as? Double {
        if (gpa > highestGpa) {
            highestGpa = gpa
            highestPerformingStudent = student
        }
    }
}

print(highestPerformingStudent)
// prints ["firstName": "Nancy", "lastName": "Smith", "gpa": 3.5]

A: As @Alexander suggested in the comments, you would be better served to define a struct to hold your student name and gpa data.  Then you will have strongly typed members and not have to cast Any to String and Double.  Structs automatically provide an initializer which takes each of the members.  This prevents you from making a typo when initializing your array of Student data.
Making your struct CustomStringConvertible and implementing var description allows you to format the output of the struct nicely.
You can then use max(by:) to find the Student with the largest gpa by passing a closure which defines how to compare two Student records.
struct Student: CustomStringConvertible {
    var firstName: String
    var lastName: String
    var gpa: Double

    var description: String { return "\(firstName) \(lastName) (\(gpa))" }
}

let students: [Student] = [
    Student(firstName: "John", lastName: "Wilson", gpa: 2.4),
    Student(firstName: "Nancy", lastName: "Smith", gpa: 3.5),
    Student(firstName: "Michael", lastName: "Liu", gpa: 3.1)
]

if let student = students.max(by: { $0.gpa < $1.gpa }) {
    // Print the student information
    print(student)

    // Print the student's name
    print("\(student.firstName) \(student.lastName)")

    // Print the highest gpa
    print(student.gpa)
}

Output:

Nancy Smith (3.5)
Nancy Smith
3.5

Alternate way to initialize Student data:
As @LeoDabus suggested, you can use an array of tuples and map() to initialize your students array like this:
let students = [
    ("John", "Wilson", 2.4),
    ("Nancy", "Smith", 3.5),
    ("Michael", "Liu", 3.1)
].map(Student.init)

This has the advantage of eliminating visual clutter and saving typing at the cost of not explicitly showing which fields are being initialized.


text:
Q: Android add onClick to dynamically created gallery item I am trying to create a gallery that will show a picture fullscreen when you tap on the thumbnail.
I followed sort of a tutorial which nicely created the gallery, but I don't know how to give each image thumbnail an onClick event.
In my gallery page, inside the onCreate, I have this:
public class GalleryPage extends Activity {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery_page);
        ...
        this.imageGrid = (GridView) findViewById(R.id.gallery_container);
        this.bitmapList = new ArrayList<Bitmap>();

        File f = new File(latest_directory);
        File file[] = f.listFiles();
        for (int i=0; i < file.length; i++) {
            this.bitmapList.add(loadImage(latest_directory + "/" + file[i].getName()));
        }
        this.imageGrid.setAdapter(new ImageAdapter(this, this.bitmapList));
    }
}

Then, the ImageAdapter looks like this:
public class ImageAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<Bitmap> bitmapList;

    public ImageAdapter(Context context, ArrayList<Bitmap> bitmapList) {
        this.context = context;
        this.bitmapList = bitmapList;
    }

    public int getCount() {
        return this.bitmapList.size();
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            imageView = new ImageView(this.context);
            imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageBitmap(this.bitmapList.get(position));
        return imageView;
    }
}

I was thinking I could just do:
imageView.setOnClickListener("onImageClick");

and have a method in my gallery page, but this throws an error.
How can I make it so when I click on any of the dynamically created gallery images (imageView), I can get the image location to pull the image and place it in a full size overlay.

A: Set an OnItemClickListener to the GridView.
imageGrid.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {

        //Selected bitmap
        Bitmap bitMap = bitmapList.get(position);

        //Do something with it
    }
});

A: Use setOnItemClickListener.
If you want use your custom interface then follow this :
Create Interface
public interface ItemClickListener {
    void onItemClick(Bitmap t, int position);
}

In your adapter set Listener:
public class ImageAdapter extends BaseAdapter {
/// your code
private ItemClickListener listener;

public void setListener(ItemClickListener listener) {
        this.listener = listener;
    }
// your code
}

In getView method
 public View getView(int position, View convertView, ViewGroup parent) {
        // your code
        Bitmap bitmap =  this.bitmapList.get(position);
        imageView.setImageBitmap(bitmap );
        imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listener != null)
                            listener.onItemClick(bitmap,position);
                    }
                });
        return imageView;
    }

That's it. Now implement this in your Activity.


text:
Q: Need to implementation AWS S3 Bucket file upload using c#. Whereas file size is not limit i have a requirement to upload file in AWS S3 bucket using c#, In which i have list of file to upload one time. My client send me only that for
( S3  : arn:aws:iam::3**********9:user/intl-in-livestreaming-user-prod)
credential.After upload file create URL of that file to seen from anywhere or download it through link.
Help me because i have no any idea about that first time i get that AWS work.

A: In order to upload a file to your bucket in Amazon S3, you would need to import their AWSSDK package from your Nuget manager. Once you have done that, you can use this piece of code to get your file uploaded. Please note that you would require the awsAccessKeyId, awsSecretAccessKey and the region endpoint when you setup your AmazonS3Client object. Once you do that, you would require the name of the bucket you want to upload your file to. Please ensure that the bucket has the required access to accept files from outside source.
using Amazon.S3;
using Amazon;
using Amazon.S3.Transfer;

  using (var client = new AmazonS3Client("awsAccessKeyId",
               "awsSecretAccessKey", RegionEndpoint.{yourregionendpoint}))
    {
      PutObjectRequest objReq = new PutObjectRequest
     {
         Key = "FolderName"+"/"+"ImageOne", //If you create folder inside bucket then you use key otherwise without key also upload data successfully.
         FilePath = "E:\\blah\\imageone.jpg",
         BucketName = "your bucket name",
         CannedACL = S3CannedACL.Private,
     };

        PutObjectResponse response = s3newClient.PutObject(objReq);
        if (response.ETag != null)
           {
            string etag = response.ETag;
            string versionID = response.VersionId;
           }
        }
    }


text:
Q: get user's adress using altitude and coordination points I was wondering if its possible to get a place name, adress or something other than the coordinates of the user when using MKMapView in xcode.
I would like to get something like : Starbucks cafe, 90210 or something like that using the coordinates.
Thanks in advance.

A: That's called reverse geocoding. You'll find plenty of questions about it right here on SO, and there are a number of web services out there that'll do it for you.


text:
Q: cvc-elt.1: Cannot find the declaration of element 'DataModel' What is wrong with my XML?
I am trying to import a metric family into PM, and it gives me the following error:

cvc-elt.1: Cannot find the declaration of element 'DataModel'

<?xml version="1.0" encoding="UTF-8"?>
<!--Auto-generated by the type catalog local manager.-->
<DataModel xmlns="http://im.ca.com/normalizer" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://im.ca.com/normalizer IMDBCertificationFacet.xsd">
  <Author>JMEDRAN</Author>
  <Version>1.0</Version>
  <FacetType name="NormalizedUPSInfoEltek" descriptorClass="com.ca.im.core.datamodel.certs.NormalizedFacetDescriptorImpl">
    <Documentation>Defines the identification information and polled metrics for UPS-Eltek-S</Documentation>
    <FacetOf namespace="http://im.ca.com/core" name="Item" />
</DataModel>

A: To place DataModel into the http://im.ca.com/normalizer namespace, rather than
namespace="http://im.ca.com/normalizer"

use
xmlns="http://im.ca.com/normalizer"

and change
xsi:noNamespaceSchemaLocation="IMDBCertificationFacet.xsd"

to
xsi:schemaLocation="http://im.ca.com/normalizer IMDBCertificationFacet.xsd"

Still having problems?
See these two references for how to specify the location of your XSD:

*

*How to link XML to XSD using schemaLocation or noNamespaceSchemaLocation?

*How to reference a local XML Schema file correctly?
See this reference to understand how XML and XSD namespace-related attributes work together:

*

*xmlns, xmlns:xsi, xsi:schemaLocation, and targetNamespace?

Update after OP added full XML to question
It appears that your XML has a namespace model that's being managed by the XML application, thus the namespace="http://im.ca.com/normalizer" attributes.   Given that, the above advice to use xmlns instead may be misguided.
Your question may actually be more about the particular XML application that uses the XML than it is about XML validation against an XSD.  If you feel that you simply wish to validate the XML against an XSD, please post a MCVE that includes a minimal XML instance and a minimal XSD to receive specific further guidance, or see the general XML validation reference links provided above.


text:
Q: Why the input type Spark UDF is Row for struct column? How is it implemented in Spark? For single column, the input type of UDF is the dataType of this column, while for struct column, the input type is Row, why and how is it implemented?
import org.apache.spark.sql.types._
import org.apache.spark.sql.Row
val sub_schema = StructType(StructField("col1",ArrayType(IntegerType,false),true) :: StructField("col2",StringType,true)::Nil)
val schema = StructType(StructField("subtable", sub_schema,true) :: Nil)
val data = Seq(Row(Row(Array(1,2),"eb")),  Row(Row(Array(3,2,1), "dsf")) )
val rd = sc.parallelize(data)
val df = spark.createDataFrame(rd, schema)
df.printSchema

val u =  udf((x:Row) => x, sub_schema)

root
 |-- subtable: struct (nullable = true)
 |    |-- col1: array (nullable = true)
 |    |    |-- element: integer (containsNull = false)
 |    |-- col2: string (nullable = true)

Spark UDF for StructType / Row


text:
Q: Web app push notification I'm going to make a web app using html5.
The app are going to be able to send a push notification to the phone even if the web app isn't used. Is this possible?

A: This is not possible natively in browsers yet, though W3C standards for browser-based push notifications are finalizing this year.
http://dev.w3.org/html5/eventsource/
The only options are to:

*

*wait for Apple, Google, etc to implement the W3C recommendations in their browsers (if I were to guess, probably late 2012, early 2013)

*have users install a native app that pushes notifications on behalf of your web app (like AlertRocket)

*use SMS text messages through an SMS subscription service

A: Looks like Google Chrome allows for cloud messaging (GCM).
https://developer.chrome.com/apps/cloudMessaging


text:
Q: React Native: Allow device rotation only when webview plays video My current working app is locked in portrait mode through entire screens.
The app plays embedded YouTube videos on webview and I just want to allow the landscape mode only when it plays in full screen.
I see there are some tricks for native ways and I think there aren't compatible with React Native. I also checked react-native-orientation but it doesn't help me.
Is there a simple and clean way I can implement this?

A: I may be a little late to the party but I've recently added what your question is requesting.
Our goal
The application should be fixed to a portrait orientation, unless a User is watching a video. When watching a video, Users should be able to freely switch between portrait and landscape.
Getting Started
I'll outline how I did it in iOS, the React Native part certainly works on Android too.
Enable ALL orientations
You wan't to enable all orientations (Portrait, Upside Down, Landscape Left, Landscape Right).
I've taken the following image from Google, just ensure all checkboxes are ticked.

React Native Package
Download react-native-orientation and inside of your index.ios.js, add the code to lock the device orientation.
For example, mine's inside a componentWillMount.
componentWillMount() {
  Orientation.lockToPortrait();
}

Disable lock when watching a Video via a WebView
I then have a simple VideoPlayer component.
<TouchableWithoutFeedback onPress={this.handleClick}>
  <WebView
    source={{uri: 'https://youtube.com'}}
  />
</TouchableWithoutFeedback>

I used TouchableWithoutFeedback as I don't want the User to know that they've clicked something.
Create a handleClick function:
handleClick = () => {
  Orientation.unlockAllOrientations()
}

The tricky bit, and it's hacky!
I couldn't find a way to tell when the User had finished watching a Video within a WebView. This is because iOS uses its native player.
My VideoPlayer component is within a ScrollView (amongst other components). When the User scrolls (after watching a video), the application will again lock back to a portrait orientation.
<ScrollView
  onScroll={() => { Orientation.lockToPortrait(); }}
/>

Note
This will lock on all devices, including Tablets. If you want to only run it on a phone, I use react-native-device-info to detect whether the device is a tablet or not.
You could wrap all your orientations within an if statement:
if (!DeviceInfo.isTablet()) {
  Orientation.lockToPortrait();
}


text:
Q: Application_Start versus OnInit versus constructor I've gone rounds with this ever since I started programming classic ASP 12 (or so) years ago and I've never found a great solution because the architecture of ASP and ASP.NET has always been a swamp of bad practices, magic shared singletons, etc. My biggest issue is with the HttpApplication object with its non-event events (Application_Start, Application_End, etc.).
If you want to do stuff once for the entire lifespan of an HTTP application, Application_Start is the obvious place to do it. Right? Not exactly. Firstly, this is not an event per se, it's a magic naming convention that, when followed, causes the method to be called once per AppDomain created by IIS.
Besides magic naming conventions being a horrible practice, I've started to think it might be a reason there exist no such thing as a Start event on the HttpApplication object. So I've experimented with events that do exist, such as Init. Well, this isn't really an event either, it's an overridable method, which is the next best thing.
It seems that the Init() method is called for every instantiation of an HttpApplication object, which happens a lot more than once per AppDomain. This means that I might as well just put my startup logic inside the HttpApplication object's constructor.
Now my question is, why shouldn't I put my startup logic in the constructor? Why does even Init() exist and do I need to care about Application_Start? If I do, can anyone explain why there is no proper event or overridable method for this pseudo-event in the HttpApplication object?
And can anyone explain to me why in a typical ASP.NET application, 8 instances of my HttpApplication are created (which causes the constructor and Init to run just as many times, of course; this can be mitigated with locking and a shared static boolean called initialized) when my application only has a single AppDomain?

A: The Asp.Net runtime keeps a pool of HttpApplication objects. Every .aspx request is processed by a single object which is allocated from the pool(8 objects in your case).
The answer to your question, Application_Start event is indeed called, but only for the first instance of the HttpApplication, not subsequent ones, so you can be sure that it is called exactly once whenever your application is started or the application pool of IIS is restarted. So is Application_OnEnd event (last instance)
meanwhile, the Init() and Dispose() are called on every instance of the HttpApplication object. That will be called on each instance a.k.a. each request.
Why do they do it that way..? maybe to balance performance and memory optimizations.
Hope i answered your question.

A: Calling Application_Start the first time an instance of HttpApplication is created, but not on subsequent instances seems a bit of a hack. Perhaps Microsoft didn't want to explain the concept of a static constructor to people who didn't really want to know.
Application_End(), however, seems to be a necessity, as there is no C# equivalent of a static destructor/finalizer. As hacks go, this isn't that bad. It just smells a little funny.

A: There is one HttpApplication object created for each concurrent request. That is each thread that ASP.NET creates gets its own instance of HttpApplication. Instances are re-used for subsequent requests in the same way that threads are re-used from the thread pool.
Use the Init method to initialize instance fields on the HttpApplication as these will only be initialized one the first instance if it is done in the Application_Start event .


text:
Q: Pass Oracle User Defined Type Collection to Stored Procedure Using C# I'm trying to pass an oracle User Defined Type to a stored procedure as an input parameter using C# (Which is a collection), but each time I receive back an InvalidCastException saying "Column contains NULL data".
I have been followed a tutorial which shows the steps needed to achieve this.
https://www.codeproject.com/Articles/1139474/ODP-NET-User-Defined-Type-Implementation
Each time, the code reaches
await command.ExecuteNonQueryAsync();

And then throws the exception
    type ARTICLES_TYP is record(
      article_id number(6),
      article_name varchar(50),
      update_date date
    );

    type ARTICLES_LIST_TYP is table of ARTICLES_TYP;

    PROCEDURE MyProcedure (i_articles_list in ARTICLES_LIST_TYP);

    // A custom class mapping to an Oracle user defined type.
        // Provided all required implementations by ODP.NET developer guide to represent the Oracle UDT as custom type.
        // The custom class must implement IOracleCustomType and INullable interfaces.
        // Note: Any Oracle UDT name must be uppercase.
        public class Article : IOracleCustomType, INullable
        {
            // A private member indicating whether this object is null.
            private bool ObjectIsNull;

            // The OracleObjectMapping attribute is required to map .NET custom type member to Oracle object attribute.
            [OracleObjectMapping("ARTICLE_ID")]
            public int ArticleId { get; set; }
            [OracleObjectMapping("ARTICLE_NAME")]
            public string ArticleName { get; set; }
            [OracleObjectMapping("UPDATE_DATE")]
            public DateTime UpdateDate { get; set; }

            // Implementation of interface IOracleCustomType method FromCustomObject.
            // Set Oracle object attribute values from .NET custom type object.
            public void FromCustomObject(OracleConnection con, object udt)
            {
                OracleUdt.SetValue(con, udt, "ARTICLE_ID", ArticleId);
                OracleUdt.SetValue(con, udt, "ARTICLE_NAME", ArticleName);
                OracleUdt.SetValue(con, udt, "UPDATE_DATE", UpdateDate);
            }

            // Implementation of interface IOracleCustomType method ToCustomObject.
            // Set .NET custom type object members from Oracle object attributes.
            public void ToCustomObject(OracleConnection con, object udt)
            {
                ArticleId = (int)OracleUdt.GetValue(con, udt, "ARTICLE_ID");
                ArticleName = (string)OracleUdt.GetValue(con, udt, "ARTICLE_NAME");
                UpdateDate = (DateTime)OracleUdt.GetValue(con, udt, "UPDATE_DATE");
            }

            // A property of interface INullable. Indicate whether the custom type object is null.
            public bool IsNull
            {
                get { return ObjectIsNull; }
            }

            // Static null property is required to return a null UDT.
            public static Article Null
            {
                get
                {
                    Article obj = new Article();
                    obj.ObjectIsNull = true;
                    return obj;
                }
            }
        }

        // A custom type factory class is required to create an instance of a custom type representing an Oracle object type.
        // The custom type factory class must implement IOralceCustomTypeFactory class.
        // The OracleCustomTypeMapping attribute is required to indicate the Oracle UDT for this factory class.
        [OracleCustomTypeMapping("MYPACKAGE.ARTICLES_TYP")]
        public class ArticleFactory : IOracleCustomTypeFactory
        {
            // Implementation of interface IOracleCustomTypeFactory method CreateObject.
            // Return a new .NET custom type object representing an Oracle UDT object.
            public IOracleCustomType CreateObject()
            {
                return new Article();
            }
        }

// A custom class mapping to an Oracle collection type.
    public class ArticleList : IOracleCustomType, INullable
    {
        // The OracleArrayMapping attribute is required to map .NET class member to Oracle collection type.
        [OracleArrayMapping()]
        public Article[] objArticles;

        // A private member indicating whether this object is null.
        private bool ObjectIsNull;

        // Implementation of interface IOracleCustomType method FromCustomObject.
        // Set Oracle collection value from .NET custom type member with OracleArrayMapping attribute.
        public void FromCustomObject(OracleConnection con, object udt)
        {
            OracleUdt.SetValue(con, udt, 0, objArticles);
        }

        // Implementation of interface IOracleCustomType method ToCustomObject.
        // Set .NET custom type member with OracleArrayMapping attribute from Oracle collection value.
        public void ToCustomObject(OracleConnection con, object udt)
        {
            objArticles = (Article[])OracleUdt.GetValue(con, udt, 0);
        }

        // A property of interface INullable. Indicate whether the custom type object is null.
        public bool IsNull
        {
            get { return ObjectIsNull; }
        }

        // Static null property is required to return a null UDT.
        public static ArticleList Null
        {
            get
            {
                ArticleList obj = new ArticleList();
                obj.ObjectIsNull = true;
                return obj;
            }
        }
    }

    // A custom type factory class is required to crate an instance of a custom type representing an Oracle collection type.
    // The custom type factory class must implement IOralceCustomTypeFactory and IOracleArrayTypeFactory class.
    // The OracleCustomTypeMapping attribute is required to indicate the Oracle UDT for this factory class.
    [OracleCustomTypeMapping("MYPACKAGE.ARTICLES_LIST_TYP")]
    public class ArticleListFactory : IOracleCustomTypeFactory, IOracleArrayTypeFactory
    {
        // Implementation of interface IOracleCustomTypeFactory method CreateObject.
        // Return a new .NET custom type object representing an Oracle UDT collection object.
        public IOracleCustomType CreateObject()
        {
            return new ArticleList();
        }

        // Implementation of interface IOracleArrayTypeFactory method CreateArray to return a new array.
        public Array CreateArray(int numElems)
        {
            return new Article[numElems];
        }

        // Implementation of interface IOracleArrayTypeFactory method CreateStatusArray to return a new OracleUdtStatus array.
        public Array CreateStatusArray(int numElems)
        {
            return null;
        }
    }

Execution Code
OracleParameter p = new();
            p.ParameterName = "i_articles_list";
            p.OracleDbType = OracleDbType.Array;
            p.Direction = ParameterDirection.Input;
            ArticleList al = new ArticleList();
            Article[] articles = new Article[2]
            {
                new Article() { ArticleId = 2, ArticleName = "article two", UpdateDate = DateTime.Today },
                new Article() { ArticleId = 3, ArticleName = "article three", UpdateDate = DateTime.Today }
            };
            al.objArticles = articles;
            p.Value = al;
            p.UdtTypeName = "MYPACKAGE.ARTICLES_LIST_TYP";

            OracleCommand command = connection.CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "MYPACKAGE.MyProcedure";
            command.Parameters.Add(p);

            await command.ExecuteNonQueryAsync();

Does anyone have any idea why It keeps throwing this error?


text:
Q: Aggregate the arrays in MongoDB (2) I have a database structured like this:
 {
                "teams" : [
                    {
                        "best_players" : [
                            {
                                "contact" : {
                                    "name" : "SomeName1"
                                },
                                "characteristic" : {
                                    "skills" : "good"
                                 }
                                },
                                {
                                "contact" : {
                                    "name" : "SomeName2"
                                },
                                "characteristic" : {
                                    "skills" : "good"
                                 }
                                }

                        ],
                        "teamname" : "SomeTeam1"
                    },
                    {
                    "best_players" : [
                        {
                            "contact" : {
                                "name" : "SomeName3"
                            },
                            "characteristic" : {
                                "skills" : "bad"
                             }
                            }
                    ],
                    "teamname" : "SomeTeam2"
                }
                    ]
              }

I need to rename arrays and fields, and see the information in a different form. What i'm expecting with aggregation-framework:
    {
    "team_players" : [
    {
    "player_name" : "SomeName1",
    "player_skills" : "good" ,
    "team_name" : "SomeTeam1"
    },
    {
    "player_name" : "SomeName2",
    "player_skills" : "good" ,
    "team_name" : "SomeTeam1"
    },
    {
    "player_name" : "SomeName3",
    "player_skills" : "bad" ,
    "team_name" : "SomeTeam2"
    }
    ]
    }

What is the right way to query my result with aggregation-framework?

A: This is working fine
     db.are.aggregate([
    { "$unwind": "$teams" },
    { "$unwind": "$teams.best_players" },
    {
        "$group": {
            "_id": null, "team_players": {
                "$push":
                {
                    "player_name": "$teams.best_players.contact.name",
                    "player_skills": "$teams.best_players.characteristic.skills",
                    "team_name": "$teams.teamname"
                }
            }
        }
    }
])

A: You can use $reduce with $concatArrays to transform all the best_players.
Something like
db.colname.aggregate(
{"$project":{
  "team_players":{
    "$reduce":{
      "input":"$teams",
      "initialValue":[],
      "in":{"$concatArrays":[
        "$$value",
         {"$map":{
            "input":"$$this.best_players",
            "as":"bp",
            "in":{
              "player_name":"$$bp.contact.name",
              "player_skills":"$$bp.characteristic.skills",
              "team_name":"$$this.teamname"
           }
        }}
      ]}
    }
  }
}});


text:
Q: Htaccess /username rewrite conflict with existing mapped files I have made a .htaccess file to rewrite /username to /profile.php?=username
this is my htaccess file
Options All -Indexes

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9_-]+)$ /profile.php?username=$1 [QSA,L]

the issue is that the other files in the same level are skipped unless if i added their .php extention which is awful.
Can i prevent /username rewrite if that file exist and also do another rewrite in order to have URL without file extention ?

A: You can keep these 2 rules in the given order:
Options All -Indexes -MultiViews
RewriteEngine On

## To internally rewrite /dir/file to /dir/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

## for user profile
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/?$ profile.php?username=$1 [QSA,L]

It is important to turn off -MultiViews (content negotiation service) of Apache for this.

A:
@MrWhite nothing for now, i just want to stop rewrite when file exist

The rules would work together. If you check that the target .php file exists before rewriting the request (on your extensionless URLs) - as you should be - then you don't need to apply the same filesystem check on your existing rule that rewrites the request to profile.php.
For example:
# Append ".php" if request file without extension and target file exists
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^.]+[^/])$ $1.php [L]

# Rewrite user profiles (directory check is optional)
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?username=$1 [QSA,L]

I'm assuming your URLs do not contain dots (this naturally avoids having to make an exception for requests that end in a file extension). The regex ^([^.]+[^/])$ matches URLs that do not contain a dot and do not end in a slash (ie. directories end in a slash).
Filesystem checks are relatively expensive, so are best kept to a minimum (or avoided altogether if possible). In the rule that appends the ".php" extension, there is no need to check that the request does not map to a directory before checking that the request does map to a file when .php is appended, these checks are mutually inclusive. (But if a directory did exist then the file wouldn't be accessible - catch 22.)
Likewise, there is no need to check that the user-profile URL does not map to a file, unless you also have files that don't have a file extension (very unlikely and best avoided anyway if you do).
Even the directory check on the user-profile URL is debatable. This is only required if you need to be able to access subdirectories off the root directory directly.
With this limited set of rules, it doesn't really matter whether MutliViews is enabled or not. (Although best practice would dictate that MultiViews should be disabled here, to avoid future conflicts.) The effect of having MultiViews enabled will just mean the first rule that appends the .php file extension is bypassed (not required). But having MultiViews enabled essentially enables extensionless URLs on everything.
Consider restructuring your user-profile URLs
HOWEVER, there is a fundamental "problem" with your user-profile URL structure - namely that they do "conflict" with actual file requests. The actual file requests will naturally take priority, but this means that you can't have usernames that happen to match files in the root directory - since the user profile will not be accessible. This check would need to be enforced when creating/updating user accounts.
It would be better to avoid this ambiguity to begin with and allow all usernames (that could also match root files) by creating a "unique" URL. eg. /user/<username>. This also completely avoids having to perform the directory check. For example:
# Rewrite user profiles (directory check is not required)
RewriteRule ^user/([a-zA-Z0-9_-]+)$ profile.php?username=$1 [QSA,L]


text:
Q: Unable to install updates. Unmet dependencies icedtea-7-jre-jamvm and openjdk-7-jre I am a newbie please help. Unable to install updates. Details shows:
The following packages have unmet dependencies:
icedtea-7-jre-jamvm: Depends: openjdk-7-jre-headless (= 7u55-2.4.7-1ubuntu1~0.12.04.2) but 7u51-2.4.4-0ubuntu0.12.04.2 is installed
                     Depends: zlib1g (>= 1:1.1.4) but 1:1.2.3.4.dfsg-3ubuntu4 is installed
openjdk-7-jre: Depends: openjdk-7-jre-headless (= 7u55-2.4.7-1ubuntu1~0.12.04.2) but 7u51-2.4.4-0ubuntu0.12.04.2 is installed
               Depends: libjpeg8 (>= 8c) but 8c-2ubuntu7 is installed
               Depends: libpulse0 (>= 1:0.99.1) but 1:1.1-0ubuntu15.4 is installed
               Depends: libgl1 but it is a virtual package

A: For Sun/Oracle java
Press ctrl+alt+t to open terminal.
Add the webupd8team PPA repository and install Oracle Java 7/8 using the following commands one by one:
To install Oracle Java 7:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

To install Oracle Java8:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

For Openjdk:
Open Ubuntu Software Centre. Search 'Synaptic' and select 'Synaptic package manager'. FYI, Synaptic is the old package manager for Ubuntu and should take care of all dependency problems. After installing synaptic package manager, open it from Unity dash and search for openjdk and select openjdk-7-jre from search result.
BTW, its not clear what you are trying to install.


text:
Q: Adjust position of custom Navigation Back Button I am using a custom image as the back button of my Navigation Controller but the problem is that the image is not aligned correctly with the title and the right button item. I've been trying to move the back button down a few pixels with no success.
extension UINavigationController {

       func addBackButton() {
            let imgBack = UIImage(named: "ic_back")
            navigationBar.backIndicatorImage = imgBack
            navigationBar.backIndicatorTransitionMaskImage = imgBack
            navigationBar.topItem?.backBarButtonItem = UIBarButtonItem(title: "",
                                                                       style: .plain,
                                                                       target: self,
                                                                       action: nil)
        }
}

This is what it looks like now:

As you can see I need to move the back button down a little, any help would be much appreciated.

A: This is my code for a custom back button. I added on viewDidLoad() with the image below. Maybe you need to test with your image how to size it correctly. And you can remove the part with the label.
            let backButtonView = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 44))
            let imageView = UIImageView(image: UIImage(named: "back-arrow"))
            imageView.frame = CGRect(x: -5, y: 11, width: 12, height: 22)
            imageView.image = imageView.image!.withRenderingMode(.alwaysTemplate)
            imageView.tintColor = .blue
            let label = UILabel(frame: CGRect(x: 10, y: 0, width: 40, height: 44))
            label.textColor = .blue
            label.text = "Back"
            backButtonView.addSubview(imageView)
            backButtonView.addSubview(label)
            backButtonView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(backButtonClicked)))
            let barButton = UIBarButtonItem(customView: backButtonView)
            navigationItem.leftBarButtonItem = barButton


text:
Q: Spring batch batch_job_execution_params primary key We are using Spring Batch in our project. In prod Oracle golden gate feature gives the following exception for the batch_job_execution_params table saying :
ORA-26970: table "BATCH_JOB_EXECUTION_PARAMS'" does not contain a primary key constraint

Why does this table not contain a primary key?
I don't think a singular column in this table can be made a primary key however can we have a composite primary key e.g. using the columns JOB_EXECUTION_ID & KEY_NAME? Will that effect the batch jobs in any way?


text:
Q: Question about Lie bracket and cross product Let $\chi(\mathbb{R^3})$ denote the vector space of all smooth vector fields on $\mathbb{R^3}$, and let $A$ be the subspace of $\chi(\mathbb{R^3})$ spanned by $\{X,Y,Z \}$ where
\begin{align*}
X &= y {\partial \over \partial z}-z {\partial \over \partial y},\\
Y &= z {\partial \over \partial x}-x {\partial \over \partial z},\\
Z &= x {\partial \over \partial y}-y {\partial \over \partial x}.
\end{align*}
The question first ask me to compute the Lie brackets $[X,Y]$,$[Y,Z]$ and $[Z,X]$. Which I did and they are,
\begin{align*}
[X,Y] &= y {\partial \over \partial x}-x {\partial \over \partial y},\\
[Y,Z] &= z {\partial \over \partial y}-y {\partial \over \partial z},\\
[Z,X] &= x {\partial \over \partial z}-z {\partial \over \partial x}.
\end{align*}
Then how can I deduce that there is an isomorphism from $\mathbb{R^3}$ to $A$ so that the cross product in $\mathbb{R^3}$ corresponds to the Lie bracket of vector fields.

A: You have just shown that
$$[X,Y]=-Z,\qquad [Y,Z]=-X,\qquad [Z,X]=-Y.$$
Now it remains to compare this with
$$ \mathbf{e}_x\wedge \mathbf{e}_y =\mathbf{e}_z,\qquad
\mathbf{e}_y\wedge \mathbf{e}_z =\mathbf{e}_x,\qquad
\mathbf{e}_z\wedge \mathbf{e}_x =\mathbf{e}_y.$$


text:
Q: Add anchor tags dynamically to a div when page load in Javascript I have 2 divs that all have the same css class, as follows:
/*div 1 */

                                        heading

                                        some text

                                            enter

/*div 2 */

                                        heading

                                        some text

                                            enter

As you can see, both main divs have oxilab-flip-box-col-5 class and each has an ahref tag, now I want all the div components to be linked when the page is loaded, as follows:
/*div 1 */

    .
    .
    .

/*div 2 */

    .
    .
    .

I was able to write this code with JavaScript, but unfortunately, the code I wrote does not work.
var fisrtdiv = document.getElementsByClassName("oxilab-flip-box-col-5");
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://test.com");
aTag.innerText = "some text";
fisrtdiv.appendChild(aTag);

var seconddiv = document.getElementsByClassName("oxilab-flip-box-col-5");
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://example.com");
aTag.innerText = "some text";
seconddiv.appendChild(aTag);

Any idea how I can do this and link each div separately ?

A: getElementsByClassName return an HTMLCollection of elements.
Change your code to:
var fisrtdiv = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://test.com");
aTag.innerText = "some text";
fisrtdiv.appendChild(aTag);

var seconddiv = document.getElementsByClassName("oxilab-flip-box-col-5")[1];
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://example.com");
aTag.innerText = "some text";
seconddiv.appendChild(aTag);

A: Here You Go:
var first_div = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
var parent1 = first_div.parentNode;
var a_tag1 = document.createElement('a');

parent1.replaceChild(a_tag1, first_div)
a_tag1.appendChild(first_div)
a_tag1.setAttribute('href',"http://example.com");

/////////

var second_div = document.getElementsByClassName("oxilab-flip-box-col-5")[1];
var parent2 = second_div.parentNode;
var a_tag2 = document.createElement('a');

parent2.replaceChild(a_tag2, second_div)
a_tag2.appendChild(second_div)
a_tag2.setAttribute('href',"http://example.com");

A: You should try to DRY (Don't Repeat Yourself). You can see that you do 2 times the same thing. What if you need to do it 100 times? Then your code will get messy quickly.
You'll see 2 solutions in my code: the ugly way (not DRY) and the cleaner way (DRY). There's a even cleaner way but let's start with this ;)

    /*THE UGLY WAY*/
   /*
    var fisrtdiv = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
    var first_link = document.createElement('a');
    first_link.setAttribute('href',"http://test.com");
    first_link.innerText = "some text1";
    first_link.append(fisrtdiv);

    document.body.append(first_link);

    //we take again at index 0 because before this line we changed the position of the flip boxes
    var seconddiv = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
    var second_link = document.createElement('a');
    second_link.setAttribute('href',"http://example.com");
    second_link.innerText = "some text2";
    second_link.append(seconddiv);

    document.body.append(second_link);
    */

    /*CLEANER WAY*/
    var
      list_of_flip_boxes = document.querySelectorAll(".oxilab-flip-box-col-5"),
      list_of_links = [
        {
          text : "some text 1",
          href : "http://test.com"
        },
        {
          text : "some text 2",
          href : "http://example.com"
        },
      ];

    list_of_flip_boxes.forEach(function(flip_box, index){
      var
        link_element = document.createElement("a"),
        link_data = list_of_links[index];

      link_element.setAttribute('href', link_data.href);
      link_element.innerText = link_data.text;

      link_element.append(flip_box);

      document.body.append(link_element);
    })
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">

                                        heading

                                        some text

                                            enter

                                        heading

                                        some text

                                            enter


text:
Q: Using npm install as a MS-Windows system account I have a node application running on Windows, which I want to be able to update automatically. When I run npm install -d as the Administrator account - it works fine, but when I try to run it through my automation software (that is running as local system), I get errors when I try to install a private module from a private git repository:
    npm ERR! git clone git@bitbucket.org:team/repository.git fatal: Could not change back to 'C:/Windows/system32/config/systemprofile/AppData/Roaming/npm-cache/_git-remotes/git-bitbucket-org-team-repository-git-06356f5b': No such file or directory
    npm ERR! Error: Command failed: fatal: Could not change back to 'C:/Windows/system32/config/systemprofile/AppData/Roaming/npm-cache/_git-remotes/git-bitbucket-org-team-repository-git-06356f5b': No such file or directory
    npm ERR!
    npm ERR!     at ChildProcess.exithandler (child_process.js:637:15)
    npm ERR!     at ChildProcess.EventEmitter.emit (events.js:98:17)
    npm ERR!     at maybeClose (child_process.js:735:16)
    npm ERR!     at Socket.<anonymous> (child_process.js:948:11)
    npm ERR!     at Socket.EventEmitter.emit (events.js:95:17)
    npm ERR!     at Pipe.close (net.js:451:12)
    npm ERR! If you need help, you may report this log at:
    npm ERR!     <http://github.com/isaacs/npm/issues>
    npm ERR! or email it to:
    npm ERR!     <npm-@googlegroups.com>

    npm ERR! System Windows_NT 6.1.7601
    npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-d"
    npm ERR! cwd D:\nodeapp
    npm ERR! node -v v0.10.8
    npm ERR! npm -v 1.2.23
    npm ERR! code 128

Just running git clone using the same system works fine. Any ideas?
Update: Here are the permissions on the _git_remotes directory:
> get-acl C:\Windows\system32\config\systemprofile\AppData\Roaming\npm-cache\_git-remotes |Format-list

Path   : Microsoft.PowerShell.Core\FileSystem::C:\Windows\system32\config\systemprofile\AppData\Roaming\npm-cache\_git-remotes
Owner  : BUILTIN\Administrators
Group  : NT AUTHORITY\SYSTEM
Access : NT AUTHORITY\SYSTEM Allow  FullControl
         BUILTIN\Administrators Allow  FullControl
Audit  :
Sddl   : O:BAG:SYD:AI(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)

A: Don't run the automation software as local system.  Instead, create a new dedicated service account (admin level if needed).  You can also make it so that this account can only log on from this system and not remotely.  I'd would try running the software as non-admin first.


text:
Q: How can I build a drop down menu with key values from API data array? In REACT, I am fetching data from an API and want to present key field from that in a drop down menu for user to select one of the values. API returns an array and has a key field.
//get data api - Global data
const [globalData, setGlobalData] = useState();
const [dataLoading, setDataLoading] = useState(false);

useEffect(() => { async function fetchGlobalData()
 { setDataLoading(true)
const url = "api.thevirustracker.com/free-api?global=stats";
const apiResponse = await fetch(url)
const dataFromAPI = await apiResponse.json()

...

How can I build a drop down list from one of the key fields of the array.


text:
Q: Malicious Downvotes? Two downvotes within 5 seconds of each other on two separate threads...seems intentional.  What can be done?
How can I reorder a list in python?
python chaining

A: Flag the moderator to check on it.  They're quite helpful.


text:
Q: Openstack Error Unable to establish connection to keystone endpoint I am trying to perform Openstack installation on Ubuntu Server 16.04
I am using following scenario.

Host Machine : Windows 7 ( IP : 192.168.1.15) installed VMWare
application in it.
Guest Machine : Ubuntu Server 16.04 (IP : provided by VMWare DHCP
192.168.30.178)
Network Adapter : NAT ( VMNet8)

successfully installed openstack on it.
later when I want to access openstack dashboard from my host machine http://192.168.30.178/dashboard , I changed network adapter of my virtual machine to bridged , so it changes my virtual machine IP address to
( 192.168.1.52). so now , when i try to connect http://192.168.1.52/dashboard from my host machine, it open user authetication screen . I entered

username as admin and
password as mypassword(set by me in local.conf file)

But it failed with error Unable to establish connection to keystone endpoint. I checked error log file /var/log/apache2/horizon_error.log , it gives following error
ERROR openstack_auth.plugin.base Unable to establish connection to http://192.168.30.178/identity/v3/auth/tokens : HttpConnectionPool( Host='192.168.30.178' ,port='80')

this means that horizon using my old IP address (192.168.30.178).
So please help to change my old IP address with new IP address.How to update that.my new IP address is 192.168.1.52 . I changed my local.conf file with this new IP.
please help me to solve this

A: You need to update Openstack installation or re-install it with the new IP
Otherwise go into every component configuration file and change the IP address in it
for keystone and all other components
change any occurrence of 192.168.30.178 to 192.168.1.53 in all these files:
c:\<openstack configuration directory>\
keystone\keystone.conf
nova\nova.conf
cinder\cinder.conf
glance\glance.conf
neutron\neutron.conf
swift\swift.conf
gnocchi\gnocchi.conf
aodh\aodh.conf
ceilometer\ceilometer.conf
and restart the machine


text:
Q: PyQT5 - Webview load URL - Unbalanced save/restore I try to load a page in a webview widget.
I got information:
QPainter::restore: Unbalanced save/restore
QPainter::end: Painter ended with 2 saved states

so Webview is unable to load some pages correctly

*

*My code load URL

    @pyqtSlot(str)
    def on_even_loadPAY(self, value):
        self.webView.load(QUrl(value))

*

*My web, which I got:

Some pages that is else where opens just fine.
Is there a way to fix this error?


text:
Q: Copying mini website into main website giving configuration error Recently,
I developed one mini site and had to deploy that site in one of our main project.
What I did is, I copied the whole mini project and pasted into the main project. And when I tried running the mini project, I got error as
 *It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.*

Also, the error was generated from  my mini web.config file from the line no : 45. Where the code was
<profile defaultProvider="DefaultProfileProvider">

I don't know what was the error all about. I also tried searching on the net for the issue and I got one link from here but it also didn't helped me out.
Please suggest something which can be of any help. Also let me know know If I have to make some changes.

A: Try using the System.Diagnostics.Process.Start("Link of your website.com");
or please try iframe.

A: The error is very specific as to what the problem is. You need to configure the virtual directory your "mini site" is in as an application in IIS.
Open up Internet Information Services Manager, expand the list of sites until you find your "mini site". Right click on it and choose "Convert to Application". Problem solved.

A: It sounds as though you need to mount the mini site as an application.  What version of IIS are you using?  The following steps for IIS 7 may help:
Creating a Web Application (Virtual Directory) in IIS 7
In case of link-rot, I'll summarise the points as well:

*

*Open IIS Manager

*Right-click on your master site and select "Add Application"

*Fill out the resulting dialogue box.  The alias is the "subfolder" the app will be mounted within, and the physical path is the directory your "mini site" resides in

Hope that helps.

A: Finally after researching so much, I got my answer.
What I need to do is(My mistake)

*

*Converted the Web.Config file of the mini site as Convert to Application.
After that I got error as Excel03ConString already exist. For that, I commented out that line from the mini site.
Next, When I browsed the site I got error as: The Site needs default document as it was giving Membership page which comes by default.
SO I selected the default page and it started working smoothly.


text:
Q: ssh X11forwarding not working , but only on debian8 I recently installed Debian 8 on my workstation , which before ran Ubuntu 15.04 , but after Debian 8 came into my life, I have not succeeded in running ssh with X11forwarding.
case is:
I have a server running Ubuntu 14.04, and when I login to that server from my laptop ( also Ubuntu 14.04 ), I have no problem getting X11forwarding working, but if I try to login from my Debian8 workstation, I will get this error when trying to run xterm (output is from ssh -X serverip )
connect /tmp/.X11-unix/X0: No such file or directory
xterm: Xt error: Can't open display: localhost:12.0

A ls shows that the file exists
$ ls -la /tmp/.X11-unix/X0
srwxrwxrwx 1 root root 0 Aug 18 17:53 /tmp/.X11-unix/X0

In the server's sshd_config i have the following options enabled
X11Forwarding yes
X11UseLocalhost yes ( i have tried both yes and no here )
X11DisplayOffset 12

and in my ssh_config on my Debian8, I have the following lines enabled
Host *
ForwardAgent yes
ForwardX11 yes
ForwardX11Trusted yes

As I see it with a 'ssh -vv -X serverip' all x11 debug message are the same both on my working laptop, and nonworking are the same, and ~/.Xauthority get created on the server when I login
The following environment variables are set when I log into the server from my laptop ( some variables are omitted )
SSH_CLIENT=1.1.1.1 59061 22
SSH_TTY=/dev/pts/1
SSH_AUTH_SOCK=/tmp/ssh-qHuaV5m5QO/agent.32572
LANGUAGE=en_US:en
LOGNAME=xxx
SSH_CONNECTION=1.1.1.1 59061 2.2.2.2 22
DISPLAY=localhost:12.0

the following environment variables are set when I log into the server from my debian8 workstation (some variables are omitted)
SSH_CLIENT=3.3.3.3 59148 22
SSH_TTY=/dev/pts/1
SSH_AUTH_SOCK=/tmp/ssh-fwG6aBA4he/agent.32763
SSH_CONNECTION=3.3.3.3 59148 2.2.2.2 22
DISPLAY=localhost:12.0

All tests are done with ssh -X serverip, and firewall is disabled.
Note: if I login to the server from my laptop via the Debian workstation, X11forwarding works fine


text:
Q: Role of misspecification by biased data in the generalization error I am confused with the role that model misspecification plays in the generalization error, in particular when the misspecification is due to a biased (non representative) training dataset. To clarify what I mean, imagine a non-representative sample where there seems to be a linear pattern when in fact the pattern is more complex in the population. If we base our modeling decisions on that sample we might decide for a linear model and, as a result, misspecify the model. So, some doubts I have:

*

*My understanding is that the bias and variance in the error decomposition are properties of the predictor and not the data. However, the training data causes bias error, which seems to indicate that the data does play a role in the decomposition. Is it that the decomposition assumes that the data is always representative of the population? In other words, it does not take into account biases in the data such as sampling bias or omitted variables.

*The other question I have is that it is not clear that biased data only causes bias error (misspecification) but also variance. My reasoning is that if we had chosen another training sample (one without the biases), our predictor would have made better predictions, indicating that there is variance error, too.
I think my misunderstanding is on the assumptions of the learning paradigm: for instance, that biases in the data are out of the picture when talking about variance and bias of the model, but I would like to confirm it and shed some light on these questions.

A: Bias in a model can be due to many factors. From what I understand, you maybe talking about sampling bias. It Happens when the training data doesn't accurately represent the environment the program is expected to run into.
It is not possible to train a model on the entire universe of data, rather data is assumed to be sampled from the population. There is science behind sampling the training data that is both large enough and representative enough to mitigate sample bias and must come from the same population density. In your case, the data seems to be from different population densities which contradicts the assumption of machine learning theory i.e training data should be sampled from the same population. and hence will never generalise.
The machine learning theory is based on the assumption that there exists a true function g(x) (which we don't need to know) and our goal is to come up with a hypothesis f(x) which approximates g(x) on the sampled dataset. Bias and variance in error decomposition both are dependent on your choice of hypothesis f(x) and the true function g(x) of the population.

*

*Bias occurs when your hypothesis is far from the true function. Even if you have representative data and not using the right hypothesis, you will have high bias. For ex: if you are using linear hypothesis to model a non-linear function.

*Variance occurs when you have large pool of hypothesis(high model complexity) which makes it difficult to navigate to the true function resulting in higher variance. For ex: using a polynomial regression to model a linear relationship.
For a deeper understanding check out: https://www.youtube.com/watch?v=L_0efNkdGMc
This is one of the best resource for machine learning theory.


text:
Q: Color profiles conversion I have a project on color profile conversion in C++, where the idea is to use CIELAB as transition between RGB and all others (CMY; CMYK; HSV; HSL;...).But I have one big big problem. I have searched everywhere and I cannot find any formula or descrition how could I convert CIELAB to others(CMY; CMYK; HSV; HSL; ...) only I got is what I found here : http://www.easyrgb.com/index.php?X=MATH&H=14#text14 . Can someone please help me with formula or with an idea how to get to them? Thank you so so much.
Regards,
magic :)

A: Color conversion with mathematical formulas yields very poor results with no serious application. Color systems are far too complex to capture them in simple, closed mathematical formulas let alone in linear formulas.
Good results can only be achived by using color profile files. And the conversion basically invovles interpolation between samples stored in these files.
Have a look at Little CMS. It probably does everything you need. Or if your software will run on Windows, you can use the built-in Windows Color System to do the conversion.


text:
Q: Can't create HyperlinkedRelatedField in Django Rest Framework I'm struggling to get HyperlinkedRelated fields working, and I can't figure out where I'm going wrong. No matter what I do, I get an error like:

Could not resolve URL for hyperlinked relationship using view name "court-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.

I feel that I've tried everything and I don't know where my error could be, nor how to identify it. My reading of this error message is that I am looking for a URL that corresponds to the court-detail view, but that that view doesn't exist.
Some piece of magic isn't working and any help would be greatly appreciated.
URLs:
from cl.api import views

from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'courts', views.CourtViewSet)
router.register(r'dockets', views.DocketViewSet)

router.register(r'clusters', views.OpinionClusterViewSet)
router.register(r'opinions', views.OpinionViewSet)
router.register(r'cited-by', views.OpinionsCitedViewSet)

urlpatterns = [
    # url(r'^api/rest/(?P<version>[v3]+)/', include(router.urls)),
    url(r'^api-auth/',
        include('rest_framework.urls', namespace='rest_framework')),
    url(r'^', include(router.urls)),
]

Views:
class DocketViewSet(viewsets.ModelViewSet):
    queryset = Docket.objects.all()
    serializer_class = serializers.DocketSerializer

class CourtViewSet(viewsets.ModelViewSet):
    queryset = Court.objects.all()
    serializer_class = serializers.CourtSerializer

class OpinionClusterViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.
    """
    queryset = OpinionCluster.objects.all()
    serializer_class = serializers.OpinionClusterSerializer

class OpinionViewSet(viewsets.ModelViewSet):
    queryset = Opinion.objects.all()
    serializer_class = serializers.OpinionSerializer

class OpinionsCitedViewSet(viewsets.ModelViewSet):
    queryset = OpinionsCited.objects.all()
    serializer_class = serializers.OpinionsCitedSerializer

Serializers:
from cl.audio import models as audio_models
from cl.search import models as search_models

from rest_framework import serializers

class DocketSerializer(serializers.HyperlinkedModelSerializer):
    court = serializers.HyperlinkedRelatedField(
        many=False,
        view_name='court-detail',
        read_only=True
    )

    class Meta:
        model = search_models.Docket
        fields = ('date_created', 'date_modified', 'date_argued',
                  'date_reargued', 'date_reargument_denied', 'court')

class CourtSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = search_models.Court

class AudioSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = audio_models.Audio

class OpinionClusterSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = search_models.OpinionCluster
        fields = ('judges', 'per_curiam', )

class OpinionSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = search_models.Opinion
        fields = ('pk',)

class OpinionsCitedSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = search_models.OpinionsCited

When I go to:
http://127.0.0.1:8000/dockets/
It tells gives me the error message above. Of course, if I remove the court reference from the serialization, it works fine...

A: I imagine this can be caused by a number of things, but in my case, I figured out that it was caused by having DEFAULT_VERSIONING_CLASS set without having it configured in the urls.py:
REST_FRAMEWORK = {
    # Use URL-based versioning
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning',
    'DEFAULT_VERSION': 'v3',
    'ALLOWED_VERSIONS': {'v3'},
}

The solution, therefore, was either to disable it in the settings, or to set up a url in in urls.py that accepted the version parameter:
url(r'^api/rest/(?P<version>[v3]+)/', include(router.urls)),

Ugh. Took a long time to realize I had this setting in place. Bad error message.


text:
Q: Prove that |-a| = |a| I'm struggling to understand the basic proof for the following theorem:
$\lvert -a\rvert = \lvert a \rvert$
The provided solution goes on to describe the following:
$(i)$ For $a \ge 0 $, since $-a \le 0$
        $\lvert -a \rvert = -(-a)=a, \lvert a \rvert = a$
My question: Why does $\lvert -a \rvert = -(-a)$ hold true?

A: The definition of $|a|$ is:
$|a| := \begin{cases} a \quad a \geq 0\\ -a \quad a\leq0 \end{cases}$
So, suppose $a \geq 0$
Then, $|a| = a$
$|-a| = -(-a) = a$. Therefore, $|-a| = |a|$
Now, suppose $a \leq 0$
Then, $|a| = -a$
$|-a| = -a$
Hence, $|a| = |-a|$
So, for all $a \in \mathbb{R}$, we find:
$$|a| = |-a|$$

A: The definition of $|\cdot|$ is:
$$|x| := \begin{cases}x & x \ge 0\\-x & x<0\end{cases}$$
So, for $a \ge 0$, since $-a\le 0$, we have $|-a| = -(-a)$, by the definition of $|\cdot|$.

A: Provided we are working the a subring $A$, of the reals (i.e. $\mathbb{Z, Q, R}$), then the absolute value function is defined for $a \in A$ as:
\begin{equation}
    |a|=
    \begin{cases}
      -a, & \text{if}\ a<0\\
      0, & \text{if}\ a=0 \\
      a, & \text{if}\ a>0
    \end{cases}
  \end{equation}
So to answer your question, in the case $a \geq 0$, $|-a|=-(-a)$ comes straight from the definition, as $-a \leq 0$ (obviously noting $0=-0$).

A: Let's take -a≥0 then |-a|=-a ........(1)
        0<a then |a |=a  ........(2)

by (1) and (2) |-a|=|a |
Let's take -a<0 then |-a|=-(-a)=a .........(3)
        0≤a then |a |=a ...............(4)

by (3) and (4) |-a|=|a |
conclusion= |-a|=|a |
NOTE:The absolute value function always gives the positive value of some number.That is why the negative number -a gives the positive number -(-a) as the absolute value.


text:
Q: Insert missing rows (with zero values) into table, following a display pattern I'm creating a procedure that loops through the following table to create a report:
INSERT INTO temp_data
SELECT val_year, val_name, Group_A, Group_B, Group_C, SUM(product_count) AS in_stock
FROM all_products
GROUP BY val_year, val_name, Group_A, Group_B, Group_C;

Resulting rows:
1: 2014, product_a, food, hot, delicious, 50
2: 2014, product_a, food, hot, fast, 30
3: 2014, product_a, food, cold, delicious, 10
4: 2014, product_a, drinks, hot, delicious, 20
5: 2014, product_a, drinks, cold, delicious, 40
6: 2014, product_a, drinks, cold, fast, 60

7: 2014, product_b, food, hot, delicious, 70
... etc.

The table all_products has been previously created through various UNION ALL queries etc.
I need to report these results to my superiors now, but the table looks like it has "missing" values. I need to rebuild that table so that it shows missing groups with a zero value.
I need to display all the values in a certain pattern, this example would be my desired display:
Rows:
1: 2014, product_a, food, hot, delicious, 50
2: 2014, product_a, food, hot, fast, 30
3: 2014, product_a, food, cold, delicious, 10
4: 2014, product_a, food, cold, fast, 0
5: 2014, product_a, drinks, hot, delicious, 20
6: 2014, product_a, drinks, hot, fast, 0
7: 2014, product_a, drinks, cold, delicious, 40
8: 2014, product_a, drinks, cold, fast, 60

9: 2014, product_b, food, hot, delicious, 70
... etc.

Notice row 4 and 6 have been filled to display zero values for products that are not in stock.
Is there any easy (quick) way to fill the missing rows? All I could think of was a huge 200+ lines long FOR LOOP that goes through current groups, checks for group changes and appends missing groups on group change. That approach felt kind of unprofessional.

A: You can do this by generating all the rows first (using a cross join) and then bringing in the values:
select y.val_year, g.val_name, g.Group_A, g.Group_B, g.Group_C,
       coalesce(in_stock, 0) as in_stock
from (select distinct val_year from temp_data) y cross join
     (select distinct val_name, Group_A, Group_B, Group_C from temp_data) g left join
     temp_data d
     on d.val_year = y.val_year and
        d.val_name = g.val_name and
        d.Group_A = g.Group_A and
        d.Group_B = g.Group_B and
        d.Group_C = g.Group_C;

You could also do this directly on all_products.  For instance, you could add the CTE to the above query:
with temp_data as (
      SELECT val_year, val_name, Group_A, Group_B, Group_C, SUM(product_count) AS in_stock
      FROM all_products
      GROUP BY val_year, val_name, Group_A, Group_B, Group_C
     )