text:
Q: How to avoid floods like this? Instead of describing what's happening I'll post a screenshot of Apache's server-status page:
Screenshot
It is a Nigerian IP.
I'm having this problem for years now and I never found a viable solution except banning the attacker's IP and waiting for the jerk to return via another one.
Here's a bit of further explanation. The site is custom developed and that download page is only accessible if the user is logged into the site, otherwise a redirection to the login page is served. If the user's logged it serves quite a big file. But, after serving it once, the site has sort of a RapidShare like policy, meaning that the user has to wait. So the second time it is accessed it'll only serve an error message telling the user to wait. However it looks like the attacker somehow succeeds in opening a connection and then another one and then yet another one, until MySQL on my server chokes up and starts throwing errors.
If this kind of attack is a known one, has a name and there are known solutions on how to avoid it redirect me. Any feedback or ideas are very welcome because I'm slowly going crazy here.

A: Since this is a custom developed app, would it be correct that you have the ability to change it?  If so, maybe the following suggestions would help:

*

*Use Captcha - (another link) on your login page to prevent a robotic process from taking down your server.

*Change the code so that it only allows two connections per IP per user login.  Don't redirect the user, just dump any connection greater than 2.  If you allow 2 connections, that should help in the case that something happened on the client's end that has killed connection #1.

A: There are afew approaches that you can use:
One specific tool that is setup to help in situations like this is mod_evasive:
You can block along the following criterion:

*

*Requesting the same page more than a few times per second

*Making more than 50 concurrent requests on the same child per second

*Making any requests while temporarily blacklisted (on a blocking list)

Another alternative would be to roll something on your own that scrapes the apache status from the command line (very easy, I've done it before), and then sorts by IP and URL, then you drop it,
Otherwise I think the only other 'good' solution is similar to the one mentioned above, to log IP activity to that page over say, 5 minutes, and then if you they cross over that threshold, have a script scrape through and drop that in the firewall.  You also don't have to block it necessary, you could do something like the following, which would prevent new connections after 30 attempts (adjust as appropriate for the correct eth device):
iptables -I INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set
iptables -I INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds 5 --hitcount 20 -j DROP

A: I am a bit confused as to why this "attacker" would want to download the file more than once. However there are a few ways to limit this:

*

*Create a process in your code that adds the IP address to a file or database that marks that it is currently downloading a file, and prevent access if it is currently in download or based on time (eg, one download every 5 minutes).

*Install an apache module to limit connections per IP address. Mod_limitipconn seems designed for this.

I think mod_limitipconn seems like it would fix your current issue but since this is a problem to begin with, I think there might be an issue with the code logic you have running on the site.

A: It sounds like your app may be adding the time delay record after the file completes rather than when starting, allowing parallel downloads. While it may be possible to work around on the server, it'd be better to fix the app. As you indicated it was just a delay rather than a once-per-file, have you considered moving that status recording to before sending the file? The window for opening additional downloads would be reduced (or eliminated depending on how you code it), and as a side benefit you could likely release the database connection back to the pool (or close it if you're not pooling) rather than either keeping it open until after completion for recording the completion.


text:
Q: How can I rename a directory name replacing the first letter of each word in the name string to uppercase? On a Windows 10 computer, I've been using free utilities like PFrank tool and Power Toys PowerRenamer. With PFrank I was able to change the case of each word in the name of the filenames to uppercase, but it won't change the directory names.
Please do you know of a command or script in Powershell, CMD or BASH (using Windows subsystem linux), to accomplish that? or a tool (preferable open source), that can do that. Since I already change the filenames I want to do this recursively on the directory names only.
Thanks.

A: You can use the Kernel32 method MoveFile to rename files and directories without the need to rename it twice.
The following code renames files and directories using the respective properties for the new name (depending on the type).

The method 'MoveFile' actually triggers the same process as doing it interactively using the Windows Explorer.

# "MoveFile" works for files and folders

# only add type once
if ($null -eq ('Win32.Kernel32' -as [type])) {
    # add method 'MoveFile from' kernel32.dll
    # https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefile
    $signature = @'
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool MoveFile(string lpExistingFileName, string lpNewFileName);
'@
    Add-Type -MemberDefinition $signature -Name 'Kernel32' -Namespace Win32
}

$dirPath = 'C:\temp\CaseTest'
Get-ChildItem -LiteralPath $dirPath -Recurse -Directory | ForEach-Object {
    $parentPath = $currentName = $fileExtension = $null

    if ($_ -is [System.IO.DirectoryInfo]) {
        # Directories
        $parentPath  = $_.Parent.FullName
        $currentName = $_.Name

    } elseif ($_ -is [System.IO.FileInfo]) {
        # Files
        $parentPath    = $_.Directory.FullName
        $currentName   = $_.BaseName
        $fileExtension = $_.Extension
    }

    if ($null -notin $currentName, $parentPath) {
        $newName =  @(
            [cultureinfo]::CurrentCulture.TextInfo.ToTitleCase($currentName.ToLower()),
            $fileExtension
        ) -join ''

        $newPath    = Join-Path -Path $parentPath -ChildPath $newName
        $moveResult = [Win32.Kernel32]::MoveFile($_.FullName, $newPath)

        if (-not $moveResult) {
            # 'MoveFile' returns only $false in case of errors,
            # so we have to build the respective exception.
            # This requires "SetLastError = true" in signature
            $win32Error     = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
            $win32Exception = [System.ComponentModel.Win32Exception]$win32Error
            Write-Error -Exception $win32Exception `
                -Message "$($win32Exception.Message) `"$($_.FullName)`""
        }
    }
}

A: Extending from my comment. It's simply this.
Update
Removed original long answer and replacing with the below to address your comment:
(Get-ChildItem -Path 'D:\Temp' -Directory -Recurse) -match 'src|dest' |
ForEach-Object {
    "Proccessing $($PSItem.FullName) to TitleCase"
    $renameItemTempSplat = @{
        Path     = $PSitem.FullName
        NewName  = "$((Get-Culture).Textinfo.ToTitleCase($PSitem.Name.ToLower()))1"
        #WhatIf   = $true
    }
    Rename-Item @renameItemTempSplat -PassThru |
    Rename-Item -NewName $($((Get-Culture).Textinfo.ToTitleCase($PSitem.Name.ToLower())) -replace '1')
}
(Get-ChildItem -Path 'D:\Temp' -Directory -Recurse) -match 'src|dest'
# Results
<#
Proccessing D:\Temp\dest to TitleCase
Proccessing D:\Temp\Destination to TitleCase
Proccessing D:\Temp\src to TitleCase

    Directory: D:\Temp

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         12-Oct-20     14:27                Dest
d-----         24-Jan-21     22:24                Destination
d-----         12-Oct-20     13:27                Src
#>

About WhatIf/Confirm

redpajama_set_name: RedPajamaStackExchange


text:
Q: python tensorflow import dll load failed I installed latest python 3.6.4 x64 version
and then installed tensorflow for cpu-only with pip3
C:\>pip3 install tensorflow

however when I tried to import tensorflow in python
it showed me the error below
I am sure that I have installed Microsoft Visual C++ 2015 Redistributable(x64)
so it wll not be the problem of dll msvcp140.dll lost
it say that "DLL load failed with error code -1073741795"
so what is exactly the problem here
i cannot find any other information about this error code
my os : windows 7 enterprise with service pack 1 / 64 bit / intel core i5 M 540
>>> import tensorflow
Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 571, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 571, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\site-packages\t
ensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Users\Alan\AppData\Local\Programs\Python\Python36\lib\importlib\__ini
t__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_probl
ems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

A: I got same problem with tensorflow1.6-CPU on win7 64bit(Intel Core 2 Duo Cpu T6670 2.2GHz)
After I found this, and it solved my problem.
Reference this issue: https://github.com/tensorflow/tensorflow/issues/17386
Re-installed by this tensorflow-1.6.0-cp36-cp36m-win_amd64.whl: https://github.com/fo40225/tensorflow-windows-wheel/tree/master/1.6.0/py36/CPU/sse2
Hope this .whl may help you.

A: I faced the same issue with tensorflow-1.12.0
what i did was :

*

*Install anaconda

*open anaconda prompt

*conda create -n tfp python=3.6

*activate tfp

*conda install tensorflow

*python

*Now check by importing tensorflow

the version i used was 3.6, but you can also try with 3.7
Hope it helps!

A: I downgraded tensorflow to 1.10.0 and it fixed the issue

A: Probably, your CPU does not have the instructions for AVX (needed for all tensorflow binaries since 1.6). You can check that with some tool like CPU-Z. If that is the case, you can donwload the correct wheel here (use SSE2 binaries):
tensorflow-windows-wheel

A: I had the same issue.
I upgraded pip version with:
python -m pip install --upgrade pip

also, downgraded with
pip install tensorflow==2.0

and it worked

A: ImportError: DLL load failed
for
windows 10
python 3.6
 pip install protobuf==3.6.0

or
pip3 install protobuf==3.6.0

A: I fixed it.
Spend days searching to fix them.
Installed tensorflow with pip install tensorflow-cpu
Updated visual C++ 2015-2019
The issue was because I didn't have nvidia graphics so that I should install with cpu version because I am using Radeon Vega 8 graphics.
Hope it helps.

A: I have tried different methods still it doesn't work then I apply this method it works for me.
STOP  you antivirus protection software for half hour then install anaconda,it works fine. 100%

A: If you use python 3.6.10 and tensorflow 2.1.0
Just follow this -
pip install tensorflow==2.0
It worked for me.

A: I had first Upgraded the Anaconda prompt
I had then used conda create -n tfp python=3.7
conda activate tfp
Then import the tensorflow

A: I faced the similar issue for tensorflow 2.0
First I uninstalled tensorflow using pip uninstall tensorflow (no need to uninstall tensorflow-estimator or tensorboard).
Then I reinstall using conda install tensorflow.

A: Never install the latest version of tensorflow it will raise an error
DLL file load error
pip install tensorflow

never run command on your computer as it not supports the tensorflow cpu
most of the latest version supports mostly gpu
so while installing install the lower version of the tensorflow
from my opininon the stable release of tensorflow  is tensorflow 1.5
make sure you uninstalled your tensorflow installed in your computer
pip uninstall tensorflow
After above step shutdown your pc and restart.Then only install tensorflow 1.5
command to install tensorflow version 1.5
pip install tensorflow==1.5

