text:
Q: How to reduce an if statement and pass multiple values to Contains? Lets say I want to loop trough all the files in a directory and if the file has an extension of an image format such as jpeg, bmp, or png, I want to copy the file to another directory.  Is there a way I can check for all image extensions without chaining || together?  Here is an example:
Instead of:
if(file.Extension == ".jpg" ||
     file.Extension == ".jpeg" ||
     file.Extension == ".bmp" ||
     file.Extension == ".png")
            //Copy To Image directory

Can I do something like:
if (file.Extension.Contains(...)).
I know Contains exists, but it does not take an array of values (extensions in this case)

A: List<string>validExtensions = new List<string>(){".jpg", ".jpeg" /* rest go here */ };
if(validExtensions.Contains(myFilenameExension))
{...}

If you have a LOT of extensions I'd switch it from a List to a HashSet, but for a small number of values (i.e. 4) a List will be either the same or quicker.

A: Make a collection class, like this:
List<string> validExtensions = new List<string>()
{
     ".jpg",
     ".jpeg",
     ".bmp",
     ".png"
};

then do:
if (validExtensions.Any(ext=>file.Extension.Contains(ext)))
{
     //Do code.
}

A: List<string> extensions=new List<string>()
extensions.Add("jpg");
extensions.Add("png");
extensions.Add("mbp");

if(extensions.Contains(file.Extension)
{
 //do what you want
}

A:
if (file.Extension.Contains(...))

You want the opposite:
if(new [] {".jpg", /* etc */ ".png"}.Contains(file.Extension, StringComparer.InvariantCultureIgnoreCase))
{

}

This is a LINQ method, so make sure you have a using System.Linq somewhere. Also, I pass a comparer so that the case is ignored. It seems like for what you are doing, case sensitivity is not something you want.


text:
Q: Inform7: Working with properties of rooms I'm very, very new to this language, and wrapping my head around "how to do things with stuff" is proving to be a very frustrating endeavor.
My goal here is to create a mechanic where certain rooms are dangerous, and become more dangerous the longer the player stays in them. If the player stays in a dangerous room for too long, a death scene is triggered.
I've got code that looks like this:
[The "danger rule"]
A room has a number called danger level. The danger level of a room is usually 0.

Definition: A room is dangerous if its danger level is 1 or more.
Definition: A room is deadly if its danger level is 9 or more.

Every turn (this is the increasing danger rule):
    If the player is in a dangerous room:
        Increase danger level by 1.

Every turn (this is the death by danger rule):
    If the room is deadly:
        do nothing.[Later...]

Every turn (this is the danger explanation rule):
    say danger level.

[further down]

The Feeding Chamber is south of the dungeon."You enter a large, dimly lit room with straw on the floor, surrounded by various cages embedded in the wall.[line break]Blood spatters are all over the floor, and it looks as if there's been a fight recently". After going to the feeding chamber for the first time:
    try looking;
    say "It smells like grues around here. I would be careful if I were you..";

The Feeding Chamber has danger level 5.

I can't seem to figure out how to properly work with the "danger level of a room". The explanation rule I defined causes a runtime error when entering a dangerous room:
`*** Run-time problem P31: Attempt to use a property of the 'nothing' non-object: property danger level`

..And attempts to re-word the rule to something like the danger level of the room or the danger level of this room lead to perplexing compilation messages such as:
`In the sentence 'say the danger level of the room'  , it looks as if you intend 'danger level of the room' to be a property, but 'a room' is not specific enough about who or what the owner is.`

What is the "right" way to reference properties of objects in this way?

A: The magic words here were "of the location". If we pretend that that this was another programming language for a moment, the way I was writing this was as if I was referring to a class "the room" rather than an instance of the class currently being referenced "the location".
The working rule is as follows:
Every turn while the player is in a dangerous room:
        Increase danger level of the location by 1.

The trick is to give Inform enough information to know which particular thing you're referring to. The problematic sentence in the original question is perfectly valid english that a human could parse, but the computer needs a bit more help in determining what room we mean when we say "the room".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implement Different Login Page for each role in asp.net-core 2 I want to implement different login page for each user based in its role in asp net core . I can set login path but its static for any roles.
   services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = "Account/Login/";
            options.AccessDeniedPath = "Account/Forbidden/";
        });

so when i call action that authorize(role="Admin") redirect to admin login page. and when call action that authorize(role="User") redirect to User login page

A: I add two different Authentication scheme in start up ConfigureServices like this
services.AddAuthentication(options =>
            {
                options.DefaultScheme = "UserAuth";
            })
            .AddCookie("UserAuth", options =>
      {
          options.LoginPath = "/Account/Login/";
          options.AccessDeniedPath = "/Account/AccessDenied/";

      })
       .AddCookie("AdminAuth", options =>
       {
           options.LoginPath = "/Admin/Account/Login/";
           options.AccessDeniedPath = "/Admin/Account/AccessDenied/";

       });

When authorize with admin role controller i choose admin scheme
[Authorize(Roles = "Administrator", AuthenticationSchemes = "AdminAuth")]

When authorize with user role controller i choose user scheme
 [Authorize(Roles = "User", AuthenticationSchemes = "UserAuth")]

You can review this link  How do I setup multiple Authentication schemes in ASP.NET Core 2.0?

A: Sorry, not possible. The role of a user is not known until the user has authenticated. So you can't tell which login page to serve until they have already logged in, and they can't log in until you have served a login page, so the idea simply doesn't work.
The best you can do is offer a single login page that allows the user to select their role before signing on (e.g. with radio buttons, a dropdown list, or links that take the user to separate login pages). If you like, you can set a cookie to persist the user's selection so that they will only see the appropriate role-specific page the next time they sign on.
If you wish to redirect to a different login page based on some piece of data other than user context (e.g. if you want to redirect to different login pages depending on what URL the user was originally requesting) you can always write a custom authorize attribute and override the HandleUnauthorizedRequest method. Then you can redirect anywhere you want.


text:
Q: Specify a Cross-Origin Resource Policy to prevent a resource from being blocked I am getting this error while using js.stripe.com. How do I fix it ?
This is my browser console where I am getting this error
List of resources that are being blocked
I have already added these headers in my app.js


text:
Q: is this a valid way to define an explicit function inside addEventListener? Just wondering, is this a valid way to define an explicit function inside JavaScript's addEventListener function so that it could be removed at any time using removeEventListener?
var somefunction;
window.addEventListener('load', somefunction = function(){
    //do something
}, false);

window.removeEventListener('load', somefunction, false);

In other words, is it ok to define a variable somefunction and then assign an anonymous function to it inside addEventListener, instead of defining somefunction outright from the get go? It seems to work in FF and Chrome, but just wanna make sure this is officially valid JavaScript syntax.

A: Yes, it will work. An assignment is an expression -- it assigns to the variable and also returns the value that it assigned.
Personally I think this is a confusing way to write it. If you're refer to the function by name, put the definition where you define the name, not where you use it. In particular, if you try to do this twice, you'll have a problem because each event listener will have a different function, but it has the same name.
window.addEventListener('event1', somefunction = function() {
    //do something
});
window.addEventListener('event2', somefunction = function() {
    //do something
});

Now you can only remove event2, because somefunction no longer refers to the function that was added to event1.

A:
Calling removeEventListener() with arguments that do not identify any
  currently registered EventListener on the EventTarget has no effect.

So as long as removeEventListener has say a 'click' event as an argument, any one eventListener registered to the 'click' event will be removed. This is evident in OP's case, therefore it is feasible according to the criteria previously mentioned.
The following Snippet demonstrates a registered eventListener added to #target1 to listen for the 'click' event. It will be functional until removeEventListener() is called to remove the eventListener within 4 seconds. Notice that this particular removeEventListener's arguments are:

*

*the event object............: click

*a named function..........: eventLog()

*and it's capture boolean: false
The identifying argument is 'click' and the target.event is #target that allows removeEventListener() to identify it's target.
SNIPPET

var eventLog;
var tgt1 = document.getElementById('target1');
var term = document.getElementById('btn');

tgt1.addEventListener('click', eventLog = function(e) {
  console.log('target1 has been clicked');
}, false);

setTimeout(function() {
  tgt1.removeEventListener('click', eventLog, false);
  eventLog('Target1 eventListener is removed');
}, 4000);

function eventLog(str) {
  console.log(str);
}
#target1 {
  border: 2px solid red;
}

Start clicking TARGET1 several times and you'll notice that each `click` event is firing as displayed in the console. Within 4 seconds, TARGET1's eventListener should be removed.

TARGET1


text:
Q: How to export a function from single-spa util module and import the same function in single-spa micro front end? I have the following 3 repositories.
root-config -> https://github.com/sravan464/web-root-spa
react mfe -> https://github.com/sravan464/mfe-react-1
vanilla utility module -> https://github.com/sravan464/single-spa-util-module-vanilla
I am trying to understand how to export a function from single-spa vanilla utility module and how can I import that function in my react-mfe
do we need to add a vanilla utility module in import maps of root-config ??

A: You may need to update your root-config's index.ejs, seems the path towards the vanilla utility module is wrong:
Current in your root-config repository index.ejs:

"@sravan-org/single-spa-util-module-vanilla":"//http://localhost:8081/sravan-org-single-spa-util-module-vanilla.js"

Correct one:

"@sravan-org/single-spa-util-module-vanilla":"//localhost:8081/sravan-org-single-spa-util-module-vanilla.js"

You don't need to add "http://".


text:
Q: IE8 addEventListener - Object doesn't support property or method 'addEventListener' i am debugging a WPTheme for IE8.  It has a feature that loads a post inside a lightbox window, only the parent page scroll Y coordinates get reset to the top of the page. -- so when you close the lightbox the you are at top of the page... so you lose the place where you were just browsing.
here is the code that fires right before the scroll bar shoots to the top of the page. right before the lightbox pops up.
document.addEventListener("touchmove",function(t){var n=t.targetTouches?t.targetTouches[0]:t;e.x=n.pageX,e.y=n.pageY}):document.addEventListener("mousemove",function(t){e.x=t.pageX,e.y=t.pageY}),e}()

how can i rewrite this to be compatible with IE8?

A: In IE 8 doesnt exist addEventListener. For that you must use attachEvent. You can use something like this for check what to use.
if (el.addEventListener) {
  el.addEventListener('click', modifyText, false);
} else if (el.attachEvent)  {
  el.attachEvent('onclick', modifyText);
}


text:
Q: How to Reorganize Query Results in SQL using Pivot I have a query that returns data that looks like this:
Project Name   Analyte   Result

A                 BOD       4mg/l

A              COD       10mg/l

B              BOD       4mg/l

B              COD       10mg/l

But I need it to look like this:
Project Name   Analyte   Result   Analyte  Result

A              BOD       4mg/l        COD      10mg/l

B              BOD       4mg/l        COD      10mg/l

I can't figure out how to do this with sql. Will the pivot function do this? How?

A: Assuming you are always going to have one BOD and one COD:
SELECT
  [a].[Project Name],
  [a].[Analyte] AS [Analyte1],
  [a].[Result] AS [Result1],
  [b].[Analyte] AS [Analyte2],
  [b].[Result] AS [Result2]
FROM
  [Results] [a]
  JOIN [Results] [b]
    ON [a].[Project Name] = [b].[Project Name]
WHERE
  [a].[Analyte] = 'BOD'
  AND [b].[Analyte] = 'COD';

SqlFiddle.

