text:
Q: Как передать значение переменной slug из view в controller? protected function findModelBySlug($slug) {
    if (($model = Ru::find()->where(['slug' => $slug])) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException();
    }
}

public function actionView($slug) {

    return $this->render('view', [
                'model' => $this->findModelBySlug($slug),
    ]);
}

нужно передать к примеру сюда
namespace app\controllers;

use yii\web\Controller;

class NewsController extends Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }
}

A: Вопрос твой вообще не понятен... перефразировал бы его.
и это бы изменил:
protected function findModelBySlug($slug)
{
    if (($model = Ru::find()->where(['slug' => $slug])) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException();
    }
}

на это
protected function findModelBySlug($slug)
{
    if (($model = Ru::find()->where('slug=:slug', [':slug' => $slug])) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException();
    }
}

а то получается, то, что передается пользователем то и летит в базу в запрос сразу

A: Тут есть некая неястность для меня.
Но судя по всему это 2 разных контроллера.
в actionView()  вы отдаете вид и передеаете туда модель, если вы хотите с этого экшене перенаправиться в NewsController actionIndex , то пропишите так
return Yii::$app->response->redirect(['news/index', 'model' => $this->findModelBySlug($slug)]);

само собой если у вам в базовом варианте идете рендер вида, то вам нужно задать некое условие при котором вы хотите делать перенаправление
а в actionIndex можете написать так actionIndex($model = null)
тоесть если вы не передадите параметр - ошибки не будет


text:
Q: How to remove title from woocommerce_single_product_summary hook? On my product template, I execute this action :
<?php
    /**
     * woocommerce_single_product_summary hook.
    *
    * @hooked woocommerce_template_single_title - 5
    * @hooked woocommerce_template_single_rating - 10
    * @hooked woocommerce_template_single_price - 10
    * @hooked woocommerce_template_single_excerpt - 20
    * @hooked woocommerce_template_single_add_to_cart - 30
    * @hooked woocommerce_template_single_meta - 40
    * @hooked woocommerce_template_single_sharing - 50
    */
   do_action('woocommerce_single_product_summary');
?>

What I want is do remove the woocommerce_template_single_title  hook so in my functions.php file I wrote this code :
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 1);

But it does not work and I don't know how.
Thanks for your help
!! EDIT !!
Nevermind I solved it by writing this:
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 5);

The priority have to match

A:
The author has added the one-liner to his question; as suggested by @Bugs, here it is as an answer.

// Remove title hook Woocommerce
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 5);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find out which app is using Bluetooth device I noticed that my MacBook is connected to my Kevo bluetooth lock.  This lock is supposed to connect with an iOS app, but there is no macOS app that I'm aware of, and I have never told my computer to pair with it.  I want to figure out why it's connected to my laptop and what data has been exchanged.  I tried log show --last 24h | grep Kevo but that shows nothing.  That's interesting, since there are lines in the log mentioning my trackpad by name every time it connects.  I'm just updated to High Sierra 10.13.5, and I never noticed this happening before on Sierra.
Edit:  After disconnecting the Kevo in the dropdown menu, it disappeared, so I am no longer able to reconnect to it.

A: Sometimes your iCloud account will share Bluetooth authentications across iOS and macOS devices for easier pairing. Take for instance AirPods will automatically show up in your Mac after you've paired them with your iPhone. You used to be able to turn this off in the iCloud settings -> Documents and Data option.


text:
Q: Installation of Tkinter Where can I download this programm?

A: Any recent version of Python should come with Tkinter support.  To my knowledge, you shouldn't need to install anything else.

A: As a standard python library, Tkinter is part of any standard Python installation. You can can get a standard python installation at http://www.python.org/download/.

A: If you worked on linux , and you don't have the root privilege . You need to install python locally. You can't use like the following commands:
apt-get install python-tk
sudo apt-get install python-tk

You can get the tcl/tk right here http://www.tcl.tk/software/tcltk/download.html. And then refer to this Install tkinter  and python locally


text:
Q: Execution failed for task ':path_provider_android:extractDebugAnnotations' Could not resolve all files for configuration ':path_provider_android:detachedConfiguration2'.

Could not download intellij-core-30.1.2.jar (com.android.tools.external.com-intellij:intellij-core:30.1.2)
> Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/external/com-intellij/intellij-core/30.1.2/intellij-core-30.1.2.jar'.
> Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/external/com-intellij/intellij-core/30.1.2/intellij-core-30.1.2.jar'.
> dl.google.com
Could not download kotlin-compiler-30.1.2.jar (com.android.tools.external.com-intellij:kotlin-compiler:30.1.2)
> Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/external/com-intellij/kotlin-compiler/30.1.2/kotlin-compiler-30.1.2.jar'.
> Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/external/com-intellij/kotlin-compiler/30.1.2/kotlin-compiler-30.1.2.jar'.
> No such host is known (dl.google.com)


text:
Q: Oracle - replacing & with OEM_sqlplus_input_finished in select query select * from tableName where somecode = '$$$$$$$&8Y~$$$$'

when I ran this query in SQLPlus Worksheet, I get output like this:

Enter value for 8y: old   2: And somecode = '$$$$$$$&8Y~$$$$')
  new   2: And somecode  = '$$$$$$$OEM_sqlplus_input_finished~$$$$')
no rows selected

My question is, if this query is executed as it is from ASP.NET application using OracleConnection and OracleCommand (Command type as text), will it get executed as query 1 or 2?
1. select * from tableName where somecode = '$$$$$$$&8Y~$$$$'
2. select * from tableName where somecode = '$$$$$$$OEM_sqlplus_input_finished~$$$$'

If later is the case, how I disable parameter replacing like this for current OracleConnection session only (revert back to whatever it was after closing connection)?
(It is old .NET 1.1 application, so OracleConnection and OracleCommand are used)

A: The replacement of variables starting with an ampersand (&) is a functionality provided by SQL*plus. It's neither SQL nor PL/SQL. SQL Developer implements most of these SQL*plus extensions.
So, in your .NET application, the ampersand has no special meaning.
You can also turn it off in SQL*plus and SQL Developer by executing:
SET DEF OFF


text:
Q: Mapbox Navigation SDK integration with SwiftUI 5 import SwiftUI
import Mapbox
import MapboxAnnotationExtension
import MapboxDirections
import MapboxCoreNavigation
import MapboxNavigation

