text:
Q: How data is stored in cassandra composite key Column Family I am facing some peculiar problem in DSE 3.2.4,
here is my table structure,
CREATE TABLE tbl_samp (
  PK text,
  CK1 varint,
  CK2 text,
  CK3 varint,
  value float,
  PRIMARY KEY (PK, CK1, CK2, CK3)
) WITH
  bloom_filter_fp_chance=0.010000 AND
  caching='KEYS_ONLY' AND
  comment='' AND
  dclocal_read_repair_chance=0.000000 AND
  gc_grace_seconds=864000 AND
  read_repair_chance=0.100000 AND
  replicate_on_write='true' AND
  populate_io_cache_on_flush='false' AND
  compaction={'class': 'SizeTieredCompactionStrategy'} AND
  compression={'sstable_compression': 'SnappyCompressor'};

I am dumping huge amount of data from pig to cassandra using CqlStorage();
I have around 1.12 million distinct combinations of (PK, CK1, CK2, CK3)
so when I finished running PIG
here is my Pig Relation
reqDataCQL = foreach reqData generate TOTUPLE(TOTUPLE('PK',PK), TOTUPLE('CK1',CK1), TOTUPLE('Ck2',CK2), TOTUPLE('CK3',Ck3)), TOTUPLE(value);

store reqDataCQL into 'cql://MyKeyspace/tbl_samp?output_query=update+MyKeyspace.tbl_samp+set+value+%3D+%3F' using CqlStorage();

I can see following
Input(s):
Successfully read 34327 records from: "/user/k/Input.txt"
Successfully read 4 records from: "cql://MyKeySpace/mappingtable"

Output(s):
Successfully stored 1128902 records in: "cql://MyKeySpace/tbl_samp?output_query=update+conflux.to1+set+value+%3D+%3F"

But when I Query the table tbl_samp I can see only 8600 records which are combination of (PK and CK1)
here is my count query
    select count(1) from tbl_samp limit 2000000;

 count
-------
  8681

Is there any gap in my understanding of Composite Key?
I know PK is my RowKey
and (CK1,CK2,CK3) combinations with Value will be my column name
My understanding in Cassandra Composite is
PK,(CK1|CK2|CK3|value:1),(CK11|CK22|CK33|value:11)
PK1,(CK111|CK222|CK333|value:111)

please help me on this

A: For your primary key PK, CK1, CK2, CK3:
The partition key is PK. It decides which partition the row goes into. Inside a parition, each unique combination of CK1, CK2 and CK3 define the column. So, all keys in the primary key make up a unique referemce. If you insert multiple entries with the same PK, CK1, CK2 and CK3, the last write wins.
What's your CQL query? What's the replication factor of the keyspace? What consistency level are you specifying for the reads and write? It could be that your read and write consistenty (RC and WC) are low, so you're reading from replicas that haven't been written to.

A: Sorry its my fault
my understanding of Composite Key was correct.
I have one UDF where I am overwriting this combination of (PK,CK1,CK2,CK3)
Soo in general cassandra stores based on Partition Key and combination of partition key and clustering columns gives each row.
and column names will be unique combination of Clustering columns.
PK,(CK1|CK2|CK3|value:1),(CK11|CK22|CK33|value:11)
PK1,(CK111|CK222|CK333|value:111)

thanks


text:
Q: Binding image path to Button Background in Windows Phone 7 I am trying to bind the image to button from ViewModel. But i can not bind to button. But if i bind this same value to imagebox mean it showing the image.
 <ListBox Tap="listBox1_Tap" Height="444" ItemsSource="{Binding StudentDetails,Mode=TwoWay}" HorizontalAlignment="Left" Margin="2,34,0,0" Name="listBox1" VerticalAlignment="Top" Width="476" BorderBrush="#00410D0D">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                            <StackPanel Orientation="Horizontal">

                                <Image Height="50" Source="{Binding addImage}" HorizontalAlignment="Left"  Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="50" />

                                <Button Height="80" Width="80" DataContext="{Binding DataContext, ElementName=listBox1}" Command="{Binding addPerson}">
                                    <Button.Background>
                                        <ImageBrush ImageSource="{Binding addImage}" Stretch="Fill" />
                                    </Button.Background>
                                </Button>

                            </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

A: I assume that you have set image's build action to Resource, which is default value. And your string value must be like that:
string addImage =  "/Application;component/Images/image_name.png";

I all the above is OK, then the problem must be in your Button. You have set it's DataContext to ListBox1 DataContext. Why? There is no need.
Change
<Button Height="80" Width="80" DataContext="{Binding DataContext, ElementName=listBox1}" Command="{Binding addPerson}">
    <Button.Background>
        <ImageBrush ImageSource="{Binding addImage}" Stretch="Fill" />
    </Button.Background>
</Button>

to
<Button Height="80" Width="80" Command="{Binding addPerson}">
    <Button.Background>
        <ImageBrush ImageSource="{Binding addImage}" Stretch="Fill" />
    </Button.Background>
</Button>

A: You should use a converter to bind the image.
Here is a sample I worked on. Its works fine for me. The interface definition:
<DataTemplate x:Name="lstbxCreateEventTypesTiles">
    <Button x:Name="btn1" Content="{Binding Name}" CommandParameter="{Binding ID}" Click="Button_Click"
    Style="{StaticResource ButtonStyle}" HorizontalContentAlignment="Left" BorderThickness="0" FontSize="42.67" FontFamily="Segoe WP SemiLight" Foreground="White" BorderBrush="{x:Null}">
        <Button.Background>
            <ImageBrush ImageSource="{Binding MasterTypeID, Converter={StaticResource ImageConverter}}" Stretch="None"/>
        </Button.Background>
    </Button>
</DataTemplate>

The class source:
public class ImageConverter : IValueConverter
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        ImageSource img = null;
        try {
            if (value != null) {

                switch (value.ToString()) {
                    case "1":
                        value = "Assets/tile_bg.png";
                        break;
                    case "2":
                        value = "Assets/tile2_bg.png";
                        break;

                    default:
                        break;
                }

                BitmapImage image = new BitmapImage();
                image.SetSource(Application.GetResourceStream(new Uri(@value.ToString(), UriKind.Relative)).Stream);
                img = image;

            }
        } catch (Exception ex) {

        }
        return img;

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        throw new NotImplementedException();
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: php always gives the same respone my php script always gives the same respone. i'm trying to make a login Formular for Android.
maybe some one of you know why:
<?php
$con=mysqli_connect("localhost","root","","my_db");
//echo "Welcome, I am connecting Android to PHP, MySQL";