A: You didn't specify what RDBMS you are using but you can easily use an aggregate function with a CASE expression to get the result:
select
  projectName,
  max(case when Analyte = 'BOD' then Analyte end) Analyte_BOD,
  max(case when Analyte = 'BOD' then Result end) Result_BOD,
  max(case when Analyte = 'COD' then Analyte end) Analyte_COD,
  max(case when Analyte = 'COD' then Result end) Result_COD
from yourtable
group by projectname;

See SQL Fiddle with Demo


text:
Q: Display arabic characters with weka I've a CSV file with statuses written in Arabic, but they appear in form of question marks, I want to convert this file to arff. I'm wondering if in the arff file these characters will be displayed correctly or not. How can I do the classification in this situation ?

A: I had some issues with UTF-8 characters in WEKA when using ARFF format.
I switched to the XRFF format instead which allows for explicit encoding decleration instead and this solved my problems.

A: You have to make sure that the CSV file is saved with UTF-8 encoding before loading it to Weka or converting it to arff. You might try an text editor like Notepad++


text:
Q: How to check if all of given values exists in table? I have a list like '2,3,7,8,9,10,12,13,14,16,18,22,28,30'.
I have a table with columns gridConfigId and ownerId.
I need to find all gridConfigId which list of ownerId does not have at least one of the given set.
I try the query:
SELECT
   gridConfigId, GROUP_CONCAT(ownerId separator ',') as userList
from
   gridconfig_favourites gf
where
   exists (select 1 from gridconfigs g where g.id=gf.gridConfigId and type='asset' and name='Photo Attributes')
GROUP BY gridConfigId
HAVING
   userList != '2,3,7,8,9,10,12,13,14,16,18,22,28,30';

But this variant does not work because ordering of ownerId can be different.
I was trying to add ORDER BY gridConfigId, ownerId but query does not work that way.

A: I found the solution. I've just add ORDER BY ownerId inside the GROUP_CONCAT.
GROUP_CONCAT(ownerId ORDER BY ownerId separator ',')

The result is the string with ordered ids inside. And i can compare ids list just like strings.
It is described in the docs.


text:
Q: Using node-passport with subdomains I have a node.js app using express connect-redis to store sessions. I'm also using vhost for a password protected user app:
app.use(express.vhost('users.mydomain.com', require('./users/app')));
This works fine but I want to see if a user is logged in when they are in www.mydomain.com. I tried adding this to session():
cookie: { domain:'.yourdomain.com'}
When I do this it just destroys the session when I go between users and www, but doesn't share the session. I'm lost as to where the problem would be.
edit: I've found that session survive between vhosts unless I'm using passport on that vhost.

A: It sounds like you have two apps which have their own domains. One possible solution would be to ensure that both apps share the same session_save_path and ensure that you pass the session when moving from one app to the other.
Hope that helps


text:
Q: A question about ordinal definable real numbers If ZFC (Zermelo-Fraenkel set theory with the Axiom of Choice) is consistent, does it remain consistent
when the following statement is added to it as a new axiom?
"There exists a denumerably infinite and ordinal definable set of real numbers, not all of whose elements
are ordinal definable"
If the answer to the above question is negative, then it must be provable in ZFC that every denumerably
infinite and ordinal definable set of real numbers is hereditarily ordinal definable. This is because
every real number can be regarded as a set of finite ordinal numbers and every finite ordinal number is
ordinal definable.
                                                                        Garabed Gulbenkian