A: Install Microsoft Visual C++ 2019 Redistributable & reboot the PC, it will work with tensorflow 2.3.1 in python 3.7


text:
Q: accessing dynamically loaded elements in phantomjs I'm sending a page event:
page.sendEvent('click', 650, 430);
This clicks a link that dynamically loads an element over ajax. Is it too late to access this dynamically loaded element via page.evaluate? I can't seem to return anything whatsoever in anything dynamically created on the page.

A: So far the simplest dynamic way is to catch console messages, like described here http://code.google.com/p/phantomjs/wiki/Interface#Callbacks
page.onConsoleMessage = function(msg) {
    console.log(msg);
};

In case you want to send some binary data, then I would recommend to use some kind of pipe through injecting a custom script into the webpage.

A: Why don't you use window.setTimeout and take a snapshot using page.render? So your code would change to:
window.setTimeout(function() {
   page.sendEvent('click', 650, 430);
}, 5000);
window.setTimeout(function() {
   page.render('foo.png');
});

The time out will give the ajax call a chance to complete. The render will let you see what the page is supposed to look like when the ajax call is done.


text:
Q: How to add temporary columns to list of columns in the select statement in SQL Server? I have written the following code as shown below:
DECLARE @SQL nvarchar(max);
DECLARE @ColumnList nvarchar(max);
DECLARE @SampleTable nvarchar(max);

SET @SampleTable = 'dbo.CourseType' --HERE I'LL BE GIVING LIST OF TABLES

SELECT
    @ColumnList = (SELECT STUFF((SELECT N', ' + QOUTENAME(c.name)
                                 FROM sys.columns c
                                 INNER JOIN sys.objects o ON c.object_id = o.object_id
                                 WHERE o.name = @SampleTable
                                   AND c.name NOT IN ('ID', 'Number')
                                 ORDER BY c.column_id
                                 FOR XML PATH(''), TYPE).value('text()[1]', 'nvarchar(max)'), 1, 2, N''))

SELECT @ColumnList

From this script I'll get the list of all columns except columns ID, Number. Now what I want to do is that read this list of columns i.e [Name], [Description], [SortOrder], [BusinessName], [Obsolete] with some temporary columns listed below:
NULL AS EntityID,
NULL AS ModifiedBy,
NULL AS CreatedBy

The query result should look like this:
Name         Description                        SortOrder   BusinessMeaningName         Obsolete   EntityID    ModifiedBy    CreatedBy
Inviern      Cursos de Invierno de Pregrado         1       AcademicPeriodType.Invierno    0         NULL       NULL          NULL
Lectivo      Cursos Lectivos de Pregrado            0       AcademicPeriodType.Lectivo     0         NULL       NULL          NULL
Verano       Cursos de Verano de Pregrado           1       AcademicPeriodType.Verano      0         NULL       NULL          NULL

I know that I can do this directly by just selecting the names of columns with the temporary columns for one or two tables. But i have to do this for a large bunch of tables. I cant figure out a way to do this.
Now I don't know how to add EntityID, CreatedBy, ModifiedBy in the select statement. I've tried to do something like this.
SET @SQL = 'SELET '
            + @ColumnList
            + ' FROM ' + @SampleTable;
EXEC sp_executesql @SQL;

Can anyone help me out?

A: Just add the additional columns in your dynamic statement.
--Dynamic object should be declared like this
DECLARE @SampleSchema sysname = N'dbo',
        @SampleTable sysname = N'CourseType';

SET @SQL = N'SELECT ' +
           @ColumnList +
           N', NULL AS EntityID, NULL AS ModifiedBy, NULL AS CreatedBy' +
           N' FROM ' + QUOTENAME(@SampleSchema) + N'.' + QUOTENAME(@SampleTable) + N';';
EXEC sys.sp_executesql @SQL;

Also, a object's name can only be 255 characters long, so don't use a nvarchar(MAX) for its datatype. Declare @SampleTable as a sysname.


text:
Q: How to assign all properties of a parameter that satisfies an interface to a class that implements the interface in Typescript? I have interface CommunityProps and class Community implements CommunityProps. I would like to do something like this:
class Community implements CommunityProps {
   // property declarations
   constructor(props: CommunityProps) {
      Object.assign(this, props)
   }
}

But Object.assign is not typesafe. I am stuck listing out all 10-15 properties in 1) the interface, 2) the class property declarations, and 3) one-by-one assigning the class properties to props.propName where props is passed into the constructor, like this:
interface CommunityProps {
   prop1: string
   prop2: number
   prop3: boolean
}
class Community implements CommunityProps {
   prop1: string
   prop2: number
   prop3: boolean
   constructor(props: CommunityProps) {
      this.prop1 = props.prop1
      this.prop2 = props.prop2
      this.prop3 = props.prop3
   }
}

I have about 10 such classes I need to make, each with a different set of properties. This will leave me with about 450 lines of code just to get these classes working. Surely there is a better way to do what I am trying to do?
The best alternative I have found is giving the class a single property which is of the same type as the interface, and remove the implements CommunityProps from the class declaration:
class Community {
   info: CommunityProps
   constructor(props: CommunityProps) {
      this.info = props
   }
}

But I would really, really like to be able to access these properties without having to use .info.prop1


text:
Q: Pages docs from MacBookPro not working in MacBook Air As the title says, I have a bunch of .pages docs from my previous MacBook Pro (running El Capitan), and they are not opening with the pages app on my MacBook Air (running Yosemite).
The error message being displayed is: "Doc_Name.pages" can't be opened.
Below is the screenshot:

They are opening in the previews app.  But, I want to open and edit them in the pages app.

A: A list of steps to take in order to analyze and resolve the problems:
Does the pages app open at all? If not, it could be damaged.
Are you copying the app to the external HDD, and then back to your Macbook Air?
If so, that's probably destroying various file permissions within the app bundle.

*

*Can you redownload it from the Mac App store instead? That would be easiest.

*If not, try zipping the app on your work computer before copying to your personal computer.
Open the Applications folder on your MBP, right click Pages.app and click Compress. This will take a while, and you'll end up with a Pages.app.zip.
Then copy the Pages.app.zip file to your HDD, then to your Macbook Air.
Unzip it and that should work!
Are you not opening the files in the right app?
Try opening the Pages app first, and from there navigating to file -> Open, and then choosing your file.
Are the files corrupt?

*

*Do you have copies on your work computer which still open in Pages?

*Can you copy these to your personal computer without using the external HDD? (hint, try airdrop, or a HFS+ formatted USB Stick.)
People always say NTFS drivers for OS X work well, but I personally have lost data using them, so I don't trust them.

File repair
.pages files are actually zip files which contain all the images and text within the Pages document. If they wont open at all, which I suspect because preview should open them, you could try following these instructions to repair the files:

*

*Copy all the affected files to a folder on your computer. Open this folder in Finder.

*Type Command+space, type in Terminal and press Enter. This should open Terminal.

*In Terminal, type in cd (including the trailing space). Then, drag the little folder icon from the title bar of the Finder window into Terminal.

*The terminal should see cd ~/yourname/directorywithyourfiles/somethingelse/. Press Enter.

*Then type in zip -F 'filename' --out 'filenamefixed', where filename is the name of one of your documents.

Probably clearer instructions here.
http://computers.tutsplus.com/tutorials/how-to-repair-damaged-zip-files-with-terminal--mac-49294


text:
Q: Ecto preload and join nested models Here is the code:
query = from(p in Tree,
     where: p.name == ^tree,
     where: p.user_id == ^user_id,
      preload: [kw: :keyo]
      )
     data = Repo.all(query)