if (mysqli_connect_errno($con))
{
   //echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$username = $_POST['username'];
$password = $_POST['password'];

$result = mysqli_query($con,"SELECT Username FROM user where     Username='$username' and Password='$password'");

$flag['code'] =0;

if($result)
{
    $flag['code']=1;

} else {

    $flag['code'] = 0;

}

print(json_encode($flag));
//echo json_encode($flag)

mysqli_close($con);
?>

it always Prints Code:1
i hope some one know why this happens.

A: You do not check the result. You are just checking if it is non null. By the way you should handle a connection problem too.
I would modify your check to:
if(mysqli_num_rows($result) == 1) {
    $flag['code'] = 1;
} else {
    $flag['code'] = 0;
}

This will check if you got one result which means that you got a working login.
Please keep in mind to hash your passwords. Even within development you should keep passwords save.


text:
Q: Can I use any library or Scipy in Python for 4 or n dimensional interpolation? I've searched a lot on the internet but haven't found an exact method. If someone can point me to a library that can do this, that would be great.
I want to find a 4-dimensional cubic spline function such that f(A, B) = C,D.
Thanks in advance!

A: There is a function called CubicSpline in scipy.interpolate.


text:
Q: D3 charts - how to develop Map to filter ZIP code using dc.js and crossfilter I'm developing a d3 charts dashboard using dc.js charts and crossfilter. We have to implement a map feature that shows U.S map and a user can see States and Zip code. User can zoom in to a map, select a ZIP code, that will filter the rest of the charts. We're trying to use this:
http://dc-js.github.io/dc.js/vc/index.html
Is it possible to use ZIP code (using longitude and latitude) instead of just states?
We also find
http://chelm.github.io/esri-d3/css-sample.html
which have a zoom feature but only states. Though I looked at the code and it turns out the states are created using coordinates to draw the line for hover.
Is it possible to have a ZIP code implement to that map using longitude and latitude? I'm sorry I'm very new when working on the D3 map charts. I'm trying to research a possible solutions for our dashboard.
Thank you.

A: I did this in a React app using the GoogleMaps API and the npm packages "points-cluster" and "google-map-react". I got zip code lat/long data from this github gist. I won't go into any more detail here because both npm packages have pretty good documentation. I got this up and running in under two days. Hope that gets you started!


text:
Q: AngularJS + Jasmine: Comparing objects I'm just starting out writing tests for my AngularJS app and am doing so in Jasmine.
Here are the relevant code snippets
ClientController:
'use strict';

adminConsoleApp.controller('ClientController',
    function ClientController($scope, Client) {

        //Get list of clients
        $scope.clients = Client.query(function () {
            //preselect first client in array
            $scope.selected.client = $scope.clients[0];
        });

        //necessary for data-binding so that it is accessible in child scopes.
        $scope.selected = {};

        //Current page
        $scope.currentPage = 'start.html';

        //For Client nav bar
        $scope.clientNavItems = [
            {destination: 'features.html', title: 'Features'},
        ];

        //Set current page
        $scope.setCurrent = function (title, destination) {
            if (destination !== '') {
                $scope.currentPage = destination;
            }

        };

        //Return path to current page
        $scope.getCurrent = function () {
            return 'partials/clients/' + $scope.currentPage;
        };

        //For nav bar highlighting of active page
        $scope.isActive = function (destination) {
            return $scope.currentPage === destination ? true : false;
        };

        //Reset current page on client change
        $scope.clientChange = function () {
            $scope.currentPage = 'start.html';
        };
    });

ClientControllerSpec:
'use strict';

var RESPONSE = [
    {
        "id": 10,
        "name": "Client Plus",
        "ref": "client-plus"
    },
    {
        "id": 13,
        "name": "Client Minus",
        "ref": "client-minus"
    },
    {
        "id": 23805,
        "name": "Shaun QA",
        "ref": "saqa"
    }
];

describe('ClientController', function() {

    var scope;

    beforeEach(inject(function($controller, $httpBackend, $rootScope) {
        scope = $rootScope;
        $httpBackend.whenGET('http://localhost:3001/clients').respond(RESPONSE);
        $controller('ClientController', {$scope: scope});
        $httpBackend.flush();
    }));

    it('should preselect first client in array', function() {
        //this fails.
        expect(scope.selected.client).toEqual(RESPONSE[0]);
    });

    it('should set current page to start.html', function() {
        expect(scope.currentPage).toEqual('start.html');
    });
});

The test fails:
Chrome 25.0 (Mac) ClientController should preselect first client in array FAILED
    Expected { id : 10, name : 'Client Plus', ref : 'client-plus' } to equal { id : 10, name : 'Client Plus', ref : 'client-plus' }.
    Error: Expected { id : 10, name : 'Client Plus', ref : 'client-plus' } to equal { id : 10, name : 'Client Plus', ref : 'client-plus' }.
        at null.<anonymous> (/Users/shaun/sandbox/zong-admin-console-app/test/unit/controllers/ClientControllerSpec.js:43:39)

Does anyone have any ideas on why this might be happening?
Also .. as I'm new to writing AngularJS tests, any comments on whether I'm setting up my test wrong or whether it can be improved will be welcome.
Update:
Including ClientService:
'use strict';

AdminConsoleApp.services.factory('Client', function ($resource) {
    //API is set up such that if clientId is passed in, will retrieve client by clientId, else retrieve all.
    return $resource('http://localhost:port/clients/:clientId', {port: ':3001', clientId: '@clientId'}, {

    });
});

Also, I got around the problem by comparing ids instead:
it('should preselect first client in array', function () {
    expect(scope.selected.client.id).toEqual(RESPONSE[0].id);
});

A: I just had a similar problem and implemented a custom matcher as follows, based on many approaches:
beforeEach(function() {
  this.addMatchers({
    toBeSimilarTo: function(expected) {
      function buildObject(object) {
        var built = {};
        for (var name in object) {
          if (object.hasOwnProperty(name)) {
            built[name] = object[name];
          }
        }
        return built;
      }

      var actualObject = buildObject(this.actual);
      var expectedObject = buildObject(expected);
      var notText = this.isNot ? " not" : "";

      this.message = function () {
        return "Expected " + actualObject + notText + " to be similar to " + expectedObject;
      }

      return jasmine.getEnv().equals_(actualObject, expectedObject);

    }
  });
});

and then used this way:
it("gets the right data", function() {
  expect(scope.jobs[0]).toBeSimilarTo(myJob);
});

Of course, it's a very simple matcher and doesn't support many cases, but I didn't need anything more complex than that. You can wrap the matchers in a config file.
Check this answer for a similar implementation.

A: toEqual makes a deep equality comparison. Which means that when all the properties of the objects' values are equal, the objects are considered to be equal.
As you said, you are using resource which adds a couple of properties to the objects in the array.
So this {id:12} becomes this {id:12, $then: function, $resolved: true} which are not equal. Id checking should be fine if you are just testing if you set the values properly.

A: Short answer:
The existing answers all recommend either stringifying your objects, or creating a custom matcher/comparison function. But, there is an easier way: use angular.equals() in your Jasmine expect call, instead of using Jasmine's built-in toEqual matcher.
angular.equals() will ignore the additional properties added to your objects by Angular, whereas toEqual will fail the comparison for, say, $promise being on one of the objects.

Longer explanation:
I ran across this same problem in my AngularJS application. Let's set the scenario:
In my test, I created a local object and a local array, and expected them as responses to two GET requests. Afterwards, I compared the result of the GET's with the original object and array. I tested this using four different methods, and only one gave proper results.
Here's a portion of foobar-controller-spec.js:
var myFooObject = {id: 1, name: "Steve"};
var myBarsArray = [{id: 1, color: "blue"}, {id: 2, color: "green"}, {id: 3, color: "red"}];

...

beforeEach(function () {
    httpBackend.expectGET('/foos/1').respond(myFooObject);
    httpBackend.expectGET('/bars').respond(myBarsArray);

    httpBackend.flush();
});

it('should put foo on the scope', function () {
    expect(scope.foo).toEqual(myFooObject);
    //Fails with the error: "Expected { id : 1, name : 'Steve', $promise : { then : Function, catch : Function, finally : Function }, $resolved : true } to equal { id : 1, name : 'Steve' }."
    //Notice that the first object has extra properties...

    expect(scope.foo.toString()).toEqual(myFooObject.toString());
    //Passes, but invalid (see below)

    expect(JSON.stringify(scope.foo)).toEqual(JSON.stringify(myFooObject));
    //Fails with the error: "Expected '{"id":1,"name":"Steve","$promise":{},"$resolved":true}' to equal '{"id":1,"name":"Steve"}'."

    expect(angular.equals(scope.foo, myFooObject)).toBe(true);
    //Works as expected
});

it('should put bars on the scope', function () {
    expect(scope.bars).toEqual(myBarsArray);
    //Fails with the error: "Expected [ { id : 1, color : 'blue' }, { id : 2, color : 'green' }, { id : 3, color : 'red' } ] to equal [ { id : 1, color : 'blue' }, { id : 2, color : 'green' }, { id : 3, color : 'red' } ]."
    //Notice, however, that both arrays seem identical, which was the OP's problem as well.

    expect(scope.bars.toString()).toEqual(myBarsArray.toString());
    //Passes, but invalid (see below)

    expect(JSON.stringify(scope.bars)).toEqual(JSON.stringify(myBarsArray));
    //Works as expected

    expect(angular.equals(scope.bars, myBarsArray)).toBe(true);
    //Works as expected
});

For reference, here's the output from console.log using JSON.stringify() and .toString():
LOG: '***** myFooObject *****'
LOG: 'Stringified:{"id":1,"name":"Steve"}'
LOG: 'ToStringed:[object Object]'

LOG: '***** scope.foo *****'
LOG: 'Stringified:{"id":1,"name":"Steve","$promise":{},"$resolved":true}'
LOG: 'ToStringed:[object Object]'

LOG: '***** myBarsArray *****'
LOG: 'Stringified:[{"id":1,"color":"blue"},{"id":2,"color":"green"},{"id":3,"color":"red"}]'
LOG: 'ToStringed:[object Object],[object Object],[object Object]'

LOG: '***** scope.bars *****'
LOG: 'Stringified:[{"id":1,"color":"blue"},{"id":2,"color":"green"},{"id":3,"color":"red"}]'
LOG: 'ToStringed:[object Object],[object Object],[object Object]'

Notice how the stringified object has extra properties, and how toString yields invalid data which will give a false positive.
From looking at the above, here's a summary of the different methods:

*

*expect(scope.foobar).toEqual(foobar) : This fails both ways. When comparing objects, toString reveals that Angular has added extra properties. When comparing arrays, the contents seem identical, but this method still claims they are different.

*expect(scope.foo.toString()).toEqual(myFooObject.toString()) : This passes both ways. However, this is a false positive, since the objects are not being translated fully. The only assertion this makes is that the two arguments have the same number of objects.

*expect(JSON.stringify(scope.foo)).toEqual(JSON.stringify(myFooObject)) : This method gives the proper response when comparing arrays, but the object comparison has a similar fault to the raw comparison.

*expect(angular.equals(scope.foo, myFooObject)).toBe(true) : This is the correct way to make the assertion. By letting Angular do the comparison, it knows to ignore any properties which were added in the backend, and gives the proper result.

If it matters to anyone, I'm using AngularJS 1.2.14 and Karma 0.10.10, and testing on PhantomJS 1.9.7.

A: I had the same problem so I just called JSON.stringify() on the objects to be compared.
expect( JSON.stringify( $scope.angularResource ) == JSON.stringify( expectedValue )).toBe( true );

A: Long story short: add angular.equals as a jasmine matcher.
beforeEach(function(){
  this.addMatchers({
    toEqualData: function(expected) {
      return angular.equals(this.actual, expected);
    }
  });
});

So, then you can use it as follows:
it('should preselect first client in array', function() {
    //this passes:
    expect(scope.selected.client).toEqualData(RESPONSE[0]);

    //this fails:
    expect(scope.selected.client).toEqual(RESPONSE[0]);
});

A: A little bit verbose, but produces helpful message when expectation fails:
expect(JSON.parse(angular.toJson(resource))).toEqual({ id: 1 });

Explanation:
angular.toJson will strip the resource of all angular specific properties like $promise
JSON.parse will convert JSON string back to normal Object (or Array), which can now be compared to another Object (or Array).


text:
Q: Pass a varaible to a javascript src='xxx' external include My problem is that I have a number of external javascript code blocks in various directories and I need to be able to change the name of each directory as the code is included. I have been looking at this for a while and I am not even sure it can be done.
Example:
script type="text/javascript" src="http://www.wanowandthen.com/"+galleryName+"/getalbumpics.php?id=gallery1"; /script

What I want to do is pass a directory name to the variable galleryName so that one HTML file can access a variety of different directories and show the pictures in them.
A copy of the .JS file exists in each directory and all I need is to be able to tell the .JS include statement which directory to use.

A: You should append this to the script that creates the galleryName variable:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.wanowandthen.com/" + galleryName + "getalbumpics.php?id=gallery1";
document.body.appendChild(script);

EDIT: This should be the code you need:
<form>
  <select onchange="myFunction()" name="galleryName" id="galleryName">
    <option value="abandoned-western-australia" Selected>Abandoned WA</option>
    <option value="Albany-gallery" Selected>Albany</option>
  </select>
</form>

function myFunction() {
    var galleryName = document.getElementById("galleryName").value;
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://www.wanowandthen.com/" + galleryName + "getalbumpics.php?id=gallery1";
    document.body.appendChild(script);
    console.log(galleryName);
}


text:
Q: Change the colour of a particle I'm working in 1.14 and I have this particle command: /particle minecraft:effect ~-10 ~ ~ 1 0 1 1 50which is the particle effect for potions, the swirling bubbles.  The problem with this is that the effect will always be white.  I'd like to change the colour of this paricle, similar to what you can do with the dust particle, where you use RBG codes to change the colour.  But whenever I try to define these parameters for the effects particle, I am getting an error.  Is there a way I can change the colour of the effect particle specifically?

A: You can use this command to make red particles:
/particle entity_effect ~ ~ ~10 1 0 0 1 0 normal @a

The syntax is
/particle entity_effect <location> <red> <green> <blue> <changes saturation in some way> 0 <normal|forced> <viewers>


text:
Q: Trying to Set a Shortcut to a Directory Im trying to run several different scripts on my Mac for data stored in different paths. So I put all said scripts into a folder. In order for a script to work, I have to be cd'd to a specific folder required for said script. I use the scripts to get different types of output (ex: Image volumes, MRI info, etc..).
I was wondering if there was a way to store all my scripts in one directory and assign a shortcut to it. That way, I can cd to my folder, and only type something like $ScriptsFolder/Script_1 to have it. Ive seen this done in the FSL software package, where typing $FSLDIR/data/standard would give you the items in that folder.
UPDATE:
Im using Script=/Users/ray/Documents/Script which works until I close down my terminal to start a new one. Any way to make the setup permanent?

A: EDITED
Found this helpful in the end.
http://www.techradar.com/how-to/computing/apple/terminal-101-creating-aliases-for-commands-1305638
I used it to create a shortcut to my scripts which are all placed in a folder for easy referencing.


text:
Q: MongoDB исключение поля из запроса на обновление документа Возможно ли во время запроса на обновление с помощью какого-то оператора "проигнорировать/удалить из запроса" определённое поле объекта, которое мы передаём в запросе, не трогая при этом сам объект ?
То есть, условно у нас есть вот такой запрос:
{ "$set": { "_id": "...", "name": "...", "description": "..." } }

Необходимо проигнорировать/избавиться от _id в запросе, не трогая при этом сам объект
(объект { "_id": "...", "name": "...", "description": "..." } должен остаться в первоначальном виде)
Я знаю, что для массива это можно реализовать с помощью операторов $pop или $pull, а вот как подобное реализовать для объекта ?
Главное условие - в запросе должен передаваться объект


text:
Q: adding array in NSDictionary and ordering it i have three array like below
names                      birthdate                remanning

"Abhi Shah",                 "01/14",                  300
"Akash Parikh",              "12/09/1989",             264
"Anand Kapadiya",            "12/01",                  256
"Annabella Faith Perez",     "03/02",                  347
"Aysu Can",                  "04/14/1992",             25
"Chirag Pandya"              "10/07/1987"              201

plz it will be great help if you give me code for how to add this three array in NSDictionary and then after ordering(ascending) whole dictionary in accordance to "remaning" array
Note in Dic everything should get changed. not only remaning array.  names and birthdate should get changed in same way remaning days are getting changed
thank you so much in advance

A: I would advise you to change the design of your project and  create a model for same as having properties :
@interface YourModel : NSObject
    @property (strong) NSString *name;
    @property (strong) NDDate *birthDate;
    @property NSInteger remaining;
@end

And then create an NSMutableArray in your class, and go on to add them.
This will make your work easier, as searching, sorting, filtering , than handling 3 parallel arrays.

A: If you use the design proposed by Anoop, the sorting code using blocks would be something similar to this:
NSArray *sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSInteger first = [(YourModel*)a remaining];
    NSInteger second = [(YourModel*)b remaining];
    return [first compare:second];
}];

