text:
Q: Wordpress permalinks does not work on server I have uploaded WordPress website to a new server which is working fine. But Permalinks settings are not working. All other pages returning me 404 error.
and below in my .htaccess file

        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\.php$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.php [L]

A: please check the apache module rewrite.
in a root wordpress folder insert into index.php phpinfo();
and find this string mod_rewrite. If it`s not, tell it your hoster support

A: To fix this error one can also try this method:
Open phpmyadmin > wordpress database >  wp_options table
Here check first two fields and update option_value with correct WordPress location. After that reload the permalink, hopefully the error might gone

A: Go to "wp-admin", open settings->permalinks and update the permalink settings, it will update the .htaccess file on your server. Hard refresh your site, now all the links will be work perfectly.

A: there's a one tiny trick to update all links if you can access admin .
you just go to permalinks options from settings page and save permalinks to default and after saving it you may change again and update. This will work in most cases for me either its SSL based issue or urls mismatch. don't forget to view .htaccess file if you have old server and having multiple rewrites.


text:
Q: How to POST variables js to Django I have 3 variables in js. I need post to views.py
I use Python 2.7 and django 1.11 i try with ajax but i dont understand.

<head>
    <meta charset="UTF-8">
    <title>Prueba de actualización de forma</title>
    <script type="text/javascript">
        function addEvidence(form) {
            idAlumno = document.getElementById('idAlumno').value;
            competencia = document.getElementById('Competencia').value;
            var radios = document.getElementsByName('Calificacion');

            for (var i = 0, length = radios.length; i < length; i++) {
                if (radios[i].checked) {
                    calificacion = radios[i].value
                    break;
                }
            }
            alert(idAlumno + " " + competencia + " " + calificacion);

        }
    </script>
</head>

views.py

def Evidences(request, idAlumno,competencia,calificacion):

    return render(request, 'resultados_app/resultados.html')

i need post idAlumno, competencia and calificacion but i dont know

A: include jquery and this will work
$(document).on('submit', 'form', function(e) {
    $.ajax({
        type: 'POST',
        url: '/YOUR_URL/',
        data: {
            idAlumno: idAlumno,
            competencia: competencia,
            calificacion: calificacion,
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        },
        success:function() {
            console.log("success");
        },
        error: function(data) {
            console.log("error");
        }
    });
});

views.py

def Evidences(request):
    idAlumno = request.POST["idAlumno"]
    competencia = request.POST["competencia"]
    calificacion = request.POST["calificacion"]

A: i use
<script>
        $(document).ready(function () {
            $("#evidences").submit(function (event) {
                idAlumno = document.getElementById('idAlumno').value;
                competencia = document.getElementById('Competencia').value;
                var radios = document.getElementsByName('Calificacion');
                noSemana = document.getElementById('opciones').value;
                for (var i = 0, length = radios.length; i < length; i++) {
                    if (radios[i].checked) {
                        calificacion = radios[i].value
                        break;
                    }
                }
                $.ajax({
                    type: "POST",
                    url: 'evidences',
                    data: {
                        csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                        'idAlumno': idAlumno, // from form
                        'competencia': competencia,
                        'calificacion': calificacion,
                        'noSemana': noSemana
                    },
                    success: function () {
                        window.location='/'
                    }
                });
                return false; //<---- move it here
            });

        });
    </script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to install these js libraries I've got html site with little help of css.
I Never tried to use javascript, but I found one that called simplr-smoothscroll which requires jQuery Mouse Wheel Plugin.
When I downloaded both of them I got jquery.mousewheel.js and jquery.simplr.smoothscroll.js. When I searched google how to install them in my site, I found that I need to put them in the site directory and refer to them in the html like this:
<script src="js/jquery.mousewheel.js"></script>
<script src="js/jquery.simplr.smoothscroll.js"></script>

I did that and nothing happened. What should i do?
PS: there are some tips which i really don't understand in the github links of the project :)

A: You also need to include jQuery itself for those libraries to work.
You can download jQuery as well and put it there, on the top of the other two, or you can reference it from a CDN.
Most of the libraries require you to write some codes as well. You can read their documentation and see how you can use them.
simplr-smoothscroll for example, you need to add the code below to your page and put your configuration inside in order to get it to work.
<script>
    $(function () {
      $.srSmoothscroll({
        // defaults
        step: 55,
        speed: 400,
        ease: 'swing',
        target: $('body'),
        container: $(window)
      })
    })
</script>

A: First of all, you should put your jquery.mousewheel.js and jquery.simplr.smoothscroll.jsin js folder which is same hierarchical level with your index.html.
Second, did you add the JavaScript which is provided in your link?
$(function () {
  $.srSmoothscroll({
    // defaults
    step: 55,
    speed: 400,
    ease: 'swing',
    target: $('body'),
    container: $(window)
  })
})

you should add this between <script> ... </script>.

A: Include jquery js file first .here using cdn path you can download latest version and give accpording path
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript" charset="utf-8"></script>

Then include mousewheel js
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.0.6/jquery.mousewheel.min.js" type="text/javascript" charset="utf-8"></script>

Include mooth scroll js

Use Follwing code:
<script type="text/javascript" charset="utf-8">
$(function () {
  $.srSmoothscroll()
})
</script>

You can set option also ,refering to document :
https://github.com/simov/simplr-smoothscroll


text:
Q: Can't upgrade from 12.04LTS to 14.04LTS I am trying to upgrade to 14.04.1 LTS. It is showing:
You have to download a total of 137 k. This download will take about
4 seconds with your connection.

Installing the upgrade can take several hours. Once the download has
finished, the process cannot be canceled.

Continue [yN]  Details [d]d
Continue [yN]  Details [d]y

Fetched 0 B in 0s (0 B/s)

Could not download the upgrades

The upgrade has aborted. Please check your Internet connection or
installation media and try again. All files downloaded so far have
been kept.

Failed to fetch
http://archive.ubuntu.com/ubuntu/pool/main/g/gcc-defaults/libgcj-common_4.8.2-1ubuntu6_all.deb
403 Forbidden

Restoring original system state

Aborting...

A: First of all, I think it's better to disable all third-party repositories, if you have.
Next you have to update your system with:

sudo apt-get update && sudo apt-get upgrade && sudo apt-get
  dist-upgrade

Then you have to run Update Manager through terminal to upgrade to 14.04.
Open a terminal and write this:

update-manager -d

And you are ready to upgrade your distro to 14.04 ...!!!


text:
Q: How to save all pixels that were in the place of a rect in pygame? Is there a way to save all the pixels that were in the place of a rect before drawing it? So that when I draw that rect again in a different place I can replace the old one with the saved pixels instead of filling that area with colors mamually?

A: You can define a subsurface that is directly linked to the source surface with the method subsurface:

subsurface(Rect) -> Surface
Returns a new Surface that shares its pixels with its new parent. The new Surface is considered a child of the original. Modifications to either Surface pixels will effect each other.

Create a copy of the subsurface to store it permanently:
rect_area = pygame.Rect(x, y, width, height)
area_surf = screen.subsurface(rect_area).copy()

Use the Surface later to replace the rectangular area:
screen.blit(area_surf, region)


text:
Q: CodeIgniter 4 Models preloading I am new to PHP OOP and CodeIgniter and I need help. I am using CodeIgniter 4 and trying to preload model logas_model in BaseController.php:
<?php

namespace App\Controllers;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 *
 * @package CodeIgniter
 */

use App\Models\Admin\logas_model;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class BaseController extends Controller
{

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = ['form', 'session', 'html', 'number'];
    protected $logas;

    /**
     * Constructor.
     */
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        //--------------------------------------------------------------------
        // Preload any models, libraries, etc, here.
        //--------------------------------------------------------------------
        ///$this->session = \Config\Services::session();
        $this->logas = new logas_model();
    }

}

Model logas_model code:
<?php namespace App\Models\Admin;

use CodeIgniter\Model;
use Config\Services;

class logas_model extends Model
{
    protected $table = 'veiksmai_logs';
    protected $primaryKey = 'id';

    protected $returnType = 'array';
    protected $useSoftDeletes = true;

    protected $useTimestamps = TRUE;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';
    protected $deletedField = 'deleted_at';

    protected $allowedFields = ['uid', 'veiksmas'];

    public function get_all_veiksmai()
    {
        return $this->select("CONCAT(`user`.`vardas`, ' ', `user`.`pavarde`) AS `user_vardas_pavarde`, `veiksmai_logs`.`veiksmas`, `veiksmai_logs`.`created_at`, `veiksmai_logs`.`id`")
            ->join('user', 'user.id = veiksmai_logs.uid')
            ->orderBy("`veiksmai_logs`.`created_at`", 'DESC')
            ->findAll();
    }

    public function add_veiksmas($veiksmas)
    {
        $session = Services::session()->get();

        $data = [
            'uid' => $session['uid'],
            'veiksmas' => $veiksmas
        ];
        return $this->insert($data);
    }
}

And then, in other controller, which extends Controller, I am trying to use that preloaded model by using it's function like this:
$this->logas->add_veiksmas('Created User.');

Full that Controller code:
<?php namespace App\Controllers\Admin;

use App\Models\Admin\vartotojai_model;
use CodeIgniter\Controller;

class Vartotojai extends Controller
{
    private $vartotojai;

    public function __construct()
    {
        $this->vartotojai = new vartotojai_model();
    }

    public function index()
    {

        $this->logas->add_veiksmas('Created User.');

        $this->data['vartotojai'] = $this->vartotojai->get_all_vartotojai();
        echo view('templates/Admin/Header', ['title' => 'Vartotojai']);
        echo view('Admin/Vartotojai/Index', $this->data);
        echo view('templates/Admin/Footer');
    }
}

But it is not working.
What am I doing wrong?

A:
Change Controller

class Vartotojai extends Controller
{

into BaseController

    class Vartotojai extends BaseController

A: That may be because you have not extended BaseController to Vartotojai controller.
class Vartotojai extends BaseController
Please try this.

A: Kindly note: whenever you are preloading(Models, helpers, libraries e.t.c), you need to extend the BaseController on all the controllers that will be using that model.In your case you preloaded the model correctly but you did not extend your controller to the BaseController. Use the below format in your controllers:
<?php
  namespace App\Controllers;
  use CodeIgniter\Controller;

  class ClassName extends BaseController
  {
    //your functions and code
  }
?>


text:
Q: How to Explicitly Round to a Given Number of Significant Digits I have a given number: $N$, and I would like to explicitly round it to the nearest 2 significant digits
I have the following working equation that seems very redundant to me:
$$\begin{align*}
x &= \left\lfloor\log(N)\right\rfloor-1\\
y &= N 10^{-x}\\
\text{Answer} &=\left\lfloor y + (y \bmod 1)\right\rfloor 10^{x}
\end{align*}$$
I chose to use the $Floor$ operation here because I know that I can explicitly break down any floor function into $$\lfloor x\rfloor = x - (x\bmod1)$$
I know that calculating $x$ is probably necessary because I need to find the position of second most significant digit, but I can't help but feel that there is a much simpler way of performing the rounding as dropping down to a tens' digit and raising it back to it's proper position seems rather redundant to me.
Thank you in advance for all of the help

A: Take a number like $5.678758$. Then multiply it by $100$ to get $567.8758$. You can see that it places the two decimal places in the integer area now, so that only the ones place, which was the original number's hundredths place, will be affected by the round function, which is what happens when you round something to two decimal places.
The round function will make it so that when when the tenths place of our new number is $5$ or above $5$, the ones place of our number increases by $1$, otherwise, it doesn't change. This is exactly what we want, because we want a number like $5.687$ to round up to $5.69$, and a number like $5.683$ to round down to $5.68$. So, then use round() function on this number to get $568$.  Now divide by $100$ to get $5.68$.
So, in short you want to program a function like this for a number $x$: $f(x) = round(100x)/100$.


text:
Q: Count and group multiple columns I have a table like this:
id | opt1 | opt2 | opt3
1  | valX | valY | valY
2  | valX | valX | valY
3  | valY | valZ | valX

So i need to prepare the data for display a PIE Chart, it need to looks like:
id | valX | valY | valZ
1  | 1 | 2 | 0
2  | 2 | 1 | 0
3  | 1 | 1 | 1

What is the correct way to write the mysql query?
I think i have to concat all columns first but next steps?

A: Try This
SELECT ID,
       CASE WHEN opt1='valX' THEN 1 ELSE 0 END + CASE WHEN opt2='valX' THEN 1 ELSE 0 END + CASE WHEN opt3='valX' THEN 1 ELSE 0 END AS valX,
       CASE WHEN opt1='valY' THEN 1 ELSE 0 END + CASE WHEN opt2='valY' THEN 1 ELSE 0 END + CASE WHEN opt3='valY' THEN 1 ELSE 0 END As valY,
       CASE WHEN opt1='valZ' THEN 1 ELSE 0 END + CASE WHEN opt2='valZ' THEN 1 ELSE 0 END + CASE WHEN opt3='valZ' THEN 1 ELSE 0 END As valZ
FROM TableName

A: A normalised design might look like this:
id option_id option_value
 1         1 X
 1         2 Y
 1         3 Y
 2         1 X
 2         2 X
 2         3 Y
 3         1 Y
 3         2 Z
 3         3 X

From here, your query is trivial.


text:
Q: @ApiModelProperty to swagger HTML report I am creating microservice with java class using @ApiModelProperty annotation for swagger documentation.
Is it possible to generate HTML swagger documentation from this file using some IntelliJ plugin without deploying my microservice?


text:
Q: TeamCity manual job dependency on functional test build status Our TeamCity project has components for triggered build and unit tests on commits, nightly functional tests, and manual deployment.  Currently, the deployment job can be run even when the functional tests have failed.  To prevent this, I'd like to enable a pre-condition whereby a deployment can't be run or will fail if the nightly functional tests have failed.
I'm not sure if this should be done with a build step or a dependency.  There aren't actual  snapshot or artifact dependencies involved, just a job status.

A: I found a way to do this in a Powershell build step with the TeamCity REST API and guest authentication.
$url = "nytc:7070/guestAuth/app/rest/buildTypes/id:CharlesRiver_MainFunctionalTest/builds/canceled:false/status"
if ($url -ne "SUCCESS")
{
  "Can't run deploy if tests have failed."
  "##teamcity[buildStatus status='FAILURE' text='Deploy cannot run because function tests have failed']"
  exit 1
}


text:
Q: Counting lengths of subseries Imagine series of numbers like
c(21,22,23,30,31,32,34,35,36,37,38,50,NA,52)

where subseries are defined as: x[t] is a part of some subserie if x[t] = x[t-1] + 1?
So in the example above we have the following series:
c(21,22,23,30,31,32,34,35,36,37,38,50,NA,52)
## 1  1  1  2  2  2  3  3  3  3  3  4  -  5    # serie ID
##    3    |   3    |      5      | 1 | | 1    # length

What would be the most efficient way of tagging the subseries and counting their lengths (as a single function or two separate ones)?

A: We can get the difference between the adjacent elements, check whether it is equal to 1, get the cumulative sum, and use that as group to get the length of the vector
unname(tapply(v1, cumsum(c(TRUE, diff(replace(v1, is.na(v1), 0))!=1)), length))
#[1] 3 3 5 1 1 1

If we need the NA elements as ""
unname(tapply(v1, cumsum(c(TRUE, diff(replace(v1, is.na(v1), 0))!=1)),
            function(x) if(all(is.na(x))) "" else length(x)))
#[1] "3" "3" "5" "1" ""  "1"

Or a variation posted by @DavidArenburg with rle
rle(cumsum(c(TRUE, diff(replace(v1, is.na(v1), 0))!=1)))$lengths

A: I'm accepting the answer by akrun (with contribution by David Arenburg), but for the reference I provide a Rcpp solution I created in the meantime.
NumericVector cpp_seriesLengths(NumericVector x) {
  int n = x.length();
  if (n == 1)
    return wrap(1);
  NumericVector out(n);
  int tmpCount = 1;
  int prevStart = 0;

  for (int i = 0; i < (n-1); i++) {
    if ( x[i] == (x[i+1] - 1) ) {
      tmpCount += 1;
    } else {
      for (int j = prevStart; j <= i; j++)
        out[j] = tmpCount;
      tmpCount = 1;
      prevStart = i+1;
    }
  }
  for (int j = prevStart; j < n; j++)
    out[j] = tmpCount;

  return out;
}


text:
Q: Lock Screen Shell Script Troubles So I've been messing around with the lockscreen in windows 10. What I've done is created a batch script that will swap out the lockscreen every time I log into my computer such that every time I come to my PC, a new image from a group of pre-selected images will be displayed.

Here is the code:
cd C:\Lockscreen Application
set /a count=0
for /F %%N in ('dir/s/b/a-d "%~dp0LockScreenPictures\lockscreen*.png"^|findstr /ric:"\\lockscreen[0-9][0-9]*\.png$"^|find /c /v ""') do set count=%%N
echo count=%count%
set r=%time:~-2%
echo r
set first=%r:~0,1%
if %first%==0 set r=%r:~1,1%
set /a r=(%r%%%(%count%)) + 1
echo rand=%r%
SET ls=lockscreen%r%
echo %ls%
copy LockScreenPictures\%ls%.png LockScreenDestination\lockscreen.png
start ms-settings:lockscreen
timeout 1
taskkill /f /IM SystemSettings.exe

The script is running in a folder called Lockscreen Application with two additional folders inside of it; LockScreenDestination and LockScreenPictures
LockScreenPictures contains the group of pictures that the script randomly selects one from. All have the name lockscreen(1-30).png
LockScreenDestination always has one picture in it called lockscreen.png which is intended to be the current lockscreen.
In the windows Settings, I have set the lock screen option to picture and set the picture to lockscreen.png in the LockScreenDestination folder, with the intent that every time the program would run, the lockscreen would change its image to the new one with the same path in LockScreenDestination.
However, the problem I am running into is that even though the picture displayed in lockscreen settings page matches the picture in LockScreenDestination, the actual lockscreen picture wont change from the original image.png that I gave it when I was configuring the lockscreen settings originally.
I'm not sure how to fix this so any suggestions/guidance would be appreciated.


text:
Q: Why isn't video playing or is my URL not working? I want to play a video by the press of a button inside of cell. In my code get no errors so I think every thing is setup correctly however when I run the simulator the video does not play. Is it the URL or do I need to add more code somewhere? What's the best way to play a video that is hosted on a website, provide it's url? If so this hasn't worked for me.
Here's is the code:
import UIKit
import AVFoundation
import AVKit

 class VideoPlayerView: UIView {

override init(frame: CGRect) {
    super.init(frame: frame)

    backgroundColor = UIColor.black

    let urlString = "www.dailymotion.com./video/x1prji_scott-hall-vs-hollywood-hulk-hogan-sport"

    if let url = URL(string: urlString) {
    let player = AVPlayer(url: url)

        let playerLayer = AVPlayerLayer(player: player)
        self.layer.addSublayer(playerLayer)
        playerLayer.frame = self.bounds

        player.play()
    }
}
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

 }

 class DrillsTableViewCell: UITableViewCell {

@IBOutlet weak var logoImage: UIImageView!

@IBOutlet weak var drillTitle: UILabel!

@IBOutlet weak var playButton: UIButton!
@IBAction func watchButton(_ sender: Any) {
    print(123)

        if let keyWindow = UIApplication.shared.keyWindow {
            let view = UIView(frame: keyWindow.frame)
            view.backgroundColor = UIColor.white

           view.frame = CGRect(x: 0.0, y: 0.0, width: keyWindow.frame.width, height: keyWindow.frame.height)

            let videoPlayerFrame = CGRect(x: 0, y: 0, width: keyWindow.frame.width, height: keyWindow.frame.width * 9 / 16)
            let videoPlayerView = VideoPlayerView(frame: videoPlayerFrame)
            view.addSubview(videoPlayerView)

            keyWindow.addSubview(view)
            UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: {

                    view.frame = keyWindow.frame

            }, completion: { (completedAnimation) in
                //possible features implemented later
                UIApplication.shared.isStatusBarHidden = true

            })

    }

    }

 }

A: As VC.One says, the URL you are using points to a web page - i.e. a HTML page that looks like this:

In other words, you are providing the entire HTML5 page, images, Videos, CSS etc - the information a browser needs to display a whole page.
The AVPlayer is expecting a URL to a video resource - i.e. a MP4 file or a streaming index file or manifest.
Typically, sites like YouTube or DailyMotion want you to include their branding when you include a video from them.
For your example if you click the share button you will see some embed code that you can include on a web page to just include this particular video.(this is for web rather than a native player):

Scott Hall vs. "Hollywood" Hulk Hogan by Stinger1981

There is also an SDK to allow you embed DailyMotion videos in your app- this one if for ObjectiveC and there is a newer one for Swift also:

*

*https://github.com/dailymotion/dailymotion-player-sdk-ios


text:
Q: Filter multi column list with repeating entries by partial string only with formula Is it possible to filter an array by an partial string and list multiple entries only once using a single formula (without autofilter, VBA, or additional columns)
For example, I have the following spreadsheet:
A | B  | C        | D       | F
-----------------------------------
01| ID | Class    | Value   | Filter
02| 1  | A/as     | V1      |
03| 1  | B/as     | V2      |
04| 2  | A/ab     | V3      |
05| 3  | B/ab     | V4      |
06| 3  | B/as     | V5      |
07| 2  | B/ab     | V5      |
08| 1  | A/as     | V5      |
09| 3  | A/ab     | V5      |

If I filter the column B by Class "A/*" but showing their value only once, the result should be:
A | B  | C        | D       | F
-----------------------------------
01| ID | Class    | Value   | Filter
02| 1  | A/as     | V1      | V1
03| 1  | B/as     | V2      | V3
04| 2  | A/ab     | V3      | V2
05| 3  | A/ab     | V1      |
06| 3  | B/as     | V4      |
07| 2  | B/ab     | V5      |
08| 1  | A/as     | V2      |
09| 3  | A/ab     | V2      |

instead of
A | B  | C        | D       | F
-----------------------------------
01| ID | Class    | Value   | Filter
02| 1  | A/as     | V1      | V1
03| 1  | B/as     | V2      | V3
04| 2  | A/ab     | V3      | V1
05| 3  | A/ab     | V1      | V2
06| 3  | B/as     | V4      | V2
07| 2  | B/ab     | V5      |
08| 1  | A/as     | V2      |
09| 3  | A/ab     | V6      |

Filter the column by the partial string works (adapted that description) to somehow like this:
...
    IF(
                    ISNUMBER(Search("A/*"; $B$2:$B$9))
...

that results in an array with the indexes of the list $B$2:$B$9:
ISNUMBER(Search("A/*"; $B$2:$B$9): {1;0;1;1;0;0;1;1}

and so
IF(IS...): {1;3;4;8;9}
So far I haven't found any way how to combine that with the "unique name list" approach
`MATCH(0;INDEX(COUNTIF(`

as described here
The little I having is that but it's not working that well and causes quite a cpu load, e.g. cell C8
{=IFERROR(INDEX(
               INDEX($D$2:$D$9;
                     IF(ISNUMBER(SEARCH("A/*";$C$2:$C$9));
                        ROW($D$2:$D$9)-ROW($D$2)+1)));
               MATCH(0;
                     INDEX(COUNTIF($C$2:C7;
                                   INDEX($D$2:$D$9;
                                         IF(ISNUMBER(SEARCH("A/*";$C$2:$C$9));
                                            ROW($D$2:$D$9)-ROW($D$2)+1)));
                     0;0);0));
          "error")

A: I solved it, not perfectly (it needs 3 columns) but it works like a charm.
A | B     | C     | D      | E       | F       | G
-------------------------------------------------------
01| Array |Array  | Text  | search   | search  | ordered
02| Source|Source | sought| results  | results |
03|   #1  |  #2   | *a*   |    #1    |    #2   |
04| aa    | c12   |       | c12      | c12     | c02
05| ca    | c13   |       | c13      | c13     | c06
06| ad    | c06   |       | c06      | c06     | c12
07| ee    | c11   |       | c02      | c02     | c13
08| fa    | c02   |       | c06      | c25     | c25
09| gg    | c12   |       | c13      |         |
10| ba    | c06   |       | c06      |         |
11| aa    | c13   |       | c25      |         |
12| ad    | c06   |       | #NUM!    |         |
13| gt    | c12   |       | #NUM!    |         |
14| aa    | c25   |       | #NUM!    |         |

Column E list all items of column C if the corresponding cell in column B contains expression of D3.
Formula in cell E4 what is copied to E5-E14:
{=INDEX(C:C;
        SMALL(IF(ISNUMBER(SEARCH($D$3&"/*";
                                 $B$4:$B$14));
                 ROW($B$4:$B$14));
              ROWS($E$4:E4)))}

You have to hit ctrl-shift-enter to enter the formula as an array but be careful it can take quite a while when you got a large table being sought.
I have 1300 cells, that took more than minute but only for entering the formula, coping it to the other cells is without any delay.
Here comes what is does:

*

*INDEX (arg1, arg2) will output the value of item/cell n (arg2) of column C (arg1). N is calculated in Small.

*SMALL(arg1, arg2) is supposed to return the k-th (arg2) smallest value in a data set (arg1).
This function returns values with a particular relative standing in a data set. That's exactly what is needed for to the proper use of IF and ROWS, deeper nested.

*IF (logical test , value if true) is the main part of the trick: it builds an array of the row numbers where the IF condition is true (note that the IF has no 'else' value, it will be just FALSE where the condition is not true)

*

*logical test: ISNUMBER(SEARCH($D$3&"/*"; $B$4:$B$14)) returns an array of True and False depending if SEARCH results in a numerical value or not for each cell given in the range $B$4:$B$15.
The result for the upper example is:

*

*SEARCH: 1, 2, 1, #VALUE, 2, #VALUE, 2, 1, 1, #VALUE, 1

*ISNUMBER: TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE

*value if true: ROW($B$4:$B$14)) returns an array populated by the row numbers of the array $B$4:$B$14
The result for the upper example is:
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14

IF will combine logical test #1 and value if true #2. All values in #1 will be ignored where #2 says FALSE at same position within array #2. Finally we have an array, indicating in which row of column B, within the range given in ROW(...) the expression of D3 is found.
The result for the upper example is:
4,5,6,8,10,11,12,14

*ROWS($E$4:E4) is just a trick that will give you an incrementing number (ie 1 in F2, 2 in F3...). what is used in SMALL as arg2. The result in the first cell (ROWS(...)=1) will be 4 (lowest value), in the second 5 and so on.
At the end each following up cell will show the row number/position in column B where the expression of D3 is found.
Column F filters duplicates, what was the most difficult part. Column F will "only" list all items listed in column E once.
That is the formula entered in F5! (F4 is the same as in E4) using ctrl-shift-enter:
{=IFERROR(INDEX($C$2:$C$14;
                MATCH(0;
                      COUNTIF($E$4:E4;
                              $C$2:$C$14);
                      0));
          "")}

Here comes what is does:

*

*COUNTIF(arg1, arg2) results an array of the length of the range arg1, indicating by 1 where where is a match of the entries in arg2.
The result for the upper example is:
1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0

*Match(lookup value, array , match type) looks for the first occurrence of 0 in the resulting array of COUNTIF(...) what is the 3rd position in the upper example

*

*lookup value: 0, first new value/non-duplicate

*array: resulting array of COUNTIF(...)

*match type: 0 = exactly

*INDEX(arg2 of COUNTIF, Match(...)) will finally show the new/not duplicated value what is on the 3rd position of the range arg2, what is c06 in the upper example.

Column G Finally all items will be ordered alphabetically. That is the formula entered in G4 using ctrl-shift-enter:
{=IFERROR(INDEX($F$4:$F$14;
                        MATCH(ROWS($G$4:$G4);
                              COUNTIF($F$4:$F$14;
                                      "<="&$F$4:$F$14);
                              0));
        "")}

Here comes what is does:

*

*COUNTIF(arg1, arg2) is the main part of the trick: it compares the text values given in arg2 with all the other text values given in arg1 and returns its relative rank (alphabetical order).
The result for the upper example is:
3, 4, 2, 1, 5

*ROWS($E$2:E2) is just a trick that will give you an incrementing number (ie 1 in G2, 2 in G3...). what is used in Match as lookup value.

*Match(lookup value, array , match type) looks for the first occurrence of ROWS(...) in the resulting array of COUNTIF(...).
    The result for the upper example is:
    4, 3, 1, 2, 5

*

*cell: ROWS(...)=1 => 4

*cell: ROWS(...)=2 => 3

*cell: ROWS(...)=3 => 1

*cell: ROWS(...)=4 => 2

*cell: ROWS(...)=5 => 5

*INDEX(arg1 of COUNTIF, Match(...)) will finally show the sorted entry corresponding to its ROWS(...) result.
The result for the upper example is:

*

*cell: ROWS(...)=1 => 4 in COUNTIF array => c02

*cell: ROWS(...)=2 => 3 in COUNTIF array => c06

*cell: ROWS(...)=3 => 1 in COUNTIF array => c12

*cell: ROWS(...)=4 => 2 in COUNTIF array => c13

*cell: ROWS(...)=5 => 5 in COUNTIF array => c25

So far so good the final step would be to combine all in one column. At least a found some help merging columns F&G (but I won't do it today).


text:
Q: Crontab (Centos7) with Python Files I would like to get help regarding Crontab on Centos 7.
I Need to create the scheduler to run python script (which have 2-5 addition import in the same folder) by using Crontabs
Currently, my crontab looks like this I have
PATH = /srv/git/XXX
30 * * * * cd $PATH/XXX/XXXX  python $PATH/XXX/XXXX/upload.py

I have tried to use a path to the python folder and so on, nothing works.
Then I found that the best way is to use .sh files.
WHAT I NEED:
Currently, I'm looking to for the best way to run crontab scheduler,  for python script(which have an extra import in the same folder) with PROD and DEV variables for future testings. Any better way instead of .sh files? and is .sh is the best way, what if the clean way to write them?

A: I would create a *.sh (e.g. dum.sh) file like this:
#!/bin/bash
export PATH = /srv/git/XXX
python $PATH/XXX/XXXX/upload.py

and in my Crontab file use:
30 * * * * /.../dum.sh


text:
Q: how to redraw modified image using canvas let me explain you what I do. I need to draw bigg image near to 5000px to 2688px. So I can't draw whole image because in browser it's too long. I decided to add scroll bar to see whole image. The following script allows me to draw a part of canvas
var img = new Image();
     img.onload = function(){
          canvasW = 5376
          canvasH = 2688
          ctx.drawImage(img, 0,0, canvasW, canvasH);
     };
img.src = "image.png";

Now imagine I want to apply effects like blur or brigthness, contrast etc, My canvas will change, so how can I redraw modified canvas (with effect and not the first one.
I tried to check on stackoverflow but the examples is to redraw image from the first one. I mean the drawing is not from a modifed canvas.
I tried to store base64 of my canvas and redraw by using base64 :
var image = new Image()

    image.addEventListener('load', function() {
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    ctx.drawImage(image, canMouseX, canMouseY, canvasW, canvasH);

})

image.src = bases64[bases64.length - 1]

It doesn't work because by storing base64 there is just a part of canvas that is redraw. If you want more details clone my repo on : https://github.com/wyllisMonteiro/draggingScroll/tree/master
I want to find a solution to redraw a modified canvas


text:
Q: How to Bind an Observablecollection to a GridView? I am working on an App that selects Images and adds them to an Observablecollection. I want to show this collection in Xaml. There is no clear understandable answer that I have found so far.
in the MainPage:
public ObservableCollection<TimerWallpaper> timerWallpapers = new ObservableCollection<TimerWallpaper>();

And then the code for its class is this:
public class TimerWallpaper
{
    public string timerFileName;
    public BitmapImage timerImgSource;
    public string timerTime;
    public TimerWallpaper(string name, BitmapImage imgSource, int hours, int mins)
    {
        this.timerFileName = name;
        this.timerImgSource = imgSource;
        this.timerTime = hours.ToString() + " : " + mins.ToString();
    }
}

Till this point it seems as the code is working.. the obstacle is with this code:
<GridView ItemsSource="x:Bind timerWallpapers">
  <GridView.ItemTemplate>
    <DataTemplate x:DataType="local:TimerWallpaper">
      <Image Height="100" Width="100" Source="x:Bind timerImgSource"/>
      <TextBlock Text="{x:Bind timerFileName}"/>
      <TextBlock Text="{x:Bind timerTime}"/>
    </DataTemplate>
  </GridView.ItemTemplate>
</GridView>

I keep getting "Invalid Value" for the elements of the data templet.
What are the requirements to bind the GridView to the collection?
What is the correct format to do so?

A: OK, there are a number of problems with your code. First off, you should bind to properties, not fields, so your MainPage.cs should look something like this:
public sealed partial class MainPage : Page
{
    public ObservableCollection<TimerWallpaper> TimerWallpapers { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        TimerWallpapers = new ObservableCollection<TimerWallpaper>();
        DataContext = this;
    }
}

and your TimerWallpaper like this:
public class TimerWallpaper
{
    public string TimerFileName { get; set; }
    public BitmapImage TimerImgSource { get; set; }
    public string TimerTime { get; set; }

    public TimerWallpaper(string name, BitmapImage imgSource, int hours, int mins)
    {
        this.TimerFileName = name;
        this.TimerImgSource = imgSource;
        this.TimerTime = hours.ToString() + " : " + mins.ToString();
    }
}

(Or use private set if you want to)
Next, your binding syntax is wrong on a couple of lines where you forgot to enclose it in curly braces, and lastly, the DataTemplate can only have a single child, so you need to wrap your UI elements in a layout, e.g. a StackPanel, like so:
<GridView ItemsSource="{x:Bind TimerWallpapers}">
    <GridView.ItemTemplate>
        <DataTemplate x:DataType="local:TimerWallpaper">
            <StackPanel>
                <Image Height="100" Width="100" Source="{x:Bind TimerImgSource}"/>
                <TextBlock Text="{x:Bind TimerFileName}"/>
                <TextBlock Text="{x:Bind TimerTime}"/>
            </StackPanel>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>


text:
Q: Checking and removing public keypairs from Centos7 server I recently started with Keypairs to login to SSH, my knowledge here and with SSH in general is very slim, so my apologies if this is shown in my question, or it makes it tricker to answer.
I'm trying to check what public keypairs are on my CentOS7 servers, and then remove all that are not mine. I'm concerned as i have in the past provided access to my servers to people who no longer need it (root access) when they had that access, they could have made a keypair and uploaded it to the server and therefore still able to access the server despite myself changing the root password.
How would i check if any other public keys exist (other than mine) on the server, and then remove it to stop them logging in and therefore ensure security of the server?
Thank you!

A: The keypairs are only used for specific users and so are normally kept in the home directory at .ssh/. They aren't kept in any kind of centralized place other than home directories as far as I know.
If you want to be really careful you can find directories that match .ssh on the system or id_rsa.
find / -type d -name .ssh
find / -type f -name '*id_rsa*'


text:
Q: Check status in other table with relation I have in database:
User:
id | name
1  | one
2  | two
3  | three
4  | four
5  | five

House:
id | name
1  | London
2  | Barcelona

UserHouse:
id_user | id_house
 1      |  1
 2      |  2
 4      |  1

How can i use in SQL query IF and ISSET?
SELECT * from User
I would like receive:
users:
name | has_house
1    | yes
2    | yes
3    | no
4    | yes
5    | no

I must start my query with SELECT * from User. I can't star from House or UserHouse.
Is possible? If yes, how?
I can use also DOCTRINE and Symfony.

A: Try using LEFT JOIN
SELECT  a.id, IF(COALESCE(b.id_user, 1) = 1, 'no', 'yes') has_house
FROM    user a
        LEFT JOIN userhouse b
            on a.id = b.id_user

A: If you realy can start your query only with SELECT * from User, you can try this:
SELECT * FROM User
  JOIN (
    SELECT
      User.id id_user,
      IF(UserHouse.id_house > 0, 'yes', 'no') AS has_house
    FROM
        User
      LEFT JOIN
        UserHouse ON UserHouse.id_user = User.id
    ) HasHouse ON HasHouse.id_user = User.id;

A: if you are using sql server, you should use instead of the if statement a case one.
SELECT   user.id, 'Has House' =
  CASE COALESCE(b.id_user, 0)
     WHEN 0 THEN 'No'
     ELSE 'Yes'
  END
FROM user as u leftjoin userhouse as uh on u.id = uh.id_user

http://msdn.microsoft.com/en-us/library/ms181765.aspx

A: May be this will be helpful,
http://msdn.microsoft.com/en-us/library/ms182717.aspx


text:
Q: When dropping page cache, who is releasing it? When I run
echo 1 > /proc/sys/vm/drop_caches

And Cached memory block is cleared, how can I tell who released that memory? Or is it releasing memory from no longer running processes?

A: echo 1 > /proc/sys/vm/drop_caches frees the page cache. This is kernel memory that contains the contents of disk blocks. This memory belongs to the kernel.
It's a bit misleading to describe it as "releasing" memory. The memory wasn't held in the first place: it's a cache. Cache pages are removed from memory if the memory is needed for a more important purpose. This is possible precisely because they aren't held — nobody needs them.
The content of the cache entries could belong to any number of processes. A memory page is often not owned by a single process. For example, if the page contains a cached page from a file, it could be said to belong to any of the processes that has the file open. But it could also be said to belong to the system as a whole, since the cache entry is useful even if no process currently has the file open.
Note that dropping the cache is pretty much only useful for one thing: to do I/O benchmarks with a pristine cache. Disk caches are vital to performance, and dropping them is a major performance hit (and so is not leaving enough room in RAM for caches, by the way).


text:
Q: Send value in body from angular2 service I have an Angular2 service
logIn (username, password): Observable<User[]> {
  return this.http.get(this.getUserUrl + username + '/' + password)
     .map(this.extractData)
     .catch(this.handleError);
}

which sends a request to
router.get('/authenticate/:username/:password', function(req, res, next) {
schema.User.find({ username: req.param("username"), password: req.param("password")}).exec(function (err, users) {
    if (err)
      return console.error(err);
      console.log("Load success: ", users);
      res.send(users);
    });
});

but i need a way to send the username, and especially the password in a way which doesn't expose it to the request itself

A: You can change your methods to post
logIn (username, password): Observable<User[]> {
  return this.http.post(this.getUserUrl + "test", {username: username, password: password})
     .map(this.extractData)
     .catch(this.handleError);
}

node:
router.post('/authenticate/test', function(req, res, next) {
 var username = req.body.username;
 var password = req.body.password;
 schema.User.find({ username: username, password: password }).exec(function (err, users) {
    if (err)
      return console.error(err);
      console.log("Load success: ", users);
      res.send(users);
   });
});


text:
Q: Subversion and mod_dav_svn: Why make www-data the owner of the files instead of root? I've set up a dedicated Subversion server with Apache and mod_dav_svn on Ubuntu 9.10 Server, and I've got everything working fine at this point. However, I noticed that when it comes to assigning the right file permissions to the repository directory, most tutorials telll you to do something like this:
sudo chown -R www-data:www-data /svn/myrepo # make www-data the owner of the repo so Apache
                                            # can write to it
sudo chmod -R g+ws /svn/myrepo  # Give the www-data group write access as well, and enable
                                # setgid so that new directories have that group

Now, I did it a little differently. I created a new subversion group, and made that the owner of the repository, then added myself and www-data to that group, the reasoning being that this way I can edit the configuration files in /svn/myrepo/conf and the hook scripts in /svn/myrepo/hooks, and it also keeps Apache and Subversion a bit more separate from each other. I've seen other tutorials recommend something similar, but then tell you to do this:
sudo chwown -R www-data:subversion /svn/myrepo
sudo chmod -R g+ws /svn/myrepo

These same tutorials imply that you are creating the subversion group specifically to keep Subversion and Apache mostly separate from each other, so why do they turn around and make www-data the owner of the files? Is there any good reason to make www-data the owner of the repository files at all? Why not just make root the owner? It seems like keeping www-data as the owner of the repository unnecessarily ties Subversion "too much" to Apache. Is there any good reason to make the owner www-data instead of root, as long as the group is still subversion?

A: You wouldn't typically want root to be the owner of the repository because that would mean that apache (httpd) had to be running as root in order to access the svn repository, which is usually considered a security risk.
In my experience, you mostly interact with subversion via apache. Since that is the case, it seems easier and more natural to just let apache (www-data) be the owner of the subversion repository. If you have created your subversion repository in a separate directory structure from your web sites, there should be no confusion about which files are used for what. For example, I have /data/www for my websites and /data/svn for my svn repositories.
Then to allow yourself the ability to modify the repository config files and hook scripts, just make yourself a member of the www-data group and perform the:
sudo chmod -R g+ws /svn/myrepo

as you mentioned above and you're good to go.
I don't see a benefit to separating the svn repository owner from the apache user, but if you really insisted on doing that, you could create a subversion user in addition to the subversion group and make the owner of /svn/myrepo be subversion:subversion. Then just make yourself and apache a member of the subversion group and modify the directory permissions as above.

A: IIRC, Apache only needs write access to the "dav", "db", and "locks" directories. It doesn't matter if it's via user or group ownership. There's no reason for Apache to have write access to "conf" and "hooks" in most cases.


text:
Q: Router MAC address procuring for WPS positioning It is known that either Skyhook or Google procured the wireless access points mac address while roaming around.
I am curious how the MAC addresses were procured, as this does not seem to be easy to do!
MAC address is used only on the local network and falls in the datalink layer of OSI network model.
Now outside of such wifi point only IP packets are seen and the mac addresses are completely concealed.

A: The MAC address is present in every packet send. Either Wireless or Wired.
For wired they do not pass beyond a router.
For wireless the point 'up to a router' is the range of the wireless signal. Those are very easy to intercept and will be present in almost any packet.


text:
Q: Why does the protobuf use builder to construct data? In java, to create a data structure we need to do like
Builder builder=Data.newBuilder();
builder.setField(...);
...
Data=builder.build();

Why not just provoide the getter() and setter() for each field of Data?. like:
Data data=new Data();
data.setFiled(...);

A: Protobuf uses builders to generate Message objects, because the message objects themselves are immutable:

Message objects [...] are immutable, just like a Java String. To construct a message object, you need to use a builder.

This is probably done to allow optimizations that can only be done when Message objects are known not to change.


text:
Q: Linked SQL Server Issue I have 3 servers all running Windows Server 2016 Datacenter:
Server1 is a domain controller and has ssms installed for accessing SQL Server Instances on Server2 and Server3
Server2 & Server3 are running SQL Server Microsoft SQL Server 2016 (SP1-CU3)
Server2 has a linked server link to Server3
Server3 has a linked server link to Server2
If I log onto server2 and run a select query which uses the link to server3
Select top 5 * from [Server3].[DB3].[dbo].[TableName]

It runs fine and results are returned.
If I log onto server3 and run a select query which uses the link to server2
Select top 5 * from [Server2].[DB2].[dbo].[TableName]

It runs fine and results are returned.
But If I log onto Server1 and open ssms, connect to Server2 and run query
Select top 5 * from [Server3].[DB3].[dbo].[TableName]

I receive error 'Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.'
And the same happens if I log onto Server1, open ssms, connect to server3 and run query
Select top 5 * from [Server2].[DB2].[dbo].[TableName]

I am logging onto all 3 servers using the same domain credentials, but it feels to me like if im running the query from Server1, then its not passing my credentials through causing the query to be ran against the target sql instance as NT AUTHORITY\ANONYMOUS LOGON

A: This is the classic "Double Hop" problem.  Several pieces need to be in place for this to work. For server1 (SSMS) -> server2 (SQL) -> server3 (sql)

*

*server2 must have a SPN

*server3 must have a SPN

*server2 must be allowed to delegate permissions to server3

A SPN (Server Principal Name) is set in Active Directory on an account and basically ties a service to that account.  e.g.  MSSQL Server on SERVER2 is running as domain\sql_server.  When you connect with Kerberos, You request a ticket from the DC to connect to "MSSQL Server on SERVER2".  The DC replies with a ticket is can only be un-encrypted by domain\sql_server.
SQL Server will attempt to self-register an SPN when it starts.  This is logged in the ERRORLOG

The SQL Server Network Interface library successfully registered the Service Principal Name (SPN) [ MSSQLSvc/MYLAPTOP:1433 ] for the SQL Server service.
The SQL Server Network Interface library successfully registered the Service Principal Name (SPN) [ MSSQLSvc/MYLATOP ] for the SQL Server service.
SQL Server is attempting to register a Service Principal Name (SPN) for the SQL Server service. Kerberos authentication will not be possible until a SPN is registered for the SQL Server service. This is an informational message. No user action is required.

Verify that you can connect from server1 to server2/3 using Kerberos authentication:

*

*remote into server1

*connect using SSMS to server2

*Run this:

select auth_scheme from sys.dm_exec_connections where session_id =
@@spid

*If it returns NTLM, then you are either missing the SPN on server2 or you have a duplicate SPN.  If it returns "Kerberos" then congratulations, you're partially there.

*Repeat this test by trying to connect from server1 to server3.
Once you can successfully connect to both server2 and server3 using Kerberos, you need to ensure that the accounts that SQL is running as have permissions to delegate.  This is an active directory setting that is on the service account SQL is running as.


text:
Q: how to submit a from with validation in PHP? I want to submit this form through PHP. with validation for required field and validation for phone number and email field also
<form action="" method="" id="get-protected">

        First Name
    <input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" />

        Last Name
    <input id="txt_LastName" type="text" title="First Name. This is a required field" />

        Phone
    <input id="txt_Phone" type="text" title="First Name. This is a required field" />

        Email
    <input id="txt_Email" type="text" class="required" title="Email. This is a required field" />

    <input type="submit" value="" class="button" />

</form>

A: In your method attribute inside your form, you need to declare either post or get.
Since your action attribute is "" it will submit to the page itself rather than redirecting to another page, so you can have your code that checks for validation in the same PHP file. First validation that is often checked is if the variable has a value by using isset:
if(isset($_POST['txt_Phone'])) { ... }

This just checks that the Phone number field does not contain empty data. I strongly suggest you perform other validation checks on the POST array so you do not have any users posting malicious code.
You can use functions like htmlspecialchars to prevent user-supplied text depending on what you plan to do with the values
Here are some references to help you along the way in the order they should be viewed.

*

*Form Validation using PHP - PHP and MySQL Tutorial

*PHP Advance Form Validation Tutorial

*PHP Tutorial Part 2: Form Validation

A: Your form tag needs a target in the action field and a method in the method field (either GET or POST). So make the action your PHP script.
<form name="input" action="form_submit.php" method="get">

As for field validation, you will either have to parse that inside of the PHP and return a response or use Javascript in the browser to check on the fly.

A: Okay, firstly, I like to set the form action to <?=$_SERVER['REQUEST_URI']?> to submit it back to the current page, but leaving it as you have it will work fine too.
Secondly, you need to give all your <input>s a name attribute. This is the variable name that PHP will see.
When your users get an error (something doesn't validate correctly) you don't want all the data they entered to disappear. That means you have to set the value attributes of each input to what they had previously entered. Thus, your form starts to look like this:
<form action="<?=$_SERVER['REQUEST_URI']?>" method="" id="get-protected">

    First Name
    <input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" name="first_name" value="<?=htmlspecialchars($_POST['first_name'])?>" />

...

    <input type="submit" name="submit" value="" class="button" />

</form>

If you didn't know <?= is a basically a shortcut for <?php echo but it will only work if your server has short tags enabled. Some people prefer to type it out the long way (in case they want to switch servers later, or for future-compatibility, or because they're nutbars), but I say screw them, I'm lazy.
This page that has the form on it, has to saved with a .php extension (well, technically it doesn't have to, but that's another story).  Then you need to handle you form validation. You have to code that up yourself.  It might look something like this (put it above your form somewhere)
<?php
if($_POST['submit']) {
    $errors = array()
    if(empty($_POST['first_name'])) $errors[] = 'please enter your first name';

    if(empty($errors)) {
        // save the data to database or do whatever you want with it
        header('redirect:succcess.php');
    } else {
        foreach($errors as $e) {
            echo $e;
        }
    }
}
?>

It's been a while since I've coded in PHP so forgive me if there are syntax errors. That's the jist of it anyway, I'm sure you can find validation libraries out there if you Google. Might take some of the grunt work out of trying to validate email addresses and such.

A: Here is the shcema of such a script:
if ($_SERVER['REQUEST_METHOD']=='POST') {
  //data validation:
  $err="";
  if (valid_phone($_POST['phone'])) $err="Wrong phone no";
  if (!$err) {
    //record data:
    $sql="...";
    query($sql);
    Header("Location: ".$_SERVER['REQUEST_URI']);  //redirect and exit
    exit;
  }
}
?>

<? if ($err) ?> <?=$err?>
<form method="POST" id="get-protected">
here goes your form

A: Using Javascript you can do the validation for this form.For each condition you can use return true and return false,based on the condition.Then you can submit the value.
Using action attribute in form tag the values will be submitted to that file.


text:
Q: Tomcat - Further occurrences of HTTP header parsing errors will be logged at DEBUG level I have created a SpringBoot application. When I am making a HTTP Post request, with a large header size, I am getting the following error :
2018-03-09 14:53:01,190 INFO  [http-nio-8080-exec-1] logging.DirectJDKLog (DirectJDKLog.java:182) - Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Request header is too large
at org.apache.coyote.http11.Http11InputBuffer.fill(Http11InputBuffer.java:706) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.coyote.http11.Http11InputBuffer.parseHeader(Http11InputBuffer.java:853) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.coyote.http11.Http11InputBuffer.parseHeaders(Http11InputBuffer.java:565) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:703) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.27.jar:8.5.27]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.27.jar:8.5.27]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_101]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_101]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.27.jar:8.5.27]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_101]

Please note that further occurrences of HTTP header parsing errors will be logged at DEBUG level (as mentioned in the Error Note). I want to fix this, so that all occurrences of such errors are logged at INFO level itself.
So, I added these two lines in application.properties file (which is located at src/main/resources/config/):
org.apache.juli.logging.UserDataHelper.CONFIG = INFO_ALL
org.apache.juli.logging.UserDataHelper.SUPPRESSION_TIME = 0
# server.maxHttpHeaderSize=10000000

But this is not working (and only the first occurrence of the error is logged at INFO level).
Please note that,  setting maxHttpHeaderSize=10000000 is working fine, and it makes the large header issue to go away completely.
But what I want here is - that all such errors are logged at INFO level itself.
Any help will be appreciated :)
Additional Info : SpringBoot version : 1.5.10.RELEASE,
Tomcat version : 8.5.27

A: Those two properties must be set as Java system properties. There is not code-free way to set those in Spring Boot (cf. this question), so in this case I would set them in an EmbeddedServletContainerCustomizer for Spring Boot 1.x:
@Component
public class UserDataHelperCustomizer implements EmbeddedServletContainerCustomizer {

   @Override
   public void customize(ConfigurableEmbeddedServletContainer container) {
      System.setProperty("org.apache.juli.logging.UserDataHelper.CONFIG", "INFO_ALL");
   }

}

and a similar WebServerFactoryCustomizer for Spring Boot 2.x:
@Component
public class UserDataHelperCustomizer implements WebServerFactoryCustomizer<WebServerFactory> {

   @Override
   public void customize(WebServerFactory factory) {
         System.setProperty("org.apache.juli.logging.UserDataHelper.CONFIG", "INFO_ALL");
   }
}

Remark: SUPPRESSION_TIME=0 and CONFIG=INFO_ALL are equivalent, so only one needs to be set.


text:
Q: How to Hide a folder in Sharepoint What else I need to add to following code to make sure the folder is hidden or read only?
SPListItem createFolder = myDocLib.Folders.Add(myDocLib.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, "Folder444");
folder.Update();

A: Unlike actual lists, a Folder cannot be made "hidden" in the normal sense. That is, you cannot make it invisible to the UI, but still have all the normal access levels associated with it (for example, the traditional Workflow History list is hidden in this fashion). In a way, your goals of hiding and making it read-only coincide when it comes to folders, as both are accomplished by Permissions. You can technically reduce the visibility of a particular item through a complicated view filter, but that would only change things on the view level.
The visibility of a list item, which a Folder is, is based on whether you have permissions on that item. The only way to truly "hide" a list item is to remove all permissions of a person from that list item. In order to make a folder read-only, you would remove all Add, Edit, and Delete permissions from the folder. If you still have the default SharePoint permission levels (Full Control, Design, Contribute, and Read), then simply reassigning everything to Read will accomplish this goal.
Here is an example of code that I use to make a discussion (which is a folder) hidden from all users except those in the group "Engineers", to whom it is read-only.
// I excluded these two variable declarations because they were specific to
//   my situation.
// Giving you my variable declarations would be misleading, since this is
//   meant to be a generic code sample.
// SPListItem folder is the folder I am working on.
// SPWeb web is the SPWeb for the site I am on.
if (!folder.HasUniqueRoleAssignments)
{
    folder.BreakRoleInheritance(false); //Setting false erases all permissions, so now the folder is hidden from everyone.
    folder.SystemUpdate(false);
}
SPRoleDefinition role = web.RoleDefinitions["Read"];
SPPrincipal smith = web.SiteGroups["Engineers"]; //You would replace "Engineers" with the name of whatever group you want to have read permissions. Or, use web.SiteUsers[] to get a specific user.
SPRoleAssignment roleAssignment = new SPRoleAssignment(smith);
roleAssignment.RoleDefinitionBindings.Add(role);
folder.RoleAssignments.Remove(smith); //If I have already assigned a different permission, this will clear it so that I ensure that the only permission is Read.
folder.RoleAssignments.Add(roleAssignment); //This sets it to Read-Only for these people.
folder.SystemUpdate(false);

EDIT
When assigning multiple instances, it depends on whether you are doing all of the groups or just a subset. I'll list the code for all groups since that is what you are directly asking.
if (!folder.HasUniqueRoleAssignments)
{
    folder.BreakRoleInheritance(false); //Setting false erases all permissions, so now the folder is hidden from everyone.
    folder.SystemUpdate(false);
}
SPRoleDefinition role = web.RoleDefinitions["Read"];
SPRoleAssignment roleAssignment;
foreach (SPPrincipal smith = web.SiteGroups)
{
    roleAssignment = new SPRoleAssignment(smith);
    roleAssignment.RoleDefinitionBindings.Add(role);
    folder.RoleAssignments.Remove(smith);
    folder.RoleAssignments.Add(roleAssignment);
}
folder.SystemUpdate(false);

If you wanted to do it only for a subset of groups, you would define a list of the names of all of those groups, do a foreach (string groupName in groupList), and as the first line of the loop, specify SPPrincipal smith = web.SiteGroups[groupName];.

A: Thank you Cornet. Here is the method that makes a folder read only. THANKS AGAIN FOR YOUR HELP...
    private void MakeFolderReadOnly(SPWeb web,SPListItem folder)
    {
        if (!folder.HasUniqueRoleAssignments)
        {
            //Setting false erases all permissions, so now the folder is hidden from everyone.
            folder.BreakRoleInheritance(false);
            folder.SystemUpdate(false);
        }

        SPRoleDefinition role = web.RoleDefinitions["Read"];
        SPGroupCollection collGroups = web.SiteGroups;
        foreach(SPGroup group in collGroups)
        {
            SPPrincipal principal = group;
            SPRoleAssignment roleAssign = new SPRoleAssignment(principal);
            roleAssign.RoleDefinitionBindings.Add(role);
            folder.RoleAssignments.Remove(principal);
            folder.RoleAssignments.Add(roleAssign);
            folder.SystemUpdate(false);
        }

    }


text:
Q: React jsx: Cannot find module '' or its corresponding type declarations.ts(2307) after updating NodeJS from 12 LTS to 18 LTS I updated NodeJS from v12.22.9, (npm 6.14.15) (the default Ubuntu 22 comes with) to the LTS, version v18.12.0 which also comes with npm 8.19.2
I just opened VSC and all of my components have this warning for various imports:
import WhiteLogo from "assets/img/GEF-logo-white.png";
import GreenLogo from "assets/img/GEF-logo-green.svg";
import { ReactComponent as Twitter } from "assets/icons/twitter.svg";
import styles from "./OverviewBanner.module.css";

Cannot find module 'assets/img/logo-white.png' or its corresponding type declarations.ts(2307)
Cannot find module 'assets/img/logo-green.svg' or its corresponding type declarations.ts(2307)
Cannot find module 'assets/icons/twitter.svg' or its corresponding type declarations.ts(2307)
Cannot find module './OverviewBanner.module.css' or its corresponding type declarations.ts(2307)

I am using React and JS.
This is the jsconfig.json:
{
  "compilerOptions": {
    "checkJs": true,
    "jsx": "react-jsx",
    "baseUrl": "src"
  },
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules",
    "build"
  ]
}

package.json:
  "dependencies": {
    "@ant-design/icons": "^4.7.0",
    "@reduxjs/toolkit": "^1.8.6",
    "antd": "^4.23.3",
    "less": "^4.1.3",
    "react": "^18.1.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.0.4",
    "react-router-dom": "^6.4.2",
    "react-scripts": "5.0.1",
    "web-vitals": "^3.0.3"
  },

There is a file: /node_modules/react-scripts/lib/react-app.d.ts that looks like this:
/// <reference types="node" />
/// <reference types="react" />
/// <reference types="react-dom" />

declare namespace NodeJS {
  interface ProcessEnv {
    readonly NODE_ENV: 'development' | 'production' | 'test';
    readonly PUBLIC_URL: string;
  }
}

declare module '*.avif' {
  const src: string;
  export default src;
}

declare module '*.bmp' {
  const src: string;
  export default src;
}

declare module '*.gif' {
  const src: string;
  export default src;
}

declare module '*.jpg' {
  const src: string;
  export default src;
}

declare module '*.jpeg' {
  const src: string;
  export default src;
}

declare module '*.png' {
  const src: string;
  export default src;
}

declare module '*.webp' {
    const src: string;
    export default src;
}

declare module '*.svg' {
  import * as React from 'react';

  export const ReactComponent: React.FunctionComponent<React.SVGProps<
    SVGSVGElement
  > & { title?: string }>;

  const src: string;
  export default src;
}

declare module '*.module.css' {
  const classes: { readonly [key: string]: string };
  export default classes;
}

declare module '*.module.scss' {
  const classes: { readonly [key: string]: string };
  export default classes;
}

declare module '*.module.sass' {
  const classes: { readonly [key: string]: string };
  export default classes;
}

What is wrong ?

A: New File env.d.ts
declare module '*.svg' {
  const src: string
  export const ReactComponent: unknown
  export default src
}
declare module '*.png' {
  const src: string
  export default src
}
type CSSModuleClasses = { readonly [key: string]: string }

declare module '*.module.css' {
  const classes: CSSModuleClasses
  export default classes
}


text:
Q: When three numbers out of four are the same I used random generator to generate four numbers, then I have to decide if three of them are the same.
What is wrong with the following code ?
if((r1= r2 =r3)|| (r1 = r2 = r4)|| (r1 = r3 =r4)|| (r2 = r3 =r4)) {
    System.out.println("Three of a kind.");
}

The error says cannot convert from int to boolean. Also, I thought it should be ==, but == yields error while = doesn't.

A: You need to use the equality operator ==, not the assignment operator =.
When you compare integers you do it like this:
if(int1 == int2) {
    // they are equal
}

If you want to test that 3 integers are equal, you could do it like this:
if(int1 == int2 && int2 == int3) {
    // all three integers are equal
}

See that we have used the logical AND operator && to combine two boolean expressions so that both expressions must be equal for the if statement to evaluate to true.


text:
Q: Dropdownlist population error from dataset asp .net I am having trouble in populating dataset in Dropdownlist. I want to show username column from my database table in dropdownlist, but only the last row value is shown. I am stuck, after searching for hours I couldn't find any solution, Every code almost gives me same problem.
Here is what i am trying to do:
Dataset ds = new Dataset();
ds = db.search();

            if(ds.Tables[0].Rows.Count>0)
{
            DropDownList1.DataSource=ds;
            DropDownList1.DataBind();
}

In ASP Markup:
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>

A: please set below property of Dropdown list as shown in code at server side. Please replace "Username" and "ID" with retrieve recordset column Name.
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "UserName";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();

A:  Using ds As DataSet = data_readers.data.ExecuteDataSet("LoadSearch", NOTHING)
            If ds.Tables.Count > 0 Then
                If ds.Tables(0).Rows.Count > 0 Then

                    DropDownList1.DataSource = New DataView(ds.Tables("myDataset"))
                    DropDownList1.DataBind

                End If
            End If
  End Using

A: your "ASP Markup" is totally empty! Here take a look at my code, it should be a good example for your source page:
You Also need to setup a objectdatasource: I provided that code below the drop down list. Listitem value is just a preference of mine. In your situation your column name would replace TRANS_CD_DESC.
<asp:DropDownList ID="ddlTRANS_CD_DESC" DataSourceID="OBJ_TRANS_CD_DESC" DataValueField="TRANS_CD_DESC"
                            DataTextField="TRANS_CD_DESC" AppendDataBoundItems="true" runat="server" Text='<%# bind("TRANS_CD_DESC") %>'>
                            <asp:ListItem Value="">-- Select One --</asp:ListItem>
                        </asp:DropDownList>
                        <asp:ObjectDataSource ID="OBJ_TRANS_CD_DESC" runat="server" TypeName="project1.dbqry"
                            SelectMethod="gProjectCIS"></asp:ObjectDataSource>


text:
Q: Cannot get summer note in laravel vue I'm trying to get Summernote with vue in laravel but it wont work.
What I've done

*

*install summer note

*import summernote js file in bootstrap.js

require('summernote/dist/summernote-bs4.js');

*import summernote stylesheet in app.scss

@import '~summernote/dist/summernote-bs4.css';

*run npm run watch

*added codes below to my component ready part

import validate from 'validate.js';

export default {
    data: function () {
        return {
            project: {
                title: '',
                body: '',
                attachment: '',
                projectclass: '',
                deadline: '',
                budget: 0,
                user_id: '',
                report_type: '',
                csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            },
            errors: null
        }
    },
    computed: {
        currentUser() {
            return this.$store.getters.currentUser;
        }
    },
    methods: {
        add() {
            this.errors = null;
            const errors = validate(Object.assign(this.$data.project, {user_id: this.currentUser.id}));
            if(errors) {
                this.errors = errors;
                return;
            }
            axios.post('/api/projects/new', Object.assign(this.$data.project, {user_id: this.currentUser.id})).then((response) => {
                this.$router.push('/projects')
            });
            Vue.nextTick(function () {
                $('[data-toggle="tooltip"]').tooltip();
            })
        }
    },
    ready: function() {
        var config = {};
        var that = this;
        config.minHeight = null;
            config.maxHeight = null;
            config.toolbar =  [
                    ['style', ['bold', 'italic', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['height', ['height']]
            ];

        config.onBlur = function(e) {
                that.body = $('#summernote').code();
        };
        $('#summernote').summernote(config);
    },
    watch: {
        budget: function(newValue) {
            const result = newValue.replace(/\D/g, "")
                .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            Vue.nextTick(() => this.budget = result);
        },
    }
}

What I get

Question

*

*What and where did i make mistake?

*How to fix it?


text:
Q: Differentiate MMS and SMS via MMS/SMS listeners in Android Is there any ways to differentiate MMS and SMS messages by using a MMS/SMS listener before they hit the inbox?

A: The first indicator of an MMS message is a WAP-push with the MIME-type  "application/vnd.wap.mms-message", so you could register a receiver for "android.provider.Telephony.WAP_PUSH_RECEIVED":
    <receiver android:name=".SomeReceiverName"
        android:permission="android.permission.BROADCAST_WAP_PUSH">
        <intent-filter>
            <action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />
            <data android:mimeType="application/vnd.wap.mms-message" />
        </intent-filter>
    </receiver>

To discover whether or not its a received MMS you're going to have to crack open the PDU:s and extract the X-Mms-Message-Type, which should be m-notification-ind (as per WAP 209). You can also pick out the X-Mms-Transaction-ID, which one thinks should be stored in the Telephony.Mms.TRANSACTION_ID column in the message provider if you want to link them up later.


text:
Q: Powershell array to html I've three arrays that i would like to write to a HTML page :
foreach($arrin $array1){

  # create TAb in html file
 }
foreach($ar in $array2){
 # create TAb in html file
 }
foreach($a in $array3){
 # create TAb in html file
 }

How can i do this ? THNKS

A: PowerShell has a built-in command to generate HTML. Try this:
$array | ConvertTo-Html > foo.html

Or if you only want certain properties in the array:
Get-Process | ConvertTo-Html -Property Name,Id,PM


text:
Q: How do I achieve this same result using Active Query Methods? This is what I want to achieve using active query method I was asked not to do array iterations but instead use active query methods to achieve this
         def index
            @measurements = current_user.measurements.with_units.created_on
            data = Hash.new { |h, k| h[k] = [] }
            @measurements.each do |m|
              data[m.unit.title] << m
            end
            render json: { data: data, status: :ok }
          end`

This is the image of the expected JSON i wish to achieve with Active query method
and here are my models for Measurement and Units
        class Measurement < ApplicationRecord
          belongs_to :user
          belongs_to :unit
          scope :with_units, -> { includes(:unit) }
          scope :created_on, -> { order('created_at DESC') }

          validates :value, presence: true
        end

        Model for Units
        class Unit < ApplicationRecord
          has_many :measurements

          scope :with_measurements, -> { includes(:measurements) }
          scope :with_user_id, ->(user) { where(user_id: user.id) }

          validates :title, presence: true
        end

    Schema table for measurements

      create_table "measurements", force: :cascade do |t|
        t.integer "unit_id"
        t.integer "user_id"
        t.float "value"
        t.datetime "created_at", precision: 6, null: false
        t.datetime "updated_at", precision: 6, null: false
      end

Schema table for Units

      create_table "units", force: :cascade do |t|
        t.string "title"
        t.datetime "created_at", precision: 6, null: false
        t.datetime "updated_at", precision: 6, null: false
      end

A: Use as_json to convert ActiveRecord collection into json.
def index
  @measurements = current_user.measurements.with_units.created_on
  render json: { data: @measurements.as_json(include: :unit) , status: :ok }
end


text:
Q: VB.Net Parameter count mismatch I'm writing a function that convert an Array List into a Data Table, and I'm getting an error "Parameter count mismatch".
I've been looking and googling the issue but couldn't found anything that could help me resolve my issue.
```
   'Function that convert ArrayList to DataTable
Public Function ConvertArrayListToDataTable(ByVal MyAList As ArrayList) As DataTable

    Dim dt As New DataTable()
    For i As Integer = 0 To MyAList.Count - 1

        'create a Generic Object
        Dim values As Object = MyAList.Item(i)
        Dim properties() As PropertyInfo =
   values.GetType().GetProperties()

    'Loop through each property, and add it as a column to the datatable

        For Each prop As PropertyInfo In properties
            Try
                Dim dc As DataColumn = New DataColumn(prop.Name)

                'Add the column definition to the datatable
                dc.DataType = prop.PropertyType
                dt.Columns.Add(dc)
            Catch ex As Exception
                MessageBox.Show(" Can't add column" & ex.Message)
            End Try

        Next

        'for each object in the list, loop through and add
        'the data to the database
        For Each o As Object In MyAList
            Try
                'create new row
                Dim row As DataRow = dt.NewRow()
                Dim pf() As PropertyInfo = o.GetType().GetProperties()

                For Each item As PropertyInfo In pf
                    row(item.Name) = item.GetValue(o, Nothing)
                Next

                dt.Rows.Add(row)
            Catch ex As Exception
                MessageBox.Show(" Conversionerror" & ex.Message)
            End Try
        Next
    Next
    Return dt
End Function
```

I see the code get the Table and the column count as well, but cannot write value. it failed on getvalue.
The function suppose return a datatable containing retrieved data and populate datagrid
For Each prop As PropertyInfo In properties
            Try
                Dim dc As DataColumn = New DataColumn(prop.Name)
                dc.DataType = prop.PropertyType
                dt.Columns.Add(dc)
            Catch ex As Exception
                MessageBox.Show(" Can't add column" & ex.Message)
            End Try

Next

A: If you are filling a DataTable from a database just let the DataTable figure out the datatype. ArrayList is not used in new code. You can make a class or structure and then use List(Of T) or if absolutely necessary List(Of Object). Test just the plain old DataTable.
Private Sub FillDataGridView()
    Dim dt = New DataTable()
    Using cn As New SqlConnection(My.Settings.CoffeeConnection)
        Using cmd As New SqlCommand("Select * From Coffees;", cn)
            cn.Open()
            dt.Load(cmd.ExecuteReader)
        End Using
    End Using
    For Each col As DataColumn In dt.Columns
        Debug.Print(col.DataType.Name)
    Next
    DataGridView1.DataSource = dt
End Sub

A: Thank you Mary. It was a great experience. I was challenging myself to see how I can fill the Datagrid from Arraylist to Datatable. I finally follow your advice and review my Function as below:
      Public Function FillDataGridView(SQLStatement As String) As DataTable
        'create an DataTable to hold the results
        Dim dt As New DataTable()
        Try
            Using con As New SqlConnection(ConnectionString)
                con.Open()
                Using cmd As New SqlCommand(SQLStatement, con)
                    'Get the reader
                    Using Reader = cmd.ExecuteReader()
                        dt.Load(Reader)
                    End Using
                End Using
            End Using
            For Each col As DataColumn In dt.Columns
                Debug.Print(col.DataType.Name)
            Next
        Catch ex As Exception
            Console.WriteLine("SQL retrieve row:" & ex.Message & Err.Number)
        Finally
            Call CloseConn()
        End Try
        Return dt
    End Function


text:
Q: How does the WCF service interact with my winform app? I am currently developing a C# Windows Form Application that I intend to let it interact with a server. The server will receive posting from a mobile application that I have developed and whenever a posting is received, my Windows Form Application should be notified and give me a notification. In order to do this, I intend to use WCF duplex service for it.
E.g. My mobile application sends an posting over to my server. Once my server reads and receives the new posting, the service should send a message over to my winform app to alert me that a posting is received. And the UI of the winform app should update accordingly to what I want to updated. (e.g. adding new panels)
This is basically how I wish for it to work
They way this would work is

*

*WCF Service in running on my server

*Windows Form connects to my server's WCF service using Duplex Contract

*Mobile app posts to a webpage

*Once the webpage receives the posting, the asp.net will invoke the WCF service

*WCF duplex service receives the posting and sends the information to the winform app

*My winform Application aka WCF Client updates UI with this new message received

My question is, how does step 4 proceed to step 5? To be specific, how does the service sends the information over to the winform app upon receiving the posting.
To be even more specific, once the posting is received from the webpage, the service contract is invoked and the information is sent and received by the service, how does the service make use of the call back channel to send the information over to the winform app and update the UI accordingly?

A: The answer to this question depends on how your WCF service is hosted and how "big" the service will eventually be (in terms of number of simultaneous clients).

*

*The simplest scenario is a self-hosted WCF service (meaning hosted in a Windows Service or as a desktop application--not in IIS). In this case, you can use InstancePerSession mode and  make your service use sessions. In this case, you'll have a 1:1 correspondence between clients and instances of your service class. When a client connects, retrieve the callback reference and store it in a static list outside of the service class. When you need to send a message to one or more clients, simply iterate over (or find the desired client in) your list and call the appropriate function on the callback contract

*If you need to host your service in IIS, then the situation is trickier because you have the possibility of multiple processes hosting your service, so your list can potentially get fragmented (or blown away in the event of an app pool recycle). In this case, you'll have to use something external to your service (MSMQ, perhaps) to notify other application pool processes that a message needs to be sent.

A: In terms of a duplex connection, you are really just able to communicate two way over that one connection, not with all connections of the service without doing some tricky thread stuff and shutting the door on any scalability (or using something outside the service to handle to pub/sub).
One solution though that may work a lot more along the lines of what you want to do would be SignalR.  It allows a single client to make a request and then you can broadcast data from that request to other clients (or target it).  Take a look at its info, its sole purpose is real time communication in .NET with multiple clients.
Also another note, is that you will want to use some sort of BackgroundWorker or something for your listening thread in WinForms so that the UI is not locked while the background operations are running.


text:
Q: Google login failed when using new firebase app and it is working well for old firebase apps I need to change firebase app in android app, But when chaning it I have this error
Google sign in failed
com.google.android.gms.tasks.RuntimeExecutionException: com.google.android.gms.common.api.ApiException: 12500:
    at com.google.android.gms.tasks.zzu.getResult(Unknown Source)

*

*I added sh1

*Enable google loging method

*Using last updated firebase versions
implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-auth:18.1.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
add plugin to the end of the build gradle app level
apply plugin: 'com.google.gms.google-services'

add google services in gradle progject level
classpath 'com.google.gms:google-services:4.3.0'

Any one can help?
Thank you!

A: The app was working well in old firebase projects, but in new firebase projects we had to add the logo of the app in the gcp console and it is working well, the firebase support who is suggest this solution.
Thanks!


text:
Q: Applying custom formats to numeric variables in R I have a df that uses numbers to refer to categorical data and a CSV that defines the categories (1=Smoker, 2=Non-Smoker, etc). In SAS, I was able to convert the format CSV into a format file and apply these formats to the variables:
data want;
    set have;
    formatted = put(varX,custFormat.);
run;

This would provide me with the output:
varX   formatted
1        Smoker
2        Non-Smoker
3        Occasional Smoker
1        Smoker

Given that I have a csv with all the formats, I could bring this in and merge to my R df to have the formats in a new column:
print(have)
varX
1
2
3
1

print(format.file)
formatIndex  group
    1        Smoker
    2        Non-Smoker
    3        Occasional Smoker
    11       Female
    12       Male
    13       Unknown

df.format <- merge(have, format.file, by.x = "varX", by.y = "formatIndex")

print(df.format)
varX    group
  1     Smoker
  2     Non-Smoker
  3     Occasional Smoker
  1     Smoker

The issue with a join approach is I often want to apply the same formats for many columns (i.e. varX, varY, and varZ all use different formatIndex). Is there a similar method of applying formats to variables as SAS has?

A: You could use plyr::mapvalues within the across verb.
Example:
df <- data.frame(V1 = c(1,2,3,4),
                 V2 = c(2,3,1,3))

  V1 V2
1  1  2
2  2  3
3  3  1
4  4  3

liste_format <- data.frame(ID = c(1,2,3,4),
                           group = c("Smoker","Non-Smoker","Occasional Somker","Unknown"))

  ID             group
1  1            Smoker
2  2        Non-Smoker
3  3 Occasional Somker
4  4           Unknown

  library(dplyr)
df |>
  mutate(across(V1:V2,
                ~ plyr::mapvalues(.,
                                  from = liste_format$ID,
                                  to = liste_format$group,
                                  warn_missing = F),
                .names = "format_{.col}"))

  V1 V2         format_V1         format_V2
1  1  2            Smoker        Non-Smoker
2  2  3        Non-Smoker Occasional Somker
3  3  1 Occasional Somker            Smoker
4  4  3           Unknown Occasional Somker


text:
Q: How do you make a minecart move? I'm getting confused on how to make the minecart move. What do I need to do?

A: "An external impulse may be needed to make the minecart start moving. The player can slowly move the minecart forwards while riding it, by pressing forward."
http://minecraft.gamepedia.com/Minecart
You need to make a rail track made up of any type of rail.
When you are inside the minecart, you can press the forward button to move. You can also use the powered rail as the tracks, so that when you give it a redstone signal(Say a redstone torch beside it) it will go forward.

A: You should use a Powered Rail. By placing a redstone torch (or any source of redstone power) next to the rail, it will propel carts forward.


text:
Q: How to add bordered data labels to R plotly bar chart? I am using R and have added data labels to a bar chart using plotly's add_text() function. However, I am wondering how I could add data labels to a filled & bordered rectangle to make them easier to see. I wasn't sure if I could do this using add_annotations(). I was hoping to render something like the data labels on this chart:

Here is an example of my current code:
my_tibble <- tibble(mins = runif(10,10,30),
                    week = 1:10,
                    exercise = c("a", "b", "b", "b", "a", "a", "b", "b", "b", "a"),
                    weight = runif(10,150,160))

plot_ly(data = my_tibble, hoverinfo = "none") %>%

  add_trace(
    type = 'bar',
    x = ~week,
    y = ~mins,
    color = ~exercise,
    hovertext = ~weight,
    hovertemplate = paste('<b>Week</b>: %{x}', "%{hovertext}", '<extra></extra>')
  ) %>%

  add_trace(
    type = 'bar',
    x = ~week,
    y = ~mins
  ) %>%

  layout(
    barmode = 'stack'
  )%>%

  add_text(
    x = ~week,
    y = 8,
    text = "label",
    showlegend = F
  )

A: The only way I know of is to add the text as annotations, instead of a trace.
I added this to the code you have without changing anything you wrote:
  layout(annotations = list(x = ~week, y = 8, showarrow = F,
                           bgcolor = "white", text = "label"))


text:
Q: Please upgrade your Stripe CLI to the latest version to use this feature I am getting this error when I start up VS Code.

Please upgrade your Stripe CLI to the latest version to use this feature.

How do I upgrade the Stripe CLI to the latest?

A: brew upgrade stripe/stripe-cli/stripe


text:
Q: Makumba - select first value in a subset I'm trying to select the latest activity organised by an LBG for all LBGs.
currently my code looks like this:
  <mak:list from="r2.lbgs l" orderBy="l.lbg.name" where="l.toDate = nil and l.lbg.status = 2">

      <mak:value expr="l.lbg.name" />

      <mak:list from="best.johnny.Activity a" where="a.lbg = l.lbg" orderBy="a.end desc">
        <c:if test="${mak:count()==1}">
          <mak:value expr="a.season.name" />
        </c:if>
      </mak:list>

      <mak:list from="best.johnny.Activity a" where="a.lbg = l.lbg and a.isLearningEventStamped = 0" orderBy="a.end desc">
        <c:if test="${mak:count()==1}">
          <mak:value expr="a.season.name" />
        </c:if>
      </mak:list>

  </mak:list>

I wanted to ask if makumba is "clever" enough and retrieves only the first entry, or if the whole set get enumerated. First case would be awesome, otherwise is there any more sufficient way of doing this? - I couldn't find anything.
Thanks
Peter

A: Unfortunately this is, for now, the only way since you have a nested list. As it says in the documentation there is a limit attribute, but it only works for the first list.


text:
Q: Profile a gulp build with spy-js From one of the comment in the webstorm blog article, it says one can debug a grunt program by creating a script file and invoke with grunt. I have a gulp setup I like to profile. So, I created a script file with
var gulp = require('gulp');
require('./gulpfile');
gulp.start.apply(gulp, ['default'])

when I run this with a spy-js run session, it executes and ton of trace info. The traced application window shows it ran correctly as I could see the logs. But, I cannot find any of my methods in trace run window. Where should I look for say, a function called from my gulpfile.js? I tried quick search by clicking on middle window and start typing. But I cannot find any of my method.
Another qn, how to go to the next hit in the quick search window. As in the attached image, it hit one result, but I want to go to the next. How?

A: The best way would be to use capture exclusions to get rid of the noise from the files you're not interested in.

On the screenshot above, single file filter is applied (meaning that nothing but this file will be captured), so after applying such filter and restarting the session you will only see the code from gulpfile.js. You can use glob patterns to include/exclude files you need. I suspect in your scenario excluding all node modules should be enough. There's a shortcut to create such filter, just right click on the root node inside the events pane and select "Mute node modules":

If you're interested in tracing some of the node modules, you can modify the filter to exclude just those you're not interested in. You can also create filters for individual node modules by locating one of their functions in the stack tree and using "Mute this node module" context action.


text:
Q: Database Query to generate a Time-based Chart I have a logins table in the following (simplified) structure:
id | login_time
---------
1  | 2019-02-04 18:14:30.026361+00
2  | 2019-02-04 22:10:19.720065+00
3  | 2019-02-06 15:51:53.799014+00

Now I want to generate chart like this:
https://prnt.sc/mifz6y
Basically I want to show the logins within the past 48 hours.
My current query:
SELECT count(*), date_trunc('hour', login_time) as time_trunced FROM user_logins
WHERE login_time > now() - interval '48' hour
GROUP BY time_trunced
ORDER BY time_trunced DESC

This works as long as there are entries for every hour. However, if in some hour there were no logins, there will be no entry selected, like this:
time_trunced | count
---------------------
12:00        | 1
13:00        | 2
15:00        | 3
16:00        | 5

I would need a continous query, so that I can simply put the count values into an array:
time_trunced | count
---------------------
12:00        | 1
13:00        | 2
14:00        | 0 <-- This is missing
15:00        | 3
16:00        | 5

Based on that I can simply transform the query result into an array like [1, 2, 0, 3, 5] and pass that to my frontend.
Is this possible with postgresql? Or do I need to implement my own logic?

A: I think I would do:
select gs.h, count(ul.login_time)
from generate_series(
   date_trunc('hour', now() - interval '48 hour'),
   date_trunc('hour', now()),
   interval '1 hour'
) gs(h) left join
     user_logins ul
     on ul.login_time >= gs.h and
        ul.login_time < gs.h + interval '1 hour'
group by gs.h
order by gs.h;

A: This can almost certainly be tidied up a bit but should give you some ides. Props to clamp for the generate_series() tip :
SELECT t.time_trunced,coalesce(l.login_count,0) as logins
FROM
(
 -- Generate an inline view with all hours between the min & max values in user_logins table
 SELECT date_trunc('hour',a.min_time)+ interval '1h' * b.hr_offset as time_trunced
 FROM (select min(login_time) as min_time from user_logins) a
 JOIN (select generate_series(0,(select ceil((EXTRACT(EPOCH FROM max(login_time))-EXTRACT(EPOCH FROM min(login_time)))/3600) from user_logins)::int) as hr_offset) b on true
) t
LEFT JOIN
 (
 -- OP's original query tweaked a bit
 SELECT count(*) as login_count, date_trunc('hour', login_time) as time_trunced
 FROM user_logins
 GROUP BY time_trunced
) l on t.time_trunced=l.time_trunced
order BY 1 desc;


text:
Q: How can one implement Google-signin and CSP rejection of inline stylesheets? I'm trying to enable the Content-Security-Policy header on my website. I have the following header set:
Content-Security-Policy:default-src 'self'; script-src 'self' https://apis.google.com/; font-src 'self' https://fonts.gstatic.com/; style-src 'self' https://fonts.googleapis.com/ 'sha256-W/8NeLkjrtPkUUfkFDNutwiyHLsvDJAxC+dO5tQP/90='; child-src 'self' https://accounts.google.com/

This works great in Firefox. That hash in the style-src section matches the inline styles that Google-signin uses. The problem is, per Chromium Bug 546106, the hash is ignored because it's on a style, rather then a script. Worse still, from the comments Chrome/Chromium developers believe this is correct behavior, and is intended (that said, they haven't set it to "WONTFIX" yet).
I really don't want to enable 'unsafe-inline' if I don't have to.
Is there a way with Google-Signin to tell it not to use inline styling? Is there another way?


text:
Q: bootgrid jquery select row I'm using Bootgrid jquery in my asp.net mvc , and i'm trying to make row selectable  , i tried what i found on the net but it still not working , it shows up without the selection feature

            Nom du Produit
             Type du Produit

            Dernière version


text:
Q: Wrong mutt smtp server from Motion I'm using Motion to manage a camera and it works perfectly.
I've configured mutt so it can send emails when an event occur on the camera.
When I send an email via mutt by myself it works every times.
But when it's motion that send the email, the "from:" field is not good and it doesn't send the email. Do you know why ? I've configured my ~/.muttrc file and it works when I do it without motion.
my ~/.muttrc :
# Name of expeditor
set realname = "Camera"

# Activate TLS if available on the server
set ssl_starttls=yes

# Always use SSL for connection to the server
set ssl_force_tls=yes

# Configuration of imap (Only if you want to be able to read emails on the Pi)
#set spoolfile=imaps://imap.gmail.com:993/
#set imap_user = "XXXXXXXX@gmail.com"
#set imap_pass = "PASSWORD"

# Configuration SMTP
set smtp_url = "smtp://[MY_EMAIL]@smtp.gmail.com:587/"
set smtp_pass = "[MY_PASSWD]"
set from = "[MY_EMAIL]"
set use_envelope_from=yes

# Local info, date
#set locale="fr_FR"
set date_format="%A %d %b %Y à %H:%M:%S (%Z)"
#set locale="iso-8859-15"

Normal "sent" file (when I do it without Motion) :
From john.smith@gmail.com Wed May  2 07:28:59 2018
Date: Wed, 2 May 2018 07:28:59 +0000
From: =?iso-8859-1?Q?Camera <john.smith@gmail.com>
To: john.smith@gmail.com
Subject: Test
Message-ID: <20180502072859.qhqyhfwcs5nw7quj@RPi>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
User-Agent: NeoMutt/20170113 (1.7.2)
Status: RO
Content-Length: 2
Lines: 1

Wrong "sent" file (when I do it with Motion) :
From motion@RPi Wed May  2 07:17:07 2018
Date: Wed, 2 May 2018 07:17:07 +0000
From: motion@RPi
To: john.smith@gmail.com
Subject: Picture
Message-ID: <20180502071707.nx7asct4m2hds6vt@RPi>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
User-Agent: NeoMutt/20170113 (1.7.2)
Status: RO
Content-Length: 39
Lines: 1

Can you help me ?
Thank you very much
A.