text:
Q: How to get the data I want according to the rules I have a configuration table like the below, and some users with different attributes. I need to get a configuration data based on user attributes.
I don't know how to implement it, no idea.

Initial code:
void Main()
{
    var configList = new List<ConfigEntity>() {
        new ConfigEntity { ConfigCode="37", GoodCode="A", UserType="personal", Country="US", State="NewYork", City="Buffalo", Price=37 },
        new ConfigEntity { ConfigCode="36", GoodCode="A", UserType="personal", Country="US", State="NewYork", City="Albany", Price=36 },
        new ConfigEntity { ConfigCode="35", GoodCode="A", UserType="personal", Country="US", State="NewYork", City="", Price=35 },
        new ConfigEntity { ConfigCode="34", GoodCode="A", UserType="personal", Country="US", State="", City="", Price=34 },
        new ConfigEntity { ConfigCode="40", GoodCode="A", UserType="personal", Country="China", State="Guangdong", City="Guangzhou", Price=40 },
        new ConfigEntity { ConfigCode="39", GoodCode="A", UserType="personal", Country="China", State="Guangdong", City="", Price=39 },
        new ConfigEntity { ConfigCode="38", GoodCode="A", UserType="personal", Country="China", State="", City="", Price=38 },
        new ConfigEntity { ConfigCode="33", GoodCode="A", UserType="personal", Country="", State="", City="", Price=33 },
        new ConfigEntity { ConfigCode="45", GoodCode="A", UserType="organization", Country="US", State="NewYork", City="Buffalo", Price=45 },
        new ConfigEntity { ConfigCode="44", GoodCode="A", UserType="organization", Country="US", State="NewYork", City="Albany", Price=44 },
        new ConfigEntity { ConfigCode="43", GoodCode="A", UserType="organization", Country="US", State="NewYork", City="", Price=43 },
        new ConfigEntity { ConfigCode="42", GoodCode="A", UserType="organization", Country="US", State="", City="", Price=42 },
        new ConfigEntity { ConfigCode="48", GoodCode="A", UserType="organization", Country="China", State="Guangdong", City="Guangzhou", Price=48 },
        new ConfigEntity { ConfigCode="47", GoodCode="A", UserType="organization", Country="China", State="Guangdong", City="", Price=47 },
        new ConfigEntity { ConfigCode="46", GoodCode="A", UserType="organization", Country="China", State="", City="", Price=46 },
        new ConfigEntity { ConfigCode="41", GoodCode="A", UserType="organization", Country="", State="", City="", Price=41 },
        new ConfigEntity { ConfigCode="29", GoodCode="A", UserType="", Country="US", State="NewYork", City="Buffalo", Price=29 },
        new ConfigEntity { ConfigCode="28", GoodCode="A", UserType="", Country="US", State="NewYork", City="Albany", Price=28 },
        new ConfigEntity { ConfigCode="27", GoodCode="A", UserType="", Country="US", State="NewYork", City="", Price=27 },
        new ConfigEntity { ConfigCode="26", GoodCode="A", UserType="", Country="US", State="", City="", Price=26 },
        new ConfigEntity { ConfigCode="32", GoodCode="A", UserType="", Country="China", State="Guangdong", City="Guangzhou", Price=32 },
        new ConfigEntity { ConfigCode="31", GoodCode="A", UserType="", Country="China", State="Guangdong", City="", Price=31 },
        new ConfigEntity { ConfigCode="30", GoodCode="A", UserType="", Country="China", State="", City="", Price=30 },
        new ConfigEntity { ConfigCode="25", GoodCode="A", UserType="", Country="", State="", City="", Price=25 },
        new ConfigEntity { ConfigCode="13", GoodCode="", UserType="personal", Country="US", State="NewYork", City="Buffalo", Price=13 },
        new ConfigEntity { ConfigCode="12", GoodCode="", UserType="personal", Country="US", State="NewYork", City="Albany", Price=12 },
        new ConfigEntity { ConfigCode="11", GoodCode="", UserType="personal", Country="US", State="NewYork", City="", Price=11 },
        new ConfigEntity { ConfigCode="10", GoodCode="", UserType="personal", Country="US", State="", City="", Price=10 },
        new ConfigEntity { ConfigCode="16", GoodCode="", UserType="personal", Country="China", State="Guangdong", City="Guangzhou", Price=16 },
        new ConfigEntity { ConfigCode="15", GoodCode="", UserType="personal", Country="China", State="Guangdong", City="", Price=15 },
        new ConfigEntity { ConfigCode="14", GoodCode="", UserType="personal", Country="China", State="", City="", Price=14 },
        new ConfigEntity { ConfigCode="9", GoodCode="", UserType="personal", Country="", State="", City="", Price=9 },
        new ConfigEntity { ConfigCode="21", GoodCode="", UserType="organization", Country="US", State="NewYork", City="Buffalo", Price=21 },
        new ConfigEntity { ConfigCode="20", GoodCode="", UserType="organization", Country="US", State="NewYork", City="Albany", Price=20 },
        new ConfigEntity { ConfigCode="19", GoodCode="", UserType="organization", Country="US", State="NewYork", City="", Price=19 },
        new ConfigEntity { ConfigCode="18", GoodCode="", UserType="organization", Country="US", State="", City="", Price=18 },
        new ConfigEntity { ConfigCode="24", GoodCode="", UserType="organization", Country="China", State="Guangdong", City="Guangzhou", Price=24 },
        new ConfigEntity { ConfigCode="23", GoodCode="", UserType="organization", Country="China", State="Guangdong", City="", Price=23 },
        new ConfigEntity { ConfigCode="22", GoodCode="", UserType="organization", Country="China", State="", City="", Price=22 },
        new ConfigEntity { ConfigCode="17", GoodCode="", UserType="organization", Country="", State="", City="", Price=17 },
        new ConfigEntity { ConfigCode="5", GoodCode="", UserType="", Country="US", State="NewYork", City="Buffalo", Price=5 },
        new ConfigEntity { ConfigCode="4", GoodCode="", UserType="", Country="US", State="NewYork", City="Albany", Price=4 },
        new ConfigEntity { ConfigCode="3", GoodCode="", UserType="", Country="US", State="NewYork", City="", Price=3 },
        new ConfigEntity { ConfigCode="2", GoodCode="", UserType="", Country="US", State="", City="", Price=2 },
        new ConfigEntity { ConfigCode="8", GoodCode="", UserType="", Country="China", State="Guangdong", City="Guangzhou", Price=8 },
        new ConfigEntity { ConfigCode="7", GoodCode="", UserType="", Country="China", State="Guangdong", City="", Price=7 },
        new ConfigEntity { ConfigCode="6", GoodCode="", UserType="", Country="China", State="", City="", Price=6 },
        new ConfigEntity { ConfigCode="1", GoodCode="", UserType="", Country="", State="", City="", Price=1 }
    };

    configList.Dump();

}

public class ConfigEntity
{
    public string ConfigCode { get; set; }
    public string GoodCode { get; set; }
    public string UserType { get; set; }
    public string Country { get; set; }
    public string State { get; set; }
    public string City { get; set; }
    public decimal Price { get; set; }
}

if GoodCode="A" and user (UserType="personal", Country="US", State="NewYork", City="Albany"), I expect get a data of ConfigCode="36";
if GoodCode="A" and user (UserType="personal", Country="China", State="Guangdong", City=""), I expect get a data of ConfigCode="39";
if GoodCode="A" and user (UserType="personal", Country="", State="", City=""), I expect get a data of ConfigCode="33";
if GoodCode="" and user (UserType="personal", Country="", State="", City=""), I expect get a data of ConfigCode="9";
if GoodCode="B" and user (UserType="", Country="", State="", City=""), I expect get a data of ConfigCode="1";

A: The place to start is with the simplest thing that will work. In this case, say somebody gives you the following input:
{ GoodCode="A", UserType="organization", Country="China", State="Guangdong", City="", Price=47 }

So you create a new ConfigEntity with that data:
var searchFor = new ConfigEntity(
    ConfigCode="??", GoodCode="A", UserType="organization",
    Country="China", State="Guangdong", City="", Price=47);

Then you search your list sequentially:
ConfigEntity foundItem = null;
foreach (var f in configList)
{
    if (f.GoodCode == searchFor.GoodCode &&
        f.UserType == searchFor.UserType &&
        f.Country == searchFor.Country &&
        f.State == searchFor.State &&
        f.City == searchFor.City)
    {
        foundItem = f;
        break;
    }
}
if (foundItem != null)
{
    // found the item. Do something with it.
}
else
{
    // didn't find the item. Handle the error.
}

That isn't the best or most efficient way to do things, but it works. It's a start that you can then improve upon.


text:
Q: Check deleted video when getting comments I am getting statistics (video/list) and comments (commentThreads/list) for some videos and I would like to know when a video has been deleted but the problem is that no error is thrown for a removed video.
The returned results are empty for a deleted video but I cannot be 100% sure the video was deleted or it is just a matter that the video does not have comments or insights.
Is there a way to get this fixed?

A: Just call videos.list with id = {VIDEOID}
There won't be any video in response if the video is deleted.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Storing the data vs Storing of the data I would like to know if both are correct (if so, in what context and why):

Storing the data is important.
  Storing of the data was implemented using ABC.

I do not know where the "of" preposition is required. The same would be with "displaying":

Displaying the picture.
   Displaying of the picture.

