text:
Q: CSS SubMenu modification Need some CSS help regarding SubMenu creation.
I have this below code for responsive Main Menu which is working fine. I need to create a SubMenu under the main menu.
For example :- Menu2 will habe two submenu like Menu2_SubMenu1 & Menu2_SubMenu2.
The color, format and hovering effect will be same like Main menu.
Can you kindly help me out with the CSS for the same. I am messing up with the Submenu CSS code code. Thanks in advance for your help.

<!DOCTYPE html>

Menu1

**Menu2**

Menu3

      ☰

A:

$("#cssmenu").menumaker({
    title: "Menu",
    breakpoint: 768,
    format: "multitoggle"
});
@import url(https://fonts.googleapis.com/css?family=Montserrat:400,700);
#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a,
#cssmenu #menu-button {
  margin: 0;
  padding: 0;
  border: 0;
  list-style: none;
  line-height: 1;
  display: block;
  position: relative;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
#cssmenu:after,
#cssmenu > ul:after {
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}
#cssmenu #menu-button {
  display: none;
}
#cssmenu {
  font-family: Montserrat, sans-serif;
  background: #2d5c88;
}
#cssmenu > ul > li {
  float: left;
}
#cssmenu.align-center > ul {
  font-size: 0;
  text-align: center;
}
#cssmenu.align-center > ul > li {
  display: inline-block;
  float: none;
}
#cssmenu.align-center ul ul {
  text-align: left;
}
#cssmenu.align-right > ul > li {
  float: right;
}
#cssmenu > ul > li > a {
  padding: 17px;
  font-size: 12px;
  letter-spacing: 1px;
  text-decoration: none;
  color: #dddddd;
  font-weight: 700;
  text-transform: uppercase;
}
#cssmenu > ul > li:hover > a {
  color: #ffffff;
}
#cssmenu > ul > li.has-sub > a {
  padding-right: 30px;
}
#cssmenu > ul > li.has-sub > a:after {
  position: absolute;
  top: 22px;
  right: 11px;
  width: 8px;
  height: 2px;
  display: block;
  background: #dddddd;
  content: '';
}
#cssmenu > ul > li.has-sub > a:before {
  position: absolute;
  top: 19px;
  right: 14px;
  display: block;
  width: 2px;
  height: 8px;
  background: #dddddd;
  content: '';
  -webkit-transition: all .25s ease;
  -moz-transition: all .25s ease;
  -ms-transition: all .25s ease;
  -o-transition: all .25s ease;
  transition: all .25s ease;
}
#cssmenu > ul > li.has-sub:hover > a:before {
  top: 23px;
  height: 0;
}
#cssmenu ul ul {
  position: absolute;
  left: -9999px;
}
#cssmenu.align-right ul ul {
  text-align: right;
}
#cssmenu ul ul li {
  height: 0;
  -webkit-transition: all .25s ease;
  -moz-transition: all .25s ease;
  -ms-transition: all .25s ease;
  -o-transition: all .25s ease;
  transition: all .25s ease;
}
#cssmenu li:hover > ul {
  left: auto;
}
#cssmenu.align-right li:hover > ul {
  left: auto;
  right: 0;
}
#cssmenu li:hover > ul > li {
  height: 35px;
}
#cssmenu ul ul ul {
  margin-left: 100%;
  top: 0;
}
#cssmenu.align-right ul ul ul {
  margin-left: 0;
  margin-right: 100%;
}
#cssmenu ul ul li a {
  border-bottom: 1px solid rgba(150, 150, 150, 0.15);
  padding: 11px 15px;
  width: 170px;
  font-size: 12px;
  text-decoration: none;
  color: #dddddd;
  font-weight: 400;
  background: #2d5c88;
}
#cssmenu ul ul li:last-child > a,
#cssmenu ul ul li.last-item > a {
  border-bottom: 0;
}
#cssmenu ul ul li:hover > a,
#cssmenu ul ul li a:hover {
  color: #ffffff;
}
#cssmenu ul ul li.has-sub > a:after {
  position: absolute;
  top: 16px;
  right: 11px;
  width: 8px;
  height: 2px;
  display: block;
  background: #dddddd;
  content: '';
}
#cssmenu.align-right ul ul li.has-sub > a:after {
  right: auto;
  left: 11px;
}
#cssmenu ul ul li.has-sub > a:before {
  position: absolute;
  top: 13px;
  right: 14px;
  display: block;
  width: 2px;
  height: 8px;
  background: #dddddd;
  content: '';
  -webkit-transition: all .25s ease;
  -moz-transition: all .25s ease;
  -ms-transition: all .25s ease;
  -o-transition: all .25s ease;
  transition: all .25s ease;
}
#cssmenu.align-right ul ul li.has-sub > a:before {
  right: auto;
  left: 14px;
}
#cssmenu ul ul > li.has-sub:hover > a:before {
  top: 17px;
  height: 0;
}
#cssmenu.small-screen {
  width: 100%;
}
#cssmenu.small-screen ul {
  width: 100%;
  display: none;
}
#cssmenu.small-screen.align-center > ul {
  text-align: left;
}
#cssmenu.small-screen ul li {
  width: 100%;
  border-top: 1px solid rgba(120, 120, 120, 0.2);
}
#cssmenu.small-screen ul ul li,
#cssmenu.small-screen li:hover > ul > li {
  height: auto;
}
#cssmenu.small-screen ul li a,
#cssmenu.small-screen ul ul li a {
  width: 100%;
  border-bottom: 0;
}
#cssmenu.small-screen > ul > li {
  float: none;
}
#cssmenu.small-screen ul ul li a {
  padding-left: 25px;
}
#cssmenu.small-screen ul ul ul li a {
  padding-left: 35px;
}
#cssmenu.small-screen ul ul li a {
  color: #dddddd;
  background: none;
}
#cssmenu.small-screen ul ul li:hover > a,
#cssmenu.small-screen ul ul li.active > a {
  color: #ffffff;
}
#cssmenu.small-screen ul ul,
#cssmenu.small-screen ul ul ul,
#cssmenu.small-screen.align-right ul ul {
  position: relative;
  left: 0;
  width: 100%;
  margin: 0;
  text-align: left;
}
#cssmenu.small-screen > ul > li.has-sub > a:after,
#cssmenu.small-screen > ul > li.has-sub > a:before,
#cssmenu.small-screen ul ul > li.has-sub > a:after,
#cssmenu.small-screen ul ul > li.has-sub > a:before {
  display: none;
}
#cssmenu.small-screen #menu-button {
  display: block;
  padding: 17px;
  color: #dddddd;
  cursor: pointer;
  font-size: 12px;
  text-transform: uppercase;
  font-weight: 700;
}
#cssmenu.small-screen #menu-button:after {
  position: absolute;
  top: 22px;
  right: 17px;
  display: block;
  height: 4px;
  width: 20px;
  border-top: 2px solid #dddddd;
  border-bottom: 2px solid #dddddd;
  content: '';
  box-sizing: content-box;
}
#cssmenu.small-screen #menu-button:before {
  position: absolute;
  top: 16px;
  right: 17px;
  display: block;
  height: 2px;
  width: 20px;
  background: #dddddd;
  content: '';
  box-sizing: content-box;
}
#cssmenu.small-screen #menu-button.menu-opened:after {
  top: 23px;
  border: 0;
  height: 2px;
  width: 15px;
  background: #ffffff;
  -webkit-transform: rotate(45deg);
  -moz-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  -o-transform: rotate(45deg);
  transform: rotate(45deg);
}
#cssmenu.small-screen #menu-button.menu-opened:before {
  top: 23px;
  background: #ffffff;
  width: 15px;
  -webkit-transform: rotate(-45deg);
  -moz-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  -o-transform: rotate(-45deg);
  transform: rotate(-45deg);
}
#cssmenu.small-screen .submenu-button {
  position: absolute;
  z-index: 99;
  right: 0;
  top: 0;
  display: block;
  border-left: 1px solid rgba(120, 120, 120, 0.2);
  height: 46px;
  width: 46px;
  cursor: pointer;
}
#cssmenu.small-screen .submenu-button.submenu-opened {
  background: #274f75;
}
#cssmenu.small-screen ul ul .submenu-button {
  height: 34px;
  width: 34px;
}
#cssmenu.small-screen .submenu-button:after {
  position: absolute;
  top: 22px;
  right: 19px;
  width: 8px;
  height: 2px;
  display: block;
  background: #dddddd;
  content: '';
}
#cssmenu.small-screen ul ul .submenu-button:after {
  top: 15px;
  right: 13px;
}
#cssmenu.small-screen .submenu-button.submenu-opened:after {
  background: #ffffff;
}
#cssmenu.small-screen .submenu-button:before {
  position: absolute;
  top: 19px;
  right: 22px;
  display: block;
  width: 2px;
  height: 8px;
  background: #dddddd;
  content: '';
}
#cssmenu.small-screen ul ul .submenu-button:before {
  top: 12px;
  right: 16px;
}
#cssmenu.small-screen .submenu-button.submenu-opened:before {
  display: none;
}
#cssmenu.small-screen.select-list {
  padding: 5px;
}
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<meta charset="UTF-8">
<title>Title</title>

 Home

 Menus

Menu 1

Menu 1.1

Menu 1.1.1

Menu 1.1.2

Menu 1.2

Menu 1.3

Menu 2

Menu 2.1

Menu 2.2

Menu 2.3

Menu 3

Menu 3.1

Menu 3.2

Menu 3.3

Menu 3.4

Menu 3.5

 Settings

Settings 1

Settings 1.1

Settings 1.2

Settings 1.3

Settings 1.4

Settings 2

Settings 2.1

Settings 2.2

Settings 3

Settings 3.1

Settings 3.2

Settings 4

Settings 4.1

Settings 4.2

Settings 4.3

Settings 4.4

 Contact


text:
Q: Can CDI @Producer method take custom parameters? I think i understood how CDI works and in order to dive deep in it, i would like to try  using it with something real world example. I am stuck with one thing where i need your  help to make me understand. I would really appreciate your help in this regard.
I have my own workflow framework developed using Java reflection API and XML  configurations where based on specific type of "source" and "eventName" i load appropriate  Module class and invoke "process" method on that. Everything is working fine in our project.
I got excited with CDI feature and wanted to give it try with workflow framework where i am planning inject Module class instead of loading them using Reflection etc...
Just to give you an idea, I will try to keep things simple here.
"Message.java" is a kind of Transfer Object which carries "Source" and "eventName", so that we can load module appropriately.
public class Message{
private String source;
private String eventName;
}