This works but returns data in this structure like this:
{
 Kw: [
  {user_id: 1, keyo_id: 2, keyo: {some_keyo_thing: 5},
  {user_id: 1, keyo_id: 32, keyo: {#keyo data}
  ...
  ]
}

Anyway to get merged output of kw/keyo data in the query above? I would like result to be:
[
  {user_id: 1, keyo_id: 2, some_keyo_thing: 5,
  {user_id: 1, keyo_id: 32, , some_keyo_thing: 3
  ...
  ]

A: Instead of using preload, you're probably better off going with an explicit join, and then selecting the fields you want returned
query = from(p in Tree,
             join: kw in Kw, on: kw.tree_id == p.id,
             join: k in Keyo, on: k.kw_id == kw.id,
             where: p.name == ^tree,
             where: p.user_id == ^user_id,
             select: %{ user_id: p.user_id, keyo_id: k.id, some_keyo_thing: k.some_keyo_thing }
        )

Repo.all(query)

It's a little more verbose, but gives you a lot more control. I've guess at your model names for kw and keyo, so correct as necessary but this should work


text:
Q: I want to expand.grid from each row of a matrix when the matrix could have variable number of rows

myMatrix <- matrix(c(1,2,3,4,5,6),2,3, byrow=T) # line 1

exp.myMatrix <- function(myMatrix) { # line 2
  for (rownum in 1:nrow(myMatrix)) assign(paste("R",rownum, sep=""), myMatrix[rownum,]) # line 3
  Combinations <- do.call(expand.grid, lapply(ls(pattern='^R\\d$'), get)) # line 4
  rm(list=ls(pattern='^R\\d$')) # line 5
  return(Combinations) # line 6
} # line 7

Combinations <- exp.myMatrix(myMatrix) # line 8

The above code gives error: "Error in FUN(X[[i]], ...) : object 'R1' not found".
However, when I do not use the function and run only lines 1, 3, 4, 5, I do not get any error. But I need to pass myMatrix through a function as the matrix would have variable number of rows. Also note that I need to run line 5 as I need to clear the variables for the next matrix which could have lesser number of rows than the previous one.

A: You must rather use:
do.call(expand.grid, split(myMatrix, rep(1:nrow(myMatrix), ncol(myMatrix))))

#  1 2
#1 1 4
#2 2 4
#3 3 4
#4 1 5
#5 2 5
#6 3 5
#7 1 6
#8 2 6
#9 3 6


text:
Q: CSS: DIVs overlaping, z-index doesn't fix This is my html:

This is my css:
.game {
  width: 807px;
  height: 607px;
  filter: drop-shadow(10px 10px 32px black) opacity(50%) grayscale(80%);
  margin: auto;
  margin-left: -220px;
  margin-right: -220px;
  transform: scale(0.7,0.7);
  transition: 150ms ease-in-out;
  position: relative;
  z-index: 99;
}
.game#csgo {
  background: url('game-csgo.png') no-repeat rgba(0,255,0,0.5);
  background-size: 100%;
}
.game#minecraft {
  background: url('game-minecraft.png') no-repeat rgba(0,255,0,0.5);
  background-size: 100%;
}
.game#lineage {
  background: url('game-l2.png') no-repeat rgba(0,255,0,0.5);
  background-size: 100%;
}
.game.hover {
  filter: drop-shadow(20px 20px 64px black) opacity(100%) grayscale(0%);
  transform: scale(1,1);
  transition: 150ms ease-in-out;
}
.game-handle {
  width: 411px;
  height: 525px;
  cursor: pointer;
  position: fixed;
  bottom: 0;
  left: 198px;
  z-index: 99999;
  background: rgba(255,0,0,1);
}

jQuery script to toggle .hover class:
jQuery(function() {
  jQuery('.game-handle').mouseenter(function() {
    jQuery(this).parent('.game').addClass('hover',0);
  }).mouseleave(function() {
    jQuery(this).parent('.game').removeClass('hover',0);
  });
});

And the thing is that the RED parts are the things that I want to register mouseover events with. But the divs next to the previous ones, going from left-to-right, overlap the RED areas too! :( The GREEN parts are the divs holding the backgrounds itself. Any idea how to bring all the RED divs into the absolute front?
(The only reason why I do this this way is because the custommer wants to have "cards" that have thing hanging from them like the sword,gun,arm and stuff, and then the main div has to be bigger in width and have negative margin from both sides)
Screen:

Fiddle example: https://jsfiddle.net/9yy2csvd/
The Problem:

cursor is on the red part but the green from div on the right overlaps it (no mouseenter event triggered). So you have to go more to the left with cursor so you only touch the red part (and trigger the event). But I need it that the red part is on top of all the green,
Each background of divs with class .game look like this:

I need that only when I move the mouse cursor over the "card" itself, not the transparent background around it (including parts of the picture that are sticking out of the "card"), the event is triggered.

A: This is complicated.
When z-index typically works?
z-index works inside a scope of closest parent with z-index. In other words, you can never have child higher then other parents when if this child's parent has set z-index.
The chase
From my personal tests I concluded that you indeed can achieve desired effect, as long as you will not use any of the following:

*

*Any z-index for parent

*Any transform for parent

*Any filter for parent

Turns out every property from the list above will break the result.
Example
There're many variables for when z-index works or doesn't work as you'd expect. I prepared a test environment for you to try out. Notice when it breaks and what property you can apply to fix it.

$(function() {
  $('body').addClass('child-relative'); // Simplest combination when it works

  $('label input').click(function() {
    var className = $(this).data('class');
    $('body').toggleClass(className);
  }).each(function() {
    var className = $(this).data('class');
    $(this).attr({
      checked: $('body').hasClass(className)
    });
  });
});
/*/ "Works" = .child is above all .parent-s /*/

/*/ Basic styles /*/
.parent {
  outline: 2px dotted blue;
  background: rgba(0, 0, 255, .2);
  width: 200px;
  height: 200px;
  float: left;

  margin-right: -50px;
}

.child {
  background: yellow;
  outline: 2px dashed red;
  width: 150px;
  height: 150px;
  margin: 25px;
}

/*/ Variables /*/
.parent-relative .parent {
  /* Works when .child has position: relative/absolute; AND z-index > 0 */
  position: relative;
}

.parent-z-index .parent {
  /* Never works */
  z-index: 0;
}

.parent-transform .parent {
  /* Never works */
  transform: scale(1);
}

.parent-transform-rotate .parent {
  /* Never works */
  transform: rotate(360deg);
}

.parent-filter .parent {
  /* Never works */
  filter: opacity(100%);
}

.child-relative .child {
  /* Works when .parent has only position: static; OR when .child has z-index as well */
  position: relative;
}

.child-z-index .child {
  /* Works when .parent has position: static; OR position: relative; WITHOUT z-index */
  z-index: 1;
}

.child-transform .child {
  /* Doesn't matter */
  transform: scale(1);
}

.child-transform-rotate .child {
  /* Doesn't matter */
  transform: rotate(360deg);
}

.child-filter .child {
  /* Doesn't matter */
  filter: opacity(100%);
}

/*/ Ignore following code /*/
h2 {
  margin-bottom: 0;
}
.parent {
  margin-top: 20px;
}
.controls .bad {
  color: red;
}

.parent { }

    <input type="checkbox" data-class="parent-relative">
    position: relative;

    <input type="checkbox" data-class="parent-z-index">
    z-index: 0;

    <input type="checkbox" data-class="parent-transform">
    transform: scale(1);

    <input type="checkbox" data-class="parent-transform-rotate">
    rotate: scale(360deg);

    <input type="checkbox" data-class="parent-filter">
    filter: opacity(100%);

.child { }

    <input type="checkbox" data-class="child-relative">
    position: relative;

    <input type="checkbox" data-class="child-z-index">
    z-index: 1;

    <input type="checkbox" data-class="child-transform">
    transform: scale(1);

    <input type="checkbox" data-class="child-transform-rotate">
    rotate: scale(360deg);

    <input type="checkbox" data-class="child-filter">
    filter: opacity(100%);

    Child 1

    Child 2

    Child 3

Keep in mind that I have tested this only in Chrome on Windows. Perhaps in other environments properties marked as .bad will work without issue. I'll leave detailed tests for you to perform! ;-)
Have a nice day!
~Wiktor


text:
Q: Do potted flowers count towards beehives or just planted ones? The beehive's description states it is most efficient with at least 8 flowers within the hive's range. Does this count potted flowers? I'm guessing it only means flowers planted from a forester but I cannot find details on either.

A: I found my answer. Turns out you can right-click the beehives and it'll tell you how many flowers are in range.


text:
Q: BitBake: Can we use DEPENDS with package name? From BitBake User Manual, I know that when using RDEPENDS, we should always use the variable in a form with an attached package name, for example: RDEPENDS_${PN} += "a"
Can we do the same for DEPENDS variable ? Like: DEPENDS_${PN} += "b"
I got this question because when I put this into my recipe, BitBake do not raise any error, but my build sometime failed due to it cannot handle the dependecies.

A: DEPENDS is about compile time dependencies. The results of a single compile can be used in multiple packages so making the variable package-specific is not possible: DEPENDS is always used for the whole recipe and cannot be postfixed with a packagename.


text:
Q: Generalizations of the Gauss circle problem The Wikipedia article on the Gauss circle problem states that, if there are $N(r)$ lattice points of radius less than $r$ from the origin, then we know that $|E(r)|=|N(r)-\pi r^2|=O(r^{131/208})$.
Do we know whether this bound holds if we put the center of the circle at an arbitrary point in the plane rather than at a lattice point?


text:
Q: Shortest path GENERATION with exactly k edges in a directed and weighted graph (edit: visit each node only once) This following code is from https://www.geeksforgeeks.org/shortest-path-exactly-k-edges-directed-weighted-graph/. All credit goes to PranchalK.
I am dealing with the problem of generating k-edge shortest path. The code below gives the shortest "distance" with pre-defined k.
However, I will need the "path"
For the code below the path seems to be:
0 --> 2 --> 3 .
Edit: Ajay's code solves this problem. However, each node needs to be visited only once. I haven't mentioned this in the original question. I have included an extra data set to test it.
# Python3 program to find shortest path
# with exactly k edges

# Define number of vertices in the graph
# and inifinite value

# A naive recursive function to count
# walks from u to v with k edges
def shortestPath(graph, u, v, k):
    V = 4
    INF = 999999999999

    # Base cases
    if k == 0 and u == v:
        return 0
    if k == 1 and graph[u][v] != INF:
        return graph[u][v]
    if k <= 0:
        return INF

# Initialize result
    res = INF

# Go to all adjacents of u and recur
    for i in range(V):
        if graph[u][i] != INF and u != i and v != i:
            rec_res = shortestPath(graph, i, v, k - 1)
            if rec_res != INF:
                res = min(res, graph[u][i] + rec_res)
    return res

# Driver Code
if __name__ == '__main__':
    INF = 999999999999

    # Let us create the graph shown
    # in above diagram
    graph = [[0, 10, 3, 2],
            [INF, 0, INF, 7],
            [INF, INF, 0, 6],
            [INF, INF, INF, 0]]
    u = 0
    v = 3
    k = 2
    print("Weight of the shortest path is",
            shortestPath(graph, u, v, k))

# This code is contributed by PranchalK

Expected outcome is:
[0,2,3]
0 is the starting node, 3 is the ending node. The number of edges is 2. The path is 0 --> 2 --> 3
Edit: Ajay's answer is very very close. However, each node needs to be visited only once. I am sorry that I haven't mentioned this originally. Here is a bigger data to test.
    graph = [[0, 10, 3, 2,4,1],
            [1, 0, 3, 7,4,1],
            [2, 8, 0, 6,0,1],
            [4, 1, 3, 0,1,2],
            [3, 1, 2, 2,4,1],
            [7, 1, 3, 0,3,3]]

Weight of the shortest path is 14
Shortest path is  [0, 2, 0, 2, 3]

A: Store the node which yields min. sum of weight for every edge length < k.
def shortestPath(graph, u, v, k):
    V = 4
    INF = 999999999999

    # Base cases
    if k == 0 and u == v:
        return 0,[]
    if k == 1 and graph[u][v] != INF:
        return graph[u][v],[]
    if k <= 0:
        return INF,[]

# Initialize result
    res = INF

# Go to all adjacents of u and recur
    k_minus_one_path = []
    least_sum_node = None
    for i in range(V):
        if graph[u][i] != INF and u != i and v != i:
            rec_res, path = shortestPath(graph, i, v, k - 1)
            if rec_res != INF:
                if res > graph[u][i] + rec_res:
                    k_minus_one_path = path
                    least_sum_node = i
                    res = graph[u][i] + rec_res

    if least_sum_node is not None:
        k_minus_one_path.insert(0, least_sum_node)

    k_path = k_minus_one_path

    return res,k_path

# Driver Code
if __name__ == '__main__':
    INF = 999999999999

    # Let us create the graph shown
    # in above diagram
    graph = [[0, 10, 3, 2],
            [INF, 0, INF, 7],
            [INF, INF, 0, 6],
            [INF, INF, INF, 0]]
    u = 0
    v = 3
    k = 2
    weight, path = shortestPath(graph, u, v, k)
    if weight != INF:
        path.insert(0, u)  # source
        path.append(v)  # Destination
    print("Weight of the shortest path is", weight)
    print("Shortest path is ", path)

A: By checking the existing NetworkX algorithms in Shortest Paths it seems none of these allows to directly obtain all simple paths between two nodes and along with the corresponding weights.
So it will be necessary to do both things separately:

*

*Compute all paths between two given nodes, and keep only those of length k

*And then compute the weight of each of these indivudual paths and select the one of less weight

 General Solution
def shortest_path_k_edges(graph, source, target, k):
    '''
    Computes the shortest simple path with
    exactly k edges of a weighted graph
    between the specified source and target
    ----
    graph: np.array
       Adjacency matrix for the graph
    source: int
       Source node
    target: int
       Target node
    k: int
       Amount of edges of the path
    ----
    Returns:
       Shortest k length path
    '''
    import networkx as nx
    # Builds graph from the adjacency matrix
    g = nx.from_numpy_array(graph)
    # Generates all simple paths (no repeated nodes)
    # in the graph from source to target
    all_paths = nx.all_simple_paths(g, source, target)
    # Keeps only paths with k edges
    paths = [i for i in all_paths if len(i) == k+1]
    # Compute the weights of each of the paths
    # using the adjacency matrix
    weights = [sum(graph[i[j], i[j+1]]
                   for j in range(len(i)-1))
               for i in paths]
    # Return path of minimum weight, and
    # corresponding weight
    min_w = min(weights)
    return paths[weights.index(min_w)], min_w

 Output
Lets check the results with the proposed parameters:
u = 0
v = 3
k = 2
INF = 999999999999
import numpy as np
graph = np.array(
       [[0, 10, 3, 2],
        [INF, 0, INF, 7],
        [INF, INF, 0, 6],
        [INF, INF, INF, 0]])

path, weight = shortest_path_k_edges(graph, u, v, k)

print(path)
# [0, 2, 3]

print(weight)
# 9


text:
Q: Help with c++ template templates Ok, so I wrote an stl-like algorithm called cartesian_product. For those who don't know, the cartesian product is every possible pair of elements from two sets. So the cartesian product of {1, 2, 3} and {10, 20, 30} is
{(1,10), (1,20), (1,30), (2,10), (2,20), (2,30), (3,10), (3,20), (3,30)}
So the function looks like
template <typename InIt1, typename InIt2, typename OutIt>
void
cartesian_product(InIt1 first1, InIt1 last1, InIt2 first2, InIt2 last2, OutIt out)
{
    for (; first1 != last1; ++first1)
        for (InIt2 it = first2; it != last2; ++it)
            *out++ = std::make_pair(*first1, *it);
}

There aren't template typedefs, so I made a traits class to hold the type that
the output iterator is from:
template <typename ObjA, typename ObjB, template <typename> class Container>
struct cartesian_product_traits
{
    typedef Container<std::pair<ObjA, ObjB> > type;
};

So then I can say:
typedef cartesian_product_traits<int, int, std::vector>::type IntPairList;
IntPairList my_list;
cartesian_product(v1.begin(), v1.end(),
                  v2.begin(), v2.end(),
                  std::back_inserter(my_list);

but this doesn't seem to compile. I get a nice error:
error C3201: the template parameter list for class template 'std::vector' does not match the template parameter list for template parameter 'Container'

So I'm stumped. How do I get this to work?

A: The template parameter list for vector isn't just one element, it takes two:
template < class T, class Allocator = allocator<T> > class vector

so in order to accept vector, you need to have a template template parameter with two blanks:
template <typename ObjA, typename ObjB, template <typename, typename> class Container>
struct cartesian_product_traits

Edited: cut some advice, misread your code.
The way to do this properly would be to use a variadic macro on the template template parameter:
template <typename ObjA, typename ObjB, template <typename ...> class Container>
struct cartesian_product_traits

But that's far away from being a standard. If it were my code, I'd probably just have the consumers pound out the full template:
std::vector< std::pair<int, int> >

is shorter than
cartesian_product_traits<int, int, vector>

and the latter would only help if the definition for a Cartesian product changed.

A: std::vector's template is actually quite complex (with optional template parameters for allocators &c) -- and other containers in the stdlib aren't any simpler either. In your shoes, I'd make the third parameter of cartesian_product_traits into a plain typename PairsContainer and depend on the caller to go to the small trouble of passing it as a suitable container of pairs.


text:
Q: #include files not including (c++) I'm having a problem with #including files in C++. When I try to compile the following code
#ifndef TILE_H_INCLUDED
#define TILE_H_INCLUDED
#include "location.h"
#include "Thing.h"
#include "Container.h"
#include <string>
using namespace std;

class Tile              //VIRTUAL CLASS
{
protected:
    Container onTile;   //holds objects that are on the tile
    Location * loc;     //location
    Tile* N;            //links to Tiles of that direction (null if nothing)
    Tile* E;
    Tile* S;
    Tile* W;
public:
//no constructor because superclass?
//loc can't move
//actions
bool placeOnTile(Thing * i){return onTile.addItem(i);}
    //put a thing on the tile (on the floor)
Thing* takeFrmTile(int i){return onTile.movItem(i);}
    //take a thing from the tile (from the floor)
Thing* access(int i) {return onTile.getItem(i);}
    //gets an item, but doesn't move it (for like, flipping switches)

//direction setters/getters
void setLoc(Location* i){loc = i;}
void setN(Tile* i){N = i;}
void setE(Tile* i){E = i;}
void setS(Tile* i){S = i;}
void setW(Tile* i){W = i;}
Location* getLoc(){return loc;}
Tile* getN(){return N;}
Tile* getE(){return E;}
Tile* getS(){return S;}
Tile* getW(){return W;}

//displays
void dispOnTile(){onTile.allDisplay();}
void dispSingle(int i){onTile.singleDisplay(i);}
};

I get the error message that "Container" and "Thing" are not defined. Why is this? The #includes look to me like they are coded correctly, and they've worked in the past. I assumed it might be an issue of the #included files being not end-bracketed correctly or not using the same namespace, but they are ended correctly (with a }; ) and they are using the standard namespace. What's up? I can't find an answer and I know it's got to be something simple. For the record, the #included files are below:
    #ifndef CONTAINER_H_INCLUDED
#define CONTAINER_H_INCLUDED
#include "Thing.h"
using namespace std;

class Container
{
private:
    Thing ** contents;  //array of pointers to Things
    int numItems;       //count item
    int maxSize;        //maxSize

public:
    //constructor
    Container(int i) {contents = new Thing*[i]; numItems = 0; maxSize=i;}
        //sets num of items (for set-size bags)
    Container() {contents = new Thing*[100]; numItems = 0; maxSize=100;}
        //creates array of things
    ~Container() {delete contents;}  //cleanup

//actions
bool addItem(Thing* th);    //adds item to bag (really just rereferences the pointer)
bool rmvItem(int i);        //removes item in array pos i
Thing* getItem(int i);      //returns a pointer to item at array pos i
Thing* movItem(int i);      //moves an item (deletes it and returns it)

//construction tools
void setMax(int i){delete contents; contents = new Thing*[i];}

//displays
void allDisplay();           //displays entire contents of container, numerated
void singleDisplay(int i);   //displays content item i

};

#endif // CONTAINER_H_INCLUDED

    #ifndef LOCATION_H_INCLUDED
#define LOCATION_H_INCLUDED
#include <string>
#include <sstream>
#include "Tile.h"
using namespace std;

class Location  //stores xy coordinates of something
{
int x;   //0 is NOT on map
int y;
Tile* ti;   //Locations contain pointers to tiles
public:
//constructors (mainly for debug)
Location(){x=y=0;}  //put object OUT OF MAP
Location(int ix, int iy){x=ix;y=iy;} //put object AT loc on map

//setters
void setX(int ix){x=ix;} //sets x
void setY(int iy){y=iy;} //sets y
void setT(Tile*i){ti=i;} //sets Tile

//getters
int getX() {return x;}
int getY() {return y;}
string getloc()     //return location as a string, separated by a comma
{
    ostringstream locxy;    //create stringstream obj to handle input
    locxy << getX() << "," << getY() << ". ";   //put x, space, y into stringstream
    string locret = locxy.str();        //convert stringstream to string
    return locret;                      //return string
    }
};

#endif // LOCATION_H_INCLUDED

    #ifndef THING_H_INCLUDED
#define THING_H_INCLUDED
#include <string>
#include "location.h"
using namespace std;

class Thing             //superclass that will be the base for objects
{
protected:
    Location * loc;     //location (in or out of map)
    string name;        //name
    string desc;        //description
    bool deletable;     //deletable (for undestructible items)
    bool takeable;      //if you can put it in your inv
    bool hasInv;        //returns true if the item has an inventory
public:
//constructor/destructor (debug only)
Thing() //sets initial values
    {loc = new Location(0, 0);
    name = "Uninitialized";
    deletable = takeable = true;
    }
Thing(int ix, int iy)  //sets location
    {loc = new Location(ix, iy);
    name = "Uninitialized";
    deletable = takeable = false;}
~Thing() {delete loc;}              //deletes allocated data

//getters
Location* getLoc() {return loc;}    //returns the location
string getDesc(){return desc;}      //returns the description
bool getDel(){return deletable;}    //returns deletable status
bool getTake(){return takeable;}    //returns takeable status
string getName(){return name;}      //returns name
string dispLoc(){return loc->getloc();} //displays location

//setters
void setName(string s){name = s;}   //sets name
void setDel(bool b){deletable = b;} //sets deletability
void setDesc(string d) {desc = d;}  //sets desc
void setLoc(Location* l) {loc = l;} //sets loc
void setTake(bool b){takeable = b;} //sets takeability

//accessors
};

#endif // THING_H_INCLUDED

A: I believe this is because you have recursive dependincies. That is, your classes all depend on each other, which means that at some point one of the classes will not be able to compile, because in order to get compiled it will need declaration of a class, but, it will not be able to find the declaration, because it is in the header file that is already up there in the stack of "#include" and thus because of guarding "#ifdef" becomes empty.
To give you the example.
To compile Tile, you need declaration of Location, so, naturally, you #include "location.h". But, to compile declaration of Location, you need declaration of Tile, so, you #include "Tile.h". But Tile.h has been #include-ed already, so there is no declaration for it!
The way to fight such circular dependencies is to use incomplete class declaration. For example, instead of including location.h into Tile.h, write
class Location;

class Tile
{
    Location* loc;
}

This works as long as Location is only used to declare a pointer or reference and no members of Location class are accessed.
Then, in you 'Tile.c' file you can #include "location.h"  and allow your inplementation of Tile methods access to Location members.

A: You have an include-loop

*

*Tile.h includes

*

*location.h

*Thing.h

*Container.h

*Container.h includes Thing.h

*Thing.h includes location.h

*location.h includes Tile.h
Oops.
So let us say in the .cpp, the first to be included is Container.h. Then that includes Thing.h before it declares anything. Thing.h in turn includes location.h before it declares anything. Then that includes Tile.h before it declares anything. In Tile.h, all the include guards make the recursive includes no-ops.
And thus in Tile.h, Thing and Container are unknown.


text:
Q: When should we assign a value to a new variable? Given the following code:
AND (myTable.field_1 IN ('" . implode("','", $myObj->userStatus) . "')
  OR myTable.field_2 IN ('" . implode("','", $myObj->userStatus) . "')
  OR myTable.field_3 IN ('" . implode("','", $myObj->userStatus) . "'))";

What is the BEST practice and WHY:
1) Use as it is. (Ugly for reading but does NOT create a new variable that will be read-only).
2) Make it better for reading and maintain creating a variable to hold that value and do like so:
$userStatus = $myObj->userStatus;
//Some Code HEre

AND (myTable.field_1 IN ('" . implode("','", $userStatus) . "')
  OR myTable.field_2 IN ('" . implode("','", $userStatus) . "')
  OR myTable.field_3 IN ('" . implode("','", $userStatus) . "'))";

Is there any "down side" for creating a variable in this case? Or it does not impact performance so we should take the "nice to read" path?

A: First, you can precompute the implode("','", $userStatus) into a variable. This way, you don't have to repeat the implode function multiple times. It's both more readable and has better performance.
Second, the most important thing is that you are dealing with your data in the wrong way! this kind of computations should be done in your database. For example, you have converted the many-to-many relation into a one-to-many. This has made your code less readable and less efficient.
Third, don't over-engineer your code. If you are making an operation, do it in a variable to be more readable rather than more performant. Performance is usually dependent on algorithm, structure, and design not by defining variables.

A: As a general practice, I don't assign a new variable unless I'm actually going to use it in a way that requires it.  There are of course exceptions to this, where readability would be significantly improved.  I don't think your example meets that threshold at all.
In fact, I think your specific example, assigning another variable here makes it potentially unclear what $userStatus is.  It's another thing to keep track of when skimming through code.
Certainly, there's nothing "ugly" about $myObj->userStatus.
In any case, there are other problems here.  You should never concatenate data directly into an SQL query.  It requires escaping at a minimum, but binding parameters is better.  Otherwise, you're opening yourself up to a whole host of bugs and security issues.
If you used named parameters, you'd find you would only use $myObj->userStatus once anyway.

A: You should try the following code :
$userStatus = $myObj->userStatus;
//Some Code HEre

$userStatusimp = implode(',', $userStatus);

AND (myTable.field_1 IN ('" .$userStatusimp. "')
  OR myTable.field_2 IN ('" .$userStatusimp . "')
  OR myTable.field_3 IN ('" .$userStatusimp. "'))";

A: The second way is the way to go. Much better to read and if you need to change something its easier to maintain.
I cant say something fact based on the performance, but i think that option 1) will work a little faster but as long as you dont work on really high performing  projects the difference should not be important.


text:
Q: What's the name of signal encoding used by WS2812 LEDs? The WS2812b color LED uses some kind of duty cycle encoding to encode three states:

*

*one

*zero

*reset

This can be seen in the following figure:

(Source: https://cpldcpu.files.wordpress.com/2014/01/ws2812_protocol.png)
What's the name of the used encoding?
It's not classic Pulse Width Modulation (PWM).
Edit:
While this question What encoding is used in this signal? asks for a name of a similar modulation, it does not give a name for the modulation.

A: AFAIK it doesn't have a fixed name, apart from 'the WS2812 protocol'. As described, it is a fixed-cell pulse-width encoding.
FYI: in practice, it isn't fixed-cell at all: provided that the pauses (T1L, T0L) are shorter than Treset, all that matters is the pulse width (T0H, T1H). This makes it a plain pulse-wdith encoding, and it makes bit-banging waaaaay easier.

A: This is what World-Semi calls it, they make the WS2812B

The data transfer protocol use single NZR communication mode. After the pixel power-on reset, the DIN
  port receive data from controller, the first pixel collect initial 24bit data then sent to the internal data latch,
  the other data which reshaping by the internal signal reshaping amplification circuit sent to the next cascade
  pixel through the DO port. After transmission for each pixel,the signal to reduce 24bit. pixel adopt auto resha
  -ping transmit technology, making the pixel cascade number is not limited the signal transmission, only depend
  on the speed of signal transmission.


text:
Q: Error : Cannot Assign a Value to Final Variable I'm new to android development and I'm trying to learn SharedPreferences.
How do I manipulate the value of X using buttons and then save it to SharedPreferences again using a button.
I have to declare SharedPreferences after OnCreate, but if I declare X after
OnCreate I have to set it Final so I can use it in my onClickListener, because it's inner class, but if I do then I'd get a complier error that reads:

"Error:(42, 17) error: cannot assign a value to final variable x"

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
        final Editor editor = pref.edit();

         int x = pref.getInt("Value", 0);

        final TextView txt = (TextView) findViewById(R.id.textView);
        final Button ButtonAdd = (Button) findViewById(R.id.buttonPlus);
        final Button ButtonMinus = (Button) findViewById(R.id.buttonMinus);
        final Button ButtonCommit = (Button) findViewById(R.id.buttonCommit);
        final EditText EditText = (EditText) findViewById(R.id.editText);

        txt.setText(Integer.toString(x));

        ButtonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                x = x + 1;
                EditText.setText(Integer.toString(x));

            }

        });

        ButtonMinus.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {

                if(x != 0){
                    x=x-1;}

                EditText.setText(Integer.toString(x));

            }

        });

        ButtonCommit.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {

                txt.setText(Integer.toString(x));
                editor.putInt("Value", x);

            }

        });

    }

}