A: "Storing the data is important" is correct, but it would be more usual to say "Storage of the data was implemented using ABC".
Storage is "the act of storing" (see here: http://www.thefreedictionary.com/storage for example) which is what your second sentence is talking about.
For your second examples the first sentence is again correct, and the second would more usually be "Display of the picture".
I've said more usually: it is possible to say "Displaying of the picture" and it's not wrong, but it is unusual and might be better reserved for stylistic effect.

A: Yes, there's a difference in structure between

*

*Storing the data is important.

*Storing of the data was implemented using ABC.
Their subject constituents

*

*Storing the data

*Storing of the data
vary in an interesting way.
(2), but not (1), can start with an article
(ungrammatical examples are marked with an asterisk * )

*

**The storing the data

*The storing of the data
Only noun phrases can take an article, which means that in (2) storing is a noun.
But in (1) storing is a verb -- a Gerund -- and the data is its direct object (therefore no preposition is needed). This becomes clearer with sentences:

*

**The singing the "Star-Spangled Banner" starts at 9. (noun - can't take direct object)

*The singing  of the "Star-Spangled Banner" starts at 9. (noun - OK with preposition)

**Singing of the "Star-Spangled Banner" starts at 9. (gerund - needs no preposition)

*Singing the "Star-Spangled Banner" starts at 9. (gerund - OK with direct object)

You may have been taught that any noun that ends in -ing is a Gerund. This is not correct.
Gerunds are verbs and have verbal properties (like having direct objects);
nouns, on the other hand, have nominal properties, like taking determiners.
They may sound the same, but they don't act the same.


text:
Q: Why different ways of Get-ChildItem filtering give same objects that are actually different? For several unrelated reasons I'm playing with several ways to deal with filtering the pipeline output when usign the Get-ChildItem command.
I've created a short code to exemplify what I mean. When I use different ways to get the same item, the item gets "stringified" differently depending on the way it was found, even when it's the same item every time.
Lets say we have this folder C:\Folder1\Folder1-a with File1.7z and File2.txt inside.
There are more File1-X folders inside Folder1, each with a .7z and a .txt file inside, and their names can have some special characters like square brackets. This is no relevant for this question, but it's the reason of why I would prefer to use some specific way of filtering over another (explained in the comments of the attached code).
Here's the code that exemplifies my point:
#Initialize 7zip
if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"}
set-alias 7zip "$env:ProgramFiles\7-Zip\7z.exe"

#this is a placeholder, $TXTFile would be the result of an iteration over a previous Item array
$TXTFile = Get-Item -Path "C:\Folder1\Folder1-a\File2.txt"

#Now there comes 3 different ways to select the 7z file in the same directory as File2.txt

# I use this to modify the path name so square brackets are properly escaped
$directory1 =$TXTFile.DirectoryName -replace "\[","`````[" -replace "\]","`````]"
[array]$7ZFile1 = Get-ChildItem -File -Path "$directory1\*.7z"

# This option uses LiteralPath so no modification is needed.
# More convenient since it supports any kind of special character in the name.
$directory2=$TXTFile.DirectoryName
[array]$7ZFile2= Get-ChildItem -File -LiteralPath $directory2 -Filter *.7z

# This option uses LiteralPath so no modification is needed.
# More convenient since it supports any kind of special character in the name.
$directory3=$TXTFile.DirectoryName
[array]$7ZFile3 = Get-ChildItem -File -LiteralPath $directory3 | Where-Object {$_.Extension -eq ".7z"}

#Lets see each item. They all seem equal
$7ZFile1
$7ZFile2
$7ZFile3
Write-Host "`n"

#Lets see how they have he same FullName
Write-Host $7ZFile1.FullName
Write-Host $7ZFile2.FullName
Write-Host $7ZFile3.FullName
Write-Host "`n"

#Lets compare them using -eq. Damn, they are not equal
if($7ZFile1 -eq $7ZFile2){"7ZFile1=7ZFile2"}Else{"7ZFile1!=7ZFile2"}
if($7ZFile2 -eq $7ZFile3){"7ZFile2=7ZFile3"}Else{"7ZFile2!=7ZFile3"}
if($7ZFile3 -eq $7ZFile1){"7ZFile3=7ZFile1"}Else{"7ZFile3!=7ZFile1"}
Write-Host "`n"

#This is relevant if we "stringify" each object. First one returns FullName, the two others return Name
Write-Host $7ZFile1
Write-Host $7ZFile2
Write-Host $7ZFile3
Write-Host "`n"

#Example of this being relevant. Inside File1.7z is a txt file. If you use 7zip por example like this:
7zip t $7ZFile1 *.txt -scrc     #Success
7zip t $7ZFile2 *.txt -scrc     #Fail, can't find 7ZFile2
7zip t $7ZFile3 *.txt -scrc     #Fail, can't find 7ZFile3

I'm using $7ZFile.FullName to consistently always get the string that I want, however I would like to know why does this happen? why is there a difference in the first place?

A: There are two unrelated problems here:

*

*In Windows PowerShell - but fortunately no longer in PowerShell Core - the System.IO.DirectoryInfo and System.IO.FileInfo instances that Get-ChildItem outputs situationally stringify differently - mere filename vs. full path - depending on the specifics of the Get-ChildItem call.

*

*See this answer for details.

*The underlying cause is an inconsistency in the .NET types involved, which has been corrected in .NET Core (on which PowerShell Core is built), as explained in this comment on GitHub.

*To be safe, always use the .FullName property when passing instances as arguments to other commands or when the intent is to stringify by full name.

*A simple demonstration of the problem:
# Full-name stringification, due to targeting a *file* (pattern).
PS> (Get-ChildItem $PSHOME\powershell.exe).ToString()
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

# Name-only stringification, due to targeting a *directory* by *literal* name
# (even though a filter to get a file is applied) and
# not also using -Include / -Exclude
PS> (Get-ChildItem $PSHOME -Filter powershell.exe).ToString()
powershell.exe

*

*System.IO.DirectoryInfo and System.IO.FileInfo are reference types, which means that their instances are compared using reference equality: that is, two variables containing instances only compare the same if they point to the very same object in memory.

*

*Therefore, $7ZFile1 -eq $7ZFile2 is never $true if the two instances were obtained by different Get-ChildItem calls; the best approach is to compare instances by their .FullName property.

*See this answer for more information about reference equality vs. value equality.

*A simple demonstration of the reference-equality behavior:
PS> (Get-ChildItem $PSHOME\powershell.exe) -eq (Get-ChildItem $PSHOME\powershell.exe)
False  # Distinct FileInfo objects, which aren't reference-equal.

A: It's a common annoyance in PS 5, where the string version of what get-childitem returns doesn't have the full path.  It's changed in later versions of PS.  Get full path of the files in PowerShell
get-childitem .   | foreach tostring  # not full path
get-childitem .\* | foreach tostring  # full path


text:
Q: Is there any way to install MS Office Shortcut Bar (from Office 2000) on Windows 10? While I am aware that Office 2000 is not compatible with Windows 10, I am attempting to see if there's any trick to install a lone component called MS Office Shortcut Bar from Office 2000 on to Windows 10 64bit.
Those of you who might have used Office 2000 way back in late 90's or early 2K would be familiar with this component called MS Office Shortcut Bar. A handy toolbar to create and launch your shortcuts. This feature was later permanently discontinued by Microsoft. I successfully installed it up till Windows 7 though.
When I attempt to install it from Office 2000 setup on Windows 10 64, it throws error while registering 4 DLLs
MSOLAP, MSMDCUBE, MSMDGRV & MSOLAPUI.  These get copied at C:\Program Files(x86)\Common Files\System\OLE DB\
Error 1904 Failed to register <filename>.DLL

I can ignore and continue but the resulting shortcut bar (though installs) fails to launch any shortcuts indeed.
I have tried to manually register these DLLs using regsvr32 invoked from SYSWOW64 but it does just nothing. The control returns to command prompt without any warning or error or anything whatsoever.
Does anyone know of any trick to make it work?


text:
Q: List all git commits that have no files changed I'm working with an open source repository that seems to have been copied over from either a combined git repo or some other kind of VCS. There are an enormous amount of commits in the repo, most of them with zero files changed:

What would be the best way to list all the commits with no files changed, count them, and potentially remove them from the local git repo?
Edit: I'm specifically looking for a way to assess the extent of the issue before running a time consuming, destructive command like filter-branch as referenced in Remove empty commits in git

A: So it turns out the keyword I was missing in Google was "empty" (was searching for "remove commits with no files changes", etc)
List commits that have no changes (empty commits):
git rev-list HEAD | while read commitHash; do
    if [ $(git diff-tree --name-status --no-commit-id $commitHash | wc -l) -eq 0 ]; then
        echo $commitHash
    fi;
done

List commits that have changes, and files changed (non empty commits):
git rev-list HEAD | while read commitHash; do
    git diff-tree --name-status $commitHash
done

Count empty commits
git rev-list HEAD | while read commitHash; do
    if [ $(git diff-tree --name-status --no-commit-id $commitHash | wc -l) -eq 0 ]; then
        echo '1'
    fi;
done | wc -l

Count non empty commits
git rev-list HEAD | while read commitHash; do
    if [ $(git diff-tree --name-status --no-commit-id $commitHash | wc -l) -gt 0 ]; then
        echo '1'
    fi;
done | wc -l

And finally, as per @JKillian's suggestion, remove all empty commits from the repo using git filter-branch:
git filter-branch --tag-name-filter cat --commit-filter 'git_commit_non_empty_tree "$@"' -- --all

Documentation on filter-branch, specifically --commit-filter:
https://git-scm.com/docs/git-filter-branch#git-filter-branch---commit-filterltcommandgt


text:
Q: User entity in domain layer in ASP.NET Core in Clean Architecture thinking in an application that needs User authentication/authorization in the context of Clean Architecture and DDD, how can I decouple de User entity in my domain layer from the Identity of the ASP.NET Core, ie, how can I put the User in my domain layer without referencing Identity (which is a Infrastructure detail) and still in some way using the ASP.NET Core Identity, it is even possible?

A: AFAIK, If clean Architecture and DDD was that importance from your viewpoint. I would assume we would heading to build a microservices architecture.
If that's the case, IMO, we should choose another approach that separate Asp.Net UserIdentity as central identity provider, and a user service that serve our own purpose for the business ourself.
As such, User entity of Asp.net would responsible for all the from login, 2 factor authentication, external identity service provider, mapping with current existing account,...
Our own application User identity would serve specific business logic, as user role, address, rewarding point,...
So, perfectly satisfied both bounded context of DDD and clean architecture for each service themself.


text:
Q: How use Greater Than 0 (>0) within Case in Sql Server? I have this line in my stored procedure.
CreatedBy = CASE
               WHEN @Userregisteredby = 0 THEN 0
               ELSE CreatedBy
            END

In my table there is either 0 or 1 or any other values  for CreatedBy.
I want to get only that rows with CreatedBy=0 if I send 0 from front end radio button list.
Same way, I want to get only that rows with CreatedBy > 0 if I send 1 from the front end. For the ELSE condition I want to get all rows. How to do this thing?
In my code, I am unable to use condition something like this:
WHEN @Userregisterdby = 1 Then > 0

A: I think you need something like this:
SELECT fields FROM table
WHERE
    (@UserRegisteredBy = 0 and CreatedBy = 0)
    or
    (@UserRegisteredBy = 1 and CreatedBy > 0)
    or
    (@UserRegisteredBy is null)

A: If I understand your requirements correctly you want to

*

*Pull all records where CreatedBy = 0 when @Userregisteredby = 0

*Pull all records where CreatedBy > 0 when @Userregisteredby > 0

WHERE CreatedBy = CASE
                     -- Admin
                     WHEN @Userregisteredby = 1 AND CreatedBy > 0 THEN CreatedBy
                     -- Self
                     WHEN @Userregisteredby = 0 THEN 0
                     -- Everyone else (exclude self/admin records)
                     WHEN CreatedBy > 1 THEN CreatedBy
                  END


text:
Q: Python Pulp replicating Excel's solver When i try to use the math.log function in the objective expression, this error pops out. Can someone help me understand how can a add the formula that i need to optimize?
model_MPL += samples * (math.log(beta_var) - beta_var * math.log(alfa_var)) + suma
I am trying to reproduce Excel's solver in order to optimize the alpha and beta parameters of a weibull distribution.
data = np.array([509,660,386,753,811,613,848,725,315,872,487,512])

def func_aplicada(x):
    return (beta_last -1)*math.log(x)-(x/alfa)**beta_last

alfa = 688.916073521629
beta_last = 3.979166666666667

suma=0
samples=data.shape[0]
for i in range(0,samples):
    suma += func_aplicada(data[i])

print('Cantidad de muestras = ',samples, '/ sumaacum =',suma)

import pulp as pl

model_MPL = pl.LpProblem("MPL", pl.LpMaximize)

beta_var = pl.LpVariable("beta_var",beta_last*0.5 , beta_last*1.5)
alfa_var = pl.LpVariable("alfa_var", alfa*0.5, alfa*1.5)

model_MPL += alfa_var>=0.1
model_MPL += beta_var>=0.1

model_MPL += samples * (math.log(beta_var) - beta_var * math.log(alfa_var)) + suma

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-52-08c6614fb718> in <module>
     22 model_MPL += beta_var>=0.1
     23
---> 24 model_MPL += samples * (math.log(beta_var) - beta_var * math.log(alfa_var)) + suma

TypeError: must be real number, not LpVariable

A: As the error indicates alpha_var and beta_var are of the type LpVariable but you want there numerical value.
Call alpha_var.value() to get the value of a LpVariable.
model_MPL += samples * (math.log(beta_var.value()) - beta_var.value() * math.log(alfa_var.value())) + suma

A: I think you need to use lpSum in the objective function
import pulp as pl

model_MPL = pl.LpProblem("MPL", pl.LpMaximize)

beta_var = pl.LpVariable("beta_var",beta_last*0.5 , beta_last*1.5)
alfa_var = pl.LpVariable("alfa_var", alfa*0.5, alfa*1.5)

model_MPL += alfa_var>=0.1
model_MPL += beta_var>=0.1

model_MPL += lpSum([sample * (math.log(beta_var) - sample * beta_var + sample * math.log(alfa_var))
                    for sample in samples]) + suma


text:
Q: Setup pull requests with git flow and azure pipelines I'm trying to setup a library project using DevOps. The branching strategy choosed is git-flow in order to have use git version and follow semver with releases and hotfixes.
So i tried was to protect both develop and release branches by activating pull requests.
Everything works fine unless a release is going to be closed. Here I see two problems:

*

*In git-flow the system try to realign develop from master, but devops doesn't know this is git-flow and just merges release to master.

*Develop branch is protected, so if i want to realign manually i should create a new pull request, from master to a feature branch in order to solve conflicts

I'm not sure about the correctnes of the implemented workflow. Is there a better way to accomplish this realignment?
Any suggestions are welcome
Thanks

A: At present, azure devops is designed like this. Devops can only be one-to-one branch merge at the same time.The release branch cannot be merged into the master branch and into the develop branch at the same time.

When the release is finished, the release branch is merged into master
  and into develop too, to make sure that any changes made in the
  release branch aren't accidentally lost by new development.

This feature described in git flow cannot be implemented in azure Devops.
So, your understanding is correct, you can do it manually by your method, although this may be a bit inconvenient.


text:
Q: Host main domain on Apache and some of the sub-domains on Nginx I recently bought a linode 1GB plan. Installed Apache on it, had my website up and running on it.
However I installed gitlab on the server and mapped it to a sub-domain. Since the installation guides recommended using Nginx as the server, I installed it and is running on port 80. Currently my apache is not running since there are port conflicts.
But I fixed it by editing the /etc/apache2/ports.conf file and instructing apache to serve on a different port.
Now when I visit the main domain that is pointing to a port(8000) and using apache doesn't show up.
gitlab is installed at http://gitlab.myserver.com and I am able to access it., but if I try to navigate to http://myserver.com, I get the content of http://gitlab.myserver.com
My gitlab config serving under Nginx is as follows:
# GITLAB
# Maintainer: @randx
# App Version: 5.0

upstream gitlab {
 server unix:/home/git/gitlab/tmp/sockets/gitlab.socket;
}

server {
  listen my_server_ip default_server;  # e.g., listen 192.168.1.1:80; In most    cases *:80 is a good idea
  server_name gitlab.myserver.com;         # e.g., server_name source.example.com;
  server_tokens off;     # don't show the version number, a security best practice
  root /home/git/gitlab/public;

# individual nginx logs for this gitlab vhost
access_log  /var/log/nginx/gitlab_access.log;
error_log   /var/log/nginx/gitlab_error.log;

location / {
  # serve static files from defined root folder;.
  # @gitlab is a named location for the upstream fallback, see below
  try_files $uri $uri/index.html $uri.html @gitlab;
}

# if a file, which is not found in the root folder is requested,
# then the proxy pass the request to the upsteam (gitlab unicorn)
location @gitlab {
  proxy_read_timeout 300; # https://github.com/gitlabhq/gitlabhq/issues/694
  proxy_connect_timeout 800; # https://github.com/gitlabhq/gitlabhq/issues/694
  proxy_redirect     off;

  proxy_set_header   X-Forwarded-Proto $scheme;
  proxy_set_header   Host              $http_host;
  proxy_set_header   X-Real-IP         $remote_addr;

  proxy_pass http://gitlab;
 }
}

My Apache config for myserver.com is as follows:
# domain: myserver.com
# public: /home/me/public/myserver.com/

<VirtualHost *:8000>
 # Admin email, Server Name (domain name), and any aliases
 ServerAdmin webmaster@myserver.com
 ServerName  www.myserver.com
 ServerAlias myserver.com

 # Index file and Document Root (where the public files are located)
 DirectoryIndex index.html index.php
 DocumentRoot /home/me/public/myserver.com/public

 # Log file locations
 LogLevel warn
 ErrorLog  /home/me/public/myserver.com/log/error.log
 CustomLog /home/me/public/myserver.com/log/access.log combined
</VirtualHost>

Where am I going wrong?

A: A good solution is to continue to run Nginx on port 80, while adding proxy directives to Nginx to serve as a proxy for specific domains that are running on Apache. An example Nginx configuration:
server {
    server_name  www.myserver.com;
    server_name myserver.com;

   location / {
      proxy_pass http://127.0.0.1:8000;
   }
}

I do this myself, and it works great.

A: I solved the issue. The issue was with the following line in my gitlab config:
server {
  listen my_ip default_server;
  server_name gitlab.myserver.com;         # e.g., server_name source.example.com;
  server_tokens off;     # don't show the version number, a security best practice
  root /home/git/gitlab/public;
  ......
}

I changed this to the following:
server {
      listen 80;
      server_name gitlab.myserver.com;         # e.g., server_name source.example.com;
      server_tokens off;     # don't show the version number, a security best practice
      root /home/git/gitlab/public;
      ......
    }

And I followed your instructions on serving sites on apache via nginx by using proxy_pass
Thanks a lot..
Cheers....


text:
Q: How can I find out which columns in a Postgres database could be NOT nullable? We have some legacy code+data which was a bit lazy when it comes to setting NOT NULL restrictions on columns (ditto for the code which generates the data).
It's not always known whether these columns should be nullable or not (sometimes features were written years ago).
It would be great to look in our real data to see if any of these columns are NULLABLE but happen to have no NULL values in. We might consider some of these as candidates to add not null restrictions on.
(Obviously, merely having no nulls doesn't mean it this doesn't necessarily mean they should be not-nullable: we might just have got unlucky, but it's a good place to start)

A: Here is what I came up with:
CREATE OR REPLACE FUNCTION any_is_null(col TEXT, tab TEXT, OUT tmp BOOL) RETURNS boolean
AS $$
  BEGIN
    EXECUTE format('SELECT
                   true
                   from %s
                   WHERE %s IS NULL LIMIT 1
                   ', tab, col) into tmp;
  END;
$$ LANGUAGE plpgsql;

select c.table_schema,
       c.table_name,
       c.column_name,
       case c.is_nullable
            when 'NO' then 'false'
            when 'YES' then 'true'
       end as nullable,
       CASE
         WHEN any_is_null(c.column_name, c.table_name) IS NULL
            AND c.is_nullable = 'YES'
         THEN true
         ELSE FALSE
       END as could_be_non_nullable

from information_schema.columns c
join information_schema.tables t
     on c.table_schema = t.table_schema
     and c.table_name = t.table_name
where c.table_schema in ('public')
      and t.table_type = 'BASE TABLE'
order by table_schema,
         table_name,
         column_name;

Replace the where c.table_schema in ('public') with the schema(s) you want to focus on.
Don't forget to drop the function after you're done.
PS: This will probably max out your database if you have a lot of columns with no NULL values in as each column will get full table-scanned) so be careful!


text:
Q: symfony dynamically add translation based on condition I'm searching for a way to add a translation to an existing translation catalogue during runtime.
I have a working symfony 2.3 application which uses translations in de/en/fr/it and fetches all available translation keys from /Resources/translations/messages..yml.
Now if a user logs in I want to have the possibility to override some of the already loaded labels based on setting for that user (e.g. textfield in DB which holds key-value-pairs).
E.g.
messages.en.yml
  company.name.short: Company profile

Usersetting:
  company.name.short: Profile for company

I found no way to add/override keys to the existing catalogue or to make them available in twig. Is there a Bundle or a setting or some Symfony magic to get this to work?

A: You'll probably want to extend Symfony's own translation class for this. This article explains how to do that:
http://www.webtipblog.com/extend-symfony-2-translator-to-log-untranslated-messages-to-a-database/
The key point is to override the "translator.class" parameter in your config, and then point it to your own class that first checks for database overrules and will defer to the symfony default implementation if it cannot find one.


text:
Q: If I specify a has_many :through association in Ruby on Rails, do I have to create a model for the 3rd table? Let's say I have
class CreateAppointments < ActiveRecord::Migration
  def change
    create_table :physicians do |t|
      t.string :name
      t.timestamps null: false
    end

    create_table :patients do |t|
      t.string :name
      t.timestamps null: false
    end

    create_table :appointments do |t|
      t.belongs_to :physician, index: true
      t.belongs_to :patient, index: true
      t.datetime :appointment_date
      t.timestamps null: false
    end
  end
end

1- Do I have to define again the associations on the model file? which leads me to my next question....
2- Do I have to create a model for this third table of appointments or just run the migration and the Active Record will take care of updating it everytime a doctor and a patient updates? when will the insert to this third table will be triggered in this type of association?

A: There is alot of magic inside of active record, so i understand where you are coming from.

*

*Yes, The migration will not add the proper associations to your ActiveRecord models.  Migrations are there to make changes to the database.

*Yes, if you did not generate this using rails g scaffold or model, then you will need to create an Appointment class that inherits from ActiveRecord::Base in order to work with it through the orm.  Then put the proper associations on them (patients have many appointments, they would also have many doctors through appointments.  vice versa for doctors.


text:
Q: click events on flags doesn't work in Highstocks Hi everyone I need to convert some code from old highstock lib to new one, but I can't make the click event work on flags. I am adding example of what happens. It always fires first series events, but I need to get flag event and use its data later on. also, this data will be later on added dynamically.
PS. It needs to work without jQuery.
Thank you

var DD = [
 {x: 1438639200000},
 {x: 1438719200000}
];

var chart = Highcharts.stockChart('container', {
 rangeSelector: {
  selected: 0
 },
 series: [{
  name: 'ADBE',
  data: ADBE,
  point:{
   events: {
    click: function () {
     alert('first Series');
    }
   }
  }
 },{
  name: 'Flags',
  type: 'flags',
  data: DD,
  cursor: 'pointer',
  point: {
   events: {
    click: function () {
     alert('second Series');
    }
   }
  },
  zIndex: 500
 }]
});


text:
Q: Angular SPA for only authenticated portions of the site I am thinking of adding AngularJS to a project I'm working on.
To avoid dealing with SEO issues I think I just want the single page app experience for authenticated users on pages where SEO is not an issue.
Can I have my rails routes and angular routes working essentially side by side?


text:
Q: How to create an undeletable app in Android? At first: Yes I've seen the answers with "device administrator" in similar questions, which doesn't work in this case.
I want to make an app just for me against thieves. I know there are a bunch of them out there, but I don't want to trust a third party with location history. The app should only collect the current position every 2 minutes and upload it to my own server.
But I am aware, that thieves know how to factory reset phones, so I need an option, to make it impossible to delete an app (without flashing a new rom).
My first thought is to flash the app with a custom recovery, to make it part of the rom. But I don't know where I have to put the file (i guess a *.jar or even an executable arm file) and what APIs or syscalls I can still use on that level.
I would be glad if someone knows an answer to this. Thanks in advance :)


text:
Q: Taylor's Theorem For Error Approximation I'm trying to evaluate a function $f(t)$ with a given $t$ value to within 10$^{-5}$.
So, if I use Taylor's Theorem :
$f(a)+f′(a)1!(x−a)+f′′(a)2!(x−a)2+⋯+f(n)(a)n!(x−a)n.$
Would my $t$ value = $a, f(t) = f(a),$ and $ n= 5$? Meaning that I would have to evaluate the 5th derivative of my $f(x)$?

A: Use this:

Lagrange's Form of the Remainder: If $f^{(N+1)}$ is continuous on an open interval $I$ that contains $a$, and $x$ is in $I$, then there
  exists a number $c$ between $a$ and $x$ such that
  $$R_N(x)={f^{(N+1)}(c)\over (N+1)!}(x-a)^{N+1}.$$

You didn't tell us what your $f(x)$ was or the center of the series, $a$, or the $x$ value at which you want the approximation smaller than $10^{-5}$. But given those ingredients, you find the smallest positive integer $N$ which solves the inequality
$$
|R_N(x)|<10^{-5}.
$$
In practice, you can replace $|f^{(N+1)}(c)|$ with $\max_{x\in I}|f^{(N+1)}(x)|$ since the latter is an upper bound on the former. This will provide an upper bound on $|R_N(x)|$.


text:
Q: recipient-list-router Spring integration i'm new in spring integration.
In my configuration of spring integration i have :
  <int:chain input-channel="channel1_2" output-channel="channel1_3">
    <int:service-activator>
        <bean class="com.csv.CSVEntreprise"/>
    </int:service-activator>
</int:chain>

<int:channel id="channel1_3"/>

<int:recipient-list-router id="id-entreprise" input-channel="channel1_3">
    <int:recipient channel="channel1_3TRUE" />
    <int:recipient channel="channel1_3FALSE"/>
</int:recipient-list-router>

<int:channel id="channel1_3TRUE"/>
<int:channel id="channel1_3FALSE"/>

In the class CSVEntreprise i definied method with Boolean return, i want when it's return true use the channel channel1_3TRUE and when it's return false use the channel  channel1_3FALSE ?

A: You might want to consider using a header value router (http://docs.spring.io/spring-integration/reference/html/messaging-routing-chapter.html).
You use your CSVEnterprise bean to set the Boolean value in the MessageHeaders.
Your @ServiceActivatorshould set the value of your header:
return MessageBuilder.withPayload(message)
                    .setHeader("MY_HEADER", Boolean.FALSE).copyHeadersIfAbsent(headers).build();

Then, use a header value router to determine which channel to route the order.
<int:header-value-router input-channel="channel1_3" header-name="MY_HEADER" id="headerValueRouter">
    <int:mapping value="true" channel="channel1_3TRUE"/>
    <int:mapping value="false" channel="channel1_3FALSE" />
</int:header-value-router>


text:
Q: Deploy angular 6 in Azure I am trying to deploy an example app on the azure portal and am encountering some difficulties.
At first I'm just testing, so I've created an angular app with just ng new poc-pwa-angular-v2. After that I went up to a Bitbucket repository.
In Azure I created a web application and in the deployment options I connected on bitbucket and set my master branch.
I tried to generate the scripts with kudu (deploy.cmd and .deployment), but I got an error on the first deploy.
Can anyone give a tip?
Look at my log.
Command: deploy.cmd
Handling node.js deployment.
Creating app_offline.htm
KuduSync.NET from: 'D:\home\site\repository' to: 'D:\home\site\wwwroot'
Copying file: 'package.json'
Deleting app_offline.htm
Invalid start-up command "ng serve" in package.json. Please use the format "node <script relative path>".
Looking for app.js/server.js under site root.
Missing server.js/app.js files, web.config is not generated
The package.json file does not specify node.js engine version constraints.
The node.js application will run with the default node.js version 10.6.0.
Selected npm version 6.1.0

> poc-pwa-angular-v2@0.0.0 postinstall D:\home\site\wwwroot
> npm run build

> poc-pwa-angular-v2@0.0.0 build D:\home\site\wwwroot
> ng build

'ng' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! poc-pwa-angular-v2@0.0.0 build: `ng build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the poc-pwa-angular-v2@0.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     D:\local\AppData\npm-cache\_logs\2018-11-13T22_16_35_989Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! poc-pwa-angular-v2@0.0.0 postinstall: `npm run build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the poc-pwa-angular-v2@0.0.0 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
Failed exitCode=1, command="D:\Program Files (x86)\nodejs\10.6.0\node.exe" "D:\Program Files (x86)\npm\6.1.0\node_modules\npm\bin\npm-cli.js" install --production
npm ERR!     D:\local\AppData\npm-cache\_logs\2018-11-13T22_16_36_053Z-debug.log
An error has occurred during web site deployment.
Invalid start-up command "ng serve" in package.json. Please use the format "node <script relative path>".\r\nMissing server.js/app.js files, web.config is not generated\r\n'ng' is not recognized as an internal or external command,\r\noperable program or batch file.\r\nnpm ERR! code ELIFECYCLE\r\nnpm ERR! errno 1\r\nnpm ERR! poc-pwa-angular-v2@0.0.0 build: `ng build`\r\nnpm ERR! Exit status 1\r\nnpm ERR! \r\nnpm ERR! Failed at the poc-pwa-angular-v2@0.0.0 build script.\r\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\r\n\r\nnpm ERR! A complete log of this run can be found in:\r\nnpm ERR!     D:\local\AppData\npm-cache\_logs\2018-11-13T22_16_35_989Z-debug.log\r\nnpm ERR! code ELIFECYCLE\r\nnpm ERR! errno 1\r\nnpm ERR! poc-pwa-angular-v2@0.0.0 postinstall: `npm run build`\r\nnpm ERR! Exit status 1\r\nnpm ERR! \r\nnpm ERR! Failed at the poc-pwa-angular-v2@0.0.0 postinstall script.\r\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\r\n\r\nnpm ERR! A complete log of this run can be found in:\r\nnpm ERR!     D:\local\AppData\npm-cache\_logs\2018-11-13T22_16_36_053Z-debug.log\r\nD:\Program Files (x86)\SiteExtensions\Kudu\78.11022.3613\bin\Scripts\starter.cmd deploy.cmd

A: The issue is that on Azure Angular cli is not installed.
You will need to do ng build locally(or as part of your build and release pipe line. You can also use Azure DevOps builds for that where you have 240 build minutes for free) and upload it to (just options):

*

*Azure App service.

*Upload it to blob storage and use Azure functions proxy to serve your files.

*If you need server side rendering then you will need to upload it as an NodeJs app or part of .net app

A: Thanks for the time of yours, in this case I removed the package.json script block and went up again and it worked.
...
"version": "0.0.0",
  "scripts": {
  },
...


text:
Q: How to apply sum and groupby on a list in Scala? I am trying to use groupby method on transactionDay and take the sum of the transactionAmount. and print the output.
case class Transaction(
  transactionId: String,
  accountId: String,
  transactionDay: Int,
  category: String,
  transactionAmount: Double)

I created a list like this:
val transactions: List[Transaction] = transactionslines.map { line =>
  val split = line.split(',')
  Transaction(split(0), split(1), split(2).toInt, split(3), split(4).toDouble)
}.toList

Can anyone help with using the groupBy method.
If you have any documents to share it would be really helpful.

A: Following code should work to get the solution you require
val transactions = transactionslines.map( line => line.split(","))
  .map(split => Transaction(split(0), split(1), split(2).toInt, split(3), split(4).toDouble))
transactions.groupBy(_.transactionDay).mapValues(trans => trans.map(amount => amount.transactionAmount).sum).foreach(println)


text:
Q: What does "That guy's brain is a bag full of cats." imply or mean in the context? In the humorous exchange in the Avengers I, Bruce said:

"I don't think we should be focusing on Loki," Bruce said. "That guy's
  brain is a bag full of cats. You can smell the crazy on him."
Thor took a step toward Bruce. "Have a care how you speak," he warned.
  "Loki is beyond reason, but he is of Asgard . . . and he is my
  brother."
"He killed eighty people in two days," Natasha pointed out.
Acknowledging this, Thor backed down a little. "He's adopted."

I could not locate the exact meaning/implication of "cats" here. So far I have three guesses:
1) There is a phrase "let the cats out of the bag", meaning secrets leaked; so does this mean "Loki's head is full of (dark) secrets?
2) According to Collings dictionary: "a bag of cats" is an Irish informal way of speaking someone "bad-tempered"; so does this mean "Loki is a bad-tempered person? (which I personally don't think it fits the context and the usage of Irish English does not make sense to me in an American movie.)
3) In my culture, cat has some connotation of "smart\clever", which leads to "sly"; so does this sentence mean "Loki's brain is very smart and he is sly?"
Anyone could help me with the "cats" here please? Thanks a lot.

A: "A bag full of cats" is an Irish expression for a bad-tempered person and that does seem the closest definition to what is intended here. However, that isn't widely known and I'm not sure that is what influenced your quote from Avengers.
Not all metaphors and expressions are out of a book - some are made up on the spot! I think the writer just thought that cats can act crazy, a lot of cats in a bag would act super crazy, so let's say this crazy guy's brain is a bag of cats!

A: "A brain like a bag full of cats', is a chaotic brain filled with violent contradictory ideas and feeling all working against each other.


text:
Q: adhoc builds for keyboard extensions I am creating an adhoc build for a keyboard extension in ios 8. Somehow, the build fails to install in the iOS 8 iPhone when the build is shared via Testflight.
Is there a special way to prepare adhoc build for extensions or a different way of preparing them for Testflight? For example, is the bundle id for the target of the container app the same as the bundle id of the target for the extension?
Thanks a lot.

A: There is not any special way to create a adhoc build for iOS App extension just create your App adhoc build and its ready to upload on Testflight.
Bundle id should be different for App extension.
For example:
App bundle id: com.abc.myapp
Extension bundle id: com.abc.myapp.myextension


text:
Q: Strange noise when holding MacBook Pro I recently bought a MacBook Pro Retina and for now I'm a little bit worried. Everytime I hold it up by one of its edges or even press this part (video), it makes this strange noise, like its gonna break. I thought the material was resistant.
I'm pressing the downside of the notebook, like at the start of the notebook. Downside, of course. If I hold the notebook to get it by this particular corner it also makes this strange noise. I'm a little worried.
Should I take it to an Apple Store?

Here is a video with the strange sound!
Picture of the exact corner:

A: I had a problem where is sounded like a "click" when pressing on the area you described. This was quite annoying while typing.
To resolve this I added a little bit of sewing oil to the screws and edges of the case where it makes the noise.

*

*Press on the area where it does make a sound

*Add a little drop of sewing oil (not too much) to the screws and edges

*Press a few times times.

*Wipe it the excesses and check if the noise is gone


text:
Q: Union Bound of two events? Inequality 1
\begin{align}
\mathbb{P}\left(\frac{1}{n} \sum_{i=1}^{n}\left(f\left(x_{i}\right)-\mathbb{E}[f]\right) z_{i} \geq \frac{\epsilon}{8}\right) \leq 2 \exp \left(-\frac{\epsilon^{2} n d}{9^{4} c L^{2}}\right)
\end{align}
Since we assumed that the range of the functions is in $[-1,1]$ we have $\mathbb{E}[f] \in[-1,1]$ and hence:
Inequality 2
$$
\mathbb{P}\left(\exists f \in \mathcal{F}: \frac{1}{n} \sum_{i=1}^{n} \mathbb{E}[f] z_{i} \geq \frac{\epsilon}{8}\right) \leq \mathbb{P}\left(\left|\frac{1}{n} \sum_{i=1}^{n} z_{i}\right| \geq \frac{\epsilon}{8}\right)
$$
By Hoeffding's inequality, the above quantity is smaller than $2 \exp \left(-n \epsilon^{2} / 8^{3}\right)$ (recall that $\left.\left|z_{i}\right| \leq 2\right)$.
Thus we obtain with an union bound:
$$
\begin{aligned}
\mathbb{P}\left(\exists f \in \mathcal{F}: \frac{1}{n} \sum_{i=1}^{n} f\left(x_{i}\right) z_{i} \geq \frac{\epsilon}{4}\right) & \leq|\mathcal{F}| \cdot \mathbb{P}\left(\frac{1}{n} \sum_{i=1}^{n}\left(f\left(x_{i}\right)-\mathbb{E}[f]\right) z_{i} \geq \frac{\epsilon}{8}\right)+\mathbb{P}\left(\left|\frac{1}{n} \sum_{i=1}^{n} z_{i}\right| \geq \frac{\epsilon}{8}\right) \\
& \leq 2|\mathcal{F}| \cdot \exp \left(-\frac{\epsilon^{2} n d}{9^{4} c L^{2}}\right)+2 \exp \left(-\frac{n \epsilon^{2}}{8^{3}}\right)
\end{aligned}
$$

I am not getting how Union bound is getting happened using Ineq 1 and 2. Can anyone help me with that how they able to reach last inequality?

A: By the triangle inequality, the event
$$A=\left\{\exists f \in \mathcal{F}: \frac{1}{n} \sum_{i=1}^{n} f\left(x_{i}\right) z_{i} \geq \frac{\epsilon}{4}\right\}$$
is contained in the union of the two events
$$B=\left\{\exists f \in \mathcal{F}: \frac{1}{n} \sum_{i=1}^{n}\left(f\left(x_{i}\right)-\mathbb{E}[f]\right) z_{i} \geq \frac{\epsilon}{8}\right\}$$
and
$$D=\left\{\exists f \in \mathcal{F}: \ \frac{1}{n} \sum_{i=1}^{n} \mathbb{E}[f] z_{i} \geq \frac{\epsilon}{8}\right\} \,.
$$
Moreover, $B=\bigcup_{f \in \mathcal{F}}B_f$ where
$$B_f=\left\{  \frac{1}{n} \sum_{i=1}^{n}\left(f\left(x_{i}\right)-\mathbb{E}[f]\right) z_{i} \geq \frac{\epsilon}{8}\right\} \,,
$$
so
$$A\subset \left(\bigcup_{f \in \mathcal{F}} B_f \right) \cup B \,$$
To this relation the union bound is applied, together with inequality 2 to bound $P(D)$.


text:
Q: Is $G$ a cyclic group?
Let $G = \{ z \in \mathbb{C} | z^n= 1 \ \text{for some  positive integer}\  n \}$, with group structure given by multiplication of complex numbers.

Choose the correct option:
$1.$ $ G$ is  a  group of finite order
$2.$ $ G$ is a group of infinite order, but every element of G has finite order
$3.$ $G$ is a cyclic group
$4.$ None of these
My attempt: options $1, 3$ are true.
$G$ consists of all $n$-roots of unity for some positive integer $n$.  Any element of $G$ can be uniquely written as $e^{({\frac{2i\pi k}{n}})}$ for some $k\in \{ 0,\ldots ,n-1\}$ that is prime with $n$.
$\exp\left( \frac{2k\pi i}{n}\right)^n=\exp\left( \frac{2\pi ki}{n}\cdot n\right)=\exp(2\pi k i)=1$
So  $G$ is a cyclic group and $G$ is a group of finite order.
Is my solution correct?

A: No! $G$ is not cyclic( If it were, then upto isomorphism, $G \sim (\Bbb Z,+)$ .Note that $-1$ has order $2$ in $G$ but in $(\Bbb Z,+)$, there is no such element )
The group $G$ is actually union of all $n$-th root of unity. That is $$G:=\cup_{n \in \Bbb N} \{z \in \Bbb C: z^n=1\}$$
So $G$ is a group of infinite order. Also note that , for $z \in G$, order of $z$ is atmost $n$, so second option is true!


text:
Q: Batch For loop exclude file name that contains I have a simple batch file that will loop through all *Test.htm files and copy them.  Some of the files will contain a string that I don't want to copy.
FOR /R "C:\" %%g IN (*Test.htm) DO  (
echo %%g
)

