text:
Q: Why am I getting this error while installing pygame in pycharm Command "python setup.py egg_info" failed with error code 1 in C:\Users\Eli Heist\AppData\Local\Temp\pip-install-fjf50xi9\pygame\
this is the full process
(venv) C:\Users\Eli Heist\PycharmProjects\Space Invaders Ultimate>pip install pygame
Collecting pygame
  Downloading https://files.pythonhosted.org/packages/c7/b8/06e02c7cca7aec915839927a9aa19f749ac17a3d2bb2610b945d2de0aa96/pygame-2.0.1.tar.gz (5.5MB)

    100% |████████████████████████████████| 5.5MB 996kB/s
    Complete output from command python setup.py egg_info:

    WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
    Using WINDOWS configuration...

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Eli Heist\AppData\Local\Temp\pip-install-fjf50xi9\pygame\setup.py", line 318, in <module>
        buildconfig.config.main(AUTO_CONFIG)
      File "C:\Users\Eli Heist\AppData\Local\Temp\pip-install-fjf50xi9\pygame\buildconfig\config.py", line 221, in main
        deps = CFG.main(**kwds)
      File "C:\Users\Eli Heist\AppData\Local\Temp\pip-install-fjf50xi9\pygame\buildconfig\config_win.py", line 574, in main
        return setup_prebuilt_sdl2(prebuilt_dir)
      File "C:\Users\Eli Heist\AppData\Local\Temp\pip-install-fjf50xi9\pygame\buildconfig\config_win.py", line 499, in setup_prebuilt_sdl2
        DEPS.configure()
      File "C:\Users\Eli Heist\AppData\Local\Temp\pip-install-fjf50xi9\pygame\buildconfig\config_win.py", line 336, in configure
        from . import vstools
      File "C:\Users\Eli Heist\AppData\Local\Temp\pip-install-fjf50xi9\pygame\buildconfig\vstools.py", line 11, in <module>
        compiler.initialize()
      File "C:\Users\Eli Heist\AppData\Local\Programs\Python\Python38\lib\distutils\msvc9compiler.py", line 372, in initialize
        vc_env = query_vcvarsall(VERSION, plat_spec)
      File "C:\Users\Eli Heist\PycharmProjects\Space Invaders Ultimate\venv\lib\site-packages\setuptools-40.8.0-py3.8.egg\setuptools\msvc.py", line
147, in msvc9_query_vcvarsall
      File "C:\Users\Eli Heist\PycharmProjects\Space Invaders Ultimate\venv\lib\site-packages\setuptools-40.8.0-py3.8.egg\setuptools\msvc.py", line
1227, in return_env
      File "C:\Users\Eli Heist\PycharmProjects\Space Invaders Ultimate\venv\lib\site-packages\setuptools-40.8.0-py3.8.egg\setuptools\msvc.py", line
876, in VCIncludes
      File "C:\Users\Eli Heist\PycharmProjects\Space Invaders Ultimate\venv\lib\site-packages\setuptools-40.8.0-py3.8.egg\setuptools\msvc.py", line
555, in VCInstallDir
    distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.2 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualst
udio.microsoft.com/downloads/
    Making dir :prebuilt_downloads:
    Downloading... https://www.libsdl.org/release/SDL2-devel-2.0.14-VC.zip 48d5dcd4a445410301f5575219cffb6de654edb8
    Unzipping :prebuilt_downloads\SDL2-devel-2.0.14-VC.zip:
    Downloading... https://www.libsdl.org/projects/SDL_image/release/SDL2_image-devel-2.0.5-VC.zip 137f86474691f4e12e76e07d58d5920c8d844d5b
    Unzipping :prebuilt_downloads\SDL2_image-devel-2.0.5-VC.zip:
    Downloading... https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-devel-2.0.15-VC.zip 1436df41ebc47ac36e02ec9bda5699e80ff9bd27
    Unzipping :prebuilt_downloads\SDL2_ttf-devel-2.0.15-VC.zip:
    Downloading... https://www.libsdl.org/projects/SDL_mixer/release/SDL2_mixer-devel-2.0.4-VC.zip 9097148f4529cf19f805ccd007618dec280f0ecc
    Unzipping :prebuilt_downloads\SDL2_mixer-devel-2.0.4-VC.zip:
    Downloading... https://www.ijg.org/files/jpegsr9d.zip ed10aa2b5a0fcfe74f8a6f7611aeb346b06a1f99
    Unzipping :prebuilt_downloads\jpegsr9d.zip:
    Downloading... https://pygame.org/ftp/prebuilt-x64-pygame-1.9.2-20150922.zip 3a5af3427b3aa13a0aaf5c4cb08daaed341613ed
    Unzipping :prebuilt_downloads\prebuilt-x64-pygame-1.9.2-20150922.zip:
    copying into .\prebuilt-x64
    Path for SDL: prebuilt-x64\SDL2-2.0.14
    ...Library directory for SDL: prebuilt-x64/SDL2-2.0.14/lib/x64
    ...Include directory for SDL: prebuilt-x64/SDL2-2.0.14/include
    Path for FONT: prebuilt-x64\SDL2_ttf-2.0.15
    ...Library directory for FONT: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64
    ...Include directory for FONT: prebuilt-x64/SDL2_ttf-2.0.15/include
    Path for IMAGE: prebuilt-x64\SDL2_image-2.0.5
    ...Library directory for IMAGE: prebuilt-x64/SDL2_image-2.0.5/lib/x64
    ...Include directory for IMAGE: prebuilt-x64/SDL2_image-2.0.5/include
    Path for MIXER: prebuilt-x64\SDL2_mixer-2.0.4
    ...Library directory for MIXER: prebuilt-x64/SDL2_mixer-2.0.4/lib/x64
    ...Include directory for MIXER: prebuilt-x64/SDL2_mixer-2.0.4/include
    Path for PORTMIDI: prebuilt-x64
    ...Library directory for PORTMIDI: prebuilt-x64/lib
    ...Include directory for PORTMIDI: prebuilt-x64/include
    DLL for SDL2: prebuilt-x64/SDL2-2.0.14/lib/x64/SDL2.dll
    DLL for SDL2_ttf: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64/SDL2_ttf.dll
    DLL for SDL2_image: prebuilt-x64/SDL2_image-2.0.5/lib/x64/SDL2_image.dll
    DLL for SDL2_mixer: prebuilt-x64/SDL2_mixer-2.0.4/lib/x64/SDL2_mixer.dll
    DLL for portmidi: prebuilt-x64/lib/portmidi.dll
    Path for FREETYPE not found.
    ...Found include dir but no library dir in prebuilt-x64.
    Path for PNG not found.
    ...Found include dir but no library dir in prebuilt-x64.
    Path for JPEG not found.
    ...Found include dir but no library dir in prebuilt-x64.
    DLL for freetype: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64/libfreetype-6.dll

    ---
    For help with compilation see:
        https://www.pygame.org/wiki/CompileWindows
    To contribute to pygame development see:
        https://www.pygame.org/contribute.html
    ---

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Eli Heist\AppData\Local\Temp\pip-install-fjf50xi9\pygame\

A: Today my friends met the same questions.
It seems that pygame has been not suit to python3.11.0,becase I can install it by python 3.10.7 but not by python 3.11.0.So you can use python3.10.7 instead of python3.11.0 to solve this quesiton.

A: You are seeing this error because pip is attempting to compile the complete SDL library for pygame, and your machine is missing the build requirements to do so. This is in your error message:
Microsoft Visual C++ 14.2 is required

Luckily, pygame offers pre-compiled binaries for most operating systems so you don't have to compile yourself. They are distributed as Python wheels. All you should have to do to access the pre-compiled version is install wheel:
C:\>pip install wheel
C:\>pip install pygame

A: I am not sure how this problem can be solved but I will try to help.
Try the following things:

*

*Don't install it for that specific project. Try to just go to cmd and install it for your whole python env.

*Make sure python is properly installed in the PATH variable.

*Try to use py -m pip install -U pygame --user instead. If that doesn't work, try python3 -m pip install -U pygame --user.

If you are using python 3.8 and/or none of the above methods work, you have two options: either revert to python 3.7 or wait for pygame to get updated. Pygame is known to function improperly in python 3.8. I had faced the same issue and I solved it by switching to python 3.7 for pygame projects and the latest version for other python projects.


text:
Q: NodeJS include header and footer without EJS I was hoping someone may be able to assist me with NodeJS. Iv recently started developing my site using NodeJS.
The problem:
im looking for a way to send my documents as a header, content, footer style so it reduces repeating code for each section.
I have a public folder setup so i can include Js, CSS and common files etc...
self.app.use(express.static(__dirname + '/public'));

This all works, however im unsure about how to implement a simple way to join the file content. Every source iv looked at online suggests the "correct" way to do it is via a package called EJS templates.
So im looking for something similar to this implementation in EJS:
<header>
    <% include ../partials/header %>
</header>

<footer>
    <% include ../partials/footer %>
</footer>

However, the service im hosting on does not support EJS, so is it possible to do something like this?
self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('header.html')+self.cache_get('index.html')+self.cache_get('footer.html') );
        };

Is there another simple way to separate header, content and footer to make it simpler to develop website with dynamic content?

A: Trumpet should let you do this. Something like this may work:
const trumpet = require('trumpet')
const tr = trumpet()

tr.pipe(res)

const header = tr.select('header').createWriteStream()
fs.createReadStream('header.html').pipe(header)

const footer = tr.select('footer').createWriteStream()
fs.createReadStream('footer.html').pipe(footer)

fs.createReadStream('index.html').pipe(tr)

A: While you could write your own js to do this, at your current level I don't recommend it (other than for learning and experimental purposes). This is why node is so powerful, because you don't have to reinvent the wheel all the time. You noted that you are using openshift, and that you cannot use modules. This is where you are incorrect.
This link explains how to use npm with openshift. It would be extremely silly for any node.js hosting service to not allow package integration. To briefly explain how this works, you essentially install your packages in your local environment using the --save flag. This will update your local package.json file with details about your dependencies and versions. When you push your repo to your host, it looks at this file, and takes care of the dependency installation for you.
On this note, if you are going to continue using node.js, you should have a good read about package management. https://docs.npmjs.com/how-npm-works/packages

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can't I capture a MetaInspector::TimeoutError inside an Async block in Ruby 3 with Async 2.3.0 and MetaInspector 5.13.0? I am using Ruby 3.0.0, MetaInspector 5.13.0, and socketry's Async 2.3.0 to scrape the meta from a list of urls. I set the connection and read timeouts as per the documentation for MetaInspector and test with httpbin's delay endpoint. MetaInspector's documentation notes I should be able to capture a MetaInspector::Timeout error but instead the Async block errors out uncaptured, even if I capture all errors. Here is my test script called timeout_error.rb:
require 'async'
require 'metainspector'