Module configurations are as below
<modules>
<module>
    <source>A</source>
    <eventName>validate</eventName>
    <moduleClass>ValidatorModule</moduleClass>
</module>
<module>
    <source>B</source>
    <eventName>generate</eventName>
    <moduleClass>GeneratorModule</moduleClass>
</module>
</modules>

ModuleLoader.java
public class ModuleLoader {
public void loadAndProcess(Message message){
    String source=message.getSource();
    String eventName=message.getEventName();

    //Load Module based on above values.

}
}

Question
Now , if i want to implement same via CDI to inject me a Module (in ModuleLoader class), I can write Factory class with @Produce method , which can do that. BUT my question is,
a) how can pass Message Object to @Produce method to do lookup based on eventName and source ?
Can you please provide me suggestions ?
Thanks in advance.

A: This one is a little tricky because CDI doesn't work the same way as your custom solution (if I understand it correctly). CDI must have all the list of dependencies and resolutions for those dependencies at boot time, where your solution sounds like it finds everything at runtime where things may change. That being said there are a couple of things you could try.
You could try injecting an InjectionPoint as a parameter to a producer method and returning the correct object, or creating the correct type.
There's also creating your own extension of doing this and creating dependencies and wiring them all up in the extension (take a look at ProcessInjectionTarget, ProcessAnnotatedType, and 'AfterBeanDiscovery` events. These two quickstarts may also help get some ideas going.

A: I think you may be going down the wrong path regarding a producer.  Instead it more than likely would be much better to use an observer especially based on what you've described.
I'm making the assumption that the "Message" transfer object is used abstractly like a system wide event where basically you fire the event and you would like some handler defined in your XML framework you've created to determine the correct manager for the event, instantiate it (if need be), and then call the class passing it the event.

@ApplicationScoped
public class MyMessageObserver {

    public void handleMessageEvent(@Observes Message message) {
        //Load Module based on above values and process the event
    }
}

Now let's assume you want to utilize your original interface (I'll guess it looks like):

public interface IMessageHandler {
     public void handleMessage(final Message message);
}

@ApplicationScoped
public class EventMessageHandler implements IMessageHandler {

    @Inject
    private Event<Message> messageEvent;

    public void handleMessage(Message message) {
        messageEvent.fire(message);
    }
}

Then in any legacy class you want to use it:
@Inject
IMessageHandler handler;
This will allow you to do everything you've described.

A: May be you need somthing like that:

*

*You need the qualifier. Annotation like @Module, which will take two paramters source and eventName; They should be non qualifier values. See docs.

*Second you need a producer:
@Produces
@Module
public Module makeAmodule(InjectionPoint ip) {
   // load the module, take source and eventName from ip
}

*Inject at proper place like that:
@Inject
@Module(source="A", eventName="validate")
Module modulA;

There is only one issue with that solution, those modules must be dependent scope, otherwise system will inject same module regardles of source and eventName.
If you want to use scopes, then you need make source and eventName qualified parameters and:

*

*make an extension for CDI, register programmatically producers

*or make producer method for each and every possible combinations of source and eventName (I do not think it is nice)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Cloud PHP Natural Language find date within sentence I am using the Google Cloud PHP Natural Language library, but I am struggling to extract the date from a sentence. The date would be in various formats e.g.

*

*Tomorrow at 9am

*Monday 23rd of July

*01-01-2018

*24-01-2018

*01-24-2018 (if you're not British)
I can get this working with Dialofglow, so it knows when an entity is a date and/or datetime, but for some reason with this library it cannot figure out if something is a date and/or date time
Any help would be much appreciated

A: You can get dates out from text on Dialogflow because this is a Natural Language Understanding service, while Cloud NL API is only a Natural Language Processing service.
This means that on Cloud NL API you can only do some types of analyses, such as Syntax Analysis, Entity Analysis, Sentiment Analysis, Entity Sentiment Analysis and Content Classification.
You may say: "Wait, then why a date is not classified as an entity?" and the answer is that it could, but it's not a feature yet released on this product. You may consider to request this feature on GCP's Issue Tracker.


text:
Q: About moderncv footer Is there any way I can turn off the footer from appearing in all but the last page of the CV? (and once again in the cover letter). Is a nice idea that even with just the first page they could call you, but I need the space. I've already modified the template in order to do so, but I wanna try to keep my cv as vanilla as possible.
\documentclass[11pt,letterpaper,sans]{moderncv}

% moderncv themes
\moderncvstyle{casual}
\moderncvcolor{blue}
\usepackage[scale=0.75]{geometry}

% personal data
\name{John}{Doe}
\phone[mobile]{+1~(234)~567~890}

% content

\begin{document}
\makecvtitle

\section{Education}
\cventry{1998-2007}{Degree}{Institution}{City}{\textit{Grade}}{Description}

\pagebreak % just to simulate a lenghty CV for this MWE

\section{Computer skills}
Second page

\end{document}

A: To remove extra white space from footer you can also use
\usepackage[scale=0.75, top=1cm, bottom=1cm]{geometry}

Add/Edit the above code at the beginning of your Latex file. Setting "bottom" length is doing the wonders over here.
After adding this your code should look something like this
\documentclass[11pt,a4paper,sans]{moderncv}

% modern themes
\moderncvstyle{banking}
\moderncvcolor{black}
%\renewcommand{\familydefault}{\sfdefault}
\nopagenumbers{}

% character encoding
\usepackage[utf8]{inputenc}
%\usepackage{CJKutf8}

% adjust the page margins
\usepackage[scale=0.75, top=1cm, bottom=1cm]{geometry}
\setlength{\hintscolumnwidth}{3cm}
\setlength{\makecvtitlenamewidth}{10cm}

\usepackage{import}

A: If I understand correctly, you want the footer only in the last page.
This can be achieved in the following way:

*

*Put \pagestyle{empty} just after \makecvtitle to remove the footer from all pages.

*Put \thispagestyle{plain} just before \end{document}. This ensures that the last page has the footer (note that moderncv redefines and uses the plain style).

MWE
\documentclass[11pt,letterpaper,sans]{moderncv}

% moderncv themes
\moderncvstyle{casual}
\moderncvcolor{blue}
\usepackage[scale=0.75]{geometry}

% personal data
\name{John}{Doe}
\phone[mobile]{+1~(234)~567~890}

% content

\begin{document}
\makecvtitle
\pagestyle{empty}

\section{Education}
\cventry{1998-2007}{Degree}{Institution}{City}{\textit{Grade}}{Description}

\pagebreak % just to simulate a lenghty CV for this MWE

\section{Computer skills}
Second page

\thispagestyle{plain}
\end{document}

Output:


text:
Q: Passing of function argument through ng-change not working I have an array of objects that each have a name and url property. I am using ng-options to display the name property of each object in a select list.
I am then using ng-change to invoke a function with the url of the selected object as the function argument. When executing this I am not getting any errors, but when console logging the passed argument in the function after invocation, it returns undefined. So something with passing the url as argument is not working. It would be great if someone could point me into the right direction.
Here comes the html:
<div ng-controller="TaskChartCtrl">
  <select ng-model="selectedP" ng-options="project as project.name for project in projectList" ng-change="populateGraphs(project.url)">
    <option value="">Select A Project</option>
  </select>
</div>

This is the controller code:
mod.controller("TaskChartCtrl", ["$scope", "$http", function ($scope, $http) {

    $scope.projectList = [];

    $http.get('https://api.freeagent.com/v2/projects',     config).then(function(response) {
        $scope.projectList = response.data.projects;
    });

    $scope.populateGraphs = function(projectUrl) {
        console.log(projectUrl);
        $scope.selectedP = projectUrl;
        //REST OF FUNCTION CODE USING $scope.selectedP
    }

Sample of projectList after get has returned:
$scope.projectList = [{
    'name':'projectName',
    'url':'projectUrl'
}, {
    'name':'projectName2',
    'url':'projectUrl2'
}, {
    ...
}]

Any help would be appreciated.

A: Try:
ng-change="populateGraphs(selectedP.url)"

The model of the select is selectedP, so you want to get the selected value from there.


text:
Q: Error during trigger execution - ORA-06512 - ORA-04088 I've these tables
CELL(CellId, x0, y0, x1, y1, CurrentPhone#, MaxCalls)
TELEPHONE(PhoneNo, x, y, PhoneState)
STATE_CHANGE(ChangeId, TimeStamp, PhoneNo, x, y, ChangeType)
And I've to create this trigger (the trigger is mandatory)
Changing the maximum number of active calls: The maximum number of active calls related to a single cell may be reduced by the cellular phone network for managing issues (decrease of the MaxCalls value in the CELL table). The update on the MaxCalls attribute for a single cell could cause an inconsistent situation in which the MaxCalls value in the CELL table becomes smaller than the number of currently Active phones (PhoneState='Active') in the considered cell. If so, the corresponding MaxCalls attribute needs to be updated with the number of currently Active phones (PhoneState='Active') in the considered cell
I wrote this trigger
create or replace trigger CELL_T1
AFTER UPDATE OF MAXCALLS ON CELL
BEGIN
UPDATE CELL E1
SET E1.MAXCALLS=(
    SELECT COO
    FROM (SELECT E2.CELLID, COO
          FROM CELL E2, (
             SELECT CELLID, COUNT(*) COO
             FROM CELL C2, TELEPHONE
             WHERE PhoneState='Active' AND x<x1 AND x>=x0 AND y<y1 AND y>=y0
             GROUP BY C2.CellId
             )TW
         WHERE E2.CELLID=TW.CELLID AND COO>E2.MAXCALLS
         )
 )
WHERE  E1.CELLID IN (
SELECT C1.CELLID
FROM CELL C1, (
            SELECT CELLID, COUNT(*) COO
            FROM CELL C3, TELEPHONE
            WHERE PhoneState='Active' AND x<x1 AND x>=x0 AND y<y1 AND y>=y0
            GROUP BY C3.CellId
            )TW1
WHERE C1.CELLID=TW1.CELLID AND COO>C1.MAXCALLS and e1.cellid=tw1.cellid
         );
END;

The trigger compiled without a problem; then I wrote the update statement:
UPDATE CELL SET MAXCALLS=MAXCALLS-2;

but I got these errors:
ORA-06512: at "MATTEO.CELL_T1", line 2
ORA-04088: error during execution of trigger 'MATTEO.CELL_T1'
ORA-06512: at "MATTEO.CELL_T1", line 2
ORA-04088: error during execution of trigger 'MATTEO.CELL_T1'
ORA-06512: at "MATTEO.CELL_T1", line 2
ORA-04088: error during execution of trigger 'MATTEO.CELL_T1'
ORA-06512: at "MATTEO.CELL_T1", line 2
ORA-04088: error during execution of trigger 'MATTEO.CELL_T1'
ORA-06512: at "MATTEO.CELL_T1", line 2
ORA-04088: error during execution of trigger 'MATTEO.CELL_T1'
ORA-0

*

*UPDATE CELL

*SET MaxCalls = MaxCalls-2;

I can't find anything wrong in my trigger; what's going wrong?

A: The problem is most likely that you're doing a recursive update here. When you execute your UPDATE your trigger does another UPDATE, which fires the trigger which does another UPDATE in a never ending cycle. Until, that is, Oracle gets bored and raises all those exceptions.
In this situation there's really only two ways out.

*

*Don't UPDATE the table and use an INSTEAD OF DML trigger on a view (or something) so that the trigger only fires once.

*Remove all of this logic into a stored procedure and don't use a trigger at all.

A: While I know that the reason for this question (your university assignment) is not relevant anymore. Someone else might still have some similar problem.

*

*If you need consistency checks in triggers do them BEFORE the update, not afterwards.

*Only check the rows actually modified by your statement.

*For this kind of operation, use a ROW trigger, not a STATEMENT trigger

*Make use of the ":OLD" and ":NEW" datasets instead of querying the table

So do something like this (NOT tested in a database, only written on the fly)
CREATE OR REPLACE TRIGGER cell_t1
BEFORE UPDATE OF maxcalls ON cell
FOR EACH ROW
DECLARE
  v_active_cnt      NUMBER(20);
BEGIN
  SELECT COUNT(*)
  INTO v_active_cnt
  FROM telephone
  WHERE phonestate='Active'
    AND x<:NEW.x1
    AND x>=:NEW.x0
    AND y<:NEW.y1
    AND y>=:NEW.y0;

  IF ( :NEW.maxcalls < v_active_cnt )
  THEN
    :NEW.maxcalls := v_active_cnt
  END;
END;

What this does is
 - Query the telephone table for the number of active phones in the cell identified by the currently modified row (:NEW dataset)
 - Check if the modified maxcalls value is bigger than this number and if so modify the new maxcalls value accordingly
This, by the way, is exactly what these kind of triggers are for.


text:
Q: Lost 12 hours of progress; did I permanently kill the woman who Channels Blood Echoes into stat upgrades? I was reading about NPC's that you can permanently kill - some you want to, some you might not want to. Included on that list was the woman in the Hunter's Dream.
Me and a friend have been playing together; and with the controller on its own on the sofa, the dog knocked it and hit the trigger and killed the Channel Blood Echoes woman :|
I didn't know whether she'd be dead forever - our current stats therefore locked in - so I pulled the power out of the PS4.
When I loaded the game back up, it said Save data corrupted and the Continue option had gone, leaving only New game.
Checking the PS+ Online Storage, I found a saved game from a few days ago, but I've now lost 12 hours of progress.... lol!
I'll replay it all, but I'm left wondering whether I pulled the power cord in vain, or not? :P

A: Your source of information is incorrect she can be killed but she ressurects when you reenter the Hunter's Dream.
So to answer your question, yes you pulled the plug in vain as currently there's no known way of permanently killing the doll.


text:
Q: Use python def function to append for a list There're a few categorical features in my dataset. I want to know how many unique numbers of each categorical feature coz I won't convert those with large unique numbers.
Instead of using df['column name'].nunique() to each feature one at a time, I want to get all numbers at once. Below, I'm trying to make a list of unique numbers per categorical column by defining a function but only get an empty list as result. I hope someone can figure out why my code doesn't work.
 #make a list of all categorical features

 cat_feats=['hotel','arrival_date_month','assigned_room_type','customer_type','deposit_type','distribution_channel','market_segment','meal','reserved_room_type',
 'country','reservation_status','reservation_status_date']

# define a function
 n_unique = []
def function(cat_feats):
    for x in cat_feats:
        n = hotel['x'].nunique()
        n_unique.append(n)
    return n_unique

A: Instead of creating list of all categorical  and then using for loop and appending number of unique value to a new list
Just use this:-
n_unique=hotel.nunique().to_list()


text:
Q: How to handle events from Android power button I want to handle the button on the edge of the upper right side of the device. The one that turns the screen on and off.
What is the name of that button and how do I handle events from it?


text:
Q: Python 2.7- Replace a string "}," with another "}" followed by a newline I have a text file with contents such that there are no line breaks. Its a file of records and I need to replace the string "},"
I need to remove the comma without touching the other commas in the file and replace the comma which follows the closed curly brace with a new line while leaving the curly brace as is. The code below does not work
textToSearch = "},"
for line in fileinput.input( fileToSearch ):
    if textToSearch in line :

    tempFile.write( line.replace( textToSearch, "}\n" ) )
tempFile.close()

A: Let me see if I got your question.
You want to find only '},' a exact match right? and replace to '\n'
I think this will gonna work for you:
textToSearch = "},"
for line in fileinput.input( fileToSearch ):
    if textToSearch in line:
        with open("tempFile.txt", "a") as f:
            f.write(line.replace(textToSearch, "}\n")
            f.close()

I have tested and its fine for me.
Let me know if you have any other concern


text:
Q: Is natural filtration of a left-continuous modification of a Poisson process is right-continuous? I know that a natural filtration of a Poisson process is right-continuous.
But does the same hold for a left-continuous modification of that Poisson process (denote $N'$).
My guess, it does not hold. Since at the time of the first jump (it is totally inaccessible s.t.) $t_0$ we have $N'_{t_0}=0,$ so $\mathcal{F}_{t_0}=\{\emptyset, \Omega\}$, but strictly immediately after $t_0<s$ we have $\mathcal{F}_{s}=\sigma(N'_u,u\le s ) \ne \mathcal{F}_{t_0}.$


text:
Q: What's a good way to save all data related to a training run in Keras? I know how to do a few things already:

*

*Summarise a model with model.summary(). But this actually doesn't print everything about the model, just the coarse details.

*Save model with model.save() and load model with keras.models.load_model()

*Get weights with model.get_weights()

*Get the training history from model.fit()
But none of these seem to give me a catch all solution for saving everything from end to end so that I can 100% reproduce a model architecture, training setup, and results.
Any help filling in the gaps would be appreciated.

A: model.to_json() can be used to convert model config into json format and save it as a json.
You can recreate the model from json using model_from_json found in keras.models
Weights can be saved separately using model.save_weights.
Useful in checkpointing your model. Note that model.save saves both of these together. Saving only the weights and loading them back useful when you need to work with the variables used in defining the model. In that case create the model using the code and do model.load_weights.


text:
Q: Is Fourier transform always unique? I am a physicist, so forgive my ignorance... I would like to know if FT mapping is always unique in a sense discussed here. Correct me if I am wrong, but it looks like FT is uniques up to a phase and maybe a constant factor, correct? I would really appreciate if you share the info on the cases when FT is NOT unique, references etc.
Thanks in advance!


text:
Q: unexpected token "export" in webpack build The error I am getting is that webpack is unable to recognize export as a keyword. I have updated my .babelrc and install the necessary dependencies. I am sure it has something to do with it not understanding es6, but I cannot find a solution that fixes my problems. Below are the necessary file to see my dependencies, error, and important files.

ERROR in ./index.scss Module build failed (from
  ./node_modules/extract-loader/lib/extractLoader.js):
  /Users/rahmijamalpruitt/Documents/LetsGraduate/BigCo/CooleyProduct/White-Blob.png:1
  export default webpack_public_path +
  "5d40bf92e9838f27f887c783f1001e8f.png"; ^^^^^^ SyntaxError: Unexpected
  token 'export'

directory
CornellTech.png
buildings.jpeg
index.scss
Orange-Blob.png
index.css
node_modules
RahmiHeadShot.jpg
index.css.map
package-lock.json
SuitGuy.png
index.html
package.json
White-Blob.png
index.js
webpack.config.js

webpack.config.js
const autoprefixer = require("autoprefixer");

module.exports = {
  entry: ["./index.scss", "./index.js"],
  output: {
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "bundle.css"
            }
          },
          { loader: "extract-loader" },
          { loader: "css-loader" },
          {
            loader: "postcss-loader",
            options: {
              plugins: () => [autoprefixer()]
            }
          },
          {
            loader: "sass-loader",
            options: {
              sassOptions: {
                includePaths: ["./node_modules"]
              }
            }
          }
        ]
      },
      {
        test: /\.js$/,
        loader: "babel-loader",
        query: {
          presets: ["@babel/preset-env"]
        }
      },
      {
        test: /\.(gif|png|jpe?g|svg)$/i,
        use: [
          "file-loader",
          {
            loader: "image-webpack-loader",
            options: {
              bypassOnDebug: true, // webpack@1.x
              disable: true // webpack@2.x and newer
            }
          }
        ]
      }
    ]
  }
};

index.html
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=<>, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link rel="stylesheet" href="bundle.css" />

 LOGO

 about us

            <button class="sign-up-button mdc-button">sign up</button>

            <button class="login-button mdc-button">login</button>

The best tool for the best firms

A new solution for the firm pushing the future fowards

          ×

Some text in the Modal..

          Let this be the year of producivity

 LOGO

The Team

Rahmi Pruitt

                Software Engineer / Designer

                Passionate about fullstack development. Resume can be seen below

Rahmi Pruitt

                Software Engineer / Designer

                Passionate about fullstack development. Resume can be seen below

Rahmi Pruitt

                Software Engineer / Designer

                Passionate about fullstack development. Resume can be seen below

Rahmi Pruitt

                Software Engineer / Designer

                Passionate about fullstack development. Resume can be seen below

Rahmi Pruitt

                Software Engineer / Designer

                Passionate about fullstack development. Resume can be seen below

.babelrc
{
  "presets": ["@babel/preset-env"]
}

package.json
{
  "name": "cooleyproduct",
  "version": "1.0.0",
  "description": "",
  "main": "homepage.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.7.7",
    "@babel/core": "^7.7.7",
    "@babel/preset-env": "^7.7.7",
    "autoprefixer": "^9.7.3",
    "babel-loader": "^8.0.6",
    "css-loader": "^3.4.0",
    "extract-loader": "^3.1.0",
    "file-loader": "^5.0.2",
    "image-webpack-loader": "^6.0.0",
    "node-sass": "^4.13.0",
    "postcss-loader": "^3.0.0",
    "sass-loader": "^8.0.0",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.1"
  },
  "dependencies": {
    "@material/button": "^4.0.0",
    "@material/ripple": "^4.0.0"
  }
}

A: I have found deleting the extract-loader plugin from webpack.config.js was sufficient to getting my code to run. I think it has something do with the extract-loader plugin is not able to work with scss. The docs specifically say it is built for html and css. If anyone is still interested in an extract-loader plugin, it can be found here

A: Solved the same problem setting esModule: false option with file-loader


text:
Q: Capturing the same variable in one of multiple closures I have two closures that capture the same Vec and I don't know how to write this in idiomatic Rust:
use std::error;

fn get_token -> Box<Vec<u8>>() {...}
fn do_stuff(file: &str) -> std::io::Result<i32> {...}
fn do_other_stuff(a: &str, a: &str) -> std::io::Result<i32> {...}

enum MyError {
    IoError { token: Vec<u8>, reason: String ),
}

fn consumer() -> Result<MyError, ()> {
    let token = get_token();

    try!(do_stuff("a")
        .map_err(|e| MyError::IoError { token: token, reason: "foo".to_str() }));
    try!(do_other_stuff("b", "c")
        .map_err(|e| MyError::IoError { token: token, reason: "bar".to_str() }));
}

I could replace the map_err calls with match expressions but I really am stumped by this: how do I pass a Vec to multiple closures?

A: First of all: Please make sure to provide an MCVE in the future, it's not fun to have to fix syntax errors before being able to reproduce your problem: http://is.gd/tXr7WK
Rust does not know that the only way the second closure can run, is if the first closure did not run and will never run. You can either wait for the let/else RFC to be accepted, implemented and stabilized, or you can create your error in steps, first create an inner closure that does all the operations for that one error kind without using up the token, then run the closure, then map the error to your custom error type.
|| -> _ {
    try!(do_stuff("a").map_err(|e| ("foo".to_owned(), e)));
    try!(do_other_stuff("b","c").map_err(|e| ("bar".to_owned(), e)));
    Ok(())
} ().map_err(|(reason, e)| MyError::IoError{ token: token, reason: reason })

There's something weird going on where the closure requires us to specify that it returns something with -> _, but I'm not sure what it is.

A: Much more straightforward is to just not use try! or closures:
if let Err(e) = do_stuff("a") {
    return Err(MyError::IoError{token: token, reason: "foo".to_owned()});
}
if let Err(e) = do_other_stuff("b", "c") {
    return Err(MyError::IoError{token: token, reason: "bar".to_owned()});
}

This lets Rust perform straightforward analysis like you want it to, and is much more readable than dancing through hoops.

A: You can use and_then() combinator to avoid additional closure:
try!(do_stuff("a").map_err(|_| "foo" )
        .and_then(|_|
            do_other_stuff("b","c").map_err(|_| "bar")
        )
        .map_err(|e| MyError::IoError{token:token,reason:e.into()})
);


text:
Q: Prevent MS SQL 2005 master DB from being corrupted I am trying to resolve what cause the following corruption.

2011-06-29 10:47:26.42 spid5s      Starting up database 'master'.
2011-06-29 10:47:26.53 spid5s      Error: 9003, Severity: 20, State: 1.
2011-06-29 10:47:26.53 spid5s      The log scan number (216:72:1) passed to log scan in database 'master' is not valid. This error may indicate data corruption or that the log file (.ldf) does not match the data file (.mdf). If this error occurred during replication, re-create the publication. Otherwise, restore from backup if the problem results in a failure during startup.
2011-06-29 10:47:26.53 spid5s Cannot recover the master database. SQL Server is unable to run. Restore master from a full backup, repair it, or rebuild it. For more information about how to rebuild the master database, see SQL Server Books Online.

I can find plenty of threads and information on how to recover databases when master db is corrupt. I can recover them succussfully.
HOWEVER, this is not very satisfactory for customers to have perform these operations. I have been able to examine event log files of when the corruption occurs. From there I can see server working fine then computer is shutdown, few hours later the computer is switched on and master db is corrupted.
Any help greatly appreciated

A: One of:

*

*disk corruption. Run chkdsk etc with SQL Server shutdonw

*someone has been playing with the MDF/LDF files

The master DB starts once when SQL Server starts up: so why did this happen? Patch? BSOD? PEBKAC? Note: the MDF/LDF files won't be locked when SQL is shutdown...
I can't recall a corrupt master, ever, unless it's one of the 3 reasons above


text:
Q: Linear Programming Problem about optimal solution
Let $X_1$ and $X_2$ are the optimum solutions of LPP, then
(a) $X = λX_1+(1- λ)X_2$, $λ \in \Bbb R$ is also an optimal solution
(b) $X = λX_1+(1-λ)X_2$, $0 \leq λ \leq 1$ gives an optimal solution
(c) $X = λX_1+(1+λ)X_2$, $0 \leq λ \leq 1$ gives an optimal solution
(d) $X = λX_1+(1+λ)X_2$, $λ \in \Bbb R$ gives an optimal solution

Please explain (in detail) how to solve it...
Thanks in advance.

A: A set $K$ is called convex if $X_1, X_2 \in K$ and for  $0 \leq λ \leq 1 :$ $λ X_1+(1- λ )X_2 \in K$, that means that each convex combination of two points of $K$ is also a point of $K$. In other words if $X_1,X_2$ are the optimal solutions of LPP, then (b) $X = λX_1+(1-λ)X_2$, $0 \leq λ \leq 1$ gives an optimal solution. A convex combination of $x_1,x_2$ is each point $x$ of the form:$$x=\Sigma_{i=1}^{k}{λ_ix_i}$$ with $λ_i \geq 0$ and $\Sigma_{i=1}^{k}λ_i=1$


text:
Q: Parsing json data with random/unknown value data type for key How to parse json data with random/unknown value type for keys?In below json data,key data can be a json object or string depending upon response from server.
Response 1(Json object)
 {
          "responseCode": 2,
          "responseMessage": "hi",
          "data": {
            "key": "Id",
            "value": "10312412",
            "key2": "Id2",
            "key3": "Id3"
          }
    }

Response 2(String)
   {
          "responseCode": 2,
          "responseMessage": "hi",
          "data": "String here"
    }

A: The best you can do is
Object data = response.get("data");

Though, you might be able to try
boolean gotObject = true;
String dataString = null;

// Try to request a JSONObject as a String
dataString = String.valueOf(response.optJSONObject("data"));

// If there wasn't a JSONObject, then try to get a String
if (dataString.isEmpty() || dataString.equals("null")) {
    dataString = response.optString("data");
    gotObject = false;
}

Then, you can try this
if (gotObject) {
    JSONObject data = new JSONObject(dataString);
}

Realistically, you should make a more consistent server API


text:
Q: Convert the difference between two dates into an integer I have a date-frame (df) which the head looks like:
        DATE  BBG  FLAG  DATE_DIFF
0 2014-03-04    A     0        NaT
1 2014-04-04    B     1    31 days
2 2014-04-07    C     0     3 days
3 2014-04-08    D     0     1 days
4 2014-04-09    E     0     1 days

the column DATE_DIFF is the difference between the date in a row and the date in the row above.  I used the following to calculate DATE_DIFF:
df['DATE_DIFF'] = (df['DATE']-df['DATE'].shift(1))

I am looking for a way to convert the DATE_DIFF column to interger so the resulting data-frame would look like:
        DATE  BBG  FLAG  DATE_DIFF
0 2014-03-04    A     0        NaN
1 2014-04-04    B     1         31
2 2014-04-07    C     0          3
3 2014-04-08    D     0          1
4 2014-04-09    E     0          1

I have tried to use:
df['DATE_DIFF'] = (df['DATE']-df['DATE'].shift(1)).astype(int)

but that just gives me the error:
TypeError: cannot astype a timedelta from [timedelta64[ns]] to [int32]

A: Your can do the exact same thing you are currently doing just add dt.days
df['diff'] = (df['DATE']-df['DATE'].shift(1)).dt.days

    DATE    BBG FLAG    diff
0   2014-03-04  A   0   NaN
1   2014-04-04  B   1   31.0
2   2014-04-07  C   0   3.0
3   2014-04-08  D   0   1.0
4   2014-04-09  E   0   1.0

just note that the dtype will be a float not an int because the first row is NaN

A: If you have two date objects, you can just subtract them.
from datetime import date

d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print delta.days

The relevant section of the docs:
https://docs.python.org/library/datetime.html


text:
Q: How to edit drive partitions for dual booting? I need to install Ubuntu on my new laptop for some development. I want to dualboot, which I've done a few time before, however I'm having some trouble with the partitioning. There are lots of partitions on the drive, most of which I'm not sure what they do.
Here is a picture of the partitions. Could someone tell me how to edit the drive to allow me to do this?

A: here you can find some info about what the flags on the partitions mean. Adding to that, WinRE is the Windows Recovery Environment, and it is usual on laptop to come with a partition containing some propretary software (like the LENOVO in your case).
If you're not sure, don't remove the other partitions, just reduce the main one (sda5 in your case, judging by the size). To do this you can either use the embedded disk partition tool from windows (see for example this guide), or gparted from ubuntu (there are a lot of guides about this process, see for example WindowsDualBoot or HowToResizeWindowsPartitions,


text:
Q: How to check if consecutive digits in a number are even or odd? I am doing some exercises and learning Python. I need to be able to check for an input number whether its consecutive digits are even or odd. So, if the first number is odd, the next should be even and so on in order for the terms to comply. I have the following code:
def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    cifre = cifre[::-1]
    ind = cifre[0]
    for broj in cifre:
        if cifre[0] % 2 == 0:
            # for br in range(len(cifre)):
            if cifre[ind + 1] % 2 != 0:
                ind = cifre[ind+1]

n = int(input("Unesite broj n: "))
print(par_nepar(n))

As you can see, I am struggling with index looping. I took the input number and transformed it into a list. Created a variable for index[0] and don't really know how to loop through consecutive indexes. I know I might be able to use zip or enumerate but I think that is not a truly pythonic solution here and probably there is a simpler way to loop over consecutive list numbers and compare them to index[-1].
Input examples:
>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False

A: try this:
def par_nepar(n):

    split = [int(i) for i in str(n)].

    for i in range(1,len(split)):

        if (split[i] % 2 == 0) ^ (split[i-1] % 2 == 1):
            return False

    return True

Works as:

*

*Converts integer to list: 1234 -> [1,2,3,4]

*iterate the elements (excluding the first)

*XOR condition that takes False if two consecutive digits are even or odd.

Tests:
>>> print(par_nepar(2749))
True

>>> print(par_nepar(2744))
False

A: mine solution is very simple. just change a bit your code and avoiding using indexes just looping through all digits in cifre and handling boolean flags:
def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    even = True
    odd = True
    output = "The number complies to the needed terms"

    for broj in cifre:
        if broj % 2 == 0 and odd:
            even = True
            odd = False
        elif broj % 2 != 0 and even:
            odd = True
            even = False
        else:
            return "The number doesn't comply to the needed terms."
    return output
n = int(input("Unesite broj n: "))
print(par_nepar(n))

outputs:
Unesite broj n: 33890
The number doesn't comply to the needed terms.

Unesite broj n: 4963850
The number complies to the needed terms

A: I think instead of getting an integer as input you can get a string and convert it to a list of integers
def par_nepar(n):
    s,h=0,0
    for i in range(len(n)-1):
        if n[i]%2==0 and n[i+1]%2!=0:
            s+=1
        elif n[i]%2!=0 and n[i+1]%2==0:
            h+=1
    if s==len(n)//2 or h==len(n)//2:
        print("The number complies to the needed terms")
    else:
        print("The number does not complies to the needed terms")

# list of digits in the provided input
n = list(map(lambda x: int(x),list(input("Unesite broj n: "))))
par_nepar(n)

A: def par_nepar(n):
    cifre = list(str(n))
    flg = False
    if int(cifre[0]) % 2 == 0:
        flg = True
    for d in cifre[1:]:
        _flg = False
        if int(d) % 2 == 0:
            _flg = True
        if not flg^_flg:
            print("The number does not complies to the needed terms")
            return
        flg = _flg
    print("The number complies to the needed terms")
    return

A: Maybe you would also like this one liner.
In a single loop, we find if the number mod 2 is the same as the (first number + the index) mod 2.
This works for you alternating use case.
par_nepar = lambda x: all([(int(k) % 2) == ((i + int(str(x)[0])) % 2) for (i, k) in enumerate(str(x))])

print(par_nepar(2749))
print(par_nepar(2744))

# Output
True
False

Or if you want with the strings you said, slightly bigger
par_nepar = lambda x: 'The number complies to the needed terms. ' if all(
    [(int(k) % 2) == ((i + int(str(x)[0])) % 2) for (i, k) in
     enumerate(str(x))]) else "The number doesn't comply to the needed terms."

#Output
The number complies to the needed terms.
The number doesn't comply to the needed terms.


text:
Q: Move to specific position in TextFlow JavaFX I'm having a TextFlow inside a StackPane which is inside a ScrollPane. I'm adding text with different colors to this TextFlow
Text txt = new Text(msg);
txt.setFill(Paint.valueOf(color));
txtFlow.getChildren().add(txt);

I want to scroll to a some specific point in the textflow.
e.g. First text that is in blue color.
I know I can get the text and check the color. But how can I scroll down to that specific position?
Can I achieve that sort of functionality through the TextFlow?
Simply I'm trying to build up a diff view in JavaFX. And want to travel through the diffs.

A: I would take a ListView and put some stackpanes or directly the texts in it.
Text content = new Text("Custom Text");
content.setFill(Color.valueOf(yourcolor));
ListView<Text> list = new ListView<Text>();
list.add(content);

Because...
there's a void scrollTo() where you can scroll to the item directly by the Text object or to the item by the index (int).
To get a transparent background on the listview you can use:
list.setStyle("-fx-background-color: transparent;");

I hope this helped you.
I'm sorry if I missunderstood your question.
Peace

A: Use one of the free styledtext-editors - they all are using ListView or VirtualView internally. See https://github.com/TomasMikula/RichTextFX/wiki/JavaFX-Controls-for-Code-Editing for examples


text:
Q: How do I call a function that is member of a class, from another function? So I have the following:
INT CMainFrm::load(Cstring path)
{

}

extern "C"
{
   EXPORT void fileLoad(CString filePath)
   {
      CMainFrm *cmf = new CMainFrm();
      cmf->load(filePath);
   }
}

Both are located in mainfrm.cpp.
fileLoad()  is called from a dll and that works fine.
When I try to call load() from inside fileload() it gives me unhandled exception...I also tried calling it using an instance of CMainFrm but the result is the same. Any suggestion on how to do this properly?

A: You need to call the CMainFrm object that already exists. (It is created at program startup.) MFC provides a global function that you can call to get a pointer to this main window: AfxGetMainWnd(). You may cast the returned value to CMainFrm* and use it to call load.

A: You must call Create for dynamically allocated/created MFC classes (CWnd), otherwise your m_hWnd will not be valid and your window not created.
Most likely you will get a exception.


text:
Q: How Can I deploy a Multi Module Maven Project with a docletArtifact as a self referencing dependency? I have a Multi-Module Web Application project like so:
Parent

*

*Web-Base

*auth

*doc

*ADFS

*Test-Site

Test-Site uses all the other modules just fine.
doc combines JavaDocs and mounted Web Page information to build a SiteMap. Because It's parsing the JavaDocs for my SiteMap Generation
It's also a Doclet Jar, since a Doclet was the easiest way to parse and store the info for the site map.
In Test-sites pom.xml I have
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-javadoc-plugin</artifactId>
  <version>2.9</version>
  <executuions>
    <exceution>
      <id>build-siteMap-Descriptions</id>
      <phase>process-classes</phase>
      <goals>
        <goal>javadoc</goal>
      </goals>
      <configuration>
        <doclet>
          us.ak.state.revenue.cssd.utils.SiteMapDoclet
        </doclet>
        <docletPath>
          \;.;${project.build.outputDirectory};
        </docletPath>
        <docletArtifacts>
          <docletArtifact>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.6.2</version>
        </docletArtifact>
        <docletArtifact>
          <groupId>us.ak.state.revenue.cssd</groupId>
          <artifactId>doc</artifactId>
          <version>${project.version}</version>  <!-- problematic section -->
        </docletArtifact>
      </docletArtifacts>

      <bootclasspath>
         \;.;
         ${bootClassPath};
         ${env.CLASSPATH};
      </bootclasspath>

        <destDir>SiteMap</destDir>

        <author>false</author>
        <!-- don't print the packages/classes it's running on -->
        <quiet>true</quiet>
        <debug>true</debug> <!-- save options -->
        <useStandardDocletOptions>false</useStandardDocletOptions>

        <additionalparam>
          -sitemap us.ak.state.revenue.cssd.webBaseTest.Pages.SiteMap
        </additionalparam>

        <name>SiteMapDoclet</name>
        <description>Page Descriptions for SiteMap generation</description>
      </configuration>
    </execution>
  </exectuions>
</plugin>

So when I run mvn release:prepare it wants to resolve snapshot dependencies and then it errors with:
[INFO] An error has occurred in SiteMapDoclet report generation: Unable to find artifact:groupId = 'us.ak.state.revenue.cssd'
[INFO] artifactId = 'doc'
[INFO] version = '1.5.8'
[INFO]
[INFO] Unable to download the artifact from any repository

So how do I correctly reference my Doclet when I deploy my project?

A: @khmabaise is correct to reference my old Question: How can I compile and run my Custom Doclet class in my project?
Turns out the solution while slightly messy was to move doc to docletPath
<docletPath>
  \;.;${project.build.outputDirectory};
  ${project.parent.basedir}/doc/target/doc-${project.version}.jar;
  ${m2Repository}/us/ak/state/revenue/cssd/doc/${project.version}/doc-${project.version}.jar;
</docletPath>

and then in the add doc's dependencies directly to <docletArtifact>
for the record ${m2Repository} is defined in my my poms properties as
<m2Repository>${env.USERPROFILE}/.m2/repository</m2Repository>


text:
Q: Listing and hooking of functions of an app I have the following issue. I need to hook a method of an app for monitoring. The issue is that I'm not allowed to change its source code except for including a library and some sort of initialization maybe. So the only options seemed to be Frida and Xposed at first sight, which would require a rooted phone. Another no-go in my case. After a few hours of research, I found a great variant of xposed that seems to be for local apps - the whale framework ( https://github.com/asLody/whale ). It seems to be used like xposed in a similar way.
The only issue I have is that I have no clue on how to use it and the typical examples as listed in the xposed tutorial ( https://github.com/rovo89/XposedBridge/wiki/Development-tutorial ) cannot be used right away. In particular, I'm looking at "implements IXposedHookLoadPackage" and lpparam.*
Does anyone has an idea on how to use it maybe?

A: In fact, after hours of research, I was able to find a tutorial on how to use the Whale Framework. If you don't speak Chinese, use Google Translator. After performing the steps described there and based on the provided code, it works great. It let's one make use of the huge resources of Xposed modules for the own, local app to change functionality without root requirements like it is required for my monitoring purposes.
https://blog.csdn.net/tianseyiwan008/article/details/97522266
Notice: A similar way is AspectJ, but Xposed is far more straight forward in my opinion.


text:
Q: Reliable or not PDO lastInsertId() when using transactions I use PDO transaction
try {
    DB::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    DB::$db->beginTransaction();

    $db->prepare( insert query );
    $db->execute();

    $last_insert_id = $db->lastInsertId();

    ...
    ...

Multiple concurrent requests are expected on this script.
Question: is it possible that lastInsertId() return incorrect value for the user, who actually inserted the row?
(by "incorrect value" i mean:  id that is inserted by some other user).

A: You're safe.  The ID you get will be the correct one.
PDO's lastInsertId (and mysql's last_insert_id to which your PDO delegates the call in this case) gives the last autogenerated ID on a per-connection basis.
From mysql's documentation:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

Concurrent connections will not compromise the integrity of the returned id.  And as you mention in your comment, transactions have no bearing on this. Just don't forget to commit!
I'll also mention there is the unlikely possibility, if you run multiple statements on the same connection, and if your execute method throws an exception which isnt handled correctly, that lastInsertId could return the id of the last successful insert on that connection. But it can never return an ID from another user's query.


text:
Q: Frechet derivative of nonlinear functional I have the following functional
$F(E(k,t))=\int_0^{k}E(\mu,t)\mu^2d\mu\int_k^{\infty}E(p,t)^{1/2}p^{-3/2} dp $
I would like to compute  $F'(E_0(k,t))$, the Fréchet derivative of $F$ at $E_0(k,t)$.
If I call
$A(E(k,t))=A(k,t)=\int_0^{k}E(\mu,t)\mu^2d\mu $
$B(E(k,t))=B(k,t)=\int_k^{\infty}E(p,t)^{1/2}p^{-3/2}dp $
Using the product rule,I  know
$F'(E_0)=A'(E_0)B(E)+A(E)B'(E_0)$
Now using the method proposed in
this answer.
$A'=\frac{d}{ds}A(E_0+sE_1)|_{s=0}=\frac{d}{ds}\int_0^{k}(E_0+sE_1)\mu^2d\mu |_{s=0}=\int_0^{k}(E_1)\mu^2d\mu$
$B'=\frac{d}{ds}B(E_0+sE_1)|_{s=0}=\int_k^{\infty}(E_0+sE_1)^{1/2}p^{-3/2}dp |_{s=0}=\int_k^{\infty}\frac{E_1}{2}(E_0)^{-1/2}p^{-3/2}dp$
so my result is
$F'(E_0)=B(E)\int_0^{k}(E_1)\mu^2d\mu+A(E)\int_k^{\infty}\frac{E_1}{2}(E_0)^{-1/2}p^{-3/2}dp$
I know that this result is wrong because the good one is
$F'(E_0)=B(E)\int_0^{k}\frac{E_1(\mu,t)}{E_0(\mu,t)}\dot{A}(\mu,t)d\mu-\frac{1}{2}A(k,t)\int_k^{\infty}\frac{E_1(p,t)}{E_0(p,t)}\dot{B}(p,t)dp$
where point denote derivative with respect to $\mu$ for $A(\mu,t)$ and $p$ for $B(p,t)$.
But I do not know where  my mistakes are, maybe is there something liked with the chain rule that I do not consider ?.
Thanks for your help


text:
Q: XMLHttpRequest.status always returning 0 html
click me

js code
var MyObj =
{
    startup : function()
    {
        var ajax = null;
        ajax = new XMLHttpRequest();
        ajax.open('GET', 'http://www.nasa.gov', true);
        ajax.onreadystatechange = function(evt)
        {
            if(ajax.readyState == 4)
            {
                if (ajax.status == 200)
                {
                    window.dump(":)\n");
                }
                else
                {
                    window.dump(":(\n");
                }
            }
        }
        ajax.send(null);
    }
}

ajax.status always returning 0, no matter which site it is, no matter what is the actual return code. I say actual, because ajax.statusText returning correct value, eg OK or Redirecting...
ajax.readyState also returns proper values and 4 at the end.

A: You can overcome this easily in a local environment by setting up a php proxy (xampp a server and pass a querystring for the url you want to grab). Have your php proxy wget the url and echo its contents. That way your local html file (when viewed as http://localhost/your.html) can send ajax requests out of domain all day. Just don't expect the content to work as though it were local to that domain.

A: Is your site part of http://www.nasa.gov/? Otherwise, XMLHttpRequest will fail due to Same Origin Policy.
Also, if the page is served as a non-HTTP request, the status can be 0. See https://developer.mozilla.org/En/Using_XMLHttpRequest#section_3.


text:
Q: Sequence: last_value billions bigger that actual count of rows In my PostgreSQL 9.6 database, INSERT on a certain table is not possible anymore: The primary key column is an integer and the last_value of the sequence in question is 2,147,484,010 - which is too big for an integer. As a consequence, I get 'integer out of range'.
So far, so good.
The question is: How come? Why is last_value so huge?
The actual count of rows is just 112,698. The table rows are not deleted normally.
And there seems to be no general, reproducible problem. I've tried with the following: I copied that database, deleted all rows from the table in question, reset the sequence, and created entries with an (almost) 'real life query'. I could create more than 6 million rows with any problems.
I know that sequences are not designed to be gapless (e.g. on the above-mentioned test I got a last_value of 8,946,095 for 6,404,000 rows), however having a value 2 billion bigger than the row count seem pretty strange to me. Obviously, something went wrong here.
How could I debug this further?
Edit: data of the sequence is as follows:
+------------+-------------+--------------+-----------------------+-----------+-------------+---------+-----------+-----------+
| last_value | start_value | increment_by | max_value             | min_value | cache_value | log_cnt | is_cycled | is_called |
| 2147484010 | 1           | 1            | 9,22337203685478E+018 | 1         | 1           | 32      | False     | True      |
+------------+-------------+--------------+-----------------------+-----------+-------------+---------+-----------+-----------+


text:
Q: How to log the segmentation faults and run time errors which can crash the program, through a remote logging library? What is the technique to log the segmentation faults and run time errors which crash the program, through a remote logging library?
The language is C++.

A: Here is the solution for printing backtrace, when you get a segfault, as an example what you can do when such an error happens.
That leaves you a problem of logging the error to the remote library. I would suggest keeping the signal handler, as simple, as possible and logging to the local file, because you cannot assume, that previously initialized logging library works correctly, when segmentation fault occured.

A: I'd like to give some solutions:

*

*using core dump and start a daemon to monitor and collect core dumps and send to your host.

*GDB (with GdbServer), you can debug remotely and see backtrace if crashed.

A:
What is the technique to log the segmentation faults and run time errors which crash the program, through a remote logging library?

From my experience, trying to log (remotely or into file) debugging messages while program is crashing might not be very reliable, especially if APP takes system down along with it:

*

*With TCP connection you might lose last several messages while system is crashing. (TCP maintains data packet order and uses error correction, AFAIK. So if app just quits, some data can be lost before being transmitted)

*With UDP connection you might lose messages because of the nature of UDP and receive them out-of-order

*If you're writing into file, OS might discard most recent changes (buffers not flushed, journaled filesystem reverting to earlier state of the file).

*Flushing buffers after every write or sending messages via TCP/UDP might induce performance penalties for a program that produces thousands of messages per second.

So as far as I know, the good idea is to maintain in-memory plaintext log-file and write a core dump once program has crashed. This way you'll be able to find contents of log file within core dump. Also writing into in-memory log will be significantly faster than writing into file or sending messages over network. Alternatively, you could use some kind of "dual logging" - write every debug message immediately into in-memory log, and then send them asynchronously (in another thread) into log file or over the network.
Handling of exceptions:
Platform-specific. On windows platform you can use _set_se_handlers and use it to either generate backtrace or to translate platform exceptions into c++ exceptions.
On linux I think you should be able to create a handler for SIGSEGV signal.
While catching segfault sounds like a decent idea, instead of trying to handle it from within the program it makes sense to generate core dump and bail. On windows you can use MiniDumpWriteDump from within the program and on linux system can be configured to produce core dumps in shell (ulimit -c, I think?).

A: To catch the segfault signal and send a log accordingly, read this post:
Is there a point to trapping "segfault"?
If it turns out that you wont be able to send the log from a signal handler (maybe the crash occurred before the logger has been intitialized), then you may need to write the info to file and have an external entity send it remotely.
EDIT: Putting back some original info to be able to send the core file remotely too
To be able to send the core file remotely, you'll need an external entity (a different process than the one that crashed) that will "wait" for core files and send them remotely as they appear. (possibly using scp) Additionally, the crashing process could catch the segfault signal and notify the monitoring process that a crash has occurred and a core file will be available soon.


text:
Q: Image upload in firebase storage I am getting the following error when trying to upload an image in my firebase storage.
Firebase Storage: User does not have permission to access 'images/istockphoto-1071305262-612x612-removebg-preview.png'. (storage/unauthorized)
Below are my db rules:
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if
          request.time < timestamp.date(2022, 2, 9);
    }
  }
}

Below are the storage rules:
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}


text:
Q: Python Reddit API have URLs in variable but need to sort them So I'm using PRAW, a python wrapper for reddit api (http://praw.readthedocs.io/en to find out more), and I have managed to print the URL's of my latest upvoted posts.
# start subreddit instance
subreddit = reddit.subreddit('dankmemes')

print("\n -> Current Subreddit: ")
print(subreddit.display_name)
redditor2 = reddit.redditor('me')
for upvoted in reddit.redditor('Kish_v').upvoted():
    print(upvoted.url)

This outputs a long list of imgur URLs etc. However, I want to be able to download those images to a folder and then reupload them as a sort of scraper.
So I have got to the point where upvoted.url holds my URLs but would the best way to do the above be to put the links into an "array" and then download those images individually? - How would I go around doing this, sorry I am fairly new to python as I came from PHP to use this well documented API.
Thank you,
Kish

A: Check out the requests module, this SO question should get you pointed in the right direction with downloading the URLs you have on hand. I can't comment on the reuploading half.
How to download image using requests


text:
Q: Is there a way to set up a python socket so that the server only sends when the client asks for an updated value? I am trying to get a value from one python script into another.
the first script must stay running constantly, and the receiving script can't run constantly and needs to get the latest value from the first.
Right now the script does function barely. but since the receiver is running slower than the sender, a backlog forms. I also need a way to continue the second script with the previous value if there is no new data from the sender. Otherwise, the program hangs when the sender stops.
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
tabletPressure = "Value constantly updates while pen is pressed, value is between 0,4096"

while True:
    if pen_pressed:
        intValue = int(tabletPressure)
        bytesValue = (intValue).to_bytes(4, byteorder="little")
        sock.sendto(bytesValue,("0.0.0.0", 33335))

The receiving script looks like this
import socket
import time

dataBus = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
dataBus.bind(('0.0.0.0', 33335))

def modal(self, context, event):

    if event.type in {'RIGHTMOUSE', 'ESC'}:
        self.cancel(context)
        self.dataBus.close()
        return {'CANCELLED'}

    if event.type == 'MOUSEMOVE':
        data, addr = dataBus.recvfrom(4)
        print(int.from_bytes(data, byteorder="little"))

I would really appreciate any help! Thanks!

A: Set up the server to only send its message when it receives one.  Example:
server.py
from socket import *
from threading import Thread
from time import sleep

s = socket(AF_INET,SOCK_DGRAM)
s.bind(('',5000))

counter = 0

def datagram_server():
    while True:
        data,addr = s.recvfrom(4096)                # receive any message
        s.sendto(counter.to_bytes(4,'little'),addr) # respond to client address

Thread(target=datagram_server,daemon=True).start()

while True:
    sleep(.5)
    counter += 1 # constantly updating value

client.py
from socket import *
from time import sleep

s = socket(AF_INET,SOCK_DGRAM)
server = 'localhost',5000
ping = b'' # message content doesn't matter

def get_latest_counter():
    s.sendto(ping,server)      # ping server to get a response
    data,addr = s.recvfrom(4)  # get the response
    return int.from_bytes(data,'little')

while True:
    print(get_latest_counter())
    sleep(1)

Output:
5
7
9
11


text:
Q: How to check return procedure value from sql I have this procedure
create proc Insert_New_Emp
    @EMP_Name varchar(50),
    @EMP_Email varchar(50),
    @EMP_Role  varchar (10),
    @Username  varchar(50),
    @password  varchar(50),
    @EMP_Phone  varchar(15),
    @EMP_Department  varchar(50),
    @Question  varchar(200)
as
begin
    insert into EMP_Info (EMP_Name, EMP_Email, EMP_Role, Username, password,
                          EMP_Phone, EMP_Department, Question)
    values (@EMP_Name, @EMP_Email, @EMP_Role, @Username, @password,
            @EMP_Phone, @EMP_Department, @Question)

    if (exists(select EMP_Role from EMP_Info where EMP_Role ='Admin' ))
        return 'Admin'
    else
        return 'Employee'
end

I need to check the procedure code in Windows Form C#
When the return Admin do something and else do something

A: A RETURN statement can return an integer code, with zero indicating success and non-zero for warning/error.  It is not intended to return data.  To return a scalar value back to the application, use either an OUTPUT parameter or SELECT statement.  Examples below.
CREATE PROC Insert_New_Emp
    @EMP_Name varchar(50)
  , @EMP_Email varchar(50)
  , @EMP_Role varchar(10)
  , @Username varchar(50)
  , @password varchar(50)
  , @EMP_Phone varchar(15)
  , @EMP_Department varchar(50)
  , @Question varchar(200)
  , @EmpType varchar(8) OUTPUT
AS
    BEGIN
        INSERT  INTO EMP_Info
                ( EMP_Name
                , EMP_Email
                , EMP_Role
                , Username
                , password
                , EMP_Phone
                , EMP_Department
                , Question
                )
        VALUES  ( @EMP_Name
                , @EMP_Email
                , @EMP_Role
                , @Username
                , @password
                , @EMP_Phone
                , @EMP_Department
                , @Question
                );

        IF EXISTS ( SELECT    EMP_Role
                      FROM      EMP_Info
                      WHERE     EMP_Role = 'Admin' )
            SET @EmpType = 'Admin'
        ELSE
            SET @EmpType = 'Employee';
    END;
GO

CREATE PROC Insert_New_Emp
    @EMP_Name varchar(50)
  , @EMP_Email varchar(50)
  , @EMP_Role varchar(10)
  , @Username varchar(50)
  , @password varchar(50)
  , @EMP_Phone varchar(15)
  , @EMP_Department varchar(50)
  , @Question varchar(200)
AS
    BEGIN
        INSERT  INTO EMP_Info
                ( EMP_Name
                , EMP_Email
                , EMP_Role
                , Username
                , password
                , EMP_Phone
                , EMP_Department
                , Question
                )
        VALUES  ( @EMP_Name
                , @EMP_Email
                , @EMP_Role
                , @Username
                , @password
                , @EMP_Phone
                , @EMP_Department
                , @Question
                );

        IF EXISTS ( SELECT    EMP_Role
                      FROM      EMP_Info
                      WHERE     EMP_Role = 'Admin' )
            SELECT 'Admin' AS EmpType
        ELSE
            SELECT 'Employee' AS EmpType;
    END;
GO

A: If you want to execute storedproc from c# code then you need to do as below :
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
  cmd.CommandType = CommandType.StoredProcedure;

  cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
  cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;

  con.Open();
  cmd.ExecuteNonQuery();
}

}
}
Just replace the procedure name from 'sp_Add_contact' and add your own parameters with the data type as defined in your stored proc
Original answer : here

A: I will suggest you to modify your SP to return an integer value, because a Stored Proc can only return Integer values. Modiy it like this:-
Declare @ReturnVal  INT
    if (exists(select EMP_Role from EMP_Info where EMP_Role ='Admin' ))
          SET @ReturnVal = 1 -- return 1 for Admin
          else
         SET @ReturnVal = 2  --return 2 for Employee
Return @ReturnVal
      end
Then you can call this SP from your ADO.NET code as:-
SqlParameter returnParam = cmd.Parameters.Add("ReturnVal", SqlDbType.Int);
  returnParam.Direction = ParameterDirection.ReturnValue;
  cmd.ExecuteNonQuery();
 //Read the returned value.
  int UserType= (int) returnParam.Value;

Also, It would be better if you define an Enum in your code like this and use this in your code rather than hard-coding in SP:-
 public enum EmployeeType
    {
        Admin = 1,
        Employee = 2
    }


text:
Q: Cross Domain Tracking script into Google Tag Manager settings? I am trying to set up my website to have cross domain tracking with the online store Gumroad.com, inside my Google Analytics. So that I can follow the user events from one site onto the next.
Gumroad has instructions at this link, but they are in the format of a script to be pasted into the site.
I use Tag Manager and am wanting to input these parameters into my Google Analytics Settings variable (which is how Google recommends doing Cross domain tracking with Tag Manager)
I'll attach the script that they provided, as well as my Google Analytics Settings variable in Tag Manager. If anyone knows how to set up the rest of the parameters that would be greatly appreciated!
Script:
<script>
// mystorefront.com is your site's domain.
ga('create', 'UA-XXXXX-Y', 'mystorefront.com;, {'name': 'sampleTracker', 'allowLinker': true, ';cookieDomain': 'mystorefront.com'});
ga('sampleTracker.require', 'linker');
ga('sampleTracker.linker:autoLink', ['mystorefront.com']);
ga('sampleTracker.send', 'pageview');
</script>

My Tag Manager (Google Analytics Settings variable) setup so far:
[]

A: Set domains in list without protocol.
It also does not make sense that you use cookieDomain as Field to set when it is already defined in the field below the tracking ID.


text:
Q: How do you use Snap's authentication mechanisms during a single POST request? I'm working on a Haskell Snap-based web app, and I want to expose an API endpoint that will be invoked by a remote service without establishing an authenticated session a-priori; however, I do want that request to be authenticated, so the credentials should be provided at the time of the request.
You could imagine the request containing four fields:

*

*username

*password

*payload id

*payload file

The payload id and file might be irrelevant for this question, but I include them because I (a) need to support file uploads in this request (which, as I understand it, restricts the encoding used to send fields) and (b) need to retrieve at least one non-file field.  The combination of those things posed some difficulty when I set this up without authentication, so perhaps it is relevant.
In Snap parlance, let's call this handler uploadHandler.
As indicated above, I have this working fine without authentication, with a setup like this:
uploadHandler :: Handler App App ()
uploadHandler = do
  -- collect files / form fields and process as needed.

-- and using the routes:
routes :: [(ByteString, Handler App App ())]
routes = [ ("/login",    with auth handleLoginSubmit)
         , ("/logout",   with auth handleLogout)
         , ("/new_user", with auth handleNewUser)

         -- handle the upload:
         , ("/upload",   handleUpload)
         ]

The naive solution is to simply add 'with auth' and change the type of handleUpload:
uploadHandler :: Handler App (AuthManager App) ()
uploadHandler = do
  -- collect files / form fields and process as needed.

-- and using the routes:
routes :: [(ByteString, Handler App App ())]
routes = [ ("/login",    with auth handleLoginSubmit)
         , ("/logout",   with auth handleLogout)
         , ("/new_user", with auth handleNewUser)

         -- handle the upload, with auth:
         , ("/upload",   with auth handleUpload)
         ]

However, this seems to require two requests: (i) authenticate and establish a session, (ii) send the POST request containing the actual payload.
I found a way to do this in one request, but it seems like there should be a more elegant means.  Here's the example restricted POST handler I've hacked together:
restrictedPOST :: Handler App (AuthManager App) ()
restrictedPOST = do
  mName <- getPostParam "username"
  mPass <- getPostParam "password"
  let uName = C8.unpack $ fromMaybe "" mName
      pass = ClearText $ fromMaybe "" mPass

  authResult <- loginByUsername (T.pack uName) pass False
  case authResult of
    Left authFail -> writeText "Could not log in"
    Right user    -> writeText (T.append "Hello " (userLogin user))

Is there something like 'with auth' that I can use instead of turning this example (restrictedPOST) into a combinator?  I realize it may need to know which fields to get credentials out of, but I also know very little about web services (maybe there is another means? Maybe this is a total non-issue, and I just don't know how to check auth for POST requests. I'm open to any suggestions!)

A: I don't think you understand what with auth is doing.  It has nothing to do with whether authentication is required.  All it does is convert a Handler b (AuthManager b) into a Handler b v.  No permissions checks are performed.  Your restrictedPOST function has the right idea.


text:
Q: Setting secure session cookies in php Syntax to set session cookies
session_set_cookie_params($lifetime, $path, $domain, $secure, true);

Q1. Is setting session cookie like below secure or is there more to be done?
session_set_cookie_params('3600', 'www.example.com', isset($_SERVER["HTTPS"]), true);

Q2. What should be the ideal lifetime for setting a session (from security view point) cookie?
Q3. If ever I decide to shift my web admin folder to sub domain then will the above code require change?.

A: A1: Your above code looks ideal, as long as it follows the PHP documentation page, who are we to say otherwise;
A2: This all just depends on exactly what this is being used for. In banking, some like to kill the session within minutes of inactivity. In gaming or social networking, these settings tend to be more relaxed and lenient as to give the user more leeway;
A3: Yes, you would have to change the cookie to reflect the new subdomain admin change. If you wanted to set a global cookie (that works on all subdomains):
session_set_cookie_params('3600', 'example.com', (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')? true : false, true);

Hope this helps!

A: define('SESSION_EXPIRE',3600*6);

define('SESSION_EXPIRE_RELOAD',1800);

ini_set('session.gc-maxlifetime',SESSION_EXPIRE);

ini_set('session.name','prl');

ini_set('session.cookie_httponly',true);

ini_set('session.cookie_secure',false);

session_set_cookie_params(SESSION_EXPIRE);

session_start();

[How do I expire a PHP session after 30 minutes?
    sessionRegenerate(){
        if (!isset($_SESSION['SESSION_CREATED']))
        {
            $_SESSION['SESSION_CREATED'] = time();
        }
        else if (( SESSION_EXPIRE -(time() - $_SESSION['SESSION_CREATED']) ) < SESSION_EXPIRE_RELOAD && ( SESSION_EXPIRE -(time() - $_SESSION['SESSION_CREATED']) ) > 0 )
        {
            session_regenerate_id(true);
            $_SESSION['SESSION_CREATED'] = time();
        }
    }


text:
Q: How to create an image with color gradient in React's JSX? This is what I have so far:

homepageImage: {
    position: "relative",
    textAlign: "center",
    height: "100vh",
    backgroundImage: `linear-gradient(
      #3A8DFF,
      #86B9FF
      ), url("images/bg-img.png")`,
  },

I got the above code by referencing this Stackoverflow post, but I guess this method doesn't work with JSX? The colors with the gradient displays in the div, but the image does not appear. I can confirm the url is the correct path as I tested with an  tag with "images/bg-img.png" as the src and the image appears.
Would it be a better approach to create a gradient with the  tag instead of the
 tag? Not sure where to go from here.

A: Try this :
You need to use rgba() to specify the opacity of the color.
App.js
import React from 'react';
import './style.css';

export default function App() {
  return (

How to create an image with color gradient in React's JSX

  );
}

const homepageImage = {
  position: 'relative',
  textAlign: 'center',
  height: '100vh',
  backgroundSize: 'cover',
  backgroundImage: `linear-gradient(
      rgba(58, 141, 255, 0.9),
      rgba(134, 185, 255, 0.3)
      ), url("https://images.unsplash.com/photo-1593642532400-2682810df593?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80")`
};

Demo : Stackblitz


text:
Q: How to find if a string has a character which isn't in another string For example I can have the string 'acagtcas' and I want to find if the string has any characters that aren't a, c, g or t. I've tried using not but I haven't been able to make it work. How can I implement this?

A: You can use set.difference:
s = "acagtcas"

x = set(s).difference("acgt")
print(x)

Prints:
{'s'}

A: You can use a comprehension to check the validity of each letter, and then use any() to see whether at least one of them is invalid:
valid_letters = 'acgt'
data = 'acagtcas'

any(letter not in valid_letters for letter in data)

Output:
True

A: valid_letters = 'acgt'
data = 'acagtcas'

print(bool(set(data)-set(valid_letters)))

output:
True

valid_letters = 'acgt'
data = 'acagtcas'

print(set(data)-set(valid_letters))

Output:
{'s'}


text:
Q: Reload or Refresh a page using Jquery from local machine I have a html document on my local machine, I created a button using JQuery and set an on click for the button. When the button is clicked, I want the current index.html page refresh.
This following is in the script tags:
    var refreshButton = '<button id="refresh"> Refresh </button>';
    $body.append(refreshButton);
    $('#refresh').click(function(){
      refresh(forceGet);
    });

i tried, location.refresh(); & window.location.refresh(); & refresh(); but they didnt work.

A: $body.append(refreshButton);

needs to be
$('body').append(refreshButton);

and window.location.reload(true); should work.  Try this:
$( document ).ready(function() {
   $('body').append('<button id="refresh"> Refresh </button>');
   $('#refresh').click(function(){
      window.location.reload(true);
   });
});

A: You need to use window.location.reload().

$('document').ready(() => {
    $('#last-date').html(new Date())
    $('#refresh').on('click', () => {
        console.log('Refreshing...')
        window.location.reload(true)
    })
})

<button id="refresh">Refresh</button>

Last loaded at


text:
Q: Handling Guards with redirections, callbacks and unknown paths For a project, I have a Router with those available paths :
const appRoutes: Routes = [
  {path: '', component: AppComponent},
  {path: 'dashboard', component: DashboardComponent},
  {path: 'leaderboard', component: LeaderboardComponent},
  {path: 'authentication', component: AuthenticationComponent},
  {path: '**', redirectTo: '/authentication', pathMatch: 'full}
];

The Injectable Service of the AuthenticationComponent was handling the router. The user if not authentified would be redirected to /authentication, whatever the route was, and to /dashboard if he's logged in.
The problem is if I want to reload the /leaderboard page, it redirects to /dashboard everytime, and it shouldnt be The Authentication Service's job as well.
I've tried, using This guide to understand guards, which allowed me to handle basic navigation throught the /dashboard and /leaderboard, the callback of Auth0 and the refresh as well, but  when accessing my login page while being already authentified, it is not redirecting, same behavior with unknown paths.
Is there a way for me to check if the provided route is known by my Router, and redirect correctly if the user is logged in or not ?
My Guard :
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {AuthenticationService} from './component/authentification/authentication.service';
import {Injectable} from '@angular/core';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthenticationService,
              private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    console.log(route, state);
    this.authService.handleAuthentication();
    if (this.authService.isAuthenticated()) {
      return (true);
    } else {
      this.router.navigate(['/authentication']);
    }
  }
}

My current router :
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';

import {DashboardComponent} from './component/dashboard/dashboard.component';
import {LeaderboardComponent} from './component/leaderboard/leaderboard.component';
import {AuthenticationComponent} from './component/authentification/authentication.component';
import {AppComponent} from './app.component';
import {AuthGuard} from "./app-routing.guard";

const appRoutes: Routes = [
  {path: '', canActivate: [AuthGuard], redirectTo: '/dashboard', pathMatch: 'full'},
  {path: 'dashboard', canActivate: [AuthGuard], component: DashboardComponent},
  {path: 'leaderboard', canActivate: [AuthGuard], component: LeaderboardComponent},
  {path: 'authentication', component: AuthenticationComponent},
  {path: '**', canActivate: [AuthGuard], redirectTo: '/authentication'}
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes
    )
  ],
  exports: [
    RouterModule
  ]
})

export class AppRoutingModule {
}

A: If your goal is to check if the provided route is known to the Router, use RoutesRecognized event:
export class AppComponent {

  constructor (private router: Router){
    this.router.events.subscribe(
      (event) => this.handleRouterEvents(event)
    );
  }

  handleRouterEvents(event){
    if (event instanceof RoutesRecognized){
      console.log("The user provided the known route");
    } else{
      console.log("The user provided unknown route");
    }
  }

If you need the URL of the route, check the Router.url property. Turn on the tracing and check the output on the console:
export const routing = RouterModule.forRoot(routes,
  { enableTracing: true });

A: I went too deep, I only needed to add more verifications in my guard :
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  this.authService.handleAuthentication();
  if (this.authService.isAuthenticated()) {
    if (state.url === '/authentication') {
      this.router.navigate(['/dashboard']);
    } else {
      return (true);
    }
  } else if (state.url === '/authentication') {
    return (true);
  } else {
    this.router.navigate(['/authentication']);
  }
}


text:
Q: Random SQL connection issues. Works, then doesn't work, then works, then BAM! Never works again? I am using WebMatrix here, and have a DB, and it was all working just fine until it randomly threw an error at me about a connection string not being there. And this always happens from time to time, and I'm assuming it's a bug in WebMatrix where it just forgets or loses a setting somewhere, because it's not related to any change that I've made.
Here's the error, along with the stacktrace: (apologies for such a long error)
Server Error in '/' Application.
--------------------------------------------------------------------------------

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Source Error:

Line 1:  @{
Line 2:     WebSecurity.InitializeDatabaseConnection("SV", "UserProfile", "UserId", "Email", true);
Line 3:      WebMail.SmtpServer = "mail.sv.com";
Line 4:      WebMail.EnableSsl = false;

Source File: d:\HostingSpaces\svisible\sv.com\wwwroot\_AppStart.cshtml    Line: 2

Stack Trace:

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5064474
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
   System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity) +341
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject) +129
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) +270
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +195
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +232
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +185
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +33
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +524
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
   System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +479
   System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +108
   System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +126
   System.Data.SqlClient.SqlConnection.Open() +125
   WebMatrix.Data.Database.EnsureConnectionOpen() +44
   WebMatrix.Data.<QueryInternal>d__0.MoveNext() +71
   System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +4232308
   WebMatrix.Data.Database.QuerySingle(String commandText, Object[] args) +103
   WebMatrix.WebData.SimpleMembershipProvider.CheckTableExists(Database db, String tableName) +59
   WebMatrix.WebData.SimpleMembershipProvider.CreateTablesIfNeeded() +55
   WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider sMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +73
   WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
   WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionStringName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
   ASP._Page__AppStart_cshtml.Execute() in d:\HostingSpaces\svisible\sv.com\wwwroot\_AppStart.cshtml:2
   System.Web.WebPages.ApplicationStartPage.<ExecuteInternal>b__3() +65
   System.Web.WebPages.ApplicationStartPage.<GetSafeExecuteStartPageThunk>b__a(Action action) +7
   System.Web.WebPages.ApplicationStartPage.ExecuteInternal() +78
   System.Web.WebPages.ApplicationStartPage.ExecuteStartPageInternal(HttpApplication application, Action`1 monitorFile, Func`2 fileExists, Func`2 createInstance, IEnumerable`1 supportedExtensions) +202
   System.Web.WebPages.ApplicationStartPage.ExecuteStartPage(HttpApplication application, Action`1 monitorFile, Func`2 fileExists, Func`2 createInstance, IEnumerable`1 supportedExtensions) +41

[HttpException (0x80004005): Exception of type 'System.Web.HttpException' was thrown.]
   System.Web.WebPages.ApplicationStartPage.ExecuteStartPage(HttpApplication application, Action`1 monitorFile, Func`2 fileExists, Func`2 createInstance, IEnumerable`1 supportedExtensions) +88
   System.Web.WebPages.ApplicationStartPage.ExecuteStartPage(HttpApplication application) +287
   System.Web.WebPages.WebPageHttpModule.StartApplication(HttpApplication application, Action`1 executeStartPage, EventHandler applicationStart) +113
   System.Web.WebPages.WebPageHttpModule.StartApplication(HttpApplication application) +71
   System.Web.WebPages.WebPageHttpModule.Init(HttpApplication application) +217
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +517
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +194
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +339
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +253

[HttpException (0x80004005): Exception of type 'System.Web.HttpException' was thrown.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9079228
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +256

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.237

Why does WebMatrix keep doing this to me? Can someone please try to help me resolve this? I have searched endlessly, and have found plenty of somewhat-related pages but not able to get it working.
Thank You

A: Check and make sure that TCP Chimney is disabled on both your web server and the SQL Server.  http://technet.microsoft.com/en-us/library/gg162682(WS.10).aspx