A: The original problem solves in the positive: there is a model of ZFC in which there exists a countable OD (well, even lightface $\Pi^1_2$, which is the best possible) set of reals $X$ containing no OD elements. The model (by the way, as conjectured by Ali Enayat at http://cs.nyu.edu/pipermail/fom/2010-July/014944.html) is a $\mathbf P^{<\omega}$-generic extension of $L$, where $\mathbf P$ is Jensen's minimal $\Pi^1_2$ real singleton forcing and $\mathbf P^{<\omega}$ is the finite-support product of $\omega$ copies of $\mathbf P$.
A few details. Jensen's forcing is defined in $L$ so that $\mathbf P =\bigcup_{\xi<\omega_1} \mathbf P_\xi$, where each $\mathbf P_\xi$ is a ctble set of perfect trees in $2^{<\omega}$, generic over the outcome $\mathbf P_{<\xi}=\bigcup_{\eta<\xi}\mathbf P_\eta$ of all earlier steps in such a way that any $\mathbf P_{<\xi}$-name $c$ for a real ($c$ belongs to a minimal countable transitive model of a fragment of ZFC, containing $\mathbf P_{<\xi}$), which $\mathbf P_{<\xi}$ forces to be different from the generic real itself, is pushed by $\mathbf P_{\xi}$ (the next layer) not to belong to any $[T]$ where $T$ is a tree in $\mathbf P_{\xi}$. The effect is that the generic real itself is the only $\mathbf P$-generic real in the extension, while examination of the complexity shows that it is a $\Pi^1_2$ singleton.
Now let $\mathbf P^{<\omega}$ be the finite-support product of $\omega$ copies of $\mathbf P$. It adds a ctble sequence of $\mathbf P$-generic reals $x_n$. A version of the argument above shows that still the reals $x_n$ are the only $\mathbf P$-generic reals in the extension and the set $\{x_n:n<\omega\}$ is $\Pi^1_2$. Finally the routine technique of finite-support-product extensions ensures that $x_n$ are not OD in the extension.
Addendum. For detailed proofs of the above claims, see this manuscript.
Jindra Zapletal informed me that he got a model where a $\mathsf E_0$-equivalence class $X=[x]_{E_0}$ of a certain Silver generic real is OD and contains no OD elements, but in that model $X$ does not seem to be analytically definable, let alone $\Pi^1_2$. The model involves a combination of several forcing notions and some modern ideas in descriptive set theory recently presented in Canonical Ramsey Theory on Polish Spaces. Thus whether a $\mathsf E_0$-class of a non-OD real can be $\Pi^1_2$ is probably still open.
Further Kanovei's addendum of Aug 23.
It looks like a clone of Jensen's forcing on the base of Silver's (or $\mathsf E_0$-large Sacks) forcing instead of the simple Sacks one leads to a lightface $\Pi^1_2$ generic $\mathsf E_0$-class with no OD elements. The advantage of Silver's forcing here is that it seems to produce a Jensen-type forcing closed under the 0-1 flip at any digit, so that the corresponding extension contains a $\mathsf E_0$-class of generic reals instead of a generic singleton. I am working on details, hopefully it pans out.
Further Kanovei's addendum of Aug 25.
Yes it works, so there is a generic extension $L[x]$ of $L$ by a real in which the
$\mathsf E_0$-class $[x]_{\mathsf E_0}$ is a lightface $\Pi^1_2$ (countable) set with no OD elements. I'll send it to Axriv in a few days.
Further Kanovei's addendum of Aug 29.   arXiv:1408.6642

A: (I am replacing prior nonsense with a completely different suggestion. I am also turning this into CW so details can be added by somebody with time (which, sadly, most likely won't be me). Comments prior to Feb. 9, 2011, refer to said prior nonsense.)

Start with $V=L$ and force to add a Mathias real $s$. Let $W$ be the resulting extension. Let $A$ be the set of reals $r$ that are Mathias generic over $L$ and such that $L[r]=W$. I strongly suspect that a real $r$ is in $A$ iff it differs from $s$ finitely often, and so $A$ is countable, ordinal definable, and lacks any ordinal definable members.
(I have briefly discussed this idea with other set theorists, but we did not elaborate any details.)

From Andreas Blass: The following began as a comment, but Andres suggested adding it to his answer, for improved visibility.  As it stands, with ordinary Mathias forcing, this won't work, because if $r\subset\omega$ is a Mathias real then so is the result of shifting it to the right (or left) by 1, and it still generates the same model.  Instead of a simple shift, you could apply any strictly monotone function from $L$.  But suppose you did Mathias forcing with respect to the constructibly-first non-principal ultrafilter on $\omega$ in $L$.  That would avoid this problem.  (Note that Joel David Hamkins's comment also depends on the fact that Prikry forcing is with respect to an ultrafilter in the ground model.)


text:
Q: Reduction of Order for two 2nd Order ODEs to a system of four 1st order ODE with Initial Conditions and sine functions I am trying to determine how to turn these two 2nd order ODEs into a system of four 1st order ODEs with initial conditions. Afterwards, I am to turn it into a matrix.
eqn 1:
$$3.2\theta''_1 + 1.44[\cos(\theta_2-\theta_1)]\theta''_2 - 1.44[\sin(\theta_2-\theta_1)]\theta'^2_2+62.784\sin(\theta_1)=0$$
eqn 2:
$$1.08\theta''_2+1.44[\cos(\theta_2-\theta_1)]\theta''_1+1.44[\sin(\theta_2-\theta_1)\theta'^2_1+17.658\sin(\theta_2)=0$$
Initial Conditions:
$$\theta_1(0)=0.2 rad$$ $$\theta'_1(0)=0.4 rad/s$$
$$\theta_2(0)=0.3 rad$$ $$\theta'_2(0)=0.5 rad/s$$
I have tried doing some variable substitution, but it has not gotten me anywhere. What stumps me the most is the variables being embedded within a sine function $\sin(\theta)$ and the $\theta'^2$ as I have never come across it before in my diff eq classes. Does this also require some sort of Laplace Transform?

A: You can write your ODE in the following form:
$$
  \begin{pmatrix}
    3.2 & 1.44[\cos(\theta_2-\theta_1)] \\
    1.44[\cos(\theta_2-\theta_1)] & 1.08
  \end{pmatrix}
  \vec \theta''
  = \vec f(\vec\theta,\vec\theta'),
$$
where $f(\ldots)$ encompasses all of the other terms you show.
If you denote the matrix by $A(\vec\theta)$, then you can multiply through with $A^{-1}$ to obtain
$$
  \vec \theta''
  = A(\vec\theta)^{-1} \vec f(\vec\theta,\vec\theta'),
$$
and now you can probably see where this is going: If you introduce $\vec\psi=\vec\theta'$, you can rewrite the differential equation in first order form as
$$
  \vec\theta' = \vec\psi
\\
  \vec \psi'
  = A(\vec\theta)^{-1} \vec f(\vec\theta,\vec\psi).
$$
This is the desired first order form.


text:
Q: Enabling specific access with iptables on Debian Iam running a Debian server that hosts several docker containers but also works as my router and internet gateway.
Iam having trouble getting ssh access from outside (specific ipaddresses) working on the host (not in the docker containers. All access to docker containers works just fine.
I can see with a nmap from the inside of my network to the local IP and my external IP that the port is open although it seems to be open just by enabling ssh on that port. So if I set the ssh port in the sshd_config to be 5501 and restarts the ssh daemon, an nmap to that port shows the port is open, if I change the port to 22 it shows that port is open although I haven't changed anything in my iptables script, so my worries besides not being able to reach the server from sepcific external IP's is that the script is to openly configured.
An iptables -L -a command don't list the port for SSH (5501), although it lists all other ports in the script.
Is it because I don't have a table for the rules for the host itself? Searching around stackoverflow for similar questions dosen't seems to be requiring a table?
Below is my complete IP tables script.
PATH=/usr/sbin:/sbin:/usr/bin:/bin
#!/bin/sh
##################################################################################################
# General variables for this script                                                              #
##################################################################################################
SERVER_IP="192.168.0.1"
A="xxx.xxx.xxx.xxx"
B="xxx.xxx.xxx.xxx"
C="xxx.xxx.xxx.xxx"
D="xxx.xxx.xxx.xxx"
E="xxx.xxx.xxx.xxx"
InternalNet="192.168.0.1-192.168.0.100"

##################################################################################################
# Docker stop                                                                                #
##################################################################################################
service docker stop

##################################################################################################
# Flushing all rules                                                                             #
##################################################################################################
iptables -F
iptables -X

##################################################################################################
# Setting default filter policy                                                                  #
##################################################################################################
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

##################################################################################################
# Allow unlimited traffic on loopback                                                            #
##################################################################################################
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

##################################################################################################
# Allow unlimited traffic to eth1 (homeserver internal)                                          #
##################################################################################################
iptables -A INPUT -i eth1 -j ACCEPT
iptables -A OUTPUT -o eth1 -j ACCEPT

##################################################################################################
# Allow all traffic form internal to all outbound                                                #
# And all related and established traffic from the internet                                      #
##################################################################################################
iptables -A OUTPUT -o eth0 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT

##################################################################################################
# Start Docker                                                                                #
##################################################################################################
service docker start

##################################################################################################
# Create a PRE_DOCKER table                                                                      #
##################################################################################################
iptables -N PRE_DOCKER

##################################################################################################
# Insert this as the first table on the FORWARD chain.                                           #
##################################################################################################
iptables -I FORWARD -o docker0 -j PRE_DOCKER

#################################################################################################
# Docker internal use                                                                            #
##################################################################################################
iptables -A PRE_DOCKER -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -A PRE_DOCKER -i docker0 ! -o docker0 -j ACCEPT
iptables -A PRE_DOCKER -m state --state RELATED -j ACCEPT
iptables -A PRE_DOCKER -i docker0 -o docker0 -j ACCEPT

##################################################################################################
#  Allow specific trafic from specific ips                                                       #
##################################################################################################
iptables -I PRE_DOCKER -p tcp -s $A,$B,$C,$D,$E -d $SERVER_IP --dport 19999 -m state --state NEW,ESTABLISHED -j ACCEPT #Netdata
iptables -I PRE_DOCKER -p tcp -s $SERVER_IP -d A,$B,$C,$D,$E t --sport 19999 -m state --state ESTABLISHED -j ACCEPT #Netdata

iptables -I PRE_DOCKER -p tcp -s A,$B,$C,$D,$E -d $SERVER_IP --dport 8080 -m state --state NEW,ESTABLISHED -j ACCEPT #Tomcat
iptables -I PRE_DOCKER -p tcp -s $SERVER_IP -d A,$B,$C,$D,$E --sport 8080 -m state --state ESTABLISHED -j ACCEPT #Tomcat

iptables -I PRE_DOCKER -p tcp -s A,$B,$C,$D,$E -d $SERVER_IP --dport 8081 -m state --state NEW,ESTABLISHED -j ACCEPT #Phabricator
iptables -I PRE_DOCKER -p tcp -s $SERVER_IP -d A,$B,$C,$D,$E --sport 8081 -m state --state ESTABLISHED -j ACCEPT #Phabricator
##################################################################################################
# Allow access from internet                                                                     #
##################################################################################################

#HTTPS(443) from internet to docker apache
iptables -A INPUT -p tcp -d $SERVER_IP --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s $SERVER_IP --sport 443 -m state --state ESTABLISHED -j ACCEPT

iptables -I PRE_DOCKER -p tcp -d $SERVER_IP --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT #Apache
iptables -I PRE_DOCKER -p tcp -s $SERVER_IP --sport 443 -m state --state ESTABLISHED -j ACCEPT #Apache

##################################################################################################
# Allow specific traffic from specific ips to homeserver                                         #
##################################################################################################

#SSH(on port 5501) from known IPs
iptables -A INPUT -p tcp -s A,$B,$C,$D,$E -d $SERVER_IP --dport 5501 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s $SERVER_IP -d A,$B,$C,$D,$E --sport 5501 -m state --state RELATED,ESTABLISHED -j ACCEPT

#Netdata(on port 19999) from known IPS
iptables -A INPUT -p tcp -s A,$B,$C,$D,$E -d $SERVER_IP --dport 19999 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s $SERVER_IP -d A,$B,$C,$D,$E --sport 19999 -m state --state RELATED,ESTABLISHED -j ACCEPT
#iptables -t nat -A PREROUTING -i eth1 -d $SERVER_IP -p tcp --dport 5501 -j  DNAT --to-destination 192.168.0.1:5501

A: The A in this line is missing a $ sign - iptables -A INPUT -p tcp -s $A,$B,$C,$D,$E -d $SERVER_IP --dport 5501 -m state --state NEW,ESTABLISHED -j ACCEPT
If that doesn't change a thing, replace the above with iptables -A INPUT -p tcp --dport 5501 -j ACCEPT. Does it work?
Also, these rules are effectively iptables -P OUTPUT ACCEPT:
iptables -A OUTPUT -o eth1 -j ACCEPT
iptables -A OUTPUT -o eth0 -j ACCEPT

You can use iptables -P OUTPUT ACCEPT and remove all rules in the OUTPUT chain.


text:
Q: Difference in Behavior Between Firefox and Chrome for HTML Canvas fillRect operation and fontBoundingBoxAscent I am working on a bug in a library for Leaflet and I cannot figure out how to work around a difference in how Firefox and Chrome implement HTML Canvas.  It revolves around the ctx.fillRect function -- it does not appear to be working in Firefox.  On Chrome, the application works properly and the labels are properly coloured:
Chrome

However with Firefox it appears as such:
Firefox

The code in my library which draws the labels is:
  drawLabel(labelText, textColor, backgroundColor, labelPosition) {
    const textWidth = this.ctx.measureText(labelText).width;
    const textHeight = this.ctx.measureText(labelText).fontBoundingBoxAscent;

    // Calculate label xy position
    const labelX = labelPosition.x;
    const labelY = labelPosition.y;
    this.ctx.fillStyle = backgroundColor;
    // Magic numbers will centre the rectangle over the text
    this.ctx.fillRect(labelX - textWidth / 2 - 1, labelY - textHeight + 1, textWidth + 3, textHeight + 2);
    this.ctx.fillStyle = textColor;
    this.ctx.fillText(labelText, labelX - textWidth / 2, labelY);
  }

I've tried to leverage ctx.rect and ctx.fill as a substitute but that does not work.  Logging the ctx object did show that Chrome and Firefox implement Canvas context a little differently, but the fields that I am modifying do not appear to be different.

A: The problem is that fontBoundingBoxAscent is not enabled in Firefox by default and requires the user to turn it on in about:config under dom.textMetrics.fontBoundingBox.enabled.


text:
Q: Why is the smallest normal subgroup containing part of the kernel also in the kernel? In the book "Algebra" by Serge Lang it is stated that, if $f : G \to G'$ is a group homomorphism, $H$ is a subgroup contained in the Kernel of f, and $N$ is the smallest normal subgroup containing $H$, then $N$ is in the Kernel of f.
I would like to fill in the details myself, but somehow I am stuck. How can I use the normality of $N$ to show this ? Does it have to do with the fact that any element in $N$ can be written as a product containing elements of $H$ ?
Thanks for your help!!

A: We can do this by considering the "universal" definition of $N$: $N$ has the following properties:

*

*$H\subseteq N$;

*$N\triangleleft G$; and

*If $K$ is any subgroup such that $H\subseteq K$ and $K\triangleleft G$, then $N\subseteq K$.

Since $\mathrm{ker}(f)\triangleleft G$, and we are assuming that $H\subseteq \mathrm{ker}(f)$, property 3 implies immediately that $N\subseteq \mathrm{ker}(f)$.
We can also do this by considering the top-down construction of $N$: $N$ is the intersection of all normal subgroups of $G$ that contains $H$:
$$N = \bigcap_{H\subseteq K\triangleleft G} K.$$
Then since $H\subseteq \mathrm{ker}(f)\triangleleft G$, it follows that $N\subseteq\mathrm{ker}(f)$.
Or we can do this by considering the bottom-up construction of $N$; but here you are somewhat incorrect above. You write that "every element of $N$ can be written as a product containing elements of $H$", and this is not quite good enough. The correct statement is that $N$ consists exactly of products of conjugates of elements of $H$:
$$N = \Bigl\{ (g_1h_1g_1^{-1})\cdots(g_mh_mg_m^{-1})\Bigm| g_i\in G, h_i\in H, m\in\mathbb{N}\Bigr\}.$$
Given such an element, if we apply $f$ to it we get:
$$\begin{align*}
f\Bigl((g_1h_1g_1^{-1})\cdots(g_mh_mg_m^{-1})\Bigr) &= f(g_1)f(h_1)f(g_1)^{-1}\cdots f(g_m)f(h_m)f(g_m)^{-1}\\
&= f(g_1)1f(g_1)^{-1}\cdots f(g_m)1f(g_m)^{-1} \quad\text{(since }H\subseteq \mathrm{ker}(f)\text{)}\\
&= 1,
\end{align*}$$
so for every $n\in N$ we have $f(n)=1$; hence, $N\subseteq \mathrm{ker}(f)$.


text:
Q: Laravel Object Access in Blade Template I have queried in the blade template in a foreach loop like the way
@foreach ($employees as $employee)
 {{ $employee->name }}

   @php
     $project_info = \App\Models\Project::select('title')->find($employee->id);
     echo $project_info;
   @endphp

@endforeach

Output: {"title":"Hull 21"}     // when echo $project_info;
The problem is that I can not access to the "title" so that "Hull 21" is shown.
I have tried the following ways, but no luck.
// way 1
echo $project_info->title;
// way 2
echo $project_info['title'];

Output way 1
Trying to get property 'title' of non-object (View: /home/sajib/Desktop/emp/resources/views/backend/attendee/index.blade.php)

Output way 2
Trying to access array offset on value of type null (View: /home/sajib/Desktop/emp/resources/views/backend/attendee/index.blade.php)

If I debug with dd($project_info->title) then it gives output "Hull 21";
I need to echo/print the project title "Hull 21" for each Employee.

A: There was a great Mistake I did.
I should have searched the Project by Project ID, not Employee ID. Since each employee contains the project_id which is foreign key in the Employee Table.
Database Table looks like this
Project                 Employee
=========               ==========
id                      id
title                   name
                        phone
                        designation
                        project_id

So search query should be like this,
 \App\Models\Project::select('title')->find($employee->project_id);

Instead of,
\App\Models\Project::select('title')->find($employee->id);


text:
Q: Permissions Issue with AppFusions Google Analytics plugin for Confluence I have recently installed AppFusion's Google Analytics plugin for Confluence, but when I am on a page in a space, I click the 'See who's viewed this page', to which I get a forever loading box stating it's getting information from Google Analytics.
Checking the logs, this is what I get:
2015-09-16 20:38:33,423 ERROR [http-nio-8090-exec-9] [plugins.googleanalytics.utils.DataFeedUtils] getGaData  ++ Oh heck:  GoogleJsonResponseException -- 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "User does not have sufficient permissions for this profile.",
"reason" : "insufficientPermissions"
  } ],
  "message" : "User does not have sufficient permissions for this profile."
}
 -- referer: https://confluenceURL | url: /rest/googleanalytics/1.0/content/page/47843376/pageviews/2015-08-16/2015-09-16 | userName: email@email.com

See here for information on setting up the plugin: https://www.appfusions.com/display/GANLC/Documentation

A: In this case, no website profile had been selected on Step 4: Select Website Profile in the plugin configuration screen, so the error logged is slightly misleading.
Having created a property in Google Analytics Administration and then selected a profile on the plugin configuration screen (below) everything started working again.

A: The user that you have authenticated with does not have access to the Google Analytics profile that you have set in your code.
Either give the user you are authenticating with access to read from that account. or Authenticate with an account that does have access.


text:
Q: How to prove $\ln{\frac{n+1}{n}}\le\frac{2}{n+1},\forall n\in\mathbb{N}^+$? I found an inequality: $$\ln\left(\frac{n+1}{n}\right)\le\frac{2}{n+1},\forall n\in\mathbb{N}^+.$$
I tried induction. It is obvious if $k=1$, when $n=k$, $\ln\sqrt{\left(\frac{k+1}{k}\right)^{k+1}}\le 1$, but bogged down for $n=k+1$:
$$\ln\sqrt{\left(\frac{k+2}{k+1}\right)^{k+2}}\le 1$$

A: Apply $\exp$ (which is strictly increasing) to both sides. Then your inequality is equivalent to
$$ \frac{n+1}{n}\le e^{\frac2{n+1}}$$
One of the most useful inequalities about the exponential is
$$ e^t\ge 1+t.$$
This gives us
$$ e^{\frac2{n+1}}\ge 1+\frac2{n+1}\stackrel{(*)}\ge1+\frac1n=\frac{n+1}n$$
where $(*)$ follows from $\frac2{n+1}-\frac1n=\frac{2n-(n+1)}{n(n+1)}\ge0$.

A: $$\ln((n+1)/n) = \ln(n+1)-\ln(n) = \int_n^{n+1}\frac{1}{x} dx \le \frac{1}{n} \le \frac{2}{n+1}$$

A: Take $x=\frac1n$ so you will have
$$\ln(1+x)\leq \frac{2x}{x+1}$$ now suppose $f(x)=\ln(1+x)- \frac{2x}{x+1}\\x \in [0,1]$
$$f'(x)=\frac{1}{x+1}-\frac{2}{(x+1)^2}=\frac{1+x-2}{(x+1)^2} \to x=1$$ so $f'(x) \leq 0 \text {  when x is } \in [0,1]$ so $f(x)$ is decreasing in this interval
so $$f(x)\leq f(0) \text{ when } x\in [0,1]\\ \to f(x)\leq f(0)\\f(x) \leq \ln(1+0)-0\\f(x)\leq 0\\\ln(1+x)- \frac{2x}{x+1}\leq 0\\
\ln(1+x)\leq \frac{2x}{x+1} , x \in [0,1] \\and \\\ln(1+x)\leq \frac{2x}{x+1} , x \in (0,1]$$ now put $x=\frac1n$

A: HINT
Use the fact that $(1 + \frac 1 n)^n \lt e$ See Euler's constant

A: Start from:
1) ln$ (1 +x) \le x$, for $x \ge 0$.
2) $ n +1 \le 2n$,
$\rightarrow 1/n \le 2/(n+1)$.
Combining :
ln$ (1+ 1/n) \le 1/n \le 2/(n +1)$,
where  $n$ is  a positive integer.
Proof of 1):
Series expansion for $e^x$:
$ e^x = 1+ x + x^2/2! + x^3/3! +....  $
$\rightarrow$ $(1+x) \le e^x$ for $x \ge 0$.
ln is a stricly monotonously increasing function , hence
ln $(1+ x) \le x$ for $x\ge0$.