/****** some classes for different types of annotations

struct MapboxRepresent: UIViewRepresentable {

................

   class Coordinator: NSObject, MGLMapViewDelegate {

        func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) {
            let navigationViewController = NavigationViewController(for: directionsRoute!)
            navigationViewController.modalPresentationStyle = .fullScreen
            !!!! -> present(navigationViewController, animated: true, completion: nil)
// here is error - Use of unresolved identifier 'present'
        }
   }

.................

}

This code works properly; it shows map and all annotations.
The function for tap is just for testing. As I'm new in SwiftUI5 I can not understand how to fix this problem.

A: You cannot call .present inside a Coordinator defined in SwiftUI View. You need to create a new SwiftUI View that represents the Mapbox NavigationViewController. Then you can use .sheet to open a modal for that Swift navigation view. Look at this tutorial to know how to bring a Mapbox map and navigation to iOS app using SwiftUI.


text:
Q: How to read value when using model.save() or fetch()? Man = Backbone.Model.extend({
        url:'/test.aspx',
        initialize: function(){
        },
        defaults: {
            name:'Jim',
            age: '38'
        },
        validate:function(attributes){
            if(attributes.name == '') {
                return "name can't be null";
            }
        }
    });
    var man = new Man;
    man.set({name:'the5fire'});
    man.save();  //the format is json{"name":"the5fire","age":38}

In test.aspx.cs, how can I read this value {"name":"the5fire","age":38} ?
I have tried Request.Form.ToString() but found no data there.
Chrome developer tools shows this json-format data in the "request payload" block.

update:
If I use man.fetch({ data: { Pagesize: '1', PageIndex: '111' } ), then on the server side, I can use Request.Params["PageIndex"]. But how can I get the name? the age?

A: You can access the raw body of the request via HttpRequest.InputStream and  convert it to a string :
string jsonstring = new System.IO.StreamReader(Request.InputStream).ReadToEnd();

You would then deserialize this string to get an object, for example:
using System.Web.Script.Serialization;
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize<dynamic>(jsonstring);
string name = (string)d["name"];


text:
Q: How do I disable all old meeting reminders (from years ago) Just installed the new Outlook on mac and sync'd up with gmail and yahoo - but it keeps flooding me with meeting reminders from 10 years ago.  How do I disable/delete all these old meeting reminders.

A: Is this what you are looking for as an answer: Office 2016 can't dismiss old notifications (Mac)


text:
Q: How to list hardware in DOS? I have a PC running MS-DOS (i.e. no Windows). How can I retrieve a list of all hardware present on the PC? Something like Everest for Windows, or something simpler, like lspci from Linux.

A: SOLUTION-1:
There is a free tool from FreeDOS, which is very similar to 'lspci'. This tool should be compatible with MS-DOS. Download it from: http://www.ibiblio.org/pub/micro/pc-stuff/freedos/files/distributions/1.2/repos/pkg-html/pcisleep.html
And use it as:

pcisleep L

this will list devices on PCI bus...

addr vendor:type  vendor description
-----------------------------------
xxxx [8086:7111]  Intel  IDE Controller
xxxx [9999:9999]  AMD    LAN Ethernet
...

SOLUTION-2 (only for Network Cards on PCI):
There is a free tool, called 'nicscan.exe' which scans PCI for Network cards available. Donwload from here: https://www.jumpjet.info/Application-Software/DOS/Hardware/2/NICSCAN/NICSCAN.zip

nicscan.exe

it will list something like:

Bus: 2     Device: 0          Function: 0

PCI vendor: 1022 = Advanced Micro Devices [AMD]
PCI device: 2000 = 79c790 [PCnet32 LANCE]

The result shown above is the VMWare NIC AMD 79c790 10Mbps

A: You can use HWiNFO, available for DOS.

Hardware Info (HWiNFO) is a powerful system information utility
  designed especially for detection of hardware.

Download here(Look HWiNFO v5.5 for DOS).

A: Another option (for DOS) may be Quarterdeck's QEMM may have Manifest (mft.exe)
The term "system profiler" may be useful when searching for additional alternatives for general hardware detection.  Additionally, there are specific methods to detect specific types of hardware, so if you need something specific, do clarify.
It looks like some more software for ports may be found from I/O port programs (see file listing at ../../menu/io_mouse.txt ; I can't put a direct hyperlink there because I've only recently registered so I'm limited to only 2 links total).  I can't 100% vouch for the software there, but vague memory suggests to me that WhatPort may be good for detecting COM ports.
If you want more, please elaborate (like describing just what hardware you're looking for).  Otherwise, there you go.

A: In the case you mean cmd when you say DOS
type the following into at the prompt
systeminfo

you can also launch a GUI version of the tool by typing msinfo32 at the prompt
For difference between DOS and cmd see here
Edit
Slightly changed the wording for people who landed here looking cmd instead of DOS


text:
Q: iOS - trying to understand how movies work I am working on an application that has to be tight control of time flow during a movie recording.
Apple says the iPhone 5 can capture HD video up to 30 fps. If shoot a video and play it on quicktime I see a variable FPS, that reaches 30 fps at some moments, but at the same time quicktime reports the video as being 29.75 fps.
As far as I understand, for each second of video, an integer number of frames should be displayed, not a fractional number. I first thought that could be related to drop frames. Then I decided to design an method to measure drop frames and realized that for every second of video, the iPhone drops from 1 to 4 frames. Also discovered that every time a frame is dropped iPhone simply copies the last frame again to fill the gap. So in theory, dropping a frame would make no difference in the total number of frames a move would have.
So, this is my problem. What this 29.75 fps is telling? How this number is obtained?

A: It's not so much that x number of frames are shown per second, but each frame is shown for 1/x seconds. NTSC (the TV standard in US, Japan and others), runs at 29.97fps. So, each frame is shown for a bit more than 3/100ths of a second before the next frame is drawn. So, in your case, each frame is displayed for roughly .0336 of a second before the next one is shown.


text:
Q: How to retrieve data from Postgresql index using java I am writing an application for searching, using text search of Postgresql. I am a beginner in Database. I created a Gin index and i am trying to get data from it. My code is
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class JDBCPostgressRetrieve {

    private static String Database = "jdbc:postgresql://localhost/search";
    private static String user = "postgres";
    private static String password = "abcd";

    public static String getDatabase() {
        return Database;
    }

    public static String getUser() {
        return user;
    }

    public static String getPassword() {
        return password;
    }

    public void retrieve(int limit) {

        Statement stmt = null;
        Connection connection = null;
        ResultSet rs = null;
        int i = 0;
        try {

            Class.forName("org.postgresql.Driver");

        } catch (ClassNotFoundException e) {

            System.out.println("Where is your PostgreSQL JDBC Driver? "
                    + "Include in your library path!");
            e.printStackTrace();
        }

        try {

            connection = DriverManager.getConnection(
                    JDBCPostgressRetrieve.getDatabase(),
                    JDBCPostgressRetrieve.getUser(),
                    JDBCPostgressRetrieve.getPassword());

            if (connection == null) {
                System.out.println("Failed to make connection!");
            } else {

                DateFormat dateFormat = new SimpleDateFormat(
                        "yyyy/MM/dd HH:mm:ss");
                Date date = new Date();

                // Creating Statement for query execution
                stmt = connection.createStatement();
                // creating Query String
                String query = "SELECT (person_name,email,mobile_number,key_skills,current_employer)\n" +
                                "FROM bhubneshwar\n" +
                                "WHERE textsearchable_index_col @@ to_tsquery('MBA & HR')\n" +
                                "LIMIT 10";

                // excecuting query
                rs = stmt.executeQuery(query);
                while (rs.next()) {
                    // Didplaying data of tables
                    System.out.println("Name : " + rs.getString("person_name"));
                    System.out.println("email : " + rs.getString("email"));
                    System.out.println("mobile_number : " + rs.getString("mobile_number"));
                    System.out.println("key_skills : " + rs.getString("key_skills"));
                    System.out.println("current_employer : " + rs.getString("current_employer"));
                }
            }

        } catch (SQLException e) {

            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
        }
        finally {
            try {
                rs.close();
                stmt.close();
                connection.close();
            }catch(SQLException e) {
                System.err.println("SQLException while closing connection. "+ e.getMessage());
            }
        }
    }

    public static void main(String args []) {
        JDBCPostgressRetrieve ret = new JDBCPostgressRetrieve();
        ret.retrieve(100);
    }
}

textsearchable_index_col is the index column in the table. But after running the code I am getting an error.
org.postgresql.util.PSQLException: The column name person_name was not found in this ResultSet.
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.findColumn(AbstractJdbc2ResultSet.java:2727)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getString(AbstractJdbc2ResultSet.java:2567)
at com.presciencesoft.postgres.search.JDBCPostgressRetrieve.retrieve(JDBCPostgressRetrieve.java:77)
at com.presciencesoft.postgres.search.JDBCPostgressRetrieve.main(JDBCPostgressRetrieve.java:103)

In this way can I retrieve from index as table ?? This query is running perfectly in command prompt.

A: The parentheses form a row-constructor, so your query returns a single column row literal, essentially an anonymous composite type.
Compare:
regress=> SELECT (1,2);
  row
-------
 (1,2)
(1 row)

regress=> SELECT 1, 2;
 ?column? | ?column?
----------+----------
        1 |        2
(1 row)

You would've quickly realised this if you'd run the query on the psql command line (or in PgAdmin-III if you prefer GUIs).
A second misunderstanding: You don't retrieve data from an index1. You get data from a table. The database engine might used any indexes that are present to speed your query up, but you're still getting data from the table. You can see this if you explain a command to get its query plan.
1: ... well, arguably until PostgreSQL 9.2's with index-only scans, but that's a bit of an implementation detail.


text:
Q: Remote method in LoopBack not being called When calling a remote method in my LoopBack project, it seems to only return an empty array. I don't think it is really being called at all but perhaps the default implementation is being called.
member.js
module.exports = function(Member) {
  Member.getProjectsForMember = function(id, callback) {
    console.error('HERE');
    return callback(null, {'test': '123'});
  };
};

member.json
{
  "name": "member",
  "base": "User",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "projects": {
      "type": "hasMany",
      "model": "project",
      "options": {
        "nestRemoting": false
      }
    }
  },
  "acls": [{
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW"
    },
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$unauthenticated",
      "permission": "DENY"
    }
  ],
  "methods": {
    "getProjectsForMember": {
      "accepts": [{
        "arg": "id",
        "type": "number",
        "required": true,
        "http": {
          "source": "path"
        }
      }],
      "returns": [{
        "arg": "projects",
        "type": "Object",
        "root": true,
      }],
      "http": [{
        "path": "/:id/projects",
        "verb": "get"
      }]
    }
  }
}

I am calling it using the LoopBack API Explorer via a GET to /members/{id}/projects:
http://localhost:3000/api/members/3e26u0aa62155715vcb52afa/projects?access_token=R6GKVHwFuMG2caJexuyoMd0JSNOWtvLVXIEmRj1IkNSrM54bwomQLxHcpqlyFaHk
The response is []. I would expect to see the response of {'test': '123'} and the 'HERE' logged to the terminal but I do not.


text:
Q: Headings Element in Internet Explorer I have a website that running OK at Mozilla Firefox and Google Chrome. But in Internet Explorer, it won't show the title of paragraph. I use Headings Elements like H1, H2 and so on. But in Internet Explorer it won't show up. How it could be?
h2 {
margin:8px 0;
margin-top:-10px;
padding:8px 0;
font-size:26px;
font-weight:bold;
line-height:1.2em;
color:#333;
text-transform:none;}

I use
Title of Book
  and above is my code.

A: You are specifying margin: 8px 0 --- This will take margin as 8px from top and bottom and 0 from right and left.
And again in the next line you are applying margin-top : -10px.
Maybe that is causing the problem.
Not sure but still you can try !!


text:
Q: jQuery event specific to a video element I am trying to make custom video controls for a bootstrap plugin and I am having trouble with making the jQuery more detailed. The actual jQuery code works, but I need to be able to make the jQuery have some section to it that allows multiple instances of that video to be in a page so that the plug-in is easier to use and has less restrictions.
So far, this is what I have:
window.onload = function() {

// Video
var video = document.getElementById("video");

// Buttons
var playButton = document.getElementById("play");
var muteButton = document.getElementById("mute");
var fullScreenButton = document.getElementById("full-screen");

// Sliders
var seekBar = document.getElementById("seek-bar");
var volumeBar = document.getElementById("volume-bar");

// Event listener for the play/pause button
$(playButton).click(function() {
    if (video.paused == true) {
        // Play the video
        video.play();
        // Update the button text to 'Pause'
        $(playButton).removeClass("glyphicon-play").addClass("glyphicon-pause");
    } else {
        // Pause the video
        video.pause();
        // Update the button text to 'Play'
        $(playButton).removeClass("glyphicon-pause").addClass("glyphicon-play");
    }
});

// play if video is clicked
$(video).click(function() {
    if (video.paused == true) {
        // Play the video
        video.play();
        // Update the button text to 'Pause'
        $(playButton).removeClass("glyphicon-play").addClass("glyphicon-pause");
    } else {
        // Pause the video
        video.pause();
        // Update the button text to 'Play'
        $(playButton).removeClass("glyphicon-pause").addClass("glyphicon-play");
    }
});
// Event listener for the mute button
$(muteButton).click(function() {
    if (video.muted == false) {
        // Mute the video
        video.muted = true;
        // Update the button text
        $(muteButton).removeClass("glyphicon-volume-up").addClass("glyphicon-volume-off");
    } else {
        // Unmute the video
        video.muted = false;
        // Update the button text
        $(muteButton).removeClass("glyphicon-volume-off").addClass("glyphicon-volume-up");
    }
});
// Event listener for the full-screen button
$(fullScreenButton).click(function() {
if (video.requestFullscreen) {
    video.requestFullscreen();
    } else if (video.mozRequestFullScreen) {
        video.mozRequestFullScreen(); // Firefox
    } else if (video.webkitRequestFullscreen) {
        video.webkitRequestFullscreen(); // Chrome and Safari
    }
});
// Event listener for the seek bar
$(seekBar).change(function() {
// Calculate the new time
    var time = video.duration * (seekBar.value / 100);
    // Update the video time
    video.currentTime = time;
});
// Update the seek bar as the video plays
video.addEventListener("timeupdate", function() {
    // Calculate the slider value
    var value = (100 / video.duration) * video.currentTime;
    // Update the slider value
    seekBar.value = value;
});
// Event listener for the volume bar
$(volumeBar).change(function() {
    // Update the video volume
    video.volume = volumeBar.value;
});
}

This is all that I have for the jQuery so far and the basic html for the video is as follows:

    <video id="video" width="640" height="365" poster="pictures\MCR-Logo.png">
      <source src="videos\MCR-TheLightBehindYourEyes.mp4" type="video/mp4">
    </video>

        <button type="button" id="play" class="play glyphicon glyphicon-play btn"></button>
        <input type="range" id="seek-bar" value="0" max="100">
        <button type="button" id="mute" class="glyphicon glyphicon-volume-up btn"></button>
        <input type="range" id="volume-bar" min="0" max="1" step="0.01" value="1">
        <button type="button" id="full-screen" class="glyphicon glyphicon-fullscreen btn"></button>

So I basically just need to know how to make it possible to have multiple video  elements in ran off of one jQuery file, and more importantly, be in only a section of the file because the rest of it will need to have the code for the other functions of the plug-in. Any help in this will be extremely valuable to me and i need to know how to finish this very quickly so that i can get to work on the other sections of the plugin.

A: Since you want to have multiple instances in the same page, the first step would be to move from the id attribute and start using classes.

    <video class="video" width="640" height="365" poster="pictures\MCR-Logo.png">
      <source src="videos\MCR-TheLightBehindYourEyes.mp4" type="video/mp4">
    </video>

        <button type="button" class="play" class="play glyphicon glyphicon-play btn"></button>
        <input type="range" class="seek-bar" value="0" max="100">
        <button type="button" class="mute" class="glyphicon glyphicon-volume-up btn"></button>
        <input type="range" class="volume-bar" min="0" max="1" step="0.01" value="1">
        <button type="button" class="full-screen" class="glyphicon glyphicon-fullscreen btn"></button>

Then, you can make use of the jQuery.each() function to make a loop on all elements in the page and then run your code for every element.
See the following snippet that uses the jQuery.each() function. In every loop, the $item is a jQuery object of the current div.video-container element.
Then you can use jQuery.find() to find the control buttons and the video element.
The rest of the code is pretty much the same, the only changed I made is to re-use the jQuery selectors, there is a (small in your case) performance gain.
window.onload = function() {
    $('.video-container').each(function(idx, item) {
        var $item = $(item);

        // Video
        var video = $item.find(".video")[0];

        // Buttons
        var $playButton = $item.find(".play");
        var $muteButton = $item.find(".mute");
        var $fullScreenButton = $item.find(".full-screen");

        // Sliders
        var $seekBar = $item.find(".seek-bar");
        var $volumeBar = $item.find(".volume-bar");

        // Event listener for the play/pause button
        $playButton.click(function() {
            if (video.paused == true) {
                // Play the video
                video.play();
                // Update the button text to 'Pause'
                $playButton.removeClass("glyphicon-play").addClass("glyphicon-pause");
            } else {
                // Pause the video
                video.pause();
                // Update the button text to 'Play'
                $playButton.removeClass("glyphicon-pause").addClass("glyphicon-play");
            }
        });

        // play if video is clicked
        $(video).click(function() {
            if (video.paused == true) {
                // Play the video
                video.play();
                // Update the button text to 'Pause'
                $playButton.removeClass("glyphicon-play").addClass("glyphicon-pause");
            } else {
                // Pause the video
                video.pause();
                // Update the button text to 'Play'
                $playButton.removeClass("glyphicon-pause").addClass("glyphicon-play");
            }
        });
        // Event listener for the mute button
        $muteButton.click(function() {
            if (video.muted == false) {
                // Mute the video
                video.muted = true;
                // Update the button text
                $muteButton.removeClass("glyphicon-volume-up").addClass("glyphicon-volume-off");
            } else {
                // Unmute the video
                video.muted = false;
                // Update the button text
                $muteButton.removeClass("glyphicon-volume-off").addClass("glyphicon-volume-up");
            }
        });
        // Event listener for the full-screen button
        $fullScreenButton.click(function() {
        if (video.requestFullscreen) {
            video.requestFullscreen();
            } else if (video.mozRequestFullScreen) {
                video.mozRequestFullScreen(); // Firefox
            } else if (video.webkitRequestFullscreen) {
                video.webkitRequestFullscreen(); // Chrome and Safari
            }
        });
        // Event listener for the seek bar
        $seekBar.change(function() {
        // Calculate the new time
            var time = video.duration * ($seekBar.val() / 100);
            // Update the video time
            video.currentTime = time;
        });
        // Update the seek bar as the video plays
        video.addEventListener("timeupdate", function() {
            // Calculate the slider value
            var value = (100 / video.duration) * video.currentTime;
            // Update the slider value
            $seekBar.val(value);
        });
        // Event listener for the volume bar
        $volumeBar.change(function() {
            // Update the video volume
            video.volume = volumeBar.val();
        });
    });
};

Note: One more thing I would change is to add to your classes (your IDs in your sample) a prefix so that they are unique and avoid being used in some other CSS style. For example instead of .play you could use .bsvideo-play.


text:
Q: Push docker image with devops to private azure container registry So I have a private Azure container registry, which by its nature also sites on a private VNET (it has to).
I have configured my private container registry to:
"Allow trusted Microsoft services to access this container registry"

I have also in my VENT allow Microsoft Container registry as a service endpoint.
However, when I push my image in devops with the below code:
  variables:
  # Container registry service connection established during pipeline creation
  dockerRegistryServiceConnection: 'myacr'
  imageRepository: 'my-image-repo'
  containerRegistry: 'myacr.azurecr.io'
  dockerfilePath: '$(Build.SourcesDirectory)/Dockerfile'
  tag: '$(Build.BuildId)'
 steps:
- task: Docker@2
  displayName: Login to ACR
  inputs:
    command: login
    containerRegistry: $(dockerRegistryServiceConnection)
- task: Docker@2
  displayName: Build image with arguments
  inputs:
    command: build
    arguments: --build-arg git_personal_token=MYTOKEN
    repository: $(imageRepository)
    dockerfile: $(dockerfilePath)
    containerRegistry: $(dockerRegistryServiceConnection)
    tags: |
      $(tag)
- task: Docker@2
  displayName: push the image
  inputs:
    containerRegistry: $(dockerRegistryServiceConnection)
    repository: $(imageRepository)
    command: push
    tags: |
      $(tag)

I get the error:
denied: client with IP '51.145.2.107' is not allowed access. Refer https://aka.ms/acr/firewall to grant access.

However, I cannot set an IP address in the firewall, as the builder IP changes with each unique build that is generated. I thought I had allowed all microsoft services the correct access, have I missed something, or how can I debug this further?

A: If you have an Azure Container Registry where you have disabled public network access you will not be able to access it from a Microsoft Hosted Azure Devops Agent.
The Trusted services currently only contains a handful of service currently, but more may be added in the future:

*

*Azure Container Instances

*Microsoft Defender for Cloud

*ACR Tasks

*Machine Learning

*Azure Container Registry

However it is not likely that Azure DevOps (at least not the agents) will be added, since Microsoft has no control over what code executes in them (an thus they are not trusted). The same principle applies for the Azure DevOps service tag, which do not include the Microsoft Hosted agents.
If you really need your registry to be fully private, you will need to use a self hosted agent deployed in your own network that has access to the registry.


text:
Q: Forms Authentication won't Work I have been trying to no-avail to get Forms Authenticaiton to work on my project. Right now it is just local and I am running it through Visual Studio.
1st Try(Using root Directory Web.Config):
<?xml version="1.0"?>
<configuration>
<location path="~/Account/Admin.aspx">
<system.web>
  <authorization>
    <deny users="*"/>
    <allow users="*"/>
  </authorization>
  <authentication mode="Forms">
    <forms loginUrl="Login.aspx" timeout="30" name=".ARBBADMIN" requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx">
      <credentials passwordFormat="Clear">
        <user name="user1" password="pass1"/>
      </credentials>
    </forms>
  </authentication>
</system.web>
</location>

</configuration>

Does not work, even when I try to deny ALL users
2nd Option, I put a seperate web.config inside the account folder, and I get this error:
It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.
I've googled it and researched and the solution is to make the folder an IIS Directory, Which , I have no idea how to do while running on localhost.
`

A: Why are you allowing same user group and denying it again
<authorization>
 <deny users="*"/>
 <allow users="*"/>
</authorization>

I guess following is enough to allow all users
<authorization>
 <allow users="*"/>
</authorization>

Correct me if I did not understand question properly.


text:
Q: Create instance of unmanaged dll class How do I create a class that I can reference to and directly use to call methods from an unmanaged dll? (assuming an unmanaged dll is a dll that doesn't exists/is known @ compile time)
For example I have a dll which contains the class helloWorld and I want to create an instance of the class and then call helloWorld.tell().

A: It appears that you are attempting to dynamically load an assembly, not neccessarily work with an unmanaged assembly.  It seems you are looking for information on reflection.  You can use Activator to create the objects you need.  There are a lot of ways to do this, and I would read up on it.  Here are a few resources to get started:
Code Project - Reflection in C# Tutorial
CSharp.Net - Reflection Introduction
CodeGuru.com - An Introduction to Reflection

A: You can use your assembly with a COM interface, which is available from unmanaged code.
There are some examples here that you can download. Check out the COM Interop Part II code. http://code.msdn.microsoft.com/windowsdesktop/Visual-Studio-2010-Samples-31b491f3
If you're feeling brave, here's another explanation: http://msdn.microsoft.com/en-us/library/aa645738(v=vs.71).aspx
Hope that helps.


text:
Q: how do you have css padding around a multiline div i have the following css to put padding around a div:
.orangeAllDay, .orangeAllDay a {
    background: #fab384 !important;
    color: white;
    padding: 5px;
}

it works great until the content (which happens to be inside a cell in an html table takes up two lines.  When i look at this in firefox, it looks like its trying to add the padding to each line of the content (even though its all inside one div) so i get some weird overlap of space above the second line that covers part of the first line.
Is there a workaround for this issue or another solution that doesn't break on multiline.

A: It is adding this padding because you have included both the .orangeAllday and .orangeAll Day a together, so both the link & the elemenent .orangeAllday will get padding of 5px.
You would need to separate them like so:
.orangeAllDay {
    background: #fab384 !important;
    color: white;
    padding: 5px;
}

.orangeAllDay a {
    background: #fab384 !important;
    color: white;
}

this is done with the assumption that you want padding on the .orangeAllDay element only, but wish to retain background / color for link a.

A: You've got the padding around the div (.orangeAllDay) and the link. What you are seeing is the padding of the link. There are several ways around this, depending on how exactly the HTML looks like.
If it only contains the link, I'd suggest to actually drop the div and just have the link display as a block:
...

a.orangeAllDay {
    background: #fab384 !important;
    color: white;
    padding: 5px;
    display: block;
}


text:
Q: What is FormalExpression in the context of BPMN? Here is what I come across in process definition examples:
<conditionExpression xsi:type="tFormalExpression">${wf_reviewOutcome == 'Approve'}</conditionExpression>

It's obvious what the code does, but I want to learn more about FormalExpression, like, where it comes from and what else can be done with it beyond comparing two values.

A: FormalExpression is declared as part of the BPMN 2.0 specification.
From the spec:
The FormalExpression class is used to specify an executable Expression using a specified Expression language.

What can be achieved by the expression is going to be different based on the engine you are using, in the case of Activiti, the expression language is JUEL.
Typically expressions are used primarily for conditional gateways and so simple comparisons to strings such as approved/rejected etc are all that is needed, however you can make the expression script as complex as you deem fit (keep in mind maintainability).
Hope this helps,
Greg


text:
Q: Different values of pi? ini_set('precision', 64);
echo M_PI."
";
echo pi()."
";
echo "3.14159265358979323846264338327950
";

For reference I've used http://www.eveandersson.com/pi/digits/100
If you compare the output you get the following:
3.1415926535898
3.141592653589793115997963468544185161590576171875
3.14159265358979323846264338327950

So what's with the precision value of pi()? It seems its totally off. Yes, I know pi is irrational, but at least to 100 significant digits it should be accurate?
Can anyone confirm this problem, and is it possible to explain why after 16 digits it goes wrong in php?

A: The "problem" is that the value of M_PI (which is the same value returned by pi()) is hardcoded.
From the php_math.h file:

#ifndef M_PI
#define M_PI           3.14159265358979323846  /* pi */
#endif