A: public class MainActivity extends AppCompatActivity {

  private int x;   //declare here

Now in your onCreate()
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
        final Editor editor = pref.edit();

         x = pref.getInt("Value", 0);  //assign values to global variable
         //rest of the code
    }

See this for different Types of variables and Their usage

A: declare x as a member field of your Actvity and it will be accessible in your inner class


text:
Q: Upload Videos into Django Model FileField with Python Script I am trying to upload a small video file (10mb) to a Django model FileField with the python script below. I have a form setup but want to bypass this with the script going forward. When I run the script I get http response 200 but the video file does not appear in the relevant folder. What is the problem?
pythonscript.py

# uplaod video file to django model
f = open('/path/to/video.mp4', 'rb')
urls='http://127.0.0.1:8000/showvideo'
r=requests.post(urls, files= {'videofile':f})
print(r.status_code)

models.py

from django.db import models

class VideoUpload(models.Model):
    name= models.CharField(max_length=500)
    videofile= models.FileField(upload_to='videos/', null=True, verbose_name="")

    def __str__(self):
        return self.name + ": " + str(self.videofile)

forms.py

from django import forms
from .models import VideoUpload

class VideoForm(forms.ModelForm):

    class Meta:
        model = VideoUpload
        fields = ["name", "videofile"]

