text:
Q: No Ajax success after php-script is run I have a php-script which performs a database backup of my website. This backup-script can be triggered by clicking a button on the websites' admin-panel.
I'd like to have some text in the admin-panel that tells the user when the backup is ongoing and when it's complete (process takes about 1 minute) in real-time.
I believe using Ajax is the only reasonable way of doing this, and I have tried the following so far:
<button id="btn">Backup</button>
<script>
    $("document").ready(function(){
        $("#btn").click(function(){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "backup/db_backup.php",
                success: function(data) {
                    alert("success!!!");
                }
            });
        });
    });
</script>

The above does run the backup-script just fine, but I'm unsure why the alert doesn't trigger once the script has finished running. Is there something specific in the php-file I need to have for this to work?
Any help is much appreciated!
EDIT: added the php script as requested
<?php
    include_once '../includes/db_connect.php';

    ini_set("max_execution_time", 0);

    $zip = new ZipArchive();
    $dir = "backups";

    if(!(file_exists($dir))) {
        mkdir($dir, 0777);
    }

    $p = backup_tables($mysqli);
    echo $p;
    if (glob("*.sql") != false) {
        $filecount = count(glob("*.sql"));
        $arr_file = glob("*.sql");

        for($j=0;$j<$filecount;$j++) {
            $res = $zip->open($arr_file[$j].".zip", ZipArchive::CREATE);
            if ($res === TRUE) {
                $zip->addFile($arr_file[$j]);
                $zip->close();
                unlink($arr_file[$j]);
            }
        }
    }

    //get the current folder name-start
    $path = dirname($_SERVER['PHP_SELF']);
    $position = strrpos($path,'/') + 1;
    $folder_name = substr($path,$position);
    //get the current folder name-end

    $zipname = date('Y/m/d');
    $str = "dRbot-".$zipname.".zip";
    $str = str_replace("/", "-", $str);

    // open archive
    if ($zip->open($str, ZIPARCHIVE::CREATE) !== TRUE) {
        die ("Could not open archive");
    }

    $zip->addFile(realpath($folder_name . "/" . $p));
    // close and save archive
    $zip->close();
    echo "Archive created successfully.";

    copy("$p.zip", "$dir/$str");
    unlink("$p.zip");

    /* backup the db OR just a table */
    function backup_tables($mysqli, $tables = '*') {
        //get all of the tables
        if($tables == '*') {
            $tables = array();
            $result = $mysqli->query('SHOW TABLES');
            while($row = $result->fetch_array(MYSQLI_NUM)) {
                $tables[] = $row[0];
            }
        } else {
            $tables = is_array($tables) ? $tables : explode(',',$tables);
        }
        $return = "";

        //cycle through
        foreach($tables as $table) {
            $result = $mysqli->query('SELECT * FROM '.$table);
            $num_fields = mysqli_field_count($mysqli);
            $return.= 'DROP TABLE '.$table.';';
            $result2 = $mysqli->query('SHOW CREATE TABLE '.$table);
            $row2 = $result2->fetch_row();
            $return.= "nn".$row2[1].";nn";

            while($row = mysqli_fetch_row($result)) {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j<$num_fields; $j++) {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = preg_replace("#n#","n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }
                $return.= ");n";
            }
            $return.="nnn";
        }

        //save file
        $path = 'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql';
        $handle = fopen($path,'w+');
        fwrite($handle,$return);
        fclose($handle);
        return $path;
    }

?>

A: Your script db_backup.php should output something in JSON format, echo something like this.
echo json_encode(array('success'));

OR
You can change your code to this:
<button id="btn">Backup</button>
<script>
    $("document").ready(function(){
        $("#btn").click(function(){
            $.ajax({
                type: "POST",
                url: "backup/db_backup.php",
                success: function(data) {
                    alert("success!!!");
                }
            });
        });
    });
</script>

A: I would try something like this:
 var serverCall=function(){
      var ajax=$.ajax({
            type: "POST",
            dataType: "json",
            url: "backup/db_backup"
        });

     return ajax.then(function(data,status,xhr){
                              // success
                }, function(){
                    // fail
                });

  }

 $("#btn").on('click',serverCall);

That should give you what you want.  One thing to keep in mind is what you are returning from your server code.   If you are returning false or true, it will have no impact on which callback handler is called.  You need to send an HTTP status code in your response headers.  That is the only way jQuery can determine if the request was successful.
Lastly.  You only have a success callback.  Your code should still work unless the server side returned a 4xx or 5xx response code.  Then it will fire the fail callback handler, which you don't have, so nothing will happen.  You can attach a function instead of then called always as a callback handler.  This will fire a callback regardless of the outcome.
I recommend investigating what I said in the jQuery docs.


text:
Q: Basic resolve for Angular routing I'm creating a very basic login system with Angular JS. Basically, after a login form is submitted, credentials are checked against a database using PHP and Mysqli. If all is ok, it returns successful and I set a variable like $rootScope.isLoggedIn = true and user details in other similar variables.
Now I'm trying to work out the best way to use resolve with my routes so that only logged in users or users with correct permissions can access a page (including on page reload!)
I just can't get my head around how these resolves work. My routing looks like this so far (the dashboard page needs user to be logged in):
app.config(function($routeProvider) {

  $routeProvider

  //login
  .when('/', {
    templateUrl : 'framework/views/login.html',
    controller  : 'LoginCtrl',
    title: 'Admin Login'
  })

  //dashboard
  .when('/dashboard', {
    templateUrl : 'framework/views/dashboard.html',
    controller  : 'DashboardCtrl',
    title: 'Dashboard',
    resolve: { ? }
  })

  //catch all redirect
  .otherwise({ redirectTo: '/' });

 });

A: Resolve will open your route with a resolved variable (that can be injected into controller) as soon as it gets value (instantly or when returned promise will be resolved). See:
resolve: {
    myVar: function(service, $rootScope, etc){
        return service.obj; // or primitive, or promise or something else
    }
}
.controller('DashboardCtrl', function(myVar){
    console.log(myVar); // that service.obj goes here
}

That can't prevent route from loading (as I understand, please correct me if I'm wrong).
For your case it's better to use something like this:
.when('/', {
    templateUrl : 'framework/views/login.html',
    controller  : 'LoginCtrl',
    title: 'Admin Login',
    authenticate: false
})
.when('/dashboard', {
    templateUrl : 'framework/views/dashboard.html',
    controller  : 'DashboardCtrl',
    title: 'Dashboard',
    authenticate: true
})

$rootScope.$on("$routeChangeStart", function(event, toState){
    if (toState.authenticate && !$rootScope.isLoggedIn){
        $location.path('/');
    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Data adds up but does not display in single compile I am using service-based database (.mdf file) to add name and the photo to my database in VS 2010. After debugging and adding the data it adds up into the .mdf but while trying to retrieve it, it doesn't show. It shows only after next debugging. I am really stuck in this for 2 days please help me.
Thank you in advance.
Connection string I am currently using :
Dim path As String = (Microsoft.VisualBasic.Left(Application.StartupPath, Len(Application.StartupPath) - 9))
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=" & path & "Database1.mdf;Integrated Security=True;User Instance=True")

This is the code I am using to save the image and name :
Dim cmd As New SqlCommand("INSERT INTO Information VALUES(@name,@photo)", con)
        cmd.Parameters.AddWithValue("@name", TextBox1.Text)
        Dim ms As New MemoryStream()
        PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
        Dim data As Byte() = ms.GetBuffer()
        Dim p As New SqlParameter("@photo", SqlDbType.Image)
        p.Value = data
        cmd.Parameters.Add(p)
        cmd.ExecuteNonQuery()
        MessageBox.Show("Name & Image has been saved", "Save", MessageBoxButtons.OK)

And this is the code I am using to display data in the datagridview
Me.InformationTableAdapter.Fill(Me.Database1DataSet.Information


text:
Q: Using google-maps sdk in Android App with custom Tiles from GeoServer I'm trying to create an App which displays a 2D map using google-maps sdk and gets the Tiles from GeoServer, I'm having a problem regarding the server returning the different zoom-levels not as expected 1x1, 4x4, 16x16 squares, instead it uses half the Tiles in Height compared to width: 4x2, 16x8 etc...
This ends up in the map being displayed kind of ok but with half the tiles at the top being empty, is there a way to configure this and male it work with this kind of tiles?
The server uses EPSG:4326 projection.
Using an offset I was able to center the map but while zooming it doesn't behave as expected...
Here is a gif of the resulting map: https://gph.is/g/E1qQgkw
Here are some captures on the right of the tiles being returned and on the left a different layer that works as expected:

Is there a way to configure google-maps to work with this projection and tiles? I'm even willing to switch to a different sdk if that's not the case...
I'll appreciate any help or pointers...

A: EPSG 3857, Pseudo-Mercator is really the client "standard" for consuming tiles
https://epsg.io/3857
and I'm not aware of any other SDK capable of consuming non-standard tiles (osmdroid, mapsforge, mabox,..)
So your Geoserver instance will have to serve EPSG:3857, either on-the-fly, or pre-generated.
I couldn't understand if Geoserver is serving WMS tiles. In that case you can pass the EPSG code as parameter while requesting tiles.
Take a look at this add-on for Google Maps, to see how it's done,
https://github.com/shalperin/android-wms
In case Geoserver is just serving a cache of pre-generated X/Y/Z tiles you'll have to regenerate that cache.
Nevertheless, here's the official demo on how to consume tiles using TileOverlay
https://github.com/googlemaps/android-samples/blob/master/ApiDemos/java/app/src/main/java/com/example/mapdemo/TileOverlayDemoActivity.java

A: By default, GeoServer (actually the internal GeoWebCache) is able to provide tiles using 3 related but distinct standards WMTS, TMS and WMS-C in two projections EPSG:4326 (lat/lon degrees) or EPSG:900913 (now known as EPSG 3857, Psuedo Web Mercator).
Which of those end points you need is dependent on the SDK you are using, but looking at the images you show the one on the left is in EPSG:4326 and the right is EPSG:3857.

A: After much investigation we figure out the problem and come to a solution, maybe it can help someone in the future, the problem was that the Satellite tiles where in a different projection compared to the Road ones, ESPG:4326 vs ESPG:3857 (The most common one aka Web Mercator that google maps and all other sdk use)
We couldn't make any changes to the tiles but we did have the posibility to make changes to the server so MapProxy was our best option, using that tool we where able to transform 4326 to 3857 and consume the tiles from the mobile client with no changes.
it's a python program that runs on windows, and acts as a proxy between the tiles that the client request and the server providing the tiles, reprojecting and exposing them on a new endpoint.


text:
Q: Python tkinter buttons from sql query i'm completely new to python and try to wrap my head about the following problem.
I need to create buttons from an sql query.
Right now one button looks like this (i skip style things)
def __init__ (self, screen):

    self.frame = Frame(screen)
    self.frame.grid()
    self.button01Image = PhotoImage(file=row[2])
    self.button01 = Button(
        self.frame,
        image = self.button01Image,
        command = self.button01Activate,
        )
    self.button01.grid(row = 0, column = 0)

    def button01Activate(self):
        self.button01.configure(
            state = DISABLED
            )
        dosomething(23)
        dosomething(01)

result (row) from sql query looks like this
('01', '23', 'picturefilename.png' ,'0')

In the end i want something like this, yes i know that it doesn't work.
def __init__ (self, screen):

    self.frame = Frame(screen)
    self.frame.grid()
    self.button + row[0] Image = PhotoImage(file=row[2])
    self.button + row[0]  = Button(
        self.frame,
        image = self.button01Image,
        command = self.button01Activate,
        )
    if row[3] == 0
        self.button + row[0] + .configure(
            state = DISABLED
            )
    #counting up to a 3x5 grid)
    self.button + row[0] + .grid(row = 0, column = 0)

    def button + row[0] + Activate(self):
        self.button + row[0] + .configure(
            state = DISABLED
            )
        dosomething(row[1])
        dosomethingelse(row[0])

So basically i need to assign functions and pictures to the button from the database.
I got no clue where to start change things here, i guess my approach is completely wrong.
Can somebody point me into the right direction?

A: You have to construct the Activate functions through a closure.
I have replaced the images with text for the example. Just look at the comments.
#!/usr/bin/env python3
import tkinter as tk

class CreateButtons:
    def __init__ (self, screen, sqlresult):

        self.frame = tk.Frame(screen)
        self.frame.grid()
        self.buttons = {}
        for i,row in enumerate(sqlresult):
            #buttonImage = PhotoImage(file=row[2])
            buttonId = row[0]
            button = tk.Button(
              self.frame,
              text = 'button-'+str(buttonId)
              #image = buttonImage
            )
            button['command'] = self.createButtonCommand(buttonId, row[1])
            self.buttons[buttonId] = button
            if row[3] == 0:
                button.configure(state = tk.DISABLED)
            #counting up to a 3x5 grid)
            button.grid(row = i//5, column = i%5)

    def createButtonCommand(self, buttonId, buttonArg):
        def command():
            self.buttonActivate(buttonId, buttonArg)
        return command

    def buttonActivate(self, buttonId, buttonArg):
        button = self.buttons.get(buttonId)
        if not button: return
        button.configure(state = tk.DISABLED)
        print("Button Pressed:", buttonId)
        #dosomething(buttonArg)
        #dosomethingelse(buttonId)

sqlresult = [(0,1,'pict1.png',1),(4,6,'pict2.png',0),(10,11,'pict3.png',1)]
root = tk.Tk()
CreateButtons(root, sqlresult)
root.mainloop()


text:
Q: Mapreduce similar movies MapReduce:Find Similar Movies
After creating pairs of candidate similar movies how do i calculate the jaccard similarity between them, so that i found the similar movies?
e.g. userID, movie ID1, movie ID2 rating1, rating2
 1,      1        , 2         5      , 4
 2,      1        , 4         4      , 3
 3,      1        , 2         4      , 5

the table shows that movie1 and movie 2 are similar because they had been rated from 2 different users (user1 and user3) the similar rating.

A: Read "Non-negative matrix factorization" in Wikipedia.
On MapReduce level: stochastic gradient descent is done my dividing the training set into subsets processed by reducers and then averaging parameters between subsets.
See Collaborative Filtering in Mahout for reference.


text:
Q: How to calculate the normalized magnitude of a complex number? I have a set of complex numbers which is used to create an image. According to the documentation, each pixel is calculated using the normalized magnitude in decibel scale of the complex number.
How can I calculate the normalized magnitude and obtain a single value (with no imaginary part)?
Thank you.

A: You have a set of $z_n$ complex numbers with $n$ from $1$ to $N$. $n$ might be a set of two indices in case of an image. The magnitude of $z_n=\Re z_n+i\Im z_n$ is given by $|z_n|=\sqrt{\Re^2z_n+\Im^2z_n}$. The normalizes magnitude is given by $I_n=\frac{|z_n|}{max(|z_j|)}$. In decibels you just need to use $10\log_{10}I_n$.
In a program, do the following steps:

*

*Calculate the magnitude of all complex numbers

*Find the maximum of these magnitudes

*Divide all magnitudes by the maximum value

*Take the logarithm base 10, and then multiply by 10.


text:
Q: Get ModifiedBy user ID that most recently modified a DataExtention I'm making this SOAP API call to get info about data extensions in a targeted business unit.  The only real piece of information I need is: who last modified the data extension.  In looking at the DataExtension object in Salesforce Marketing Cloud, I don't see 'ModifiedBy' or anything similar field that would identify the user that did the last modification.  Any direction on where I would find that information?

A: This unfortunately is not possible by an external API we have access to or any other process available to us. You would only be able to get this information via an internal API or via the UI.  None of the REST nor SOAP API calls have this information as a possible property in the return.
You can see some details in this answer about 'Created by', which is identical to your request on 'Modified By'.
Below is a quick snippet of that answer:

For example if you go into Contact Builder and watch the network tab, it will point to this REST Endpoint:
GET https://www-mc-{{stack}}.exacttargetapis.com/internal/v1/customobjects/{{deID}}

Which, as you may guess by the 'internal' part, it will not accept the authentication we receive via the current OAuth token from our REST applications. Which means we are not able to access this without an 'internal' auth token.

I would love for users to push these requests for API functionality to the ideas page or other avenues to let SFMC know how useful and in-demand these capabilities are. Without this information or push for capabilities, they will not realize where they need to put effort.


text:
Q: Change to hour and min format in superset I have a column durationInSeconds.
I used that column and pulled in as metric and used custom sql as SUM(durationInSeconds)
I am getting the result in the format 49.2B.
How can I change this to hour and min format? I am using superset.

A: Use this metric to convert into minutes.
SELECT ROUND(durationInSeconds/60, 0)


text:
Q: How can server notify mobile app? I have been researching for the last few days but have not found any concrete answer for this question.
I have a mobile app that users logged in to . The app makes call to an external database using REST Api and fetches data when required e.g : Button press , loading etc...
However , i can't figure out how to make the server notify a user/mobile app when something happens.>
The only way i can think of is to make the app check the server every second which is overkill and will drain battery life along with database call.
Let's say one user messages another user , how can i make the server send a ping or something to that specific user's mobile app to inform him of a new message ?
As far as i know , REST is completely independent of the server/app and the communications goes only one way : app -> server -> return data to app
Is there any way for the server to send data to the app without any initial request ?
Or if there is a better way to do this

I'm using Xamarin cross-platform with a php backend (Slim)
I read a bit about push notifications , but i'm not sure if thats what im looking for .
I want to update the app while the user is still on at times - like when they get a message - instead of receiving a push notification from google , the app should simply be alerted by the server that a new message is in and reload the "thread"

A: Try using a realtime database like firebase.
I think, you must create a consumer tolisten the database events. With this approach the database notifys your consumer from events ocurred on the server, same as message received on server side from another device.
See if oficial docs suits for your problem: https://firebase.google.com/docs/database/


text:
Q: jQuery validate post error message under input Hello stackoverflow members . I  need to show errors messages generated by jQuery validate plugin under each input that have not pass the validation. How can i set this messages in errorPlacement function? Here is my code.
$(document).ready(function(){
    var base_url = window.location.origin;
    //Preiau mesajele de erroare pentru form

    var language = $("#lang").val();
    var firstname = $("#fname").val();
    var lastname = $("#lname").val();
    var email_req = $("#em_req").val();
    var email = $("#em").val();
    var email_remote =$("#email_remote").val();
    var country = $("#cntry").val();
    var city = $("#cit").val();
    base_url=base_url+"/admin/"+language+"/adduser/";
    $("#success_message").hide();
    $("#addnewuser").validate({

            rules:{
                firstname: {
                    required:true,
                },
                lastname:{
                    required:true,
                },
                email:{
                    required:true,
                    email: true,
                    remote: {
                        url: base_url+"checkemail",
                        type: "POST",
                        datatype:"JSON",
                        data:{
                            email: function(){
                                return $("#email").val();
                            }
                        },
                    }
                },
                country: {
                    required:true,
                },
                city:{
                    required:true,
                },
            },

            messages:{
                firstname: {
                    required:firstname,
                },
                lastname:{
                    required:lastname,
                },
                email:{
                    required:email_req,
                    email: email,
                    remote:email_remote,
                },
                country: {
                    required:country,
                },
                city:{
                    required:city,
                },
            },
            errorPlacement:function(error,element){

            },
            submitHandler: function(form){
                        $.ajax({
                            type: "POST",
                            url:base_url+"addUser",
                            dataType: "html",
                            data: $("#addnewuser").serialize(),
                            success: function(data){
                                if(data == true)
                                {
                                    $("#success_message").show();
                                }
                            }
                        });
                    return false;
                }

        });
});

A: I got this. I need to set this errorPlacement function like this.
errorPlacement:function(error,element){
                 error.appendTo(element.parent().parent().after());
            },

A:     You can do it as follows :

         $("#addnewuser").validate({
                                   invalidHandler: function(e, validator) {
                                       var errors = "Errors found, Please check your information";
                                       if (errors) {

                                           $("div.error-banner").show();
                                           $("div.success-banner").hide();

                                       } else {

                                           $("div.error-banner").hide();
                                       }

                                   },
                                   success: function(label) {
                                        var lblMsg = "This field is validated"
                                        label.html(lblMsg).addClass("checked");
                                        $(".checked").prev().addClass("checked-field");
                                    },
                                    highlight: function(element) {
                                        $(element).addClass("error");
                                        $(element).removeClass("checked-field");
                                        $(element).next(".error").remove();
                                        $(element).next().removeClass("checked");

                                    },
                                   errorPlacement: function(error, element) {
                                       error.insertAfter(element);
                                   },
                                     ignore: ".hide input"

                               });

    if($.validator){
    $.validator.addMethod("cRequired", $.validator.methods.required, requiredMessage);
    }

$.validator.addClassRules("required-field", {
                           cRequired: true
                       });

where requiredMessage is your variable for setting the message.


text:
Q: How to query Firebird SQL Dialect I'm trying to query the SQL dialect of a Firebird database (using the embedded driver):
procedure TFrmFireDACEmbed.BtnGetDBDialectClick(Sender: TObject);
var
   lFDConnection : TFDConnection;
   lDriverLink   : TFDPhysFBDriverLink;
   l             : Integer;
begin
   if not DlgOpen.Execute then Exit;

   lDriverLink   := TFDPhysFBDriverLink.Create(nil);
   lFDConnection := TFDConnection.Create(nil);
   try
      lDriverLink.DriverID := 'FBEmbedded';
      lDriverLink.VendorLib := 'fbembed.dll';  // 32-bits embedded
      lFDConnection.DriverName := S_FD_FBId;
      lFDConnection.Params.Database := DlgOpen.FileName;
      lFDConnection.Params.Add('Server=127.0.0.1');
      lFDConnection.Params.UserName := 'SYSDBA';
      lFDConnection.Params.Password := 'masterkey';
      lFDConnection.LoginPrompt := False;
      lFDConnection.Open;
      l := lFDConnection.Params.IndexOf('SQLDialect');
      if l <> -1 then
         ShowMessage(lFDConnection.Params[l])
      else
         ShowMessage('SQLDialect not found');
   finally
      lFDConnection.Close;
      lFDConnection.Free;
      lDriverLink.Free;
   end;
end;

But the lFDConnection.Params only contains DriverID, Database, Server, User_Name, Password.
The inspector shows:
(nil, $2F22820, #$D#$A, nil, 0, ',', '"', '=', [soWriteBOM,soTrailingLineBreak,soUseLocale], (('DriverID=FB', nil), ('Database=D:\Temp\KLANTEN.GDB', nil), ('Server=127.0.0.1', nil), ('User_Name=SYSDBA', nil), ('Password=masterkey', nil), ('', nil), ('', nil), ('', nil)), 5, 8, False, dupIgnore, False, (FireDAC.Stan.Def.TFDDefinition.ParamsChanged,$2F5C4F0), (FireDAC.Stan.Def.TFDDefinition.ParamsChanging,$2F5C4F0), False, TFDConnectionDef($2F5C534) as IFDStanDefinition)

And lFDConnection.Params.SQLDialect is not recognized by the compiler.
Digging though the system tables I found that for a dialect 3 db the query
select mon$sql_dialect from mon$database

will return 3, but for an older version mon$database does not exist.
How can I retrieve the SQL dialect for any dialect?
The intention is to rewrite old code that used 'under the hood' functions like isc_attach_database, isc_database_info (which had to be dynamically linked, GetProcAddress, etc).

A: How to get SQL dialect of the connected Firebird database?
You can replace your legacy code by something like this:
uses
  FireDAC.Phys.IBWrapper;

procedure TForm1.Button1Click(Sender: TObject);
var
  SQLDialect: Integer;
  IBDatabase: TIBDatabase;
begin
  IBDatabase := TObject(FDConnection1.CliObj) as TIBDatabase;
  SQLDialect := IBDatabase.db_sql_dialect;
end;

How to specify SQL dialect for Firebird database connection at runtime?
You can specify connection definition parameter for SQL dialect by:
FDConnection1.Params.Add('SQLDialect=1');

Or by typecasting to specific Firebird DBMS connection definition class like this:
TFDPhysFBConnectionDefParams(FDConnection1.Params).SQLDialect := 1;

A: I'm not familiar with Delphi, so my answer is from a generic Firebird perspective.
The MON$DATABASE table exists both in dialect 1 and dialect 3 databases, provided that database is at least ODS 11.1 (Firebird 2.1, which introduced the monitoring pseudo-tables). If you don't have a MON$DATABASE table then the database is ODS 10.0 (InterBase 6/Firebird 1.x) or ODS 11.0 (Firebird 2.0).
In other words, if you don't have a MON$DATABASE, you could backup and restore the database to upgrade it and then check MON$DATABASE.
Otherwise, there is a trick you can use to determine if a database is dialect 1 or dialect 3. The trick is to execute the following query:
select 1/2 from rdb$database

If the result is 0 (integer), then your database is dialect 3, if the result is 0.500000 (double precision), the database is dialect 1. In theory preparing the query should be enough, the value would be described as DOUBLE PRECISION in dialect 1 and as BIGINT (or DECIMAL(18,0)) in dialect 3.
This is because this is one of the differences between dialect 1 and dialect 3: integer division in dialect 1 is done as floating point division.
Be aware: it is possible to explicitly set a connection dialect and override the default of using the database dialect. This should produce a warning on connect, but not all drivers/components communicate that warning.
Alternatively, you could query for isc_info_db_sql_dialect using isc_database_info (or check if your component has something that does this for you, see the answer by Victoria), or use gstat -h to check the database header page directly.


text:
Q: Is using Rule Engine to implement chain of rules [complex business logic] overkill? Recently, I am reading about the rule engines in JBOSS Drools Manual [ref - 2.2.5. Strong and Loose Coupling]. Below is the excerpt from it 'If your rules are all strongly coupled, the chances are that the rules will have future inflexibility, and more significantly, that perhaps a rule engine is overkill (as the logic is a clear chain of rules - and can be hard coded. [A Decision Tree may be in order]). This is not to say that strong or weak coupling is inherently bad, but it is a point to keep in mind when considering a rule engine and in how you capture the rules. "Loosely" coupled rules should result in a system that allows rules to be changed, removed and added without requiring changes to other rules that are unrelated.'
Does that mean, the rule engine is not  suitable option to implement complex business logic [tightly coupled rules or chain of rules].
In my current project, we have chain of rules i.e. outcome of 1 rule decides the outcome of another rule and so on. The application has many internal variables to chain the rules. I thought rules engine might help to handle the complexity with the added advantage of declarative rules and dynamic business logic.
Discussion in this regard will be helpful ...

A: Some logic just isn't all that easy to get right even if you exactly know the order and nature of the tests you need to perform, and the actions that should result.  Examples are Corporate Audits, Means testing for Assistance programs, Insurance regulations, etc.
Most Rules Engines today are beginning to include a Decision Table feature, which in all reality introduces some "limited strong coupling" (I don't know if that is really a term, but it is how I understand the effect in systems such as ILog, Drools, etc.).  This is helpful because some tests are just related to other tests and decision tables are far better for structuring these tests than IF THEN ELSE structures.
Corticon (a proprietary Rules Engine) and DTRules (an open source Rules Engine) just toss the whole loosely coupled rules approach, and just build decision tables.  The idea is that giving a nice structure for the construction of your decisions (which amount to decision trees underneath everything) is easier for many applications.

A: "Avoiding strong coupling" has nothing to do with "avoiding complexity".
What the documentation advocates is that you should not call one rule from another, instead, each rule should produce an outcome, and the outcome itself should trigger the next rule in chain. This way rules do not concern with what happens next, and instead they deal with facts (aha!). And if - instead of writing rules for facts - you focus on writing an ordinary flow of procedural logic, you do not really need the added complexity of a rules engine.
The difference is subtle, but not more subtle than rules like "don't put your business logic in view" or "don't put your database access code in your business logic".

A: In IBM ILOG Jrules there are many ways you can represent your rules.

*

*In plain english like language , if else kind of syntax.

*decision table - for a set of value

*decision tree  - multiple outcomes , branching out.

so you can decide on which way you can use the above three ways which fits to crack your complex rules into a more simpler form.
you can use rule flow orchestration with conditional flow  to tackle " outcome of 1 rule will be the input of another rule "

A: I think it all depends on UI, not on actual logic that the rule(s) contain(s). Remember that most of today's engines are decision-table-mentality-based. And all that "Strong and Loose Coupling" is nothing more than buzz words used as an excuse for a bad UI or lack of it. Normal engine can handle execution of a rule of any complexity. Note that this is my personal opinion, lots of folks out there would completely disagree. So, please don't rush to downgrade my answer, I'm just trying to help :)
The typical notion is that the rule with complex logic would look really "messed up" or even impossible to implement in a decision table. Normally, guys try to combat that by dividing complex rules into smaller simple rules and stack them up into rule sets based on execution priorities.
There are new engines that have decision-table-less UIs by implementing parentheses instead of priorities. Parentheses also help with complexity.


text:
Q: Tastypie 'Search' Only Returns Resource Name I'm trying to create a function that filters objects by a ForeingKey field (or rather the object being referenced in the field). I wrote the function which I have included below, which is based off the Tastypie Cookbook's Adding Search Functionality. The function does work in that it returns the objects, however it only returns the objects' names as a string.
This is the result of calling the function:
{'receipt_items': [<ReceiptItem: Item1>, <ReceiptItem: Item2>, <ReceiptItem: Item3>]}
Here is my resource:
class ReceiptItemResource(ModelResource):
receipt = fields.ToOneField(ReceiptResource, 'receipt', full = True)
class Meta:
    queryset = ReceiptItem.objects.all()
    serializer = Serializer()
    allowed_methods = ['get', 'post', 'put', 'delete']
    always_return_data = True

def prepend_urls(self):
    return [
        url(r'^(?P<resource_name>%s)/filter%s$' % (self._meta.resource_name, trailing_slash()), self.wrap_view('filter_by_receipt'), name = 'filter_by_receipt'),

        ]

def filter_by_receipt(self, request, **kwargs):
    data = self.deserialize(request, request.body, format = request.META.get('CONTENT_TYPE', 'application/json'))

    receipt_id = data.get('receipt_id', '')
    print receipt_id

    receipt = Receipt.objects.get(id = receipt_id)

    receipt_items = ReceiptItem.objects.filter(receipt = receipt)

    item_list = {
        'receipt_items' : receipt_items,
    }

    print item_list
    return self.create_response(request, receipt_items)

    #return super(ReceiptItemResource, self).get_object_list(request).filter(receipt = receipt)

def get_object_list(self, request):
    user = request.user
    member = user.member
    owner = member.owner

    return super(ReceiptItemResource, self).get_object_list(request).filter(owner = owner)

Ideally I would like this function to return the full object details in JSON. Is there any way to make this happen?
I have looked into Tastypie's resource filtering, however I don't believe this would work since the field I am trying to filter by is a ForeignKey.
All help is greatly appreciated, thank you.

A: You should not need to do this. You can filter on foreignKey by default using the filtering option
from tastypie.resources import ALL, ALL_WITH_RELATIONS

class RecieptResource(ModelResource):
    class Meta:
       fields = ["id"]
       filtering = {
         "id": ALL
       }

class ReceiptItemResource(ModelResource):
    receipt = fields.ToOneField(ReceiptResource, 'receipt', full = True)
    class Meta:
        queryset = ReceiptItem.objects.all()
        allowed_methods = ['get', 'post', 'put', 'delete']
        always_return_data = True
        filtering = {
            "reciept": ALL_WITH_RELATIONS
        }

Now the following should url (depending on how you have yours configured) should give you what you want
/api/v1/reciept-item/?receipt__id=1&format=json


text:
Q: How to get the nsmutablearray data into float getting dataset as like below
Webservices *details=[[Webservices alloc] init];
[details getMobileNumberDetails:phnotextfield.text];
NSLog(@"longitudes Arrays from %@",details.resultData);

"-91.57696007",
      "10.343234",
      "74.982343",
      "76.464844",
      "76.464844",

But how to convert total dataset into float on iOS?

If we use OjectAtIndex:0 it takes first position but I have to store total response into single float value without using OjectAtIndex:0 in iphone.

A: use
float x = [[Array objectAtIndex:0] floatValue];


text:
Q: Vertical alignment CSS not aligning I am experiencing a problem with vertical alignment with products on the vape site I'm working on, I can't seem to align the products, reason being mainly is because description length, star rating and price/sale differ by up to 3 lines.
Ideally I would like to align:

top of pics

And

add to cart/choose options

not just one or the other as it is right now.
Here is the vape site I'm working on.
Would anyone be able to help with this?

A: In the div with the classes box-text box-text-products text-center grid-style-2 I would add another class or add the following to the box-text class.
  height: 100%;
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-auto-flow: row;

Then add align-self:end to the div's with classes price-wrapper & add-to-cart-button.  You might also need to make sure that the overall containing div is set to height of 100%, I think it is the div with the class of col-inner. If you have more questions about using css grid you can refer to CSS Trick Guide to Grid.


text:
Q: Cordova DatePicker for WP8 I am unable to use the DatePicker plugin for WP8 as it is not supported. Is there any option/alternative for showing a datePicker and timePicker for WP8 in the Cordova project?
This alternative does not build using the CLI, neither does this as it gives the error:


text:
Q: Apache Solr PDF indexing I want to index the pdf documents whenever it is uploaded by an application. At the time of indexing I am sending the filename and fileType in the url like follows
http://localhost:8983/solr/update/extract?stream.file=/D:\apache-solr-3.3.0\example\exampledocs\Accessing_MySQL_from_IntalioBPMS.pdf&stream.contentType=application/pdf&literal.id=111&literal.fileName=Test.pdf&literal.fileType=pdf&commit=true

I am having the fields fileName and fileType in my schema.xml file as well.
After I indexed the pdf documents I do the search it shows only the content and id of the pdf document but not the filename and filetype.
What I am doing wrong?

A: When you define your schema, you must specify which fields will be stored (or retrievable upon search). In this case, it is likely that your filename and filetype fields are only indexed and not stored.
Make sure your schema is like the following:
<field name="filename" type="{yourDesiredType}" indexed="true"stored="true"/>
<field name="filetype" type="{yourDesiredType}" indexed="true"stored="true"/>
For more information about editing the schema.xml, go to http://wiki.apache.org/solr/SchemaXml.


text:
Q: How to convert JSON data to Array in JQuery? I am getting Json data from result as following,
   var chartData1 = [
     {\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},
     {\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},
     {\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}
     ]

I want to convert it to following,
   var chartData2 =  [
    ['Action', 'value', 'platform'],
    ['Twitter', '1.00', 2],
    ['WhatsApp', '1.00', 3],
    ['Messaging', 'WhatsApp', 4],
   ]

I have used different methods like parseJSON,map,etc , but i could not get expected results.
Can you help me out from this.

A: I'm assuming you first need to parse valid JSON string containing your data and then convert each row with object to array. And prepend whole array with array with column names. Following code will exactly do that:
var chartDataString = "[{\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},{\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},{\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}]";

var chartData = JSON.parse(chartDataString);

var keys = [];
var data = [];
var row;
for (var i = 0; i < chartData.length; i++) {
    row = [];
    for (var key in chartData[i]) {
        if (i === 0) {
            keys.push(key);
        }

        row.push(chartData[i][key]);
    }

    if (i === 0) {
        data.push(keys);
    }

    data.push(row);
}

console.log(data);

A: The following will convert it to an array, providing that it is already parsed as an object.
var chartData2 = Object.keys(chartData1).map(function(k) { return chartData1[k] });

console.log(chartData2);

A: Probably the most ideal here is to map original array to new structure:

var chartData1 = [
     {"Action":"Twitter","value":"1.00","platform":"2"},
     {"Action":"WhatsApp","value":"1.00","platform":"3"},
     {"Action":"Messaging","value":"1.00","platform":"4"}
];

var result = chartData1.map(function(el) {
    return [el.Action, el.value, el.platform];
});
result.unshift(['Action', 'value', 'platform']);

alert(JSON.stringify(result, null, 4));


text:
Q: Как присвоить значение и получить доступ к статической переменной класса, объявленной как указатель на целое, из функции main или другого класса? Есть пример (упрощённый) кода:
#include <iostream>
using namespace std;

class Foo {
private:
    static int* intptr;
public:
    void static stuff(int* p) {
        intptr = &(*p);
        //cout << *intptr << endl;
    }
};

int main() {
    int a = 33;
    Foo::stuff(&a);
}

При компиляции вылезает ошибка undefined reference to `Foo::intptr'. Подскажите, пожалуйста, решение проблемы.

A: Для статических переменных класса нужно подсказать компилятору, где сохранить все это. Самый простой способ - прямо над main написать вот такое
int* Foo::intptr = nullptr; // или чем там инициализировать.

Если стандарт (с++17) и компилятор позволяют, то можно просто вот так написать
    static inline int* intptr;

и будет тоже работать.


text:
Q: Best way to add filter to URL in .NET MVC I'll try to make this as concise as possible.

*

*Webpage contains a table that allows for filtering and sorting

*Changes to filtering and sorting should be reflected in the URL so the user can bookmark or share filtered views.

The question is: What is an effective convention of allowing all of the sort and filter syntax to be part of the URL and easily interpret/use it on the server without having to write a bunch of custom code that interprets it?
I've been doing some research and I came across the OData URI conventions and I like the way they do things.
http://www.odata.org/developers/protocols/uri-conventions
More research shows the the MVC 4 Web API allows for use of that convention by returning an IQueryable. This looks fantastic except for one part... I'm not implementing a RESTful API at this point and that's all it seems to work with. So how can I use something like OData and still return a View or PartialView? Is there something that will parse the OData URI convention into a C# object?
If anyone has any insights into this problem or suggestions, I'm all ears.

A: As for the url convention part of your question, I think you have answered your own question with OData. As for getting this data into a C# object I would use the following approach:
Use an action filter to interperet the url parameters and parse them into a c# object.
In your action filter add the url parameters to the route data and the c# object will be available in your action.
ASP.NET MVC Pass object from Custom Action Filter to Action
Take a look at the Telerik MVC grid, they use a GridAction action filter that does pretty much what you are asking.

A: I would look at custom model binding. A good overview can be found here: http://weblogs.asp.net/nmarun/archive/2010/02/25/asp-net-mvc-model-binding.aspx
It's typically used for POST requests with forms but there's no reason why you can't use it for GET requests too.
Basically, your approach should be to:

*

*Create a new Model class with your filter/sorting parameters as properties:
public class TableParameters {
     public string TableFilter { get; set; }
}

*In your Controller's Action, add the model as a parameter
 public ActionResult TableAction(TableParameters parameters) { /* Action logic */ }

*Set your parameters in the URL by saying:
 /Controller/TableAction?TableFilter=[your-filter-string]

The parameters object in your action will have the property populated with the value from the query string.


text:
Q: Getting an empty 500 http status code from Web API I have a circular object graph in my model, but that is inevitable.
As per the advice given in this article, I have used the DataContractAttribute and set IsReference = true on all members. I have also provided the DataMemberAttribute on all properties that I want to serialize.
To make sure that the serializer does not face any problem again, I have only chosen not to serialize navigational properties.
However, I still encounter an exception in my catch block. The details of the exception are as follows:
        _innerException: {"Type
'System.Data.Entity.DynamicProxies.Author_615FB9F8BB22B55A7CA168DA5ED29EC6A0B59F62FD79D1346045351BE2F163A4' with data contract name
    'Author_615FB9F8BB22B55A7CA168DA5ED29EC6A0B59F62FD79D1346045351BE2F163A4:
http://schemas.datacontract
    .org/2004/07/System.Data.Entity.DynamicProxies' is not expected.
Consider using a
    DataContractResolver or add any types not known statically to
the list of known types - for
    example, by using the KnownTypeAttribute attribute or by adding them
to the list of known types
    passed to DataContractSerializer."}

I could but do not wish to:
1) Disable proxy creation. I could remove proxy creation just for the sake of serialization, which I may do. But I also want to learn why I am still getting the exception and what I can do about it.
2) Remove the circular references. Reason: These sorts of references are very common in Entity Framework generated models. If I were to be doing a large project with 800 - 1000 classes in the model, it be a nightmare to implement it by removing circular references.
I have described the architectural elements of this little spike solution below.
Database Schema
Id  AuthorName
-------------------------------
1   Charles Dickens
2   Charles Petzold
3   Charles Darwin
4   Charles Chaplin
5   Leo Tolstoy
6   Fydor Dostoevsky
7   Ayn Rand
8   Napolean Hill
9   Claude M. Bristol
10  Edward Dwight Easty
11  O. Henry
12  William Shakespeare
13  Juwal Lowy
14  Jeffrey Richter
15  Chris Sells
16  Don Box
17  Steven Pinker
18  Jim Rohn
19  George Eliot
20  Sathyaish Chakravarthy

Id          Title                                              AuthorId
----------- -------------------------------------------------- -----------
1           Nicholas Nickleby                                  1

Id          BookId      Review
----------- ---------------------------------------------------------------
1           1           How do I know? I haven't read it.

Model
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace BookReviewsModel
{
    [DataContract(IsReference = true)]
    public partial class Author
    {
        [DataMember]
        public virtual int Id { get; set; }

        [DataMember]
        public virtual string AuthorName { get; set; }

        public virtual ICollection<Book> Books { get; set; }
    }
}

namespace BookReviewsModel
{
    [DataContract(IsReference = true)]
    public partial class Book
    {
        [DataMember]
        public virtual int Id { get; set; }

        [DataMember]
        public virtual string Title { get; set; }

        [DataMember]
        public virtual int AuthorId { get; set; }

        public virtual Author Author { get; set; }

        public virtual ICollection<BookReview> BookReviews {  get; set; }
    }
}

namespace BookReviewsModel
{
    [DataContract(IsReference = true)]
    public partial class BookReview
    {
        [DataMember]
        public virtual int Id { get; set; }

        [DataMember]
        public virtual int BookId { get; set; }

        [DataMember]
        [AllowHtml]
        public virtual string Review { get; set; }

        public virtual Book Book { get; set; }
    }
}

Controller Code
namespace BookReviews.Controllers
{
    public class AuthorController : ApiController
    {
        [HttpGet]
        public IEnumerable<Author> Index()
        {
            try
            {
                using (var context = new BookReviewEntities())
                {
                    var authors = context.Authors.ToList();

                    var str = Serialize(new XmlMediaTypeFormatter(), authors);

                    System.Diagnostics.Debugger.Break();
                    System.Diagnostics.Debug.Print(str);

                    return authors;
                }
            }
            catch (Exception ex)
            {
                var responseMessage = new HttpResponseMessage
                {
                    Content = new StringContent("Couldn't retreive the list of authors."),
                    ReasonPhrase = ex.Message.Replace('\n', ' ')
                };

                throw new HttpResponseException(responseMessage);
            }
        }

        string Serialize<T>(MediaTypeFormatter formatter, T value)
        {
            Stream stream = new MemoryStream();
            var content = new StreamContent(stream);

            formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait();

            stream.Position = 0;
            return content.ReadAsStringAsync().Result;
        }
    }
}

A: Solution:
This issue is resolved in the AspNetWebStack Nightly Build.
I have not tracked down which check-in corrects the behavior as I am following up on multiple issues.
You can update your solution to use the latest nightly packages by adding http://www.myget.org/F/aspnetwebstacknightly/ to your Package Manager config, and then explicitly updating from this additional repository.
As far as I can tell, the 1/18 nightly is stable within my solution (odata queries return MUCH faster as well.)
Workaround:
If you can't use the latest aspnetwebstack builds, there is a potential workaround if you don't require an XML formatted feed.
http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization
This document shows how to configure formatters used by web-api controllers, it also shows how to deal with circular references, and how to reconfigure/replace the default xml formatter.
As a workaround you can remove the xml formatter during Application_Start:
var xmlFormatter = config.Formatters.XmlFormatter;
if (xmlFormatter != null)
{
    config.Formatters.Remove(xmlFormatter);
}

A: I don't know WebAPI very well, but you solve the same problem in WCF by using the ProxyDataContractResolver.  Hopefully, there's a similar hook in WebAPI?


text:
Q: Exclusive object type on interface interface A {
  common: number
  onlyA: number
}

interface B {
  common: number
  onlyB: number
}

function foo(param: A | B) {
  if(param.common)
}

In this code, TS autocomplete just show me the props that are common to both objects (common), but I want it to show the props that are unique to each object with a sintax like param?.onlyA, because I want it to be OR interface A OR interface B.
If instead of | operator I use & operator, TS understands that there will always be onlyA or onlyB props, autocomplete like param.onlyA.


text:
Q: ReactJS - "react-google-maps": after clicking on a marker, no InfoWindow is displayed I am implementing Google Maps with react-google-maps and I am able to render a marker on the map. However, after clicking on the marker, the InfoWindow is not displayed. This is my approach:
import React from "react";
import { withScriptjs,
        withGoogleMap,
        GoogleMap,
        Marker,
        InfoWindow } from "react-google-maps";

const MyMapComponent = withScriptjs(withGoogleMap((props) =>
  <GoogleMap
    defaultZoom={8}
    defaultCenter={{ lat: -34.397, lng: 150.644 }}
  >
    <Marker
        position={{ lat: -34.397, lng: 150.644 }}
        onClick={this.onToggleOpen}
    >
        { props.isOpen && <InfoWindow onCloseClick={this.onToggleOpen}>asg</InfoWindow>}
    </Marker>
  </GoogleMap>
))
export default class GoogleMapsSample extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
          isOpen: false
        }
    }

    onToggleOpen(){
        console.log('x');
        this.setState({isOpen: !this.state.isOpen})
    }

    render() {
        return (
            // Important! Always set the container height explicitly

                <MyMapComponent
                    googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=AIzaSyDFD30jUKH0Cl8qrZoNCe-eEGQBIfApzE0"
                    loadingElement={<div style={{ height: `100%` }} />}
                    containerElement={<div style={{ height: `400px` }} />}
                    mapElement={<div style={{ height: `100%` }} />}
                    isOpen={this.state.isOpen}
                />

        );
    }
}

I have also tried to look if the onToggleOpen action actually triggers when is clicked, but it doesn't - the line console.log('x'); doesn't execute anything.
It looks that I am probably passing the props incorrectly, however, after trying a few approaches, I still cannot find the right one.

A: onToggleOpen function is defined in parent compoent, So you should pass it and access it as props.onToggleOpen in your MyMapComponent

A: There are a couple of things you are doing wrong and some missing props.
The below should work for you
import ReactDOM from "react-dom";

import React, { Component } from "react";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  InfoWindow
} from "react-google-maps";

const MyMapComponent = withScriptjs(
  withGoogleMap(props => (
    <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
      <Marker
        position={{ lat: -34.397, lng: 150.644 }}
        onClick={() => props.onToggleOpen()}
      >
        {props.isOpen && <InfoWindow>
hey, some info here
</InfoWindow>}
      </Marker>
    </GoogleMap>
  ))
);

class GoogleMapsSample extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isOpen: false
    }
  }

  onToggleOpen = () => {
    this.setState({ isOpen: !this.state.isOpen })
  }

  render() {
    const { isOpen } = this.state
    return (
      // Important! Always set the container height explicitly

        <MyMapComponent
          googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=AIzaSyDFD30jUKH0Cl8qrZoNCe-eEGQBIfApzE0"
          loadingElement={<div style={{ height: `100%` }} />}
          containerElement={<div style={{ height: `400px` }} />}
          mapElement={<div style={{ height: `100%` }} />}
          isOpen={isOpen}
          onToggleOpen={this.onToggleOpen}
        />

    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<GoogleMapsSample />, rootElement);


text:
Q: How To Keep Ruby Updated on Mac I keep updating my Ruby to the newest version, and it somehow keeps reverting back to the old version I had installed, 2.3.7. I'm confused how or why this is happening? How can I keep it on the newest version on my computer?

A: You need to pin the default version:
rvm use --default 2.5.3

Then check that's applied by opening a new shell:
rvm list

If it's not staying pinned it possible RVM isn't properly initialized in your shell. Check that the .profile or .bash_profile or .bashrc or whatever shell you're using has the right RVM environment setup at the bottom.

A: Suggesting to work with rvm or rbenv
rvm - rvm documentation
Installation:
RVM - copy/paste to terminal the url below.
\curl -sSL https://get.rvm.io | bash -s stable --ruby
Make sure to restart terminal after installing RVM environment has to be loaded.
Usage:
rvm list - see all installed or available ruby version in the machine.
rvm install ruby-2.5.1 - installing ruby 2.5.1 version
rvm use 2.5.1 - using specific version
rvm use --default 2.5.1 - to make it default


text:
Q: ItemAdding list field I am trying to update list field using ItemAdding,
public override void ItemAdding(SPItemEventProperties properties)
    {

        SPListItem curListItem = properties.ListItem;
        curListItem.Web.AllowUnsafeUpdates = true; // This property should be set to true for the update to go through
        curListItem["Age"] = "";
        curListItem.Update(); // This line should update the ListItem but it doesnt

    }

UPDATE
  public override void ItemAdding(SPItemEventProperties properties)
    {

        string empty = "";
        properties.AfterProperties["Age"] = empty;
        base.ItemAdding(properties);

    }

A: Use properties.AfterProperties["Age"] = "Your Value";
See Set custom field value in ItemAdding event for more information.


text:
Q: how HTTPS request is handled by IIS server I am trying to understand the working of HTTP , IIS and sql server.
I am having an IIS 7 server in my environment which is interacting with a sql database server.
The architecture is
Apache ----> IIS -----> SQL server
The Apache is a reverse proxy server which is sending the HTTP request to the IIS server and from there IIS server is interacting with the  SQL database connecting by different application pools for different applications.
My query is if some request has been forwarded by the Apache server and it has reached the IIS ; after that, if the network between the Apache and IIS is having any packet drops ;

*

*Will that have any affect to the performance of IIS and database server?

*Will there be any long running queries in the worker process of the IIS? Because my concern is what will happen after the queries that has successfully executed in the Database server. But since the network between the IIS and Apache is broken how can they be forwarded further to the Apache and further to the end user.

*Will these queries keep on holding the resources till they are forwarded from IIS to Apache? Because they have successfully completed their tasks but because of network issue they are not being forwarded further. Or are such request stacked up somewhere by the IIS to free up the resources for the upcoming requests??

A: Once a request has reached IIS it will go and do the required actions, and format the reply. It will try to send the reply to the requestor but if the link has gone, it will be unable to. It will then abandon the request. Resources it is holding for that request will be freed.
To get the data it had for you, Apache has to repeat the request.


text:
Q: How to limit items per order line but not per order I have a Woocommerce site with just one customisable product. I'd like the customer to be able to add multiple instances of that product to their order, but individually. ie to remove the quantity per line item.
So the order summary would look like:
Product A with options 123 = £10
Product A with options 345 = £20
Rather than:
Product A x2
How can I do this?


text:
Q: Youtube api v3 captions download always return 403 - Forbidden access Since recent changes in youtube api v3 captions download, the call to download transcript is always returning 403 Forbidden Access, How can we make this work?
FYI, the access token was generated from service account


text:
Q: jQuery Draggable Handler inside IFrame What a mouthful.
Basically I have a parent
 and inside that an . I need an element inside the iframe to be the handle to drag the parent div. Is this even possible?
I have tried:
$(node).draggable("option","handle",$('iframe',node).contents().find('#handle'));
$(node).draggable("option","handle",$('iframe',node).contents().find('#handle')[0]);

It is targeting the right DOM element but it just won't drag. It might be possible to overlay a hidden div ontop of the iframe but I have found the iframe takes the event over the div when position is absolute. Strange.

A: try this
$('#Div').draggable({ iframeFix: true });
this should work

A: I decided to take a stab at this and boy, it's a lot of work with little progress using an internal iframe node as a handle. Anyway, here are two solutions, the first one doesn't work really well, but if you can get it to work, it may be more desirable.
main.html (plagiarized from the demo)

I can be dragged only by this handle

inner-handle.html

handle

JavaScript
$(function () {
    var moveEvent;
    $(document).mousemove(function (e) {
        moveEvent = e;
    });

    $("#draggable").draggable();
    $('iframe', '#draggable').load(function () {
        $('iframe', '#draggable')[0].contentWindow.$('#innerHandle').mousedown(function (e) {
            $('#draggable').draggable().data('draggable')._mouseDown(moveEvent);
            return false;
        });
    });
});

It took me a while to find something that "worked." The problem here was that since the mousedown event occurred on an element inside the iframe, the mouse event is relative to the iframe, not the main document. The workaround is to have a move event on the document and grab the mouse position from there. The problem, once again, is that if the mouse is inside of the iframe, it is "not" moving according to the parent document. This means that the drag event only happens when the mouse reaches the edge of the iframe into the parent document.
A workaround for this might be to manually generate events with the calculated position of the iframe relative to its mouse movement. So when your mouse moves within the iframe, calculate its movement using the coordinate of the iframe to the parent document. This means that you need to use the event from the mousedown and not the mousemove,
$('iframe', '#draggable')[0].contentWindow.$('#innerHandle').mousedown(function (e) {
    // do something with e
    $('#draggable').draggable().data('draggable')._mouseDown(e);
    return false;
});

The second solution is the way you have mentioned, have an absolute positioned div over the iframe itself. I have no trouble in getting the div to be on top of the iframe, that is,

I can be dragged only by this handle

The problem with your div being behind the iframe might be because the z-index is off. If you declare your div before the iframe and you didn't specify the z-index, then the iframe will be on top.
Whichever way you choose, good luck!

A: what happens when you do this (with firebug activated):
var frameContent = $('iframe',node).contents()
var handle = frameContent.find('#handle');
console.debug(frameContent, handle)

Does handle contain a list of elements? And if so, look carefully at the Document object which is frameContent - is the URL "about:blank"? It's just a hunch, but if you get these outputs, it's probably executing the jQuery selector before the frame content has loaded (i.e., before the #handle element exists).
In which case, you can add an event to the IFRAME'd document, and communicate with the parent frame via window.parent.


text:
Q: Which Windows Server 2008 Backup Do I need? I am looking at creating backups of our C: drive in case we have a major HD or OS failure... This is a web server, so I want the fastest way of restoring IIS with all the settings and all the program files (SQL Server etc.) and read the built in 'Windows Server 2008 Backup' is what I should be using.
So I basically want the C drive backed up so I can restore it to how it was before a failure...

*

*But I am confused by the options, do I need to be choosing bare metal recovery?

*Or just The C Volume and the 'System State'?

*Does system state include IIS settings etc..?

*Is bare metal used if I won't be recovering from a fresh Win2008 install?

Sorry for all the questions I just want to make sure I choose the correct options for what I need

A: For the OS/ System recovery you want to do a system state backup.  This will include the registry, System Files, IIS metadata, etc.  For a full list see: System State
The OS/ System State backup will NOT backup your actual data, however.  For that, you need to backup the SQL/ other data separately.  Your restore process would include booting to the 2008 server dvd, choosing repair system, and selecting the backup to restore from.  Once the OS is restored you would then restore the SQL/ other data.


text:
Q: Is there a way to disable R abbreviation in list indexing? at the moment I'm quite stunned by this piece of code:
bad.list <- list(xx = "A")
print(is.null(bad.list$x))   # FALSE: Bad since there is no x
print(is.null(bad.list$xx))  # FALSE: Correct since there is xx
print(is.null(bad.list$xxx)) # TRUE:  Correct since there is no xxx

Normally you would expect is.null(bad.list$x) to be evaluated as TRUE since there is no x in the list. But since R allows you to use abbreviations it evaluates to FALSE. In my situation I can't change the names of the list entries.
Is there a way to force R to disable abbreviations?

A: You can use the [[...]] notation:
bad.list <- list(xx = "A")
print(is.null(bad.list[["x"]]))   # is TRUE now
print(is.null(bad.list[["xx"]]))  # FALSE: Correct since there is xx
print(is.null(bad.list[["xxx"]])) # TRUE:  Correct since there is no xxx


text:
Q: whats wrong in below code for searching a word in a file and writing that too another file? I am unable to find whats wrong in this code. It is not creating new file i.e., FinalResult.txt.
import os

log = open('C:\\Sanity_Automation\\Work_Project\\Output\\Result.doc','r')
log_read=log.readlines()
x="FAIL"
if x in log_read:
    with open('C:\\Sanity_Automation\\Work_Project\\Output\\FinalResult.txt', 'w') as fout:
        fout.write("\n")
        fout.write(x)

One more thing. When it finds that word, it should write complete line of text where it was found (instead of just "FAIL").

A: log_read is a list (as the result of .readlines).
If you test x in log_read, you're asking if any item in the list is equal to FAIL.  In other words, any entire line.
Do you mean the following?
for line in log_read:
   if x in line:
      # found it

A: log_read is a list of each line in the file. I think what you wanted to do was see if a word existed in the whole file instead of the word being one line.
for line in log_read:
    if x in line:
        with open('C:\\Sanity_Automation\\Work_Project\\Output\\FinalResult.txt', 'w') as fout:
            fout.write('\n')
            fout.write(line) # Writes the line to the file as well

A: Also, you are reading for a ".doc" file, which i suppose is a Microsoft Word file.
You should consider converting this to a flat text file

A: It has not created FinalResult.txt as there may not be "FAIL" in the 'log_read'.  BTW, log_read is list. you are not searching in each line in the list instead searching against whole line, which will(in most cases) fail.
Do this to write whole line in file, there is not much change.
  import os

        log = open('C:\\Sanity_Automation\\Work_Project\\Output\\Result.doc','r')
        log_read=log.readlines()
        x="FAIL"
        for line in log_read:
            if x in line:
                with open('C:\\Sanity_Automation\\Work_Project\\Output\\FinalResult.txt', 'w') as fout:
                    fout.write("\n")
                    fout.write(line)

A: Well you have defined X= 'Fail'. If you write x then only Fail will be written.
You should do
for line in log_read:
    if x in line : fout.write('%s\n'%line)

Moreover open the output handle only once (before the loop). Or get all writable lines first and then write once (for efficiency)
result = []
for line in log_read:
    if x in line: result.append(line)
if result: fout.write('\n'.join(result))


text:
Q: How do you handle conditional html formating? In one of my html pages I have the following:
{% for bet in recent_bets %}
    {% if bet.status__name == "Won" or bet.status__name == "Half Won"%}

    {% elif bet.status__name == "Lost" or bet.status__name == "Half Lost"%}

    {% elif bet.status__name == "Void" or bet.status__name == "Cancelled"%}

    {% elif bet.status__name == "Cash Out" %}

{% endif %}

Based on what the bet.status__name is, it returns a different background color ex bg-success.
Apart from this case, I have a few other cases similar to that.
I would like to know how do you handle these things. Just leave it in the html, create a filter/tag that returns the appropriate html or something else ?

A: You should definitely encapsulate the logic about which kind of status leads to which CSS class. You can create a filter that takes a bet and returns the right CSS class:

This way you can also reuse it with Bootstrap's alert component etc.


text:
Q: Stranded Deep - Can't water plot If I have a bucket of fresh water and try to long press on a plot (which has no water), my character drinks the water. If my character isn't thirsty, it just does nothing. Is there a special technique to watering plots?
I also noticed that the plant, though dead, still produces fruits (although they seem to always be spoiled).


text:
Q: Writing multiple, non-numeric sets of data to .txt file using numpy #This provides desired format, but only works with one variable at a time
np.savetxt("test2.txt", list(zip(shared_A_B)), fmt='%.18s',delimiter='\t')

#Attempted to write for loop but, this only stores the last variable
cut2=(shared_A_B, shared_A_C, shared_A_B_C..)
for i in cut2:
   np.savetxt("ReportName3.txt", list(zip(i)), fmt='%.18s')

#example input set data
shared_A_B= {'Rik',
            'Rik5',
            'Rikb4'}

#example output written .txt file, this is works but only for idividual variables
shared A_B=Rik
           Rik5
           Rikb4

I would like to assign the set data contained within each variable to its own column (primary issue), and eventually define each column with the variable name (this is secondary issue). The only approach I can think of, is it to write a for loop, however this overwrites the data of the preceding variable and does not produce additional columns. I have tried making a numpy array but I ran into errors with dimension requirements, and I think there are probably more practical approaches. If anyone can offer advice, alternative approaches, or a solution, it would be greatly appreciated. Cheers
Alternatively: I have data already successfully written to a .txt file
format=Shared A and B {'Got1', 'Arg2', 'Fpgs'..}
Is there an approach to transpose this data?


text:
Q: Mate desktop freezes the connection over RDP while unpainting GUI elements I have installed Ubuntu Server 16.04.6 LTS on a remote VM(on vSphere) which needs to be connected through a VPN. I mostly access it through SSH. But I have installed Mate Desktop Environment(along with xrdp) to access some GUI components for some work.  I use Remote Desktop Connection(RDC) program on Windows 10 to login into GUI.
Whenever I minimize or close an application the graphical "unpainting" takes some time to finish. And that process will get stuck in between the process many times. I usually kill it forcefully through Task Manager tool. When I re-login I see the remote machine state as it is and no application is crashed during that process. So it only crashes RDC's connection but the OS does not hang.
Is there a way to tweak UI to use less resources over RDC application?

Slow action of unpainting.


text:
Q: Can I use Google Auth 2.0 from any origin? I develop modal window with React.js, that can be distributed for several sites via some kind of web application market.
So I faced the issue, that for any website, that would install this extension (btw it's builded to a simple html page + couple of js files, so app will be hosted directly on website of even customer), Google auth error will throw exception of invalid origin.
So is there any way to find a workaround for my case?
btw now I'm using react-google-login library

A: Google allows you to set multiple URIs. Just take a look in the settings.


text:
Q: How to get the value with one of tuples? Here is my code
crel = {('hanso', 'unif', 'manjo', 'sandi'): ['coiu','lemin'],('yyy', 'qe', 'tgg', 'ijg'):['KOH','TYH']}

key = 'tgg'
for k, v in crel.items():
    if key in k:
        print(v)
    else:
        print('no result')

Output:
no result
['KOH', 'TYH']

I want to use one of tuples to get all the values in the list, but there is always "no result" comes out along with my desired result.
I know it's because I use "for" loop, but I have tried really hard to avoid this happening.
How do I use 'tgg'  to get the result like this:
['KOH', 'TYH']

Or, use 'hanso' to get the result like this:
['coiu','lemin']

Could someone please help me use one of the tuples and show the corresponding value?
When there is really not a match, show 'no result'

A: crel = {('hanso', 'unif', 'manjo', 'sandi'): ['coiu', 'lemin'],
        ('yyy', 'qe', 'tgg', 'ijg'): ['KOH', 'TYH']}

key = 'tgg'
values = [crel[k] for k in crel.keys() if key in k]
if len(values) > 0:
    for val in values:
        print(val)
else:
    print("no result")


text:
Q: How compare two objects in javascript and create new object whose values are diffrent var obj1={
  name:"jhon",
  age:"26",
  role:"intern"
}

var obj2={
  name:"jhon berner",
  age:"26",
  role:"intern"
}

//so the name value has changed in the above object so I need new object like
expected output
var newobj={
name:"jhon berner"
}

// can I do like this for objects

A: I was not sure which value you wanted as an output for different keys, so I added both different values in an array... you can modify it based on your requirement.

Assumption: keys present in both objects are the same.

var obj1 = { name: 'jhon', age: '26', role: 'intern' };
var obj2 = { name: 'jhon berner', age: '26', role: 'intern' };
var newObj = {};
Object.keys(obj1).forEach((key) => {
    if (obj1[key] !== obj2[key]) {
        newObj[key] = [obj1[key], obj2[key]];
    }
});

console.log(newObj);


text:
Q: How to avoid hardcoding a control's name in a data verification rule function Goal: Avoid hard coding the control's name in my VBA data verification function
I have a control which has a data validation rule.
It calls a user defined function that measures how many decimals have been entered in the control.
Function GetDPstr() As Integer
    ' Returns for the number of decimal places in a string

    Dim NumberBox   As Control
    'Error here: I would like to be able to implicitly access the control's value without
    'having to hard code the control's name so I can reuse the code for other controls
    'as opposed to using "Me.Controls!ControlName"
    Set NumberBox = Me.txtbox

    If Len(NumberBox) - Len(Replace(NumberBox, ".", "")) = 0 Then        ' test for decimal point separator
    GetDPstr = 0
Else
    GetDPstr = Len(RTrim(NumberBox)) - InStr(RTrim(NumberBox), ".")
End If
End Function


text:
Q: ng2-split-pane adjusting height of a vertical pane after initial render Once the page initializes, I can't find a way to resize the height of a vertical panel. If I select the split pane component with jquery and set a min height the component does not respond by resizing its separator or internal panel. Is there any way to change the height of a vertical panel dynamically after the initial page load?

A: Found a way, just needed to target .v-outer instead of the actual container.


text:
Q: MySQL Create View I tried to create a view for the table VIEW in information_schema.
CREATE OR REPLACE VIEW Research as
select * from VIEWS;

But I'm getting an error like:
Error Code: 1044. Access denied for user 'root'@'localhost' to database 'information_schema'
What is the problem here? I can select other tables from the schema.

A: you should run mysql -u root -p in bash, not at the MySQL command-line. If you are in mysql, you can exit by typing exit.
NOTE: use 'quit' to exit the mysql,then you will be in bash


text:
Q: Add div to the date showing in html and separate the days and month I have some list of dates and I want to add div to the date and separate the days and months to a different div.

30/11/2016 -
  Dummy Text

I want to select and add div to the date. I also want to separate the days and months like this. Any help appreciated in advance.

30

Nov

2016

  Dummy Text

I have tried the append method but I am not able select the date and store in a variable.

A: You can use .prepend( function ) to insert new HTML content in first of element.

var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];

$(".campaign").prepend(function(){
  var dates = $(this).contents()[0].nodeValue.trim().match(/\d+/g);
  $(this).contents()[0].nodeValue = "";
  return '\

\

'+dates[1]+'
\

'+monthNames[+dates[0]-1]+'
\

'+dates[2]+'

 \

';
});

11/30/2016 -
  Dummy Text

A: Check whether this is working for you?

$('#convert').click(function(){
  let date = $('.campaign').text().split('/');

  let dateDiv ='
'+date[1]+'
';
  let monthDiv = '
'+date[0]+'
';
  let yearDiv = '
'+date[2]+'

';

  $('.campaign').html(dateDiv + monthDiv + yearDiv)

})

11/30/2016 -
Dummy Text

<button id="convert">Convert</button>

A: Bit late to the party. My solution uses date parsing to extract date results. Prepending divs is much simpler in this case.

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];

var campaign = $($('.campaign')[0]);
var dateString = campaign.text().split('-')[0];
var date = new Date(Date.parse(dateString));

campaign.contents()[0].nodeValue = "";
campaign.prepend('
'+date.getFullYear()+'
');
campaign.prepend('
'+months[date.getMonth()]+'
');
campaign.prepend('
'+date.getDate()+'
');

11/30/2016 -
Dummy Text

A: Try it.

$('.campaign').each(function(){

 var dateStr = $(this).text().split('/'),
  dateDD = dateStr[0],
  dateMM = dateStr[1],
  dateYY = dateStr[2];

 function GetMonthName(monthNumber) {

  var months = ['Jan', 'Feb', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil', 'Août', 'Sept', 'Oct', 'Nov', 'Dec'];
  return months[monthNumber - 1];

 }

 var newDate = '
'+'
'+'
'+dateStr[0]+'
'+ '
'+GetMonthName(dateMM) + '
 ' + '
'+dateStr[2]+'
'+'
'+'Dummy Text'+'
';
 $('.test').append(newDate);

});

30/11/2016

Dummy Text

</test>


text:
Q: How to make font-face work with all letters I am hoping this is a CSS clash some place that I am missing, but the site is here:
https://bbking2019.wpengine.com/
The code is here:
/*Set the font face for h3*/
@font-face {
  font-family: carrotflower;
  src: url('/wp-content/uploads/fonts/Carrotflower.eot') format('embedded-opentype'),
       url('/wp-content/uploads/fonts/Carrotflower.woff') format('woff'),
       url('/wp-content/uploads/fonts/Carrotflower.woff2') format('woff2'),
       url('/wp-content/uploads/fonts/Carrotflower.ttf') format('truetype');
}

h3{
    font-family: carrotflower !important;
}

This works on all the letters EXCEPT the capital V in Visitor Testimonials - when editing in the browser tools a lowercase v works perfectly with the font.
Any ideas on how to make the capital V work would be fantastic.
Thanks in advance!
An example can be messed with here: https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_font-face_rule
Just change out the url for the woff file to https://bbking2019.wpengine.com/wp-content/uploads/fonts/Carrotflower.woff
Then in the type some text and add a v and a V - the capital is still not working.

A: Thanks to some digging from Rene van der Lende and Joel, indeed the V was/is not implemented in the font table. We are going to work around it with a similar font and contact the creator.
Thanks everyone for your efforts.


text:
Q: How to do to make clickable only parent but not children? Here is my XML
<android.support.v7.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="4dp">

        <LinearLayout
            android:id="@+id/commander_image_selector"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical"
            android:background="?attr/selectableItemBackground"
            android:padding="15dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingBottom="15dp"
                android:paddingEnd="15dp"
                android:paddingLeft="15dp"
                android:paddingRight="15dp"
                android:paddingStart="15dp"
                android:text="@string/image_chooser_txt"
                android:textAlignment="center" />

            <ImageView
                android:id="@+id/commander_result_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:minHeight="150dp"
                android:minWidth="200dp"
                android:padding="5dp"
                android:scaleType="centerInside"
                android:src="@mipmap/default_image"
                android:contentDescription="@string/chosen_image" />
        </LinearLayout>
    </android.support.v7.widget.CardView>

I would like to set android:background="?attr/selectableItemBackground" on the LinearLayout if i click on it or on the imageView.
Is there any solution ? It is like pointer-event: none in css

A: By default, a LinearLayout is not clickable, and will not receive touch events. You can simply indicate that your LinearLayout should be clickable, an d your ImageView is not by adding:
<LinearLayout
        android:id="@+id/commander_image_selector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="vertical"
        android:background="?attr/selectableItemBackground"
        android:padding="15dp"
        android:focusable="true"
        android:clickable="true">

          <ImageView
            android:focusable="false"
            android:clickable="false"
            />
       />

A: Edit
<android.support.v7.widget.CardView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="4dp">
    <LinearLayout
        android:id="@+id/commander_image_selector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:addStatesFromChildren="true"
        android:background="?attr/selectableItemBackground"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="15dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="15dp"
            android:paddingEnd="15dp"
            android:paddingLeft="15dp"
            android:paddingRight="15dp"
            android:paddingStart="15dp"
            android:text="@string/image_chooser_txt"
            android:textAlignment="center" />
        <ImageView
            android:id="@+id/commander_result_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:contentDescription="@string/chosen_image"
            android:minHeight="150dp"
            android:minWidth="200dp"
            android:padding="5dp"
            android:scaleType="centerInside"
            android:src="@mipmap/default_image" />
    </LinearLayout>
</android.support.v7.widget.CardView>

With android:addStatesFromChildren="true", selectableItemBackground works for children. Then I just have to set my imageView non clickable programmatically (doesn't work in xml) and it works like I wanted to


text:
Q: $\vert G \vert < \infty$, $A,B,C \leq G$, $B \leq A \Rightarrow \vert A:B \vert \geq \vert C \cap A : C \cap B \vert$ I am stuck with the following problem. I am sure it cannot be that hard since it is intuitively true, but I can't find a way to prove it.
Let $A,B,C \leq G$ where $G$ is a finite group. Suppose moreover that $B \leq A$. Then $\vert A:B \vert \geq \vert C \cap A : C \cap B \vert$.

A: Asked is to show that $\frac{|A|}{|B|} \geq \frac{|A\cap C|}{|C\cap B|}$ since everything is finite.
We may use that $|A|\cdot |C| = |A\cap C|\cdot |AC|$ and similarly for $B$ and $C$, this amounts to showing that $|AC| \geq |BC|$, which is obvious since $B\subseteq A$.

A: You don't need G to be finite.
You can construct the function $\begin{array}{rcl} f: (C\cap A)/ (C\cap B) & \to & A/B \\ x \cdot C\cap B & \to & x \cdot B \end{array}$
You can verify that f is well defined and injective and this gives you the desired inequality.


text:
Q: How to vectorize a pandas DateOffset? I need to offset a DateTimeIndex index by a CustomBusinessDay, a trading day offset, which I instantiate like so:
import pandas_market_calendars as mcal
TCal = mcal.get_calendar('NYSE')
from pandas.tseries.offsets import CustomBusinessDay
TDay = CustomBusinessDay(calendar=TCal, holidays = TCal.holidays().holidays)

Applying this offset to a 'date' level of a MultiIndex:
df.index.set_levels(df.index.levels[0] + TDay, level=0)
yields the non-vectorized DateOffset being applied warning:
python3.8/site-packages/pandas/core/arrays/datetimes.py:692: PerformanceWarning: Non-vectorized DateOffset being applied to Series or DatetimeIndex

Is there a way to vectorize my CustomBusinessDay, or produce an analogous date offset that is vectorized? Thanks!
UPDATE: Here's the code that exemplifies the dataframe I am working with:
import numpy as np
import pandas as pd

dates = list(map(pd.to_datetime, ['2020-07-16', '2020-07-17']))
strings = ['A', 'B', 'C', 'D']
df = pd.DataFrame(
    index=pd.MultiIndex.from_product([dates, strings], names=['date', 'string']),
    data=np.random.uniform(size=(len(dates) * len(strings), 2))
)


text:
Q: How to use limit correctly in Codeigniter Framework PHP In my project I want to show 3 rows, for which i use limit('3'), but when my result is greater then 3, content is not showing.
if i limit increase from 3 to 5 or 6 then items again start to show.
how to fixed this problem, so that if item count is more, it shows just 3?
Here is database code, written into Model:
public function select_all_contenta()
{

 $this->db->select('*');
 $this->db->from('content');

 $this->db->order_by('date_add','DESC');
 $this->db->limit('3');

 $query_result=$this->db->get();
 $allcontent_infoa=$query_result->result();
 return $allcontent_infoa;
}

A: public function select_all_contenta() {
   $this->db->from('content');
   $this->db->order_by('date_add','DESC');
   $this->db->limit('3');
   $query_result = $this->db->get();
   $allcontent_infoa = $query_result->result_array();
   return $allcontent_infoa;
}

A: change
   $this->db->limit('3');

into
   $this->db->limit ( 3 );

It should be number not string value (limit the number of rows you would like returned by the query)

A: Try to change this code
$this->db->limit(2,0); //$this->db->limit(3,0);

A: your code is not optimised.
try this instead
public function select_all_contenta()
{
  $q = $this->db->get('content' , 3)->order_by('date_add','DESC');
  return $q->result();
}


text:
Q: What are the differences between a VM image and a Docker image? Are there any differences in images of Docker and Virtual Machine?
Except the image formats, I couldn't find any info on this anywhere.
Please comment out on the things like image size, instance creation time, capture time, etc.
Thanks!

A: These are some differences between a docker and a VM image which I could list out:
1. Snapshot process is faster in Docker than VMs
We generally start with a base image, and then make our changes, and commit those changes using docker, and it creates an image. This image contains only the differences from the base. When we want to run our image, we also need the base, and it layers our image on top of the base using a layered file system. File system merges the different layers together and we get what we want, and we just need to run it. Since docker typically builds on top of ready-made images from a registry, we rarely have to "snapshot" the whole OS ourself. This ability of Dockers to snapshot the OS into a common image also makes it easy to deploy on other docker hosts.
2. Startup time is less for Docker than VMs
A virtual machine usually takes minutes to start, but containers takes seconds, and sometime even less than a second.
4. Docker images have more portability
Docker images are composed of layers. When we pull or transfer an image, only the layers we haven't yet in cache are retrieved. That means that if we use multiple images based on the same base Operating System, the base layer is created or retrieved only once. VM images doesn't have this flexibility.
5. Docker provides versioning of images
We can use the docker commit command. We can specify two flags: -m and -a. The -m flag allows us to specify a commit message, much like we would with a commit on a version control system:
$ sudo docker commit -m "Added json gem" -a "Kate Smith"
0b2616b0e5a8 ouruser/sinatra:v2
4f177bd27a9ff0f6dc2a830403925b5360bfe0b93d476f7fc3231110e7f71b1c

6. Docker images do not have states
In Docker terminology, a read-only Layer is called an image. An image never changes. Since Docker uses a Union File System, the processes think the whole file system is mounted read-write. But all the changes go to the top-most writeable layer, and underneath, the original file in the read-only image is unchanged. Since images don't change, images do not have state.
7. VMs are hardware-centric and docker containers are application-centric
Let's say we have a container image that is 1GB in size. If we wanted to use a Full VM, we would need to have 1GB times x number of VMs you want. In docker container we can share the bulk of the 1GB and if you have 1000 containers we still might only have a little over 1GB of space for the containers OS, assuming they are all running the same OS image.
8. Supported image formats
Docker images:

*

*bare. The image does not have a container or metadata envelope.

*ovf. The OVF container format.

*aki. An Amazon kernel image.

*ari. An Amazon ramdisk image.

*ami. An Amazon machine image.

VM images:

*

*raw. An unstructured disk image format; if you have a file without an
extension it is possibly a raw format

*vhd. The VHD disk format, a
common disk format used by virtual machine monitors from VMware, Xen,
Microsoft, VirtualBox, and others

*vmdk. Common disk format supported
by many common virtual machine monitors

*vdi. Supported by VirtualBox
virtual machine monitor and the QEMU emulator

*iso. An archive format
for the data contents of an optical disc, such as CD-ROM.

*qcow2.
Supported by the QEMU emulator that can expand dynamically and
supports Copy on Write

*aki. An Amazon kernel image.

*ari. An Amazon
ramdisk image.

*ami. An Amazon machine image.


text:
Q: jQuery scrollTo plugin does not take "over" argument into account These two lines scroll to exactly the same place (the left side of the target element)
$("#gallery").stop().scrollTo(thisP, 400, {offset:{top:0, left:-$(window).width()/2}}, {over:0.5});
$("#gallery").stop().scrollTo(thisP, 400, {offset:{top:0, left:-$(window).width()/2}});
Note: #gallery is a div with a horizontal scrollbar, and thisP is an element contained inside that div
The documentation says {over:0.5} should cause it to scroll to the center of the target, but it doesn't seem to do anything. I also tried {over: {top:0, left:0}}, and changing the order of offset and over, but it still doesn't scroll to the middle of the target. :<

A: scrollTo function takes only three arguments, the third one is an object, containig properties. That's why fourth argument is just ignored.
Try to do this:
$("#gallery").stop().scrollTo(thisP, 400, {offset:{top:0, left:-$(window).width()/2}, over:0.5});


text:
Q: Sql server covering index and join I understand that covering index will speed up read operation if all the columns in select list are covered in the index.
But what if I select and filter on columns in other tables as well? Would covering index still help in this case?
Here is my thought: Since the join would force the clustered key to be matched, so the clustered key look up couldn't be avoided. And by finding the clustered key we would have all the information we need thus covering index wouldn't help to speed up the read.

A: Not sure what you mean by:

the join would force the clustered key to be matched.

Non-clustered indexes include the clustered index key (needed as the unique row locator).  Consequently, a non-clustered index can cover a query as long as the query references only columns in the clustered index key, non-clustered index key columns, and included columns.
A potentially covering non-clustered index might not be used if other indexes are available to process the query more efficiently depending on the columns specified in WHERE, JOIN, or ORDER BY clauses.


text:
Q: html php javascript form popup Apologies for the ambiguous title, it just goes to show how confused I am with this one.
change image

The link above is inside a form and is supposed to allow a user to change the image on an article. The functional php side of things is sorted - uploading the image, changing the image etc, but this will require the main form being submitted which is fine for the initial upload - not so much for the edit.
When the user clicks the "change image" link, I would ideally like to process that particular request alone in a different form, then update the parent page. I thought of doing it with a javascript new window popup which would have been ideal, except that I can't figure out how to pass the article_id as well as the img_id to the new popup page but above all... is this the most efficient way of doing this nowadays?
If not, How do I carry out this task? I have thought of ajax, jquery... but the same issue of passing the article_id and img_id still limits me.
I hope all of this makes sense and thanks in advance
ps: An article can have multiple images and article id is dynamic.

A: ajax sounds good to me.
may be you try something like this (jquery)?!
$.ajax({
  type: "POST",
  url: "page.php",
  data: { article_id: 123, images: { i1: "img1", i2: "img2" } }
}).done(function( msg ) {
  alert( "done: " + msg );
});

for further information and examples: http://api.jquery.com/jQuery.ajax/

A: Check this up: http://www.malsup.com/jquery/form/ - jQuery is a prerequisite but plugin allows you to send form elements via ajax, including file fields using simple API and does all heavy lifting for you.

A: why cant u receive article_id and img_id?
if you use:
edit

u can get article_id and img_id in $_GET
however, this is a oldfashioned way getting this done.


text:
Q: Search Results Web Part - Hide pages based on Custom field I have a Search Results Web Part (SRWP) and there are few Pages which are based on Content Type, that content type contains a field "Visibility". There is a custom web part which searches for this content type pages and ignores the one's having Visibility set to false.
But since SRWP don't know about this field, it still shows up the one's having this field set to false.
Is there a way to customize SRWP to not show Pages where this custom field is set to false?
Or is there a way to completely ignore this content type in SRWP (since we have a separate page for searching these content types)?

A: You should be able to use the "Append text to Query" property on the Search Core Results webpart:

*

*Search Core Results web part

*Search Core Results Action Links

*Results Query Options

*Append Text to Query

Try to append something like NOT YOURPROPERTY:1
Hopefully this will give you all pages without your property, or with your property set to 0 (false)
http://maxderungs.wordpress.com/2012/05/26/using-append-text-to-query-in-search-core-results/