Changing the precision doesn't change the already defined constant value. Additionally the usual "how are float/double numbers are stored" still apply.

A: In the bcmath extensions manual page the following is presented:
//bcpi function with Gauss-Legendre algorithm
//by Chao Xu (Mgccl)

function bcpi($precision){
  $n=0;
    $limit = ceil(log($precision)/log(2))-1;
    bcscale($precision+6);
    $a = 1;
    $b = bcdiv(1,bcsqrt(2));
    $t = 1/4;
    $p = 1;
    while($n < $limit){
        $x = bcdiv(bcadd($a,$b),2);
        $y = bcsqrt(bcmul($a, $b));
        $t = bcsub($t, bcmul($p,bcpow(bcsub($a,$x),2)));
        $a = $x;
        $b = $y;
        $p = bcmul(2,$p);
        ++$n;
    }
    return bcdiv(bcpow(bcadd($a, $b),2),bcmul(4,$t),$precision);
}

echo bcpi(64);
echo "
3.1415926535897932384626433832795028841971693993751058209749445923";

It seems therefore, that ini_set('precision',64); doesn't do anything constructive for the regular php math functions (>15), but bcmath extension ignores the setting entirely.
So to work in precision >= 16 use bcmath extension
otherwise ini_set works up to 15
And @Progman's answer that float/double storing rules still apply - means that there is a cap on 15 decimal points (even though php stores all floats as double)