views.py

from django.shortcuts import render
from .models import VideoUpload
from .forms import VideoForm
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def showvideo(request):

    lastvideo= VideoUpload.objects.last()

    videofile = lastvideo.videofile if lastvideo else None

    form= VideoForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()

    context= {'videofile': videofile,
              'form': form
              }

    return render(request, 'video.html', context)

A: I played around with this and realised the name field was interfering with the upload. I removed the name field from models.py and forms.py and the video file now uploads successfully and appears in the relevant folder.
models.py

from django.db import models

class VideoUpload(models.Model):
    videofile= models.FileField(upload_to='videos/', null=True, verbose_name="")

    def __str__(self):
        return self.name + ": " + str(self.videofile)

forms.py

from django import forms
from .models import VideoUpload

class VideoForm(forms.ModelForm):

    class Meta:
        model = VideoUpload
        fields = ["videofile"]


text:
Q: Page navigation from a pivot control My application is pivot based. I have a pivot control which contains few pivot items. And from one of the pivot item (Settings) i want to navigate to another page(Settings edit page).
This is how i am navigating to setting page.
void MainPage::OnChangeSettingsClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    ViewModelSettings->ChangeSettings();
    this->Frame->Navigate(TypeName(SettingsPage::typeid));
}

This takes me to full screen settings page nicely.
I am coming back to the MainPage as below :
void SettingsPage::OnCancelSettingsButtonClicked(Object^ sender, PointerRoutedEventArgs^ e)
{
    this->Frame->Navigate(TypeName(MainPage::typeid));
}

This also brings me back to mainpage nicely.
But when i try to switch pivot or do anything inside pivot i am getting below exception :
Microsoft C++ exception: Platform::DisconnectedException

Why am i trapped with disconnected exception afterward. Am i missing something?


text:
Q: Unable to make a protocol for enum I am not very good with protocols, and I'm quite stuck right now. I am trying to make a protocol for an enum, which has a name property (or function if it needs to be).
This will allow me to get the name of an enum value, similar to conforming to String alone, but with the first letter capitalised instead. For example, what I want to happen:
enum Furniture: Named {
    case table, chair, lamp
}

Furniture.table.name   // Returns 'Table'
Furniture.chair.name   // Returns 'Chair'
Furniture.lamp.name    // Returns 'Lamp'