A: Integrate $\frac{1}{x}$ between $n$ and $n+1$: $\ln \frac{n+1}{n} = \ln (n+1) - \ln (n) = \displaystyle\int_n^{n+1} \frac{1}{x} \operatorname{d}x$. As $x\to \frac{1}{x}$ is decreasing, you get $\ln \frac{n+1}{n}\leq \displaystyle\int_n^{n+1} \frac{1}{n} \operatorname{d}x = \frac{1}{n}$.
It is moreover clear that $\frac{1}{n} \leq \frac{2}{n+1}$ for $n\geq 1$, so you get $\ln \frac{n+1}{n} \leq \frac{2}{n+1}$

A: Your question is equivalent to prove the following form
$$
(2-\frac{n-1}{n})\leq 2^{(1-\frac{n-1}{n+1})} \tag{1}
$$
The relation $(1)$ is true becuse $\frac{n-1}{n} \geq \frac{n-1}{n+1}$.
Edit:
If the relation $(1)$ be true then we can conclude that:
$$
\left\{
\begin{array}{c}
(2-\frac{n-1}{n})\leq 2^{(1-\frac{n-1}{n+1})} \\
\\
2^{(1-\frac{n-1}{n+1})}  \leq e^{(1-\frac{n-1}{n+1})}
\end{array}
\right.
\Rightarrow
(2-\frac{n-1}{n})\leq e^{(1-\frac{n-1}{n+1})} \tag{2}
$$
$$
\ln (2-\frac{n-1}{n})\leq (1-\frac{n-1}{n+1})
\Rightarrow
\ln\left(\frac{n+1}{n}\right)\le\frac{2}{n+1}
$$


text:
Q: iPhone 3D compass I am trying to build an app for the iPhone 4 which enables the user to "point" at a hardcoded destination and a dot appears where the destination is located.
First, i use the compass to make a horizontal compass(this will cover the left/right rotation):
// Heading
nowHeading = heading.trueHeading;

// Shift image (horizontal compass)
float shift = bearing - nowHeading;
destinationImage.center = CGPointMake(shift+160, destinationImage.center.y);

I shift the dot 160 pixels because the screen is 320 pixels width. My question is now, how can I expand this code to handle up and down? Meaning that if i point the phone down in the table, the dot wont show.. I have to point (like taking a picture) at the destination in order for it to be drawn on the screen. I've already implemented the accelerator. But i don't know how to unite these components to solve my problem.

A: Bearing should depend on the field of vision of the camera. For iPhone 4 the horizontal angular view is 47.5 so 320 points/47.5 = xxx points per degree, use that to shift horizontally. You also have to add an adaptive filter to the accelerometers, you can get one from the AccelerometerGraph project from Apple.
You have the rotation in one axis (bearing) you should get the rotation on the other two from the accelerometers. The atan2 of two axis give you the rotation on the third. Go to UIAcceleration and imagine an axis physically piercing the device if that helps and do double xAngle = atan2(acceleration.y, acceleration.z); So once you have the rotation upside down you can repeat what you did for the horizontal with the vertical field of view, eg: 60 for the iPhone.
That is going to be one rough implementation :) but achieving smooth movement is difficult. One thing you can do is use the gyros to get a faster response and correct their signal periodically with the accelerometers. See this talk for the troubles ahead: Sensor Fusion on Android Devices. Here is a website dedicated to the Kalman Filter. If you dare with Quaternions I recommend "Visualizing Quaternions" from Andrew J. Hanson.

A: It sounds like you are trying to do a style of Augmented Reality. If that. Is the case there are several libraries and sample code suggested here:
Augmented Reality


text:
Q: Error binding IValueConverter class in C++/CX I have an exception in XAML Editor that doesn't let me correctly see my custom IValueConverter class applied to my view, but when I run it it works very well.
I have been reading many topics from similar situations, I found a post that is similar to my problem: xaml Invalid Markup but still compiles/runs. It took me a while to verify my all namespaces in my solution, to finally decide to recreate the projects and build again, it compiles very well, even I can see the formatter at runtime, but I'm still facing the same issue when I try to edit my view in XAML.
If I declare the ToBrushFormatter inside the Grid.Resources and compile, I get: The text associated with this error code could not be found. Cannot create instance of type 'Promotion.DataBinding.ToBrushFormatter'.

But If I declare it outside in Page.Resources and compile I also receive: The specified module could not be found. (Exception from HRESULT: 0x8007007E).
In addition I have registered my ToBrushFormatter.h in my pch.h, MainScenarioList.xaml.cpp and MainScenario.xaml.h:

Thanks in advance.
UPDATE:
ToBrushFormatter.h and ToBrushFormatter.cpp added.

A: Hmm.. it seems it can't find the reference completely.  Change
MainPage.xaml.h  or whatever page you're accessing the Converter on
#include "MainPage.g.h"
#include "MyConverter.h"    // include your converter.h file instead of mine

Then MainPage.xaml
<Page.Resources>
    <local:MyConverter x:Key="whatever"></local:MyConverter>
</Page.Resources>

Should fix all your ugly looking wiggles.

Do a Clean Rebuild just to make sure :)


text:
Q: Get domain name My computer is in a Domain (Active Directory) and I need to get the domain name dynamically. I found the following code on the internet:
SelectQuery query = new SelectQuery("Win32_ComputerSystem");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
    foreach (ManagementObject mo in searcher.Get())
    {
        if ((bool)mo["partofdomain"])
        {
            this.Domain = mo["domain"].ToString();
            break;
        }
    }
 }

It works exactly as I want and returns exactly the domain name as I want (when I am logged as Administrator). If the user is not a Domain Admin, I have an Access denied exception.
Does anybody know how to get the domain even with non-domain administrator users?
NOTE: I have found this solution on Internet System.Environment.UserDomainName; but it only gives me a part of the domain name.
I.e. my domain is: something.domain.com
and the UserDomainName returns only something.

A: I'm going to add an answer to try to clear up a few things here as there seems to be some confusion. The main issue is that people are asking the wrong question, or at least not being specific enough.
What does a computer's "domain" actually mean?
When we talk about a computer's "domain", there are several things that we might be referring to. What follows is not an exhaustive list, but it covers the most common cases:

*

*A user or computer security principal may belong to an Active Directory domain.

*The network stack's primary DNS search suffix may be referred to as the computer's "domain".

*A DNS name that resolves to the computer's IP address may be referred to as the computer's "domain".