text:
Q: Running 2 commands on Xaml Button I am currently developing an application using WPF/ Xaml in MVVM format.
I am attempting to run 2 commands from one single button to close a control and delete the object the control was based on.
The viewmodels that these commands are created in are separate so i am unsure of how to do this in the Viewmodels.
I am hoping for a solution that just runs these 2 commands in the Xaml if this is possible
The code if necessary
<Button Grid.Column="4"
Command="{Binding DeleteCustom}"
Visibility="{Binding IsCustom}"/>

The other command i want to run is called
CancelCommand

I hope someone can help

A: There is only a single Command property that can be set to a single ICommand but you can create another command property in your view model that executes both commands and bind to this one:
public ICommand CompositeCommand { get; } = new RelayCommand<object>((arg) =>
{
    DeleteCustom.Execute(null);
    CancelCommand.Execute(null);
});

A: Maybe if you write your command in a base class and override it
ViewModelBase
{

    public virtual ICommand CompositeCommand { get; } = new RelayCommand<object>((arg) =>
    {
        DeleteCustom.Execute(null);
        CancelCommand.Execute(null);
    });

    protected virtual DeleteCustom(object arg)
    {
       /.....
    }

    protected virtual CancelCommand(object arg)
    {
        /....
    }

    //..........
}

FirstViewModel : ViewModelBase
{
    // ...............

    protected override void  DeleteCustom(object arg)
    {
    }
    // ..........
}

SecondviewModel : ViewModelBase
{
     // ...............

    protected override void  CancelCommand(object arg)
    {

    }
    // ..........
}


text:
Q: Sort search results by popularity using - C# ASP.NET I'm building a site that is mostly a collection of links to different pages and forms for a company's intranet. All the links are logged in a SQL database that has tables for specific links, the tags that connect to those links, and how often the link is used. Every time a link is used, it creates a row in the last table that contains

*

*an id for each row

*the link's id which is related to the table that contains the link's title and tags

*the actual link

*the date of the click.

I'm trying to figure out a way to sort the results based on the number of entries there are in the tracking database. I can search the database currently, but it just lists the results in the order they are in the database.
public ActionResult Index(string method = null)
    {
        var model = new SearchResults()
        {
            ContentLink = database.ContentLinks.Where(x => x.Title.ToLower().Contains(method) && method != "").ToList(),
            ContentTag = database.ContentTags.Where(x => x.Tag.ToLower() == method).ToList()
        };

        return View(model);
    }

The results are passed into a model that contains lists for each respective table. I'm just trying to figure out a way that sorts the results based on which link has the most clicks logged in the table.

A: Return your Links based on an aggregate function. They will already be sorted.
SELECT links,
       COUNT(links) as LinkCount
FROM   youtable
GROUP  BY links
ORDER  BY COUNT(links) desc

You can drop the "COUNT(links) as LinkCount" line if you don't actually need the count.

A: You need a group by. I'm not clear on your exact entity/table structure, so you'll probably need to extrapolate an exact solution. Generally, it's going to be like:
var links = db.LinkClicks
    .GroupBy(m => m.Link)
    .OrderByDescending(o => o.Count)
    .Select(m => m.Key);

GroupBy returns essentially a list of lists keyed by the property you're grouping by. Therefore, you can order by the count of each sub list to sort by the "popularity" of that particular link (what you're grouping by). Then, Select can be used to coallesce it into a simply list of the links, which will now be ordered by how many clicks each has.


text:
Q: Passing string from IronPython to Javascript I am new to Javascript and I have no idea how to get a simple string, which contains a path that changes, from my Pythonscript.
It is a local script so I dont have the possibility to write down a file and import it with Javascript or use a webserver to pass the data.
My Pythonscript sends commands to the Javascript. Both scripts work independent as long as I pass the path manually which is pretty annoying.
I am looking for something simple like in Bash and Python
Bash:
export myPath = 'myString'
Python:
import os
myPath = os.environ['myPath']
Thanks in advance

A: Encode the data as JSON and output it into a JavaScript section, e.g.:
<script type="text/javascript">
var jsPath=<?python import json; print json.dumps(myPath) ?>
</script>

Except use the actual syntax for inline Python that your engine uses.


text:
Q: Obtener posición GPS con la máxima exatitud solo una sola vez en Android Necesito obtener la coordenadas GPS solo una vez cuando el usuario pulsa un botón, teniendo en cuenta la exactitud de los datos, es decir consultar a menudo hasta tener la precisión, para así dar como buena la posición, tambien especificando un TIMEOUT, es decir si al X tiempo no se ha podido obtener una buena posición, parar la escucha.
Ahora mismo solo tengo como obtener una vez los datos del GPS, y veo que si voy pulsando el botón cada vez, los datos son más exactos.
Se podría dar como buena precisión el accuracy este menos de 20m

A: Obtener la posicion GPS mas exacta se realiza mediante el proveedor de GPS. Lo que deseas es

consultar a menudo hasta tener la precisión

Consultar varias veces en un lapso corto de tiempo puede traer por consecuencia un alto consumo de tu bateria, pero si lo deseas realizar, puedes obtener una muestra de lecturas y obtener la que tiene mayor precision, esto se realiza mediante el metodo getAccuracy() del provider.
LocationManager locManager = (LocationManager)getSystemService(LOCATION_SERVICE);
List<String> listaProviders = locManager.getAllProviders();
LocationProvider provider = locManager.getProvider(listaProviders.get(0));
int precision = provider.getAccuracy();
boolean obtieneAltitud = provider.supportsAltitude();
int consumoRecursos = provider.getPowerRequirement();