A: You have to take each record (names, birthdate, remanning ) in the dictionary or any structure. And array of that dictionary should be created. To sort the array as per your requirement any sorting mechanism can be used.
-(void)sort
{
    //This is the array of dictionaries, where each dictionary holds a record
    NSMutableArray * array;
    //allocate the memory to the mutable array and add the records to the arrat

    // I have used simple bubble sort you can use any other algorithm that suites you
    //bubble sort
    //
    for(int i = 0; i < [array count]; i++)
    {
        for(int j = i+1; j < [array count]; j++)
        {
            NSDictionary *recordOne = [array objectAtIndex:i];
            NSDictionary *recordTwo = [array objectAtIndex:j];

            if([[recordOne valueForKey:@"remaining"] integerValue] > [[recordTwo valueForKey:@"remaining"] integerValue])
            {
                [array xchangeObjectAtIndex:i withObjectAtIndex:j];
            }
        }
    }

    //Here you get the sorted array
}

Hope this helps.


text:
Q: Conversion of SSL certificate from .pfx to .key What is the use of -nodes in the command to convert .pfx to .pem?
Can I use
openssl pkcs12 -in keyStore.pfx -out keyStore.key -nodes

A: Per the OpenSSL documentation :
-nodes : don't encrypt the private keys at all.
Yes, you can use this command but what are you trying to do ? From the title, I'm understanding that you want to convert a certificate from pfx to pem format, is that right ?


text:
Q: Hiding Bootstrap Popover on Click Outside Popover I'm trying to hide the Bootstrap Popover when the user clicks anywhere outside the popover. (I'm really not sure why the creators of Bootstrap decided not to provide this functionality.)
I found the following code on the web but I really don't understand it.
// Hide popover on click anywhere on the document except itself
$(document).click(function(e) {
    // Check for click on the popup itself
    $('.popover').click(function() {
        return false; // Do nothing
    });
    // Clicking on document other than popup then hide the popup
    $('.pop').popover('hide');
});

The main thing I find confusing is the line $('.popover').click(function() { return false; });. Doesn't this line add an event handler for the click event? How does that prevent the call to popover('hide') that follows from hiding the popover?
And has anyone seen a better technique?
Note: I know variations of this question has been asked here before, but the answers to those questions involve code more complex than the code above. So my question is really about the code above

A: I made http://jsfiddle.net/BcczZ/2/, which hopefully answers your question
Example HTML

    Popover
    Bad button

JS
var $popover = $('[data-toggle=popover]').popover();

//first event handler for bad button
$('.bad').click(function () {
    alert("clicked");
});

$(document).on("click", function (e) {
    var $target = $(e.target),
    var isPopover = $target.is('[data-toggle=popover]'),
        inPopover = $target.closest('.popover').length > 0

    //Does nothing, only prints on console and wastes memory. BAD CODE, REMOVE IT
    $('.bad').click(function () {
        console.log('clicked');
        return false;
    });

    //hide only if clicked on button or inside popover
    if (!isPopover && !inPopover) $popover.popover('hide');
});

As I mentioned in my comment, event handlers don't get overwritten, they just stack. Since there is already an event handler on the .bad button, it will be fired, along with any other event handler
Open your console in the jsfiddle, press 5 times somewhere on the page (not the popover button) and then click bad button you should see clicked printed the same amount of times you pressed
Hope it helps

P.S:
If you think about it, you already saw this happening, especially in jQuery.
Think of all the $(document).ready(...) that exist in a page using multiple jquery plugins. That line just registers an event handler on the document's ready event

A: I just did a more event based solution.
var $toggle = $('.your-popover-button');
$toggle.popover();

var hidePopover = function() {
    $toggle.popover('hide');
};

$toggle.on('shown', function () {
    var $popover = $toggle.next();
    $popover.on('mousedown', function(e) {
        e.stopPropagation();
    });
    $toggle.on('mousedown', function(e) {
        e.stopPropagation();
    });
    $(document).on('mousedown',hidePopover);
});

$toggle.on('hidden', function () {
    $(document).off('mousedown', hidePopover);
});

A: short answer
insert this to bootstrap min.js
when popout onblur will hide popover
when popout more than one, older popover will be hide
$count=0;$(document).click(function(evt){if($count==0){$count++;}else{$('[data-toggle="popover"]').popover('hide');$count=0;}});$('[data-toggle="popover"]').popover();$('[data-toggle="popover"]').on('click', function(e){$('[data-toggle="popover"]').not(this).popover('hide');$count=0;});

A: None of the above solutions worked 100% for me because I had to click twice on another, or the same, popover to open it again. I have written the solution from scratch to be simple and effective.
   $('[data-toggle="popover"]').popover({
        html:true,
        trigger: "manual",
        animation: false
    });

    $(document).on('click','body',function(e){
        $('[data-toggle="popover"]').each(function () {
            $(this).popover('hide');
        });

        if (e.target.hasAttribute('data-toggle') && e.target.getAttribute('data-toggle') === 'popover') {
            e.preventDefault();
            $(e.target).popover('show');
        }
        else if (e.target.parentElement.hasAttribute('data-toggle') && e.target.parentElement.getAttribute('data-toggle') === 'popover') {
            e.preventDefault();
            $(e.target.parentElement).popover('show');
        }
    });

A: My solution, works 100%, for Bootstrap v3
$('html').on('click', function(e) {
    if(typeof $(e.target).data('original-title') !== 'undefined'){
         $('[data-original-title]').not(e.target).popover('hide');
    }

    if($(e.target).parents().is('[data-original-title]')){
         $('[data-original-title]').not($(e.target).closest('[data-original-title]')).popover('hide');
    }

    if (typeof $(e.target).data('original-title') == 'undefined' &&
!$(e.target).parents().is('.popover.in') && !$(e.target).parents().is('[data-original-title]')) {
        $('[data-original-title]').popover('hide');
    }
});


text:
Q: Bind JNDI datasource in tomcat? Is it possible to bind programatically a DataSource to Tomcat's 6 JNDI?
I want to create a DataSource on the fly and then make it available through JNDI ( to ColdFusion for instance ).
This is what I have:
public void bindToConext(DataSource dataSource) throws NamingException, SQLException {
    Context initContext = new InitialContext();
    Context envContext  = (Context)initContext.lookup("java:/comp/env");
    envContext.bind("jdbc/mydatasource", dataSource);
}

But I'm getting this exception:
javax.naming.OperationNotSupportedException: Context is read only

Is there a work around?

A: Well it was not possible because tomcat's context becomes read-only after startup.
So what we did was to use SimpleJNDI which is a in memory context ( more like a glorified HashMap ) and that worked for us.
It needs a jndi.properties file that has to be in the classpath and where you define the directory where to look for resources and the initial context factory
java.naming.factory.initial=org.osjava.sj.SimpleContextFactory
org.osjava.sj.root=some/relative/path
org.osjava.jndi.delimiter=/
org.osjava.sj.jndi.shared=true

To make the binding with ColdFusion first we create the data source programatically and then bind it to the context:
DataSource ds = ...
Context c = new InitialContext();
c.bind( "jdbc/my/blah/"+var , ds );
...

Then using CF admin api we create a CF datasource of type JNDI just using the jndiname

A: Tomcat's working context is java:comp/env. This context is read-only. But you can create your own contexts, using Tomcat's JNDI Implementation, as long as you keep yourself out of "java:comp/env".
Context ctx = new InitialContext()
ctx.createSubcontext("any_name").createSubcontext("any_sub_name");
ctx.bind("any_name/any_sub_name/myDataSource", myDataSource);

By default Tomcat's contexts are shared, so the DataSource is retrievable from anywhere in your app this way:
Context ctx = new InitialContext()
DataSource ds = (DataSource)ctx.lookup("any_name/any_sub_name/myDataSource");


text:
Q: "Expected associated type, found `u32`" when using the lifetime of a parameter as trait parameter in where bound I tried to compile this code (Playground):
trait Family<'a> {
    type Out;
}

struct U32Family;
impl<'a> Family<'a> for U32Family {
    type Out = u32;
}

trait Iterator {
    type Item;
    fn next<'s>(&'s mut self) -> <Self::Item as Family<'s>>::Out
    where
        Self::Item: Family<'s>;
}

struct Foo;
impl Iterator for Foo {
    type Item = U32Family;

    fn next<'s>(&'s mut self) -> <Self::Item as Family<'s>>::Out
    where
        Self::Item: Family<'s>,
    {
        0u32  // <-- in real code, this is somehow calculated
    }
}

But sadly, it results in this error:
error[E0308]: mismatched types
  --> src/main.rs:28:9
   |
24 |     fn next<'s>(&'s mut self) -> <Self::Item as Family<'s>>::Out
   |                                  ------------------------------- expected `<U32Family as Family<'s>>::Out` because of return type
...
28 |         0u32
   |         ^^^^ expected associated type, found u32
   |
   = note: expected type `<U32Family as Family<'s>>::Out`
              found type `u32`

I really don't understand why. Obviously, in this code snippet, <U32Family as Family<'s>>::Out is exactly u32. But Rust seems to think that it's not always the same. Why? And how can I make it compile?
Some notes:

*

*There are a bunch of similar situations where a similar error occurs, but I think this is different from everything I've seen so far.

*I cannot use type Out: for<'a> Family<'a>;. So that's not a workaround that works for me.

*If I remove the lifetime parameter of Family, everything works.

*If I replace Family<'s> with Family<'static> in the function signature, everything works.

EDIT: I can work around this problem by adding:
impl U32Family {
    fn from<'a>(v: u32) -> <Self as Family<'a>>::Out {
        v
    }
}

Then I can just say Self::Item::from(0u32) in the body of next(). (Playground)
I think it's clear why the error in next() is gone: U32Family::from always takes u32 as argument. Hardcoded. Never changing. The bigger question about this workaround is: why does the from() method compile fine? So in from() the compiler somehow knows that <Self as Family<'a>>::Out is always u32, but if I try the same in next(), somehow the compiler doesn't understand that <Self::Item as Family<'s>>::Out is u32. Now I'm even more confused.
EDIT2: first, I suspected that specialization is the problem. For example, you might write:
impl Family<'static> for U32Family {
    type Out = char;
}

Then of course, the compiler would be right in assuming that u32 is not always the same as <Self::Item as Family<'s>>::Out for any 's. However, I think this is not the problem.
First of all, impls that can be specialized need to be marked with the default keyword. I did not do that, so I should be able to assume the associated type is in fact u32 (the RFC talks about something very similar). But additionally, specialization based on lifetimes is not allowed.
So by now I tend to think this is a compiler error. But I'd love to get another answer!

A: I think the problem is that it is a "coincidence" that <Self::Item as Family<'s>>::Out is u32 for all 's. The compiler can prove it for any 's you want, but it can't even express the concept that it is true for all 's.
The work-around you have found is the right approach: add a method to U32Family which converts a u32 into a <Self as Family<'a>>::Out. The body of the method is entirely inside the scope of 'a, so the compiler can prove that the conversion is type-correct for that 'a, and therefore that the method is type-correct. Then, at the call-site, you're telling the compiler to use its knowledge about the method.

