text:
Q: AMP HTML Page not valide Hi I'm trying to integrate my page for amp https://www.ampproject.org/.
I have taken the exemple in the documentation and copy paste it in my page.
<!doctype html>

    <meta charset="utf-8">

    <title>Hello, AMPs</title>
    <link rel="canonical" href="http://example.ampproject.org/article-metadata.html" />
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

Welcome to the mobile web

I'm trying to check if my page is recognize as an amp valide page.
So I have created a new route and put the argument to have the debug validation in my chrome console.
But I have this errors:

Powered by AMP ⚡ HTML – Version 1491601970987
  http://local.dev/amp/actualites/test#development=1
validator.js:380 AMP validation had errors:
validator.js:380 http://local.dev/amp/actualites/test:28:0 The inline
  'style' attribute is not allowed in AMP documents. Use 'style
  amp-custom' tag instead. (see
  https://www.ampproject.org/docs/guides/responsive/style_pages)
validator.js:380 http://local.dev/amp/actualites/test:28:69 The tag
  'script' is disallowed except in specific forms.
validator.js:380 http://local.dev/amp/actualites/test:28:19029 The tag
  'script' is disallowed except in specific forms.

It seems like the page is not amp valide. But I don't understand, I just took the exemple documentation!!!
What did I do wrong?
https://www.ampproject.org/docs/guides/debug/validate

A: Found it. I'm using symfony which is a php framework.
In dev mode the framework inject in the DOM a debug toolbar which content html, js, etc... Because of that AMP is not valid.
To resole the problem you can disable the toolbar in the config_dev.yml file or run the site in prod mode with app.php
web_profiler:
    toolbar: true


text:
Q: Laravel Eloquent no primary key I would like to update an old table that have a composite primary key. In order to generate a full update query such as:
UPDATE foos SET (...) WHERE pk1 = ? AND pk2 = ?;

Instead Eloquent tries to do the following which does massive update:
UPDATE foos SET (...) WHERE pk1 = ?;

I set the primary key attribute to null as seen on Google:
class Foo extends Model {
    protected $guarded = [];
    protected $primaryKey = null;
    public $incrementing = false;
    public $timestamps = false;
}

But I get this error:
Illuminate\Database\QueryException: SQLSTATE[42S22]:
Column not found: 1054 Unknown column '' in 'where clause'
(SQL: update `previews` set `preview_id` = 1805 where `` is null) in
./vendor/illuminate/database/Connection.php on line 664

I suppose this is not a supported feature of Eloquent, so how can I generate my update query?
My update query was:
    $p = Foo
        ::where('pk1', $foo)
        ->where('pk2', $bar)
        ->first();

    $p->update('column', 42);