urls = ["https://httpbin.org/delay/15", "https://www.google.com"]

Async do

  urls.each do |url|

    Async do

      begin
        page = MetaInspector.new(url, connection_timeout: 10, read_timeout: 5, allow_non_html_content: true)
      rescue MetaInspector::TimeoutError
        puts "rescued MetaInspector's TimeoutError"
      rescue => e
        puts "rescued everything else, type: #{e.class}, message: #{e.message}"
      end

      puts "made it to the end of the nested Async block with #{url}"
    end
  end
end

Here is my output from the shell:
meta_collector git:(master) ✗ ruby -v
ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-darwin21]
meta_collector git:(master) ✗ ruby bin/timeout_error.rb
made it to the end of the nested Async block with https://www.google.com
.../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/async/scheduler.rb:213:in `select': execution expired (Timeout::Error)
    from .../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/async/scheduler.rb:213:in `run_once'
    from .../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/async/scheduler.rb:232:in `run'
    from .../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/kernel/async.rb:32:in `Async'
    from bin/timeout_error.rb:6:in `<main>'

I expect to see once the "rescued everything else..." alongside two "made it to the end of the nested.." output, but I never do. Anyone have any insights here?


text:
Q: Angular's $scope doesn't work within PayPal methods promises In PayPal promises, my $scope seems to be broken:
onAuthorize: function(data, actions) {

  paypal.request.post(execute_payment_url)
    .then(function(data) {

      $rootScope.loader = true; // no response?!

      if (data.payment.state === 'approved') {
        alert('hey!') // worked

        $location.path('/signup/').search({ // no response
          email: data.payment.payer.payer_info.email
        });
      }

    })
    .catch(function(err) {
      alert('error')
    }).finally(function() {
      $rootScope.loader = false;
    })
}

I have no clue why, $rootscope and $location have already been injected in my controller. When I call console.log($location), I can see the object is there.

A: This is happening because the PayPal promise is not an AngularJS $q Service promise. $q Service promises are integrated with the AngularJS framework digest cycle. It can be brought into the $q Service promise event queue with $q.when.
onAuthorize: function(data, actions) {

  //paypal.request.post(execute_payment_url)
  $q.when(paypal.request.post(execute_payment_url))
    .then(function(data) {

      $rootScope.loader = true; // no response?!

      if (data.payment.state === 'approved') {
        alert('hey!') // worked

        $location.path('/signup/').search({ // no response
          email: data.payment.payer.payer_info.email
        });
      }

    })
    .catch(function(err) {
      alert('error')
    }).finally(function() {
      $rootScope.loader = false;
    })
}

$q.when
Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

-- AngularJS $q Service API Reference - $q.when.

A: The issue might be that you are using the paypal library instead of the angular $http service to make the request. Because of that, angular does not know it needs to update data. In order to force it to, you can $apply the changes manually:
onAuthorize: function(data, actions) {
  paypal.request.post(execute_payment_url)
    .then(function(data) {
      $rootScope.$apply(function() {

        $rootScope.loader = true; // no response?!

        if (data.payment.state === 'approved') {
          alert('hey!') // worked

          $location.path('/signup/').search({ // no response
            email: data.payment.payer.payer_info.email
          });
        }
      });
    })
    .catch(function(err) {
      alert('error')
    }).finally(function() {
      $rootScope.$apply(function() { $rootScope.loader = false; });
    })
}

[[Update]]
Moved the $apply statements inside the success/finally callbacks.


text:
Q: Asking Nix for metadata about the given package I'm using Nix on macOS and on (non-NixOS) Linux. I'd like to give Nix a package or attribute name and have it show me

*

*the latest version number of that package that Nix knows about and

*the path to my local copy of the corresponding .nix file (or maybe a URL to that .nix file within the nixpkgs repository on GitHub).

I'm essentially looking for the Nix equivalent of Homebrew's brew info packagename.
How can I get Nix to give me these pieces of information?

A: With nix-env on the CLI, I think the best we can currently and (relatively) conveniently do is JSON or XML:
$ nix-env --query --available --attr nixpkgs.hello --meta --json

# Or in terse form:
$ nix-env -qaA nixpkgs.hello --json

Neither output nor input are especially human-friendly, typical Nix usability…
The path to the .nix file is listed as position, also in the REPL as in Robert's neat answer it's hello.meta.position. It is worth mentioning nix edit nixpkgs.hello, for opening the file.

A: Perhaps there's a better way, like with nix-env, but I usually use nix repl for this purpose.
$ nix repl '<nixpkgs>'
Welcome to Nix version 2.2.2. Type :? for help.

Loading '<nixpkgs>'...
Added 10069 variables.

nix-repl> docker-c[TAB]
docker-compose         docker-credential-gcr
nix-repl> docker-compose.version
"1.23.1"


text:
Q: How to revoke access to system.* table for db user? I'm creating a user with the following permissions:
CREATE USER IF NOT EXISTS U371bqJkJ6sGJ IDENTIFIED WITH sha256_password BY '...O4CqSR1' SETTINGS PROFILE 'default' DEFAULT ROLE user GRANTEES NONE
REVOKE ALL ON *.* FROM U371bqJkJ6sGJ
GRANT SHOW DATABASES ON U371bqJkJ6sGJ.* TO U371bqJkJ6sGJ
GRANT SELECT ON U371bqJkJ6sGJ.* TO U371bqJkJ6sGJ

But for some reason, he can read system.* tables, e.g.
SELECT * FROM system.errors

How to revoke access to the system tables?
Thanks!

A: here is the only way https://github.com/ClickHouse/ClickHouse/issues/24887
create user foo identified by '123';
revoke all on *.* from foo;

create role RO;

CREATE ROW POLICY ro_query_log_filter  ON system.query_log USING 1 AS RESTRICTIVE TO RO;
CREATE ROW POLICY ro_part_log_filter  ON system.part_log USING 1 AS RESTRICTIVE TO RO;
CREATE ROW POLICY ro_trace_log_filter ON  system.trace_log USING 1 AS RESTRICTIVE TO RO;
CREATE ROW POLICY ro_processes_filter ON  system.processes USING 1 AS RESTRICTIVE TO RO;

grant RO to foo;
ALTER USER foo DEFAULT ROLE RO SETTINGS NONE;

clickhouse-client -u  foo --password=123

select count() from system.trace_log;
0 rows in set.

select count() from system.query_log;
0 rows in set.

select count() from system.tables;
0 rows in set.

select query from system.processes;
0 rows in set


text:
Q: powershell - zabbix take cpu processes and send in % i want monitor windows cpu processes in % by zabbix but zabbix item proc.cpu.util[Sqlsvr.exe] is not supported in windows.
so i try to do a script in powershell and executed by zabbix, i don't know if its a good idea, do you have idea ?
my powershell script to take cpu process in %:
$test = Get-WmiObject -class Win32_PerfFormattedData_PerfProc_Process
-filter "Name='chrome'" |
    Select-Object @{ Expression = {$_.PercentProcessorTime}} |Format-Table -AutoSize
     echo $test

do you have idea to take cpu process in % or take only cpu process in % ?

A: Zabbix expects a numeric value from a plugin. It is not designed to give you statistics you are looking for, that would be performance tools like Newrelic.  Your code returns a collection of processes. try this for chrome process:
# Declare collection
$t = New-Object System.Collections.ArrayList;
# For loop 5 times
For ($i=0; $i -lt 5; $i++) {
    # Add slot cpu time
    [void]$t.Add( (Get-Counter "\Process(chrome)\% Processor Time").CounterSamples.CookedValue );
    sleep -Seconds 1;
}
# Return average with two decimal places
write-host ([math]::Round(($t | Measure-Object -Average).Average, 2));


text:
Q: Swift, iOS: How to get Polymorphic and Decouple Coordinator from concrete type I have these protocols:
protocol Coordinator {
    var rootViewController: UIViewController { get set }
    func start()
}

protocol UIViewControllerFactory {
    func mainViewController() -> UIViewController
}

And I created a MainCoordinator that conforms to this protocol and I pass a factory that allows me to decouple the coordinator from creating and capturing a concrete type so it can be polymorphic and can be used with more implementations of UIViewController either as rootViewControllers and mainMenuViewController as shown below:
class MainCoordinator: Coordinator {
    var rootViewController: UIViewController
    let factory: UIViewControllerFactory

    init(rootViewController: UIViewController, factory: UIViewControllerFactory) {
        self.rootViewController = rootViewController
    }

    start() {
        guard let mainVC = factory.mainViewController() as? MainViewController, let rootViewController = rootViewController as? UINavigationViewController  else { return }

        mainVC.delegate = self
        rootViewController.push(mainVC, animated: true)
    }

As you can see, although I've created the coordinator to accept any subclass of UIViewController it has been coupled in the start function to the concrete implementation of UIViewController: MainViewController.
So my question is how to decouple it from MainViewController and have it more polymorphic?

A: You can pass coordinator as a parameter type in factory function and set delegate directly in factory function while creating controller instance. That way you wouldn't have to expose controller type explicitly out of factory classes.
I came up with below approach.
protocol Coordinator {
    var rootViewController: UIViewController { get set }
    func start()
}

protocol UIViewControllerFactory {
    func getViewController(delegateType:CoordinatoreTypes,delegateObject:Coordinator) -> UIViewController?
}

class MainCoordinator: Coordinator {
    var rootViewController: UIViewController
    let factory: UIViewControllerFactory

    init(rootViewController: UIViewController, factory: UIViewControllerFactory) {
        self.rootViewController = rootViewController
        self.factory = factory
    }

    func start() {
        guard let controller = factory.getViewController(delegateType: .MainCoordinator, delegateObject: self),let rootViewController = rootViewController as? UINavigationViewController else {
            return
        }
        rootViewController.push(mainVC, animated: true)
    }
}

extension MainCoordinator:DelegateCaller{
    func printHello() {
        print("helloo")
    }
}

enum CoordinatoreTypes{
    case MainCoordinator
    case none
}

class Factory:UIViewControllerFactory{
    func getViewController(delegateType:CoordinatoreTypes,delegateObject:Coordinator) -> UIViewController?{
        switch delegateType{
        case .MainCoordinator:
            let controller = MainViewController()
            controller.delegate = delegateObject as? MainCoordinator
            return controller
        case .none:
            break
        }
        return nil
    }
}

class MainViewController:UIViewController{
    weak var delegate:DelegateCaller?
}

protocol DelegateCaller:AnyObject{
    func printHello()
}


text:
Q: Moving Eclipse Workspace from ~ to new directory? Okay, so I made a mistake of setting my home directory (~, a.k.a. /home/user) to be my workspace location on my RHEL6 box.
I want to change my workspace to ~/workspace. However, I can't seem to do this by copying files.
For some background, the project I am currently working on and have fully set up under the ~ workspace, has all source files stored elsewhere (~/depot/.../../../../src), so I don't even see a folder in ~ representing my project.

A: Do the following steps:

*

*close all the projects in workspace

*close Eclipse

*move the directory .metadata from ~ to ~/workspace

*open Eclipse and when prompted for the workspace selection set it to ~/workspace

A: After closing Eclipse projects and Eclipse itself, move all project folders and .metadata folder in the new workspace folder.

A: *

*Close Eclipse.

*Open the location of the workspace and cut paste the entire directory (which contains the ".metadata" directory into the intended location.

*Restart Eclipse with newly copied folder as the workspace (parent directory of ".metadata" folder).

A: On Windows 8 I did this:

*

*Closed All of the projects in Eclipse

*Closed Eclipse

*Physically moved the workspace folder to a new location (in my case I put it into c:\projects as I
have this backed up).

*Started Eclipse

*File > Switch Workspace and selected the new path. Then eclipse restarted itself and all projects showed up.

A: I was testing to move files manually from workspace and suddenly my eclipse did not show them in my eclipse view so i moved them back to the same location where they have come from, entered eclipse and clicked right click on the package where i am expecting those files and clicked Refresh, Now i can view them on my Eclipse under packages, so try do refreshing it might work for u.


text:
Q: How to sort a column which contains Coldfusion server-side generated values other than database values in jQuery Datatables I am using  Datatables.net  for one of my page to display data.I am using server-side scripting to display datatables.
In my html I have 17 columns.Some columns for fetched values and other 3 contains some mathematics calculations with Coldusion functions that I am returning in the server side script.Those are not depending on database fields.
What my problem is I need to sort columns that have generated values.But this is not possible because datatables SQL ordering statement returns an error because these columns are not in the actual SQL table.
Doese anyone knows how can I sort these generated columns? Do we have any sorting that I can do for those columns without interfering SQL ordering clause(maybe sort in client side).


text:
Q: Как отправить данные с сайта на сервер node.js и получить результат обратно? На SPA сайте/клиенте при клике на разные элементы собирается массив данных selectedItems = [1,2,3].

*

*Мне нужно отправить итоговый массив в anotherFile.js, в котором бы произошла обработка данных.

*Из обработанных данных в anotherFile.js вышли бы новые данные newData = {}, которые
мне нужно отправить и показать клиенту/на сайте.

Подскажите, как это делается?
Пока мне понятно только то, что нужно создать сервер, данные отправлять туда и обратно в виде json, с запросами get и post. Понятны только примеры с api, но у меня не api.


text:
Q: Allow bluetooth devices to wake PC I have a bluetooth mouse and keyboard attached to my Windows 10 desktop. However neither of these devices are able to wake the computer from sleep and no guide online appears accurate.
Does anyone know if and how this can be configured?

A: Enable device Wake-on-Bluetooth

*

*Connect the Bluetooth device

*Run Device Manager

*Double-click Bluetooth

*Double-click the specific device (not the Bluetooth adapter!)

*Click the "Power Management" tab

*Click to check "Allow this device to wake the computer"

*Click OK

*Reboot.

If the device doesn't have a "Power Management" tab, perhaps the
following can still help.
Disable hibernate
In general, the Bluetooth device will be disconnected when the system
enters sleep or hibernate mode, so cannot wake up the computer.
However, if Modern Standby is supported, the Bluetooth devices are
still connected
after the system enters sleep mode. But if it enters hibernate mode,
the connection will be disabled.
Here is how to enable Modern Standby:

*

*In the Start menu, run "Choose a power plan"

*Click "Change plan settings" for your power plan

*Click "Change advanced power settings"

*Expand "Hibernate after", located under "Sleep"

*Set "On battery" and "Plugged in" as "Never"

*Click OK

*Reboot.

If this doesn't work still, the chances are slim, but continue on.
Last-ditch effort

*

*Run Command Prompt (cmd) as Administrator

*Enter the command: powercfg /devicequery wake_programmable

*If you see the Bluetooth device in the list, run
  powercfg /deviceenableawake "Bluetooth Device exact name"

Note: The above command is worded according to the documentation
with deviceenableawake.
However, the help shown by powercfg /? says rather that the
verb is deviceenablewake:
 powercfg /deviceenablewake "Bluetooth Device exact name"

*Run the command:
  powercfg -devicequery wake_armed

If your device is now in the list, this should now work. Reboot.
If nothing works, then the computer hardware probably does not
support Wake-on-Bluetooth.

A: It looks like most Wifi+bluetooth addon PCIe adapters simply do not support hardware-based BT key storing, which is required when the OS with its BT driver is sleeping. There maybe some adapters or USB dongles with such feature, but you rather find this feature on high class laptops.


text:
Q: Sticky div in CSS I would like a div to be pushed down (see "Search while I move the map" in the screenshot), to float above the map, but so that if I use any constants for margin-top or top, then that's relative to the parent div (map), not the browser window.
How can I do so? Website link I have tried to add position: relative; to the parent #map but this is what I get (the map gets hidden):

This is my CSS code:
#map {
    #searchCheckboxContainer {
        position: absolute;
        display: inline-table;
        white-space: nowrap;
        margin-top: 24px;  // sure, this works, but it's 24px *from the browser window*
        top: 0px;          // any way to make it relative to the parent div (map)?
        left: 50%;
        transform: translateX(-50%);
        background: rgb(255, 255, 255) !important;
    }

    #searchCheckboxContainer {
        height: 40px;
    }
}

HTML:

            <input id="checkbox" class="form-check-input" type="checkbox" value="" id="defaultCheck1">

              Search as I move the map

A: Adding as an answer to avoid the comment noise:
All of the #map element children are positioned absolute. So, essentially they aren't in the normal document flow and will not affect the height of the #map div.
You need to add:
position: relative;
height: 100vh (or whatever)

To your #map div.
Then, to your #searchCheckboxContainer, add a z-index: 100 //could be anything but that worked
This will put the box above the map.

A: I assume you need it to look like that:

In this case you need to modify the following:
#map {
    position: relative;
    height: calc(100vh - 86px); // The height of header on mobile and you need to add responsive media queries to handle it.
}

#map #searchCheckboxContainer{
    position: absolute;
    display: inline-table;
    white-space: nowrap;
    margin-top: 0;
    bottom: 0;
    left: 0;
    top: auto;
    transform: none;
    background: #ffffff !important;
    z-index: 2;
    width: 100%;
    padding: 15px;
}

#searchCheckbox .form-check-input{
    position: relative;
    margin-top: 0;
    margin-left: 0;
}

#map #mapid{
    height: 100%;
    width: 100%;
    position: absolute;
    background-color: yellow;
    z-index: 1;
}


text:
Q: How to include a mapping as a base to a new mapping? Is it possibly to use a mapping from a referenced assembly as a base for a new mapping?
The reasoning behind this is there are general objects many applications use, thus they reference the CentralDataLayer.dll. The issue is some applications have additional tables that are relational to tables from the CentralDataLayer. So I want to be able to extend these mapping from these applications.
The referenced base mapping looks as it normally would:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="CentralDataLayer" namespace="NHibernate.Map">
    <class name="NHibernate.Map.Employee, CentralDataLayer" table="`wt_employee`" schema="`wt_global`">

        <id name="Id" column="`emp_id`" type="Int32" unsaved-value="0">
            <generator class="native" />
        </id>

        <property name="Number" column="`emp_number`" type="Int32" not-null="true" />
        <property name="Email" column="`email`" type="String" length="100" />
        <property name="IsFullTime" column="`is_full_time`" type="Boolean" not-null="true" />
        <property name="HireDate" column="`hire_date`" type="Date" />

        <property name="SsnSerialNumber" column="`last4ssn`" type="String" lazy="true" />

        <property name="OfficePhone" column="`work_phone`" type="String" length="10" />
        <property name="OfficeExtension" column="`work_phone_extn`" type="String" length="5" />

        <component name="UpdateRecord" class="NHibernate.Map.Component.UpdateRecord, CentralDataLayer">
            <property name="Date" column="`updated_dt`" type="Date" />
            <property name="By" column="`updated_by`" type="String" length="60" />
        </component>

        <many-to-one name="User" column="`user_id`" class="NHibernate.Map.User, CentralDataLayer" unique="true" />
        <many-to-one name="Job" column="`job_id`" class="NHibernate.Map.Job, CentralDataLayer" />

    </class>
</hibernate-mapping>

The next a mapping file is the one I'm unsure about:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DataLayer" namespace="NHibernate.Map.WIP" auto-import="false">
    <class name="NHibernate.Map.WIP.Employee, DataLayer" table="`wt_employee`" schema="`wt_wip`">

        <!-- Logically I would do something like this. -->
        <include class="NHibernate.Map.Employee" table="`wt_employee`" schema="`wt_global`" />

        <property name="Active" column="`emp_active`" type="Boolean" not-null="true" />
        <property name="DashboardColumnAmount" column="`emp_dashboard_col_amount`" type="Byte" not-null="true" />

    </class>
</hibernate-mapping>

And the resulting class for the NHibernate.Map.WIP.Employee mapping would be:
namespace NHibernate.Map.WIP
{
    public class Employee : Map.Employee
    {
        #region Fields

        private bool _active;
        private byte _dashboardColumnAmount;

        #endregion Fields

        #region Properties

        public virtual bool Active
        {
            get { return _active; }
            set { _active = value; }
        }
        public virtual byte DashboardColumnAmount
        {
            get { return _dashboardColumnAmount; }
            set { _dashboardColumnAmount = value; }
        }

        #endregion Properties
    }
}

Now the developer should be able to use NHibernate.Map.WIP.Employee in there project with the connected NHibernate.Map.Employee Data.

A: AFAIK you can't. you could load the mapping xml and alter it befor feeding it to the session factory or you could port it to FluentNHibernate and then you can add subclasses as long as you want.


text:
Q: Refuse space only input with ng-required Is there a simple way to make inputs and textareas with the ng-required attribute set to true invalid if it contains only spaces or blank characters ?
I'm looking for a generic way that would be applied to all my fields.
Note : I'm using angular 1.5.5

A: There is a way that you can set "ng-required=checkVar" and all input field you want to be validate in the same way can be put same class (class tag), e.x: class="check". Then you can bind an event handle function to all these fields as:
$('.check').on('click', function(e){
    do your work (validating)
    if (validated)
          $scope.checkVar = true;
    else
          $scope.checkVar = false;
}

This is my idea.

A: Ok, so in the end I didn't manage to find a generic way.
I had to change every template, but it can be done quickly using the replace option of any IDE.
I replaced every <textarea occurences with <textarea ng-pattern="/^(?=.*\S).+$/"
So, ng-pattern was my solution choice, there's probably a better way though.


text:
Q: Проверка переменной на валидность UTF-8 function getPassword() {// Возвращает валидный пароль
    global $length; // Длинная пароля
    $glength = $length;
    $password = getRandomPassword(); // Пароль
        do {
           $password = getRandomPassword();
            $test_lentgh = iconv_strlen($password, 'UTF-8') != $glength; //Проверка пароля на длинну
        } while($test_lentgh);
    return $password;

Функция берет пароль и возвращает только те, которые соответствуют заданной длинне.
Как можно в цикл запихать проверку на валидность?
Требования к паролю такие: Минимум 1 Спецсимвол, и минимум 2 цифры.
в пароле есть кирилица.

A: Вот реализация которая вас интересует:
function getPassword($length)
    while (true) {
        $password = getRandomPassword();
        if (iconv_strlen($password, 'UTF-8') != $length) continue;
        if (/* не удовлетворяет условию 2 */) continue;

        // если все условия выполнены, то возвращаем результат
        return password;
    }
}

Но в целом такой подход плохой, потому как результат можно никогда так и не получить. Лучше переделать функцию getRandomPassword() так, что бы она генерировала именно то, что вам нужно


text:
Q: Memory pressure warning, while take screen shot. UIGraphicsBeginImageContext(screenRect.size);

If I use this, no memory pressure occurs. but If I use below line memory pressure occurs.
UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, 4.0f);

I don't know why this hapening.. Any body tell me how to handle this?

A: I'm not sure what you mean by "memory pressure", I assume what you mean is a memory warning/crash. The reason for that is with the first example:
UIGraphicsBeginImageContext(screenRect.size);

You're creating a context of the current screen size where as when you use:
UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, 4.0f);

You're creating a context 4 times the size of the current screen size which requires more memory, and if the device doesn't have enough memory to allocate then bad things will happen.
You can watch the memory allocations by using Instruments. Product -> Profile (⌘I) and selecting 'Allocations' from the Templates:


text:
Q: How would I make a web image viewer with a static image? I am interested in making an application that does various things, but I am having trouble getting a static image, such as an avatar off of a web page.
Any ideas?

A: I have figured it out. Visit this site:
Here


text:
Q: Can't modify objectAtIndex NSMutableArray of SKSpriteNodes OK, so I'm having a problem directly modifying the contents of an NSMutableArray. Basically, I have an Array of SKSpriteNodes created in the initialisation function.  I want to be able to modify a SKSpriteNode at a specified index depending on where the user touches the screen. I can get the correct index, and I can get the node, but I can't seem to get the properties of the node to change.
I've included the full code in here for clarity, but the issue is in the last function (touchesBegan).
What I want to do is be able to set the properties of the SKSpriteNode at the specified index. The debug messages are saying that *leftTile is being created properly and contains the correct data, but the changes don't take effect on the screen when I call the setHidden function.
#import "FLGameScene.h"

@implementation FLGameScene

/**
 * Convert Multidimensional Coordinates to Single Index
 *
 * @param int row                   Row index.
 * @param int col                   Column index.
 *
 * @return int
 */
- (int)multiToSingle:(int)row :(int)col
{
    return ((row * numTiles) + col);
}

/**
 * Determine the Iso Coordinates closest to the Real Position.
 *
 * @param CGPoint coords            Real coordinates.
 *
 * @return CGPoint
 */
- (CGPoint)xyToIso:(CGPoint)coords
{
    // Determine the Row and Column
    int x = (coords.x - offsetX) / tileSize;
    int y = (coords.y - offsetY) / tileSize;

    // Create the CGPoint
    return CGPointMake(x, y);
}

/**
 * Determine the Real Coordinates for a specified index.
 *
 * @param CGPoint coords            Iso coordinates.
 *
 * @return CGPoint
 */
- (CGPoint)isoToXY:(CGPoint)coords
{
    // Determine the X and Y Values
    float x = (coords.x * tileSize) + offsetX;
    float y = (coords.y * tileSize) + offsetY;

    // Create the CG Point
    return CGPointMake(x, y);
}

/**
 * Initialisation Function.
 *
 * @param CGSize size               Size of the Scene Area.
 *
 * @return *SKScene
 */
- (id)initWithSize:(CGSize)size
{
    // Call the Parent Constructor
    if (self = [super initWithSize:size])
    {
        // Log a Message
        if (debugMode) NSLog(@"Game Scene Created. Size: %f x %f", size.width, size.height);

        // Set the Background Colour
        [self setBackgroundColor:[UIColor colorWithRed:0.15f green:0.25f blue:1.0f alpha:1.0f]];

        // Set the Tile Size
        tileSize = 50.0f;

        // Set the Number of Tiles
        numTiles = 14;

        // Determine the Offset
        offsetX = (size.width / 2.0f) - ((numTiles / 2) * tileSize);
        offsetY = (size.height / 2.0f) - ((numTiles / 2) * tileSize);

        // Create the Lilypad Texture
        SKTexture *lilypadTex = [SKTexture textureWithImageNamed:@"lilypad"];

        // Create the Frog Texture
        SKTexture *frogTex = [SKTexture textureWithImageNamed:@"frog"];

        // Create the Tile Array
        _tileArray = [[NSMutableArray alloc] initWithCapacity:(numTiles * numTiles)];

        // Loop through and Create the Grid
        for (int col = 0; col < numTiles; col++)
        {
            for (int row = 0; row < numTiles; row++)
            {
                // Create a Random BOOL Value for the Frogs
                int containsFrog = (rand() % 2);

                // Log a Message
                if (debugMode) NSLog(@"Square %i, %i :: %i", row, col, containsFrog);

                // Calculate the X Position
                float posX = (col * tileSize) + offsetX;

                // Calculate the Y Position
                float posY = (row * tileSize) + offsetY;

                // Create the Sprite Node
                SKSpriteNode *tile = [[SKSpriteNode alloc] initWithTexture:lilypadTex];

                // Set the Tile Origin
                [tile setAnchorPoint:CGPointZero];

                // Add the Sprite User Data Dictionary
                [tile setUserData:[NSMutableDictionary dictionary]];

                // Set the Flag for Containing a Frog
                [tile.userData setValue:[NSNumber numberWithInt:containsFrog] forKey:@"containsFrog"];

                // Set the Tile Position
                [tile setPosition:CGPointMake(posX, posY)];

                // Set the Tile Size
                [tile setSize:CGSizeMake(50.0f, 50.0f)];

                // Add the Tile to the Board
                [self addChild:tile];

                // Add the Tile to the Array
                [_tileArray addObject:[tile copy]];
            }
        }

        for (SKSpriteNode *tile in _tileArray)
        {
            if ([[tile.userData valueForKey:@"containsFrog"] boolValue] == YES)
            {
                // Create a Frog Node
                SKSpriteNode *frog = [[SKSpriteNode alloc] initWithTexture:frogTex];
                [frog setAnchorPoint:CGPointZero];
                [frog setSize:CGSizeMake(tileSize, tileSize)];
                [frog setPosition:tile.position];

                // Add the Frog Node
                [self addChild:frog];
            }
        }
    }

    // Return the Instance
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // Get the Touches
    UITouch *touch = [touches anyObject];

    // Get the Touch Location
    CGPoint touchLocation = [touch locationInNode:self];

    // Determine the Tile X and Y
    CGPoint tileIndex = [self xyToIso:touchLocation];

    // Log a Debug Message
    if (debugMode) NSLog(@"Tile at %f, %f Tapped", tileIndex.x, tileIndex.y);

    // Search Available Tiles

    // Tile to the Left
    int leftTileIndex = [self multiToSingle:(int)tileIndex.x - 2 :(int)tileIndex.y];

    // Get the Tile Object
    SKSpriteNode *leftTile = [_tileArray objectAtIndex:leftTileIndex];

    if (debugMode) NSLog(@"Description: %@", [leftTile.userData description]);

    // Check for Frogs
    if ([[leftTile.userData objectForKey:@"containsFrog"] boolValue] == NO)
    {
        NSLog(@"Tile empty");
        [leftTile setHidden: YES];
    }
}

@end

A:             // Add the Tile to the Board
            [self addChild:tile];

            // Add the Tile to the Array
            [_tileArray addObject:[tile copy]];

The sprite added to the scene graph is not the same as the one you add to the array because you create a copy of it. Don't copy and it'll work.
Even better: put all the tiles in an SKNode so you don't need the extra array, instead you can then refer to tiles via the children array.


text:
Q: Equivalent conditions for relative compactness in the Skorohod space Let $(E,d)$ be a complete separable metric space and $\mathcal X$ be a family of càdlàg functions $E\to[0,\infty)$. Consider the following claim:

*

*For all $t\in[0,\infty)\cap\mathbb Q$, there is a compact $K\subseteq E$ with $$x(t)\in K\;\;\;\text{for all }x\in\mathcal X\tag1.$$

*For all $m\in\mathbb N$, $$\left\{x(t):t\in[0,m]\text{ and }x\in\mathcal X\right\}\tag2$$ is relatively compact.

How can we show that 1. and 2. are equivalent?

Now, if $E=\mathbb R$, consider

*For all $m\in\mathbb N$, $$\sup_{x\in\mathcal X}\sup_{t\in[0,\:m]}|x(t)|<\infty\tag3.$$

How can we show that 1. and 3. are equivalent?

Actually, this should be easy, but I'm not sure, especially for 1. and 2., how to do it. Is separability really needed?

A: I don't know why you say this should be easy since one of the implications isn't even true.
First, $(2)$ and $(3)$ are clearly equivalent in the case $E = \mathbb{R}$, this is just Heine-Borel. It is also clear that $(2)$ implies $(1)$, even with some uniformity in how you choose $K$.
However $(1)$ implies $(2)$ is false, even in the case $E = \mathbb{R}$. For example, fix a bump function $\phi$ with height $1$ supported in $(-1,1)$. For each $n \geq 1$, define
$$\phi_n(\cdot) = n \phi \bigg((n+1)^2(\cdot - 1 + \frac1n)\bigg)$$
The important properties of this construction are that each $\phi_n$ is a bump function with height $n$ and for $n \neq m$, $\operatorname{supp} \phi_n \cap \operatorname{supp} \phi_m = \emptyset$. In particular, at a fixed time $t$, $\{\phi_n(t): n \geq 1\}$ contains just $2$ points and so condition $(1)$ is satisfied.
However, condition $(2)$ fails with $m = 1$, since $\{n : n \geq 1\} \subseteq \{\phi_n(t): t \in [0,1], n \geq 1\}$ and so the right hand set is not relatively compact by Heine-Borel.
Since $(2)$ and $(3)$ are equivalent in this case, this also shows that $(1)$ does not imply $(3)$ when $E = \mathbb{R}$.


text:
Q: Deleting data from SQLite3 iPhone SDK? Hey,
How can I delete data from SQLite3 iPhone SDK? I am able to insert data into the database by using this code:
-(void)insertRecordIntoTableNamed:(NSString *)tableName
                   withField1:(NSString *)field1
                  field1Value:(NSString*)field1Value
                    andField2:(NSString *)field2
                  field2Value:(NSString *)field2Value
{
    NSString *sql = [NSString stringWithFormat:@"INSERT OR REPLACE INTO '%@' ('%@' , '%@')     VALUES ('%@','%@')",tableName,field1,field2, field1Value,field2Value];
    char *err;
    if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
        sqlite3_close(db);
        NSAssert(0,@"error updating table.");
    }
}

I think I have to change something in NSString *sql but I can't figure out what do I have to change it to.
Thanks.

A: You need to use an SQL DELETE statement:
NSString *sql = [NSString stringWithFormat:@"DELETE FROM '%@' WHERE '%@' = '%@'", tableName, field1, field1Value];

The WHERE clause, of course, depends on what you want to delete from tableName.


text:
Q: Browser-sync not injecting CSS for remote site I need to do CSS styling of a remote site. I can't host the site locally for development, so I'd rather tweak the CSS locally and see the changes without having to wait for it to upload and then refresh the browser.
Seems like Browser-sync should be able to do this.
I set up a file bs.js:
var browserSync = require('browser-sync');

browserSync({
  proxy: {target:'http://mysite.ca/'},
  files: "css/*.css",
  serveStatic: ['css']
});

and run "node bs.js". It opens a browser window with URL http://localhost:3000/ displaying my remote site. So far so good, and if I make a change to my local custom.css (which is also on the remote site, with the same directory structure)  it displays "[Browsersync] File event [change]: css\custom.CSS"
However, nothing changes in the browser window. If I use chrome inspector, the contents of css\custom.CSS have not changed, though the file name has changed to custom.css?browsersync=1606353064487
Why won't it inject the changed CSS file?
Edit: Also, I can see that browser-sync has injected
    <script id="__bs_script__">//<![CDATA[
    document.write("<script async src='/browser-sync/browser-sync-client.js?v=2.26.13'><\/script>".replace("HOST", location.hostname));
//]]></script>

into the remote site so that is not the problem.

A: Figured it out. You need staticStatic set to the directory you are serving your local files from. Use rewrite rule if your local directory structure isn't the same as the remote site.  match parameter should be the path to the CSS file on the remote site.  The return parameter is the name of your local CSS file you will be serving. Seems like it is relative to the serveStatic path, so you don't put the full file path here.
var browserSync = require('browser-sync');

browserSync({

  proxy: 'https://mysite.dev/',

files: "./themes/bootstrap_sass/css/*.css",
serveStatic: ['./themes/bootstrap_sass/css'],
rewriteRules: [
  {
    match: new RegExp('sites/mysite.dev/themes/bootstrap_sass/css/style.css'),
    fn: function() {
      return 'style.css';
    }
  }
]

});


text:
Q: JOIN SQL is not working when join table is empty I am working on a project where multiple table data exists for a user but if empty one table from any of them then SQL return empty data even other tables data exist like below SQL
$id = 40;
SELECT *
  FROM players a
  JOIN pitcher b
    ON a.id = b.user_id
  JOIN outfield_position c
    ON a.id = c.user_id
  JOIN infield_position d
    ON a.id = d.user_id
  JOIN defensive_statistics e
    ON a.id = e.user_id
  JOIN career f
    ON a.id = f.user_id
 WHERE a.id = $id

like if $outfield_position table is empty then the SQL returns an empty array but sometimes maybe data here, what can I do if data available or not available every way can works?
Thanks

A: The default join used is inner join and as already explained here joins .
The output in this case will be intersection of the tables it is joined with,so if any table does not have any value then intersection will give empty result.
You can try with LEFT OUTER JOIN or FULL OUTER JOIN , in Left Outer Join if data is present in $players the value will be displayed.If unsure about the data Full Outer join will give all the results from all the tables.


text:
Q: Communicating between the tablayout Fragments I used a tab layout with fragment. The scenario goes like this.
Activity:
Fragment 1 , Fragment2 , Fragment3
From Fragment2 Updating the UI of Fragment1.
I tried to access the methods from fragment but resulting null pointer exception.

A: *

*You may use Observer Pattern to achieve this. To do this, You have to  create a MutableLiveData in your MainActivity and pass it to fragment through interface.

*Then post value from FragmentA and observe it from FragmentB and do operation when change

Create interface:
interface UpdateFragmentListener {
    fun onUpdate(): MutableLiveData<Any>
}

Implements this in Activity:
class MainActivity: AppCompatActivity, UpdateFragmentListener {
   val fragmentUpdate: MutableLiveData<Any> = MutableLiveData()

   ...

   override fun onUpdate(): MutableLiveData<Any> = fragmentUpdate
}

Inside FragmentA:
...
val updateListener: UpdateFragmentListener

override fun onAttach(context: Context) {
    updateListener = context as UpdateFragmentListener
}

override fun onViewCreated(v: View, savedInstanceState: Bundle) {
    super.onViewCreated(v, savedInstanceState

    //use like this by modifying it wherever you need inside FragmentA
    updateListener.onUpdate().postValue(Any())

}

Inside FragmentB:
...
val updateListener: UpdateFragmentListener

override fun onAttach(context: Context) {
    updateListener = context as UpdateFragmentListener
}

override fun onViewCreated(v: View, savedInstanceState: Bundle) {
    super.onViewCreated(v, savedInstanceState

    //Observe it and do operation wherever you need inside FragmentB
    updateListener.onUpdate().observe(this, Observer {
        // implement your logic here
    })

}


text:
Q: Why can not write some characters on pop up in a website by my mobile with android? When I am in a website on my mobile, my device does not allow put some letters in a pop up that showed at the begining, why happened on my mobile Virgin (kyocera)?.. Who can I help me about that question? in another devices work very well

A: Open your browser then press the Menu button -> More -> Check if "Text encoding" is "Unicode UTF-8". If not change it.


text:
Q: How to put page numbers in PDF using NVelocity I am using NVelocity to create PDF in C#.NET. My question is how to number the pages in the produced PDF document in code.
The number of pages is not predefined, and the numbering should appear on the bottom of the page in the format page 1 of 10.
Thanks!


text:
Q: Strange behavior of multiple call of Application.Run in Windows 10 environment I have application of two forms (just created by AddNewForm)
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
        Application.Run(new Form2());
    }

When Form1 is closed by red cross in top-right corner Form2 is shown as expected.
When Form1 is closed by context menu "Close" shown on form icon in taskbar, application terminates almost immediately. In case Form2 is not shown following happens - its Load eventhandlers are processed, but its FormClosed eventhandlers are not called.
I observe this behavior only on Windows 10 (unable to simulate on Windows 7) and in approx. 80% cases. Any reason WHY?

A: If I replace Application.Run(new FormXX()) by new FormXX().ShowDialog() application starts behaving as expected. So there will be some issue in Application.Run related to multiple call of this method in one thread.
My current solution is based on running Application.Run() only one time per thread. Following code never ends up closing Form2 immediately:
Thread thread1 = new Thread(() =>
{
    Application.Run(new Form1());
});
thread1.SetApartmentState(ApartmentState.STA);
thread1.Start();
thread1.Join();

Thread thread2 = new Thread(() =>
{
    Application.Run(new Form2());
});
thread2.SetApartmentState(ApartmentState.STA);
thread2.Start();
thread2.Join();


text:
Q: DOMPDF with css float I am not sure why but the html page displays just fine but the dompdf does not utilize the floats.
Code is 2300 + line long so to long to post here.... But it is all inline css.

I have tried both wrapping the css in a style tag and inline with no luck.
This is the html page
http://www.ems-complete.com/ccems/ccems_reports/daily_vehicle_check_sheet.php?id=5
This is the dompdf link
http://www.ems-complete.com/ccems/ccems_reports/form_daily_vehicle_check.php?id=5
I am not sure why but the html page displays just fine but the dompdf does not utilize the floats...
Code is 2300 + line long so to long to post here.... But it is all inline css...

A: use def("DOMPDF_ENABLE_CSS_FLOAT", true);  in dompdf_config.inc.php
it works for your css float

A: you need use https://github.com/barryvdh/laravel-dompdf
is the plugin dompdf for Laravel 5.
and change the config in:
vendor/barrryvdh/laravel-dompdf/config/dompdf.php
def("DOMPDF_ENABLE_CSS_FLOAT", true);

A: Float support is introduced in the 0.6.0 code base, but it is disabled by default since it is still in development. Make sure you have enabled it by setting DOMPDF_ENABLE_CSS_FLOAT to true.
Starting with version 0.7.0 float support is enabled by default.
That being said, since the feature is still in development you're not going to get the results you want. Floats that span more than one page don't currently work as expected because a page break occurs before the non-floated content is rendered.

A: Guys use display: inline-block; instead of float. I use the older version of dompdf in my project. I enable DOMPDF_ENABLE_CSS_FLOAT true in dompdf_config.custom.inc file. But the float result is overlapping and distorted.The inline-block is the new and better way than using float left every time. Visit the following w3school link to more info. CSS Layout - inline-block

A: use

 in my case
def("DOMPDF_ENABLE_CSS_FLOAT", true);

is Not Working


text:
Q: Counting the image of a map of varieties using the trace formula Suppose $f: X\to Y$ is a finite map of varieties over a finite field $\mathbb F_q$. Is there an etale constructible $\mathbb Q_\ell$ sheaf $\mathscr F$ on $Y$ which counts the number of rational points of the form $f(x)$ for $x$ itself rational (as an application of the trace formula)?
If $f$ is closed, we can just use the pushforward. On the other hand,even if $X,Y$ are both spectra of fields, say of $\mathbb F_{q^n},\mathbb F_q$,then I am not sure what we want.
Edit 1: It seems to me that it might be easier to count $\deg(f)$ times the number of points and that's okay too. For instance, the number of squares in $\mathbb P^1$ is $(q-1)/2 + 2$ but since the eigenvalues are algebraic integers, we can't get a factor of $q/2$ by cohomology calculations. But if we multiply by $2$, it's possible.
Edit 2: In the case of $()^{\ell^n}: \mathbb G_m \to \mathbb G_m$, let us suppose we have a sheaf of the form we want and let the Frobenius have eigenvalues $q\alpha_i$ on degree zero compactly supported cohomology.
We can work out the number $\ell^n$ th powers in $\mathbb F_{q^r}$ and it depends on what power of $\ell$ divides $q^r-1$. If we further assume that $q-1$ is exactly divisible by $\ell$, we get equations of the form $\sum_i \alpha_i^r = \max(\ell^{n-k},\ell)$ for $\ell^{k-1}||r$.
We can solve this using Fourier inversion and it seems the unique solutions give us $\ell^{n-2k}$ copies of $\alpha_i = \zeta_{\ell^k}$ as $\zeta_{\ell^k}$ ranges over all primitive $\ell^k$ roots of unity and $1\leq k \leq n-1$ and $\ell^{n-1}$ copies of $1$.
Unfortunately $\ell^{n-2k}$ is not integral which seems to show that no $\mathbb Q_\ell$ sheaf that is defined by localizing a $\mathbb Z_\ell$ sheaf can work. Is there some other formalism of $\mathbb Q_\ell$ sheaves that can give us something useful?
Alternatively, perhaps we need to assume that the base field is large enough (perhaps large enough to make the galois group of the generic fiber constant?)


text:
Q: Grouping attributes based on other field using ArcGIS Pro How do I group my attributes and show total area of districts or number of blocks for each contract?
I tried to use groupby clause in select by attribute tool but it did not work.
I work in ArcGIS Pro. Moreover, I would like to show it on the map with a proper symbology

A: Each attribute row in a feature layer represents a geometry(Point, Line, or Polygon). Herewith your concern the districts are associated with multiple contract agreement types. As @PolyGeo shared you can easily get the required outcome using summarize, but that could not be used when you want this for a display.
So, one possible workflow you can follow is to create a multipart feature layer out of the existing unique features(single part).
This can be achieved using the Dissolve Tool in ArcGIS Pro:
Multiple State Names representing Population:

Pairwise Dissolve Tool:

Resulting Layer

Note: This process will create a new layer, and you can use it for symbolizing features accordingly.


text:
Q: When analyzing the time complexity of an algorithm why do we drop the constant of the term with the largest degree Suppose I have the following : T(n) = 5n^2 +2n
The asymtotic tight bound of this is theta n^2. I want to understand the reason behind dropping the 5. I understand why we ignore the lower order terms.

A: Consult the definition of big-O.
Keeping things simple[*], let's define that a function g is O(f) if there exist constants C and M such that for n > M, 0 <= g(n) < Cf(n).
The presence of a positive constant multiplier in f doesn't affect this, just choose C appropriately. Your example T is O(n^2) by choosing a value of C greater than 5, and a value of M big enough that the +2n is irrelevant. For for example, for n > 2 it's a fact that 5n^2 + 2n < 6n^2 (because n^2 > 2n), so with C= 6 and M = 2 we see that T(n) is O(n^2).
So it's true that T(n) is O(n^2), and also true that it's O(5n^2), and O(5n^2 + 2n). The most interesting of those facts is that it's O(n^2), since it's the simplest expression and the other two are logically equivalent. If we want to compare the complexities of different functions, then we want to use simple expressions.
For big-Theta just note that we can play the same trick when f and g are the other way around. The relation "g is Theta(f)" is an equivalence relation, so what are we going to choose as the representative member of the equivalence class of T? The simplest one.
[*] Keeping things less simple, we cope with negative numbers by using a limsup rather than a plain limit. My definition above is actually sufficient but not necessary.

A: wEverything comes back to the concept of "Order of Magnitute". Given something like
5n^2 +2n
You think that the 5 is significant, however when you break it down and think about the numbers, the constant really doesn't matter (graph it and you will see why). For example .. say n is 50.
5 * 50^2 + 2 * 50 --> 5 * 2500 + 2 * 50 --> 12,600
As you mentioned, the 2*n is insignificant when compared to n^2. This same concept applies when viewing the constant as well... you might think that 2500 vs 125,000 is a big difference; however consider if the algorithm was n^3... you are now looking at 12,600 vs 625,100
So  the factor that will have the most significant difference on the cost of an algorithm is just n^2.

A: The constant is dropped because it does not affect which complexity class the function belongs to.
If you have two functions f(n) = c1 * n^2 and g(n) = c2 * n^3, where c1 and c2 are constants, it doesn't matter how large c1 is and how small c2 is, g(n) will ALWAYS overtake and outgrow f(n) at some value of n.


text:
Q: Restangular: Failed requests stops execution with await I have an error interceptor like below:
RestangularProvider.addErrorInterceptor((response) => {

    const error = EnumerableFromObject(response.error.Errors)
      .Select(i => i.Value.Message)
      .FirstOrDefault();
    toastr.error(error, "Error");

    return true;
  });
}

Below is the code of my auth service:
  async Login(login: string, password: string) {
    const sessions = this.rest.all("sessions");
    const params = {Login: login,Password: password };
    const response = await sessions.post(params).toPromise();
    return response;
  }

And this is how I am calling it in my component:
this.loader.show();
const response = await this.authorizationService.Login(login, password);
this.loader.hide();

So I have to hide loader after the service is completed, failed or not.
My issue is when a request fails with any reason - like wrong credentials - execution stops, & it never reaches to this.loader.hide();
How can I handle this without using then. In my project all methods are called with await. So I can't remove await & use then. It will require so much rework.
Can anyone tell me what I am missing here?

A: The problem is you do not have any error handling in place. If your request fails the await part will throw an exception - that means the function is exited --> your .hide() call is never reached
To handle this you can wrap it inside a try catch, e.g.
this.loader.show();
try {
    const response = await this.authorizationService.Login(login, password);
} catch (error) {
    // do something with the error here
}
this.loader.hide();


text:
Q: Completion block not executed in a Singleton to access UIManagedDocument I am using the singleton pattern to access the unique UIManagedDocument accross my app. Everything works fine except that a completion block inside the singleton is never executed.
ManagedDocumentHelper.m:
+ (UIManagedDocument *) sharedDatabaseUsingBlock:(completion_block_t) completionBlock
{
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"database"];

    static UIManagedDocument *managedDocument;
    static dispatch_once_t mngddoc;

    // synchronous
    dispatch_once(&mngddoc, ^{
        managedDocument = [[UIManagedDocument alloc] initWithFileURL:url];

        if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]){

            NSLog(@"Creating...");
            [managedDocument saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
                NSLog(@"Created!");
                completionBlock(managedDocument);
            }];

        } else if(managedDocument.documentState == UIDocumentStateClosed){

            NSLog(@"Openning..."); //EXECUTED!
            [managedDocument openWithCompletionHandler:^(BOOL success){
                if(success){
                    NSLog(@"Open!"); //EXECUTED!
                    completionBlock(managedDocument); //NOT NIL
                }
            }];

        } else if(managedDocument.documentState == UIDocumentStateNormal){
            completionBlock(managedDocument);
        }
    });

    return (UIManagedDocument *) managedDocument;
}

With typedef void (^completion_block_t)(UIManagedDocument *document);
Inside my controller:
@interface MyViewContoller()
{
    UIManagedDocument *_database;
}

@end

@implementation MyViewContoller

- (void) initializeDataBase
{
    if(!_database){
        _database = [ManagedDocumentHelper sharedDatabaseUsingBlock:^(UIManagedDocument *document){
            NSLog(@"DATABASE LOADED!! %@", document); // NEVER EXECUTED :(
        }];
    }
}

Thank you very much!

A: Are you sure completionBlock(managedDocument) gets called in all the cases? Did you try with breakpoints?
MySingleton.h
typedef void (^completion_block_t)(UIManagedDocument *document);

@interface MySingleton : NSObject

+ (instancetype)sharedInstanceWithCompletion:(completion_block_t)block;

@end

MySingleton.m
#import "MySingleton.h"

@implementation MySingleton

+ (instancetype)sharedInstanceWithCompletion:(completion_block_t)block
{
    static dispatch_once_t token;
    static MySingleton *instance;
    dispatch_once(&token, ^{
        instance = [[MySingleton alloc] init];
    });
    block(nil);
    return instance;
}

@end

and wherever you want:
[MySingleton sharedInstanceWithCompletion:^(UIManagedDocument *document) {
    NSLog(@"Done");
}];

works for me.

A: The problem was that in a previous controller I was accessing the UIManagedDocument as well with the singleton and this created some kind of conflict with this access. Maybe the previous block was still in memory and this newer one was never called.


text:
Q: Write specific property of nested object to CSV I'm writing a CSV file based on an object which has another object nested in it.  I only want to write a specific property of that nested object, not all properties.
In the below example, my desired outcome would be to only write the network name of the user object to the CSV file, not the network name and operator ID.  However, as written, it will output both.  I could write a custom Definition map just for this scenario, but I'm wondering if I can indicate a specific property to use.
public sealed class InventoryDefinitionMap : CsvClassMap<InventoryItem>
{
    public InventoryDefinitionMap()
    {
        Map(m => m.inventoryId).Name("Inventory Id");
        Map(m => m.serialNumber).Name("Serial Number");
        References<UserDefinitionMap>(m => m.AssignedUser);
    }
}

public sealed class UserDefinitionMap : CsvClassMap<User>
{
    public UserDefinitionMap()
    {
        Map(m => m.operatorId).Name("ID");
        Map(m => m.networkName).Name("Network Name");
    }
}

void WriteCSVFile(List<InventoryItem> Items)
    {
        using (TextWriter writer = File.CreateText(fileLoc))
        using(var Csv = new CsvWriter(writer))
        {
            Csv.Configuration.RegisterClassMap<InventoryItemDefinitionMap>();
            Csv.WriteHeader<InventoryItem>();

            foreach (Item I in Items)
            {
                Csv.WriteRecord(I);
            }
        }
    }


text:
Q: BST printing without mutating? So i basically want to printbst's .. here is a little more detail
Provide a function (printbst t) that prints a BST constructed from BST as provided by bst.rkt in the following format:
-Each node in the BST should be printed on a separate line;
-the left subtree should be printed after the root;
-The right subtree should be printed before the root;
-The key value should be indented by 2d spaces where d is its depth, or distance from the root. That is, the root should not be indented, the keys in its subtrees should be intended 2 spaces, the keys in their subtrees 4 spaces, and so on.
For example, the complete tree containing {1,2,3,4,5,6} would be printed like this:
  6
    5
4
    3
  2
    1

Observe that if you rotate the output clockwise and connect each node to its subtrees, you arrive at the conventional graphical representation of the tree. Do not use mutation.
Here is what i have so far:
#lang racket
;;Note: struct-out exports all functions associated with the structure
(provide (struct-out BST))

(define-struct BST (key left right) #:transparent)

(define (depth key bst)
  (cond
    [(or (empty? bst) (= key (BST-key bst))) 0]
    [else (+ 1 (depth key (BST-right bst)) (depth key (BST-left bst)))]))

(define (indent int)
  (cond
    [(= int 0) ""]
    [else "  " (indent (sub1 int))]))

(define (printbst t)
  (cond
    [(empty? t) (newline)]
    [(and (empty? (BST-right t)) (empty? (BST-left t)))
     (printf "~a~a" (indent (depth (BST-key t) t)) (BST-key t))]))

My printbst only prints a tree with one node thou .... i have an idea but it involves mutation, which i can't use :( ..... Any suggestions ? Should i change my approach to the problem all together?

A: Short answer: yes, you're going to want to restructure this more or less completely.
On the bright side, I like your indent function :)
The easiest way to write this problem involves making recursive calls on the subtrees. I hope I'm not giving away too much when I tell you that in order to print a subtree, there's one extra piece of information that you need.
...
Based on our discussion below, I'm going to first suggest that you develop the closely related recursive program that prints out the desired numbers with no indentation. So then the correct output would be:

6
5
4
3
2
1

Updating that program to the one that handles indentation is just a question of passing along a single extra piece of information.
P.S.: questions like this that produce output are almost impossible to write good test cases for, and consequently not great for homework. I hope for your sake that you have lots of other problems that don't involve output....


text:
Q: Calculated columns, columns names and localization I provision a list in SharePoint 2010 with two date fields: one for a start date and one for an end date. I would like to add a third column for the duration.
Naturally, I could add a calculated column which uses the DATEDIF function. The problem is that my date fields get their names from a resource file. It appears that calculated columns refer to other columns by their display name. Is there any way around that? I'd hate to have to add an event receiver just for this.

A: Just to share, I have found a workaround for this issue here: http://www.hezser.de/blog/archive/2008/10/12/programmatically-creating-a-spfieldcalculated.aspx
In short, you make the calculated column like this:

*

*Save the value of web.Locale

*Set web.Locale to English

*Create the calculated column using English formula

*Set web.Locale to the original value

That way, you can approach formulas as always being in English. Saves a LOT of headache


text:
Q: Android, Allow user to draw polyline on map Im trying hard to allow user to draw polyline on map when they touch on the map, i dnt know where i went wrong, I think the problem is with onMapTouch method because map displayed normally but when I touch map it says "Unfortunately application has stopped working", what you think, Here is logcat:
17319-17319/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.sarahn.myapplication, PID: 17319
    java.lang.IllegalArgumentException: no position in marker options
            at com.google.l.a.ce.a(Unknown Source)
            at com.google.maps.api.android.lib6.d.ft.a(Unknown Source)
            at com.google.android.gms.maps.internal.l.onTransact(SourceFile:167)
            at android.os.Binder.transact(Binder.java:380)
            at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.addMarker(Unknown Source)
            at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
            at com.example.sarahn.myapplication.MapsActivity.onMapClick(MapsActivity.java:91)
            at com.google.android.gms.maps.GoogleMap$8.onMapClick(Unknown Source)
            at com.google.android.gms.maps.internal.zzj$zza.onTransact(Unknown Source)
            at android.os.Binder.transact(Binder.java:380)
            at com.google.android.gms.maps.internal.ar.a(SourceFile:93)
            at com.google.maps.api.android.lib6.gmm6.c.ac.b(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.n.bt.d(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.n.ak.onSingleTapConfirmed(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.h.g.onSingleTapConfirmed(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.h.i.handleMessage(Unknown Source)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:211)
            at android.app.ActivityThread.main(ActivityThread.java:5317)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
public class MapsActivity   extends                                                                     FragmentActivit                                                                  implementsGoogleMap.OnMapClickListener{

private GoogleMap mMap;
ArrayList<LatLng> arrayList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();
    arrayList = new ArrayList<LatLng>();
    SupportMapFragment f =                                               (SupportMapFragmen)                                                                                getSupportFragmentManager().findFragmentById(R.id.map);
    mMap= f.getMap();
    mMap.setMyLocationEnabled(true);
    mMap.setOnMapClickListener(this);
    }

    @Override
    protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
    }

    public void onMapClick(LatLng latLng) {

    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    mMap.addMarker(markerOptions);
    PolylineOptions p = new PolylineOptions();
    p.color(Color.RED);
    p.width(5);
    arrayList.add(latLng);
    p.addAll(arrayList);
    mMap.addPolyline(new PolylineOptions());
    mMap.addMarker(new MarkerOptions());

    }

A: This may have to do with the fact that the position method of MarkerOptions returns the object to which you are setting the position.
Try:
MarkerOptions markerOptions = new MarkerOptions();
markerOptions = markerOptions.position(latLng);

EDIT:
I was wrong above. It is because of this line of code:
mMap.addMarker(new MarkerOptions());

You are adding a new marker on the map with no position. You need to set the position of the marker before attempting to add to the map. I am unsure of why you are adding a second marker to the map since you already have added the one at the user's touch location. You are also trying to add a polyline to the map with no attributes.
Try this and see what happens:
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
mMap.addMarker(markerOptions);
PolylineOptions p = new PolylineOptions();
p.color(Color.RED);
p.width(5);
arrayList.add(latLng);
p.addAll(arrayList);
mMap.addPolyline(p);


text:
Q: Calculating the number of elements in an array using pointer arithmetic I have come across a piece of example code that uses pointers and a simple subtraction to calculate the number of items in an array using C++.
I have run the code and it works but when I do the math on paper I get a different answer.
There explanation does not really show why this works and I was hoping someone could explain this too me.

#include <iostream>
using namespace std;
int main() {
int array[10] = {0, 9, 1, 8, 2, 7, 3, 6, 4, 5};
int stretch = *(&array + 1) - array;
cout << "Array is consists of: " << stretch << " numbers" << endl;
cout << "Hence, Length of Array is: " << stretch;
return 0;
}

From: https://www.educba.com/c-plus-plus-length-of-array/
When I run the code I get the number 10.
When I print the results of *(&array + 1) and array by
cout << *(&array+1) << endl; cout << array << endl;

I get of course two hex address's.
When I subtract these hex numbers I get 1C or 28???
Is it possible that C++ does not actually give the hex results or their translation to decimal but rather sees these numbers as addresses and therefore only returns the number of address slots remaining?
That is the closest I can come to an explanation if some one with more knowledge than I could explain this I would be very grateful.

A: Let's take one step back and take it step-by-step to see if it will help. Continuing from my comment, the problem you are having difficulty with is one of type.
Let's take the array iteself:
int array[10] = {0, 9, 1, 8, 2, 7, 3, 6, 4, 5};

On access, an array is converted to a pointer to the first element in the array (e.g. the address of the first element) subject to caveats not relevant here. So when you say array, you have type int *, a pointer to the first element in array.
Now what happens when I take the address of the array? (&array in)
int stretch = *(&array + 1) - array;

When you take the address of the array, the result is the same address as array, but has type int (*)[10] (a pointer-to-array-of int[10]). When you add 1 to that pointer (recall type controls pointer arithmetic), you get the address for the pointer to the next array of int[10] in memory after array -- which will be 10 int after the first element of array.
So *(&array + 1) gives you the address to the next array of int[10] after array, and then dereference is only needed for type compatibility. When you dereference an int (*)[10] you are left with int[10] -- which on access gives you the address of the first element of that array (one after the original)
Think through the types and let me know if you have further questions.

A: You forgot a small detail of how pointer addition or subtraction works. Let's start with a simple example.
int *p;

This is pointing to some integer. If, with your C++ compiler, ints are four bytes long:
++p;

This does not increment the actual pointer value by 1, but by 4. The pointer is now pointing to the next int. If you look at the actual pointer value, in hexadecimal, it will increase by 4, not 1.
Pointer subtraction works the same way:
int *a;
int *b;

// ...
size_t c=b-a;

If the difference in the hexadecimal values of a and b is 12, the result of this subtraction will not be 12, but 3.

When I subtract these hex numbers I get 1C or 28 ???

There must've been a mistake with your subtraction. Your result should be 0x28, or 40 (most likely you asked your debugger or compiler to do the subtraction, you got the result in hexadecimal and assumed that it was decimal instead). That would be the ten ints you were looking for.

A: I will try it with 5 items
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
   int array[] {1,2,3,4,5};
   int items= sizeof(array)/sizeof(array[0]);
   cout << items << endl;
   int items2 = *(&array +1) - array;
   cout << items2 << endl;
   cout << array << endl;
   cout << *(&array +1) << endl;
   return 0;
}

root@localhost:~/Source/c++# g++ arraySize.cpp
root@localhost:~/Source/c++# ./a.out
5
5
0x7fe2ec2800
0x7fe2ec2814
using https://www.gigacalculator.com/calculators/hexadecimal-calculator.php to subtract the numbers from each other
I get
14 hex
20 decimal.
that fits with the 4 bytes to an integer.
thanx guys :)
this is an edit done on the 12th of december melbourne time ::
I have still had questions on this topic and something did not fit right with me about the entire route to counting array items via this code.
I found something I think is interesting and again would love to know why ( I shall try to explain it as best I can my self anyway)
*(&array + 1)   is the question.
lets have a look at it.
as arrays are at there very nature in c and c++ only pointers to the first element in the array how can this work.
I shall use a small set of cout calls to see if I can find out whats happening.
#include <iostream>

using namespace std;

int main(int argc, char* argv[]){
        int array[] {1,2,3,4,5,6,7,8,9,10};
    int size {0};
    size = *(&array + 1) - array;
    cout << "size = *(&array + 1) - array = " << size << endl;
        cout << "*(&array + 1) = " << *(&array + 1) << endl;
    cout << "(&array + 1) = " << (&array + 1) << endl;
    cout << "(array + 1) = " << (array + 1) << endl;
    cout << "&array = " << &array << endl;
    cout << "array = " << array << endl;
    cout << "*(&array) = " << *(&array) << endl;
    cout << "*(array) = " << *(array) << endl;
    cout << "*array = " << *array << endl;
    return 0;
}

again this is off proot in my phone so still under root with no systemd.
root@localhost:~/Source/c++# g++ arrayPointerSize.cpp
root@localhost:~/Source/c++# ./a.out
size = *(&array + 1) - array = 10
*(&array + 1) = 0x7ff6a51798
(&array + 1) = 0x7ff6a51798
(array + 1) = 0x7ff6a51774
&array = 0x7ff6a51770
array = 0x7ff6a51770
*(&array) = 0x7ff6a51770
*(array) = 1
*array = 1

we see that as a pointer array can be called with * too derefernce the pointer and give the variable held in position [0] in the array.
when calling &array or reference too array we get the return of the address at the first position in the array or [0].
when calling just array we also get the address for the first position in the array or [0].
when calling *array the * is working as it does for pointers and it is dereferencing the arrays first position [0] to give the variable.
now things get a little interesting.
*(array) also dereferences the array as is seen by its value being given as 1 in this instance.
yet *(&array) does not dereference the array and returns the address to the first position in the array.
in this instance memory address 0x7ff6a51770 is the first spot in the array  array = 0x7ff6a51770
and &array (reference to the pointer of the position in memory that is the first spot in the array) gives the same address 0x7ff6a51770.
it is also of note in this instance to remind us of the fact that *(&array) is also returning the first possition in the array and *(array) is not
so we can not dereference a pointer too a position in memory as its variable is the position in memory.
if array and &array give the same answer as array is a pointer too the memory position in the first spot in our array and a reference to
this pointer.
why the different answer for (array + 1) and (&array + 1).
we get the memory address 0x7ff6a51774 for (array + 1) which is in line with an integer taking four bytes on my linux or
the addition of four bytes in memory past the first spot in the array (second array spot) but (&array + 1) gives a different answer.
if we follow the bytes and the code we see that (&array + 1) actually gives us the memory address four bytes after the end of the array.
so pointer too memory address  add one gives the amount of bytes the variable type is past the memory address for the start of the array
and the reference to the pointer too the memory address add one gives the address the amount of bytes the variable type is after the last ?? spot in the array.
how then can array and &array return the same answer if (array + 1) and (&array + 1) do not.
it seems to me that the & reference when working with arrays overloads the + operator when doing arithmatic.
this would explain the difference in answers as straight &array has no operator too overload so returns the same answer as calling for
straight    array
this small peice of code also shows that the use of pointers using *(&array + 1) is a very bad way to show a way to find array size with
pointers as really arrays are pointers and *(&array + 1) and (&array + 1) give the same result.
the heavy work was really being done by the reference operator &.
I may still be missing something here as I have used cout directly with the different experssions and being a stream it may
be limited in its ability to take advantage of what the reference operator is really doing when working with arrays.
I am still learning this language but I shall for sure keep this in mind as I dive deaper into c++.
I believe other than a few other trials with variables that the true answer will be found when reading the source for GCC g++.
I am not ready for that yet.


text:
Q: How to loop over table rows with jQuery in PhantomJS I'm trying to learn some web scraping with node.js. I chose some sample page for example http://www.imdb.com/chart/top. Then I tried to scrape all titles with rating. I created a PhantomJS script (I need to use it because it's dynamic so it uses JavaScript on the site). It's working, but I don't know how to make a loop for each title.
For example:
$('.lister-list tr').each(
  function(){
    $(this).find('.titleColumn').text().replace(/\n/g, '');
    $(this).find('.imdbRating').text().replace(/\n/g, '');
  }
);

Then I put it all in a JSON file. At this moment I can only put data without loop. This is my script:
var phantom = require('phantom');
var fs = require('fs');

phantom.create(function (ph) {
  ph.createPage(function (page) {
    page.open("http://www.imdb.com/chart/top", function (status) {
      page.evaluate(function () {

        //search datajquer
        var k_title = $('.lister-list tr .titleColumn').first().text().replace(/\n/g, '');
        var k_rating = $('.lister-list tr .imdbRating').first().text().replace(/\n/g, '');

        // create json data
        var metadata = JSON.stringify({
          Title: k_title,
          Rating: k_rating
        });

        return metadata;

      }

        , function (result) {
        //save json data
        fs.appendFile('java.json', "\n" + result, function (err) {
          if (err) throw err;
          console.log('file is updated!');
        });
        //display data in console
        console.log('Result: ' + result);
        ph.exit();
        });
    });
  });
});

How I can make a loop which will loop over all TR elements?

A: What you need is an array. You could initialize an empty array and push new objects onto it like this:
page.evaluate(function () {
    var metadataList = [];
    $('.lister-list tr').each(function(){
        var metadata = {
            Title: $(this).find('.titleColumn').text().replace(/\n/g, ''),
            Rating: $(this).find('.imdbRating').text().replace(/\n/g, '')
        };
        metadataList.push(metadata);
    });

    return JSON.stringify(metadataList);
}, function(result){ ... });

You could also use the jQuery map() function to map each row to an object and create an array that way:
page.evaluate(function () {
    var metadataList = $('.lister-list tr').map(function(){
        return {
            Title: $(this).find('.titleColumn').text().replace(/\n/g, ''),
            Rating: $(this).find('.imdbRating').text().replace(/\n/g, '')
        };
    }).get();

    return JSON.stringify(metadataList);
}, function(result){ ... });

Notice that get(), must be called on the map() result to retrieve the actual array and not the jQuery object.
You don't need jQuery to do this:
page.evaluate(function () {
    var metadataList = [];
    [].forEach.call(document.querySelectorAll('.lister-list tr'), function(tr){
        var metadata = {
            Title: tr.querySelector('.titleColumn').textContent.replace(/\n/g, ''),
            Rating: tr.querySelector('.imdbRating').textContent.replace(/\n/g, '')
        };
        metadataList.push(metadata);
    });

    return JSON.stringify(metadataList);
}, function(result){ ... });


text:
Q: OpenID Connect: How to maintain a single sign-on experience between multiple web clients of the same umbrella application? I'm considering how to take a fairly complex tiered application with multiple web apps that delegate back to the same application server, and migrate it to use OIDC authentication with auth code flow. I am anticipating using identity server 4.
My question is: what would be accepted best practice in terms of maintaining a single-sign-on experience between these different web client applications (i.e. user signs into one, she's signed into them all until she signs out).
https://auth0.com/docs/api-auth/why-use-access-tokens-to-secure-apis suggests:

Note that the audience (aud claim) of the [id token] is set to the client's identifier, which means that only this specific client should consume this token.

This suggests that I should consider my backend application server to be my single 'client', and have my web apps share that same client ID. I can imagine doing this by storing the id token browser-side in a secure cookie.
https://connect2id.com/learn/openid-connect seems to validate this idea:

Put into a browser cookie the ID token can be used to implement lightweight stateless sessions.

But I wonder if it's security best practice to keep an id_token in a cookie.
I wonder if there are any other approaches - like:

*

*Considering each web application a separate 'client'

*When the user logs on to a second web application, have them direct back to the OIDC provider, which would automatically create a client token for the new client based on some notion that they are still basically 'logged-on' to the OP.

It seems like this must be a solved problem. What is accepted best practice here?


text:
Q: Script1014: Invalid Character replacing fetch with jQuery.ajax for IE 11 I'm adding i18n support to an old javascript component. It didn't need xhr/fetch before, but it does still need to work in IE11.
I wan't to write:
    fetch("/libs/cq/i8n/dict." + lang + ".json")
        .then(function(response) { return response.json(); })
        .then(function(data) {
            dictionary = data;
        });

But I know IE doesn't support fetch. We've got jQuery available, so I tried:
    jQuery.ajax({
        url: "/libs/cq/i18n/dict." + lang + ".json",
        success: function (response) {
            dictionary = JSON.parse(response);
            onReady();
        }
    })

Now I'm getting this:

SCRIPT1014: Invalid Character
index.js (49,17)

I realize the 49,17 is referring to a position in the file, line 49, char 17.  That's the d in dictionary = JSON.parse(response);
I've tested the response, it's strict valid JSON.
For some reason dictionary = eval(response) is working.

A: The problem was that jQuery was already detecting that it was JSON and parsed it for me.
The Invalid Character error message was telling me that the string I passed to JSON.parse was an object.
All I needed on line 49 was:
            dictionary = response;


text:
Q: How to make starting a UiApp by a group of users easy? After opening Gmail or Google Drive you see the google bar (containing the Google logo, a searchbox and clickable button for apps, notification of unread messages, sharing and about) on top of the window.
I want to put a put a button for starting my UiApp (build with GAS) there as well.
Is this possible (and how) ?
Several users will have read access to the google drive. I want those users to be able to start my UiApp from a button in google bar as well. What should I do (and what should they do) to make that possible?
If this is not possible, where can I put my UiApp best so users can start it easy?
My application is NOT intended to be accessible by other people except the ones I provided access to my Google Drive.

A: I believe you can accomplish this by leveraging the Gadgets section of the Gmail API to accomplish this as detailed here. I've seen this type of Gadget added by a Chrome Extension before but not directly from Google Apps Script.

A: I think you would need to use the "New" button, and publish a script to the Chrome Web Store.  Then your app would be in the drop down list of the "New" button.  The problem with that, is that the general public could see the app.  I'm assuming you don't want that.
If you want an easily accessible central location for users, you could create a website with Google App Engine.  You can get a free domain name of
www.mySiteName.appspot.com
It would be easier for users to get there than the URL of your Apps Script.


text:
Q: Picture download from url via lotus script I want to download one picture from url to my Lotus Notes application.
I can get text field from url, but image is difficult.
I try to put pic to a rich text field, but it doesn't work.
Any idea?

A: You can download an image from URL via LotusScript with the help of a little Script Library of type "Java".
Create a Script Library "GetImageFromUrl" of Type "Java" and put in following code:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class GetImageFromUrl {

    public static boolean getImageFromUrl(String imageUrl, String filePath) {
        try {
            URL url = new URL(imageUrl);
            InputStream is = url.openStream();
            OutputStream os = new FileOutputStream(filePath);
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) != -1) {
                os.write(b, 0, length);
            }
            is.close();
            os.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

Then you can use the method getImageFromUrl(imageUrl, filePath) in your LotusScript code to download the image to a file. From there you can attach the image file to a RichText item with rtitem.EmbedObject(EMBED_ATTACHMENT, "", "c:/temp/image.jpg").
Option Declare

UseLSX "*javacon"

Use "GetImageFromUrl"

Sub Initialize
    dim jSession As New JavaSession
    dim jClass As JavaClass
    Set jClass = jSession.GetClass( "GetImageFromUrl" )
    If jClass.getImageFromUrl("https://your.url", "c:/temp/image.jpg") Then
        MessageBox "File is downloaded"
    End If
End Sub


text:
Q: InfoPath and UserProfileService I am having a strange problem with UserProfileService that I can't seem to resolve.  When I add http://<mySite>/_vti_bin/UserProfileService.asmx as a data source, none of the methods are listed, and when I click Finish I get the error The file is not a valid XML file.  The form contains XML that cannot be parsed:  End tag 'ul' does not match the start tag 'p'.  From looking at the source that comes up when I open this page in a browser, it seems that the problem may be that there are a large number of <p> tags without closing </p> tags.  I also tried appending ?wsdl to the URL, but then I get the message The selected XML document cannot be used as a data connection because it includes inline XDR schemas.  Has anyone else had this problem?
EDIT:  Just for clarification, these errors both come up when I try to create the data source, preventing me from actually creating it.

A: I would be incredibly surprised if the SharePoint user profile service was returning malformed XML -- unless it was modified or you don't have permission to access it and it's trying to serve you some other data...
Make sure the URL you're entering in InfoPath is:
    /_vti_bin/UserProfileService.asmx?WSDL
Also try logging on to the SharePoint site you're attempting to get UserProfileService data from right before you try accessing the service in InfoPath. Oh! And make sure you're using https:// if your site is also running on https..
Additionally, you might find it easier to simply use the 'User Information List' from the site you're working with, just set the q:User_name field to the userName() function when you load the form then query the data from the list... just as simple and won't need to change when they stop providing asmx and other services in _vti_bin :-)

A: Here's a link to a blog post about using the UserGroup web service, it might help you with the UserProfile service:
http://blog.ianchivers.com/2011/01/using-sharepoint-usergroup-web-service.html

A: This is an old post, but I don't see a resolution provided, so I'll share a solution that fix this issue for us.  We were getting the same error as the above user,
but were instructed by MS to Disable the loopback check on the server and this issue went away.
Hope this helps someone else.