A: struct U32Family;
...
impl Iterator for Foo {
type Item = U32Family;

So next() must return Option<U32Family>, whose only possible values are None and Some(U32Family{})
You probably want Item = <U32Family as Family<'static>::Out which fixes this issue but creates some lifetime issues. (The Item needs a lifetime because Family has one, but you only accept a lifetime on next())


text:
Q: Restricting the file extension saved when using tkFileDialog.asksaveasfile I am currently writing a GUI in python using Tkinter where the user is able to save the state of the GUI in their directory with the extension ".espace".
filename = tkFileDialog.asksaveasfilename(defaultextension=".espace")
If the user specifies a different file extension then the file is saved with the extension that they specified. Is there anyway to prevent this? So that they are completely restricted to saving the file with the extension ".espace"?

A: Hi I know I'm 7 years late but you could force your extension my doing a simple if command after the dialog box, just add this simple line:
filename = filename if ".space" in filename else filename + ".space"

Basically checks if the default extension was used, if not it will add it to the end.If user types another extension it will be invalidated.

A: In order for the solution of @IsraelJ to apply to different extensions and be resistant to upper / lower case letters, I suggest:
fileext = ".space"
filename = filename if filename[-len(fileext):].lower() == fileext else filename + fileext

A: You can specify file type by using the 'filetypes' option. The below example will change the file type drop down on the save dialog to .espace and all files.
filename = tkFileDialog.asksaveasfilename(defaultextension=".espace", filetypes=(("espace file", "*.espace"),("All Files", "*.*") ))

I have not found an option, using asksaveasfilename, to restrict use of other file extensions. I'd think you could write a loop that would force the user to use that extension:
import os
import sys
ext = ""
while ext != ".escape":
   filename = tkFileDialog.asksaveasfilename(defaultextension=".espace", filetypes=(("espace file", "*.espace"),("All Files", "*.*") ))
   file,ext = os.path.splitext(filename)


text:
Q: Finding order of a point on eliptic curve Just started studying eliptic curves and am having trouble with this question. An explanation/solution would be much appreciated.
Find the order of the point X on the elliptic curve $E/Q$ for the two cases:
$X = (0,16)$ on $y^2 = x^3 + 256$
$X = (0.5,0.5)$ on $y^2 = x^3 + 0.25x$

A: I will describe the group law for an elliptic curve in short form, ie $E: y^2=x^3+Ax+B$ for some $A$, $B$.
The group law on the elliptic curve can be defined geometrically, if $P$, $Q$ are distinct points, then draw the straight line between the two points. This line will intersect the curve with multiplicity $3$ so let $R$ be the third point. Finally if $R=(x,y)$, then reflect in the $x$-axis and take $P+Q=(x,-y)$ and this defines an abelian group. Note here that $R=(x,y)$ is the inverse of $P+Q$, i.e. $(P+Q)+R=O$, where $O$ acts as the identity and is the point at infinity.
There are a couple of exceptions to this:
$1)$ If $P=Q$, then we take the tangent line to the curve instead to find $R$.
$2)$ If either $P=O$ (respectively $Q=O$), we set $P+Q=Q$ (respectively $P$).
$3)$ If $P=(x,y)$ and $Q=(x,-y)$, then the line is vertical and we set $R=P+Q=O$.
Using this we note that if $P \in E$ has the form $P=(x,0)$ then by point $3)$, $P=-P$, ie $2P=P+P=O$.
Now let's calculate the order of your points.
Let $E: y^2=x^3+256$, $X=(0,16)$.
We obtain the derivative of the curve which is $2y \dfrac{dy}{dx} = 3x^2$ so at $X$, we have $\dfrac{dy}{dx}=0$ so the tangent line has gradient $0$. Further the tangent passes through $X$ so the equation is $y=16$. Substituting this back into our original equation, we get $16^2=x^3-256$ so $x^3=0$.
The only solutions to this is $x=0$, so our point $R$ is again $X=(0,16)$. Hence $2X=X+X=(0,-16)$ by above. Now notice that $X=-2X$ so in particular $3X=O$ and since $X \neq O$, the order of $X$ must be $3$.
Now your second curve is $E: y^2=x^3+x/4$ with $X=(1/2,1/2)$. Again the derivative of $E$ is $2y \dfrac{dy}{dx} = 3x^2+1/4$ so the gradient at $X$ is $1$ and so the equation of the tangent is $y-1/2=x-1/2$, ie $y=x$.
Putting this back into $E$, we get $x^2=x^3+x/4 = x(x-1/2)^2$. Since $X$ has $x$ coordinate $1/2$, $R$ must have $x$ coordinate $0$. Putting this back into our equation for the tangent line $y=x$ we get $R=(0,0)$ and hence $2X=X+X=(0,0)$.
Now we again apply point $3)$, since the $y$-coordinate is $O$ to find that $4X=O$ so $X$ has order at most $4$. However, by our calculations $2X \neq 0$ so it cannot have order $2$ and hence the order equals $4$.


text:
Q: how to read ellipses data in java or using selenium How to read data which ends with the ellipses(...) in java and selenium.
I have tried with the option as gettext().split(",")[0]. Each time the data length gets differently some times data will display with "," or some time data will display "Name..." in this situation it is difficult to get to know where the comma "," ends. When hover the mouse on the text will get display the full data on the tooltip. Please help how to handle it.


text:
Q: Button not centering after moving it to bottom of div I'm trying to create a form where the submit is always at the bottom and in the center.
I'm centering by using text-align: center in the parent div and moving it to the bottom with position: absolute and bottom: 20px, but it seems that after I do that it moves slightly off center - why is this case and how do I remedy this?
HTML:

  <form>

      <input name='group 1' type='radio' id='1' />
      option 1

      <input name='group 1' type='radio' id='2' />
      option 2

      <input name='group 2' type='radio' id='3' />
      option 1

      <input name='group 1' type='radio' id='4' />
      option 1

    <button type='submit'>
      Submit
    </button>
  </form>

CSS:
.container {
  width: 400px;
  height: 400px;
  border: 2px solid red;
  text-align: center;
}

button {
  position: absolute;
  bottom: 20px;
}

Demo: https://jsfiddle.net/f9ktLn9o/3/

A: Where you've pulled it out of the stack using position: absolute; it'll now be centered to the left of the button. If you translate it 50% of the width of the button to the left, it should fix the issue.
transform: translateX(-50%);

https://jsfiddle.net/f9ktLn9o/4/

A: Taking a look at Computed styles you will see left and right position values defined in the box model.
You'll need to unset these values with your own, with a few other adjustments, you will achieve the intended behaviour.
Updated JSFiddle
Code Snippet Demonstration:

.container {
  width: 400px;
  height: 400px;
  border: 2px solid red;
  text-align: center;
  /* Additional */
  position: relative; /* position absolute child relative to parent */
}

button {
  position: absolute;
  bottom: 20px;
  /* Additional */
  left: 0;
  right: 0;
  display: block;
  margin: auto;
  width: 100px;
}

  <form>

      <input name='group 1' type='radio' id='1' />
      option 1

      <input name='group 1' type='radio' id='2' />
      option 2

      <input name='group 2' type='radio' id='3' />
      option 1

      <input name='group 1' type='radio' id='4' />
      option 1

<button type='submit'>
      Submit
    </button>
  </form>

A: Try this instead of your css:
button {
  position: relative;
  margin-top: 40%;
}

It work for chrome, Firefox, Edge and IE (just tested these)
By using position: absolute;, the button is fixed in the page, but not fixed in the div.
Always try  to use percentage and not pixel if you can (responsive design is way beter for end users)


text:
Q: Force per unit area on conducting sheet in magnetic field Question from I.E. Irodov (3.260)

I'm having trouble with the (c) part because the external magnetic field should be towards the right to give such a result,hence the force on unit area should be downwards,I'm also unable to find the magnitude in (c) part.Any help would be appreciated.

A: The case c) as depicted (assuming field lines are in the plane of the paper) implies two things:

*

*the current flows perpendicularly into the plane of the paper;

*the total field magnitude has left-to-right component on both sides, but field is weaker on the right-hand side.
This situation will occur if the external field has non-zero horizontal component $\mathbf B_{h}$ (left-to-right) and vertical component $\mathbf B_v$(bottom-to-top).
The horizontal component will contribute with force directed downwards (according to formula $\mathbf F = \int \mathbf j\times\mathbf B\,dV$). The vertical component will contribute with force directed to the right.
It is not clear why the solution in Irodov claims there is only force to the right. Perhaps it would be true if the plate was infinite and with zero ohmic resistance; then the sum of Lorentz forces acting on the current-forming mobile charge carriers would not translate into ponderomotive force on the plate, but would accelerate only the mobile charge carriers themselves (and change the current in the plate).


text:
Q: (More) nested dictionary comprehensions: How to switch inner values to keys? Very similar to this previous question but not quite they same. In that example, the question is essentially how to perform some function on the values of the 'inner' dictionary - but the keys of both outer and inner dicts stay the same. I want the values of the inner dict to become they keys of the new dict, and the have new values based on the old keys.
I have a 'nested' dictionary like this:
data = {
    "A":{"X":1, "Y":2, "Z":3},
    "B":{"X":4, "Y":5, "Z":6},
    "C":{"X":7, "Y":8, "Z":9},
}

I want to create a new dictionary with the values of the inner dictionaries (i.e. the numbers) as the new keys, with new values based on concatenating the keys of the outer and inner dictionaries:
new_data = {
    1:"AX",
    2:"AY",
    3:"AZ",
    4:"BX",
    5:"BY",
    6:"BZ",
    7:"CX",
    8:"CY",
    9:"CZ",
}

Based on the linked post, I tried
data = {inner_v: outer_k + inner_k for inner_k, inner_v in outer_v.items() for outer_k, outer_v in outer_dict.items()}

But I get an error saying outer_v is not defined

A: When writing nested for loops in a comprehension, the nesting is happening left-to-right (and not viceversa).
Therefore, you just need to swap the order of the loops in the comprehension, with the understanding that outer_dict is actually data.
data = {
    "A":{"X":1, "Y":2, "Z":3},
    "B":{"X":4, "Y":5, "Z":6},
    "C":{"X":7, "Y":8, "Z":9},
}

outer_dict = data
new_data = {inner_v: outer_k + inner_k for outer_k, outer_v in outer_dict.items() for inner_k, inner_v in outer_v.items()}
print(new_data)
# {1: 'AX', 2: 'AY', 3: 'AZ', 4: 'BX', 5: 'BY', 6: 'BZ', 7: 'CX', 8: 'CY', 9: 'CZ'}


text:
Q: Error trying to diff '[object Object]'. Only arrays and iterables are allowed - Angular API Get Request from .Net I'm a on learning stage, and a little bit of a noob, sorry if this is a stupid question. I'm working on a Movie DB project, with movies from live API, Favorite list, JWT auth, etc. I'm now on the end part, have everything done so far, and have one problem. Every person who click's on see details about movie, the movie will be sent on my DB. And with this user can save movie to his favorite table (.net Crud operations). Everything work but when I want to get movies from a table that's between movies table and users table (favorite table many to many relation) I get a error in my swagger everything is working, and I can get every movie that's in favorite, but in angular I user *ngFor, and the error say that it must return a array, but I'm getting a Object, every other get request works only this one doesn't. Here is my code and error:

You can see I get everything I want in console, but UI is Error
Component .ts and HTML:
//HTML

 {{fav.Title}}

.Ts
export class FavoriteListComponent implements OnInit {

  constructor(public service: MovieService) { }
  requests: any = [];

  ngOnInit(): void {
    this.getFav();
  }