text:
Q: what is lifetime of static dictionary | LifestyleTransient | C# | WCF I am storing some information in static dictionary which is defined in class inside WCF service component like below :
    public class UserAuthenticator : IUserAuthentication
    {

                public static ConcurrentDictionary<UserInfo, ConcurrentDictionary<string, BookingDetails>>BookingDetailsDictionary = new ConcurrentDictionary<UserInfo, ConcurrentDictionary<string, BookingDetails>>(new UserEqualityComparer());

                public static ConcurrentDictionary<string, Connector> connectorDictionary = new ConcurrentDictionary<string, Connector>();

      public BookingDetails Authenticate(UserInfo userInfo, ServiceDetails serviceDetail, XmlElement requestData)
            {
                var bookDetails = new BookingDetails();
                try
                {
                    ConcurrentDictionary<string, BookingDetails> dicObject = null;
                    if (bookingDictionary.TryGetValue(userInfo, out dicObject))
                    {...}
                    else
                    {
                    //  call Database and get value from database and fill db value in to static ConcurrentDictionary
                    }
                }
            }
    }

Here I check static ConcurrentDictionary key if value in the not in dictionary then call database and fill value in the dictionary.
Expected output is first time invoke wcf service then call database and fill value in the ConcurrentDictionary and then after all the WCF service call read data from ConcurrentDictionary
Now, problems is sometimes I see that the static ConcurrentDictionary count are zeroed. And the strange part is the application pool is still active. no application pool is recycle still randomly it call database and sometime it take data from ConcurrentDictionary
This is really strange for me. I assume that static variable will hold its value until the application ends. But even the application pool did not recycle or IIS is not restarted, the static variable is zeroed.
What do you suggest? Is using ConcurrentDictionary variables a better choice?
Note : I have used castle windsor dependency injection in my wcf application and UserAuthenticator class is register with LifestyleTransient() like below
Component.For<IUserAuthentication, UserAuthenticator>().LifestyleTransient()

Please advice me the best solution
Thanks in advance

A: Finally I got solution of above problem
As I have used static ConcurrentDictionary in WCF project and also implemented web garden and static variables per process so its not working in another process some time with web gardern
Solution is as off now stopped wen garden and its working fine and in future will implement distributed cache like (Radis, NCache, etc) with web garden
Thanks to  @mjwills and @ Shantanu  for valuable comments


text:
Q: Problem with apache2 server So I am having a problem with my apache2 server sharing a file.  I am on ParrotSec OS 4.11 debian.  Anyhow, when I create a file alexa.exe and place it in /var/www/html directory and then start service apache2 start  Then on my windows computer I go to my Parrot machines IP http://192.168.1.218/alexa.exe and it does not work.  The response says cannot reach this page.  Make sure you have the right webaddress.
I tried it from my cellphone and it timed out.  However, if I try it from my parrot machine it works.  I tried turning off my firewall on my parrot machine and it still does not work.  I cannot see why this should not work.  Does anyone have any suggestions?
It is not a fresh apache install, however I can reach the default page and the firewall is gufw a gui which I turned off.
I have know problem getting apache to work on Kali and it should basically be the same on parrot im guessing.  I may just try doing a fresh install.  There is no reason it should not work after that, but if anyone has any other ideas I would be happy to hear.


text:
Q: How to compare Json date and return a new array I have problem with the code below. I'm trying to return all votes between two dates, but for some reason it doesn't work well.
FirstShiftStart date -> 2022-12-21 8:0:0
FirstShiftEnd date -> 2022-12-21 14:0:0
let current_datetime = new Date();
var firstShiftStart = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate() + " " + 08 + ":" + 00 + ":" + 00;
var firstShiftEnd = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate() + " " + 14 + ":" + 00 + ":" + 00;;

    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
    var yyyy = today.getFullYear();

    today = yyyy + '-' + mm + '-' + dd;

votesforDay is returning only today's records(all data is ok).
However, the last line it's returning empty array.
    var votesforDay = dataAllJson.filter(x => x.Created >= today);

    int likesFirstShift = votesforDay.filter(x => x.Created >= firstShiftStart && x.Created <= firstShiftEnd && x.Choice == "Like").length;

int likesFirstShift = votesforDay.filter(x => x.Created >= firstShiftStart && x.Created <= firstShiftEnd && x.Choice == "Like").length;

Choice: "Like"

Created: "2022-12-21 07:50:04"

Id: 12123

A: The last line of your code won't return a thing, if these conditions are not met:

*

*the Created property of a specific JSON element of your array must be greater than or equal to firstShiftStart (2022-12-21 08:00:00, in your code)

*the Created property of that same JSON element of your array must be less than or equal to firstShiftEnd (2022-12-21 14:00:00, in your code)

*finally, the Choice property of that same JSON should be equal to Like
Since we know only one element of your array of JSON objects, we can see that one of the conditions is not met - the timestamp is before firstShiftStart, and your filter will remove it from the array.
Also, there are some syntax errors in your code - leading zeroes, double zeroes, etc.
I've taken the liberty of fixing it up a bit (not entirely), and changing your filtering in the last line, so that you may better understand why your code isn't returning anything.

let current_datetime = new Date();

var firstShiftStart = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate() + " 08:00:00";

var firstShiftEnd = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate() + " 14:00:00";

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = yyyy + '-' + mm + '-' + dd;

var dataAllJson = [
    {
        "Choice": "Like",
        "Created": "2022-12-22 11:50:04",
        "Id": 1
    },
    {
        "Choice": "dislike",
        "Created": "2022-12-22 11:44:04",
        "Id": 2
    },

    {
        "Choice": "dislike",
        "Created": "2022-12-22 07:50:04",
        "Id": 3
    },
    {
        "Choice": "dislike",
        "Created": "2022-12-22 07:50:04",
        "Id": 4
    },
    {
        "Choice": "dislike",
        "Created": "2022-12-22 07:50:04",
        "Id": 5
    },
    {
        "Choice": "Like",
        "Created": "2022-12-22 07:50:04",
        "Id": 6
    },

];

var votesforDay = dataAllJson.filter(x => x.Created >= today);
var likesFirstShift = votesforDay.filter(function(x) {
  if(x.Created >= firstShiftStart && x.Created <= firstShiftEnd && x.Choice == "Like") {
    console.log(x.Id);
    console.log(x.Created + " >= " + firstShiftStart);
    console.log(x.Created + " <= " + firstShiftEnd);
    console.log(x.Choice + " == Like");
  }
    return x.Created >= firstShiftStart && x.Created <= firstShiftEnd && x.Choice == "Like"
}).length;

console.log("=============================");
console.log(likesFirstShift);

Some things to note:

*

*firstShiftStart and firstShiftEnd are defined in a slightly different manner. Note the differences between the example and what was in your code

*I've changed the date to todays (22nd of December 2022), so that you can test the code

*I have also filled dataAllJson with semi-random data, again, for testing purposes

*votesForDay.filter(...) has been expanded to a slightly different notation, for testing purposes (note the console.logging)


text:
Q: Pivot Table with Additional Columns Let's have a 2D double array such as:
% Data: ID, Index, Weight, Category
A0=[1 1121 204 1;...
    2 2212 112 1;...
    3 2212 483 3;...
    4 4334 233 1;...
    5 4334 359 2;...
    6 4334 122 3 ];

I am needing to pivot / group by the rows with the highest Weights, for each given Index, which can be achieved with any Pivot Table | Group By functionality (such as  pivottable, SQL GROUP BY or MS Excel PivotTable)
% Current Result
A1=pivottable(A0,[2],[],[3],{@max}); % Pivot Table
A1=cell2mat(A1); % Convert to array

>>A1=[1121 204;...
      2212 483;...
      4334 359 ]

How should I proceed if I need to recover also the ID and the Category columns?
% Required Result
>>A1=[1 1121 204 1;...
      3 2212 483 3;...
      5 4334 359 2 ];

The syntax is Matlab, but a solution involving other languages (Java, SQL) can be acceptable, due they can be transcribed into Matlab.

A: You can use splitapply with an anonymous function as follows.
grouping_col = 2; % Grouping column
maximize_col = 3; % Column to maximize
[~, ~, group_label] = unique(A0(:,grouping_col));
result = splitapply(@(x) {x(x(:,maximize_col)==max(x(:,maximize_col)),:)}, A0, group_label);
result = cell2mat(result); % convert to matrix

How it works: the anonymous function @(x) {x(x(:,maximize_col)==max(···),:)} is called by splitapply once for each group. The function is provided as input a submatrix containing all rows with the same value of the column with index grouping_col. What this function then does is keep all rows that maximize the column with index maximize_col, and pack that into a cell. The result is then converted to matrix form by cell2mat.

With the above solution, if there are several maximizing rows for each group all of them are produced. To keep only the first one, replace the last line by
result = cell2mat(cellfun(@(c) c(1,:), result, 'uniformoutput', false));

How it works: this uses cellfun to apply the anonymous function @(c) c(1,:) to the content of each cell. The function simply keeps the first row. Alternatively, to keep the last row use @(c) c(end,:). The result is then converted to matrix form using cell2mat again.


text:
Q: quick way to add checkbox jQuery UI datepicker I want to add the check box "no end date" to the end of my date picker widget. I see people using "beforeshow" method under datepicker but it doesn't seem to work.
Here is what I have.
$("#to").datepicker({
    dayNamesMin: ["S", "M", "T", "W", "T", "F", "S"],
    firstDay: 1,
    dateFormat: "d MM, yy",
    onClose: function (selectedDate) {
        $("#from").datepicker("option", "maxDate", selectedDate);
    },
    beforeShow: function (input, inst) {
        setTimeout(function () {
            var buttonPane = $(input)
                .datepicker("widget")
                .find(".ui-datepicker-buttonpane");
            var html = '
<input type="checkbox"> No End Date
';
            buttonPane.append(html);
        }, 10);

    }
});

A: You have to set the button panel of datepicker in order to target it using var buttonPane = $(input).datepicker("widget").find(".ui-datepicker-buttonpane");:
showButtonPanel: true,

But as your image suggests it, you don't want the button panel, so use instead:
var buttonPane = $(input).datepicker("widget");

DEMO


text:
Q: I need to find and press a button on a webpage using VBA I have written a macro that will open a webpage, find the spots I need to put the data into, and then I want the macro to hit a prefill button, then hit Ok.
The page source code for the button is:
<input type="text" size="30" maxlength="40" name="name" id="name">
<input type="button" value="Prefill" onclick="prefill()">