Here is what I have so far:
protocol Named {
    var name: String { get }
}

extension Named where Named: String {
    var name: String {
        let str: String = self.rawValue
        return str.prefix(1).uppercased() + str.dropFirst()
    }
}

This gives me errors, and when I try to correct them, another error pops up.
Right now, this shows me the following errors:

Type 'Named' constrained to non-protocol, non-class type 'String'
Value of type 'Self' has no member 'rawValue'

How can I fix this?

A: Enums get their raw value via the RawRepresentable protocol, so that's what you should use when constraining your extension:
extension Named where Self: RawRepresentable, RawValue == String {
    var name: String {
        let str: String = self.rawValue
        return str.prefix(1).uppercased() + str.dropFirst()
    }
}

You also need to declare that your enum uses a String as the type of its rawValue:
enum Furniture: String, Named {
    case table, chair, lamp
}

A: Set the Furniture enum to a string raw type, the Swift compiler automatically adds RawRepresentable conformance.
protocol Named {
    var name: String { get }
}

enum Furniture: String, Named {
    case table, chair, lamp
}

extension Named where Self: RawRepresentable, RawValue == String {
    var name: String {
        return rawValue.capitalized
    }
}

A Unit Tests to validate the Furniture enum,
import XCTest

class FurnitureTests: XCTestCase {

    func testEnumDisplayNameFirstLetterCapitlized() {
        XCTAssertEqual(Furniture.table.name, "Table")
        XCTAssertEqual(Furniture.chair.name, "Chair")
        XCTAssertEqual(Furniture.lamp.name, "Lamp")
    }

    func testEnumRawValue() {
        XCTAssertEqual(Furniture.table.rawValue, "table")
        XCTAssertEqual(Furniture.chair.rawValue, "chair")
        XCTAssertEqual(Furniture.lamp.rawValue, "lamp")
    }
}


text:
Q: Permanently add persons to a group calendar view I tried out the group calendar feature in SP2010 and it works pretty good. My only problem is that every time I load the page with the calendar view, it only adds my current user in the calendar. So I enter some users or group manually from the "Add Person" text box and it shows exactly what I would like to see by default. The problem is that I did not found any solution to save this in a view or in the default view.

As my goal is to share the team schedule, I would like be able to set a default list of persons or a group to my calendar view so the user don't have to add all of them manually. I think I am missing something because using a calendar group and displaying only your schedule makes no sense.
Thanks.

A: [EDIT] I didn't spot that you were looking for an "official" answer - if you want that I suggest posing the question to Microsoft. One would hope this gets fixed in vNext.
AFAIK this is expected behaviour.
Obviously this is inadequate as (like you say) it effectively defeats the purpose of the Web part.
This has been discussed on numerous forums but the closest item I found to a fix is this:
http://zepeda-mcmillan.blogspot.com/2011/03/displaying-default-resources-on-group.html
The workaround involves using fiddler (a Web debugging proxy) to grab the ECMAScript used to add the appropriate resources to the calendar, uploading the script and referencing it in the appropriate page.
Whilst far from ideal it's a decent blog post and a relatively straightforward solution assuming the resource list wont change too often.

A: I'm just experimenting with Groupcalendar function, too.
Although I am a big fan of JS/ECMA to pimp SharePoint, I had to find a no code solution, which can be done by End-Users.
It seems to me, that the threatowner was not aware of selector function in the ribbon, neither was I a few minutes ago.
So if you are able to put all persons of your team in one single sharePoint Group (including yourself), you can view every calendar with just one more click.
Just click the downarrow under "people" and select on of the Groups, you are member of.
(Maybe it's neccessary to create a new group but at least its enduser compatible)

A: I was working on a staff rota and came up with a sort of solution that allows the team to see what they should be doing on any particular day in a sort of Group Calendar.
Basically - stop thinking of a date as a date, but think of it as a piece of text that is ordered by column number that just happens to look like a date.
I created a spreadsheet of dates across the top from column b to ev and then team members a2 to a8. Populated the relevant cells with known activities (luckily a staff rota is usually one activity per date), converted to a Table and then uploaded to SharePoint. I only did 4 months as a full year caused the upload process to crash despite several attempts.
It seems to work in Standard view because SharePoint treats the dates as text, not dates and those dates just happen to be in the right order.
It is possible to select a team member and edit their activities. The difficulty arises when a new team meber needs to be added - then just update the spreadsheet - delete the old SharePoint list and upload the new one. Obvioulsy edit the view to show only the relevant dates displayed by ticking or unticking the appropriate date text box.
Not pretty, but it works.


text:
Q: jQuery - What's wrong with that code? I've onclick jquery code that doesn't give any response even with an error!
I don't know why, but here's my jQuery Code:
/* This Is working correctly */
$(".add-blog .blog-add-form .add-article .input-group select").on("change", function() {
  var tagsUl = '
 ' + $(".add-blog .blog-add-form .add-article .input-group select option:selected").text() + '
';
  $(".add-blog .blog-add-form .add-article .input-group ul").append($(tagsUl));
  $(".add-blog .blog-add-form .add-article .input-group select option:selected").remove();
});

/* This isn't working correctly */
$(".add-blog .blog-add-form .add-article .input-group ul li i").on("click", function() {
  var optionValue = $(this).parent().attr("class"),
    optionText = $(this).parent().text(),
    appendedOption = "<option value='" + $(optionValue) + "'>" + $(optionText) + "</option>";
  $(this).parent().parent().parent().children("select").append($(appendedOption));
  $(this).parent().remove();
});

I'm 100% sure that this element selector exist
when I open the css element inspector, select the element and put the same element selector, it shows that this element is the selected one.
anyway, here's my HTML Code:

      <form method='POST' action='example.php' class='form-horizontal'>

          <select></select>

 Anytext

      </form>

A: Your problem is that you are casting your optionValue and optionText to another jQuery object when you add them to appendOption. Remove the $() around optionValue and optionText and it should work.

$(".add-blog .blog-add-form .add-article .input-group ul li i").on("click", function() {
  var optionValue = $(this).parent().attr("class");
  var optionText = $(this).parent().text();
  var appendedOption = "<option value='" + optionValue + "'>" + optionText + "</option>";
  $(this).parent().parent().parent().children("select").append($(appendedOption));
  $(this).parent().remove();
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

      <form method='POST' action='example.php' class='form-horizontal'>

          <select></select>

 Anytext

      </form>

A: You're trying to pass to the jQuery function ($) a string, and it interept it as a selector:
appendedOption  = "<option value='" + $(optionValue) + "'>" + $(optionText) + "</option>";

Instead, do it as follows:
appendedOption  = "<option value='" + optionValue + "'>" + optionText + "</option>";

$(".add-blog .blog-add-form .add-article .input-group ul li i").on("click", function() {
    var optionValue     = $(this).parent().attr("class"),
        optionText      = $(this).parent().text(),
        appendedOption  = "<option value='" + optionValue + "'>" + optionText + "</option>";
    $(this).parent().parent().parent().children("select").append(appendedOption);
    $(this).parent().remove();
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

      <form method='POST' action='example.php' class='form-horizontal'>

          <select></select>

 Anytext

      </form>

A: Solved
Thanks to everyone who helped me in solving this problem !
When you guys have told me that the code is working fine with you,
I knew that the problem isn't from the onclick jQuery function.
My new code :
$(".add-blog .blog-add-form .add-article .input-group select").on("change", function() {
  var tagsUl = '
 ' + $(".add-blog .blog-add-form .add-article .input-group select option:selected").text() + '
';
  $(".add-blog .blog-add-form .add-article .input-group ul").append($(tagsUl));
  $(".add-blog .blog-add-form .add-article .input-group select option:selected").remove();
$(".add-blog .blog-add-form .add-article .input-group ul li i").on("click", function() {
  var optionValue = $(this).parent().attr("class"),
    optionText = $(this).parent().text(),
    appendedOption = "<option value='" + optionValue + "'>" + optionText + "</option>";
  $("select").append(appendedOption);
  $(this).parent().remove();
});
});


text:
Q: Sockets not working in AWS ec2 using PHP? Unable to make socket.io working on AWS EC2
 https://mydoamin.com:2120/socket.io/?EIO=3&transport=polling&t=NQpMyRI net::ERR_TIMED_OUT
i.create @ socket.io.js?v=1609310849:7

Localhost everything working fine the way it should be working but on live environment, I am getting above error.
When I connect using [workerman][1] and starting it using CLI on was ubuntu instance it is working fine
Somehow ports are not working properly even I have added it in security groups under inbound settings:-
And now this error after configuring:
<?php
use kriss\webMsgSender\WebMsgSender;

return [
   'components' => [
       // others
       WebMsgSender::COMPONENT_NAME => [
           'class' => WebMsgSender::class,
           'pushApiClientHost' => '0.0.0.0',
           'logCategory' => 'webMsgSender',
       ],
   ],
];

New error
socket.io.js?v=1609310849:7 GET https://myDoamin.com:2120/socket.io/?EIO=3&transport=polling&t=NQpU3PA net::ERR_CONNECTION_RESET

Extension I am using

A: Make sure you configure socket io to listen to be bonded to all IP addresses, not just the localhost
so instead of
<?php
use kriss\webMsgSender\WebMsgSender;

return [
    'components' => [
        // others
        WebMsgSender::COMPONENT_NAME => [
            'class' => WebMsgSender::class,
            'pushApiClientHost' => 'localhost',
            'logCategory' => 'webMsgSender',
        ],
    ],
];

change to
<?php
use kriss\webMsgSender\WebMsgSender;

return [
    'components' => [
        // others
        WebMsgSender::COMPONENT_NAME => [
            'class' => WebMsgSender::class,
            'pushApiClientHost' => '0.0.0.0',
            'logCategory' => 'webMsgSender',
        ],
    ],
];

basically change localhost to 0.0.0.0


text:
Q: Swift 2.0 url post request I've been trying to figure out what is wrong whit my code but i keep getting this error in swift 2.0
Errors thrown from here are not handled because the enclosing catch is not exhaustive

The automated conversion from XCode did a lot of work for me (also gave a LOT of errors) but this is still not working. I don't understand what is working so maybe you guys can throw some light on the case. Thanks in advance
here is my code
if config.isConnected() {
        let post:NSString = "postID=\(postID)"
        //NSLog("PostData: %@",post);
        let url:NSURL = NSURL(string:"https://www.example.com/json/index.php")!
        let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
        let postLength:NSString = String( postData.length )

        let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.HTTPBody = postData
        request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        var reponseError: NSError?
        var response: NSURLResponse?

        var urlData: NSData?
        do {
            urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) // gives error
        } catch let error as NSError {
            print(reponseError)
            reponseError = error
            urlData = nil
        }
        if ( urlData != nil ) {
            Webiew.loadRequest(request)
        } else {
            let alert: UIAlertView = UIAlertView(title: "OOPS", message: "There is nothing here!", delegate: nil, cancelButtonTitle: "OK");
            alert.show()
        }
    } else {
        // not connected
    }

A: Try this code *explained inside *
 let parameters = ["userId":"1", "userName":"2"] as Dictionary<String, String>
    //create the url with NSURL
    let url = NSURL(string: "URL") //change the url

    //create the session object
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST" //set http method as POST

    //request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body

    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setBodyContent(parameters)
    //create dataTask using the session object to send data to the server
    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        // println("Response: \(response)")
        let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("Body: \(strData)")
        let json = try!NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! NSDictionary
        print("account data")
        completion(result: json as NSDictionary?)

        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(error != nil) {
            print(error!.localizedDescription)
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
        }
        else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json as NSDictionary! {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                _ = parseJSON["success"] as? Int
                //println("Succes: \(success)")
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                _ = NSString(data: data!, encoding: NSUTF8StringEncoding)
               // println("Error could not parse JSON: \(jsonStr)")
            }
        }

    })

    task.resume()

Add this extension :
extension NSMutableURLRequest {
    func setBodyContent(contentMap: Dictionary<String, String>) {
        var firstOneAdded = false
        var contentBodyAsString = String()
        let contentKeys:Array<String> = Array(contentMap.keys)
        for contentKey in contentKeys {
            if(!firstOneAdded) {

                contentBodyAsString = contentBodyAsString + contentKey + "=" + contentMap[contentKey]!
                firstOneAdded = true
            }
            else {
                contentBodyAsString = contentBodyAsString + "&" + contentKey + "=" + contentMap[contentKey]!
            }
        }
        contentBodyAsString = contentBodyAsString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
        self.HTTPBody = contentBodyAsString.dataUsingEncoding(NSUTF8StringEncoding)
    }
}

A: This is my solution, i did not need to use the extension you've made.
This way the request is synchronous and it directly gives my response back and i parse it to get the values. It took some searching and trial & error but it is solved :) the code i pasted below is for something else but the principles are the same
    let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: config.versionURL() as String)!)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    var response: NSURLResponse?

    if config.isConnected() {
        var urlData: NSData?
        do {
            urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
        } catch _ {
            urlData = nil
        }
        if ( urlData != nil ) {
            let myJSON = try! NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableLeaves) as? NSDictionary
            if let parseJSON = myJSON {
                onlineVersion = parseJSON["version"]?.integerValue
                if onlineVersion > prefs.integerForKey("offlineVersion") {
                    showActivityIndicator(self.view)
                    self.structureSetup()
                } else if onlineVersion == prefs.integerForKey("offlineVersion") {
                    if (fileExistance) {
                        let jsonStringData = NSDictionary(contentsOfFile: jsonFilePath)
                        fullStructure = JSON(jsonStringData!)
                        numCats = fullStructure["posts"].count
                        self.homeTable.reloadData()
                        hideActivityIndicator(self.view)
                    } else {
                        if config.isConnected() {
                                self.structureSetup()
                        } else {
                            // alert, nothing here
                        }
                    }
                }
            }
        }
    } else {
        if (fileExistance) {
            let jsonStringData = NSDictionary(contentsOfFile: jsonFilePath)
            fullStructure = JSON(jsonStringData!)
            numCats = fullStructure["posts"].count
            self.homeTable.reloadData()
        } else {
            if config.isConnected() {
                self.structureSetup()
            } else {
                // alert, nothing here
            }
        }
    }