  getFav(){
    this.service.getFavorite1().subscribe(
      res => {
      this.requests = res;
      console.log(res)
    });
  }
}

MovieService
getFavorite1(){
  return this.http.get('http://localhost:5002/api/Favorite/getUsersFavorite').pipe(map(res => res));
  }

And this is my get request in .Net 5
        [Authorize]
        [HttpGet("getUsersFavorite")]
        public async Task<IActionResult> GetUsersFavoriteMovies()
        {
            string userId = User.Claims.First(a => a.Type == "UserID").Value;
            var user = await _context.DbUsers.Where(n => n.Id == Int32.Parse(userId)).Select(movies => new FavoriteView()

            {
                ImdbId = movies.Favorites.Select(n => n.ImdbId).ToList(),
                Title = movies.Favorites.Select(n => n.Movies.Title).ToList(),
                Poster = movies.Favorites.Select(n => n.Movies.Poster).ToList()

            }).FirstOrDefaultAsync();

            return Ok(user);
        }

I tried a lot of thing, the closest I get is this, and when I change in .net request the .FirstOrDefaultAsync() to .ToListAsync(). When I it to ToListAsync I get this:

In this case I don't get any error but nothing is showing in UI
I know the question is big, but I'm desperate, I'm stuck on this a few day's, and every help is great. Thank you!!!

A: Use this way, it will work.
<ng-container *ngIf="requests">

{{ requests.title[i] }}

</ng-container>

Example:
https://stackblitz.com/edit/angular-ivy-f251ko?file=src%2Fapp%2Fapp.component.html


text:
Q: Extract the list of all extras from an Intent in Xamarin.Android and save it in a dictionary I want to list all extras (and their values) of an Intent object and save them in a dictionary.
The first problem is I don't necessary know all the keys.
The second problem is that some values are strings, some are boolean... and so on.
How could I get the values in a loop (looping through the keys) and save the value in C# Xamarin.Android?

A: You could make this a convenient extension method as well:
public static Dictionary<string, string> ToDictionary(this Bundle bundle)
{
    var dictionary = new Dictionary<string, string>();
    foreach (var key in bundle.KeySet())
    {
      dictionary.Add(key, b.Get(key).ToString());
    }
    return dictionary;
}

A: Here what I found after a while and I'm going to share it so that someone else can save time.
//Didactic version
Bundle b = myIntent.Extras; //Where myIntent is of course an Intent
ICollection<string> c = b.KeySet(); //This is the collection of extras
Dictionary<string, string> d = new Dictionary<string, string>();

foreach (var key in c)
{
  Object value = b.Get(key);
  d.Add(key, value.ToString());
}

//Short version
var b = myIntent.Extras;
var d = new Dictionary<string, string>();

foreach (var key in b.KeySet();)
{
  d.Add(key, b.Get(key).ToString());
}

A: LINQ variant
Bundle bundle = intent.Extras;
Dictionary<string, object> dict = bundle.KeySet()
    .ToDictionary<string, string, object>(key => key, key => bundle.Get(key));


text:
Q: Codeigniter caching issue when dealing with query string parameters Greetings,
I'm writing a CI web application which implements the standard file caching functionality as such:
$this->output->cache(n);

I'm using a combination of segments and query string parameters, and appear to be experiencing an issue as a result. What I'm seeing in my use cases and in the Output class code is that the caching is solely segment based. As such, http://www.example.com/segment/?q=foo and http://www.example.com/segment/?q=bar are treated as identical requests.
Does anyone have any insight or recommendations regarding how the url_helper, Output class, or CI base class can be edited such that the above example treats example.com/segment/?q=foo and example.com/segment/?q=bar as separate, unique requests and stores the responses in separate files individually?

A: Due to this is very old answer and the website that was linked to does not exist anymore (new link). I'll copy the code to here for old version of Codeigniter.
This is an answer since Codeigniter 2.
Create MY_Output.php file in application/core and use the code below.
<?php

/**
 * @author vee
 */

class MY_Output extends CI_Output
{

    public function __construct()
    {
        parent::__construct();
    }// __construct

    /**
     * Update/serve a cached file
     *
     * @access    public
     * @return    void
     */
    public function _display_cache(&$CFG, &$URI)
    {
        $cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path');

        // Build the file path.  The file name is an MD5 hash of the full URI
        $uri = $CFG->item('base_url').
                $CFG->item('index_page').
                $URI->uri_string;
        // buld query strings
        $querystrings = $_SERVER['QUERY_STRING'];
        if ( $querystrings != null ) {$querystrings = "?".$querystrings;}
        $uri = $uri.$querystrings;

        $filepath = $cache_path.md5($uri);

        if ( ! @file_exists($filepath))
        {
            return FALSE;
        }

        if ( ! $fp = @fopen($filepath, FOPEN_READ))
        {
            return FALSE;
        }

        flock($fp, LOCK_SH);

        $cache = '';
        if (filesize($filepath) > 0)
        {
            $cache = fread($fp, filesize($filepath));
        }

        flock($fp, LOCK_UN);
        fclose($fp);

        // Strip out the embedded timestamp
        if ( ! preg_match("/(\d+TS--->)/", $cache, $match))
        {
            return FALSE;
        }

        // Has the file expired? If so we'll delete it.
        if (time() >= trim(str_replace('TS--->', '', $match['1'])))
        {
            if (is_really_writable($cache_path))
            {
                @unlink($filepath);
                log_message('debug', "Cache file has expired. File deleted");
                return FALSE;
            }
        }

        // Display the cache
        $this->_display(str_replace($match['0'], '', $cache));
        log_message('debug', "Cache file is current. Sending it to browser.");
        return TRUE;
    }// _display_cache

    /**
     * Write a Cache File
     *
     * @access    public
     * @return    void
     */
    public function _write_cache($output)
    {
        $CI =& get_instance();
        $path = $CI->config->item('cache_path');

        $cache_path = ($path == '') ? APPPATH.'cache/' : $path;

        if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
        {
            log_message('error', "Unable to write cache file: ".$cache_path);
            return;
        }

        $uri = $CI->config->item('base_url').
                $CI->config->item('index_page').
                $CI->uri->uri_string();
        // buld query strings
        $querystrings = $_SERVER['QUERY_STRING'];
        if ( $querystrings != null ) {$querystrings = "?".$querystrings;}
        $uri = $uri.$querystrings;

        $cache_path .= md5($uri);

        if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE))
        {
            log_message('error', "Unable to write cache file: ".$cache_path);
            return;
        }

        $expire = time() + ($this->cache_expiration * 60);

        if (flock($fp, LOCK_EX))
        {
            fwrite($fp, $expire.'TS--->'.$output);
            flock($fp, LOCK_UN);
        }
        else
        {
            log_message('error', "Unable to secure a file lock for file at: ".$cache_path);
            return;
        }
        fclose($fp);
        @chmod($cache_path, FILE_WRITE_MODE);

        log_message('debug', "Cache file written: ".$cache_path);
    }// _write_cache

}

Clear all cache files and folders in application/cache.

Original answer (2011)
this can fix codeigniter cache with querystring
codeigniter cache with querystring
it is thai language page but you can just copy that code and put it in application/core/MY_Output.php :)

A: Into config/config.php
You should enable cache_query_string like this
$config['cache_query_string'] = TRUE;

take all query parameters into account.
Please be aware that this may result in numerous cache files generated for the same page over and over again.

A: Here's some code to override Codeigniter's Output class which seems to work for me.
Create the file application/core/MY_Output.php, copy in the _write_cache() and _display_cache() functions from Output.php and update it like this:
class MY_Output extends CI_Output {

    function __construct() {
        parent::__construct();
    }

    function _write_cache($output) {
        ....

        $uri = $CI->config->item('base_url').
               $CI->config->item('index_page').
               $CI->uri->uri_string();

        // append querystring
        $qs = (empty($_SERVER['QUERY_STRING'])) ? '' : '?'.$_SERVER['QUERY_STRING'];
        $uri .= $qs;
        // append querystring

        ....
    }

    function _display_cache(&$CFG, &$URI)
        ....

        $uri = $CI->config->item('base_url').
               $CI->config->item('index_page').
               $URI->uri_string;

        // append querystring
        $qs = (empty($_SERVER['QUERY_STRING'])) ? '' : '?'.$_SERVER['QUERY_STRING'];
        $uri .= $qs;
        // append querystring

        ....
    }

A: You should cache if the value of _GET is empty
if(!$_GET)
    $this->output->cache(0);


text:
Q: How Can I Include One Form within Another Form in Rails? I have a form with multiple fields, including a coupon code. I want the user to be able to independently check if the coupon code is valid without submitting the entire form. I created a form and "Check" submit_tag for the coupon code on its own, which works fine. However, if I put it inside the main form, when the user clicks on "Check" the entire form is submitted. If I put it outside the main form, the coupon code won't be included when the main form is submitted.
How can I include the small form inside the main form, and still allow it to be checked independently?
Possible Solution:
I can put the "Check" form outside the main form and add a duplicate coupon field to the main form and fill it in with javascript on submission, but I was wondering if there's a better way.

A: Why not just use javascript and a link that looks like a button to check asynchronously?
The button shouldn't trigger the form submit action, and you can update the view according to the js response.
The other advantage of doing it this way is that you won't lose all the form data on refresh.


text:
Q: Why am I getting protocol/SSL-errors on NPM install? I'm a newly hired employee trying to get NPM to work on the machine I just got from my company (Lenovo P15s with Windows 10). No matter what I try to fetch with NPM, I get the following error:

request to https://registry.npmjs.org/@angular%2fcli failed, reason: write EPROTO 10540000:error:0A000152:SSL routines:final_renegotiate:unsafe legacy renegotiation disabled:c:\ws\deps\openssl\openssl\ssl\statem\extensions.c:922:

NPM init works fine.
What I've tried so far:

*

*Checked proxysettings to see if I'm behind a proxy (I'm not, as far as I can see - the settings are all clear)

*Removed and reinstalled Nodejs and NPM several times, both through the Windows installer and through NVM/cli

*Running "NPM install" from Node version 19.4, 18 and 17 with correlated NPM-versions. Same error regardless

*Turning off strict-ssl (I'm aware of the risk, just tried for test purposes) - on Node v17+ I get the same error, but turning off strict-ssl on v16 gives me this error instead:

errno SELF_SIGNED_CERT_IN_CHAIN ERR! request to https://registry.npmjs.org/@angular%2fcli failed, reason: self signed certificate in certificate chain

*

*Testing on another clean machine from the company still gives me the EPROTO error

*Setting the NPM-registry with "npm config set registry http://registry.npmjs.org/"

*Setting NODE_TLS_REJECT_UNAUTHORIZED=0 (I know this is risky as well).

No luck.
I have read that you can set the path to a certificate-file in the config file, but walking down that whole certificate-road, I honestly have no idea what I'm doing. I downloaded a DigiCertHighAssuranceEVRootCA-certificate and tried pointing the path to that, no change at all.
Any suggestions on what I'm missing or what I can do?


text:
Q: Circular References in my C# projects I have the following situation:

*

*A project MyCompany.MyProject.Domain which contains my domain model, and partial classes (such as Contact).

*I want to 'extend' (by partial class, not extension method) my Contact class with a property Slug which will give me a simple URL friendly text representation of first and last name.

*I have a string extension method ToSlug() in my Utility project MyCompany.MyProject.Utilities which does exactly what I want in 2).

*The problem: My Utility project is already referencing my Domain project which means that I can't get the Domain project to see the Utility project's ToSlug() method without causing circular reference.
I'm not keen on creating another project to solve this, and I really want to keep the Slug logic shared.
How can I solve this?