I've been searching for answers all week and I think I have a basic understanding of how this is supposed to work by running a loop to search for it, but I'm having no luck in my endeavor of actually getting this to work.
Can someone show me the loop that will search my page for this button?
Thank you in advance.
Requested code so far
Private Sub Populate_Click()
    Dim i As Long
    Dim IE As Object
    Dim objElement As Object
    Dim objCollection As Object

    Set IE = CreateObject("InternetExplorer.Application")

    IE.Visible = True
    IE.Navigate "website" 'make sure you've logged into the page

    Do
        DoEvents
    Loop Until IE.READYSTATE = 3

    Do
        DoEvents
    Loop Until IE.READYSTATE = 4
    ActiveSheet.EnableCalculation = False
    ActiveSheet.EnableCalculation = True
    Call IE.document.getelementbyid("name").SetAttribute("value", ActiveSheet.Range("b2").Value)
    Call IE.document.getelementbyid("aw_login").SetAttribute("value", ActiveSheet.Range("a2").Value)

    Set objCollection = IE.document.getElementsByTagName("input")
    i = 0
    While i < objCollection.Length
        If objCollection(i).Type = "button" And _
            objCollection(i).Name = "Prefill" Then
                Set objElement = objCollection(i)
        End If
        i = i + 1
    Wend
    objElement.Click
End Sub

A: Looks like you are pretty close, this is what I have used to do something similiar
    With ie.document

        Set elems = .getelementsbytagname("input")
        For Each e In elems
            If (e.getattribute("className") = "saveComment") Then
                e.Click
                Exit For
            End If
        Next e

    End With

You will probably just have to change the if statement.
I also notice that your code refers to .Name = "Prefill" but your html snippet refers to .value = "Prefill"


text:
Q: Emacs in a Debian 8 chroot environment? I'm working with a Debian maintainer on a failed self test for a software package under ARMEL. The maintainer was kind enough to help me duplicate his environment.
When I attempt to add http://ftp.debian.org/debian unstable main to the local sources.list, I get an error:
root@debian-8:/# find ./ -name sources.list
./usr/share/doc/apt/examples/sources.list
./etc/apt/sources.list
root@debian-8:/# emacs ./etc/apt/sources.list
bash: emacs: command not found

Within the environment, I cannot perform a apt-get install emacs due to a lame sources.list. I also exited chroot and added the source to /etc/apt/sources.list, but it was not carried over or made available to the chroot environment.
The host is Debian-8, x86_64, fully patched.
How do I add emacs to the chroot environment?

# apt-get install qemu-user-static debootstrap
# qemu-debootstrap --arch=armel --keyring /usr/share/keyrings/debian-archive-keyring.gpg \
  --variant=buildd --exclude=debfoster unstable debian-armel http://ftp.debian.org/debian
# chroot debian-armel
# apt-get install devscripts
[add 'deb-src http://ftp.debian.org/debian unstable main' to /etc/apt/sources.list]
# cd
# apt-get update && apt-get source libcrypto++
# cd libcrypto++-*
# debuild

A: I understand you do not know how to use alternative editors like vi or nano. Hence, inside your chroot:

*

*First try directly installing emacs,
   apt-get install emacs

If this works, fine. Otherwise:

*Copy your current sources.list out of the way:
 cd /etc/apt
 cp sources.list sources.list.old

*Now let us build a new sources.list :
 cat "deb http://ftp.us.debian.org/debian/ jessie main contrib non-free" > sources.list

 cat "deb http://security.debian.org/ jessie/updates main contrib non-free" >> sources.list

 cat "deb http://ftp.us.debian.org/debian/ jessie-updates main contrib non-free" >> sources.list

 cat "deb http://ftp.us.debian.org/debian/ jessie-proposed-updates main contrib non-free" >> sources.list

 cat "deb http://ftp.debian.org/debian/ jessie-backports main contrib non-free" >> sources.list

Please do not confuse >> with >. Also, please notice this is for the current Debian stable, a.k.a jessie. Should you wish any other version, like wheezy or unstable, you will have to substitute for jessie in the commands above the name of the version you have installed.

*Now we are ready:
 apt-get update
 apt-get install emacs


text:
Q: Why aren't my RadioButtons & JLabels showing? i created a component which extends a JDialog. It creates a JPanel (with a big size) inside a JScrollPane. Then i add RadioButtons and JLabels to the JPanel
two problems :
 1 - the RadioButtons and JLabels don't show.
 2 - the scrollBars of the JScrollPane don't show
here is my code :
public class xuggleJOptionPane1 extends JDialog{

    Container pane;
    JPanel paneMain;
    JLabel ms1;
    xuggleJOptionPane1 myFrame;
    JPanel panel;
    JScrollPane paneScroll;
    JPanel paneScrollpanel;

    public xuggleJOptionPane1(JFrame parent, String str, int nf)
    {
        super(parent, str);

        myFrame = this;
        myFrame.setPreferredSize(new Dimension(400, 160));
        myFrame.setSize(new Dimension(400, 160));

        panel = new JPanel();
        panel.setSize(400, 160);

        ms1 = new JLabel();

        paneScroll = new JScrollPane();

        paneScroll.setPreferredSize(new Dimension(380,100));

        paneScrollpanel = new JPanel();

        paneScrollpanel.setPreferredSize(new Dimension(1600, 1600));
        //if i add this line the whole paneScrollpanel disappears
        //paneScrollpanel.setSize(1600, 1600);

        String pl ="";
        if (nf != 1) pl = "es";
        String s1 = "We found " + nf + " flux"+pl+". Which one do you wanna choose ?";

        ms1.setText(s1);

        ArrayList<JRadioButton> Buttons = new ArrayList<JRadioButton>();
        ArrayList<JLabel> Labels = new ArrayList<JLabel>();

        ButtonGroup group = new ButtonGroup();
        for (int i = 0; i < nf; i++)
        {
            Buttons.add(new JRadioButton());
            Labels.add(new JLabel("test"));
            paneScrollpanel.add(Buttons.get(i));
            paneScrollpanel.add(Labels.get(i));
            group.add(Buttons.get(i));
        }
        Buttons.get(0).setSelected(true);

        paneScroll.add(paneScrollpanel);
        panel.add(ms1);
        panel.add(paneScroll);
        myFrame.add(panel);

        myFrame.setVisible(true);
        myFrame.setResizable(false);
    }

}

A: Change
paneScroll.add(paneScrollpanel);

to
paneScroll.setViewportView(paneScrollpanel);

While I'm here...
This is kinda pointless (IMHO)
myFrame = this;
myFrame.setPreferredSize(new Dimension(400, 160));
myFrame.setSize(new Dimension(400, 160));

You could use
this.setSize(new Dimension(400, 160));

or
setSize(new Dimension(400, 160));

This is kind of pointless
panel.setSize(400, 160);

As the layout manager will make it's own decisions about what size to make the panel
You'd probably also like to look into pack
Of, on a personal note, I really, really dislike frames that aren't resizable :P


text:
Q: Why am I getting this error in the logs? Ok so I just started a new ubuntu server 11.10 and i added the vhost and all seems ok ...I also restarted apache but when i visit the browser i get a blank page
the server ip is http://23.21.197.126/ but when i tail the log
tail -f /var/log/apache2/error.log
[Wed Feb 01 02:19:20 2012] [error] [client 208.104.53.51] File does not exist: /etc/apache2/htdocs
[Wed Feb 01 02:19:24 2012] [error] [client 208.104.53.51] File does not exist: /etc/apache2/htdocs

but my only file in sites-enabled is this
<VirtualHost 23.21.197.126:80>
         ServerAdmin something@gmail.com
         ServerName logicxl.com
         # ServerAlias
         DocumentRoot /srv/crm/current/public
         ErrorLog /srv/crm/logs/error.log

           <Directory "/srv/crm/current/public">
             Order allow,deny
             Allow from all
           </Directory>
   </VirtualHost>

is there something i am missing .....the document root should be /srv/crm/current/public and not /etc/apache2/htdocs as the error suggests
Any ideas on how to fix this
UPDATE
sudo apache2ctl -S
VirtualHost configuration:
23.21.197.126:80       is a NameVirtualHost
     default server logicxl.com (/etc/apache2/sites-enabled/crm:1)
     port 80 namevhost logicxl.com (/etc/apache2/sites-enabled/crm:1)
Syntax OK

UPDATE
 <VirtualHost *:80>
    ServerAdmin something@gmail.com
    ServerName logicxl.com
    DocumentRoot /srv/crm/current/public
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /srv/crm/current/public/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

A: This sounds like apache is not finding your sites-enabled directory.
Look in your apache2.conf file (etc/apache2/apache2.conf) for a line like this:
Include sites-enabled/

Change it to an absolute path like this:
Include /etc/apache2/sites-enabled/

This should do the trick.

A: This is probably due to:
<VirtualHost 23.21.197.126:80>

Any request to http://localhost could have missed the initial vhost definition.
You then then changed it (correctly) to:
<VirtualHost *:80>

Unless you have a specific reason you should always use *:80 as this defines what address to listen on. ServerName defines what name to respond to . For example:
NameVirtualHost *:80
<VirtualHost *:80>
...
</VirtualHost>

A: You have forgot to add the new site to apache:
$ sudo a2ensite (your project name)

A: I had the same problem. However, in my case it was simply due to... sites-available/default not being linked to sites-enabled/default.
In apache2.conf I have:
Include sites-enabled/

And my sites-enabled/default:
<VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

  Alias /doc/ "/usr/share/doc/"
  <Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
  </Directory>

</VirtualHost>

A: Check that there is a VirtualHost directive for the interface IP you are making the query to. This error happens, as also detailed above, when apache can find no server configuration to answer your query - but it is listening to it in ports.conf.

A: I had exactly the same error after a system upgrade. I modified UserDir /etc/apache2/mods-enabled/userdir.conf. Original:
Userdir public_html