What I want in pseudo code:
@echo off
FOR /R "C:\" %%g IN (*Test.htm) DO (
   if %%g contains "Exclude" do nothing
else
   copy...
)

A: For filename:
@echo off

FOR /R "C:\" %%g IN (*Test.htm) DO (
   (Echo "%%g" | FIND /I "Exclude" 1>NUL) || (
       Copy "%%g"...
   )
)

For File content:
@echo off

FOR /R "C:\" %%g IN (*Test.htm) DO (
   (Type "%%g" | FIND /I "Exclude" 1>NUL) || (
       Copy "%%g"...
   )
)


text:
Q: Writing to Descriptors BLE on iOS device I have created a simple application and my requirement is to write to a descriptor to a Peripheral in order to get Sensor data. There is a method writeValue(data:Data, descriptor: CBDescriptor) on the apple documentation, but when I try to execute it I get an NSException stating

"Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Client Characteristic Configuration descriptors must be configured using setNotifyValue:forCharacteristic:'".

Can someone please tell me how to write for a descriptor?

A: Rather than calling WriteValue, you should call SetNofifyValue.
I'm using Xamarin, and the code is as follows (it should be the same principle for xcode)
void SwitchNotify(CBCharacteristic mychar,bool SwitchOn)
{
    mychar.Service.Peripheral.SetNotifyValue(SwitchOn,mychar);
}