A: copy ToSlug method to Domain project and Delegate Utility's ToSlug call to this new method

A: If you cannot share the domain (probably right) and it must consume the logic from a shared library then then you really have to introduce a another assembly.
Or you could load the logic at runtime in the domain by reflection in the domain to access the dependent library. Its not hard just breaks compile time checking.

A: If you're sure about keeping the code in the utility DLL (Eric's answer seems smart to me), then you could create an interface in your utility project, pass that interface as a parameter to your ToSlug method and then have your domain object implement the interface.

A: Your Utility project referencing your MyCompany.MyProject.Domain seems like a bit of a code smell.  I'm assuming here that these are utilities that specifically work on domain objects--if that's the case, then why don't you include MyCompany.MyProject.Utilities within your Domain project (naturally, modifying the namespace accordingly)?
In any case, the normal way to break these kinds of dependencies is to abstract what is required by one project into a set of interfaces, and encapsulate those in a separate assembly.  Before doing that though, make sure that what you're doing conceptually is the right thing.
In your particular situation though, consider introducing an interface, viz., INameHolder:
public interface INameHolder
{
    string FirstName { get; set; }
    string LastName { get; set; }
}

Then Contact implements INameHolder.  INameHolder exists in another assembly, let's call it MyCompany.MyProject.Domain.Interfaces.
Then your Utilities project references Interfaces (not Domain) and so does Domain, but Interfaces doesn't reference anything--the circular reference is broken.


text:
Q: Is libwebp 0.3.0-3 used by pillow on Centos 7 concerned by CVE-2020-36328? We scanned the same host (a CentOS Linux release 7.6.1810 (Core)) with two vulnerability scanners (Nessus and Rapid7).

*

*Rapid7 reported that libwebp-0:0.3.0-7.el7.x86_64 is vulnerable CVE-2020-36328.

*Nessus did not report a vulnerability, the plugin CentOS 7 : qt5-qtimageformats (CESA-2021:2328) did not fire.

The installed library (libwebp-0:0.3.0-7.el7.x86_64) is used by python-pillow-0:2.0.0-19.gitd1c6db8.el7.x86_64 and not by qt5-qtimageformats (against which the test is done)
My question: which one these two scanners is reporting correct information?
Or in other words: is this vulnerability strictly linked to the package that uses it, or is a standalone library vulnerable as well?


text:
Q: array_push not working in ajax called page My input field is
<input type="text" id="quantity" value="0" autocomplete="off" size="2" onKeyUp="myfun(this.value,<?php echo $rw['product']?>)">

Here is my ajax code
function myfun(a,b)
{
   var dat = a*<?php echo $rw['amount'] ?>;
   $('#result').html(dat);
   var datas = 'val=' + a + '&id=' + b ;
   if(datas)
   {
      $.ajax({
         type:"POST",
         url:"insert.php",
         data:datas,
         success: function(html){
            $("#result").append(html);
           }
      });
      return false;
   }
}

In insert.page i have the code like below.
$id = $_POST['id'];
if(!isset($_SESSION['QUANTITY'])){
    $_SESSION['QUANTITY']=array();
}
$newdata= array(
        'id' => $id,
        'val' => $val
        );

$_SESSION['QUANTITY'][]=$newdata;
print_r($_SESSION['QUANTITY']);

Every time i hv changed the value in input fied , it should push the data to session array. but it is replacing the values in array rather than append. Please help me to push the values to array every time i changed my value in input field.


text:
Q: react-testing-library's fireEvent.click not updating result of debug() when testing react-native-web So I have created a simple ConnectFour game using React https://github.com/pavilion/ConnectFourTDD
I have created a Board and Cell components. The board is composed of a table of Cells.
The test renders a 4x4 Board and clicks the first element of the first column, so the outcome would be to get a X in the bottom of the first column:
+--------------------+--+--+--+
| Click happens here |  |  |  |
+--------------------+--+--+--+
|                    |  |  |  |
+--------------------+--+--+--+
|                    |  |  |  |
+--------------------+--+--+--+
| X                  |  |  |  |
+--------------------+--+--+--+

However, when I do debug() which basically prints the DOM tree, it doesn't show any "X". Here is the test: https://github.com/pavilion/ConnectFourTDD/blob/testing-library/packages/web/src/tests/App-test.tsx#L19
What am I doing wrong?

A: After some research I found that the responder system doesn't rely on click events so you can't expect to dispatch those DOM events have onPress get called.
Therefore, if you are using react-native-web you should not write your web tests with react-testing-library but with react-native-testing-library.


text:
Q: xml transforming   <Products>
    <Product ProductID="1">
      <productName>Ball</productName>
      <Color>Green</Color>
    </Product>
    <Product ProductID="2">
      <productName>Doll</productName>
      <Color>White</Color>
    </Product>
  </Products>

I have an xml input like above.But i have problem in creating the product element that have the product name as attribute and the product id as the element under product.below is the code that i have.
 <?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
 <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

 <xsl:template match="//Products">
 <html>
  <body>
   <Products>
    <xsl:for-each select="//Product">
     <xsl:call-template name="Import"/>
    </xsl:for-each>
   </Products>
  </body>
 </html>
 </xsl:template>

  <xsl:template name="Import" match="@*|node()">
    <xsl:copy>
     <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>

   </xsl:stylesheet>

A: I believe you can do it in a following way:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="//Products">
        <html>
            <body>
                <Products>
                    <xsl:apply-templates />
                </Products>
            </body>
        </html>
    </xsl:template>
    <xsl:template match="Product">
        <xsl:element name="product">
            <xsl:attribute name="name" select="ProductName/text()" />
            <xsl:element name="productID">
                <xsl:value-of select="@ProductID" />
            </xsl:element>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