new:
Userdir /home/*/public_html

works great now :)


text:
Q: How to plot a plane that is parallel to the z-axis in gnuplot? When plotting a plane that is not parallel to the z-axis, one can simply solve the equation with respect to z and plot it as a function of x and y using splot. When plotting the plane x+y+z=1 for example one can just use z(x, y)=1-x-y and then splot z(x, y).
But how can I plot the plane x+y=1 in gnuplot when there is no function z(x, y) that describes it?

A: Use the parametric mode to plot such a plane:
set parametric
splot 2 - u, u, v w l

For the records, here's the full code to generate the above plot:
set ticslevel 0
set xzeroaxis
set yzeroaxis
set xlabel 'x'
set ylabel 'y'
set zlabel 'z'
set autoscale fix
set parametric
splot 2 - u, u, v w l


text:
Q: jquery/javascript initiation of File download with MVC custom BufferedMediaTypeFormatter I have a web api which is returning me a user list based on (at the moment) some simple search criteria.
 public class UserListAPIController : APIController
{

    public List<UserManagerSearchResult> Get(int siteGroupId)
    {
        return userService.UserManagerSearch(LoggedInUserToken.DefaultSiteID, siteGroupId);
    }
}

This is called from the client knockoutjs viewmodel using an ajax getJson request with a dynamically generated url based on the various filter criteria selected.
  self.LoadUsers = function () {

    var SiteGroupID = self.selectedSiteGroup();
    $.getJSON("/API/UserListAPI/?siteGroupId=" + SiteGroupID
        , function (allData) {
        var mappedUsers = $.map(allData, function (item) {
           //mapping code
            return dbu;

        });
        self.Users(mappedUsers);
    });
};

This then uses the knockout template binding to display the results nicely in a grid.
I also need to implement a "download to csv" feature which will return the exact same results as selected for the ui search listing.
So my idea was to implement a custom mediatypeformatter which would allow me to execute the same web api but return a csv response rather than a json response.
I have implemented and tested this in fiddler and is working as expected.so when I set the type to 'text/csv' and call the web api I get the csv results.
public class UserManagerSearchResultCSVFormatter : BufferedMediaTypeFormatter
{

    public UserManagerSearchResultCSVFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
    }

    public override bool CanReadType(Type type)
    {
        return false;
    }

    public override bool CanWriteType(Type type)
    {
        if (type == typeof(UserManagerSearchResult))
        {
            return true;
        }
        else
        {
            Type enumerableType = typeof(List<UserManagerSearchResult>);
            return enumerableType.IsAssignableFrom(type);
        }

    }

    public override void WriteToStream(Type type, object value, Stream writeStream,
                                       System.Net.Http.HttpContent content)
    {
        using (var writer = new StreamWriter(writeStream))
        {
            var results = value as List<UserManagerSearchResult>;
            if (results != null)
            {
                foreach (var result in results)
                {
                    WriteItem(result, writer);
                }
            }
            else
            {
                var result = value as UserManagerSearchResult;
                if (result == null)
                {
                    throw new InvalidOperationException("Cannot serialize type");
                }
                WriteItem(result, writer);
            }
        }
        writeStream.Close();
    }

    // Helper methods for serializing Products to CSV format.
    private void WriteItem(UserManagerSearchResult result, StreamWriter writer)
    {
        writer.WriteLine("{0},{1},{2}", Escape(result.UserId),
            Escape(result.UserName), Escape(result.Year));
    }

    static char[] _specialChars = new char[] { ',', '\n', '\r', '"' };

    private string Escape(object o)
    {
        if (o == null)
        {
            return "";
        }
        string field = o.ToString();
        if (field.IndexOfAny(_specialChars) != -1)
        {
            return String.Format("\"{0}\"", field.Replace("\"", "\"\""));
        }
        else return field;
    }

}

That is all the background.
I have hit a couple of issues which I don't know how best to implement.
Firstly in order for this to work I need to be able to do the following :
1. dynamically build up the url (as seen for the ajax getjson example above)
2. set the type of request to 'text/csv'
3. initite the call to the url  with the request type and force a download of the file.
This is pretty much were I am stuck as the best way to implement this. Ive been looking at some jquery ajax to try and achieve this but not getting very far and could do with someones opinions on the best way this can be implemented.


text:
Q: How to extract 2D Double Array from ifs text file (Java) affine  2
 0.62367 -0.40337   0.40337  0.62367 0.00 0.00 0.75
-0.37633 -0.40337   0.40337 -0.37633 1.00 0.00 0.25
scale 500
height 690
width 410
xOffset 134
yOffset 112
name Golden Dragon

From this text file, I want to extract an array named affine with a width of 2.
The following values separated by whitespace on the next 2 lines are the values inside the array.
I have been able to read the other variables from the text file but can't seem to figure out the array.
Here is my code so far:
 public FileIfs(File path){

         try (BufferedReader ifsReader = new BufferedReader(new FileReader(path))) {
            String line = null;
            int i = 0; int j = 0;

             while((line = ifsReader.readLine()) != null) {
                if (line.startsWith("name")) {
                    name = line.substring(4).trim();
                    System.out.println("Name: " + name);
                 }
                 if (line.startsWith("scale")) {
                    scale = Double.parseDouble(line.substring(5).trim());
                    System.out.println("Scale: " + scale);
                 }
                 if (line.startsWith("height")) {
                    height = Integer.parseInt(line.substring(6).trim());
                    System.out.println("Height: " + height);
                 }
                 if (line.startsWith("width")) {
                    width = Integer.parseInt(line.substring(5).trim());
                    System.out.println("Width: " + width);
                 }
                 if (line.startsWith("xOffset")) {
                    xOffset = Integer.parseInt(line.substring(7).trim());
                    System.out.println("xOffset: " + xOffset);
                 }
                 if (line.startsWith("yOffset")) {
                    yOffset = Integer.parseInt(line.substring(7).trim());
                    System.out.println("yOffset: " + yOffset);
                 }
                 if (line.startsWith("affine")) {
                    int arrLeng = Integer.parseInt(line.substring(6).trim());
                    System.out.println("Array Length: " + arrLeng);

                    affine = new double[arrLeng][7];
                 }
                 else {
                    if (line.startsWith(" ")) {
                        line.trim();
                    }

                    String currentLine [] = line.split("\\s+");

                    if (!line.trim().isEmpty()){
                        for (String s : currentLine) {
                            if (!s.trim().isEmpty()) {
                                affine[i][j++] = Double.parseDouble(s);
                            }
                        }
                        line = ifsReader.readLine();
                        i++;
                        j = 0;
                    }

                 } //end of ifelse
             } //loop through every line of file
             ifsReader.close();
         }
         catch (Exception e) {
             System.out.println("could not find file");
         }  //end of try-catch
    }

The code in the else section is where I am attempting to read the array.
If anyone could help out, or point me in the right direction that would be great.
Thanks.

A: A possible solution. It uses lists to persist array data. If you need, it's easy to convert a list to a real array.
public void fileIfs(Path path) throws IOException {
    try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {

        // ------- read parameters -------

        Pattern paramPattern = Pattern.compile("([A-Za-z]+)\\s+([\\w\\s]+)");
        Matcher paramMatcher = paramPattern.matcher(lines.collect(Collectors.joining(",")));
        Map<String, String> params = new HashMap<>();

        while (paramMatcher.find()) {
            params.put(paramMatcher.group(1), paramMatcher.group(2));
        }
        String name = params.get("name");
        int affine = Integer.parseInt(params.get("affine"));
        int scale = Integer.parseInt(params.get("scale"));
        int height = Integer.parseInt(params.get("height"));
        int width = Integer.parseInt(params.get("width"));
        int xOffset = Integer.parseInt(params.get("xOffset"));
        int yOffset = Integer.parseInt(params.get("yOffset"));

        // ------- read array -------

        List<List<Double>> affineList = new ArrayList<>();
        Pattern arrayPattern = Pattern.compile("([\\-\\d]+\\.\\d+)");

        lines.forEach(line -> {
            Matcher arrayMatcher = arrayPattern.matcher(line);
            List<Double> numbers = new ArrayList<>();
            while (arrayMatcher.find()) {
                numbers.add(Double.parseDouble(arrayMatcher.group(1)));
            }
            if (!numbers.isEmpty()) {
                affineList.add(numbers);
            }
        });

        // ---------------

        System.out.println("params: " + params);
        System.out.println("affineList: " + affineList);
    }
}

Output:
params: {yOffset=112, xOffset=134, width=410, name=Golden Dragon, scale=500, affine=2, height=690}
affineList: [[0.62367, -0.40337, 0.40337, 0.62367, 0.0, 0.0, 0.75], [-0.37633, -0.40337, 0.40337, -0.37633, 1.0, 0.0, 0.25]]


text:
Q: Why does append() and += give different results when I want to add a dictionary into a list in Python? I want to append a dictionary germany into a list travel_log.
travel_log = [
{
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
}]
germany = {
  "country": "Germany",
  "visits": 5,
  "cities": ["Berlin", "Hamburg", "Stuttgart"]
}

When I use travel_log += germany, the result is
[{'country': 'France', 'visits': 12, 'cities': ['Paris', 'Lille', 'Dijon']}, 'country', 'visits', 'cities'].
The values in germany disappeared.
But when I use travel_log.append(germany), the result is
[{'country': 'France', 'visits': 12, 'cities': ['Paris', 'Lille', 'Dijon']}, {'country': 'Germany', 'visits': 5, 'cities': ['Berlin', 'Hamburg', 'Stuttgart']}]
This is the correct one.
Why these two results are diffrent?

A: Because += extends the list with another iterable, and iterating over a dict iterates over the keys (try print(list(germany))).
You'd get the same effect with travel_log.extend(germany).
.append(x) doesn't iterate over x, it just appends it as-is to the list.

A: The two results are different because += and .append are designed to do completely different things.
.append adds a value to the end of a list. For example:
a = [1, 2, 3]
a.append(4)
print(a)
# => [1, 2, 3, 4]

+= adds all the values from another iterable to the end of the list - it does the same as .extend. If you tried to do a += 4 in the example above, it would error as 4 is not an iterable.
However, you are adding a dictionary, and a dictionary is an iterable - iterating over it will iterate over its keys. Hence += here does not error, but instead adds all the keys of the dictionary to the list (without erroring).


text:
Q: I can't induce a contradiction by assuming negation, what does that imply? Suppose I want to prove that $A \Rightarrow B$. So I assume $A$ and $\neg B$ and hope to arrive at a contradiction. But suppose $\neg B$ does not induce any contradiction - I don't mean "suppose I fail to spot any contradictions", I mean let's pretend I have proven that no contradictions arise (if that's even formally possible to do). Does this mean that I have proven $A \not \Rightarrow B$?
I mean, I have shown that $\neg B$ is consistent with $A$, or that $\neg B \not \Rightarrow \neg A$. But I'm no formal logic expert so I'm not convinced that this is equivalent to $A \not \Rightarrow B$. Help?

A: On way to prove $A \Rightarrow B$ is to assume $\neg B$ and arrive at (not a contradiction) but $\neg A$.
If you prove that no contradiction follows from $\neg B$, all that shows is that $\neg B$ is internally consistent. But it doesn't follow that it is consistent with $A$.
For example suppose $A = B$. Showing that $\neg B$ (i.e. $\neg A$) entails no contradiction doesn't show that $\neg B$ (i.e. $\neg A$) is consistent with $A$!

A: $(A \Rightarrow B) \Leftrightarrow (\neg B \Rightarrow  \neg A)$
The right statement is called the contrapositive.
What they are saying is that the satisfaction of $A$ results in a satisfaction of $B$.
If you happen to show that there are cases where $\neg B$ is satisfied but $\neg (\neg A)$ isn't then you have proved that $\neg B \not \Rightarrow \neg A$. At this point, this is telling us that there are cases where $\neg B $ and $A$ are simultaneously verified. What does this mean? it means that we can have $A$ satisfied and not be satisfied by $B$. Thus it does imply $A \not \Rightarrow B$ and your assumption is correct.


text:
Q: Apollo: Using executor function server side removes operation names I currently have the following code in a codebase using "@apollo/client": "^3.4.17",
const getFrontEndApiSchema = async (authToken: string, hostname: string) => {
  const executor = async ({
    document,
    variables,
  }: Parameters<Parameters<typeof introspectSchema>[0]>[0]) => {
    const fetchResult = await crossFetch(`${resolveApiUri(hostname)}/graphql`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authentication-Token': authToken,
      },
      body: JSON.stringify({ query: print(document), variables }),
    })
    return fetchResult.json()
  }
  return makeExecutableSchema({
    typeDefs: wrapSchema({
      schema: buildClientSchema(await unzipSchema()),
      executor,
    }),
  })
}

export const getSchema = async () => {
  const frontEndSchema = await getFrontEndApiSchema()
  return stitchSchemas({
    subschemas: frontEndSchema ? [frontEndSchema, schema] : [schema],
    mergeDirectives: true,
  })
}

  const apolloClient = createApolloClient(
      {
        schema,
        rootValue: { request: req },
      },
      getAuthenticationToken(req),
      false,
    )

Which works and fires off requests. However we noticed during a Telemetry exercise (whereby we are trying to track traces through individual operations in DataDog / NewRelic) that a single operation is effectively being split up into it's constituent queries and sent without it's parent operation name.
It's not so clear to me from reading the docs why I would need to this executor function for graphql queries rather than the standard Apollo link chain (similar to what i'm using for the client side apollo client).
So I removed the unneeded executor function to the following.
  makeExecutableSchema({
    typeDefs: wrapSchema({
      schema: buildClientSchema(await unzipSchema()),
    }),
  })

This worked in so far as  the operations where being made and return a result, however ostensibly it was returning results which matched those which would be returned if unauthenticated, (i.e. no authentication token set in the header).
I've checked my error link and have logged context headers and it appears to have the token.
I've also tried swapping the Schemalink for a normal link with no success.
export default function createApolloClient(
  schema: SchemaLink.Options,
  token: string,
  isTest?: boolean,
) {
  const link = from([
    authLink(token),
    serverErrorLink(),
    ...(__DEV__ ? [logLink(true)] : []),
    new SchemaLink(schema),
  ])

  return new ApolloClient({
    link,
    cache: createCache(),
    ssrMode: true,
    queryDeduplication: true,
    ...(!isTest && {
      defaultOptions: {
        watchQuery: {
          fetchPolicy: 'cache-and-network',
        },
        query: { fetchPolicy: 'cache-first' },
      },
    }),
  })
}

A typical graphql operation I'm sending

query myOperationName{
  user {
    id
    firstName
  }
  query2{
    id
  }
  query3{
    id
  }
}

When I do print(document) in the body of my original executor function I am getting
query2{
    id
  }

etc
So my question is how server side do I construct the correct Apollo client/ link chain combo  such that operations are not stripped of their operation names? And any additional clarity on whether it's necessary to use the SchemaLink at all if my express server is on a different box to the api it talks to would be helpful


text:
Q: Keep unique index (or id) in pandas when appending I want to add a new row in pandas DataFrame. But also, I want to have another DataFrame that references the first one.
For example, I have a table with news, each row is a unique news, e.g.
pd.DataFrame.from_dict({0: ['company1 is bankrupt'],
                        1: ['company2 and company3 are going to merge. company1 is good'],
                        2: ['company3 is going to create a new product. CEO of company3 says it will be a good product']}, orient='index', columns=['text'])

I also want to keep information on what companies are in each news and how many times each one appears in the text. I want to create a new dataframe such as:
index company  freq
news1 company1 2
news1 company2 1
news2 company3 3

...
But to do this, I need to have stable id of a news, but if I append, I need to reindex. and if I deleted a news in the middle, then reindex, id will be changed, so appending a new row can change my id, so I can't reference this id. What should I do? Maybe I should create a dataframe (or dictionary) in dataframe to get rid of this problem?

A: Why not simply, as you said, create an ID for the news? It doesn't need to be in the index. Simply do:
df['news_id'] = [i for i in range(len(df))]

This will attach an ID (duplicate to your index, probably) to each news. Now you can just reference news_id in your appended rows, without worrying about the index.
EDIT: If you are regularly updating the database, you can simply use a more complex ID creator. Something like:
import random
characters = 'abcdefghijklmnopqrstuvwxyz123456789'
used_ids = []
def pick_id():
    global used_ids #this allows us to use and modify the used_ids list in the function
    ID = ''.join([random.choice(characters) for i in range(16)]) #arbitrary length of 16 for IDs
    while ID in used_ids: #this simply repeats the generation of IDs if the ID is already in used_ids
        ID = ''.join([random.choice(characters) for i in range(16)])
    used_ids.append(ID) #now add the used ID to used_ids
    return ID

Now you can simply do:
df['news_id'] = [pick_id() for i in range(len(df))]

This requires that you keep track of news_id but it's not so bad: whenever you run this program you can read your new dataframe like thus:
used_ids = list(set(list(new_dataframe['news_id'])))

That will give you all unique IDs already taken.


text:
Q: Passing a mock DOM event to component method in Angular for unit testing I am trying to test a method in one of my components as follows:
toggle(event: Event): void {
    event.stopPropagation();
    this.isCollapsed = !this.isCollapsed;
}

I cannot find a way to pass the event object to the method in the unit test case for example:
test('it should call stop propagation when toggled', () => {
    testHostComponent.toggleLineBreakDown(mockEventGoesHere, 0);
});

A: You can test that preventDefault has been called via a Jasmine Spy.
You will have to create the event you are listening to, before using the SpyOn method. (In the following example it's a 'click' event). After creating the event and the spy, you will then need to dispatch the event to the element.
As an example:
const event = new MouseEvent('click');
spyOn(event, 'preventDefault');

element.dispatchEvent(event);
expect(event.preventDefault).toHaveBeenCalled();

Hopefully this helps!


text:
Q: The stalk as a colimit From Vakil's notes:

The notion of colimit is defined for diagrams $D:I\to\textbf{Set}$. The colimit of $D:I\to\textbf{Set}$ is the limit of $D^{op}:I^{op}\to \mathbf{Set}^{op}$. What exactly is the diagram $D:I\to\textbf{Set}$ in 2.2.5? Well, I guess $I$ is given (it's the category whose objects are all open sets containing $p$), and I thought $D$ acts on objects by sending $U$ to $\mathscr F(U)$. But $\mathscr F$ is a contravariant functor, so the $D$ that I defined should be a functor with domain $I^{op}$. How to sort out this mess?
Now, to see that this definition of stalk is equivalent to the non-categorical one, I guess one needs to explicitly describe the colimit. The (vertex of the) colimit (cocone) in this case is $\sum_I \mathscr F (U)$ modulo the equivalence relation generated by something like $\{(f,res_{V,U}(f)): f\in \mathscr F (V), U\subset V\text{ in } I \}$. How is this the same as the set of equivalence classes of pairs of the form $(g,U)$? There is a "type" mismatch.

A: Consider the partial order $\mathcal{O}_X^{op}$, expressed as a category.
That is, $U \to V$ is the set $\{0 \mid V \subseteq U\}$. There is exactly 1 arrow $U \to V$ if and only if $V \subseteq U$, and there is no arrow $U \to V$ otherwise.
Now $\mathscr{F}$ is a functor $\mathcal{O}_X^{op} \to Sets$.
Consider the full subcategory $Neigh_p$ of $\mathcal{O}_X^{op}$, which contains only those open sets that are neighbourhoods of the point $p \in X$. Let $i : Neigh_p \to \mathcal{O}_X^{op}$ be the fully faithful inclusion functor.
Then the colimit is taken over the diagram $\mathscr{F} \circ i : Neigh_p \to Sets$.
To show that this definition is equivalent to the non-categorical one, you need to prove the universal property of the colimit for the non-categorical definition.

A: The key here is to reverse the ordering. In the definition of direct limit, you have morphisms $A_i \rightarrow A_j$ for $i < j$, that is: from the small element to the big element. In this case, you have a restriction morphism $F(U) \rightarrow F(V)$ if $V \subseteq U$, that is : from the big set to the small set.
Therefore, define the partial order on open sets of $X$ as $U < V$ iff $V \subseteq U$.