I'm not sure if there's a way of writing the descriptors directly, or why Apple have decided to only allow notify/indicate by using this method. Android and Windows (UWP) both allow direct writing of descriptors.


text:
Q: How to load jQuery from the iframe to its parent page I have a below code in my iframe and it contain some jQuery and I want to call it from the iframe to parent page but it not working and path of the iframe is the content/test/doubleimg.html

And double img contain some jQuery function which is execute onload of the page and it work fine but if i put it in iframe its not working.
And my html markup like and path of the parent file is template/category.html

-----------
-----------

So please suggest me the idea how can I use jQuery from the iframe and my jQuery is execute on the page load.
Actually I am trying to call api of the Bigcommerce but for that I need to set https and I can't set it because it not allowed in the Bigcommerce to set https in category page url
And if I am not set https then the API returns a 401 authentication error
So please help me out from this.

A: Something like this, if documents are in the same domain:
var iframe = document.getElementsByTagName('iframe')[0];
var jQuery = iframe.contentWindow.jQuery;
alert(jQuery);

See my jsfiddle for more information. It include other jsfiddle in iframe there I inited jQuery.

A: try this
window.parent.document.wirte('');


text:
Q: Memory limit wamp x64 bigger than 4GB I have install WAMP server X64 on my  localhost and was expecting to make it work over 4GB (I have installed 8 GB), so I edited the php.ini the variable to memory_limit = 6000 M so it uses 6 GB but doesn't work, I get
[05-Nov-2016 14:26:29 UTC] PHP Fatal error:  Allowed memory size of 262144 bytes exhausted (tried to allocate 989 bytes) in F:\SERVER\www\index.php on line 141
If I add 4095 M it works. And it is indeed the x64 version for apache and for WAMP
WAMP X64 Proof