Which one do I want?
This is highly dependent on what you are trying to do. The original poster of this question was looking for the computer's "Active Directory domain", which probably means they are looking for the domain to which either the computer's security principal or a user's security principal belongs. Generally you want these when you are trying to talk to Active Directory in some way. Note that the current user principal and the current computer principal are not necessarily in the same domain.
Pieter van Ginkel's answer is actually giving you the local network stack's primary DNS suffix (the same thing that's shown in the top section of the output of ipconfig /all). In the 99% case, this is probably the same as the domain to which both the computer's security principal and the currently authenticated user's principal belong - but not necessarily. Generally this is what you want when you are trying to talk to devices on the LAN, regardless of whether or not the devices are anything to do with Active Directory. For many applications, this will still be a "good enough" answer for talking to Active Directory.
The last option, a DNS name, is a lot fuzzier and more ambiguous than the other two. Anywhere between zero and infinity DNS records may resolve to a given IP address - and it's not necessarily even clear which IP address you are interested in. user2031519's answer refers to the value of HTTP_HOST, which is specifically useful when determining how the user resolved your HTTP server in order to send the request you are currently processing. This is almost certainly not what you want if you are trying to do anything with Active Directory.
How do I get them?
Domain of the current user security principal
This one's nice and simple, it's what Tim's answer is giving you.
System.Environment.UserDomainName

Domain of the current computer security principal
This is probably what the OP wanted, for this one we're going to have to ask Active Directory about it.
System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain()

This one will throw a ActiveDirectoryObjectNotFoundException if the local machine is not part of domain, or the domain controller cannot be contacted.
Network stack's primary DNS suffix
This is what Pieter van Ginkel's answer is giving you. It's probably not exactly what you want, but there's a good chance it's good enough for you - if it isn't, you probably already know why.
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName

DNS name that resolves to the computer's IP address
This one's tricky and there's no single answer to it. If this is what you are after, comment below and I will happily discuss your use-case and help you to work out the best solution (and expand on this answer in the process).

A: I found this question by the title. If anyone else is looking for the answer on how to just get the domain name, use the following environment variable.
System.Environment.UserDomainName

I'm aware that the author to the question mentions this, but I missed it at the first glance and thought someone else might do the same.
What the description of the question then ask for is the fully qualified domain name (FQDN).

A: Why are you using WMI? Can't you use the standard .NET functionality?
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

A: If you want specific users to have access to all or part of the WMI object space, you need to permission them as shown here.  Note that you have to be running on as an admin to perform this setting.

A: I know this is old.  I just wanted to dump this here for anyone that was looking for an answer to getting a domain name.  This is in coordination with Peter's answer.  There "is" a bug as stated by Rich.  But, you can always make a simple workaround for that.  The way I can tell if they are still on the domain or not is by pinging the domain name.  If it responds, continue on with whatever it was that I needed the domain for.  If it fails, I drop out and go into "offline" mode.  Simple string method.
 string GetDomainName()
    {
        string _domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;

        Ping ping = new Ping();

        try
        {
            PingReply reply = ping.Send(_domain);

            if (reply.Status == IPStatus.Success)
            {
                return _domain;
            }
            else
            {
                return reply.Status.ToString();
            }
        }
        catch (PingException pExp)
        {
            if (pExp.InnerException.ToString() == "No such host is known")
            {
                return "Network not detected!";
            }

            return "Ping Exception";
        }
    }

A:  protected void Page_Init(object sender, EventArgs e)
 {
   String hostdet = Request.ServerVariables["HTTP_HOST"].ToString();
 }


text:
Q: In SSIS, can we download data from a server which only supports Active Directory Integrated Authentication Using SSIS, we need to download data from a server  which only supports Active Directory Integrated Authentication. Is it possible? What is the process?

A: Yes it is possible.  The process is to use a connection string that specifies integrated security, and to run the package in the context of an active directory user account that has the needed permission on the database server.

A: Got this. Updated Data Tools to Sql Server Data Tools Update 2 and using ado.net connection, I am able to pull data from the server.


text:
Q: Renaming '_next' to 'next' in the out directory: NextJS I'm building NextJS chrome extension, the problem that I'm facing is that when I 'load unpacked' extension it say that "Cannot load extension with file or directory name _next. Filenames starting with _ are reserved for use by the system."
I have checked some solutions online which says that renaming '_next' to 'next' and then changing all '_next' to 'next' in the 'out' directory should work.
the commands for the above tasks are
rm -rf .next/ out/
rm extension.zip
npm run build
npm run export
mv ./out/_next ./out/next
cd ./out && grep -rli '_next' * | xargs -I@ sed -i '' 's/_next/next/g' @
zip -r -FS ../my-extension.zip *

I have checked the above commands but it changes my styles and routing doesn't work after that.
before changing '_next' to 'next' my extension looks like this in the browser

after moving '_next' to 'next' in the 'out' directory,
mv ./out/_next ./out/next

my extension looks like this in the browser.

Note: I know that i have to change all the chunks which include '_next' to 'next' in the 'out' directory, but I don't know how to do that, because when I run
cd ./out && grep -rli '_next' * | xargs -I@ sed -i '' 's/_next/next/g' @

the output it gives me is:
$ cd ./out && grep -rli '_next' * | xargs -I@ sed -i '' 's/_next/next/g' @
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory
sed: can't read s/_next/next/g: No such file or directory

kindly guide me, how can I rename all '_next*' to 'next*' in the this directory.
Thank you for your precious time.


text:
Q: Error de match con expresiones regulares en preg_match_all El problema es que al hacer un match de cada aparición de un carácter regex del string me retorna todo bien, pero el primer resultado siempre le falta el último carácter.
$string = "@user#12458 y @user2#12345 son dos apariciones";
preg_match_all('/\@(.*?)\#([0-9]*5)/i', $string, $mentions, PREG_SET_ORDER);
foreach ($mentions as $user){
    $x = $user[1];
    $x = $user[2];
    $getUser = $connection->prepare("SELECT id FROM x WHERE x =:x AND x =:x");
    $getUser->bindParam("x", $x);
    $getUser->bindParam("x", $x);
    $getUser->execute();
    $userId = $getUser->fetch();
    if ($userId>0) {
        echo "hay";
    }else{
        echo "no hay";
    }
}

El código de arriba tiene una función pregmatchall con la expresión irregular que se supone que debe encontrar todo lo que tenga un @, letras, # y números, soy nuevo en esto de las regex así que tuve que consultar si estaba bien y me dijeron que así es, pero no sé porque a la hora de hacer $user[1] de el primer resultado, me devuelve "1245", dejando de lado al 8 que es el último carácter, pero en el segundo resultado y $user[1] me devuelve el numero completo.
Probé editando el *5 por * y no hay problemas, pero también pierde el chiste el la función, porque sólo quiero que sean 5 carácteres después de 5, esto sólo me pasa en php, no me pasa en js.

A: Tu problema esta en la regex, la misma debería ser la siguiente \@(.*?)\#([0-9]{5})/.

El porque del error es el siguiente:

{5} Indica que debe el resultado del token anterior debe
  coincidir con la cantidad especificada, en este caso exactamente 5.
*5 Indica que cualquier cantidad del token anterior ( 0 o mas) y que debe
  coincidir con el 5 al final


text:
Q: Uncaught TypeError: Cannot read property 'top' of null in fullCalendar For fullCalendar I have written the code below:
$('#mycalendar').fullCalendar(
            {
                allDaySlot:false,
                slotDuration: '00:30:00' ,
                //slotMinutes: '120',
                lang: currentLangCode,
                minTime: '4:00am',
                maxTime: '24:00pm',
                slotEventOverlap: true,
                slotLabelFormat:'h(:mm)a',
                showAgendaButton: true,
                columnFormat: { month: 'ddd', week: 'ddd M/D', day: 'ddd M/D' },
                timeFormat: 'H:mm',
                defaultView: 'listWeek',
                eventLimit: true,
                theme:false,
                editable: true,
                contentHeight:'auto',
                weekends: false ,
                //timezoneParam: 'America/Los_Angeles',
                //ignoreTimezone: false,
                header:
                {
                    left: 'prev,next today',
                    center: 'title',
                    // right: 'agendaWeek'
                    right: 'month,agendaWeek,agendaDay,listWeek'
                },
                views: {
                    listDay: { buttonText: 'Day' },
                    listWeek: { buttonText: 'Week' },
                    month: {
                        columnFormat: 'ddd'
                    },
                    agenda: {
                        columnFormat: 'ddd'
                    }
                },

I am getting below error for agendaWeek and agendaDay:

I am using:
jQuery JavaScript Library v3.3.1
FullCalendar v3.9.0

A: It's because your values for minTime and maxTime and invalid and not parseable as momentJS objects. fullCalendar relies on momentJS to do its date and time processing. Because of this the calendar does not know where to start the display (and thus where the "top" of the calendar is, hence the error message).
Set them to
minTime: '04:00',
maxTime: '24:00',

instead.
See here for a working demo: http://jsfiddle.net/sbxpv25p/581/
See http://momentjs.com/docs/#/parsing/string/ for a list of valid date/time formats which momentJS can recognise. You'll see that "am" and "pm" are not recognised items. In any case they are also unnecessary since you're already specifying the time in 24hr format.


text:
Q: dask.bag, how should I efficiently run several computations over the same data I'm processing a fair amount of data, and the bulk of the time is spent loading the data and parsing the json/whatever. I'd like to collect simple statistics over the whole dataset using a single scan.
I'd hoped I could use the graph simplification in compute using the following pattern:
parsed = read_text(files).map(parsing)
example_stat_future = parsed.map(foo).frequencies()
another_stat_future = parsed.map(bar).sum()
etc.
example_stat, another_stat = compute(example_stat_future, another_stat_future)

but I see extreme slowdowns when trying that. Here's my example code:
from json import loads, dumps
from time import time
import dask.bag as db

print("Setup some dummy data")
for partition in range(10):
    with open("/tmp/issue.%d.jsonl" % partition, "w") as f_out:
        for i in range(100000):
            f_out.write(dumps({"val": i, "doubleval": i * 2}) + "\n")

print("Running as distinct computations")
loaded = db.read_text("/tmp/issue.*.jsonl").map(loads)
first_val = loaded.pluck("val").sum()
second_val = loaded.pluck("doubleval").sum()
start = time()
first_val.compute()
print("First value", time() - start)
start = time()
second_val.compute()
print("Second value", time() - start)

print("Running as a single computation")
loaded = db.read_text("/tmp/issue.*.jsonl").map(loads)
first_val = loaded.pluck("val").sum()
second_val = loaded.pluck("doubleval").sum()
start = time()
db.compute(first_val, second_val)
print("Both values", time() - start)

And the output
On datasets with millions of items, I've never finished a run before killing it for taking too long.
Setup some dummy data
Running as distinct computations
First value 0.7081761360168457
Second value 0.6579079627990723
Running as a single computation
Both values 37.74176549911499

Is there a common pattern for solving this kind of issue?

A: Short answer
Import and run the following and things should be faster
from dask.distributed import Client
c = Client()

Make sure you have dask.distributed installed
conda install dask distributed -c conda-forge
# or
pip install dask distributed --upgrade

Although note, you'll have to do this within an if __name__ == '__main__': block at the bottom of the file rather than at the top level:
from ... import ...

if __name__ == '__main__':
    c = Client()
    # proceed with the rest of your dask.bag code

Long answer
Dask has a variety of schedulers.  Dask.bag uses the multiprocessing scheduler by default, but could use others just as easily.  See this doc for more information.
The multiprocessing scheduler does work in a separate process, and then it brings those results back to the main process when necessary.  For simple linear workloads like b.map(...).filter(...).frequencies() tasks can all be fused into one single task that goes to a process, computes, and then returns just a very small result.
However, when a workload has any sort of forking (such as you describe) the multiprocessing scheduler has to send the data back to the main process.  Depending on the data, this can be expensive because we need to serialize the objects as they move between processes.  The basic multiprocessing scheduler within Dask has no concept of data locality.  Everything is coordinated by the central process.
Fortunately, Dask's distributed scheduler is much smarter and can handle these situations easily.  When you run dask.distributed.Client() without any arguments you create a local "cluster" of processes on your computer.  There are a variety of other advantages to this; for example if you navigate to https://localhost:8787/status you'll be treated to a running dashboard of all of your computations.


text:
Q: Cypress using typescript - Getting no spec files were found error Getting the error "Can't run because no spec files were found. , even though .ts spec file is available in Cypress.
Run the following command in terminal:
npx cypress run --spec="./cypress/integration/specs/Test1.spec.ts".

Tried to run in Cypress test runner using "npx cypress open", but the spec file is not displayed in runner
tsconfig.json file:
 {
  "compilerOptions": {
    "target": "es2017",
    "lib": ["es2017", "dom"],
    "types": ["cypress", "node"],
    "baseUrl": "./"
  },
  "include": ["./**/*.ts"]
}

Test1.spec.ts file:
/// <reference types="Cypress" />

describe('Google Navigation', () => {
    it('Google Search',() => {
        cy.visit('https://www.google.com');

    });
});

Folder structure:

A: Change the = into a space
npx cypress run --spec "cypress/integration/specs/Test1.spec.ts"

cypress run --spec


text:
Q: endl doesn't seem to execute I've read and re-read the code but I can't find a logical conclusion as to why when run, there isn't a newline created between the start and end times. Both positive and negative advice is appreciated.
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    //start time and end time of shift
    vector <int> vstart;
    vector <int> vend;
    vector <string> days_of_week = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    int start, end;
    while (cin >> start) {
        vstart.push_back(start);
    }
    while (cin >> end) {
        vend.push_back(end);
    }

    for (string d : days_of_week) {
        cout << d << "\t";
    }
    cout << endl << "---------------------------------------------------------\n";
    for (int s : vstart) {
        cout << s << "\t";
    }
    cout << endl;
    for (int e : vend) {
        cout << e << "\t";
    }
    cout << endl;
}

A: Let's look at this portion of code.
while (cin >> start) {
    vstart.push_back(start);
}
while (cin >> end) {
    vend.push_back(end);
}

In the first loop, you read in values until cin>>start reaches an end-of-file byte, or fails in a different way. But you do not clear that fail-state.
You have to call cin.clear(); to be able to read new input in the second loop.
while (cin >> start) {
    vstart.push_back(start);
}
cin.clear();
while (cin >> end) {
    vend.push_back(end);
}

Further reading: Why would we call cin.clear() and cin.ignore() after reading input?

A: This while loop will execute as long as it can successfully extract int values. It doesn't know to stop after reading 7 numbers and is putting all your input into vstart.
while (cin >> start) {
    vstart.push_back(start);
}

I think you want something like this for loop that includes logic to stop after reading 7 values.
for (int i = 0; (i < 7) && (cin >> start); ++i) {
    vstart.push_back(start);
}


text:
Q: How to draw a cube completely filled with water, the other with water by half and the last leave it empty? I want to draw 3 cubes, one filled with water, a full half full and another completely empty. I can draw them, but I can't do the impression of three forms: full, empty and half full.
\documentclass{article}
\usepackage{tikz}
\usepackage{xcolor}
\begin{document}
\newcommand{\Depth}{2}
\newcommand{\Height}{2}
\newcommand{\Width}{2}
\begin{tikzpicture}
\coordinate (O) at (0,0,0);
\coordinate (A) at (0,\Width,0);
\coordinate (B) at (0,\Width,\Height);
\coordinate (C) at (0,0,\Height);
\coordinate (D) at (\Depth,0,0);
\coordinate (E) at (\Depth,\Width,0);
\coordinate (F) at (\Depth,\Width,\Height);
\coordinate (G) at (\Depth,0,\Height);
\draw[blue,fill=gray!20] (O) -- (C) -- (G) -- (D) -- cycle;
\draw[blue,fill=gray!20] (O) -- (A) -- (E) -- (D) -- cycle;
\draw[blue,fill=gray!10] (O) -- (A) -- (B) -- (C) -- cycle;
\draw[gray,fill=gray20,opacity=0.4] (D) -- (E) -- (F) -- (G) -- cycle;
\draw[blue,fill=gray!20,opacity=0.6] (C) -- (B) -- (F) -- (G) -- cycle;
\draw[blue,fill=gray!20,opacity=0.8] (A) -- (B) -- (F) -- (E) -- cycle;
\end{tikzpicture}
\qquad
\begin{tikzpicture}
\coordinate (O) at (0,0,0);
\coordinate (A) at (0,\Width,0);
\coordinate (B) at (0,\Width,\Height);
\coordinate (C) at (0,0,\Height);
\coordinate (D) at (\Depth,0,0);
\coordinate (E) at (\Depth,\Width,0);
\coordinate (F) at (\Depth,\Width,\Height);
\coordinate (G) at (\Depth,0,\Height);
\draw[fill=whitegray!20] (O) -- (C) -- (G) -- (D) -- cycle;
\draw[fill=gray!20] (O) -- (A) -- (E) -- (D) -- cycle;
\draw[fill=gray!10] (O) -- (A) -- (B) -- (C) -- cycle;
\draw[fill=gray20,opacity=0.4] (D) -- (E) -- (F) -- (G) -- cycle;
\draw[fill=gray!5,opacity=0.6] (C) -- (B) -- (F) -- (G) -- cycle;
\draw[fill=gray!5,opacity=0.8] (A) -- (B) -- (F) -- (E) -- cycle;
\end{tikzpicture}
\qquad
\begin{tikzpicture}
\coordinate (O) at (0,0,0);
\coordinate (A) at (0,\Width,0);
\coordinate (B) at (0,\Width,\Height);
\coordinate (C) at (0,0,\Height);
\coordinate (D) at (\Depth,0,0);
\coordinate (E) at (\Depth,\Width,0);
\coordinate (F) at (\Depth,\Width,\Height);
\coordinate (G) at (\Depth,0,\Height);
\draw[fill=whitegray!20] (O) -- (C) -- (G) -- (D) -- cycle;
\draw[fill=gray!20] (O) -- (A) -- (E) -- (D) -- cycle;
\draw[fill=gray!10] (O) -- (A) -- (B) -- (C) -- cycle;
\draw[fill=gray20,opacity=0.4] (D) -- (E) -- (F) -- (G) -- cycle;
\draw[fill=gray!5,opacity=0.6] (C) -- (B) -- (F) -- (G) -- cycle;
\draw[fill=gray!5,opacity=0.8] (A) -- (B) -- (F) -- (E) -- cycle;
\end{tikzpicture}
\end{document}

A: Something like this?

I defined a command \FillCube with an optional argument taking values between 1 and 0, controlling up to where the cube is filled. The default is 1, meaning full (0 means empty).
The code:
\documentclass[varwidth=50cm,border=5pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}

\newcommand{\Depth}{2}
\newcommand{\Height}{2}
\newcommand{\Width}{2}

\newcommand\FillCube[1][1]{
\coordinate (O) at (0,0,0);
\coordinate (A) at (0,\Width,0);
\coordinate (B) at (0,\Width,\Height);
\coordinate (C) at (0,0,\Height);
\coordinate (D) at (\Depth,0,0);
\coordinate (E) at (\Depth,\Width,0);
\coordinate (F) at (\Depth,\Width,\Height);
\coordinate (G) at (\Depth,0,\Height);
\ifx#10\relax
\else
\draw[fill=blue!40] (O) -- (C) -- (G) -- (D) -- cycle;
\fi
\draw[fill=gray!20,opacity=0.5] (O) -- (C) -- (G) -- (D) -- cycle;
\draw[fill=gray!20] (O) -- (A) -- (E) -- (D) -- cycle;
\draw[fill=blue!40] (O) -- ( $ (O)!#1!(A) $ ) -- ( $ (D)!#1!(E) $ ) -- (D) -- cycle;
\draw[fill=gray!20] (O) -- (A) -- (B) -- (C) -- cycle;
\draw[fill=blue!40] (O) -- ( $ (O)!#1!(A) $ ) -- ( $ (C)!#1!(B) $ ) -- (C) -- cycle;
\draw[fill=gray!20,opacity=0.4] (D) -- (E) -- (F) -- (G) -- cycle;
\draw[fill=blue!40,opacity=0.4] (D) -- ( $ (D)!#1!(E) $ ) -- ( $ (G)!#1!(F) $ ) -- (G) -- cycle;
\draw[fill=gray!20,opacity=0.6] (C) -- (B) -- (F) -- (G) -- cycle;
\draw[fill=blue!40,opacity=0.6] (C) -- ( $ (C)!#1!(B) $ ) -- ( $ (G)!#1!(F) $ ) -- (G) -- cycle;
\if#10\relax
\else
\draw[fill=blue!40,opacity=0.6] ( $ (O)!#1!(A) $ ) -- ( $ (C)!#1!(B) $ ) -- ( $ (G)!#1!(F) $ ) -- ( $ (D)!#1!(E) $ ) -- cycle;
\fi
}
\begin{document}

\begin{tikzpicture}
\foreach[count=\xi] \Valor in {1,0.8,...,0.2,0}
{
\begin{scope}[xshift=\xi*3cm]
\FillCube[\Valor]
\end{scope}
}
\end{tikzpicture}\par\bigskip

\begin{tikzpicture}
\FillCube
\begin{scope}[xshift=3cm]
\FillCube[0.5]
\end{scope}
\begin{scope}[xshift=6cm]
\FillCube[0]
\end{scope}
\end{tikzpicture}

\end{document}

An animation:

The code for the animation:
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{calc}

\newcommand{\Depth}{2}
\newcommand{\Height}{2}
\newcommand{\Width}{2}

\newcommand<>\FillCube[1][1]{
\only#2{\coordinate (O) at (0,0,0);
\coordinate (A) at (0,\Width,0);
\coordinate (B) at (0,\Width,\Height);
\coordinate (C) at (0,0,\Height);
\coordinate (D) at (\Depth,0,0);
\coordinate (E) at (\Depth,\Width,0);
\coordinate (F) at (\Depth,\Width,\Height);
\coordinate (G) at (\Depth,0,\Height);
\ifx#10\relax
\else
\draw[fill=blue!40] (O) -- (C) -- (G) -- (D) -- cycle;
\fi
\draw[fill=gray!20,opacity=0.5] (O) -- (C) -- (G) -- (D) -- cycle;
\draw[fill=gray!20] (O) -- (A) -- (E) -- (D) -- cycle;
\draw[fill=blue!40] (O) -- ( $ (O)!#1!(A) $ ) -- ( $ (D)!#1!(E) $ ) -- (D) -- cycle;
\draw[fill=gray!20] (O) -- (A) -- (B) -- (C) -- cycle;
\draw[fill=blue!40] (O) -- ( $ (O)!#1!(A) $ ) -- ( $ (C)!#1!(B) $ ) -- (C) -- cycle;
\draw[fill=gray!20,opacity=0.4] (D) -- (E) -- (F) -- (G) -- cycle;
\draw[fill=blue!40,opacity=0.4] (D) -- ( $ (D)!#1!(E) $ ) -- ( $ (G)!#1!(F) $ ) -- (G) -- cycle;
\draw[fill=gray!20,opacity=0.6] (C) -- (B) -- (F) -- (G) -- cycle;
\draw[fill=blue!40,opacity=0.6] (C) -- ( $ (C)!#1!(B) $ ) -- ( $ (G)!#1!(F) $ ) -- (G) -- cycle;
\if#10\relax
\else
\draw[fill=blue!40,opacity=0.6] ( $ (O)!#1!(A) $ ) -- ( $ (C)!#1!(B) $ ) -- ( $ (G)!#1!(F) $ ) -- ( $ (D)!#1!(E) $ ) -- cycle;
\fi}
}

\begin{document}

\begin{frame}
\centering
\begin{tikzpicture}
\foreach[count=\xi] \Valor in {1,0.975,...,0.025,0}
  {\FillCube<\xi>[\Valor]}
\end{tikzpicture}
\end{frame}

\end{document}

On a terminal (using ImageMagick):
convert -verbose -delay 12 -loop 0 -density 300 a.pdf a.gif

A: I adapted Gonzalo Medina's solution to use the TikZ perspective library.
Please pay attention to the changed axis directions.
The view point can be changed by the 3d view={az}{el} option.
\documentclass[varwidth=50cm,border=5pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{perspective}
\newcommand{\Depth}{2}
\newcommand{\Height}{2}
\newcommand{\Width}{2}
\newcommand\FillCube[1][1]{
\coordinate (O) at (0,0,0);
\coordinate (A) at (0,0,\Depth);
\coordinate (B) at (0,\Width,\Depth);
\coordinate (C) at (0,\Width,0);
\coordinate (D) at (\Height,0,0);
\coordinate (E) at (\Height,0,\Depth);
\coordinate (F) at (\Height,\Width,\Depth);
\coordinate (G) at (\Height,\Width,0);

\ifx#10\relax
\else
\draw[fill=blue!40] (O) -- (C) -- (G) -- (D) -- cycle;
\fi

\draw[fill=gray!20,opacity=0.5] (O) -- (C) -- (G) -- (D) -- cycle;
\draw[fill=gray!20,opacity=0.6] (O) -- (A) -- (E) -- (D) -- cycle;
\draw[fill=gray!20,opacity=0.6] (O) -- (A) -- (B) -- (C) -- cycle;
\draw[fill=gray!20,opacity=0.6] (C) -- (B) -- (F) -- (G) -- cycle;
\draw[fill=gray!20,opacity=0.6] (D) -- (E) -- (F) -- (G) -- cycle;

\draw[fill=blue!40,opacity=0.3] (O) -- ( $ (O)!#1!(A) $ ) -- ( $ (D)!#1!(E) $ ) -- (D) -- cycle;
\draw[fill=blue!40,opacity=0.3] (O) -- ( $ (O)!#1!(A) $ ) -- ( $ (C)!#1!(B) $ ) -- (C) -- cycle;
\draw[fill=blue!40,opacity=0.6] (C) -- ( $ (C)!#1!(B) $ ) -- ( $ (G)!#1!(F) $ ) -- (G) -- cycle;
\draw[fill=blue!40,opacity=0.6] (D) -- ( $ (D)!#1!(E) $ ) -- ( $ (G)!#1!(F) $ ) -- (G) -- cycle;

\if#10\relax
\else
\draw[fill=blue!40,opacity=0.6] ( $ (O)!#1!(A) $ ) -- ( $ (C)!#1!(B) $ ) -- ( $ (G)!#1!(F) $ ) -- ( $ (D)!#1!(E) $ ) -- cycle;
\fi}
\begin{document}

\begin{tikzpicture}[3d view={120}{15}]
\foreach[count=\xi] \Valor in {1,0.8,...,0.2,0}
{
    \begin{scope}[xshift=\xi*3cm]
        \FillCube[\Valor]
    \end{scope}
}
\end{tikzpicture}\par\bigskip
\begin{tikzpicture}[3d view={120}{15}]
\FillCube
\begin{scope}[xshift=3cm]
\FillCube[0.5]
\end{scope}
\begin{scope}[xshift=6cm]
\FillCube[0]
\end{scope}
\end{tikzpicture}
\end{document}


text:
Q: Is "Adding up to the many times they have." after this sentence correct?
The ministers voted to increase their income. Adding up to the many times they have.

"...the many times they have VOTED TO INCREASE THEIR INCOME"?
is that it?
Can we end sentences that way?

A: In general, yes, when a past participle complement of "to have" is being repeated, then often we can omit the second instance when it is obvious. For example:

I've visited Paris, just as you have.

However, your sentence doesn't make sense because "adding up" doesn't seem to be used correctly here. Also, your second "sentence" is really a fragment. This would be better:

The ministers voted to increase their income, adding to the great number of times that they have.

However, this is still not so good, because the position of the implied verb (at the end of the sentence) is very far from its first instance ("voted"), while two other verbs ("to increase" and "adding") intervene. It is therefore not so easy for the reader to figure out what is meant. I would use a "pro-verb" to help the reader understand the intended structure:

The ministers voted to increase their income, adding to the great number of times that they have done so.


text:
Q: Get Mesh of particle collider How would I go about getting the mesh filter of a particle collision and than assign that mesh to the particle.
So I have a OnParticleCollision. I hit the object take this object I get its Mesh Filter. I than want to assign this to that of my particle so it takes the effect of its physical build.
Here is my code so far.
    void Start()
    {
        Debug.Log("Script Starting...");
        part = GetComponent<ParticleSystem>();
        collisionEvents = new List<ParticleCollisionEvent>();
    }

    void OnParticleCollision(GameObject coll)
    {
        // Getting the object of the collider
        Collider obj = coll.GetComponent<Collider>();

        Mesh mesh = obj.GetComponent<MeshFilter>().mesh;

        // Assign the mesh shape of the collider to that of the particle
        ElectricWave.shape.meshRenderer = mesh; // I know this doesnt work as is.

        // Play effect
        ElectricWave.Play();

    }

A: If you're wanting all particles in the system to take on that mesh, it's straightforward. Just get the collided-with object mesh and apply that to the ParticleSystemRenderer:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParticleCollision : MonoBehaviour
{

    private ParticleSystemRenderer particleRenderer;

    void Start()
    {
        particleRenderer = GetComponent<ParticleSystemRenderer>();
    }

    void OnParticleCollision(GameObject other)
    {
        particleRenderer.renderMode = ParticleSystemRenderMode.Mesh;
        particleRenderer.material = other.GetComponent<Renderer>().material;
    }
}

However, if you instead are looking to change the mesh of only that particle, it will be a lot more complicated, since the ParticleCollisionEvent data does not contain which particle collided with it. A good starting point might be looking at the ParticleCollisionEvent.intersection value, and trying to find the particle nearest that point using GetParticles. It might be extrememly computationally expensive, though, if it works at all.
An easier way might be to fake it by having multiple particle systems with extremely low emission rates, so that changing the mesh of a whole particle system results in changing just one visible particle, and resetting the system's mesh before every new particle is emitted. That way you get the visual effect you're looking for, but under the hood it's multiple particle systems acting as one.


text:
Q: addClass removeClass w/jQuery for Animations SEE MY ANSWER BELOW
I'm implementing my own sliding page transition with CSS using jQuery and having the following issue:
I'm using the addClass method and it works the first time a link is fired to load a page dynamically into the div. When another link is fired, the page loads without the transition.  I figured it was that I need to use the removeClass method but this prevents the transitions from not fireing at all. Iv'e tried various ways of using the two classes but I cant get it to work every time a link is fire.
Any idea to what I have wrong/missing?
EDIT  For those who doesnt under stand the CSS subClass:

More than one class may be added at a time, separated by a space, to
  the set of matched elements, like so:

$("p").addClass("myClass yourClass");

Taken from the jQuery Docs
thnx.
/* --------------- Handle Page Body Loading ----------------- */

function loadBody(target, gotoURL)
{
    $('#' + target)
    .addClass('slide out')
    .load(gotoURL, function (response)
    {
        iniScroll('scrollBody', 'bodyScrollContainer');
    })
    .addClass('slide in')
    removeSlideClass();//WITHOUT THIS, IT FIRES ONLY THE FIRST USE!!
};

function removeSlideClass()
{
    $('#bodyContent').removeClass('slide in');
    $('#bodyContent').removeClass('slide out');
};

IF i WRITE THE CODE AS SAID BELOW, IT WORKS EXACTLY THE SAME (jQuery 101);
function loadBody(target, gotoURL)
{
    $('#' + target).addClass('slide out');
    $('#' + target).load(gotoURL, function (response)
    {
        iniScroll('scrollBody', 'bodyScrollContainer');
    });
    $('#' + target).addClass('slide in');
    $('#' + target).removeSlideClass();
};

function removeSlideClass()
{
    $('#bodyContent').removeClass('slide in');
    $('#bodyContent').removeClass('slide out');
};

the CSS:
.out, .in {
    -webkit-animation-timing-function: ease-out;
    -webkit-animation-duration: 650ms;
}
.slide.out {
    -webkit-transform: translateX(-100%);
    -webkit-animation-name: slideouttoleft;
}

.slide.in {
    -webkit-transform: translateX(0);
    -webkit-animation-name: slideinfromright;
}

A: I figured it out:
Binding the .addClass('slide out') method with webkitAnimationEnd event,  followed by a return statement, fires the second transition when the first has completed. When this event fires, it removes all classes from the original page. Remembering to unbind the webkitAnimationEnd event prevents adding on extra handlers to the new page so the process can start again when we need it. Thus jQuery's removeClass() method is not needed.
The new page transition method.
/* --------------- Handle Page Body Loading ----------------- */

function loadBody(target, gotoURL)
{
    $('#' + target)
    .addClass('slide out')
    .bind('webkitAnimationEnd', function(){
        $(this).load(gotoURL, function (e)
        {
            iniScroll('scrollBody', 'bodyScrollContainer');
            $('#' + target)
            .toggleClass('slide in')
            .unbind('webkitAnimationEnd');
        });
    });
};

A: CSS class should not include any spaces...
ie:
slide out, should be slide-out, or slide_out or slideOut
Try removing the spaces and fixing the classes in the css to Match.


text:
Q: How can I add an onclick event to just the first column of a gridview and not the entire row? Title is pretty self-explanatory. I have a gridview, and when the user clicks on a particular row, I add a shadow to the first column. The problem is, the user can click anywhere on the row, and the shadow is added, but the link is only opened in a new tab if the user clicks on the link (i.e. first column). How do I add the onclick event to the first column of every row only?
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // Javascript function to call on row-click event
        e.Row.Attributes.Add("onClick", "javascript:void SelectRow(this);");
    }

If it helps, I used the example here to implement SelectRow.

A: Add it to e.Row.Cells[0]  instead
if (e.Row.RowType == DataControlRowType.DataRow)
{
   e.Row.Cells[0].Attributes.Add("onClick", "SelectRow(this);");
}

A: Try:
e.Row.Cells[0].Attributes.Add("onClick", "javascript:void SelectRow(this);");


text:
Q: Rails Mountable Engine "update" method inaccessible I have a project with a mounted engine within it. So far, everything works as I expect except "update" functionality.  The engine controller was created via scaffold, and everything looks as I expect it to.  Index, Show, Edit, Delete all work as expected, as do the associated before and after filter actions.
However, Update throws the following exception:
screen:
NoMethodError in MeetmeManagerPlugin::ConferenceRoomsController#update

private method `update' called for #<MeetmeManagerPlugin::ConferenceRoom:0x007fe8ac24a080>

console:
NoMethodError (private method `update' called for #<MeetmeManagerPlugin::ConferenceRoom:0x007fe8ac24a080>):
  activemodel (3.2.13) lib/active_model/attribute_methods.rb:404:in `method_missing'
  activerecord (3.2.13) lib/active_record/attribute_methods.rb:149:in `method_missing'
  /Volumes/MacTheCrypt 1/Project Work/jkl5_projects/meetme_manager_plugin/app/controllers/meetme_manager_plugin/conference_rooms_controller.rb:57:in `update'
  actionpack (3.2.13) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
  actionpack (3.2.13) lib/abstract_controller/base.rb:167:in `process_action'
  actionpack (3.2.13) lib/action_controller/metal/rendering.rb:10:in `process_action'
  actionpack (3.2.13) lib/abstract_controller/callbacks.rb:18:in `block in process_action'

The actual code in the controller looks like:
def update
  if @conference_room.update(conference_room_params)
    redirect_to @conference_room, notice: 'Conference room was successfully updated.'
  else
    render action: 'edit'
  end
end

What it is choking on is the "@conference_room.update(conference_room_params)".
A fair bit of web searching hasn't yet put any light on this, so I figured someone here might have a suggestion.  Thanks in advance, and let me know if you need anything further from me.

A: The work around for this problem is to use "update_attributes" and not "update":
def update
  if @conference_room.update_attributes(conference_room_params)
    redirect_to @conference_room, notice: 'Conference room was successfully updated.'
  else
    render action: 'edit'
  end
end # def update

Works just fine this way. So while I'm still not sure why the other approach is borken, given it's scaffold code, this does allow program execution to complete without error.


text:
Q: CASE clause statement in DB2 I have a table PROCESS . Currently it doesnt not have any records in it. I need to return one hardcoded row if the table doesnt have any record .
I am doing a select when the primary key column "id" is null then i hard code the values and return it as below
SELECT CASE WHEN p.ID IS NULL THEN 1 ELSE p.ID END ,
CASE WHEN p.COMPANY IS NULL THEN 'COMP1' ELSE p.COMPANY END
FROM PROCESS p

I took reference from the below link
If-else statement in DB2/400
But it always returns me an empty row in DB2 database and not the hardcoded values used in select statement.
08:50:27    SUCCESS SELECT  0.307   0.301   0   Empty result set fetched
08:50:29    FINISHED        0.307   0.301   0   Success: 1 Failed: 0
Please help me on this

A: no way to do in this way, since a primary key could never be null. and select * from empty table return no row (0 row) it do not return null.
you can do it like that:
select ID, COMPANY from PROCESS
UNION ALL
select 1 as ID, 'COMP1' as COMPANY from sysibm.sysdummy1 where (select count(*) from PROCESS) = 0;

A: There are various ways you could achieve what (I think) you want. This is one
SELECT
    COALESCE(ID,1) AS ID
,   COALESCE(COMPANY,'COMP1') AS COMPANY
FROM
    TABLE(VALUES 1) AS DUMMY(D)
LEFT JOIN
    PROCESS
ON
    1=1


text:
Q: Where I can find phpize for php7.1.1? I currently installed php7.0 version of phpize, and xdebug does not work, wondering if there is a phpize for php7.1.1?

A: To install xdebug for php7.1. Follow these steps to install for php7.1:

*

*Install php7.1 dev, if there go to step 2:
sudo apt install php-all-dev

*Install the xdebug module:
sudo apt install php-xdebug

*Retstart apache with:
sudo systemctl restart apache2

*To test it:
a. Go to the page you added to your OP and add the contents of your phpinfo() command to get the relevant xdebug-2.5.1.tgz file
b. Follow the steps as directed on that page:

*

*tar -xvzf xdebug-2.5.1.tgz

*cd xdebug-2.5.1/

*now run phpize7.1, not phpize as given on that page

*

*You should see this output, or something similar
Configuring for:
...
Zend Module Api No:      20151012
Zend Extension Api No:   320151012

*Add the following to the /etc/php/7.1/mods-available/xdebug.ini under any entry you see there:
xdebug.show_error_trace = 1

*Restart apache: sudo systemctl restart apache2

*Check your phpinfo() output on a webpage you should see the xdebug section now.


text:
Q: How to implement SSO using IdentityServer4 (OAuth2) in Apache Superset? I have a two web applications developed in ASP.NET MVC and ASP.NET CORE. Both uses SSO (Single Sign-On) using IdentityServer4 OAuth2.
Now, my client's new requirement is Data Analytics using Apache Superset with SSO. I have researched and read Apache Superset's official website regarding this implementation. They redirected to Flask App Builder which is used as security layer in Superset.
I read document given in Flask App Builder documentation page. They have given sample for SSO using Google or Facebook or Twitter.
But, here in my case I need to implement custom security management using IdentityServer4
Is it possible to implement Apache Superset SSO (OAuth2) using IdentityServer4?
If yes, anyone share documentation or sample to configure it.


text:
Q: Why is binary_crossentropy performing better than categorical_crossentropy for multiclass classification in Keras? I've seen many similar issues in stackoverflow but none of this refer to my case.
I have a multiclass classification problem and my labels are mutually exclusive.
Training with a binary_crossentropy due to a typo, resulted in lower loss and higher accuracy. What's interesting here is that, unlike other issues in stackoverflow, I am printing the "categorical_accuracy" of Keras. My labels are one-hot encoded.
So, to be exact my code looks like that:
net = Sequential()
net.add(TimeDistributed(model_A, input_shape=(timesteps,960, 75, 1)))
net.add(LSTM(100))
net.add(Dropout(0.5))
net.add(Dense(100, activation='relu'))
net.add(Dense(len(labels), activation='softmax'))

net.compile(loss='binary_crossentropy', optimizer=adam_opt, metrics=['binary_accuracy', 'categorical_accuracy'])

I also tried to train with "categorical_crossentropy", when I noticed the typo and the results where worse. How can this be explained?


text:
Q: First time creating HttpRequestMessage instance takes time Hello I have a problem I have an application which are hosted in OpenShift and I noticed that after deploying or restarting pods application first call is very slow. It takes more than 1 second just to create Request Message. After some debugging  with Stopwatch I see that first time creating HttpRequestMessage
    var watch1 = System.Diagnostics.Stopwatch.StartNew();

    var request = new HttpRequestMessage()
    {
        RequestUri = new Uri(OriginalEndpoint),
        Method = HttpMethod.Post,
        Content = new StringContent(requestBody, Encoding.UTF8, "application/json")
    };

    watch1.Stop();
    Console.WriteLine("Create request HttpRequestMessage: " + elapsedMs1);

always takes more than 1 second.

I tried to do separate warmup service for creating HttpRequestMessage and doing actual call.
    var request = new HttpRequestMessage()
    {
        RequestUri = new Uri("http://Example"),
        Method = HttpMethod.Get,
        Content = new StringContent(requestBody, Encoding.UTF8, "application/json")
    };

    var response = _igcApiClient.HttpClient.SendAsync(request).Result;

But after my warmup service creates RequestMessage it still takes more than one second to create original request message in other class for the first time. So maybe someone had similar problems or have some ideas how to warmup an application without calling original endpoint in warmup service.


text:
Q: How to modify custom object security I setup a custom object (called Sensitive Documents) with a child-master relationship to the Contact object.  I was hoping to control the security of my custom object independent of the parent object (the Contact).  When I go to sharing settings though, it shows as "Controlled by Parent", and if I edit the settings, my custom object is not shown (so I can't change it).  How do I modify the sharing settings for the custom object?
My use case is that we need to control the security of attachments independent of the parent record they are attached to, and that's not supported by Salesforce (attachment security is inherited by the parent).  I found the suggestion to create a custom object and then control the security of that object, but it's not looking like that's possible.  Any other suggestions?

A: If the relationship to contacts is set to Master-Detail, sharing is enforced on the parent record.
If you change that field to a Lookup field, you can choose an independent sharing model.


text:
Q: Mudar a posição de um objeto em um mapa Galera, preciso de uma lógica que, detectando se o valor de x, y mudou, troque a posição de um objeto no mapa.
Tenho um mapa que contém 50x50 tiles, e nesses tiles existem objetos que eu posso mover utilizando o código abaixo:
var playerx = 10;
var playery = 15;

function drawMap() {
    for (i = 0; i < map.length; i++) {
        for (j = 0; j < map[i].length; j++) {
            var drawTile = map[i][j];
            var drawObj = objectMap[i][j];
            var xpos = (i-j) * tileH + mapX;
            var ypos = (i+j) * tileH/2 + mapY;

            ctx.drawImage(tileImg[drawTile], xpos, ypos);

            if (drawObj) {
                ctx.drawImage(objectImg[drawObj-1], xpos, ypos - (objectImg[drawObj-1].height));
            }
        }
    }
}

Para adicionar o objeto eu uso essa propriedade:
objectmap[playerx][playery] = 1;

E para remover eu uso a função delete:
delete objectmap[playerx][playery];

O que acontece é que o objeto fica nas posições 10 e 15 que são os valores das variáveis playerx e playery,  mas eu tenho uma função que pega a posição do mouse e ao clicar muda a o valor de playerx e playery, acontece que conforme o valor da função muda, vai adicionando objetos no mapa, sem remover o último.
Desse modo o mapa fica com vários objetos, mas eu quero que o objeto fique apenas onde os valores das variáveis apontam.
Vocês sabem como fazer isso com um if ou de outro modo?


text:
Q: is it possible to place a myfile.file in C:/Windows/System32/ location at runtime? I wish to place a file named as myFile.file in
C:/Windows/System32/ location.
Here is use java code to place my file. while I execute my program it throws "Access Denied:C:/Windows/System32/myFile.file".
why is it happening? Is it possible to place in that location?

A: That (and many other) system locations are restricted for admin users/elevated applications.
Application data should be stored in the user application data files in the user profile (or the common application data).
If you really must write into the system folder, then you will need to ask the user for permission via UAC, either by using ShellExecute() with the runas verb to run another program, or COM elevation (if that's possible in Java)
Update
See Andrew's answer for a method to get the correct path in Java.

A: Put myFile.file in a sub-directory of user.home.
The sub-directory could be the package name of the class saving the file.  E.G. if your main class is our.com.Main, store the file at ${user.home}/our/com/myFile.file.  The reason to use a sub-directory is to help prevent another apps. myFile.file from overwriting or interfering with your own version.
To get the location of user.home, see:
System.getProperty("user.home");

The value of user.home here, is:
Name        Value
user.home   C:\Users\Andrew

This technique will work reliably for Mac. & *nix, as well as Windows.


text:
Q: Bitrate in TVMLKit JS media player How to get bit rate information from the TVMLKit JS player object?
In apple documentation(https://developer.apple.com/documentation/tvmljs/player), I am not able to identify any attribute/method that returns this particular information. Is this possible to get this information?

A: Doesn't seem like there is any way to read the player item's access log from JS. At least none that I have been able to find either.
However, if you have access to the native code, as a workaround, you can listen for the AVPlayerItemNewAccessLogEntry notification.
Not the perfect solution, but perhaps it's enough for your use-case.
// Add observer somewhere.
NotificationCenter.default.addObserver(self, selector: #selector(accessLog(notification:)), name: .AVPlayerItemNewAccessLogEntry, object: nil)

@objc func accessLog(notification: Notification) {
    guard let playerItem = notification.object as? AVPlayerItem,
          let accessLogEvent = playerItem.accessLog()?.events.last
    else { return }
    _ = accessLogEvent.observedBitrate
}


text:
Q: Class property not returning right datetime format Why doesn´t this property return a datetime formated with the following pattern when using the property in the codebehind page in my ASP.NET Webforms website? When debugging i can see that the value the returning datetime is "2011-02-21 16:13:29.670" wich is correct.
Public Property UserLastUpdated() As DateTime
    Get
        Return _userLastUpdated.ToString("yyyy-MM-dd HH:mm:ss.fff")
    End Get
    Set(ByVal value As DateTime)
        _userLastUpdated = value
    End Set
End Property

But when i look at the returned value in the codebehind page i get this value
objUser.UserLastUpdated = #2/21/2011 4:13:29 PM#

And after assigning the returned property value to a hiddenfield in the .aspx page i get this value assign to the hiddenfield.value "2011-02-21 16:13:29"
hdnUserLastUpdated.Value = objUser.UserLastUpdated

A: You might want to switch the return type of   UserCreated() to string since the Get is actually returning a formatted string and not a DateTime instance or you could keep it as a DateTime type and not do the formatting in the getter. You could do the formatting when you are assigning it to the hidden field value
hdnUserLastUpdated.Value = objUser.UserLastUpdated.ToString("yyyy-MM-dd HH:mm:ss.fff")


text:
Q: What are the connectors CN11 and CN12 on STM32 Nucleo-F103RB used for? On the STM32 Nucleo-F103RB board, there are two connectors on the upper part named CN11 and CN12 respectively. Next to them there's a text that says GND, but if they are grounded why do they have jumpers on them? I couldn't find any relevant info on the manual, other than the fact that these jumpers can be removed to be used in other cases.

A: A quote from product manual:

Two unused jumpers are available on CN11 and CN12 (bottom side of the
board).

In the board schematics, all four pins are connected to GND.
In short, they are four ground pins, and you can store two jumpers on them.
On boards that have more of them, one on each corner, they also function as stand-offs.


text:
Q: Redis cluster command to get memory usage by key pattern I have a redis cluster where there are 3-4 different types of keys with prefixes for each. I want to get size percentage distribution of values of particular key type.
eg
redis keys catalog:styleId1, catalog:styleId2, size:styleId1, sizeStyleId2 etc
expected output
9% catalog:style 7560 bytes
12% catalog:style x bytes
Basically even range would work, but I need a simple way to do analysis on data size of particular key type.
I tried --bigKeys but it doesn't work on particular key pattern