text:
Q: Game Theory: Prisoner Dilemma calculating the odds How can you by using a matrix, find the optimal strategies for each player in the prisoner dilemma, and calculate the odds of them choosing that option?
╔═════════╦════════════╦═════════════╗
║         ║   Confess  ║   Deny      ║
╠═════════╬════════════╬═════════════╣
║ Confess ║ 3y/3y      ║ 10y/1y      ║
╠═════════╬════════════╬═════════════╣
║ Deny    ║ 1y/10y     ║ 2y/2y       ║
╚═════════╩════════════╩═════════════╝

The column player confesses with the probability of P and denies with the probability of P-1
When I try to calculate the probability for the row player, I do: $$3p+1(1-p)=10p+2(1-p)$$
However then I get: $$P= -1/6$$
Which doesnt work. So I wonder what did I do wrong?

A: I think you  are assuming that a mixed strategy exists, that is, some probability that the Row player is indifferent between Confess and Deny. (That  is what the equation in your question is assuming.) Let $q$ be that probability.
then the row player seeks to choose $q$ to maximize:
$$U=q[3p+(1-p)1]+(1-q)[10p+2(1-p)].$$
$$=-q(6p+1)+8p+2.$$
Maximize by taking the derivative
$$\frac{du}{dq} =-(6p+1).$$
But, as you point out, unless $p$ has the impossible value-1/6, the derivative does  not equal zero. So the maximum value is a corner solution, where, since the derivative is negative, $q$ takes on it's maximum value, which, for a probability, is 1.
That is the famous solution to Prisoner's Dilemma, that whatever the other player does, your best (Dominant) strategy is to confess.


text:
Q: BizTalk Server to consume SOAP web methods without orchestrations Using BizTalk Server 2013, I want to read (pull) data from a web service and push it onto a SharePoint back-end system. The web service exposes web methods in SOAP. BizTalk has a default SOAP adapter. However, it seems that to read SOAP messages, BizTalk needs to know what XML schema to expect. Hence an orchestration in BizTalk is required to map inbound XML schemas from the web service methods to the expected outcome.
Orchestrations seem to be an overkill for this scenario. Is there a way to pull from SOAP web services using message based routing (i.e. from the BizTalk Admin Console) only?

A: I think that Basic Http Adapter can do in your case.
Even though SOAP Adapter is available, Microsoft too recommends using WCF BasicHttpAdapter instead.
Refer here: Microsoft Blog

A: This is possible.
Make sure to add generated schemas for this soap endpoint. Map the request schema to  your sharepoint document.
Then deploy your schemas and maps.
Set the map to your Receive Port Properties -> Inbound Maps

A: It is possible
Just don't forget to add the soap operation in the send port. But you can call only one method per send port


text:
Q: localStorage item not updating in axios headers I am using a JWT Token auth system, and when I login I get the token like this:
axios.post('/login', data)
    .then(response => {
        localStorage.setItem('token', response.data.token);
   });

This works well and the token is saved in localStorage. However, the token is not included in the later requests. The Authorization header is Bearer null.
This is how I set up my global axios object.
window.axios = axios.create({
    baseURL: '/api/',
    timeout: 10000,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
        'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
});

If I refresh the site, the token is set, and is used properly.
Edit:
I got it to work by removing the Authorization header from the create() method and instead using window.axios.defaults.headers.common['Authorization']. But now the same problem appears with Laravel Echo. I create the instance like this:
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'xxx',
    cluster: 'eu',
    encrypted: true,
    namespace: 'xxx',
    auth: {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
    }
});

And I update the header like this:
window.setAuthToken = (token) => {
    window.axios.defaults.headers.Authorization = 'Bearer ' + token;
    window.Echo.options.auth.headers.Authorization = 'Bearer ' + token;
    localStorage.setItem('token', token);
}

The axios header is successfully updated, but not Echo.

A: The problem is that your are using localStorage.getItem('token') at page load. When  you are setting it in localStorage, you have to update it in axios header.
window.axios = axios.create({
    baseURL: '/api/',
    timeout: 10000,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
        'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
});

axios.post('/login', data)
    .then(response => {
        localStorage.setItem('token', response.data.token);
        window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token');
    });

A: I faced the same problem before and I found out that the file that contains my axios config was being loaded at the time of storing the token, so it was accessing it before it is stored.
The solution is, in axios config:
  const axiosInstance = axios.create({
  baseURL: `${API_BASE_URL}`,
  headers: {
    Accepted: 'appication/json',
    'Content-Type': 'application/json',
  },
});

axiosInstance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.authorization = token;
    }
    return config;
  },
  (error) => Promise.reject(error),
);

export default axiosInstance;

After that, use this instance where you need to make a request.

A: Use axios interceptors for this purpose. It will run for every request call.
Better to keep axios methods in a separate file and make call to it than using it directly in all components. This way we can replace axios with another library if we want with minimal effort. Here's what I'm doing in my project.
import axios from "axios";
import AuthService from "./auth";

import config from '../config'

const instance = axios.create({
  baseURL: config.apiServer.url,
  timeout: config.apiServer.timeout
});