APACHE 64 bit proof

PHP VERSION - Says archtecture 64.

What should I do in order to get more than 4095 M?


text:
Q: How to zip and pass-through files to browser on-the-fly? I would like to implement feature like GMail's "get all attachments as zipped file".
Is there a way to select multiple files on server, zip them and on-the-fly pass-through to browser? (something similar to PHP's function readfile used for attachments streaming)
[EDIT]
It seems you misunderstood my intentions, all given examples require to create and close archive before its being sent, I want to stream while archive is created.
Something like unix command (from zip manual):
zip -r - . | dd of=/dev/nrst0 obs=16k
[EDIT2]
I have tons of ~2MB files (> 100) to serve, waiting for creation of tmp zip file forces to implement queuing mechanisms and takes storage space... If it can be done through stream/pipe directly to browser, why I should write tmp zip in filesyetm?

A: Have a look at ZipStream-PHP library - it claims to do what you need.

A: Your PHP host could happen to have the zip extension installed.
If so, you should use it. (performance reasons)
Otherwise, for zip archiving, a good library with no dependencies is PclZip.
There obviously was a PEAR library for it, but is now deprecated and focus has been moved over to the PECL (binary) extension I already mentioned. (the whole PEAR ecosystem is gradually rotting down, anyway)


text:
Q: Calculate mean of specific row pattern I have a dataframe like this:
V1 = paste0("AB", seq(1:48))
V2 = seq(1:48)

test = data.frame(name = V1, value = V2)

I want to calculate the means of the value-column and specific rows.
The pattern of the rows is pretty complicated:
Rows of MeanA1: 1, 5, 9
Rows of MeanA2: 2, 6, 10
Rows of MeanA3: 3, 7, 11
Rows of MeanA4: 4, 8, 12

Rows of MeanB1: 13, 17, 21
Rows of MeanB2: 14, 18, 22
Rows of MeanB3: 15, 19, 23
Rows of MeanB4: 16, 20, 24

Rows of MeanC1: 25, 29, 33
Rows of MeanC2: 26, 30, 34
Rows of MeanC3: 27, 31, 35
Rows of MeanC4: 28, 32, 36

Rows of MeanD1: 37, 41, 45
Rows of MeanD2: 38, 42, 46
Rows of MeanD3: 39, 43, 47
Rows of MeanD4: 40, 44, 48

As you see its starting at 4 different points (1, 13, 25, 37) then always +4 and for the following 4 means its just stepping 1 more row down.
I would like to have an output of all these means in one list.
Any ideas? NOTE: In this example the mean is of course always the middle number, but my real df is different.

A: Not quite sure about the output format you require, but the following codes can calculate what you want anyhow.
calc_mean1 <- function(x) mean(test$value[seq(x, by = 4, length.out = 3)])
calc_mean2 <- function(x){sapply(x:(x+3), calc_mean1)}
output <- lapply(seq(1, 37, 12), calc_mean2)
names(output) <- paste0('Mean', LETTERS[seq_along(output)]) # remove this line if more than 26 groups.
output

## $MeanA
## [1] 5 6 7 8

## $MeanB
## [1] 17 18 19 20

## $MeanC
## [1] 29 30 31 32

## $MeanD
## [1] 41 42 43 44

A: An idea via base R is to create a grouping variable for every 4 rows, split the data every 12 rows (nrow(test) / 4) and aggregate to find the mean, i.e.
test$new = rep(1:4, nrow(test)%/%4)
lapply(split(test, rep(1:4, each = nrow(test) %/% 4)), function(i)
                                              aggregate(value ~ new, i, mean))

#    $`1`
#      new value
#    1   1     5
#    2   2     6
#    3   3     7
#    4   4     8

#    $`2`
#      new value
#    1   1    17
#    2   2    18
#    3   3    19
#    4   4    20

#    $`3`
#      new value
#    1   1    29
#    2   2    30
#    3   3    31
#    4   4    32

#    $`4`
#      new value
#    1   1    41
#    2   2    42
#    3   3    43
#    4   4    44

A: And yet another way.
fun <- function(DF, col, step = 4){
  run <- nrow(DF)/step^2
  res <- lapply(seq_len(step), function(inc){
    inx <- seq_len(run*step) + (inc - 1)*run*step
    dftmp <- DF[inx, ]
    tapply(dftmp[[col]], rep(seq_len(step), run), mean, na.rm = TRUE)
  })
  names(res) <- sprintf("Mean%s", LETTERS[seq_len(step)])
  res
}

fun(test, 2, 4)
#$MeanA
#1 2 3 4
#5 6 7 8
#
#$MeanB
# 1  2  3  4
#17 18 19 20
#
#$MeanC
# 1  2  3  4
#29 30 31 32
#
#$MeanD
# 1  2  3  4
#41 42 43 44

A: Since you said you wanted a long list of the means, I assumed it could also be a vector where you just have all these values. You would get that like this:
V1 = paste0("AB", seq(1:48))
V2 = seq(1:48)

test = data.frame(name = V1, value = V2)
meanVector <- NULL

for (i in 1:(nrow(test)-8)) {
  x <- c(test$value[i], test$value[i+4], test$value[i+8])
  m <- mean(x)
  meanVector <- c(meanVector, m)
}


text:
Q: Changing arrowhwead size and other parameters when plotting vector fields When plotting vector fields how to keep arrow head size constant, have the arrow LENGTH proportional to the MAGNITUDE of each vector, change the thickness of the vectors (but keep this constant) and change the vector color.
It would also be nice to have the vector TAIL (rather than the vector midpoint) drawn from the appropriate vector point.
The problem seems to be that in v.10 the VectorStyle command only executes the first argument i

A: This should give you a start:
VectorPlot[{y, -x}, {x, -3, 3}, {y, -3, 3},
  VectorScale -> {Medium, 1/2, Automatic},
  VectorStyle -> {{Thick, Red}}
]

For changing the position of vector arrows please see:

*

*Unexpected behavior from VectorPlot


text:
Q: Multiple apps in express js (node js) I have a situation where I have tow express js apps App1 and App2 running on port 80 and 8080 respectively. I have declared these apps in same js file.....now I wanted to share some data from App2 request to App1. Is it possible if yes how I can do that? or can we forward App2 request to App1 directly.

A: You can easily do this with vhost() in Express. All you have to do is
var express = require('express');
var app = express();

app
.use(express.vhost('localhost', require('/path/to/website1/app.js').app))
.use(express.vhost('localhost2', require('/path/to/website2/app.js').app))
.listen(3000);

This will listen on port 3000, and check for specific host names - in this case, localhost and localhost2. If one of those hosts match, it will get an instance of their 'app' to run/use.
In this case you will have to export your app object from app.js to use all the methods and API's you have, You can simply do this by
var express = require('express');
var app = exports.app = express();


text:
Q: Redirect Single Post CPT (Custom Post Type) to a specific URL I have a domain domain.com and subdomain materials.domain.com
At the domain.com scope, I created a custom post type called resources and a portfolio grid (using Elementor) to display it's featured image with the title.
When clicking on the grid item, the single post is shown for example: domain.com/resources/resource-title
I'd like to remove the single post from the domain and redirect on click to materials.domain.com/resource-title. I already have this page on the materialssubdomain).
How can I achieve that?

A: Sometimes this would be achievable with add_rewrite_url but it looks like in this case it's not as you need to redirect to a different domain.
In this case you need .htaccess or nginx rules to do this, so you need to add something like this to your nginx config for domain.com only, in order to rewrite those URLs:
rewrite ^/resources/(.+) https://materials.domain.com/$1 permanent;
You'll likely need to restart nginx after you add this to the config file.
Happy to help if this doesn't do exactly what you want. There's more examples of nginx rewrite rules here: https://www.thegeekstuff.com/2017/08/nginx-rewrite-examples/

A: If you want to do it from WordPress environment itself..
function wpse370481_redirect_url() {
    if ( is_singular( 'resources' ) ) {
        global $post;

        $path = $post->post_name;

        $redirect_url = 'https://materials.domain.com/' . $path;

        wp_redirect( $redirect_url );
        exit;

    }
}
add_action( 'template_redirect', 'wpse370481_redirect_url' );

Havn't tested this code as I currently don't have a setup to test this, but in theory, the code should work.


text:
Q: Applying force in zero seconds? How is this possible? $F\,\Delta t=m\,\Delta v$, is the equation of impulse. Let's say that I push a wall with my hands, we can have $0$ change in velocity; therefore, $F\,\Delta t=0$, since I'm pushing the wall there is force, the only way the equation equals zero is that $\Delta t$ equals zero, applying force in zero seconds? How is this be possible?

A:
the only way the equation equals zero is that Δ equals zero,
  applying force in zero seconds?

No. The force $F$ is the net force acting on the wall, not the force you apply to the wall. So the net force can be zero.
You apply a force $F$ to the wall. The floor that holds the wall in place applies an equal and opposite force of $F$ on the wall, for a net force on the wall of zero and no acceleration of the wall per Newton's second law $F_\text{net}=ma$.
At the same time you apply a force $F$ to the wall it applies an equal and opposite force $F$ on you per Newton's third law. But you do not accelerate because the static friction force between your feet and the floor is equal and opposite to the force the wall exerts on you, for a net force on you of zero.
Hope this helps.

A: Beware of blindly applying equations.
In thinking about the velocity of the wall, then for $F\Delta t=m\Delta v$, $F$ is the net force acting on the wall. If $\Delta v=0$, then we know that $F=0$ (and the same is true vice versa).
Note that this is just Newton's second law: $F=m\frac{\Delta v}{\Delta t}=ma$. If $a=0$ then we can conclude that the net force $F$ must be $0$.
Also, if we really did have $\Delta t=0$, then of course $\Delta v=0$ since nothing can change over no time.


text:
Q: Finding the equation of the tangent line for the curve $f(x)=x^2+\frac{2}{x}$ parallel to $3y-2x=5$
Find the equation of the tangent line for the curve defined by
$$f(x)=x^2+\frac{2}{x}$$
That is parallel to
$$3y-2x=5$$

Since
$$y=\frac{5+2x}{3}$$
The slope of the parallel line is $\frac{2}{3}$, so the tangent line is also $\frac{2}{3}$.
The derivative of the curve function is
$$f'(x) = 2x - \frac{2}{x^2}$$
So if I solve
$$2x - \frac{2}{x^2} = \frac{2}{3}$$
I would get the points where there is a tangent line such that the slope is $\frac{2}{3}$, right?
But as far as I'm concerned, it's not the points what I want. It's the equation for the tangent line itself.
What should I do?

A: Your idea is good to find the point on the curve for which the slope is equal to that of the specified line. Just find the point on the graph and write the equation for the line using that point.

A: Your tangent line will have the same slope as $3y-2x = 5$, so it will have a form
$3y - 2x = b$
Once you find an $(x, y) = (x, f(x))$ of the points where the tangent line is 2/3, apply it to the equation above and solve for $b$, that will be your solution(s).

A: the equation of tangent line
$$y=\frac{2}{3}x+b$$
if $(x_0,y_0)$ is a tangent point
$$y_0=\frac{2}{3}x_0+b$$
$$b=y_0-\frac{2}{3}x_0$$


text:
Q: Using multiple users in crontab script, silently fails when changing users I'm trying to run a bash script on a centos server. I've running the script as the root user (both for file permissions), but I also need to use the aws service permissions that belong to a service account. We have decided not to give the root account access to the AWS environment.
If I run the script manually ./disk-arcive.sh it works without a problem. When I run it from my crontab it silently fails when changing to the aws-cli-user. No error message, and only when started by cron.
How it is being called in Crontab sudo crontab -e:
0 20 * * * /bin/sh /etc/disk-arcive.sh

Summary of shell file:
#!/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin    <<Same as root

find (old stuff) >> /old-stuff.temp
while read line; do
    /opt/bin/encryption-tool "$line">> /encrypt_logfile.log     << key access requires root permission
done < /old-stuff.temp

while read line; do
    sudo -u aws-cli-user /usr/local/bin/aws s3 mv "$line.pgp" s3://mybucket"$line.pgp" >> /bucket_logfile.log     #<< switch to user fails, user needed for s3 permissions
    sudo -u aws-cli-user echo "User is now aws-cli-user" >> /bucket_logfile.log   #<< added for debugging, does not work
    echo "looks like $line is done" >> /bucket_logfile.log   #<< added for debugging, Works
done < /old-stuff.temp

exit

UPDATE1
I've updated the "user switching" lines to the following. It appears to fail differently however if I use any aws-s3 options (i.e. --sse or --acl) those are being read a part of the su options.
    su -l aws-cli-user -c '/usr/local/bin/aws s3 mv "$line.pgp" s3://mybucket"$line.pgp" --sse >> /bucket_logfile.log'     #<< switch to user fails, user needed for s3 permissions
    su -l aws-cli-user  -c 'echo "User is now aws-cli-user $(whoami)" >> /bucket_logfile.log'   #<< added for debugging, does not work. enters a blank line into the log file

The output of the echo line shows that the $line is now being passed when the user is switched.

A: OK got this working it took a few changes
su -l username -c command This allowed for the user change in cron
The next thing was working with single-quote and dubble-quotes to have the command "compiled" correctly, I only found one reference to this so I may have the terminology incorrect.
su -l aws-cli-user -c '/usr/local/bin/aws s3 mv "$line.pgp" s3://mybucket"$line.pgp" --sse >> /bucket_logfile.log'

The single quote has the user "compile" the command, and it doesn't know what the $line variable is so the command can not find a file reference.
su -l aws-cli-user -c "/usr/local/bin/aws s3 mv '$line.pgp' s3://mybucket'$line.pgp' --sse >> /bucket_logfile.log"

Now with double quotes the Root user compiles the work, including the $line variable, then passes the completed command to the other user to run. Because of this using $(whoami) would always show root even if the other user is performing the command with their permissions.


text:
Q: How can I check disk space used in a partition using the terminal in Ubuntu 12.04 LTS? I am using Ubuntu 12.04 LTS and I was wondering if there is a command that can tell the space used in a partition using the terminal. Like I want to use the su command to change to a user called admin (it is named admin). So I typed :
su admin

Entered the password
Now I want to see the disk space used in this partition. So.... Is there is a command fot that?

A: You can use df -Th to get the used space of partitions:
$ df -Th

Filesystem     Type      Size  Used Avail Use% Mounted on
/dev/sda9      ext4       22G   16G  4.8G  77% /
none           tmpfs     4.0K     0  4.0K   0% /sys/fs/cgroup
udev           devtmpfs  1.5G  4.0K  1.5G   1% /dev
tmpfs          tmpfs     297M  1.4M  295M   1% /run
none           tmpfs     5.0M  4.0K  5.0M   1% /run/lock
none           tmpfs     1.5G  616K  1.5G   1% /run/shm
none           tmpfs     100M   68K  100M   1% /run/user
/dev/sda5      fuseblk    53G   34G   19G  65% /media/Songs
/dev/sda7      fuseblk   103G   90G   14G  88% /media/Data
/dev/sda6      fuseblk    69G   34G   35G  50% /media/Movies
/dev/sda1      fuseblk    49G   36G   14G  72% /media/guru/0C64A7F864A7E326

You can also provide it with a specific partition if you want to view disk utilization of  only that partition:
$ df -Th /dev/sda9

Filesystem     Type  Size  Used Avail Use% Mounted on
/dev/sda9      ext4   22G   16G  4.8G  77% /

You can also use pydf or discus to get better representation in terminal.
You need to install these if you want to use it. Type:
sudo apt-get install pydf in terminal  to install pydf.
$ pydf
Filesystem Size Used Avail Use%                                      Mounted on
/dev/sda9   22G  16G 4893M 72.7 [#########################.........] /
/dev/sda7  103G  90G   13G 87.2 [##############################....] /media/Data
/dev/sda6   69G  34G   35G 49.3 [#################.................] /media/Movies
/dev/sda5   53G  34G   19G 64.5 [######################............] /media/Songs
/dev/sda1   49G  35G   14G 71.9 [########################..........] /media/guru/0C64A7F864A7E326

A: You can easily check disk space status with df -h.
Sometimes you might end up accidentally filling your hard disk via some automated processes you've set up. When that happened to me I needed to find where most of my disk space went. The following command was helpful for that task:
$ cd /
$ sudo du -sh ./*

This gives a list of files and folders in the current directory as well as the size of each one. If a directory is larger than it should be, cd to that directory and run sudo du -sh ./* again. Repeat until you've found what is using up most of your disk space.

A: The su command is completely irrelevant. The disk usage is the same for all users. Anyway, some relevant commands and their output on my system are:
terdon@oregano ~ $ df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda7              68G   23G   43G  35% /
udev                   10M     0   10M   0% /dev
tmpfs                 800M  1.6M  798M   1% /run
tmpfs                 5.0M     0  5.0M   0% /run/lock
tmpfs                 3.2G   12M  3.2G   1% /run/shm
/dev/sda6             290G  256G   20G  94% /home
tmpfs                 3.2G  992K  3.2G   1% /tmp
none                  4.0K     0  4.0K   0% /sys/fs/cgroup
/dev/sdc1             466G  379G   88G  82% /media/terdon/Iomega_HDD

For a specific partition:
terdon@oregano ~ $ df -h /dev/sda7
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda7              68G   23G   43G  35% /

Alternatively, though this only lists the size, not the %used:
terdon@oregano ~ $ lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 465.8G  0 disk
├─sda1   8:1    0  39.2M  0 part
├─sda2   8:2    0  14.7G  0 part
├─sda3   8:3    0  78.1G  0 part
├─sda4   8:4    0     1K  0 part
├─sda5   8:5    0     2G  0 part
├─sda6   8:6    0 294.4G  0 part /home
├─sda7   8:7    0  68.7G  0 part /
└─sda8   8:8    0   7.8G  0 part [SWAP]
sdc      8:32   0 465.8G  0 disk
└─sdc1   8:33   0 465.8G  0 part /media/terdon/Iomega_HDD
sr0     11:0    1  1024M  0 rom

Conversely, you can use the du command to print directory size which will give you the disk usage of a partition if you run it on a partition's mountpoint: du -xsch /home for example. The -x option will "skip directories on different file systems," which is helpful if you have other mount points nested below the partition's mount point (typically /).


text:
Q: Hive transform with Python library in a folder I'd like to run a Python script in my TRANSFORM that uses an external library, which I'm unable to install in the cluster.
For tests outside Hive, I could just copy the folder with the main files to my home directory, where the script is, and run from there, with an "import "
For Hive, I don't know how to use this library. I tried importing the files one by one with ADD FILE and also tried zipping and using ADD ARCHIVE, but I keep getting the message
FAILED: Execution Error, return code 20003 from org.apache.hadoop.hive.ql.exec.MapRedTask. An error occurred when trying to close the Operator running your custom script.

Any suggestions on how I can adapt my script to use these files?

A: Can you please post the log dump. That would be more helpful to troubleshoot. I came across the same problem and it resulted in the transformer library i wrote was referring to non-existent classes.
I din't had enough reputation to put this in as comment.


text:
Q: OSM Map quality deteriorates when changing CRS - QGIS I have a problem with basemaps for my drawings in QGIS.
By basemaps I mean OpenStreetView, Google Maps etc. I'm aware that most of them (if not all) are natively set in EPSG:3857, and they look just fine in that CRS. However, when I'm required to use a different coordinate system in my project - for example EPSG:32630 - they understandably get a little distorted.
Are there any basemaps that would accommodate to the chosen CRS without the loss of quality?
Below I enclosed screenshots of OSM in 3857 and 32630:
3857:

32630:


text:
Q: Getting TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0] while doing multi class classification from sklearn.naive_bayes import CategoricalNB
from sklearn.datasets import make_multilabel_classification
X, y = make_multilabel_classification(sparse = True, n_labels = 15,
return_indicator = 'sparse', allow_unlabeled = False)
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=0)

I tried using X.todense() but the error is still raised.
X_train = X_train.todense()
X_test = X_test.todense()

Training on the dataset
from skmultilearn.adapt import MLkNN
from sklearn.metrics import accuracy_score
classifier = MLkNN(k=20)
classifier.fit(X_train, y_train)

predicting the output of trained dataset.
y_pred = classifier.predict(X_test)
accuracy_score(y_test,y_pred)
np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1)

A: You are trying to get the length from a matrix, which is ambigious:
len(y_pred)

Your matrix y_pred has the dimension (25,5), as seen with y_pred.shape.
So instead of len(y_pred), you could use y_pred.shape[0], which would return 25.
But then you will encounter a problem when you are using y_pred.reshape(y_pred.shape[0],1)
ValueError: cannot reshape array of size 125 into shape (25, 1)
(previously: y_pred.reshape(len(y_pred),1))
This error makes sense, because you are trying to reshape a matrix with 125 values into a matrix with only 25 values. You need to rethink your code here.


text:
Q: Drawing a scrollable tiled background I'm developing a game where the background is drawn using tiles, there are about 100 tiles in it. The background should also be scrollable. Problem is that it won't scroll smoothly, there is not enough time to update the coordinates of every tile and redraw it, so I observe some unwanted visual effects. Is there any way to solve the issue? Thanks in advance.

A: The solution looks like this:
screenL = 0;
screenR = screenWidth;
screenU = 0;
screenD = screenHeight;
curL = tileX + tileWidth;
curR = tileX;
curU = tileY;
curD = tileY + tileHeight;

if (screenL < curR & screenR > curL) {
            if (screenU < curD & screenD > curU) {
        tile.draw(canvas);
            }
        }

If you dont know how to get the width and height of the mobile phone screen, let me know. You could also write your tile map engine script.


text:
Q: Database error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified I am running SMS Enabler software in a Windows 7 environment. When a message received, the database is not updating and gives the error.

Database error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I also added the required field in Control Panel\All Control Panel Items\Administrative Tools > Data Sources (ODBC) > User DSN
I am using MySQL.

A: OK.... If test connection succeeds and your app fails then it is probably one of those awkward environment issues..
Things to check -

*

*Have you creates a System DSN or User DSN?
If your application is running as a System Service then it will only able to read System DSNs (not User DSNs)

*Was the Driver installed for all users or just the installation user?
I have seen instances where this has affected some drivers...

*Use Process Monitor (an excellent tool for tracking down issues like this)
If you haven't used Process Monitor - think of it as a sniffer for; file accesses, registry accesses and network access...
That is - you will be able to determine whether there are any files or registry accesses that are failing or being blocked.

A: To use SMS Enabler with MySQL you should install MySQL Connector/ODBC 5.1 32-bit. You should install 32-bit version of this connector even if you are on 64 bit Windows. This is because SMS Enabler is a 32-bit software.

A: Wondering again whether this is a 32/64bit issue?
There are two ODBC administrators on 64bit machines...
c:\Windows\system32\odbcad32.exe === 64bit === Also through Control Panel
c:\Windows\SysWOW64\odbcad32.exe === 32bit
If your application is 32bit then you need a 32bit ODBC Driver and have to create a 32bit ODBC data source.
If your application is 64bit then, similarly, you need a 64bit ODBC Driver and have to create a 64bit ODBC data source.
I am wondering whether your application is 32bit and hence cannot find the 64bit ODBC data source you have created...
(NOTE: all of this is only applicable on 64bit Windows OSs...)


text:
Q: Sum the values that have the same key in a dictionary I have this list of dictionaries:
[{'Total Incidents': '1', 'CrimeTime': '19'},
 {'Total Incidents': '1', 'CrimeTime': '19'},
 {'Total Incidents': '1', 'CrimeTime': '19'},
 {'Total Incidents': '1', 'CrimeTime': '20'},
 {'Total Incidents': '1', 'CrimeTime': '20'},
 {'Total Incidents': '1', 'CrimeTime': '21'},
 {'Total Incidents': '1', 'CrimeTime': '21'}]

I need to convert the value of 'Total Incidents' to int, and sum them up, for each incident that occured in the same hour (the minutes and seconds are irrelevant). The output should be something like this:
[{'Total Incidents': 3, 'CrimeTime': '19'},
 {'Total Incidents': 2, 'CrimeTime': '20'},
 {'Total Incidents': 2, 'CrimeTime': '21'}]

I have used this method:
 [{ 'CrimeTime':       g[0],
    'Total Incidents': sum(map(lambda x: int(x['Total Incidents']), g[1])) }
  for g in itertools.groupby(mydata, lambda x: x['CrimeTime']) ]

But unfortunately, sometimes it repeats 'CrimeTime' so I get two dictionaries with the same 'CrimeTime', instead of only one with the summed incidents. The original list is a lot bigger, I just used a short version to explain myself better.
Feel free to ask if you don't understand my question so that I can explain myself a bit better.

A: In most contexts (as in yours), itertools.groupby works best if the data is sorted by the grouping key because it only groups adjacent elements:
key = lambda x: x['CrimeTime']
[
    {'CrimeTime': k, 'Total Incidents': sum(int(x['Total Incidents']) for x in g)}
    for k, g in itertools.groupby(sorted(mydata, key=key), key=key)
]

Using the generator expression instead of the map-lambda is mostly a matter of taste, but, at least in Python 2, saves you some resources by not building an intermediate list.

A: This should work : (too late ;) )
 [
   {'CrimeTime': g[0], 'Total Incidents': sum(map(lambda x: int(x['Total Incidents']), g[1]))}
      for g in
        itertools.groupby(
          sorted(data,key=lambda x:x.values()[0]), lambda x: x['CrimeTime'])
]


text:
Q: PHP to return 1x1 transparent GIF, how is this data encoded? I have seen this web beacon image here
The code looks like this:
header( 'Content-type: image/gif' );
# The transparent, beacon image
echo chr(71).chr(73).chr(70).chr(56).chr(57).chr(97).
     chr(1).chr(0).chr(1).chr(0).chr(128).chr(0).
     chr(0).chr(0).chr(0).chr(0).chr(0).chr(0).chr(0).
     chr(33).chr(249).chr(4).chr(1).chr(0).chr(0).
     chr(0).chr(0).chr(44).chr(0).chr(0).chr(0).chr(0).
     chr(1).chr(0).chr(1).chr(0).chr(0).chr(2).chr(2).
     chr(68).chr(1).chr(0).chr(59);

And that made it very easy to let PHP return a transparent GIF-image. However, if I want to change the image, how can I do it? How do I transform any GIF that i create to this format?
Thanks.

A: Why don't you just have the image in a file and let PHP read and return it?
header('Content-type: image/gif');
readfile('file.gif');

If you really want to convert the image to PHP code, read it one byte at a time and create the PHP code like this:
<?php
$fh = fopen('file.gif', 'r');
$i = 0;
echo 'echo ';
while(!feof($fh)) {
  $byte = fread($fh, 1);
  $num = ord($byte);
  echo 'chr(', $num, ')';
  if(!feof($fh)) {
    echo '.'; //there's more bytes, echo dot
    if(++$i % 6 == 0) {
      echo "\n     "; //do not be too wide
    }
  }
}
echo ";\n";
fclose($fh);
?>

A: better than doing that, after you set a cookie or add a log entry, you can just redirect the call to an actual image (be it gif/jpeg/etc) and let the webserver worry about sending the content etc:
header("Location: http://webserver.com/images/beacon.gif");


text:
Q: Update files on FTP server folder hierarchy with local files from a single folder I have a little-big problem. I need to copy/overwrite JPG files from my local FOLDER to server FOLDERS.
Is there a way to search and match JPG files on SERVER with my files on LOCAL and overwrite them in server folders? I do it manually and it takes lot of time.
There are 50 000 JPGs on server and I need to overwrite 20 000 of them in short time.
Many thanks for answers!!

A: There's no magic way to do your very specific task. You have to script it.
If you are on Windows, it's rather trivial to write a PowerShell script for this, using WinSCP .NET assembly and its Session.EnumerateRemoteFiles method:
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = "ftp.example.com"
    UserName = "username"
    Password = "password"
}

$remotePath = "/remote/path";
$localPath = "C:\local\Path";

# Connect
Write-Host "Connecting..."
$session = New-Object WinSCP.Session
$session.SessionLogPath = "upload.log"
$session.Open($sessionOptions)

# Enumerate remote files
$fileInfos =
    $session.EnumerateRemoteFiles(
        $remotePath, "*.*", [WinSCP.EnumerationOptions]::AllDirectories)

# And look for a matching local file for each of them
foreach ($fileInfo in $fileInfos)
{
    $localFilePath = (Join-Path $localPath $fileInfo.Name)
    if (Test-Path $localFilePath)
    {
        Write-Host ("Found local file $localFilePath matching remote file " +
            "$($fileInfo.FullName), overwriting..."
        # Command-out this line with # for a dry-run
        $session.PutFiles($localFilePath, $fileInfo.FullName).Check()
    }
    else
    {
        Write-Host ("Found no local file matching remote file " +
            "$($fileInfo.FullName), skipping..."
    }
}

Write-Host "Done"

Save the script to a file (SortOutFiles.ps1), extract a contents of WinSCP .NET assembly package along with the script, and run it like:
C:\myscript>powershell -ExecutionPolicy Bypass -File SortOutFiles.ps1
Connecting...
Found local file C:\local\path\aaa.txt matching remote file /remote/path/1/aaa.txt, overwritting...
Found local file C:\local\path\bbb.txt matching remote file /remote/path/2/bbb.txt, overwritting...
Found local file C:\local\path\ccc.txt matching remote file /remote/path/ccc.txt, overwritting...
Done

You can first dry-run the script by commenting out the line with $session.PutFiles call.
(I'm the author of WinSCP)

A: download "Filezilla"... Upload your local files (all 50000 images).. If a image is already there in server,, it will ask you options.. select 'overwrite' and use 'apply for all'...


text:
Q: Javascript ES6: setting  with local storage and form submission I am trying to set the element #welcome_banner by using a function in javascript that takes a form submission and sets it to localStorage and then pulls that info and sets it onto an
 tag.  Apparently it works but only changes the tag for a millisecond and then it disappears!  I have tried doing the .innerHTML setting in various places inside and outside of the function clickHandler() and in the main body of the script.  I am certain this is something superbasic I am missing.
<!DOCTYPE html>

<title>Project 2</title>

    <form id="display_name">
        <input id="dn" autocomplete="off" autofocus placeholder="" type="text">
        <button>set display name</button>

A: The steps to do this are as follows:

*

*Store the typed text in localStorage, you're doing this in the event handler for the form submission: localStorage.setItem('dn', dn);

*When you submit the form, the page is going to refresh from the server. This is why you're only seeing the text briefly, then the page reloads from the server with no knowledge of what was there before.

*Look for information about page events and write a handler for the DOMContentLoaded event like you did for your submit event handler.  DOMContentLoaded is well supported these days. Something like: document.addEventListener("DOMContentLoaded", function(event) {
// code to check local storage goes here...
});

*In that handler you want to check localStorage like you're doing here: var dn = localStorage.getItem('dn').value; and if there is a value there, set the innerHtml of the
 to that value, like you're doing here: welcomBanner.innerHTML = 'Hello ${dn}';
I think you might have had a stray # character in your localStorage.getItem call that I removed in the steps above. You might also want to have default text you post if there's nothing found in localStorage when you check.

A: Here's a simplified example:
If you are calling a function to get the value from Local Storage, be sure you have a return

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <input type="text" id="something">
    <button type="button" id="click">CLICK ME</button>


text:
Q: Download DT::datatable as pdf in shiny app Is it possible to download a DT::datatable as pdf through a shiny app ?
#app.r
library(shiny)
library(ggplot2)
library(magrittr)
library(DT)
ui <- shinyUI(
  fluidPage(
    column(3,

      downloadButton(
        outputId = "downloader",
        label = "Download PDF"
      )
    ),
    column(
      width = 3,
      dataTableOutput("table")
    )

  )
)

server <- shinyServer(function(input, output, session){

  #****************************************
  #* Reactive Values

  table <- reactive({
    mtcars
  })

  #****************************************
  #* Output Components

  output$table <-
    renderDataTable({
      table()
    })

  #****************************************
  #* Download Handlers

  output$downloader <-
    downloadHandler(
      "results_from_shiny.pdf",
      content =
        function(file)
        {
          rmarkdown::render(
            input = "report_file.Rmd",
            output_file = "built_report.pdf",
            params = list(table = table()
                          )
          )
          readBin(con = "built_report.pdf",
                  what = "raw",
                  n = file.info("built_report.pdf")[, "size"]) %>%
            writeBin(con = file)
        }
    )
})

shinyApp(ui, server)

and
#report_file.rmd
---
title: "Parameterized Report for Shiny"
output: pdf_document
params:
  table: 'NULL'
---

```{r}
params[["table"]]
```

A: You can try the pdf button of the Buttons datatables extension. In this way you don't need a downloadHandler. Otherwise, below is a solution using the good old xtable package. For more sophisticated tables, use kableExtra.
library(shiny)
library(DT)
library(xtable)
library(withr)
library(shinybusy)

ui <- fluidPage(
  add_busy_spinner(spin = "cube-grid", onstart = FALSE),
  column(
    width = 3,
    downloadButton(
      outputId = "downloader",
      label = "Download PDF"
    )
  ),
  column(
    width = 3,
    DTOutput("table")
  )

)

server <- function(input, output, session){

  table <- reactive({
    mtcars
  })

  #****************************************
  #* Output Components

  output[["table"]] <- renderDT({
    datatable(table())
  })

  #****************************************
  #* Download Handlers

  output[["downloader"]] <- downloadHandler(
    filename = "results_from_shiny.pdf",
    content = function(file){
      texfile <- paste0(tools::file_path_sans_ext(file), ".tex")
      latex <- print.xtable(
        xtable(table()), print.results = FALSE,
        floating = FALSE, scalebox = "0.7"
      )
      writeLines(
        c(
          "\\documentclass[12pt]{standalone}",
          "\\usepackage{graphics}",
          "\\usepackage{caption}",
          "\\begin{document}",
          "\\minipage{\\textwidth}",
          latex,
          "\\captionof{table}{My caption}",
          "\\endminipage",
          "\\end{document}"
        ),
        texfile
      )
      with_dir(
        dirname(texfile),
        tools::texi2pdf(texfile, clean = TRUE)
      )
    }
  )
}

shinyApp(ui, server)


text:
Q: Using ASP.NET 5 with Visual Studio 2013 Community Edition I am interested in evaluating ASP.NET 5. I have installed Visual Studio 2013 - Community Edition. I am now trying to following the example provided here.That example uses Visual Studio 2015 Preview. Is there a Visual Studio Template for ASP.NET 5 for Visual Studio 2013 - Community Edition?
I cannot find one.
Thank you for your help!

A: ASP.NET 5 (vNext) isn't supported in Visual Studio 2013. If you want to test ASP.NET 5, you should install Visual Studio 2015.
Another option is to test ASP.NET 5 on a Mac or Linux machine. I was able to get it working on a Mac without too much hassle, and having Intellisense in Sublime Text was really cool.
Or, as Victor Hurdugaci points out, you don't need Visual Studio on Windows at all to run ASP.NET 5. The OmniSharp project has alternatives to Visual Studio listed, along with directions for setting them up.

A: You may develop Asp.net 5/Asp.net core with the help of Visual Studio Code Without Installing VS2015


text:
Q: gvisMotionChart returns blank plot in R slidify I'm trying to produce a google motion chart in R slidify. I looked up a lot of examples online and it seems some people have successfully embedded google motion chart in an R slidify slide. Then when I tried my own using similar code, it gives me blank result. I also use the same method to produce a google pie chart and it works well (a pie chart shows in the plotting area)
Here is my simplified code below (Here I am using the Fruits dataset just like all other demo) :
---
title: "Title"
author: "Me"
date: '`r format(Sys.time(), "%d %B, %Y")`'
output:
  ioslides_presentation:
    incremental: yes
    transition: default
    widescreen: yes
  slidy_presentation:
    incremental: yes
job: Job Title
license: by-nc-sa
mode: selfcontained
hitheme: tomorrow
highlighter : highlight.js
subtitle: Subtitle
framework: io2012
widgets: []

---

## GoogleVis Motion chart example

```{r motionchartcode1, results='asis', warning=FALSE, comment=NA}
library(googleVis)
options(gvis.plot.tag='chart')
M <- gvisMotionChart(Fruits, 'Fruit', 'Year',
         options=list(width=400, height=350))
#plot(M)
print(M, tag = 'chart')
```

---

## GoogleVis Pie chart example

```{r motionchartcode, results='asis'}
library(googleVis)
options(gvis.plot.tag='chart')
Pie <- gvisPieChart(CityPopularity,
                    options=list(width=400, height=200))
print(Pie, tag = 'chart')

```

Then I used slidify("demo.Rmd") to compile it to a html file.  The first slide gives no plots but a blank plotting area.
I'm not sure which part is effecting this outcome: the setup in --- part, the options in r markdown chunk or my browser environment?
Hope someone can give me ideas.

A: The plot command in R uses the internal R http help server to overcome this limitation.
Here's how I overcame it:
Go to

 http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html

Click on the dropbox which says 'Edit location' and choose 'add location'

Click 'browse for folder or browse for file'

Choose the folder (or file) in which was your saved html output

Click OK

Also you can modify your codes, for example I did:
suppressPackageStartupMessages(library(googleVis))

options(gvis.plot.tag='chart')

M1 <- gvisMotionChart(Fruits, idvar="Fruit", timevar="Year")

plot(M1)

print(M1, file="myGoogleVisChart.html")

Now open your googleVis html file and it should display successfully.
In fact, any googleVis file you open from within the folder you selected will also display as you would expect.
Please note that I am using MS Internet Explorer and it asked me to activate ActiveX before I was able to view the output from above, and it was working for me.
Still, if you can not see then also please check for :
https://cran.r-project.org/web/packages/googleVis/vignettes/googleVis.pdf