Btw, you have a small error in input XML (productName doesn't have a capital letter)

A: Change
<xsl:template match="//Products">
 <html>
  <body>
   <Products>
    <xsl:for-each select="//Product">
     <xsl:call-template name="Import"/>
    </xsl:for-each>
   </Products>
  </body>
 </html>
 </xsl:template>

into
<xsl:template match="Products">
 <html>
  <body>
   <Products>
    <xsl:apply-templates/>
   </Products>
  </body>
 </html>
 </xsl:template>

then write a template
<xsl:template match="Product">
  <product name="{ProductName}">
    <xsl:apply-templates select="@ProductID"/>
  </product>
</xsl:template>

and a template
<xsl:template match="Product/@ProductID">
  <productID>
    <xsl:value-of select="."/>
  </productID>
</xsl:template>


text:
Q: vertically center image in longtable I have a longtable with \cline borders. Unfortunately, the image in the second column is not vertically centered. I even fail in changing the vertical position any way. I found this similar question: Vertically center image with respect to longtable paragraph
But changing p and m parameter doesn't seem to have an influence.
Here is my minimal working example:
\documentclass[a4paper]{scrreprt}
\usepackage[utf8]{inputenc}
\usepackage[ngerman,english]{babel}
\usepackage[T1]{fontenc}
\usepackage{mwe}
\usepackage{longtable}
\usepackage{array}

\begin{document}

\begin{longtable}{m{0.06\textwidth}p{0.3\textwidth}m{0.05\textwidth}m{0.05\textwidth}m{0.05\textwidth}m{0.05\textwidth}m{0.05\textwidth}m{0.05\textwidth}}
%    \begin{longtable}{p{0.06\textwidth}m{0.3\textwidth}m{0.05\textwidth}m{0.05\textwidth}m{0.05\textwidth}m{0.05\textwidth}m{0.05\textwidth}m{0.05\textwidth}} % doesn't work either
        Index & Figure & bla & bla & bla & bla & bla & bla\\
        \cline{2-8}
        1      & \includegraphics[width=0.2\linewidth]{example-image-a} & bla & bla & bla & bla & bla & bla \\
        \cline{2-8}
        2      & \includegraphics[width=0.2\linewidth]{example-image-a} &  bla & bla & bla & bla & bla & bla  \\
        \cline{2-8}
        3  & \includegraphics[width=0.2\linewidth]{example-image-a} & bla & bla & bla & bla & bla & bla \\
        \cline{2-8}
\end{longtable}
\end{document}

The output looks like:

It seems that there is a higher bottom margin. How can I center the image vertically (and also the text as it seems that the text is too low)?

A: I always suggest \cmidrule from booktabs, since it adds a nice amount of vertical spacing. Here the trick is to lower a bit the graphics:
\documentclass[a4paper]{scrreprt}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[ngerman,english]{babel}
\usepackage{longtable}
\usepackage{array}
\usepackage{booktabs}
\usepackage{graphicx}

\newcommand{\lowincludegraphics}[2][]{%
  \raisebox{-0.7\dp\strutbox}{\includegraphics[#1]{#2}}%
}

\begin{document}

\begin{longtable}{
  c
  m{0.3\textwidth}
  *{6}{c}
}
Index & Figure & bla & bla & bla & bla & bla & bla\\
\cmidrule{2-8}
1 & \lowincludegraphics[width=0.2\linewidth]{example-image-a} &
    bla & bla & bla & bla & bla & bla \\
\cmidrule{2-8}
1 & \lowincludegraphics[width=0.2\linewidth]{example-image-a} &
    bla & bla & bla & bla & bla & bla \\
\cmidrule{2-8}
1 & \lowincludegraphics[width=0.2\linewidth]{example-image-a} &
    bla & bla & bla & bla & bla & bla \\
\cmidrule{2-8}
\end{longtable}

\end{document}

A: Here is a proposition: replace the 2nd column specifier m{0.3\textwidth} with Sc, where S is a pre-column specifier defined by package cellspace which ensures a minimal vertical spacing at the top and bottom of cells in the column, and load adjustbox. If you load siunitx
, which already defines  an S column type, replace S with C:
\documentclass[a4paper]{scrreprt}
\usepackage[utf8]{inputenc}
\usepackage[ngerman,english]{babel}
\usepackage[T1]{fontenc}
\usepackage{mwe}
\usepackage[export]{adjustbox}
\usepackage{longtable}
\usepackage{array}
\usepackage{cellspace, booktabs}
\setlength{\cellspacetoplimit}{3pt}
\setlength{\cellspacebottomlimit}{3pt}

\begin{document}

\begin{longtable}{m{0.06\textwidth}Sc m{0.05\textwidth} *{6}{m{0.05\textwidth}}}
        Index & Figure & bla & bla & bla & bla & bla & bla\\
        \cline{2-8}
        1 & \includegraphics[width=0.2\linewidth, valign = c]{example-image-a} & bla & bla & bla & bla & bla & bla \\
        \cline{2-8}
        2 & \includegraphics[width=0.2\linewidth, valign = c]{example-image-a} & bla & bla & bla & bla & bla & bla \\
        \cline{2-8}
        3 & \includegraphics[width=0.2\linewidth, valign = c]{example-image-a} & bla & bla & bla & bla & bla & bla \\
        \cline{2-8}
\end{longtable}

\end{document}


text:
Q: matplotloib: как отобразить значения в порядке возрастания, сохранив их индекс? Есть 2 списка x и y. x идет в порядке возрастания, y- хаотичный. Как отобразить ось y в порядке возрастания, но что бы значения (x,y) не поменялись?

import numpy as np
import matplotlib.pyplot as plt
x=[]
with open('D:\Programming\Contest\stepperf.txt','r') as a:
    for line in a:
        x.append(line.strip())
x =np.array(x)
y=[]
with open('D:\Programming\Contest\Hall.txt','r') as b:
    for line in b:
        y.append(line.strip())
y  = np.array(y)

fig, ax = plt.subplots(figsize=(8, 6))
plt.grid()
plt.plot(x,y)

plt.show()

A: Можно воспользоваться функцией numpy.argsort():
import numpy as np
import matplotlib.pyplot as plt

# x тут по порядку, а y случайные числа
n = 10
x = np.arange(n)
y = np.random.rand(n)

# сортируем индексы (x,y) по значениям y
ind = y.argsort()

fig, ax = plt.subplots(figsize=(8, 6))
plt.grid()
# рисуем в отсортированном порядке
plt.plot(x[ind],y[ind])

plt.show()

A: Тут нужно использовать библиотеку numpy, и библиотеку pandas
В библиотеке пандас есть возможность создать data array с индексом для каждой вещи.
Data = numpy.array(['a','b','s'])
S = pandas.Series(Data, index=[101,102,103])


text:
Q: Apply text wrap to CSV cell containing long string i am using php code to export data to CSV file.Everything is working fine as required.but problem is that when there comes long text in a cell.I want to wrap text so that i can increase cell size to handle long text.Below is my code.
header("Content-Type: application/force-download\n");
header("Cache-Control: cache, must-revalidate");
header("Pragma: public");
header("Content-Disposition: attachment; filename=store_earning_report.csv");
echo "Notes \n";
echo $Notes;
echo "\n";
exit;

I have searched but didn't find any solution.Is there any way to handle this problem.
Thank you.

A: Make sure you are including a comma "," after each field, and "\r\n" to trigger a new line in the .csv file that is created.
A .csv is just a text file with commas used to separate the field values - So there is no way you can control the cell sizes that will appear when the file is first opened in Excel.


text:
Q: Create Procedure to Insert row & Return SYS_GUID() PK in Oracle SQL My team has two Oracle DB tables - one for capturing service call requests and responses, another for logging certain kinds of errors. Currently the two tables are not related. Both of them use DEFAULT SYS_GUID() to generate their PK's on insert - but one of them stores this as raw(16) and the other as varchar2(50 BYTE).
I'm creating a table that has a FK to each of those tables, and by consensus vote I am required to use a SYS_GUID() as the PK.
Work bans pasting code here so rough sample code follows, assume typos/weird formatting are not present in code/scripts:
table SERVICE_CALLS
SERVICE_CALL_ID RAW(16) DEFAULT SYS_GUID() PRIMARY KEY,
REQUEST_DATETIME DATE NOT NULL,
RESPONSE_DATETIME DATE,
REQUEST_PAYLOAD CLOB,
RESPONSE_PAYLOAD CLOB

table ERROR_LOGS
ERROR_LOG_ID VARCHAR2(50 BYTE) DEFAULT SYS_GUID() PRIMARY KEY,
ERROR_TIMESTAMP TIMESTAMP(6) NOT NULL,
ERROR_TEXT CLOB NOT NULL

My new table:
table SERVICE_CALL_ERROR_LOG_RELATION
RELATION_ID RAW(16) DEFAULT SYS_GUID() PRIMARY KEY,
INSERT_TIMESTAMP TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP,
SERVICE_CALL_ID RAW(16) NOT NULL,
ERROR_LOG_ID CARCHAR2(50 BYTE) NOT NULL,

CONSTRAINT FK_SERVICE_CALL
FOREIGN KEY (SERVICE_CALL_ID),
REFERENCES SERVICE_CALLS(SERVICE_CALL_ID),

CONSTRAINT FK_ERROR_LOG
FOREIGN KEY (ERROR_LOG_ID)
REFERENCES ERROR_LOGS (ERROR_LOG_ID);

ERROR_LOG will have a many-to-one relationship with SERVICE_CALL, but not every ERROR_LOG will have an associated SERVICE_CALL. The RELATION table will only be populated if an ERROR_LOG is created when a SERVICE_CALL_ID is available; the availability will be determined in the actual application. If there is no SERVICE_CALL_ID, we'll just insert a record into the ERROR_LOGS table without touching the RELATION table.
I don't have much experience with stored procedures, but my goal is to create a stored procedure that will take in a SERVICE_CALL_ID (null or raw(16)) and an ERROR_TEXT (CLOB).

*

*If SERVICE_CALL_ID is null, then I'll just insert a new record into
ERROR_LOGS using the ERROR_TEXT and a CURRENT_TIMESTAMP.

*If SERVICE_CALL_ID is not null, then I want to insert a new record into ERROR_LOGS, fetch the auto-generated ERROR_LOG_ID, and insert a new record into SERVICE_CALL_ERROR_LOG_RELATION using SERVICE_CALL_ID and the fetched ERROR_LOG_ID.

Fetching the ERROR_LOG_ID is the part I'm having trouble with. I've found some answers here about getting the newly inserted record's ID if it's a sequence, but those are obviously a bit different since sequences have predictable values... Is there any way to fetch that auto-generated ID on the new record?
Final note: When there's one ERROR_LOG insert, there tend to be multiple within milliseconds, so I can't rely on, say, fetching the most recent record since by the time that processes there could be other records inserted.

A: Okay, I still have to put it all together in my actual environment, but this little test procedure works for me.
INSERT INTO TABLE() RETURNING {COLUMN} INTO {VARIABLE}

Example below:
CREATE OR REPLACE PROCEDURE LOG_SERVICE_ERROR(
SERVICE_CALL_ID IN RAW,
ERROR_TEXT IN CLOB
)
AS
v_ERROR_LOG_ID VARCHAR2(50 BYTE);
BEGIN

INSERT INTO ERROR_LOGS(SYS_GUID(), CURRENT_TIMESTAMP, ERROR_TEXT) RETURNING ERROR_LOG_ID INTO v_ERROR_LOG_ID;

IF SERVICE_CALL_ID IS NOT NULL THEN

INSERT INTO SERVICE_CALL_ERROR_LOG_RELATION(SYS_GUID(), CURRENT_TIMESTAMP, SERVICE_CALL_ID, v_ERROR_LOG_ID);

END IF;

END;


text:
Q: Create dynamic env variables based on the server inside nuxt.config.js I have added below ENV data inside nuxt.config.js file
env: {
      apiUrl: 'http://mywebsite.local/api/',
      webUrl: 'http://mywebsite.local/',

      apiUrl: 'https://mywebsite.live/api/',
      webUrl: 'https://mywebsite.live/'
},

Depending on the environment, I keep the 2 lines commented. So when I am working locally, I comment the 2 lines with mywebsite.live url. And when the files are uploaded to server, I comment the 2 lines with url mywebsite.local.
What I want to do is that the code should detect if the site is running locally or on the server and use the ENV configs based on that. How can I do that?

A: You can tell if you're in production or development with this env variable: process.env.NODE_ENV which you can use in the ternary operator to solve your problem.
env: {
  apiUrl: process.env.NODE_ENV === "production" ? 'https://mywebsite.live/api/' : 'http://mywebsite.local/api/',
  webUrl: process.env.NODE_ENV === "production" ? 'https://mywebsite.live/' : 'http://mywebsite.local/'
}

A: Instead of hard-coding your environment variables into nuxt.config, I'd recommend checking out this dotenv nuxt module or using dotenv itself.
This way, you can have actual .env files setup on each environment you need, or, if you're using Netlify or something as such for your deployments, you can set up your environment keys using their tools too.
This would also avoid nested if-else statements if you start having multiple environments and will keep your code cleaner.
If you still want to hard-code it, then you could do what was already suggested in here and use if/else or ternary operations inside your nuxt-config, like:
env: {
  apiUrl: process.env.NODE_ENV === "production" ? 'https://mywebsite.live/api/' : 'http://mywebsite.local/api/',
  webUrl: process.env.NODE_ENV === "production" ? 'https://mywebsite.live/' : 'http://mywebsite.local/'
}

But then again, I do not recommend this approach.


text:
Q: How to return a NULL from a templated method, without using a pointer I have some code that looks like this:
template <class T>
T foo(T a) {
 if (a) {
   // do somethin', returns object of type T
 } else {
   return NULL;
 }
}

But of course it won't compile since NULL is not of type T. Someone suggested this solution to me but I don't like it:
template <class T>
T* foo(T a) {
 if (a) {
   // do somethin', returns object of type T*
 } else {
   return nullptr;
 }
}

I am wondering how to make this function able to return a NULL value if possible without the use of a pointer?

A: In C++17, you will be able to use std::optional<T>. And you could do something like this:
template <class T>
std::optional<T> foo(T a) {
    if (a) {
        // do somethin', returns object of type T
        return std::make_optional(/*Anything that constructs `T`*/);
    } else {
        return {};
    }
}

And on the receiving end, you can test for the value being there:
auto my_val = foo(obj);
if(my_val){
     /* :-) ....knock yourself out! */
}
else{
     /* :-( ....we didn't find the value */
}

For now,

*

*You can use Boost.Optional.

*Or, if you are using a very recent compiler, you may be able to access it from std::experimental::optional.

*Or, if you do not want to use Boost and its dependencies, you can simply grab this tiny header (a working implementation of optional from one of the proposers of optional into the C++ standard)... It's header only, so, you only need to download/copy that single header file and #include it.

Another cool thing with C++17 is that testing for the value will now be as simple as:
if(auto my_val = foo(obj); my_val){
     // ....knock yourself out!
}

You can see more of C++17 features here: What are the new features in C++17?

A: template <class T>

T list<T>::getData(int i){

    if (i < iSize && i >= 0){

        return listData[i];

    } else {

        cout << "Does not exist";

    return {};

  }

}

//it works pretty well


text:
Q: How can I add Vulkan to a cross platform CMake project? Example? I'd like to use Vulkan in my CMake project how should I proceed?
Looking at the Vulkan samples doesn't really reveal how to do things. And many tutorials insist on you hacking up your own environment to get things working.
Ideally I just want this to work easily and not have to worry about include directories/linking.

A: This is the beauty of CMake and open source.
I'm using Windows / Visual Studio 2019 in my example but it really doesn't matter.
First download the Vulkan SDK: https://www.lunarg.com/vulkan-sdk/
Restart your computer just to be safe (environment variables). The VulkanSDK puts environment variables onto your system. (I realize you don't technically have to restart your computer, but I don't wanna give a crash course on environment variables)
Now we can move onto the CMake.
cmake_minimum_required(VERSION 3.19)

project(EXAMPLE
    LANGUAGES CXX
)

find_package(Vulkan REQUIRED)

add_executable(foobar)

target_sources(foobar PRIVATE main.cpp)

target_link_libraries(foobar PRIVATE Vulkan::Vulkan)

This is what my main.cpp looks like
#include "vulkan/vulkan.h"
#include <iostream>

int main()
{
    std::cout << "Hello World\n";
}

This is what my CMake build commands looked like:
PS C:\git\vulkan_example> cmake -S . -B build
-- Building for: Visual Studio 16 2019
-- Selecting Windows SDK version 10.0.19041.0 to target Windows 10.0.21327.
-- The CXX compiler identification is MSVC 19.29.29917.0
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio/2019/Preview/VC/Tools/MSVC/14.29.29917/bin/Hostx64/x64/cl.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found Vulkan: C:/VulkanSDK/1.2.170.0/Lib/vulkan-1.lib
-- Configuring done
-- Generating done
-- Build files have been written to: C:/git/vulkan_example/build
PS C:\git\vulkan_example> cmake --build build --verbose
Microsoft (R) Build Engine version 16.10.0-preview-21118-01+f0eebf287 for .NET Framework
Copyright (C) Microsoft Corporation. All rights reserved.

Build started 3/11/2021 10:20:28 AM.
Project "C:\git\vulkan_example\build\ALL_BUILD.vcxproj" on node 1 (default targets).
Project "C:\git\vulkan_example\build\ALL_BUILD.vcxproj" (1) is building "C:\git\vulkan_example\build\ZERO_CHECK.vcxproj" (2) on node 1 (default targets).
PrepareForBuild:
  Creating directory "x64\Debug\ZERO_CHECK\".
  Creating directory "x64\Debug\ZERO_CHECK\ZERO_CHECK.tlog\".
InitializeBuildStatus:
  Creating "x64\Debug\ZERO_CHECK\ZERO_CHECK.tlog\unsuccessfulbuild" because "AlwaysCreate" was specified.
CustomBuild:
  Checking Build System
FinalizeBuildStatus:
  Deleting file "x64\Debug\ZERO_CHECK\ZERO_CHECK.tlog\unsuccessfulbuild".
  Touching "x64\Debug\ZERO_CHECK\ZERO_CHECK.tlog\ZERO_CHECK.lastbuildstate".
Done Building Project "C:\git\vulkan_example\build\ZERO_CHECK.vcxproj" (default targets).

Project "C:\git\vulkan_example\build\ALL_BUILD.vcxproj" (1) is building "C:\git\vulkan_example\build\foobar.vcxproj" (3) on node 1 (default targets).
PrepareForBuild:
  Creating directory "foobar.dir\Debug\".
  Creating directory "C:\git\vulkan_example\build\Debug\".
  Creating directory "foobar.dir\Debug\foobar.tlog\".
InitializeBuildStatus:
  Creating "foobar.dir\Debug\foobar.tlog\unsuccessfulbuild" because "AlwaysCreate" was specified.
CustomBuild:
  Building Custom Rule C:/git/vulkan_example/CMakeLists.txt
ClCompile:
  C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\VC\Tools\MSVC\14.29.29917\bin\HostX64\x64\CL.exe /c /IC:\VulkanSDK\1.2.170.0\Include /Zi /nologo /W1 /WX- /diagnostics:column /Od /Ob0 /D WIN32 /D _WIND
  OWS /D "CMAKE_INTDIR=\"Debug\"" /D _MBCS /Gm- /EHsc /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Zc:inline /GR /Fo"foobar.dir\Debug\\" /Fd"foobar.dir\Debug\vc142.pdb" /Gd /TP /errorReport:queue C:\git\vul
  kan_example\main.cpp
  main.cpp
Link:
  C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\VC\Tools\MSVC\14.29.29917\bin\HostX64\x64\link.exe /ERRORREPORT:QUEUE /OUT:"C:\git\vulkan_example\build\Debug\foobar.exe" /INCREMENTAL /NOLOGO "C:\Vulka
  nSDK\1.2.170.0\Lib\vulkan-1.lib" kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /m
  anifest:embed /DEBUG /PDB:"C:/git/vulkan_example/build/Debug/foobar.pdb" /SUBSYSTEM:CONSOLE /TLBID:1 /DYNAMICBASE /NXCOMPAT /IMPLIB:"C:/git/vulkan_example/build/Debug/foobar.lib" /MACHINE:X64  /machine:x64 foobar
  .dir\Debug\main.obj
  foobar.vcxproj -> C:\git\vulkan_example\build\Debug\foobar.exe
FinalizeBuildStatus:
  Deleting file "foobar.dir\Debug\foobar.tlog\unsuccessfulbuild".
  Touching "foobar.dir\Debug\foobar.tlog\foobar.lastbuildstate".
Done Building Project "C:\git\vulkan_example\build\foobar.vcxproj" (default targets).

PrepareForBuild:
  Creating directory "x64\Debug\ALL_BUILD\".
  Creating directory "x64\Debug\ALL_BUILD\ALL_BUILD.tlog\".
InitializeBuildStatus:
  Creating "x64\Debug\ALL_BUILD\ALL_BUILD.tlog\unsuccessfulbuild" because "AlwaysCreate" was specified.
CustomBuild:
  Building Custom Rule C:/git/vulkan_example/CMakeLists.txt
FinalizeBuildStatus:
  Deleting file "x64\Debug\ALL_BUILD\ALL_BUILD.tlog\unsuccessfulbuild".
  Touching "x64\Debug\ALL_BUILD\ALL_BUILD.tlog\ALL_BUILD.lastbuildstate".
Done Building Project "C:\git\vulkan_example\build\ALL_BUILD.vcxproj" (default targets).

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:01.19
PS C:\git\vulkan_example>


text:
Q: Unable to fetch URL of window containing an alert box while initialization using selenium webdriver I am unable to handle getCurrentUrl() method when alert is present at the initialization of url.

A: Without providing more details I can only assume that an alert opens when you load the page but you want to get the current URL of the page? In this case you have to handle the alert before performing getCurrentUrl(). To do so you can simply use:
WebDriverWait wait = new WebDriverWait(driver, 5);
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        alert.accept();

The alert will be closed and you can continou your test and perform a getCurrentUrl(). If this is not the solution you should provide more details on your problem (what is your code, does an exception occur etc.)


text:
Q: Split pages and navigate in WPF I'm trying to create a WPF page project, in which I've split the screen in two. On the left side, I have four clickable links / buttons.
Clicking on one of the links opens a corresponding page on the right side of the screen. There, options can be set. When a user uses the navigation bar on top of the screen, it should apply on the right side only.
Is this possible to do? What would be a better approach?
I'd like to know how to tell a page (part) which page to load. So that would make the right page dynamic?
Would it be better to split up the Grid? Or would a DockPanel be a better solution?
I've created a large Window in WPF, but I'd like to split up all these pages in a usefull navigation Page. So I have a bit of experience in using WPF and XAML. How should I approach this problem?

A: Firt you need to identify the components you want, mainly I see three components, the LeftSide navigation pane, the TopSide navigation pane and the MainContent pane. First lets talk about the MainContent pane, I think the best way for doing this is to use binding and date templates for making this dynamically. In your ViewModel, or DataContext, you need to have a property that represent the Content that you want to show in the MainContent, lets call it MainContent, then the MainContent View could be a ContentControl and set the property Content bindings to the ViewModel's MainContent property. In this way you only need to set the DataTemplate for each class item that you want to show. Other way could be to use a tab control and chage the ControlTemplate, this way is not dynamic because you need predefine all contents that you will show.
Now, for the navigation pane, you could use any control, for instance you could use a Radio button and change the ControlTemplate, and make the logic in the view model, using commands, for instance.
And now, the use of the Grid or DockPanel depends of what you want your application to do. If you want a dynamic width, you should to use a Grid with a GridSplitter, but if you want fixed width, you could to use a DockPanel due it is a bit more efficient/faster than the Grid.
Hope this answers helps, and not to be confused. Please feedback if any doubt.

EDIT
For instance, in the view model:
public class MainViewModel:INotifyPropertyChanged
{
    public object Content {get; set;}    //Here you must to raise the PropertyChanged event
    private ICommand _showSummaryCommand
    public ICommand ShowSummaryCommand
    {
         get { return new _showSummaryCommand ?? (_showSummaryCommand = new SomeCommandImplementation((sender,e)=>{Content = new SummaryViewModel()},true))}    //most of commands implementations recive two parameters, an delegate to execute and a bool delegate for can excecute
    }
}

and for the view, in some resource dictionary:
<DataTemplate TargetType="{x:Type ViewModels:SummaryViewModel}">
    <DataGrid>
        <!--Here goes what ever you want to show for instace-->
        <TextBlock x:Name="descriptionText" Text={Binding Description}/>
    </DataGrid>
</DataTemplate>

and in the place where you will to show all the contents
<!--....-->
    <ContentControl Content={Binding Content}/>
<!--....-->

Hope this code helps a bit more :)


text:
Q: System.NullPointerException: Attempt to de-reference a null object I'm getting an error on a class I've written

"System.NullPointerException: Attempt to de-reference a null object
  Class.Salestreegetcontacts.execute: line 67, column 1"

I'm trying to send an auth key save on User, can anyone tell me where I'm messing up?
global class  Salestreegetcontacts implements schedulable{
global User STUser{get;set;}
public Id STUserId{get;set;}
 public string cstUsername {get;set;}
 public string cstPassword {get;set;}
 public string cstNode {get;set;}
 public string ClientAcctId {get;set;}
 public string xAuthToken{get;set;}
 public url st_Today{get;set;}
 public url st_Vault{get;set;}
 public string kind {get;set;}
 public string title {get;set;}
 public string description{get;set;}
 public date startdate{get;set;}
 public datetime startdatetime{get;set;}
 public url self{get;set;}
 public Contact__c contact;
 public map<string, string> eventmap;
 public map<string, string> UserMap;
 public map<string, string> contactmap;

global User getUserData(){

    If (STUser == null){
    User STUser = [select Id, X_Auth_token__c, CSTlastupdate__c, CST_Node__c, Client_Account_Id__c from User where X_Auth_token__c != null ];
    }
    return STUser;
    }
    global void Userdatamap(){
    if(STUser.X_Auth_Token__c != null){
map<string, string> Usermap = new map<string, string> ();
Usermap.put('Id', string.valueof(STUser.Id));
Usermap.put('xAuth', STUser.X_Auth_token__c);
Usermap.put('LastUpdate', string.valueof(STUser.CSTlastupdate__c));
Usermap.put('Node', STUser.CST_Node__c);
Usermap.put('Client_Account', STUser.Client_Account_Id__c);
}

}
public string xAuth(){
    if(xAuthToken != null){

    xAuthToken = STUser.X_Auth_token__c;
    cstNode = STUser.CST_Node__c;
    ClientAcctId = STUser.Client_Account_Id__c;
    STUserId = STUser.Id;
    }
    return xAuthToken;
    return cstNode;
    return ClientAcctId;
    return STUserId;
}

 global void execute(SchedulableContext sc){
        map<string, string> eventmap = new map<string, string>();

    HttpRequest req1 = new HttpRequest();
    HttpResponse res1 = new HttpResponse();
    Http http1 = new Http();

    req1.setMethod('POST' ); // Method Type
    req1.setEndpoint('https://web210.ntree.com/twig-cstc3/v1/node');
    req1.setheader('X-auth-token: ' , Usermap.get('xAuth'));
    string bodyrequest = '';
    Date Todaysdate = Date.today();
    String sMonth = String.valueof(Todaysdate.month());
    String sDay = String.valueof(Todaysdate.day());
    if(sMonth.length()==1){
        sMonth = '0' + sMonth;
        }
    if(sDay.length()==1){
      sDay = '0' + sDay;
      }
      String sToday = String.valueof(Todaysdate.year()) + sMonth + sDay ;
    bodyrequest += '/' + cstNode;
    bodyrequest += '/calendar?from=' + sToday;
    bodyrequest += '&to=' + sToday;

    req1.setbody(bodyrequest);

        res1 = http1.send(req1);
        if(res1.getBody() != null){

Any idea what I'm doing wrong?

A: In this block here:
if(STUser.X_Auth_Token__c != null){
  map<string, string> Usermap = new map<string, string> ();
  Usermap.put('Id', string.valueof(STUser.Id));
  Usermap.put('xAuth', STUser.X_Auth_token__c);
  Usermap.put('LastUpdate', string.valueof(STUser.CSTlastupdate__c));
  Usermap.put('Node', STUser.CST_Node__c);
  Usermap.put('Client_Account', STUser.Client_Account_Id__c);
}

you are conditionally setting the map when STUser.X_Auth_Token__c is not null. However, you are accessing the map without condition on line 67. To prevent the dreaded "NullPointerException", you can first check if the map contains the key.
if (Usermap.containsKey('xAuth'))... or use the same check you had above if(STUser.X_Auth_Token__c != null){

A: Try initiating User STUser = new User(); before using it. It might help.