instance.interceptors.request.use(
  config => {
    const token = AuthService.getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => Promise.reject(error)
);

const ApiService = {

  get(url) {
    return instance.get(url)
      .then(res => res)
      .catch(reason => Promise.reject(reason));
  },

  post(url, data) {
    return instance.post(url, data)
      .then(res => res)
      .catch(reason => Promise.reject(reason));
  },

  awaitAll() {
    return axios.all(Array.from(arguments))
      .then(axios.spread((...responses) => responses))
      .catch(reasons => Promise.reject(reasons));
  }

};

export default ApiService;

Now to use it in a component:
ApiService.get(YOUR_GET_URL)
      .then(res => {
        Console.log(res);
      ))
      .catch(reason => {
        console.log(reason);
      })


text:
Q: TypeScript doesnt understand "$location.$$path"? is there any reason why Typescript doesnt understand $location.$$path ??
Here is a fragment of my controller:
    static $inject: string[] = ["DataService", "$location", "$route", "$routeParams", "$log"];

    constructor(
        private dataService: DataService,
        private $location: ng.ILocationService,
        private $route: ng.route.IRouteService,
        private $routeParams: IRouteParams,
        private $log: ng.ILogService) {

        if ($location.$$path.includes("Reports")){

        }
    }


text:
Q: Continued fraction for $\sqrt 2$ I discovered this continued fraction for $\sqrt 2$ but could not find any sources in which it appeared. It goes as follows:
\begin{equation}
\sqrt{2} = 1 + \frac{1 + \frac{1 + \frac{1 + \dots}{3 + \dots}}{3 + \frac{1 + \dots}{3 + \dots}}}{3 + \frac{1 + \frac{1 + \dots}{3 + \dots}}{3 + \frac{1 + \dots}{3 + \dots}}}
\end{equation}
I can show that it approaches $\sqrt{2}$ via a computer program, but see no feasible way to prove it.

A: Your continued fraction is essentially the 'infinite image' of the map $x\mapsto f(x)=1+\dfrac x{2+x}$ (can you see why?) and so any limit $\alpha$ of that map must satisfy $\alpha=1+\dfrac{\alpha}{2+\alpha}$. Multiplying both sides by $2+\alpha$ and simplifying gives the equation $\alpha^2=2$, so $\sqrt{2}$ must be the limit if it exists. To show that the limit exists, you want to show that $f(x)$ is what's called a Contraction Mapping over a suitable section of the real line — that is to say, that the distance between $f(x)$ and $f(y)$ is always smaller than the distance between $x$ and $y$ within that domain. The Banach fixed-point theorem then guarantees that it has a (unique) fixed point in that region. The easiest way to show that $f()$ is a contraction mapping is to show that the derivative is less than $1$ in the domain in question (it's a little bit tricky to prove that this implies that $f()$ is a contraction mapping, but not too hard, and it should hopefully be intuitively clear). Now, the derivative of $f$ is $f'(x)=\dfrac{2}{(2+x)^2}$, and this is clearly less than $1$ for any $x\geq 0$, so the conditions hold and the limit is well-defined.
As for why showing convergence matters in a problem like this, consider the expression $6-2\times(6-2\times(6-2\times(6-\ldots)))$; applying the same argument shows that the limit $\alpha$ satisfies $\alpha=6-2\alpha$, so $\alpha=2$ if the limit exists. But iterating the map $x\mapsto 6-2x$ blows up to infinity for any starting value of $x$, so the original expression doesn't have any proper meaning (over the real numbers).

A: Let $x = \frac {1 + \frac {1 + \cdots}{3+\cdots}}{3 + \frac {1 + \cdots}{3+\cdots}}$
$x = \frac {1+x}{3+x}\\
x^2+ 3x = 1+x\\
x^2 + 2x - 1 = 0\\
x = -1 \pm \sqrt {2}$
We know that $x>0$ so we can discard the negative value.
$1 + x = \sqrt 2$


text:
Q: how crawl an URL through shell scripting? I have to check a server is up or not by Firing certain URL.
 I tried using wget command,where there is a response like "HTTP request sent, awaiting response... 200 OK "
is coming which shows the server is  up and running.but i cant return the status to make it automate.
I have a list of 10 URL which i have to nake it automate to check all the URL are responding properly or not.
please help.

A: This is literally it:
if curl https://example.com
then
    echo "up"
else
    echo "down"
fi


text:
Q: An asymptotic expansion The function $w(x)$ satisfies
$$\frac{d^2w}{dx^2} + 2x\frac{dw}{dx} - 2\beta w = 0$$
with $$w(\infty)=0 \text{ and } 0<\beta < 1.$$
By writing $w(x)= exp(-x^2)f(x)$, obtain the first two terms of an asymptotic expansion for $w(x)$ as $x \to \infty $.


text:
Q: Python mysql update doesnt update I'm trying to read an excel file and update existing records in the database. New entries will be created for new records.
New entries are being created but updates are never reflected on the DB.
mydb = mysql.connector.connect(
  host="127.0.0.1",
  port='3306',
  user="root",
  password="aaaaaa",
  database="aaaaaa",
  autocommit=True
)

wb = load_workbook(filename = 'msp.xlsx')
mycursor = mydb.cursor()

for sheet in wb.worksheets:
    rowIter = 2
    while sheet['A' + str(rowIter)].value != None and sheet['A' + str(rowIter)].value != '':
        item = sheet['A' + str(rowIter)].value

        try:
            if check_int(item):
                item = str(item)

            itemRegex = ' '.join(item.split())                        # removing extra spaces

            lp = sheet['B' + str(rowIter)].value if sheet['B' + str(rowIter)].value != None else 0
            msp = sheet['C' + str(rowIter)].value if sheet['C' + str(rowIter)].value != None else 0

            lp = 0 if check_int(str(lp)) == False else lp
            msp = 0 if check_int(str(msp)) == False else msp

            # checking if item already exists
            sql = "SELECT id FROM stock WHERE part_no = %s LIMIT 0, 1"
            val = (item, )
            mycursor.execute(sql, val)
            partFound = mycursor.fetchone()

            if partFound == None:
                # insert new record
                print('Creating new record')
                sql = "INSERT INTO stock (principal, part_no, balance, demo_pending, total, pending_sob, pending_po, reserved, msp, lp) VALUES (%s, %s, 0, 0, 0, 0, 0, 0, %s, %s);"
                val = (sheet.title, item, msp, lp, )
                mycursor.execute(sql, val)

            else:
                # updating existing record
                part_id = partFound[0]
                print('Updating record ' + str(part_id))

                sql =  "UPDATE stock SET msp = %s AND lp = %s WHERE id = %s;"
                val = (int(msp), int(lp), part_id, )
                mycursor.execute(sql, val)
                print "Row(s) were updated :" +  str(mycursor.rowcount)
                print(mycursor.statement)

        except Exception as e:
            print (str(e))
            break

        rowIter+=1

mydb.close()

Am I missing something ?
The mycursor.rowcount always returns 0

A: for updating a table, you should use:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

replace And with , in your code


text:
Q: Good resource/book for learning Objective-C I have have been trying to learn Objective-C for a little bit now. I was wondering if anyone knows of good online references guides/courses related to the topic that are good know of any good books related to this topic.
Thank you.

A: Three great free references for learning objective-C are:

*

*http://www.raywenderlich.com/  -- Ray Wenderlich provides high quality tutorials for many topics ranging from basic to advances objective-c programming.

*http://nshipster.com/ -- NSHipster is a journal of the overlooked bits in Objective-C, Swift, and Cocoa. Updated weekly.

*http://littlebitesofcocoa.com/ -- Similar to NSHipster, utilizing short, sweet, and to the point articles for IOS and OSX development.
What I used to begin learning Objective-C and IOS development are the books:

*

*Big Nerd Ranch Guide - Objective-C Programming https://www.bignerdranch.com/we-write/objective-c-programming/

*Big Nerd Ranch Guide - IOS Programming
https://www.bignerdranch.com/we-write/ios-programming/
As programming is always changing, some tutorials and methods are going to be a small bit outdated using updated versions of Xcode. If you are using a book, I would recommend downloading the version of Xcode to whatever is being used in the book.
If something is not working properly, look up errors on google or post questions on stackoverflow -- solving errors are what help you learn!
Hope this helps!


text:
Q: bootstrap accordion collapses in chrome on back click not on mozilla I have a bootstrap accordion like this in my rails app.

              Collapsible Group Item #1

             s1

              Collapsible Group Item #2

              s2

              Collapsible Group Item #3

<button type="button" class="btn btn-primary" id="proceed_to_order">Proceed</button>

Here's the fiddle.
So when I click, I am carrying these values to the next page (which I am unable to put in the fiddle). So In Mozila browser when I click back in the browser the last accordion when I had opened and clicked on proceed remains open. But for Chrome when I click back, all the accordion is automatically are closed which I don't want.
Is there any work around for this?
Please suggest.

A: replace with:

       s3

in third number of accordion group..


text:
Q: Auth::attempt not working in laravel 5.2 missing I'm missing something it shows me throw an internal server error.
Routes.php
Route::group(['middleware' => ['web']], function() {

    Route::post('/signup',[
        'uses' => 'UserController@postSignUp',//SignupProcess
        'as' => 'signup'
        ]);

    Route::post('/signin',[
        'uses' => 'UserController@postSignIn',//SigninProcess
        'as' => 'signin'
        ]);

});

Route::get('signup', function () {
    return view('signup');
});

Route::get('login', function () {
    return view('login');
});

UserController.php
<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function postSignUp(Request $request)
    {
        $username = $request['username'];
        $password = bcrypt($request['password']);
        $token = $request['_token'];

        $user = new user();
        $user->email = $username;
        $user->password = $password;
        $user->remember_token = $token;

        $user->save();

        return redirect()->back();
    }

    public function postSignIn(request $request)
    {

          if (Auth::attempt(['email'=> $request['username'], 'password' => $request['password']]))
           {
            // Authentication passed...
            return "false";
           }
    }
 }

User.php(model)
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Contracts\Auth\Authenticatable;

    class User extends Model implements Authenticable
    {

        use Illuminate\Auth\Authenticable;

    }

login.blade.php

<title>Login</title>
{!! Form::open(['url' => 'signin']) !!}
    Username
    <input type = "text" name = "username">

     Password
    <input type = "password" name = "password">

    <input type='hidden' name='_token' value='{{ Session::token()}}'>
    <input type = "submit" name = "Login">
{!! Form::close() !!}

signup.blade.php
{!! Form::open(['url' => 'signup']) !!}

<title>Login</title>
<form>
    Username
    <input type = "text" name = "username">

     Password
    <input type = "password" name = "password">

    <input type = "submit" name = "Login">
</form>

{!! Form::close() !!}

A: 2 then use this to for authentication LINK
if you want use manual way in your login form use
<form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">


text:
Q: Plotting data with R. How to break coordinates I'm plotting a geom_point() layer using ggplot. In my plot, I have one dot located very far away from the rest along the y axis. As a result, the data visualization loses granularity and displays a bunch of little dots close together, as well as a single isolated dot high and far away from the rest.
I do not want to exclude the outlier. Instead, I would like to break the y-axis coordinates, for instance displaying ylim = c(0, 220) followed by c(2000, 2100). However, I did not succeed using coord_cartesian or scale_y_continuous.
Anyone knows how can I make this works, or possibly suggest any alternative solutions? Thanks