A: Don't fetch the model, update it directly in the database:
Foo::where('pk1', $foo)
    ->where('pk2', $bar)
    ->update(['column' => 42]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to detect fast moving soccer ball with OpenCV, Python, and Raspberry Pi? This is the code. I am trying to detect different types of soccer ball using OpenCV and python. Soccer ball could of different colors. I can detect the ball if it is not moving. But, the code does not work if the ball is moving fast.
from picamera.array import PiRGBArray
from picamera import PiCamerafrom picamera.array import PiRGBArray
from picamera import PiCamera
import time, cv2, sys, imutils, cv
import cv2.cv as cv

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (400, 300)
camera.framerate = 30
rawCapture = PiRGBArray(camera, size=(400, 300))

for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    image = frame.array
    img   = cv2.medianBlur(image, 3)
    imgg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #imgg  = cv2.blur(imgg, (3,3))
                #imgg = cv2.dilate(imgg, np.ones((5, 5)))
                #imgg = cv2.GaussianBlur(imgg,(5,5),0)
    circles = cv2.HoughCircles(imgg, cv.CV_HOUGH_GRADIENT, 1, 20, param1=100, param2=40, minRadius=5, maxRadius=90)

    cv2.imshow("Frame", imgg)

    # clear the stream in preparation for the next frame
    rawCapture.truncate(0)

    key = cv2.waitKey(1) & 0xFF
    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break

    if circles is None:
        continue

    for i in circles[0,:]:
        cv2.circle(imgg,(i[0],i[1]),i[2],(0,255,0),1) # draw the outer circle
        cv2.circle(imgg,(i[0],i[1]),2,(0,0,255),3) # draw the center of the circle
        cv2.imshow("Framed", imgg)


text:
Q: populating select list with common column names b/w two tabels via subquery -oracle My code is clear enough to describe what i am trying to achieve

 SELECT  (select column_name from user_tab_cols where table_name='tbl1'
    intersect
    select column_name from user_tab_cols where table_name='tbl2')

    FROM   tbl2;

It is throwing ORA-01427: single-row subquery returns more than one row
I understand this error but don't know the alternate solution to achieve my goal .

A: You don't need the subquery here. Try this instead:
SELECT column_name FROM user_tab_cols WHERE table_name = 'tbl1'
INTERSECT SELECT column_name FROM user_tab_cols WHERE table_name = 'tbl2'

This will return a list of column names that exist in both tbl1 and tbl2.


text:
Q: T-SQL - Insert Data into Parent and Child Tables Code:
CREATE TYPE dbo.tEmployeeData AS TABLE
(
     FirstName NVARCHAR(50),
     LastName NVARCHAR(50),
     DepartmentType NVARCHAR(10),
     DepartmentBuilding NVARCHAR(50),
     DepartmentEmployeeLevel NVARCHAR(10),
     DepartmentTypeAMetadata NVARCHAR(100),
     DepartmentTypeBMetadata NVARCHAR(100)
)
GO

CREATE PROC dbo.EmployeeImport
    (@tEmployeeData tEmployeeData READONLY)
AS
BEGIN
     DECLARE @MainEmployee TABLE
                           (EmployeeID INT IDENTITY(1,1),
                            FirstName NVARCHAR(50),
                            LastName NVARCHAR(50))

    DECLARE @ParentEmployeeDepartment TABLE
                                      (EmployeeID INT,
                                       ParentEmployeeDepartmentID INT IDENTITY(1,1),
                                       DepartmentType NVARCHAR(10))

    DECLARE @ChildEmployeeDepartmentTypeA TABLE
                  (ParentEmployeeDepartmentID INT,
                   DepartmentBuilding NVARCHAR(50),
                   DepartmentEmployeeLevel NVARCHAR(10),
                   DepartmentTypeAMetadata NVARCHAR(100))

    DECLARE @ChildEmployeeDepartmentTypeB TABLE
                  (ParentEmployeeDepartmentID INT,
                   DepartmentBuilding NVARCHAR(50),
                   DepartmentEmployeeLevel NVARCHAR(10),
                   DepartmentTypeBMetadata NVARCHAR(100))

    -- INSERT CODE GOES HERE
    SELECT * FROM @MainEmployee
    SELECT * FROM @ParentEmployeeDepartment
    SELECT * FROM @ChildEmployeeDepartmentTypeA
    SELECT * FROM @ChildEmployeeDepartmentTypeB
END
GO

DECLARE @tEmployeeData tEmployeeData

INSERT INTO @tEmployeeData (FirstName, LastName, DepartmentType,
                            DepartmentBuilding, DepartmentEmployeeLevel,
                            DepartmentTypeAMetadata, DepartmentTypeBMetadata)
    SELECT
        N'Tom_FN', N'Tom_LN', N'A',
        N'101', N'IV', N'Tech/IT', NULL
    UNION
    SELECT
        N'Mike_FN', N'Mike_LN', N'B',
        N'OpenH', N'XII', NULL, N'Med'
    UNION
    SELECT
        N'Joe_FN', N'Joe_LN', N'A',
        N'101', N'IV', N'Tech/IT', NULL
    UNION
    SELECT
        N'Dave_FN', N'Dave_LN', N'B',
        N'OpenC', N'XII', NULL, N'Lab'

    EXEC EmployeeImport @tEmployeeData
GO

DROP PROC dbo.EmployeeImport
DROP TYPE dbo.tEmployeeData

Notes:

*

*The table variables are replaced by real tables in live environment.

*EmployeeID and ParentEmployeeDepartmentID columns' values don't always match each other. Live environment has more records in the udt (tEmployeeData) than just 4
Goal:

*

*The udt (tEmployeeData) will be passed into the procedure

*The procedure should first insert the data into the @MainEmployee table (and get the EmployeeIDs)

*Next, the procedure should insert the data into the @ParentEmployeeDepartment table (and get the ParentEmployeeDepartmentID) - note EmployeeID is coming from the previous output.

*Then, the procedure should split the child level data based on the DepartmentType ("A" = insert into @ChildEmployeeDepartmentTypeA and "B" = insert into @ChildEmployeeDepartmentTypeB).

*ParentEmployeeDepartmentID from @ParentEmployeeDepartment should be used when inserting data into either @ChildEmployeeDepartmentTypeA or @ChildEmployeeDepartmentTypeB

*The procedure should should run fast (need to avoid row by row operation)
Output:
@MainEmployee:
EmployeeID  FirstName   LastName
---------------------------------
1           Tom_FN      Tom_LN
2           Mike_FN     Mike_LN
3           Joe_FN      Joe_LN
4           Dave_FN     Dave_LN

@ParentEmployeeDepartment:
EmployeeID  ParentEmployeeDepartmentID  DepartmentType
-------------------------------------------------------
1           1                           A
2           2                           B
3           3                           A
4           4                           B

@ChildEmployeeDepartmentTypeA:
ParentEmployeeDepartmentID  DepartmentBuilding  DepartmentEmployeeLevel DepartmentTypeAMetadata
---------------------------------------------------------------------------------------------------------
1                           101                 IV                      Tech/IT
3                           101                 IV                      Tech/IT

@ChildEmployeeDepartmentTypeB:
ParentEmployeeDepartmentID  DepartmentBuilding  DepartmentEmployeeLevel DepartmentTypeAMetadata
----------------------------------------------------------------------------------------------------------
2                           OpenH               XII                     Med
4                           OpenC               XII                     Lab

I know I can use the OUTPUT clause after the insert and get EmployeeID and ParentEmployeeDepartmentID, but I'm not sure how to insert the right child records into right tables with right mapping to the parent table. Any help would be appreciated.

A: Here is my solution (based on the same answer I've linked to in the comments):
First, you must add another column to your UDT, to hold a temporary ID for the employee:
CREATE TYPE dbo.tEmployeeData AS TABLE
(
     FirstName NVARCHAR(50),
     LastName NVARCHAR(50),
     DepartmentType NVARCHAR(10),
     DepartmentBuilding NVARCHAR(50),
     DepartmentEmployeeLevel NVARCHAR(10),
     DepartmentTypeAMetadata NVARCHAR(100),
     DepartmentTypeBMetadata NVARCHAR(100),
     EmployeeId int
)
GO

Populating it with that new employeeId column:
DECLARE @tEmployeeData tEmployeeData

INSERT INTO @tEmployeeData (FirstName, LastName, DepartmentType,
                            DepartmentBuilding, DepartmentEmployeeLevel,
                            DepartmentTypeAMetadata, DepartmentTypeBMetadata, EmployeeId)
SELECT
    N'Tom_FN', N'Tom_LN', N'A',
    N'101', N'IV', N'Tech/IT', NULL, 5
UNION
SELECT
    N'Mike_FN', N'Mike_LN', N'B',
    N'OpenH', N'XII', NULL, N'Med', 6
UNION
SELECT
    N'Joe_FN', N'Joe_LN', N'A',
    N'101', N'IV', N'Tech/IT', NULL, 7
UNION
SELECT
    N'Dave_FN', N'Dave_LN', N'B',
    N'OpenC', N'XII', NULL, N'Lab', 8

Insert part goes here
Then, you use a table variable to map the inserted value from the employee table to the temp employee id in the data you sent to the procedure:
DECLARE @EmployeeidMap TABLE
(
    temp_id int,
    id int
)

Now, the trick is to populate the employee table with the MERGE statement instead of an INSERT...SELECT because you have to use values from both inserted and source data in the output clause:
MERGE INTO @MainEmployee USING @tEmployeeData AS sourceData ON 1 = 0 -- Always not matched
WHEN NOT MATCHED THEN
INSERT (FirstName, LastName)
VALUES (sourceData.FirstName, sourceData.LastName)
OUTPUT sourceData.EmployeeId, inserted.EmployeeID
INTO @EmployeeidMap (temp_id, id); -- populate the map table

From that point on it's simple, you need to join the data you sent to the @EmployeeidMap to get the actual employeeId:
INSERT INTO @ParentEmployeeDepartment (EmployeeID, DepartmentType)
SELECT Id, DepartmentType
FROM @tEmployeeData
INNER JOIN @EmployeeidMap ON EmployeeID = temp_id

Now you can use the data in @ParentEmployeeDepartment to map the actual values in ParentEmployeeDepartmentID to the data you sent:
Testing the inserts so far
SELECT FirstName,
     LastName,
     SentData.DepartmentType As [Dept. Type],
     DepartmentBuilding As Building,
     DepartmentEmployeeLevel As [Emp. Level],
     DepartmentTypeAMetadata As [A Meta],
     DepartmentTypeBMetadata As [B Meta],
     SentData.EmployeeId As TempId, EmpMap.id As [Emp. Id], DeptMap.ParentEmployeeDepartmentID As [Dept. Id]
FROM @tEmployeeData SentData
INNER JOIN @EmployeeidMap EmpMap ON SentData.EmployeeId = temp_id
INNER JOIN @ParentEmployeeDepartment DeptMap ON EmpMap.id = DeptMap.EmployeeID

results:
FirstName   LastName    Dept. Type  Building    Emp. Level  A Meta      B Meta  TempId      Emp. Id     Dept. Id
---------   --------    ----------  --------    ----------  ------      ------  ------      ----------- -----------
Dave_FN     Dave_LN     B           OpenC       XII         NULL        Lab     8           1           1
Joe_FN      Joe_LN      A           101         IV          Tech/IT     NULL    7           2           2
Mike_FN     Mike_LN     B           OpenH       XII         NULL        Med     6           3           3
Tom_FN      Tom_LN      A           101         IV          Tech/IT     NULL    5           4           4

I'm sure that from this point you can easily figure out the last 2 inserts yourself.


text:
Q: automatic insert of object on new page How can I have an object in the same spot of every page on a word document?
Almost like a header, but instead, I'd like to insert it and have it automatically appear in the middle of the page, that way when I fill a page, and move to the next, it's already there. Is there a way to do this?
I want to insert a vertical ruler, and a heading reading "notes" on the right side of every page to be used as a notes section of my document.
If I type, I don't want the font to go beyond the vertical ruler.

A: I think what you're actually asking for is to use Page Columns. This will allow you to split the content of your page into separate columns, one for the main content and the other for notes.

*

*Choose Page Layout from the menu

*Select the Columns drop down

*Choose More Columns
You will want to select options like below to get the desired layout. Equal column width must be unchecked in order to get columns of different sizes.

Note there are a few things you need to know to use columns correctly.

*

*When the content of your first column of a page is complete to move
to the second column you need to use Page Layout -> Insert Breaks
-> Column. Then you can start writing in the notes column.

*Once the notes column for the page is complete to move to the next
page you need to insert another column break as before or a page
break.

A: Insert a watermark for every page

A: Could be fiddly (depending on how often you're doing this) but, maybe having a background image, and on top of that a Text Box?


text:
Q: iOS - UITableViewCell, UIAlertController Good day to all. Faced a problem. I need to make a table with a button and by clicking on the button I get a alert with the number of the cell. The table cells themselves are not active. That's how I realized it. When I scroll the table in the beginning everything is fine, when you press the button, a alert is displayed with the correct line number, but  after 4 elements an error appears.
This error appears in the line where I'm working with the 4 tag.
Fatal error: unexpectedly found nil while unwrapping an Optional value
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as UITableViewCell

    if (tableView.tag == 1) {
        let numLabel: UILabel = tableView.viewWithTag(3) as! UILabel
        numLabel.text = String(indexPath.row)
    } else if (tableView.tag == 2) {

        //Error appears here
        let numButton: UIButton = tableView.viewWithTag(4) as! UIButton
        numButton.setTitle(String(indexPath.row), for: .normal)

        numButton.tag = indexPath.row
    }

    return cell
}

@IBAction func showAlertForRow(row: UIButton) {
    let alert = UIAlertController(title:"Test work",message:"Cell at row \(row.tag) was tapped!",preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

A: What you are designing for implementing this procedure is not correct. What you can do

*

*Make a custom cell

*Add a button in custom cell

*Add action in that button in CellForRowAtIndexPath

*Handle action from ViewController where you added tableView.

I made a whole project for you.Just to let you know. if you want to add customCell in tableView you need to register it like this in viewDidLoad.
i have done is in ViewController.swift file. check out my project.
let nib = UINib.init(nibName:String(describing: sampleTableViewCell.self) , bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "chatCell")

Then check cellForRowAtIndexPath function:
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "chatCell", for: indexPath) as! sampleTableViewCell

    cell.clickMeBtn.tag = indexPath.row
    cell.clickMeBtn.addTarget(self, action: #selector(onButtonPressed(sender :)), for: .touchUpInside)
    return cell

}

Button press function:
func onButtonPressed(sender:UIButton) {
    let alert = UIAlertController.init(title:"Cell index is"+String(sender.tag), message: nil, preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction.init(title: "ok", style: UIAlertActionStyle.default) { (UIAlertAction) in

    }

    alert.addAction(okAction)
    self.present(alert, animated: true, completion: nil)

}

Check only three files:
Github link

*

*ViewController.swift

*sampleTableViewCell.swift

*sampleTableViewCell.xib**
Here is the output:


text:
Q: Is there a closed form of $\sum_{k=1}^{n} \frac{|S_{1}(n,k)|}{k!}z^{k} $? So far, I have found (p. 5) the following generating functions of the unsigned Stirling numbers of the first kind:
$$ \sum_{l=1}^{n} |S_{1}(n,l)|z^{l} = (z)_{n} = \prod_{k=0}^{n-1} (z+k) , $$ and $$ \sum_{n=l}^{\infty} \frac{|S_{1}(n,l)|}{n!}z^{n} = (-1)^{l} \frac{\ln^{l}(1-z)}{l!} .$$
Instead of summing the latter expression over $n$, I'm curious whether there is a closed form of the generating sum when summed over the other indices:
$$ f(z) := \sum_{k=1}^{n} \frac{|S_{1}(n,k)|}{k!}z^{k} .$$ One could also take the sum from $k=1$ to $k=\infty$, as $|S_{1}(n,k)| = 0$ when $k>n$.

Question: is there a closed form or succinct formula for $f(\cdot)$ ?

Both derivations and references would be much appreciated.


text:
Q: How can I push a small change to heroku from my rails app without it taking 4 minutes? Every time I push to heroku, it is running bundle install and it takes me about 4 minutes. This is a small app that is not live yet. What if I only want to push a single change where I add one character to a view file? Is there anyway that I can tell heroku, here change this file and do it quickly without having to wait 4 minutes to run bundle install and everything else it does?

A: You have to wait till Heroku auto deploy your project.
There is no way to tell heroku for minor changes, Its auto deployment process done by heroku so it will follow all steps like migration,bundle,pre -compilation.
And I think it's good for us.


text:
Q: Laravel Queue Jobs are automatically processing without any queue:work or listen command I am queuing jobs to run after 1 minute from my controller and jobs appear in "jobs" table correctly, but as per doc I have to run php artisan queue:work to get jobs executed but in my case they are being executed without any command on Ubuntu server (AWS ec2). Also such jobs go to failed jobs table as they are reading some old code of controller which I changed earlier.
Note: If I run php artisan queue:work, then some of the jobs are processed by this and get executed with new code without generating any error while some of the jobs are executed by that unknown background process and generates old code error

Result of php arisan list
"root@ip-172-31-30-76:/var/www/html# php artisan list
Laravel Framework 5.5.32

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
      --env[=ENV]       The environment the command should run under
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  clear-compiled              Remove the compiled class file
  down                        Put the application into maintenance mode
  env                         Display the current framework environment
  help                        Displays help for a command
  list                        Lists commands
  migrate                     Run the database migrations
  optimize                    Optimize the framework for better performance (deprecated)
  preset                      Swap the front-end scaffolding for the application
  serve                       Serve the application on the PHP development server
  tinker                      Interact with your application
  up                          Bring the application out of maintenance mode
 app
  app:name                    Set the application namespace
 auth
  auth:clear-resets           Flush expired password reset tokens
 cache
  cache:clear                 Flush the application cache
  cache:forget                Remove an item from the cache
  cache:table                 Create a migration for the cache database table
 config
  config:cache                Create a cache file for faster configuration loading
  config:clear                Remove the configuration cache file
 customSolutions
  customSolutions:sportsplus  This command is for executing custom solutions
 datatables
  datatables:make             Create a new DataTable service class.
  datatables:scope            Create a new DataTable Scope class.
 db
  db:seed                     Seed the database with records
 entrust
  entrust:migration           Creates a migration following the Entrust specifications.
 event
  event:generate              Generate the missing events and listeners based on registration
 import
  import:SyncOrders           This imports orders from different channels
 key
  key:generate                Set the application key
 make
  make:auth                   Scaffold basic login and registration views and routes
  make:command                Create a new Artisan command
  make:controller             Create a new controller class
  make:event                  Create a new event class
  make:exception              Create a new custom exception class
  make:factory                Create a new model factory
  make:job                    Create a new job class
  make:listener               Create a new event listener class
  make:mail                   Create a new email class
  make:middleware             Create a new middleware class
  make:migration              Create a new migration file
  make:model                  Create a new Eloquent model class
  make:notification           Create a new notification class
  make:policy                 Create a new policy class
  make:provider               Create a new service provider class
  make:request                Create a new form request class
  make:resource               Create a new resource
  make:rule                   Create a new validation rule
  make:seeder                 Create a new seeder class
  make:test                   Create a new test class
 migrate
  migrate:fresh               Drop all tables and re-run all migrations
  migrate:install             Create the migration repository
  migrate:refresh             Reset and re-run all migrations
  migrate:reset               Rollback all database migrations
  migrate:rollback            Rollback the last database migration
  migrate:status              Show the status of each migration
 notifications
  notifications:table         Create a migration for the notifications table
 package
  package:discover            Rebuild the cached package manifest
 queue
  queue:failed                List all of the failed queue jobs
  queue:failed-table          Create a migration for the failed queue jobs database table
  queue:flush                 Flush all of the failed queue jobs
  queue:forget                Delete a failed queue job
  queue:listen                Listen to a given queue
  queue:restart               Restart queue worker daemons after their current job
  queue:retry                 Retry a failed queue job
  queue:table                 Create a migration for the queue jobs database table
  queue:work                  Start processing jobs on the queue as a daemon
 route
  route:cache                 Create a route cache file for faster route registration
  route:clear                 Remove the route cache file
  route:list                  List all registered routes
 schedule
  schedule:run                Run the scheduled commands
 session
  session:table               Create a migration for the session database table
 storage
  storage:link                Create a symbolic link from "public/storage" to "storage/app/public"
 vendor
  vendor:publish              Publish any publishable assets from vendor packages
 view
  view:clear                  Clear all compiled view files
"
Result of cront -l

* * * * * php /var/www/html/artisan schedule:run >> /var/www/html/logs.txt 2>&1

A: This can happen if your queue connection is still set to the default (sync). If you're using Laravel 5.7 or above, check your .env file and ensure that you have the following:
QUEUE_CONNECTION=database

Note that in Laravel 5.7, QUEUE_DRIVER was changed to QUEUE_CONNECTION: https://laravel.com/docs/5.7/upgrade

A: I had the same issue, i fixed it by restarting Redis.

Commands for help.

sudo systemctl stop redis

sudo systemctl start redis


text:
Q: Getting error 80073cf9 for specific Windows Store App after Rollback I upgraded to windows 8 about a month ago, and quickly downloaded a certain app (jetpack joyride) and enjoyed it a bit, but my system sadly had an issue that could only be fixed with a rollback. This was to the point before installing that app. The icon stays in start, I can click uninstall (but it remains), and whenever I try to install it from the store, I get error 80073cf9. Does anyone know what the issue could be?
I did a search through the registry, found three keys (which I deleted) and this let me install it from the store, but when I tried to play it, it redirects me to the app on Windows Store.
I have also looked in C:\Program Files\MicrosoftApps, but there was no reference to the app.

A: To troubleshoot the problem you can do the following.
Method 1:
Download and run the Modern UI App troubleshooter and check output.
Method 2
Run System File Checker (SFC) tool scan to verify the system and see if the issue persists.
To run System File Checker scan:

*

*Press Windows + X key and click Command Prompt (Admin).

*Type the command: sfc /scannow and press Enter.

*Restart the computer and
check.

A: I had this problem with the Skype app. Ran the "wsreset" utility (typed "wsreset"  into the search charm to run) and started the Skype install again, and it worked.

A: *

*Go to c:\Windows

*Create new folder with the name: AppReadiness

*Delete the folder with the name: AInstallAgent if this folder exist.

Then the apps will be download. This worked for me at least.


text:
Q: Why is the eBay FixedPriceTransaction notification going to the buyer when it is a notification for the seller only? I had recenlty setup the FixedPriceTransaction notification for a client which would send the order related details to the client website in the event of an order on eBay. This has worked fine.
Recently the client logged into his eBay account and bought an item from another seller on eBay and for some reason beyond my understanding the website received the notification for this transaction as well.
My understanding is that the FixedPriceTransaction notification is only sent to the seller when some one buys an item from them on eBay so this should not be sent in the case I have mentioned above.
Can any one point out why the above is happening?

A: It goes to both. You have to check whether the recipient user ID matches the seller's user ID in order to verify whether you should import that data into your selling application.


text:
Q: Magento2 - How can possible Reorder Product wise? I need All order Product Items in User My account section.

How I can get All order items with selected options.

A: This can help you out
Create a custom block and add this code :
<?php
namespace Company\Slider\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
    protected $_orderModel;
    protected $_orderCollectionFactory;
    protected $orders;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Sales\Model\Order $orderModel,
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
        array $data = []
        )
        {
            $this->_orderModel = $orderModel;
            $this->_orderCollectionFactory = $orderCollectionFactory;
            parent::__construct($context, $data);
        }

        public function getOrderItems($orderId)
        {
            $order = $this->_orderModel->load($orderId);
            return $order->getAllVisibleItems();
        }

    public function getUserId()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSession = $objectManager->create('Magento\Customer\Model\Session');
        if($customerSession->isLoggedIn()) {
            return $customerSession->getCustomer()->getId();
        }
    }

    public function getOrders($customerId)
    {

        if (!$this->orders) {
        $this->orders = $this->_orderCollectionFactory->create()->addFieldToSelect('*')->addFieldToFilter('customer_id',$customerId)->setOrder('created_at','desc');
        }
        return $this->orders;
    }
}

Create a template file and put code in it
<?php
$customerID = $block->getUserId();
$orderCollection = $block->getOrders($customerID);
foreach($orderCollection as $order){
    $items = $block->getOrderItems($order->getId());
    foreach ($items as $item) {
        $options = $item->getProductOptions();

        if (isset($options['options']) && !empty($options['options'])) {
        foreach ($options['options'] as $option) {
            echo 'Title: ' . $option['label'] . '
';
            echo 'ID: ' . $option['option_id'] . '
';
            echo 'Type: ' . $option['option_type'] . '
';
            echo 'Value: ' . $option['option_value'] . '
' . '
';
        }
        }
    }
}

This code work for me, hope so works for you too.
For reference check the links
http://blog.chapagain.com.np/magento-2-get-products-custom-option-value-from-cart-order/
http://blog.chapagain.com.np/magento-2-load-product-by-id-and-sku/
Sorry for late replay
Thanks


text:
Q: HTML Form - Prevent Form Submission For Input Using Barcode Scanner that adds Enter (CR) Suffix I have a simple table with 2 text inputs and 2 non input cells and a script that runs when the first input field is modified which queries a database and then updates the other 3 cells in the same row. This works well when manually entering the serial numbers in the first cell/column, but we have now encountered an issue with users in the warehouse using a barcode scanner to scan the serial number barcodes. The scanner is hardcoded to enter a Enter (CR) Suffix after a successful scan, which in turn is submitting the form at the same time.
Ideally we would like to allow the script to run after the barcode has been scanned (similar to when users press tab to exit the input field) as it does a database lookup and adds a new table row, but prevent the form from being submitted as well as the user isn't ready to submit the form when scanning.
Here's my form/table setup:

$(document).ready(function() {
  $("#addRow").click(function() {
    var markup = "
<input type=\"text\" class=\"form-control serialNumber\" autocomplete=\"off\" placeholder=\"Serial Number\" name=\"serialNumber[]\" value=\"\">	<input type=\"text\" class=\"form-control assetID\" autocomplete=\"off\" placeholder=\"Asset ID\" name=\"assetID[]\" value=\"\">
";
    $("#shipmentItems").append(markup);
  });

  // Find and remove selected table rows

  $("#shipmentItems").on("click", ".deleteRow", function() {
    $(this).closest('tr').remove();
  });
});

$(document).ready(function() {
  $(document).on('change', '.form-control.serialNumber', function() {

    var serialNumber = $(this).val();
    //console.log( recid );
    // Create a reference to $(this) here:
    $this = $(this);

    ID = 'ABC123';
    code = 'PC8765';
    description = 'Acme Standard Widget';

    $this.closest('tr').find('.form-control.assetID').val(ID);
    $this.closest('tr').children('.code').html(code);
    $this.closest('tr').children('.description').html(description);

    var markup = "
<input type=\"text\" class=\"form-control serialNumber\" autocomplete=\"off\" placeholder=\"Serial Number\" name=\"serialNumber[]\" value=\"\">	<input type=\"text\" class=\"form-control assetID\" autocomplete=\"off\" placeholder=\"Asset ID\" name=\"assetID[]\" value=\"\">
";
    $("#shipmentItems").append(markup);

  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<form class="form-horizontal" id="createShipments" action="processConsignment.php" method="post" role="form">

      Serial
      ID
      Code
      Description

        <input type="text" class="form-control serialNumber" autocomplete="off" placeholder="Serial Number" name="serialNumber[]" value="">
        <input type="text" class="form-control assetID" autocomplete="off" placeholder="Asset ID" name="assetID[]" value="">

  <button type="button" name="addRow" value="addRow" id="addRow" class="btn btn-primary">Add Asset</button>
  <button type="submit" name="createShipment" value="createShipment" id="save" class="btn btn-success">Create Shipment</button>

</form>

A: CR's key code is 13. So you can disable submitting on keydown event. You can also allow submitting on another combination, such as ctrl+enter.
Also, I improved you append function to auto-focus appended row's first column.

let focusing = false;

function appendRow() {

  var markup = "
<input type=\"text\" class=\"form-control serialNumber\" autocomplete=\"off\" placeholder=\"Serial Number\" name=\"serialNumber[]\" value=\"\">	<input type=\"text\" class=\"form-control assetID\" autocomplete=\"off\" placeholder=\"Asset ID\" name=\"assetID[]\" value=\"\">
";
  $("#shipmentItems").append(markup);
  focusing = true;
  $('#shipmentItems tr:last td:first input').focus();
  focusing = false;
}

function fillOtherFields(serialNumberField) {
  var serialNumber = $(serialNumberField).val();
  $serialNumberField = $(serialNumberField);

  ID = 'ABC123';
  code = 'PC8765';
  description = 'Acme Standard Widget';

  $serialNumberField.closest('tr').find('.form-control.assetID').val(ID);
  $serialNumberField.closest('tr').children('.code').html(code);
  $serialNumberField.closest('tr').children('.description').html(description);
  appendRow();

}

$(document).ready(function() {
  $("#addRow").click(appendRow);

  // Find and remove selected table rows

  $("#shipmentItems").on("click", ".deleteRow", function() {
    $(this).closest('tr').remove();
  });
});

$(document).ready(function() {
  $(document).on("keydown", '.form-control.serialNumber', function(e) {
    let code = e.code || e.keyCode || e.which;
    if (code == 13) {
      if (e.ctrlKey) {
        $('#createShipments').submit();
      } else {
        fillOtherFields(e.target);
        e.preventDefault();
        return false;
      }
    }
  });

  $(document).on('change', '.form-control.serialNumber', function(e) {
    if (focusing) return;
    fillOtherFields(e.target);

  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<form class="form-horizontal" id="createShipments" action="processConsignment.php" method="post" role="form">

      Serial
      ID
      Code
      Description

        <input type="text" class="form-control serialNumber" autocomplete="off" placeholder="Serial Number" name="serialNumber[]" value="">
        <input type="text" class="form-control assetID" autocomplete="off" placeholder="Asset ID" name="assetID[]" value="">

  <button type="button" name="addRow" value="addRow" id="addRow" class="btn btn-primary">Add Asset</button>
  <button type="submit" name="createShipment" value="createShipment" id="save" class="btn btn-success">Create Shipment</button>

</form>


text:
Q: How to merge transparent PNG with image using PHP? The situation is this: I have a small 50x50 pic. I also have a small 50x50 transparent picture which contains a frame for the 50x50 pic, so I basically want to put the transparent png on top of the image and merge those two which would lead to a final third picture that looks something like this: http://img245.imageshack.us/i/50x50n.png
Note: I don't want to do this using HTML only (I achieved this by writing a javascript plugin that put the transparent png on top of the original image).
Thanks.

A: Add imagealphablending($frame,true); before imagecopymerge() if you want to keep PNG frame transparancy over the image.

A: You can do it using ImageMagick :: Composite. The first user contributed note should be enough to grasp the concept.

A: You can merge the two images together using the PHP GD2 library.
Example:
<?php
 # If you don't know the type of image you are using as your originals.
 $image = imagecreatefromstring(file_get_contents($your_original_image));
 $frame = imagecreatefromstring(file_get_contents($your_frame_image));

 # If you know your originals are of type PNG.
 $image = imagecreatefrompng($your_original_image);
 $frame = imagecreatefrompng($your_frame_image);

 imagecopymerge($image, $frame, 0, 0, 0, 0, 50, 50, 100);

 # Save the image to a file
 imagepng($image, '/path/to/save/image.png');

 # Output straight to the browser.
 imagepng($image);
?>


text:
Q: Angular 4 (karma) Test input value to input filed I'm trying to test event which value entering by keyboard. my problem is after set value to the input field, when I print it prints, but when I print it inside the whenStable() it prints empty. I want to know why this value gets reset inside of the Whitstable() function. and how can I fix it?
I have referred: Updating input html field from within an Angular 2 test to write this test case.
it('Test input field value. ', async () => {
    const divDescription = fixture.debugElement.query(By.css('#costDescription'));

    divDescription.nativeElement.value = 'text';
    divDescription.nativeElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    console.log('sendInput : ', divDescription.nativeElement.value); // prints 'text'
    fixture.whenStable().then(() => {
      console.log('sendInput : ', divDescription.nativeElement.value); // prints ''
      expect(divDescription.nativeElement.value).toContain('text');
    });
  });

A: Removing WhenStable() make this happens.
  it('Test input field value. ', async () => {
      const divDescription = fixture.debugElement.query(By.css('#costDescription'));
      divDescription.nativeElement.value = 'text';
      divDescription.nativeElement.dispatchEvent(new Event('input'));
      fixture.detectChanges();
      expect(divDescription.nativeElement.value).toContain('text');
  });

A: you have to move Change detection call inside wheStable
it('Test input field value. ', async () => {
 const divDescription = fixture.debugElement.query(By.css('#costDescription'));

 divDescription.nativeElement.value = 'text';
 divDescription.nativeElement.dispatchEvent(new Event('input'));

 console.log('sendInput : ', divDescription.nativeElement.value); // prints 'text'
 fixture.whenStable().then(() => {
  fixture.detectChanges(); // moved inside
  console.log('sendInput : ', divDescription.nativeElement.value);
  expect(divDescription.nativeElement.value).toContain('text');
 });
});


text:
Q: What is the correct usage of "runAllManagedModulesForAllRequests" in ASP.NET MVC2/3? I've read various posts and questions about the use of runAllManagedModulesForAllRequests in the modules section of <system.WebServer> and I'm concerned that I'm using this setting incorrectly.
All my ASP.NET MVC applications are written using .NET Framework 4.0 and MVC2, plus we have a beta of an application that uses MVC3.
These apps are deployed to servers running Windows 2008R2/IIS7.5. The sites are configured to run in Integrated Pipeline/.NET 4.0 application pools.
If I set runAllManagedModulesForAllRequests="false" then I get a HTTP Error 403.14 - Forbidden error from IIS. If I set this to true then all is well.
However this article suggests this is a bad thing to do and a fix:

Don't use runAllManagedModulesForAllRequests="true" when getting your MVC routing to work

Is it really that bad, should I follow this advice?

A: How bad it is depends on the site traffic, if you are working on a high traffic website I'd say don't use it, and remove unneeded modules.


text: Q: Save multiple videos in custom designed layout in swift I've developed a dual camera app in ios. It has this layout. While developing, I came across the challenge of saving the video in this specific layout. I couldn't think of any other way of recording the video so I came up with the solution of recording the entire screen and save it as a video. But recently I've seen apps that do not record the screen and yet they're able to save the video in a custom layout. One example of such an app is this. Now I'm unable to figure out how to make a video and save it in custom layout without screen recording(since its not perfect solution). So any help in this regard would be appreciated.


text:
Q: Syntax for adding a closure to a function? I'm  trying to create a function that has a closure. Nothing is passed to the function, just after it finishes another function has to be called.  Something like this:
  func addGradient(closure: syntax) {
(closure: _ in ("function call here")   )}

so it can be called similiar to this
addGradient(closure: "function to be called")

A: Just use the signature for the function minus any of the names:
func doIt(one: Int, two: String) -> [String] {
  …
}

Would have the closure signature of:
(Int, String) -> [String]

So yours would be:
func addGradient(closure: (Int, String) -> [String]) {
  …
}

And you can call it like this:
addGradient(closure: doIt)

One more note, a function like this:
func doAgain() {
  …
}

Has a closure signature of this:
() -> ()


text:
Q: Getting same result from function every time why is my function returning the same result?
I would like to input all the values from the "ping" function to an array and then output that array in html.
I run the function 3 times but all three times the result is the same. Can you tell me why?
(The domains are just an example by the way, cant put originals here)
  var str = ' ';
  var t=[];
  var n= 2;
  var arr = ["www.google.com","www.example.com","www.example2.com"];
  var results = [];
  var finalurl = '';

    function fun1(){

        for (var i=0; i < arr.length; i++){
          str = "http://" + arr[i]  + "/images/";
          finalurl = str + "image-l.gif"  + "?id=" + (new Date()).getTime();
          ping(finalurl);
          textt += results[i] + " ";
          $('#ping').html(textt);

        }
    }

var ping = function(finalurl) {

    var l = 0;

    t.push((new Date()).getTime());
    if(t.length > n) {
        p=t[2]-t[1];
       results.push(p);
    }
    else {
      var img = new Image;
      $(img).load(function() {
        ping();
      }).attr('src', finalurl);
    }
}

//small part of html:

run

A: This generates three urls (the length of arr) but only attempts to show two (the value of n). The urls are different each time, but you are limiting them in ping so the new ones are not used.
Try setting n to higher number, you will see it will load more images each click - as it currently stands it tries to load more in a single click (3) than it allows (2).
Note: even if those urls are different, the images may be the same, this happens if the server ignores the id parameter... which probably does as it requires additional configuration for the server to handle requests to a ".gif" resource (which is not a known servcer side scripting language) - by default the server will just return the resource image-l.gif.
By the way: At $('#ping') those are the wrong quotes. Also textt is not defined - I did define it as var textt = ''; for my tests.


text:
Q: Is there a relationship between thickness of matter and luminance? I'm searching for a relationship between thickness of matter and luminance.
I'm a tribologist and I'm doing friction and wear experiments. During these experiments I'm illuminating the surface and capturing images during the whole test. The incoming light is a diffused light generated by a lighting dome. I'm observing how the pixels that are directed to the surface are getting darker over time due to wear debris deposition.
From what I'm understanding is that the pixel value of each image represent some kind of an uncalibrated luminance value. And my surface is getting darker due to attenuation of radiation (Beers Law). Therefore, is it possible to establish a relationship between Beers Law and luminance?
What I've found so far:
(1) Attenuation of radiation:
$$I(d) = I_0  e^{-\epsilon d},$$
while $\epsilon$ refers to absorption coefficient, $d$ to the material thickness, $I_0$ to the incoming luminous flux and I(d) the transmitted luminous flux.
(2) Lambertian reflection:
$$L = (E R)/\pi,$$
while $L$ refers to the luminance, $E$ to the illuminance and $R$ to the reflectance.
As $E=I_0/A$,
$$L = (I_0 R)/(A \pi),$$
while $A$ refers to the surface area.
I believe there is some kind of a relationship that could link the thickness of the deposited materials to the luminance, maybe like this
$$L(d) = L_0 e^{-\varepsilon d} + L_1$$.
So far, I could not find any link that come close to this relationship. I'm I on the wrong path? Thanks for any help!


text:
Q: Opening a Document from Visio with a SelectionAdded Event I am trying to make a shape object in Visio (2013 or later) open a local document through VBA when selected.
I have tried using the code below to get the event to create a msgbox thinking I would later change the msgbox functionality out to open a document but the msgbox won't display when I select a shape.
Private WithEvents OrgChartApp As Visio.Application

Private Sub OrgChartApp_SelectionAdded(ByVal Selection As IVSelection)
    If Selection.Count = 1 Then
        MsgBox "Hello"
    End If
End Sub


text:
Q: Random Serial Dictatorship algorithm vs linear programming in solving an assignment problem I just came across this post, which left me quite baffled.
If I had to assign N objects to N users, knowing that each user has expressed a rank preference for the objects, with the goal to achieve the lowest possible average rank (that is what the post states), my automatic choice would be linear programming.
Instead, this Random Serial Dictatorship is suggested, and it is stated that it achieves some form of optimality.
I was not sure how what looked to me like a greedy stochastic algorithm could guarantee optimality, so I tried it out.
Suppose that 3 users A, B, C have expressed rank preferences for 3 houses H1, H2, H3:
     user
house A B C
   H1 3 2 1
   H2 1 1 2
   H3 2 3 3

We want to assign a house to each user, so that the average (or sum) of ranks is minimal.
If I understood it correctly, the Random Serial Dictatorship algorithm requires choosing a random order for the users, and allow each of them to select the house they prefer.
For me it's clear that this kind of strategy may: 1) not result in the same sum of ranks each time, 2) consequently not guarantee optimality.
Imagine that A chooses first, B second and C third. A will select H2 (rank 1). But that's also B's preferred house, so B will have to go for H1 (rank 2), and C will be left with their least preferred house H3 (rank 3). Ranks = 1, 2, 3. Sum = 6, average = 2.
If, on the other hand, B chooses first, A second and C third: B = H2 (1), A = H3 (2), C = H1 (1). Ranks = 1, 2, 1. Sum = 4, average = 4/3.
As an R simulation:
# 3 users A, B, C want to buy a house each, chosen from H1, H2, H3.
# Their preferences are expressed by 'rank' (1 = first choice, 2 = second choice, etc).
d0 <- data.frame("user" = rep(c("A","B","C"), each = 3),
                "house" = rep(c("H1", "H2", "H3"), 3),
                "rank" = c(3,1,2,2,1,3,1,2,3)
                )

# 1. Assignment by random serial dictatorship

set.seed(232425)

all_ranks <- numeric(0)

for (i in 1:1000) {
  d <- d0
  # Create a random order of priority for the users.
  o <- setNames(sample(1:3), c("A","B","C"))
  # Let users choose their preferred house in turn, according to the created order.
  d["order"] <- o[d$user]
  d <- d[order(d$order, d$rank),]
  for (i in 1:2) {
    h <- d[i, "house"]
    d <- rbind(d[1:i,], d[(d$order > i) & (d$house != h),])
  }
  ranks <- d$rank
  ranks <- ranks[order(d$user)]
  all_ranks <- rbind(all_ranks, ranks)
  #print(d)
}

all_ranks <- setNames(as.data.frame(all_ranks), c("A","B","C"))
all_ranks_summary <- cbind("ID" = 1, setNames(stack(all_ranks), c("rank", "user")))
all_ranks_summary <- aggregate(ID ~ user + rank, all_ranks_summary, length)

barplot(ID ~ rank + user, all_ranks_summary, beside = TRUE, col = 2:4, legend.text = TRUE)
boxplot(rowMeans(all_ranks), main = "average rank")

Frequency of each rank for the 3 users and the average rank:

Clearly the average rank is not minimal in all cases.
Using a linear programming assignment method instead:
# 2. Assignment by linear programming

require(lpSolve)
cm <- xtabs(rank ~ house + user, d0)
lp.out <- lp.assign(cm)
lp.out$solution * cm

yields a guaranteed optimal solution:
     user
house A B C
   H1 0 0 1
   H2 0 1 0
   H3 2 0 0

My questions are:
1. Am I misunderstanding the Random Serial Dictatorship algorithm? Can it actually be written in a way that guarantees optimality?
2. Is a linear programming assignment method almost as bad, computationally, as the brute force enumeration of all combinatorial possibilities?
Perhaps I am wrong, but I'm just puzzled that one should start from a goal like:

"assign each user an option so that the average rank of the assigned option in that user's ranked list is minimized across all users"

and then settle for an algorithm that, as 'fair' and as 'fast' as it may be, does not seem to achieve that goal at all.
Unless I am completely missing the point, which is possible.

A: It's "Pareto optimal", which is to say, not optimal in general. Pareto optimal just means that you would need to harm one or more of the participants to improve the objective.


text:
Q: Use Azure AD with Active Directory PrincipalContext.ValidateCredentials Is it possible to validate users in Azure AD using the following method,
  public bool ValidateCredentials(string domainName, string userName, string password)
        {
            using (PrincipalContext pCtx = new PrincipalContext(ContextType.Domain, domainName))
            {
                bool isValid = pCtx.ValidateCredentials(userName, password);
                return isValid;
            }
        }

I have provided the domain as "xyz.onmicrosoft.com" and the user and password under the respective azure AD. and
received an exception "The server could not be contacted."

A: Azure AD does not provide the same endpoints as Active Directory as the two are completely different products.
You need to use Open Id Connect or WS-Fed or SAML2 flows to authenticate a user.
Guidance for various scenarios here: https://learn.microsoft.com/en-us/azure/active-directory/develop/authentication-scenarios


text:
Q: badly formed hexadecimal UUID string with Adafruit library The issue
I am trying to play with a Bluefruit LE Friend dongle (Adafruit).
They provide a python library to communicate with it.
Unfortunately, the example they provide doesn't work:
user@server# python ../../low_level.py
Using adapter: user-VirtualBox
Disconnecting any connected UART devices...
Searching for UART device...
Connecting to device...
Discovering services...
Traceback (most recent call last):
  File "../../low_level.py", line 106, in <module>
    ble.run_mainloop_with(main)
  File "build/bdist.linux-x86_64/egg/Adafruit_BluefruitLE/bluez_dbus/provider.py", line 118, in _user_thread_main
  File "../../low_level.py", line 70, in main
    device.discover([UART_SERVICE_UUID], [TX_CHAR_UUID, RX_CHAR_UUID])
  File "build/bdist.linux-x86_64/egg/Adafruit_BluefruitLE/bluez_dbus/device.py", line 106, in discover
  File "build/bdist.linux-x86_64/egg/Adafruit_BluefruitLE/bluez_dbus/device.py", line 137, in advertised
  File "/usr/lib/python2.7/uuid.py", line 134, in __init__
    raise ValueError('badly formed hexadecimal UUID string')
ValueError: badly formed hexadecimal UUID string

What I tried
I added a line in /usr/lib/python2.7/uuid.py to print the uuid value when the exception is raised; I get the value 1800. I can't find where does this value comes from.
I can't find the file build/bdist.linux-x86_64/egg/Adafruit_BluefruitLE/bluez_dbus/device.py to debug with that one…

Here's the code, from their GitHub repo:
# Example of low level interaction with a BLE UART device that has an RX and TX
# characteristic for receiving and sending data.  This doesn't use any service
# implementation and instead just manipulates the services and characteristics
# on a device.  See the uart_service.py example for a simpler UART service
# example that uses a high level service implementation.
# Author: Tony DiCola
import logging
import time
import uuid

import Adafruit_BluefruitLE

# Enable debug output.
#logging.basicConfig(level=logging.DEBUG)

# Define service and characteristic UUIDs used by the UART service.
UART_SERVICE_UUID = uuid.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')
TX_CHAR_UUID      = uuid.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E')
RX_CHAR_UUID      = uuid.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E')

# Get the BLE provider for the current platform.
ble = Adafruit_BluefruitLE.get_provider()

# Main function implements the program logic so it can run in a background
# thread.  Most platforms require the main thread to handle GUI events and other
# asyncronous events like BLE actions.  All of the threading logic is taken care
# of automatically though and you just need to provide a main function that uses
# the BLE provider.
def main():
    # Clear any cached data because both bluez and CoreBluetooth have issues with
    # caching data and it going stale.
    ble.clear_cached_data()

    # Get the first available BLE network adapter and make sure it's powered on.
    adapter = ble.get_default_adapter()
    adapter.power_on()
    print('Using adapter: {0}'.format(adapter.name))

    # Disconnect any currently connected UART devices.  Good for cleaning up and
    # starting from a fresh state.
    print('Disconnecting any connected UART devices...')
    ble.disconnect_devices([UART_SERVICE_UUID])

    # Scan for UART devices.
    print('Searching for UART device...')
    try:
        adapter.start_scan()
        # Search for the first UART device found (will time out after 60 seconds
        # but you can specify an optional timeout_sec parameter to change it).
        device = ble.find_device(service_uuids=[UART_SERVICE_UUID])
        if device is None:
            raise RuntimeError('Failed to find UART device!')
    finally:
        # Make sure scanning is stopped before exiting.
        adapter.stop_scan()

    print('Connecting to device...')
    device.connect()  # Will time out after 60 seconds, specify timeout_sec parameter
                      # to change the timeout.

    # Once connected do everything else in a try/finally to make sure the device
    # is disconnected when done.
    try:
        # Wait for service discovery to complete for at least the specified
        # service and characteristic UUID lists.  Will time out after 60 seconds
        # (specify timeout_sec parameter to override).
        print('Discovering services...')
        device.discover([UART_SERVICE_UUID], [TX_CHAR_UUID, RX_CHAR_UUID])

        # Find the UART service and its characteristics.
        uart = device.find_service(UART_SERVICE_UUID)
        rx = uart.find_characteristic(RX_CHAR_UUID)
        tx = uart.find_characteristic(TX_CHAR_UUID)

        # Write a string to the TX characteristic.
        print('Sending message to device...')
        tx.write_value('Hello world!\r\n')

        # Function to receive RX characteristic changes.  Note that this will
        # be called on a different thread so be careful to make sure state that
        # the function changes is thread safe.  Use Queue or other thread-safe
        # primitives to send data to other threads.
        def received(data):
            print('Received: {0}'.format(data))

        # Turn on notification of RX characteristics using the callback above.
        print('Subscribing to RX characteristic changes...')
        rx.start_notify(received)

        # Now just wait for 30 seconds to receive data.
        print('Waiting 60 seconds to receive data from the device...')
        time.sleep(60)
    finally:
        # Make sure device is disconnected on exit.
        device.disconnect()

# Initialize the BLE system.  MUST be called before other BLE calls!
ble.initialize()

# Start the mainloop to process BLE events, and run the provided function in
# a background thread.  When the provided main function stops running, returns
# an integer status code, or throws an error the program will exit.
ble.run_mainloop_with(main)

A: This code depends on D-Bus, specifically the 'properties' offered by it. I would to say that the problem is here:
uuids = self._props.Get(_INTERFACE, 'UUIDs')
https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/master/Adafruit_BluefruitLE/bluez_dbus/device.py#L131
Probably you either didn't properly install D-Bus, or there's been another issue (linking to it, configuration, version issue, etc). When you try and get the 'UUIDs' property, you get invalid strings, which then get sense down to uuid.UUID() here:
return [uuid.UUID(str(x)) for x in uuids]
and you get the error you've seen. I would print out the value of the uuids array for debugging purposes, see what the value of the elements in it are, and proceed accordingly.
Good luck!

A: Well u have two ways to fix it.
Right way read more about this and configure your adafruit bluetooth.
Or bad way u can just comment this if statement check
if len(hex) != 32:
    raise ValueError('badly formed hexadecimal UUID string')

in /usr/lib64/python2.7/uuid.py problem is comming from the len of "hex" parameter is need to be configured like thist 128 bit 6e400001b5a3f393e0a9e50e24dcca9e and not 16 bit0x1800.
To see which parameters of GATT u need to configure just put a
print "this is value of hex", hex

in /usr/lib64/python2.7/uuid.py before the previosly commented if statement.


text:
Q: Is there any way to rewrite the function in "is_lim"? I'm using Coq and Coquelicot Library, and I'd like to know a better way to handle limit easily.
When I want to prove \lim_{x \to 1} (x^2-1)/(x-1) = 2, I code as follows.
Require Import Reals Lra.
From mathcomp Require Import all_ssreflect.
From Coquelicot Require Import Coquelicot.

Lemma lim_1_2 : is_lim (fun x:R => (x^2 - 1)/(x - 1)) 1 2.
Proof.
  apply (is_lim_ext_loc (fun x:R => x + 1)).
  - rewrite /Rbar_locally' /locally' /within /locally.
    exists (mkposreal 1 Rlt_0_1).
    move => y Hyball Hyneq1.
    field; lra.
  - apply is_lim_plus'; [apply is_lim_id | apply is_lim_const].
Qed.

In this example, I explicitly write the goal term (fun x:R => x + 1). Is there any way to transform (fun x:R => (x^2 - 1)/(x - 1)) to (fun x:R => x + 1) like rewrite tactic? In other words, I'm looking for a similar tactic as under for eq_big_nat.

A: Coquelicot is optimized for ease of use and uses total functions rather than dependent restrictions wherever possible - e.g. you can write down an integral without having a prove that it exists, but as far as I know this does not extend to division by zero. To make your above equation work, one would need a definition of division, which somehow can handle the 0/0 you get for x=1. One can define a division for functions (polynomials) which can handle this in a reasonable way - and this is what you are using implicitly by stating that this makes sense, but one cannot define division for individual real numbers which can handle 0/0 in the way you would like. But the division operator you use above is a division on individual numbers and not on polynomials. In informal mathematics one is sometimes a bit sloppy about such things.
Besides the 0/0 issue, you also would have to use the axiom of functional extensionality, which states that two functions are equal in case they are equal for each point.
Here is a snippet of Coq which shows what one can be done and where the issues are :
Require Import Reals.
Require Import Lra.
Require Import FunctionalExtensionality.

Open Scope R.

Definition dom := {x : R | x<>1}.

Definition dom2R (x : dom) : R := proj1_sig x.
Coercion dom2R : dom >-> R.

Example Example:
    (fun x : dom => (x^2 - 1)/(x - 1))
  = (fun x : dom => x + 1).
Proof.
  apply functional_extensionality.
  intros [x xH].
  cbv.
  field.
  lra.
Qed.

All in all it is not that bad with the implicit coercion from dom to Real, although the function is in reality more complicated than it looks since each x is an implicit coercion projecting from dom to R.
Also one could have an axiom of functional extensionality, which works if the domain of one function is a subset of the domain of the other function. I am not sure if this would be consistent, though and it would also require a non standard definition of equality because with the usual equality only things of the same type can be equal. This would allow you to equate the polynomial fraction with the polynomial on the full R.
I hope this explains why things are as they are. Coquelicot relies on the division operator from the standard library, for which you can't prove anything in case the denominator is zero. This is sometimes inconvenient, but to my knowledge (which is not very extensive - I am physicist not mathematician) up to now nobody came up with a definition of division which allows you to easily do what you want.


text:
Q: meaning of an integral in the continuity equation This is about continuity equation. What does the last integral mean?
$$\frac{\mathrm{d}Q_V}{\mathrm{d}t}=\iiint_V \mathrm{d}^3x \,\frac{\partial\rho}{\partial t}=-\iiint_V\! \mathrm{d}^3x\,\operatorname{div}\,\mathbf{j}=-\iint\limits_{\partial V}\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\;\;\;\subset\!\supset \mathbf j\;\cdot\mathbf n\,{d}S\,,$$
EDIT:
And what does $\partial V$ mean? Why not S like surface?

A: The last integral is a surface integral. It is the fluid (current) flux crossing the volume surface integrated over the whole surface. It is how much charge is leaving the volume per second. ($\partial V$ means boundary of V and you sum all local $j_\bot dS$.)

A: Note that the range of integration has changed from $V$ meaning over the volume to $\partial{V}$ and that the variable of integration has changed from $\text{d}^3x$ to $\text{d}S$.
It means an integral over the surface that bounds the volume.
The closed curve over the integration signs implies that the surface must be closed.

This expression is an application of what physicist tend to call Gauss's Law, and mathematicians tend to know as the divergence theorem.


text:
Q: Postgres lowercase column and delete duplicates I have the following table:
Customers
---------
name          text
object_id     integer
created_time  timestamp with time zone

Indexes:
    "my_index" UNIQUE CONSTRAINT, btree (name, object_id, created_time)

The unique index works fine but then I ended up with duplicate data like:
Name  |  object_id  |  created_time
------------------------------------
john  | 1           | 2018-02-28 15:42:14.30573+00
JOHN  | 1           | 2018-02-28 15:42:14.30573+00

So I tried to lowercase all my data in the name column with:
UPDATE customers SET name=lower(name) WHERE name != LOWER(name);

But this procedure generated an error because now I would be violating the index:
ERROR:  duplicate key value violates unique constraint "my_index"
DETAIL:  Key (name, object_id, created_time)=(john, 1, 2018-02-28 15:42:14.30573+00) already exists.

What kind of procedure could I use to delete rows that after casting to lowercase generate an index violation ?

A: If you have 'JOHN' and 'John' in you table but not 'john' it gets messy. here's one solution.
insert into customers
  select distinct lower("name") ,object_id,created_time from customers
    where name <> lower(name)
      and not (lower("name") ,object_id,created_time)
       in (select * from customers);

delete from customers where name <> lower(name);

after that consider:
alter table customers alter column name type citext;


text:
Q: Best way to convert Milliseconds to number of years, months and days I'm trying to convert a Milliseconds date to number of years months weeks and days.
For example: 5 months, 2 weeks and 3 days or 1 year and 1 day.
I don't want: 7 days or 4 weeks > this should be 1 week and 1 month.
I tried few ways but it always became something like 7 days and 0 weeks.
My code:
int weeks = (int) Math.abs(timeInMillis / (24 * 60 * 60 * 1000 * 7));
int days = (int) timeInMillis / (24 * 60 * 60 * 1000)+1);

I have to add 1 to number of days because if I have 23 hours it should be 1 day.
Please explain how to convert it correctly, I think that there is more efficient ways to do it.

A: Thanks to Shobhit Puri my problem was solved.
This code calculates how many months, days etc. are in a given time in milliseconds. I use it to calculate difference between two dates.
Full solution:
long day = (1000 * 60 * 60 * 24); // 24 hours in milliseconds
long time = day * 39; // for example, 39 days

Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
int mYear = c.get(Calendar.YEAR)-1970;
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH)-1;
int mWeek = (c.get(Calendar.DAY_OF_MONTH)-1)/7; // ** if you use this, change the mDay to (c.get(Calendar.DAY_OF_MONTH)-1)%7

Thank you again!

A: Source:Convert time interval given in seconds into more human readable form
function secondsToString(seconds)
{
var numyears = Math.floor(seconds / 31536000);
var numdays = Math.floor((seconds % 31536000) / 86400);
var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;
return numyears + " years " +  numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";

}

A: I always use this for getting years etc from milliseconds and vice versa. Till now I've had no problems with it. Hope it helps.
import java.util.Calendar;

Calendar c = Calendar.getInstance();
//Set time in milliseconds
c.setTimeInMillis(milliseconds);
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
int hr = c.get(Calendar.HOUR);
int min = c.get(Calendar.MINUTE);
int sec = c.get(Calendar.SECOND);


text:
Q: Fatal error LNK1181 when trying to npm install web3 I am trying to install the web3 node package with npm install. I am aware of the fact that I first need to install Windows build tools since I am running windows:
npm install --global --production windows-build-tools

This command goes through fine but when I run the command to install web3 I get the following error:
npm WARN deprecated fs-promise@2.0.3: Use mz or fs-extra^3.0 with Promise Support
npm WARN deprecated tar.gz@1.0.7: ⚠  WARNING ⚠ tar.gz module has been deprecated and your application is vulnerable. Please use tar module instead: https://npmjs.com/tar
> scrypt@6.0.3 preinstall [project path]\node_modules\scrypt
> node node-scrypt-preinstall.js
> scrypt@6.0.3 install [project path]\node_modules\scrypt
> node-gyp rebuild
[project path]\node_modules\scrypt>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
Warning: Missing input files:
[project path]\node_modules\scrypt\build\..\scrypt\win\include\config.h
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
  Copying scrypt/win/include/config.h to scrypt/scrypt-1.2.0/config.h
  The system cannot find the file specified.
  win_delay_load_hook.cc
LINK : fatal error LNK1181: cannot open input file '[user path]\.node-gyp\9.8.0\x64\node.lib' [[project path]\node_modules\scrypt\build\copied_files.vcxproj]
  memlimit.c
  keyderivation.c
  pickparams.c
  hash.c
  win_delay_load_hook.cc
  scrypt_wrapper.vcxproj -> [project path]\node_modules\scrypt\build\Release\\scrypt_wrapper.lib
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:258:23)
gyp ERR! stack     at ChildProcess.emit (events.js:180:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:12)
gyp ERR! System Windows_NT 10.0.16299
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd [project path]\node_modules\scrypt
gyp ERR! node -v v9.8.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
npm WARN inbox@1.0.0 No description
npm WARN inbox@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! scrypt@6.0.3 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the scrypt@6.0.3 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     [user path]\AppData\Roaming\npm-cache\_logs\2018-03-16T15_29_59_737Z-debug.log

After some additional research about why this happens I found out that the error pops up when the install process tries to install scrypt (?).
What is the problem? I have also added the environment variables for python that are required after the Windows build tools setup.

A: To resolve this error, use the path, with no spaces, or quotation marks in the path of the project properties.

A: Ouch so sorry 'cause i can't see what's happening and why it's not working...
I've tryed and it's worked for me with this method :

*

*npm install --global --production windows-build-tools

*npm install --save web3@1.0.0-beta.26

And web 3 V 1.0 is correctly installed.
If someone else can help ;)

A: Running as root or Administrator can fix the problem.
I had the same error. I followed Azerus's advice and created new path with only Latin letters and no spaces (actually I just created new user and logged in). But it still did not work but the error number was different. And then I got the idea to run cmd as Administrator and... it's done.


text:
Q: How do I calculate the sub total and total in a table in the laravel? If I debug my laravel eloquent, the result like this :
SELECT a.transaction_number a.date, a.item_number, b.desc, a.variant_code, sum(a.quantity) AS quantity, a.cost
FROM `items_details` AS a
JOIN `items` AS b ON b.id = a.item_number
WHERE a.item_number = 0101010
GROUP BY a.variant_code
ORDER BY transaction_number, variant_code

I will return collection with pagination
But here I just display the array. The array like this :
$data = array(
    array('transaction_number' => 'AB-0001','date' => '2018-08-01', 'item_number' => '0101010', 'desc' => 'This is a', 'variant_code' => '002', 'quantity' => '2','cost' => '2000'),
    array('transaction_number' => 'AB-0001','date' => '2018-08-01', 'item_number' => '0101010', 'desc' => 'This is a', 'variant_code' => '004', 'quantity' => '3','cost' => '2000'),
    array('transaction_number' => 'AB-0001','date' => '2018-08-01', 'item_number' => '0101010', 'desc' => 'This is a', 'variant_code' => '005', 'quantity' => '4','cost' => '2000'),
    array('transaction_number' => 'AB-0001','date' => '2018-08-01', 'item_number' => '0101010', 'desc' => 'This is a', 'variant_code' => '006', 'quantity' => '5','cost' => '2000'),
    array('transaction_number' => 'AB-0001','date' => '2018-08-01', 'item_number' => '0101010', 'desc' => 'This is a', 'variant_code' => '008', 'quantity' => '1','cost' => '2000'),
    array('transaction_number' => 'AB-0002','date' => '2018-08-02', 'item_number' => '0101010', 'desc' => 'This is b', 'variant_code' => '013', 'quantity' => '2','cost' => '2000'),
    array('transaction_number' => 'AB-0002','date' => '2018-08-02', 'item_number' => '0101010', 'desc' => 'This is b', 'variant_code' => '020', 'quantity' => '3','cost' => '2500'),
    array('transaction_number' => 'AB-0002','date' => '2018-08-02', 'item_number' => '0101010', 'desc' => 'This is b', 'variant_code' => '022', 'quantity' => '4','cost' => '2500'),
    array('transaction_number' => 'AB-0003','date' => '2018-08-03', 'item_number' => '0101010', 'desc' => 'This is c', 'variant_code' => '007', 'quantity' => '1','cost' => '2500'),
    array('transaction_number' => 'AB-0003','date' => '2018-08-03', 'item_number' => '0101010', 'desc' => 'This is c', 'variant_code' => '015', 'quantity' => '7','cost' => '2500')
);

My script in the laravel blade to display it like this :

        transaction_number
        date
        item_number
        desc
        variant_code
        quantity
        cost

    @foreach ($items as $item)

            {{ $item->transaction_number }}
            {{ $item->date }}
            {{ $item->item_number }}
            {{ $item->desc }}
            {{ $item->variant_code }}
            {{ $item->quantity }}
            {{ $item->cost }}

    @endforeach

The result like this :

I want the result like this :

What is the best way to do it? Whether through mysql query or laravel eloquent to display like that? Or is it arranged through the view blade laravel?
Please, help me. I'm confused :)

A: Without pagination, I would do something like this (not tested)...
Requiring pagination adds complexity with regards to potentially breaking up transaction groups and the total.
Have a read of the following,
https://laravel.com/docs/5.6/blade#the-loop-variable
https://laravel.com/docs/5.6/blade#including-sub-views
You need Laravel 5.3+ for $loop.
subtotal.blade.php

    SUBTOTAL
    {{ $items->where('transaction_number', $current_transaction_number)->sum('quantity') }}
    {{ $items->where('transaction_number', $current_transaction_number)->sum('cost') }}

total.blade.php

    TOTAL
    {{ $items->sum('quantity') }}
    {{ $items->sum('cost') }}

main.blade.php

        transaction_number
        date
        item_number
        desc
        variant_code
        quantity
        cost

    @php ($current_transaction_number = null)

    @foreach ($items as $item)
        @if ($loop->index > 0 && $current_transaction_number != $item->transaction_number)
           @include ('subtotal', compact('items', 'current_transaction_number'))
        @endif

            @if ($current_transaction_number == $item->transaction_number)

            @else
                @php ($current_transaction_number = $item->transaction_number)
                {{ $item->transaction_number }}
                {{ $item->date }}
            @endif
            {{ $item->item_number }}
            {{ $item->desc }}
            {{ $item->variant_code }}
            {{ $item->quantity }}
            {{ $item->cost }}

        @if ($loop->last)
           @include ('subtotal', compact('items', 'current_transaction_number'))
           @include ('total', compact('items'))
        @endif
    @endforeach

{{ $items->links() }}

A: @php
    $previous_transaction_number = "";
    $total_quantity = 0;
    $total_cost = 0;
    $subtotal_quantity = 0;
    $subtotal_cost = 0;
@endphp

        transaction_number
        date
        item_number
        desc
        variant_code
        quantity
        cost

    @foreach ($items as $item)
        @if(!empty($previous_transaction_number) && $previous_transaction_number != $item['transaction_number'])

                SUBTOTAL:
                 {{ $subtotal_quantity }}
                 {{ $subtotal_cost }}

            @php
                $subtotal_quantity = 0;
                $subtotal_cost = 0;
                $previous_transaction_number = "";
            @endphp

        @endif

            @if($previous_transaction_number != $item['transaction_number'])
                {{ $item['transaction_number'] }}
            @else

            @endif
            {{ $item['date'] }}
            {{ $item['item_number'] }}
            {{ $item['desc'] }}
            {{ $item['variant_code'] }}
            {{ $item['quantity'] }}
            {{ $item['cost'] }}

        @php
            $subtotal_quantity += $item['quantity'];
            $subtotal_cost += $item['cost'];
            $previous_transaction_number = $item['transaction_number'];
            $total_quantity += $item['quantity'];
            $total_cost += $item['cost'];
        @endphp
    @endforeach

        SUBTOTAL:
         {{ $subtotal_quantity }}
         {{ $subtotal_cost }}

        TOTAL:
         {{ $total_quantity }}
         {{ $total_cost }}


text:
Q: as.Date / strptime format What could be the problem? I don't seem to get why this had to be NA.

as.Date("jan2012", format="%b%Y")
[1] NA

I have also used strptime function and it is the same thing. I have been using this functions but I don't know they are not working this morning. Any insight as to why this is will be useful.

A: The Date include day also.  So, we need to paste with a day i.e. 01
as.Date(paste("jan2012", "01"), format="%b%Y%d")
#[1] "2012-01-01"

A: "jan2012" isn't a date, it's a month.  You need to prefix the day you want, e.g.
as.Date(paste0("01", "jan2012"), format = "%d%b%Y")


text:
Q: Hibernate Search 6 with Lucene Highlighter and Synonym List we have a large synonym list. I use a manual analyzer to index the search field. The synonym list is annotated with the "SynonymGraphFilterFactory" filter. So far everything is good. When I do a search on the field, I get the matching result.
Synonym list looks like this:
car, vehicle
If I enter "car" in my search, the correct results are displayed and the word "car" is highlighted.
When I enter the word "vehicle" I get correct results but nothing is highlighted.
I would like to have both words highlighted in the search. "car" and "vehicle".
Is that even possible?
So far I haven't found a suitable solution. Maybe someone can help me here.
Configurations:
Hibernate-search 6, Lucene Higlighter 8.7
Code:

To index the search field, my analyzer looks like this:

context.analyzer ("myCustomAnalyzer"). custom ()
.tokenizer (StandardTokenizerFactory.class)
.tokenFilter (LowerCaseFilterFactory.class)
.tokenFilter (KeywordRepeatFilterFactory.class)
.tokenFilter (PorterStemFilterFactory.class)
.tokenFilter (TrimFilterFactory.class)
.tokenFilter (SnowballPorterFilterFactory.class) .param ("language", "German")
.tokenFilter (RemoveDuplicatesTokenFilterFactory.class)
.tokenFilter (SynonymGraphFilterFactory.class) .param ("synonyms", "synonyms / synonyms.properties")
.param ("ignoreCase", "true"). param ("expand", "true");

Highlighter method looks like this:

private Results highlighting(final Results results, final String mySearchString) {

        final SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("start", "end");
        final TermQuery query = new TermQuery(
            new Term("indexFieldName", mySearchString));
        final QueryScorer queryScorer = new QueryScorer(query, "indexFieldName");
        final Fragmenter fragmenter = new SimpleSpanFragmenter(queryScorer);
        queryScorer.setExpandMultiTermQuery(true);
        final Highlighter highlighter = new Highlighter(simpleHTMLFormatter, queryScorer);
        highlighter.setTextFragmenter(fragmenter);

        try (Analyzer analyzer = new StandardAnalyzer()) {
            for (final MyEntity my : results.getMyResults()) {
                for (final MySecondEntity sec : my.getMyDescriptions()) {

                    final String text = sec.getMyName();

                    try {
                        final TokenStream tokenStream = analyzer.tokenStream(
                            "indexFieldName", new StringReader(text));
                        final String result = highlighter.getBestFragments(
                            tokenStream, text,
                            sec.getMyName().length(), " ...");
                        if (!StringUtils.isBlank(result)) {

                            sec.setMyName(result);
                        }

                    } catch (final Exception e) {
                        LOG.warn(String.format(
                            "Failure during highlighting process for ..."...
                    }
                }
            }

        }
        return results;
    }

Thank you for your answers

A: I'm not overly familiar with highlighters, but one thing that seems suspicious in your code is the fact that you're using a StandardAnalyzer to highlight. If you want synonyms to be highlighted, I believe you need to use an analyzer that handles synonyms.
Try using the same analyzer for indexing and highlighting.
You can retrieve the analyzer instance from Hibernate Search. See this section of the documentation, or this example:
LuceneBackend luceneBackend =
        Search.mapping( entityManager.getEntityManagerFactory() )
        .backend().unwrap( LuceneBackend.class );
Analyzer analyzer = luceneBackend.analyzer( "myCustomAnalyzer" ).get();

Then use it instead of new StandardAnalyzer() in your highlighting code; just make sure you don't close this analyzer.


text:
Q: How to disable the ContextMenu but not the right click event in a WebView I have tried with the setContextMenuEnabled(false) method of the WebView class, but that also disables the right click event an does not pass it to the website, so no javascript events can be triggered.
I found other answer that shows how to add more options to the context menu, thing that I do not want to do, I just want to disable the contextMenu but no the event.


text:
Q: Directus 8 thumbnail path not found Unable to generate thumbnails, broken icon, I tried everything (Directus 8.6.2)
The only thumbnail obtained is that of the collections list (24x24), which the development tools indicate in a subfolder "public /.../ assets /" which does not exist!
I don't understand how the thumbnails work in Directus 8 ...
URL rewriting ??
My Config file (default) :
'storage' => [
'adapt' => 'local',
'root' => 'public / uploads / [...] / originals',
'root_url' => '/ uploads / [...] / originals',
'thumb_root' => 'public / uploads / [...] / generated'

Would i have missed something?
Thank you.


text:
Q: Magento 2: Need to re-save all products after re-assigning source so I deactived all MSI-related modules and found out that it still needed it for another module, so I activated it again.
Then the default source that was created by the data-migration from M1 to M2 was gone after that.
So I created a new source and added all products to that source, however all the products were still 'out of stock' on the frontend. After re-saving a product, it is displayed properly on the frontend.
Therefore I need to re-save all products. Is there a fast way to do so or can I do something else?
Btw: I tried reindexing, upgrading etc.
Thanks

A: Write a CLI command to save all products again
$storeId = 1;
$productCollection = $this->collectionFactory->create()
        ->addAttributeToSelect('id')
        ->addStoreFilter($storeId)
        ->load();

$i = 1;
foreach ($productCollection as $product) {
    $productId = $product->getId();
    $product = $this->product->create()->load($productId);

    $product->save();
    echo $i.". Saved product ".$product->getName()." with product id ".$productId. "\n";

    $i++;
}


text:
Q: skeleton grid system: make container 100% is it possible to make the the root div (container) 100% of the document?
here's my code:

topbar topbar topbar topbar topbar topbar

thanks

A: You'll need to create your own container class.  I don't know what the css for the skeleton responsive platform looks like off the top of my head.  I use one called Columnal, I know it is similar, so it should be something like this...
.full-width-container {
width: 100%;
max-width: 100%;
clear: both;
margin: 0 auto;
}

The normal css should be something like .container { max-width: 1140px; width: 100%; clear: both; margin: 0 auto; }

A: I know this question was asked ages ago but Skeleton has utility classes for this.
Basically add the .u-full-width and .u-max-full-width classes to any
 with class .container.
Just make sure it's on the
 element with class .container, as it doesn't seem to be meant for the
 elements with .row or .column classes.


text:
Q: MLP Neural Network: calculating the gradient (matrices) What is a good implementation for calculating the gradient in a n-layered neural network?
Weight layers:

*

*First layer weights:     (n_inputs+1, n_units_layer)-matrix

*Hidden layer weights: (n_units_layer+1, n_units_layer)-matrix

*Last layer weights:     (n_units_layer+1, n_outputs)-matrix
Notes:

*

*If there is only one hidden layer we would represent the net by using just two (weight) layers:
inputs --first_layer-> network_unit --second_layer-> output

*For a n-layer network with more than one hidden layer, we need to implement the (2) step.

A bit vague pseudocode:
    weight_layers = [ layer1, layer2 ]             # a list of layers as described above
    input_values  = [ [0,0], [0,0], [1,0], [0,1] ] # our test set (corresponds to XOR)
    target_output = [ 0, 0, 1, 1 ]                 # what we want to train our net to output
    output_layers = []                             # output for the corresponding layers

    for layer in weight_layers:
        output <-- calculate the output     # calculate the output from the current layer
        output_layers <-- output            # store the output from each layer

    n_samples = input_values.shape[0]
    n_outputs = target_output.shape[1]

    error = ( output-target_output )/( n_samples*n_outputs )

    """ calculate the gradient here """

Final implementation
The final implementation is available at github.

A: With Python and numpy that is easy.
You have two options:

*

*You can either compute everything in parallel for num_instances instances or

*you can compute the gradient for one instance (which is actually a special case of 1.).

I will now give some hints how to implement option 1. I would suggest that you create a new class that is called Layer. It should have two functions:

forward:
    inputs:
    X: shape = [num_instances, num_inputs]
        inputs
    W: shape = [num_outputs, num_inputs]
        weights
    b: shape = [num_outputs]
        biases
    g: function
        activation function
    outputs:
    Y: shape = [num_instances, num_outputs]
        outputs

backprop:
    inputs:
    dE/dY: shape = [num_instances, num_outputs]
        backpropagated gradient
    W: shape = [num_outputs, num_inputs]
        weights
    b: shape = [num_outputs]
        biases
    gd: function
        calculates the derivative of g(A) = Y
        based on Y, i.e. gd(Y) = g'(A)
    Y: shape = [num_instances, num_outputs]
        outputs
    X: shape = [num_instances, num_inputs]
        inputs
    outputs:
    dE/dX: shape = [num_instances, num_inputs]
        will be backpropagated (dE/dY of lower layer)
    dE/dW: shape = [num_outputs, num_inputs]
        accumulated derivative with respect to weights
    dE/db: shape = [num_outputs]
        accumulated derivative with respect to biases

The implementation is simple:
def forward(X, W, b):
    A = X.dot(W.T) + b # will be broadcasted
    Y = g(A)
    return Y

def backprop(dEdY, W, b, gd, Y, X):
    Deltas = gd(Y) * dEdY # element-wise multiplication
    dEdX = Deltas.dot(W)
    dEdW = Deltas.T.dot(X)
    dEdb = Deltas.sum(axis=0)
    return dEdX, dEdW, dEdb

X of the first layer is your taken from your dataset and then you pass each Y as the X of the next layer in the forward pass.
The dE/dY of the output layer is computed (either for softmax activation function and cross entropy error function or for linear activation function and sum of squared errors) as Y-T, where Y is the output of the network (shape = [num_instances, num_outputs]) and T (shape = [num_instances, num_outputs]) is the desired output. Then you can backpropagate, i.e. dE/dX of each layer is dE/dY of the previous layer.
Now you can use dE/dW and dE/db of each layer to update W and b.
Here is an example for C++: OpenANN.
Btw. you can compare the speed of instance-wise and batch-wise forward propagation:
In [1]: import timeit

In [2]: setup = """import numpy
   ...: W = numpy.random.rand(10, 5000)
   ...: X = numpy.random.rand(1000, 5000)"""

In [3]: timeit.timeit('[W.dot(x) for x in X]', setup=setup, number=10)
Out[3]: 0.5420958995819092

In [4]: timeit.timeit('X.dot(W.T)', setup=setup, number=10)
Out[4]: 0.22001314163208008


text:
Q: Change one word in lots of HTML pages with another word from a list of words I have about 2000 HTML pages (all pages have the same content except for the city name). I have the list of city names, and i need each page to have 1 city name.
How can I change the City name in each page?
city name list: birmingham
montgomery
mobile
huntsville
tuscaloosa
hoover.. etc...
and I need to make each page like this:
title: birmingham,
next page;
title: montgomery,
and so on.
I need the change to happen in the title:Example (City Name)
and in 2 other h2 tags.
Thank you very much for your attention!

A: Update:
This script is for the existing files. It will hierarchically find all the index.html files in the current directory and will replace the "string_to_replace" string with that file's parent directory's name which is the city name in your case. It will also make that name capitalized before the replacement.
Feel free to update the tamplate_string variable value in the script so that it fits to the string which is used in your index.html files in place of the city name.
#!/bin/bash
template_string="string_to_replace"
current_dir=`pwd`
find $current_dir -name 'index.html' | while read file; do
    dir=`basename $(dirname "$file")`
    city="$(tr '[:lower:]' '[:upper:]' <<< ${dir:0:1})${dir:1}"
    sed -i -e 's/'$template_string'/'$city'/g' $file
done

Initial answer:
My initial suggestion is to use a bash script (e.g. script.sh) similar to this:
 #!/bin/bash
    file="./cities.txt"
    template="./template.html"
    template_string="string_to_replace"
    while IFS= read line
    do
            cp $template $line".html"
            sed -i -e 's/'$template_string'/'$line'/g' $line".html"
            echo "$line"
    done <"$file"

and run it from bash terminal:
$ source script.sh

What you need to have:

*

*cities.txt with cities names list, e.g.
London
Yerevan
Berlin

*template.html with the html template you need to have in each file. Make sure the city name is set as "string_to_replace" in it, e.g. title: string_to_replace
Since you did not mention anything related to the files names, the files will be named like London.html, Yerevan.html,...
Let me know in case you don't need to create new files, and need to make replacement in the existing ones. In this case we'll need to update the script a bit after you tell me how you know which string is going to be used in the exact file.


text:
Q: Enum value doesn't show EnumMember value on razor page ASP.NET Core 3.1 I have a Razor page and on that page I show data in a JavaScript datatable. I tried to show enum value as a string, but I don't get the correct string representation for my enum value.
Startup.cs
services.AddRazorPages().AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreNullValues = true;
        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
    });

Enums.cs
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Operation
{
    [EnumMember(Value = "None")]
    None,
    [EnumMember(Value = "Send e-mail")]
    SendEmail,
    [EnumMember(Value = "Download file")]
    DownloadFile
}

Result.cs
public class Result
    {
        public int Id { get; set; }

        public DateTime StartDate { get; set; }

        public DateTime EndDate { get; set; }

        [Column(TypeName = "smallint")]
        [JsonConverter(typeof(JsonStringEnumConverter))]
        public Operation Operation { get; set; }

        public bool Success { get; set; }
    }

ResultPage
public IActionResult OnPost()
{
     var resultData = _dbContext.Results.ToList();

     var jsonData = new {recordsTotal = resultData.Count(), data = resultData
};

     return new JsonResult(jsonData);
}

ResultView
Here is just script for JS datatable
<script>
    $(document).ready(function () {
        $('#resultDatatable').dataTable({
            "processing": true,
            "serverSide": true,
            "filter": true,
            "ajax": {
                url: "/Result",
                type: 'POST',
                headers: { 'RequestVerificationToken': $('@Html.AntiForgeryToken()').val() }
            },
            "columns": [
                { "data": "id", "name": "Id", "autoWidth": true, "visible": false},
                {
                    "data": "startDate", "name": "Start date", "autoWidth": true, "render": function (d) {
                        return moment(d).format("YYYY/MM/DD");}
                },
                {
                    "data": "endDate", "name": "End date", "autoWidth": true, "render": function(d) {
                        return moment(d).format("YYYY/MM/DD");}
                },
                { "data": "operation", "name": "Operation", "autoWidth": true },
                { "data": "success", "name": "Success", "autoWidth": true }
            ]
        });
    });
</script>

When I call this I get the correct enum representation from the EnumMember value:
var test = JsonConvert.SerializeObject(resultData); //SendEmail -> "Send e-mail"

But, when I:
return new JsonResult(resultData);      //SendEmail -> "SendEMail"

I tried with this solution ASP.NET MVC Core API Serialize Enums to String but I don't get the expected results.

A: After 3 hours struggling I found that:
Serialization of enums as strings is supported by System.Text.Json.Serialization.JsonStringEnumConverter, however renaming via attributes is not implemented.
So I used accepted answer from this link, where I used NewtosoftJson instead built in System.Text.Json.
services.AddRazorPages().AddNewtonsoftJson(option =>
            {
                option.SerializerSettings.Converters.Add(new StringEnumConverter());
                option.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            });

Also I applied attribute over enum [JsonConverter(typeof(StringEnumConverter))]
[JsonConverter(typeof(StringEnumConverter))]
public enum Operation
{
    [EnumMember(Value = "None")]
    None,
    [EnumMember(Value = "Send e-mail")]
    SendEmail,
    [EnumMember(Value = "Download file")]
    DownloadFile
}

Now I have expected enum string value on my page.
deserialize json with array of enum