text:
Q: How to create sections and section titles but prevent them from showing up in the output? I'm wondering if it's possible to create section and section titles but prevent them from showing up in the output.
Below an example. Although I need the section for the numbering op my tables and figures I don't want the title in my ouput
\appendix
 \section{the first appendix}

A: Either one uses \refstepcounter{section} directly each time or  \fakesection command that does \refstepcounter{section} or redefines \section to do effectively nothing apart from \refstepcounter{section}.
In my point of view, it's better to redefine \section to provide the possibility of using the same code later on when section titles and toc entries are needed.
I've done this here by appending the redefinition code to the \appendix command, i.e. it's redefined only after \appendix has been used.
Why \refstepcounter and not just \stepcounter?
Assume, that the (non-existent) appendix section should be referenced by a \label command → this would only work with \refstepcounter{section} and not with \stepcounter only!
\documentclass{article}

\usepackage{graphicx}
\usepackage{xpatch}

\makeatletter
\let\latex@@section\section
\xapptocmd{\appendix}{%
  \renewcommand{\section}[2][]{%
    \refstepcounter{section}%
  }
  \renewcommand{\thefigure}{\thesection.\arabic{figure}}
}{}{}
\makeatother

\begin{document}
\tableofcontents
\section{A real section}

\clearpage
\appendix

\section{A dummy section}

\begin{figure}
\includegraphics[scale=2]{beeduck}
\caption{ A figure in a dummy section}
\end{figure}

\end{document}


text:
Q: Hiding google map data I've been working on a google map (v3 of the api) that is plotting 120 markers or so (or will do shortly). If you view the source the map data is for all the see, is it possible to hide this?
I'm not worried about the code that is generating the map, just the data. The data is grabbed from a Wordpress cms.

A: I think your options mostly boil down to:

*

*Obfuscate the data.  Restructure it in such a way that it is difficult to recognize as location data, and inconvenient for other people to work with.

*Don't include the data directly in the page body.  Fetch it using an AJAX request instead.  Determined users will still be able to get the data, but it won't be quite as easy/obvious, and it will not appear when doing a 'view source'.
You could of course combine the two approaches, and have an AJAX request that returns obfuscated data.
Although, your data appears to be names and locations of businesses, so I'm not sure why protecting it is a concern.  Presumably any interested party could find the same information in a phone-book (or with a Google search) if they were so inclined.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I create an static array and access the array from outside of the scope, with a pointer? I want to create an array but only in a specific situation: Can I create an static Array and access it from outside with a pointer, like this:
int ptr = NULL;
if (condition) {
    static int arr[5];
    ptr = arr;
}
printf("%d", ptr[0]);


text:
Q: Buffer overflow with disabled shell? AFAIK, a buffer overflow is achieved by overwriting memory adjacent to a C variable's buffer. This overwriting is used to spawn a shell which executes commands.
But what if the user that is running the program vulnerable to a buffer overflow has the shell disabled ?
/etc/passwd:
user1:x:1000:1000:user1,,,,:/home/user1:/bin/false
sudo -u user1 /usr/bin/programname

A: "Shell disabled" only matters if you're actually logging in. If you're exploiting an already running program then you don't need to log in.

A: Exploits do not use a shell which is configured for a user — they normally include a binary code, shellcode, which are functionally equivalent to a primitive shell, meaning that it will start any chosen executable — for example a real shell program. Exploited program is then tricked to execute this code.
There are many different shellcodes available on the net, for example which do not include a byte '\0', so they will be passed unharmed as a C string, or which only include printable characters, valid unicode strings etc.


text:
Q: Average of the normal force
I was trying to solve this exercice , but I asked my self , why and how to find out the average normal force , since we can get directly the average normal force ? , because when the ball touches the surface we automaticaly get : $N = P = m.g~~$ isn'it  ? So why to search an average force since we can directly get the force itself ?

A: The normal force is not simply given by $N = mg$ because the ball is not just resting on the surface. When the ball is far away there is no force, when the ball touches the surface it will be pushed a bit but the ball will keep going down but slowing down until it stops and then the force will keep pushing the ball making it move upwards and bounce away.
Basically you need to calculate the impulse (how much the momentum change) because that's equal to the contact time times the average normal force.
$\Delta J = N_{avg}T = (p_f - p_i)$
You can get $p_f$ and $p_i$ from energy conservation.


text:
Q: Does Android 4.x support streaming RTSP over TCP? I've used VideoView in Android to play video on wowza successfully. Now I got to deal with my server which the UDP ports seems to be blocked. With the proof of openRTSP command:
-> % openRTSP rtsp://61.218.52.250:554/live/ch00_0

Opening connection to 61.218.52.250, port 554...
...remote connection opened
Sending request: OPTIONS rtsp://61.218.52.250:554/live/ch00_0 RTSP/1.0
CSeq: 2
User-Agent: openRTSP (LIVE555 Streaming Media v2013.12.16)

Received 105 new bytes of response data.
Received a complete OPTIONS response:
RTSP/1.0 200 OK
CSeq: 2
Server: UBNT Streaming Server v1.2
Public: DESCRIBE, SETUP, TEARDOWN, PLAY

Sending request: DESCRIBE rtsp://61.218.52.250:554/live/ch00_0 RTSP/1.0
CSeq: 3
User-Agent: openRTSP (LIVE555 Streaming Media v2013.12.16)
Accept: application/sdp

Received 562 new bytes of response data.
Received a complete DESCRIBE response:
RTSP/1.0 200 OK
CSeq: 3
Server: UBNT Streaming Server v1.2
Content-Base: rtsp://61.218.52.250:554/live/ch00_0/
Content-Type: application/sdp
Content-Length: 393

v=0
o=- 1 1 IN IP4 127.0.0.1
s=Ubiquiti Live
i=UBNT Streaming Media
c=IN IP4 0.0.0.0
t=0 0
m=video 0 RTP/AVP 99
b=AS:50000
a=framerate:25
a=x-dimensions:1280,720
a=x-vendor-id:ubnt,a521
a=x-rtp-ts:4617405454576779984
a=rtpmap:99 H264/90000
a=fmtp:99 profile-level-id=42A01E;packetization-mode=1;sprop-parameter-sets=Z0IAKOkAoAt1xIAG3dAAzf5gDYgQlA==,aM4xUg==
a=control:trackID=0

Opened URL "rtsp://61.218.52.250:554/live/ch00_0", returning a SDP description:
v=0
o=- 1 1 IN IP4 127.0.0.1
s=Ubiquiti Live
i=UBNT Streaming Media
c=IN IP4 0.0.0.0
t=0 0
m=video 0 RTP/AVP 99
b=AS:50000
a=framerate:25
a=x-dimensions:1280,720
a=x-vendor-id:ubnt,a521
a=x-rtp-ts:4617405454576779984
a=rtpmap:99 H264/90000
a=fmtp:99 profile-level-id=42A01E;packetization-mode=1;sprop-parameter-sets=Z0IAKOkAoAt1xIAG3dAAzf5gDYgQlA==,aM4xUg==
a=control:trackID=0

Created receiver for "video/H264" subsession (client ports 63346-63347)
Sending request: SETUP rtsp://61.218.52.250:554/live/ch00_0/trackID=0 RTSP/1.0
CSeq: 4
User-Agent: openRTSP (LIVE555 Streaming Media v2013.12.16)
Transport: RTP/AVP;unicast;client_port=63346-63347

Received 47 new bytes of response data.
Received a complete SETUP response:
RTSP/1.0 461 Unsupported Transport
CSeq: 4

Failed to setup "video/H264" subsession: 461 Unsupported Transport

After searching around I found it seems Android still not support RTSP over TCP:

When streaming to an Android device using RTSP/RTP, the RTP portion
  must flow over UDP. Android doesn't support RTSP/RTP interleaved (RTP
  over TCP). This means that if UDP is unavailable for RTP playback, RTP
  over TCP won't work as a failover and your stream won't play.

Considering it's posted on 2010, does Android 4.x support RTSP over TCP now? I've found lots of post asking for how to force transfer via TCP other than UDP. I guess it's not.
If not, could I achieve it by re-compiling and using ffmpeg library?
Basically I hope ffmpeg could help me to automatically switch to TCP while UDP not available.


text:
Q: VB.NET Read 2 checkboxes status from file I am trying to recover the status of 2 checkboxes.
This 2 checkboxes i made them to work as radiobuttun: While one is checked, the another one uncheck.
I have an external file for the configuration of the program and i want that evrytime that I exit from the program, everything be saved in this file.
For do it I use this code:
   Private Sub Form1_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing

    Dim thefile As String = Application.StartupPath & "\SafetyBox.cfg"
    Dim lines() As String = System.IO.File.ReadAllLines(thefile)

    lines(1) = "Language_file=" & ComboBox1.Text
    If CheckBox1.Checked = True Then
        lines(2) = "Status1=" & "1"
    Else
        lines(2) = "Status1=" & "0"
    End If
    If CheckBox2.Checked = True Then
        lines(3) = "Status2=" & "1"
    Else
        lines(3) = "Status2=" & "0"
    End If
    System.IO.File.WriteAllLines(thefile, lines)

End Sub`

And this part working great. Status1 should be the status of checkbox1, while status2 is the status of checkbox2.
The code that is not working is:
 Dim path As String = Application.StartupPath & "\SafetyBox.cfg"
    If File.Exists(path) Then

        Using sr As StreamReader = New StreamReader(path)

            Dim linenew As String = sr.ReadLine()
            If linenew.Contains("\") Then
                TextBox1.Text = linenew

            Else
                MsgBox("Configura il programma da usare")
            End If

            Dim lineN As String = sr.ReadLine()
            If lineN.Contains("Language_file=") Then
                ComboBox1.Text = lineN.Split("=").Last()
            End If
            If lineN.Contains("Status1=1") Then
                CheckBox1.Checked = True
                CheckBox2.Checked = False

            ElseIf lineN.contains("Status1=0") Then
                CheckBox1.Checked = False
                CheckBox2.Checked = True

            End If

            If lineN.Contains("Status2=1") Then
                CheckBox1.Checked = False
                CheckBox2.Checked = True

            ElseIf lineN.Contains("Status2=0") Then
                CheckBox1.Checked = True
                CheckBox2.Checked = False
            End If
                sr.ReadToEnd()
            sr.Close()
        End Using

Can yOu let me understnd where is my mistake? Why when in the .cfg file is wrote correctly Status1=0 and Status2=1, when loading the program i always see checkbox1 checkd and not checkbox2?
Thanks

A: You wrote that you got the CheckBoxes working as RadionButtons. I suspect that to do this you handled either or both of the events CheckedChanged and CheckStateChanged.
So that when the CheckState is changed, the other Checkbox is set or unset appropriately.
When you load the configuration/state of the form from the file, you are setting the values on the CheckBoxes and subsequently, causing the events to be fired. To prevent the events from being fired you should temporarily remove the event handlers from the Checkbox controls.
Add the lines at the start of your method to load the configuration:
RemoveHandler Checkbox1.CheckStateChanged, AddressOf Checkbox1_CheckStateChanged
RemoveHandler Checkbox2.CheckStateChanged, AddressOf Checkbox2_CheckStateChanged

And, at the end of the method, you will need to re-establish the event handlers by using:
AddHandler Checkbox1.CheckStateChanged, AddressOf Checkbox1_CheckStateChanged
AddHandler Checkbox2.CheckStateChanged, AddressOf Checkbox2_CheckStateChanged

If this is the problem, what you have encountered is a common enough problem when a form has multiple event handlers that respond to xxxChanged events.


text:
Q: "The happiest people are those who are too busy to notice whether they are or not." - What? Happy or Busy? http://www.forbes.com/forbes/welcome/

"The happiest people are those who are too busy to notice whether they are or not."
  William Feather

I didn't get what are they too busy to notice out of the following?

*

*That they are happy?

*That they are busy?

A:
"The happiest people are those who are too busy to notice whether they are or not."

So, your first suggestion seems apt - They are too busy to notice their own happiness.
This means that the happiest people are those individuals who really don't worry too much about their happiness. When you start noticing your happiness, you tend to measure it and we humans are never satisfied with what we have. "I could be happier" - That is what creeps in when you think about how happy you are. When a person who is too busy to think about it doesn't waste time measuring his happiness. After all, Ignorance is bliss.

A: Often people are sad because they give themselves the time to wonder whether they are happy or not. Making them unhappy. However if you "do your duty" and are too busy to really stop or go for your feelings, you will be happy.


text:
Q: How to debug angular protractor tests in WebStorm There is a way to run and debug protractor web-tests in WebStorm.
I just want to share this answer here

A: *

*Get the node path (Type which node in your terminal)

*In the WebStorm: Click on "Edit configurations" - the dropdown to the left of the "Run" button (green arrow like a "play" button)

*Click on the "Add button" (green +) to add a new Node configuration. Select "Node.js"

*Fill the params:

Node interpreter: Full path to Node.js (from step 1)
Working directory: home directory for the protractor tests.
Javascript file: Full path to node_modules/protractor/lib/cli.js
Application parameters: Full path to protractor-conf.js
Now you be able to run and debug tests by clicking on "Run" or "Debug" buttons on the top of IDE

A: I was experiencing the same problems described by comments to S.Panfilov's answer, i.e., running protractor in WebStorm worked fine, but the debugging process got stuck somewhere.
The issue is described here. It was occurring under Mac OS X with version 0.20.1 of protractor, and node v0.10.26.
The problem is solved in version 0.22.

*

*Update protractor to the latest version (>= 0.22) using npm

*Run again: node_modules/protractor/bin/webdriver-manager update

*In WebStorm configure 'Your Protractor Conf' as described by S.Panfilov in his answer

*Set breakpoints in your protractor test file (watch this video first)

*Launch "Run > Debug 'Your Protractor Conf'" from WebStorm

*Enjoy debugging

A: For mac OSX:

on the left you can see tests folder structure

A: It works! Here are my settings

A: Worked for me. It was looking for the protractor.conf.js in the wrong folder. Had to look up a couple dirs.
Application parameters: ../../protractor.conf.js

A: Like some of the other responses here, I found that I could run in release but couldn't run in Debug and it would just hang at some point.  I found that I had the conf file set to target two browsers and it seems that this was too much for the debugger and it would hang without any more info.  Targeting only a single browser fixed this issue for me.

A: By the way if you need to pass additional parameters here is the configuration you need

*

*Select 'Node.js' configuration from the list

*Name: 'Protractor'

*Node interpreter: 'C:\Program Files\nodejs\node.exe'

*Node parameters: ''

*Working directory:

*JavaScript file: '~\AppData\Roaming\npm\node_modules\protractor\built\cli.js'

*Application parameters, this is where you specify path to your conf, relatively to working directory^ and then parameters like this: 'e2e/settings/configs/protractor.custom.conf.js --baseUrl="https://stage.mysite.com" --params.login="testuser" --params.password="test_USER00"'

*Environment variables: ''

This config works great in my project, where we solely rely on async/await syntax


text:
Q: Running on eclipse shows error I did git clone a repository and try working on files in it but when I try to run, "Error: Could not find or load main class " shows up every time.
So far on Eclipse, I created a workspase and cloned a repository there which is supposed to have two two folders. In one folder, there are starter codes that I need to work on for this assignment but when I cannot run it...


text:
Q: How to use window.requestFileSystem of FileSystem API? I have written below code in javascript:
javascript code:
var fs=null;

        function initFS() {
            window.requestFileSystem =window.requestFileSystem || window.webkitRequestFileSystem;
               window.requestFileSystem (window.TEMPORARY, 1024 * 1024, function (filesystem) {
                fs = filesystem;
            }, errorHandler);
        }

html code:
<input type="button"  id="button2" name="click" value="show" onclick="initFS();" />

but after clicking on show button in initFS function, after line window.requestFileSystem (window.TEMPORARY, 1024 * 1024, function (filesystem) {
it is showing error as "uncaught type error". Is there  any mistake in my code?

A: You can not define errorHandler
var fs=null;

        function initFS() {
            window.requestFileSystem =window.requestFileSystem || window.webkitRequestFileSystem;
               window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (filesystem) {
                fs = filesystem;
                console.log(fs);
            }, errorHandler);
        }
        function errorHandler(e) {
           console.log(e); // it show everything that you want
          }


text:
Q: Get user location and display data I am creating small React Native app. For backend I will probably go with firebase and mongodb. I will store some restaurants, clubs etc.. I wonder can I get user location and display clubs and restaurants that are nearby. If user denies location permission, Ill go with filter for country and city.
Thanks.

A: You can achieve this task by
First asking for location permission from the user. You have to use this package. Please go through the example codes first.
react-native-permissions
Secondly, you can check for the current location by using these packages. You can also convert the lat/long values to address and vice versa.
@react-native-community/geolocation
react-native-geolocation-service
react-native-get-location
react-native-geocoding


text:
Q: Display data fields based on checkbox selection in SAP ABAP Below is simple code where I want to display location based on checkbox selection.
Eg: id p_pune is selected at seletion screen then after WRITE command my output should be as below
EMPID  NAME  LOCATION
 1       A     PUNE

Code:
TYPES: BEGIN OF ty_emp,
       empid TYPE i,
       name TYPE char5,
       location TYPE char6,
  END OF ty_emp.

  DATA: wa_emp TYPE ty_emp,
        it_emp TYPE TABLE OF ty_emp.

  DATA: gd_ucomm TYPE sy-ucomm.

  wa_emp-empid = 1.
  wa_emp-name = 'A'.
  wa_emp-location = 'Pune'.
  append wa_emp to  it_emp.

CLEAR wa_emp.
   wa_emp-empid = 2.
  wa_emp-name = 'B'.
  wa_emp-location = 'Mumbai'.
append wa_emp to  it_emp.

CLEAR wa_emp.
  wa_emp-empid = 3.
  wa_emp-name = 'C'.
  wa_emp-location = 'Delhi'.
append wa_emp to  it_emp.

CLEAR wa_emp.
  wa_emp-empid = 4.
  wa_emp-name = 'D'.
  wa_emp-location = 'Noida'.
  append wa_emp to  it_emp.

CLEAR wa_emp.

PARAMETERS: p_pune AS CHECKBOX USER-COMMAND c1,
            p_mumbai AS CHECKBOX USER-COMMAND c2,
            p_delhi AS CHECKBOX USER-COMMAND c3,
            p_noida AS CHECKBOX USER-COMMAND c4.

A: You can try this:
IF p_pune = abap_true.

  READ TABLE it_emp INTO wa_emp INDEX '1'.

  WRITE:/ wa_emp-empid, wa_emp-name, wa_emp-location.

ENDIF.

IF p_mumbai = abap_true.

  READ TABLE it_emp INTO wa_emp INDEX '2'.

  WRITE:/ wa_emp-empid, wa_emp-name, wa_emp-location.

ENDIF.

IF p_delhi = abap_true.

  READ TABLE it_emp INTO wa_emp INDEX '3'.

  WRITE:/ wa_emp-empid, wa_emp-name, wa_emp-location.

ENDIF.

IF p_noida = abap_true.

  READ TABLE it_emp INTO wa_emp INDEX '4'.

  WRITE:/ wa_emp-empid, wa_emp-name, wa_emp-location.

ENDIF.

When you check multiple checkboxes, it will display multiple locations.
If you want to display only one location, I suggest you use RADIO BUTTON instead of CHECKBOX.

A: You could convert the boolean values of the parameters to a location, using the COND statement. Then you can loop over the internal table with LOOP AT and use it's WHERE condition to filter out the location you need.
TYPES:
  BEGIN OF employee,
    empid    TYPE i,
    name     TYPE char5,
    location TYPE char6,
  END OF employee,
  employees TYPE STANDARD TABLE OF employee WITH EMPTY KEY.

DATA(employees) = VALUE employees(
  ( empid = 1 name = 'A' location = 'Pune'   )
  ( empid = 2 name = 'B' location = 'Mumbai' )
  ( empid = 3 name = 'C' location = 'Dehli'  )
  ( empid = 4 name = 'D' location = 'Noida'  )
).

PARAMETERS: pune   AS CHECKBOX,
            mumbai AS CHECKBOX,
            dehli  AS CHECKBOX,
            noida  AS CHECKBOX.

START-OF-SELECTION.

DATA(wanted_location) = COND char6(
  WHEN pune   = abap_true THEN 'Pune'
  WHEN mumbai = abap_true THEN 'Mumbai'
  WHEN dehli  = abap_true THEN 'Dehli'
  WHEN noida  = abap_true THEN 'Noida'
).

LOOP AT employees INTO DATA(employee)
  WHERE location = wanted_location.

  WRITE:
    employee-empid,
    employee-location,
    employee-name.

  NEW-LINE.
ENDLOOP.


text:
Q: Substructure Argument for Chain Conditions Once, someone showed me a nice argument using elementary substructures for proving chain conditions about forcings. It was a basic example, maybe that Cohen forcing is ccc. I've been trying to look up this argument, but I've only found more combinatorial proofs. Can someone remind me how this argument goes or point me to a source that does? Thanks.

A: A typical argument for showing that a notion of forcing is ccc will invoke the $\Delta$-system lemma at some point, and this result has a slick proof using elementary submodels (see Lemma 24.24 of "Discovering Modern Set Theory II" by Just and Weese, or Example 2.1 of Dow's  "An introduction to applications of elementary submodels to topology".
One can usually combine these two steps into a single argument to prove that a notion of forcing is ccc using elementary submodels, although I can't point to a specific published example of this at the moment.  I'll see if I can find a reference for you where someone does this.
Edit:  The best reference is Ramiro's answer!

A: Say that $P=\{p \subset \kappa \times 2 : p \mbox{ is a finite function}  \}$ is ordered by reverse inclusion (adding $\kappa$ Cohen reals). We show that $P$ is ccc:
Let $A \subseteq P$ be an antichain and let $M$ be a countable elementary submodel of (a sufficiently large initial segment of) the universe such that $A,P \in M$. It is enough to show that $A \subseteq M$. If not, fix $p \in A \setminus M$, let $a=dom(p) \cap M$ and let $q=p \upharpoonright a$. It is clear that both $a$ and $q$ are in $M$. The existence of an $x \in A$ such that $a \subseteq dom(x)$ and $x \upharpoonright a = q$ is true in the universe ($p$ is a witness) and therefore in $M$ , so let $p' \in A \cap M$ be a witness of this. Now $p$ and $p'$ are compatible (because $dom(p) \cap dom(p')=a$) and they are different (because one is in $M$ and the other is not), a contradiction.


text:
Q: how to make it using https for a website using google cloud launcher? I am using Google cloud launcher to set up a Drupal instance. It went quite well. But the problem is that I can only access the drupal site by http, which is http://146.148.100.235. Hope someone can advise me on how to set up a secure https visiting over this?

A: Well you need to first buy a ssl certificate. Then you need to configure your web server so it listens on https port 443. After that you need to open the https port for your google compute instance.


text:
Q: Monaco Language Match Empty Line I'm trying to create a language definition for the Monaco editor. The language is a very opinionated language to which I don't control the compiler, etc.
The "\" escape character is universal; single-line comments can be continued to the next line by ending in "\"
Some examples, using C++-style comments:
// This comment \
   continues on the following line

// This one does NOT continue \\
   because the escape char was itself escaped

// This one DOES continue because \\\
   the 1st '\' escapes the 2nd; the 3rd escapes EOL

// This comment continues to the following line \

But the line was empty. This should not be commented.

I have implemented all of the semantics except the last part, because it does not appear to me possible to match on an empty line. The closest I found in documentation was '@eos' but I cannot figure out how to use it. Here is my current implementation:
comments: [
  [/\/\/$/, 'comment'], // empty single-line comment
  [/\/\//, 'comment', '@comment_cpp'],
],

comment_cpp: [
  [/(?:[^\\]|(?:\\.))+$/, 'comment', '@pop'],
  [/.+$/, 'comment'],
],

Is there a rule I can add that will enable me to "@pop" out of the "@comment_cpp" rule on an empty line so the following is true?
// This comment continues to the following line \
   and this one continues to the following empty line \

But this line is not commented

A: This issue was since resolved; the monaco team added support for matching on /$/.
https://github.com/microsoft/monaco-editor/issues/1235


text:
Q: How to check is Jenkins pram contains a character I am trying to check if my Jenkins parameter contains a hostname.
But when I use Regular Expressions to see if it contains the name it doesn't check.
I would guess I have an error in the way I am checking or how I have it wrapped in brackets.
Below is a sample of what I am working with
        stage('Release  1') {
            when {
                expression { params.SECRET_NAME != "" && params.STAGING_ENV != ("*some.host.name*") }
            }
            steps {
                    echo "Release 1"
                }
        }

        stage('Release 2') {
            when {
                expression {params.STAGING_ENV == ("*some.host.name*")  && params.SECRET_NAME == ("*+*") }
            }
            steps {
                    echo "Release 2"
                }
        }

    }

I want it to skip the stage in my Jenkins pipeline if it does not meet the conditions

A: Ok, you need multiple changes here, from inside out:

*

*Replace the * with .*. Simply put, in regex * denotes the same (set) of characters any number of times (abc* matches abccccc), whereas .* denotes any character any number of times (abc.* matches abccccc, abcdefg, abcadkhsdalksd, etc.).

*Remove the double quotes " surrounding the regex patterns; lest you want them to be interpreted as string literals.

*Wrap the regex patterns within delimiters, usually / to define the string boundary.

*The brackets () themselves are optional here.

*To match regular expressions, replace the equal operator == with the match operator ==~ (strict), which returns a boolean.

*There is no "NOT match" operator in Groovy. To invert the match, you need to invert the result of the entire expression.

*If the + in *+*should be a literal, then you must escape it as *\+*.

Stitching these together, your pipeline should look like:
stage('Release  1') {
    when {
        expression {
            params.SECRET_NAME != "" && !(params.STAGING_ENV ==~ /.*some.host.name.*/)
        }
    }
    steps {
        echo "Release 1"
    }
}
stage('Release 2') {
    when {
        expression {
            params.STAGING_ENV ==~ /.*some.host.name.*/  && params.SECRET_NAME ==~ /.*\+.*/
        }
    }
    steps {
        echo "Release 2"
    }
}

Further reading:

*

*http://docs.groovy-lang.org/latest/html/documentation/core-operators.html

*http://web.mit.edu/hackl/www/lab/turkshop/slides/regex-cheatsheet.pdf


text:
Q: angular js Unit test for directive jasmine I have written angular js directive one method, but I don't know how to write unit test for that.
 var app = angular.module("myApp",[]);

 app.directive('minMax', function() {

    return {
        require: 'ngModel',
        link: function(scope, element, attr, mCtrl) {
            function myValidation(value) {
                if (value.toString().length > 2 & value.toString().length < 6) {
                    mCtrl.$setValidity('charE', true);
                } else {
                    mCtrl.$setValidity('charE', false);
                }
                return value;
            }
            mCtrl.$parsers.push(myValidation);
        }
    };
});

How do I test this method?

A: Have a look here: https://github.com/daniellmb/angular-test-patterns.
It contains a great collection of test patterns.
Example of directive test:
describe('Directive: myDir', function () {
  var element, scope, compile, defaultData,
      validTemplate = '<my-dir ng-model="data"></my-dir>';

  function createDirective(data, template) {
    var elm;

    // Setup scope state
    scope.data = data || defaultData;

    // Create directive
    elm = compile(template || validTemplate)(scope);

    // Trigger watchers
    //scope.$apply();

    // Return
    return elm;
  }

  beforeEach(function () {

    // Load the directive's module
    module('myApp');

    // Reset data each time
    defaultData = 42;

    // Provide any mocks needed
    module(function ($provide) {
      //$provide.value('Name', new MockName());
    });

    // Inject in angular constructs otherwise,
    //  you would need to inject these into each test
    inject(function ($rootScope, $compile) {
      scope = $rootScope.$new();
      compile = $compile;
    });
  });

  describe('when created', function () {
    // Add specs
  });

  describe('when the model changes', function () {
    // Add specs
  });

  describe('when destroyed', function () {
    // Add specs
  });
});


text:
Q: IE8 Submits the form but sometimes doesn't refresh the page I have a button and when I click that button a function works, it calls jQuery .submit function.
I use jQuery 1.4.2.
However, sometimes it submits but doesn't refresh the page. I got this problem just on IE8.
Actually it works on IE8 but sometimes I get this problem and sometimes not.
My page is like that; there are some text fields and a chechboxes near every text field. I check the checkbox and push the delete button, it submits the value and that  text field disappear(it is deleted at server side and the page reloads all the text fields that saved at server side). The problem is that sometimes that textfield doesn't disappear from the screen but if I re-enter page's url and push enter or F5 the page or check the checkbox and push the delete button again everything works fine...

A: Sounds like browser caching issue. To solve this, when you submit the form add random value to its action, thus tricking the browser to think it's different page so it won't load the contents from its cache.
Sample code:
var rand = parseInt(Math.random() * 1000000 + 100000);
$(form).attr("action", "mypage.php?r=" + rand);
...

A: Problem was about my server side structure, was not related to only ie8.


text:
Q: Can you get Mink to follow redirect from https to http and keep the Session? I am trying to test my ajax scripts using codeception & PhpBrowser(which uses Mink with Goutte driver).
My ajax scripts require an authenticated session in order to execute, and the session is created via my log in page.
I am having issues with getting the PhpBrowser/Link sessions, to persist after login.
I created a PhpBrowser Helper function to overwrite _initialize so I could get https working with a self signed cert on my test server like this:
public function _initialize()
{
    $client = new \Behat\Mink\Driver\Goutte\Client();
    $driver = new \Behat\Mink\Driver\GoutteDriver($client);

    $curl_config = array_merge($this->curl_defaults, $this->config['curl']);
    array_walk($curl_config, function($a, &$b) { $b = "curl.$b"; });
    $curl_config['ssl.certificate_authority']=false;
    $client->setClient(new \Guzzle\Http\Client('', $curl_config));
    $client->followRedirects(true);
    $this->session = new \Behat\Mink\Session($driver);
    \Codeception\Util\Mink::_initialize();
}

Now when I run my acceptance test it seems like the Login works correctly, and the redirect happens based on the apache access_logs, but the PHPSESSID cookie does not persist, so all of my access request after login are unauthorized.
I tried testing this in acceptance test by comparing the
$I->getCurrentUrl()
$I->getResponseHeaders()

before and after the redirect.
The currentUrl() return value never gets to the redirect destination, although apache access_logs say otherwise.
getResponseHeaders() returns a PHP_SESSID cookie after the form submission, but it does not exist for all requests after.
Any ideas/guesses why the session created during login is not persisting after the redirect?
Do I need to do any special configuration to Mink sessions to get them to follow the redirect, or am I doing something else wrong?
Thanks in advance for your help!
-Ed

A: I finally figured out the issue.
I had to explicitly set the cookie to be saved for the /Guzzle/Http/Client object in my overwritten _initialize function.
public function _initialize()
{
    $client = new \Behat\Mink\Driver\Goutte\Client();
    $driver = new \Behat\Mink\Driver\GoutteDriver($client);
    $cookiePlugin = new \Guzzle\Plugin\Cookie\CookiePlugin(new \Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar());

    $curl_config = array_merge($this->curl_defaults, $this->config['curl']);
    array_walk($curl_config, function($a, &$b) { $b = "curl.$b"; });
    $curl_config['ssl.certificate_authority']=false;
    $guzzle_client = new \Guzzle\Http\Client('', $curl_config);
    $guzzle_client->addSubscriber($cookiePlugin);

    $client->setClient($guzzle_client);
    $client->followRedirects(true);
    $this->session = new \Behat\Mink\Session($driver);
    \Codeception\Util\Mink::_initialize();
}


text:
Q: jQuery ajax not sending anything I have a site built with CakePHP. I would like to send an HTTP post with jquery ajax (I know that cakePHP has a helper for this but I would like to do it with jQuery because it's more flexible).
My jquery function:
function warrantyqueryPost(ServiceorderSerial, ServiceorderUserId){

    var data = { 'data[Warrantyqueries][serial]' : 123, 'data[Warrantyqueries][user_id]' : 4  }

    var url = '/warrantyqueries/add';

    alert(url);
    $.ajax({
        type: 'post',
        url: url,
        data: data,
        success: function (){
            alert('hat geklappt');
        },
        error: function(){
            alert('nein');
        }
    });

    alert('test');
}

For test purposes key-value pairs are hardcoded (to avoid any mistake). The function is called but the ajax call is not executed. Nothing happens.
The absolute url of the post method is
http://localhost:8080/serviceordersystem/index.php/warrantyqueries/add

I even tried that, no success.
For test reasons I tried a very simple ajax get:
function warrantyquery(ServiceorderSerial, ServiceorderUserId){
    alert('test');
    var url = '/serviceordersystem/index.php';

    var jqxhr = $.get(url, function() {
        alert( "success" );
    })
        .done(function() {
            alert( "second success" );
        })
        .fail(function() {
            alert( "error" );
        })
        .always(function() {
            alert( "finished" );
        });
}

Nothing happens. If I call the address with my browser I get the correct string returned.
Update
For me it really looks like jquery is not working! Stand by, I will check ...

A: Is the url right with this 'index.php' ?
http://localhost:8080/serviceordersystem/index.php/warrantyqueries/add

shouldn't be:
http://localhost:8080/serviceordersystem/warrantyqueries/add

instead ?
You could debug the requisition using Chrome Developer Tools, and see the response code. If the URL is wrong it should return 404. If nothing appears in Chrome DT or Firebug it means your Ajax request is not being fired and it's not a URL problem.

A: Most likely your URL is wrong. You say the absolute path is
http://localhost:8080/serviceordersystem/index.php/warrantyqueries/add

but by using /warrantyqueries/add your URL will result in
http://localhost:8080/warrantyqueries/add

You must use the absolute path in order for this to work.
P.S: From experience I had problems with $.ajax() and http://localhost. You may want to consider using the IP instead if this still fails.

For future debugging you may consider opening your browser console and see for errors and network requests. Also consider expanding your error method.
For example
error: function(jqXHR, textStatus, errorThrown) {
  console.log(textStatus, errorThrown);
}

Taken from http://api.jquery.com/jquery.ajax/

error Type: Function( jqXHR jqXHR, String textStatus, String
  errorThrown )

A: I found out that the linked jquery library was corrupted. Downloaded the library again and now it's working.


text:
Q: Knockout MVC with existing C# code - looping The code in my view -
@{ int tabIndex = 0; }
        @using (var metricGroup = ko.Foreach(m => m.MetricGroups))
        {
            tabIndex++;

 ...

         }

The issue here is for all the divs rendered, the id is always the same - "tabs-1"
instead of that, it should be "tabs-1", "tabs-2", "tabs-3" ...
Can anyone please help me out with this issue?
I have a highly complex view and Knockout MVC is driving me crazy

A: Because of the ko.Foreach your HTML will be generated on the client side, so setting the  your div's id with Razor does not work because the Razor code is executed on server side.
What you need to do is to generate the id's on the client side with Knockout using the $index() binding context property, and the attr binding:
@using (var metricGroup = ko.Foreach(m => m.MetricGroups))
{

 ...

}

The Knockout-Mvc's ko.Bind.Attr method is not working with the GetIndex() method so you need to write out the this Knockout binding expression by hand.


text:
Q: Can I flag a chat message as redundant? I've come across a chat message which, while not offensive in any way, is redundant, as there's a more complete chat message below it. Is it possible to flag it without summoning a SWAT team and getting the person who posted it banned for 15 minutes?

A: What for? Let it stay there. Like with questions and answers, there's no need to flag them if they are not really bad.
While flagging isn't a good option, you can ask a Room Owner to move the redundant message(s) to different room (e.g. Trash room) if others agree it clutters the room without real value.

A: I don't see why it would be relevant to get a chat message that is redundant removed. Generally that would mean that 99 percent of all chat messages could be flagged.
So the answer is no: you can't and shouldn't flag such messages. You could star the other message to make it stand out more.


text:
Q: Wagtail 4.x - how to run code on save draft/publish/moderate (not clean)? Wagtail 4.x question:
On some page models, I have some calculated fields. I run some time/processor intensive methods to return and store the results based on parameters in the page set by the editor on save (publish, draft or moderate).
On previous versions of Wagtail, I'd kick these off from the clean() method of page or form.
With 4.x, the preview is constantly loading, even when hidden, so it's tripping the clean method continuously.
My idea was to move this off to an after_create_page / after_edit_page hook with the following format:
@hooks.register("after_create_page")
@hooks.register("after_edit_page")
def get_calculated_fields(request, page):
    if page.specific_class == SomePage:
        try:
            page.somefield = page.get_somefield_value()
            if page.has_unpublished_changes:
                page.save_revision()
            else:
                page.save()
        except Exception as e:
            some_error_handling()

This seems to work as I want, it only kicks in when one of the actions I want is triggered, and only after the page form has passed the clean(). Save draft saves as revision, publish saves published page.
My concern is if that page save/save_revision logic is sound though or if there are circumstances that this would be a bad idea.
I haven't found anything in the docs about dealing with this. Anyone have experience in 4.x of this and confirm this is the way or if there's a better way of handling this?
Edit: There is the logic in Wagtail docs regarding after_create_page to save the revision then publish if live, but this won't work for existing pages. Following this code, if you save draft on an existing live page, it would publish the draft immediately.


text:
Q: RAM Quantity vs Speed I'm looking to buy some new DDR3 ram for my computer and I have 4 slots on my motherboard with a maximum size of 32GB. In terms of speed, is it better to get 4 8GB ram modules or to get 4 2GB? Or a mix of both?
Edit:
Going to be running Windows 8.1 x64 Pro

A: Other things being equal, more memory is better than less. So 4 8GB modules is the best from a performance standpoint.
Having two modules is a bit faster than four. Two modules means one per channel while four modules means two per channel. With two modules on a channel, it takes a tiny bit of extra time to select the module. So unless you plan to really use more than 16GB, you could use 2 8GB modules.

A: Memory modules of different sizes but otherwise identical specs should have the same speed.
The system is another story. Because of the above, there's no way that that 4 8 GiB modules could be slower than 4 2 GiB modules. If your computer will be faster with 32 GiB of RAM than it would be with 8 GiB depends on whether your system will be using more than 8 GiB, i.e. the applications you will be running.
Most current consumer-level CPUs have a dual-channel memory architecture, meaning that memory modules should always be installed in pairs (2 or 4). As @David Schwartz pointed out, 2 modules should be slightly faster than 4 (although I don't think there would be a noticable difference, but using only two modules also leaves room for future upgrades.
Keeping all of this this in mind, 2 4 GiB modules make sense than 4 2 GiB modules. In addition, they're probably cheaper. The same goes for 2 8 GiB modules vs 4 4GiB modules.


text:
Q: Time complexity for a sorting algorithm I came across the following question while I was doing some exercise:

A sorting algorithm starts from start of the list, scan until two succeeding items that are in the wrong order are found. Swap those items and go back to the beginning. The algorithm ends when the end of the list is reached.
What is the worst-case running time for a list of size n?

I feel that it is similar with bubble sort, but probably worse that that because it doesn't finish the whole pass of scanning the list. But I can't figure out how to calculate its time complexity. I am not sure if the code I came up below for this algorithm is correct. Many thanks for your help!
for (int i=0, i<n , i++){//n is the size of the array
     if (array[i]>array[i+1]){
          swap (array[i], array[i+1]);
          i=0;
     }
}

A: The number of comparisons for the worst case (I wont prove the worst case is n, n-1, ... 1 but I assume it is) is a tetrahedral number.
Why?
imagine a sequence
n, n-1, .... 1

so for 1, will be swap when everything before is already on place. So the number of comparisons when is in the last place will be n-1 before is swapped to the second last place. From the second last place it will have to do n - 2 comparisons. Following this logic, and extending to the previous numbers we have for different n:
In other words, for position n i will need to move one number down (1), from position n - 1 I will need to move 2, (1 & 2), from n-2 (1, 2 & 3). Assuming 1,2,3... n is the valid order and they start as n,...3, 2,1.
n = 3 -> 2 + 1 * 2 = 4
n = 4 -> 3 + 2 * 2 + 3= 10
n = 5 -> 4 + 3 * 2 + 2 * 3 + 4 = 20
n = 6 -> 5 + 4 * 2 + 3 * 3 * 2 * 4 + 5 = 35
n = 7 -> 6 + 5 * 2 + 4 * 3 + 3 * 4 + 2 * 5 + 6 = 56
n = 8 -> 7 + 6 * 2 + 5 * 3 + 4 * 4 + 3 * 5 + 2 * 6 + 7= 84

And this sequence is the tetrahedral numbers.

And as a binomial coeficient:

So, it seems that it is O(n^3)

A: This is a bad form of insertion sort. In insertion sort, the complexity of insertion is linear in the length of the array, here it is quadratic. Hence the worst case time complexity of this algorithm is IMO O(n^3).
If the initial array was 4, 3, 2, 1, then the steps of the algorithm would be:
4 3 2 1
3 4 2 1
3 2 4 1
2 3 4 1
2 3 1 4
2 1 3 4
1 2 3 4

Note that each step in this sequence has a linear time complexity because to get the position of the earliest 'inversion' you scan the entire array from the beginning.

A: An array may contain O(n^2) inversions. Every run corrects only one inversion and executes O(n) steps (comparisons). So overall time complexity is O(n^3).
The worst case - backward-sorted array with N*(N-1)/2 inversions, exact runtime analysis has already been done by Raul Guiu.

A: What you descibe is a bubble sort: http://en.wikipedia.org/wiki/Bubble_sort
Bubble sort has worst-case and average complexity both О(n2)

A: First, this algorithm looks like bubble-sort but slower than that.
Second, this algorithm is doing some non-sense operations, i.e Swap those items and go back to the beginning. For example your initial array is as follows,
10 11 12 13 14 15 16 17 18 19 9

You will iterate till the end, when you see 9, swap it with 18 then go to the beginning of the array and start comparing if(arr[0] < arr[1]) but you already know that it is smaller.
The worst case running time of this is O(n^3). The pseudo code will be something like this:
for i = 0:n-1
    if(arr[i] > arr[i+1]){
        swap(arr[i], arr[i+1])
        i = 0;
    }

A: Now Compare both your Code and Bubble sort because it seems to be..
Your code
It will give Max O(n^3)
Bubble sort
void bubbleSort(int arr[])
{
    int n = arr.length;
    for (int i = 0; i < n-1; i++)
        for (int j = 0; j < n-i-1; j++)
            if (arr[j] > arr[j+1])
            {
                // swap temp and arr[i]
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
}

It will give in worst case O(n^2) and  even if array is sorted.


text:
Q: getting this error "integer expression expected : line 10 and 23" in this bash shell I'm trying to check a number is palindromic or not. I used a function called pal(). I'm getting this error that says:
./pal.sh: line 10: [: input: integer expression expected
./pal.sh: line 23: [: input: integer expression expected

My code:
#!/bin/bash

pal()
{
  num=$1
  rnum=$num
  add=0
  k=0

  while [ $num -ne 0 ]
  do
    lev=1
    mod= $num % 10
    for((i=0;i<$k;i++))
    do
      lev=`expr $lev \* 10`
    done
    mul=`expr $mod \* $lev`
    add=`expr $add + $mul`
    num=`expr $num / 10`
    k=`expr $k + 1`
  done
  if [ $rnum -eq $add ]
  then
    echo "pallindrome"
  else
    echo "not pallindrome"
  fi

}
echo "input number"
read input
pal input

A: You need to pass the value of the variable, not its name:
pal $input

Also, as anubhava points out in a comment, you will need to fix the arithmetic in the function:
mod= $num % 10

should be:
mod=$(($num % 10))

or:
((mod = $num % 10))

You should also generally avoid using expr in bash — there are built-in facilities to handle pretty much anything expr can handle.

A: You can do this with the rev from "util-linux" like so,
#!/bin/bash
pal()
{
  input=$1
  if [ $input == $(echo $input | rev) ]; then
    echo "pallindrome"
  else
    echo "not pallindrome"
  fi
}
echo "input number"
read input
pal $input

Output
$ ./pal.sh
input number
101
pallindrome
$ ./pal.sh
input number
102
not pallindrome


text: Q: How can I directly get battery status in battery status in cordova? I tried cordova-plugin-battery-status plugin to get my mobile current battery level. It's working fine when the battery level is changed. But I really want the status at my first call. Is there any solutions? or I should develop my app in native?


text:
Q: Is there a way to make `docker` output the HTTP requests sent to the daemon, just like it's possible with `kubectl` and the API server? I've been using kubectl -vvvv ... a lot to learn about the different HTTP requests sent to the API server for different commands.
However, I cannot seem to find a way of achieving the same with docker.
In particular, I've considered docker --debug ..., but e.g. docker --debug ps just displays the normal output.
How can I make docker output the HTTP requests sent to the daemon?

A:
How can I make docker output the HTTP requests sent to the daemon?

You can't, but you can set up a proxy server between the client and the docker daemon so that you can see the requests. The socat tool is useful for this. Set up a proxy by running:
socat -v unix-listen:/tmp/docker.sock,fork unix-connect:/var/run/docker.sock

And then point docker at the proxy:
docker -H unix:///tmp/docker.sock ps

As you make requests with docker, you'll see the requests and replies in the output from the socat command.
(You can set the DOCKER_HOST environment variable if you get tired of typing the -H ... command line option.)


text:
Q: Java Spring boot - Issue using entities from Oracle Sql Using Intellij i've connected to an oracle database, added persistency framework and generated persistence mapping by database schema
package springoraclesql.demo.domain;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Book {
private long bookId;
private String bookName;
private String bookAuthor;
private Long bookPrice;

@Id
@Column(name = "BOOK_ID")
public long getBookId() {
    return bookId;
}

public void setBookId(long bookId) {
    this.bookId = bookId;
}

@Basic
@Column(name = "BOOK_NAME")
public String getBookName() {
    return bookName;
}

public void setBookName(String bookName) {
    this.bookName = bookName;
}

@Basic
@Column(name = "BOOK_AUTHOR")
public String getBookAuthor() {
    return bookAuthor;
}

public void setBookAuthor(String bookAuthor) {
    this.bookAuthor = bookAuthor;
}

@Basic
@Column(name = "BOOK_PRICE")
public Long getBookPrice() {
    return bookPrice;
}

public void setBookPrice(Long bookPrice) {
    this.bookPrice = bookPrice;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Book book = (Book) o;

    if (bookId != book.bookId) return false;
    if (bookName != null ? !bookName.equals(book.bookName) : book.bookName != null) return false;
    if (bookAuthor != null ? !bookAuthor.equals(book.bookAuthor) : book.bookAuthor != null) return false;
    if (bookPrice != null ? !bookPrice.equals(book.bookPrice) : book.bookPrice != null) return false;

    return true;
}

@Override
public int hashCode() {
    int result = (int) (bookId ^ (bookId >>> 32));
    result = 31 * result + (bookName != null ? bookName.hashCode() : 0);
    result = 31 * result + (bookAuthor != null ? bookAuthor.hashCode() : 0);
    result = 31 * result + (bookPrice != null ? bookPrice.hashCode() : 0);
    return result;
}
}

I've added the Oracle jdbc and my persistence.xml under java/META-INF looks like this`

<persistence-unit name="NewPersistenceUnit">
    <class>springoraclesql.demo.domain.Book</class>
    <properties>
        <property name="toplink.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:XE"/>
        <property name="toplink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
        <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:XE"/>
        <property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver"/>
        <property name="openjpa.ConnectionURL" value="jdbc:oracle:thin:@localhost:1521:XE"/>
        <property name="openjpa.ConnectionDriverName" value="oracle.jdbc.OracleDriver"/>
        <property name="eclipselink.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:XE"/>
        <property name="eclipselink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
    </properties>
</persistence-unit>

My application.properties looks like this
oracle.dbsource.url=jdbc:oracle:thin:@localhost:1521:xe
oracle.dbsource.username=talon
oracle.dbsource.password=talon
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.name=talon
spring.datasource.password=talon
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect

When I run the spring project I have many java.sql.SQLException: ORA-01017: invalid username/password; logon denied errors. But the url, username and passwords are correct.
2018-01-12 13:05:06.521 ERROR 10220 --- [           main] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.
java.sql.SQLException: ORA-01017: invalid username/password; logon denied
...
2018-01-12 13:05:06.536  WARN 10220 --- [           main] o.s.b.a.orm.jpa.DatabaseLookup           : Unable to determine jdbc url from datasource
org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: ORA-01017: invalid username/password; logon denied
...
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: ORA-01017: invalid username/password; logon denied

at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80) ~[spring-jdbc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:326) ~[spring-jdbc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
... 61 common frames omitted
Caused by: java.sql.SQLException: ORA-01017: invalid username/password; logon denied
...
2018-01-12 13:05:06.568 ERROR 10220 --- [           main] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.
java.sql.SQLException: ORA-01017: invalid username/password; logon d
...
2018-01-12 13:05:07.169 ERROR 10220 --- [           main] org.hibernate.hql.spi.id.IdTableHelper   : Unable obtain JDBC Connection
java.sql.SQLException: ORA-01017: invalid username/password; logon denied
...
2018-01-12 13:05:07.191  INFO 10220 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-01-12 13:05:07.438  INFO 10220 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice:    org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@75f9eccc: startup date [Fri Jan 12 13:05:04 CET 2018]; root of context hierarchy
2018-01-12 13:05:07.486 ERROR 10220 --- [           main] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.
java.sql.SQLException: ORA-01017: invalid username/password; logon denied

Before I've tried connecting to the same schema using DriverManager.getConnection and I don't have any issue retrieving data that way.

A: I was using spring.datasource.name instead of spring.datasource.username


text:
Q: Populate a case class from a DB ResultSet I have the following code that I am using to retrieve data from a database and then populate a class.
If the column names and the class properties are identical is there a more elegant way of populating the class other than the two step process I currently have - of (1) creating variables and then (2) populating the object with the variables?
As you can appreciate when the class has many properties - there is a lot of doubled-up code to be typed that I would like to avoid.
Updated :
Thanks for the suggestion to use Doobie / Anorm / etc. : But I deliberately want to hand write the persistence layer as a Scala / FP learning exercise.
it is also my understanding that macros are changing in Scala 3 - which isn't too far away, now - so I'd rather have a solution that is applicable after the upgrade; Thanks!
def getGroups(): Vector[Group] = {

    def createGroup(groupname: String) = {
      Group(groupName = groupname
            ...
            ...
            ...
      )
    }

    // Get the rows returned from the database.
    val dbResults = Try { selectAllFromTable("groups") }

    dbResults match {
      case Success(rs) => {
        // Create an Iterator[]
        ResultSetUtils.toIterator(rs) { rs =>
          createGroup(
            rs.getString("groupname")
            ...
            ...
            ...
          )
        }
      }.toVector

      case Failure(ex) =>
        Vector.empty[Group]
    }
  }

A: Thanks Ygor,
I finally worked out what you were saying and got rid of the createGroup method. which of course meant I was no longer "double-typing" the case class creation and population.
Now I just have;
def getGroups(): Vector[Group] = {

    // Get the rows returned from the database.
    val dbResults = Try { selectAllFromTable("groups") }

    dbResults match {
      case Success(rs) => {
        // Create an Iterator[]
        ResultSetUtils.toIterator(rs) { rs =>
          Group(
            rs.getString("groupname")
            ...
            ...
            ...
          )
        }
      }.toVector

      case Failure(ex) =>
        Vector.empty[Group]
    }
  }


text:
Q: Amazon Device Messaging is crashing runtime, on android emulator, how to fix it? Almost all the answers available on stackover, I have already tried in last 5-6 hours, please don't mark duplicate :)
I have referred Amazon Device Messaging documentation for integration into my android project, everything compiles fine but when I run this project it crashes with a message
    FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.MainActivity}: java.lang.RuntimeException:
Stub! You are bundling a stubbed jar in the apk! Please move it to the classpath instead.

I have use the approach "Gracefully Degrade If ADM Is Unavailable" by marking in AndroidManifest.xml like below
<!-- You must explicitly enable ADM. You must also declare whether your application will run with or without ADM.
        If you specify android:required="false", your app must degrade gracefully when ADM is unavailable. -->
        <amazon:enable-feature android:name="com.amazon.device.messaging"
            android:required="false" />

Also, inside file MainActivity i am checking the availability of ADM like the below code
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //some other codes here
    boolean admAvailable = false;
    try {
        Class.forName( "com.amazon.device.messaging.ADM" );
        admAvailable = true ;
    }
    catch (ClassNotFoundException e) {
        // Handle the exception.
    }
    if(admAvailable) {
        ADMManifest.checkManifestAuthoredProperly(getApplicationContext());
    }
}

Github link of my demo app


text:
Q: Access token valid for one day only I am using server-side flow for authenticating users in my App. Most of the users are getting a 60-day valid token. However, recently there are few users whose tokens are valid only for 24 hours (Not 1 or 2hours which is the case with short-lived tokens).
Due to this problem users are stopping usage of the App as they have to authenticate every day in order to continue using it.
Any help would be much appreciated.
Thanks


text:
Q: How do a query to find by Id using DBRef in MongoDB? How do a query to find by Id using DBRef in MongoDB ?
The documents of Student collection are:
{
    "_id" : ObjectId("59bc49ef962d7420843331b7"),
    "first_name" : "Anthony",
    "last_name" : "McKelly",
}
{
    "_id" : ObjectId("59bc49f0962d74198d421a6d"),
    "first_name" : "John",
    "last_name" : "Doe",
}
{
    "_id" : ObjectId("59bc49f0962d742048757807"),
    "first_name" : "Peter",
    "last_name" : "Parquer",
}
{
    "_id" : ObjectId("59bc49f0962d742048757818"),
    "first_name" : "Katy",
    "last_name" : "Jackson",
}
{
    "_id" : ObjectId("59bc49f0962d74204d270ff3"),
    "first_name" : "Mary",
    "last_name" : "Petrova",
}

This is a part of the Queue collection:
{
    "_id" : ObjectId("59bc49ef962d7420843331c6"),
    "student" : DBRef("students", ObjectId("59bc49ef962d7420843331b7"), "school"),
    "groupid" : "59aeda24962d740934127b82"
}
{
    "_id" : ObjectId("59bc49f0962d74198d421a7c"),
    "student" : DBRef("students", ObjectId("59bc49f0962d74198d421a6d"), "school"),
    "groupid" : "59aeda24962d740934127b82"
}
{
    "_id" : ObjectId("59bc49f0962d742048757816"),
    "student" : DBRef("students", ObjectId("59bc49f0962d742048757807"), "school"),
    "groupid" : "59aeda24962d740934127b82"
}
{
    "_id" : ObjectId("59bc49f0962d742048757827"),
    "student" : DBRef("students", ObjectId("59bc49f0962d742048757818"), "school"),
    "groupid" : "59aeda24962d740934127b82"
}
{
    "_id" : ObjectId("59bc49f0962d74204d271002"),
    "student" : DBRef("students", ObjectId("59bc49f0962d74204d270ff3"), "school"),
    "groupid" : "59aeda24962d740934127b82"
}

I need know how access to student data across the DBRef in the Queue collection using a query.
This not work:
db.queue.find({student.id : '59bc49ef962d7420843331b7' })
db.queue.find({student._id : ObjectId("59bc49f0962d742048757807") })

Please any help I am very grateful.


text:
Q: What is the macro definition of isupper in C? I want to know how the "isupper" macro is defined in C/C++. Could you please provide me the same or point me to available resources. I tried looking at ctype.h but couldnt figure it out.

A: It's implementation-specific. One obvious way to implement it would be:
extern char *__isupper;
#define isupper(x) ((int)__isupper[(x)])

Where __isupper points to an array of 0's and 1's determined by the locale. However this sort of technique has gone out of favor since accessing global variables in shared libraries is rather inefficient and creates permanent ABI requirements, and since it's incompatible with POSIX thread-local locales.
Another obvious way to implement it on ASCII-only or UTF-8-only implementations is:
#define isupper(x) ((unsigned)(x)-'A'<='Z'-'A')

A: It's a function, not a macro. The function definition of isupper() differs depending on things like locale and the current character set - that's why there's a function specifically for this purpose.
For ASCII, because of the way the letters are assigned, it's actually quite easy to test for this. If the ASCII code of the character falls in between 0x41 and 0x5A inclusive, then it is an upper case letter.

A: It's implementation defined -- every vendor can, and usually does, do it differently.
The most common usually involves a "traits" table - an array with one element for each character, the value of that element being a collection of flags indicates details about the character.  An example would be:
 traits[(int) 'C'] = ALPHA | UPPER | PRINTABLE;

In which case,, isupper() would be something like:
 #define isupper(c) ((traits[(int)(c)] & UPPER) == UPPER)

A: It's actually fairly complicated, in GCC for instance.  But a simple implementation of isupper could be (although it has a double-evaluation bug) most simply defined as:
#define isupper(c) (c >= 'A') & (c <= 'Z')
http://ideone.com/GlN05
GCC specifically checks bit 0 is 1 in the character for the current locale:
(*__ctype_b_loc ())[(int) (c)] & (unsigned short int) (1 << (0))
Where __ctype_b_loc() is a function that returns a pointer into an array of characters in the current locale that contains characteristics for each character in the current character set.


text:
Q: CS50 Mario (More Comfortable) Error. why are my Pyramids not Aligning properly? what is wrong with my code? when I run both of them individually, the Pyramids align properly but after I remove the //sign to run them together, my pyramids get screwed up. Please what am I doing wrong?
#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int H;
    //Ask for Height of Pyramid
    do {
        H = get_int("Height Please: ");

    } while (H<=0 || H > 8);
    for (int x=0;  x < H; x++)
        {
        // Create left Aligned Pyramid
           for (int y = 0; y < H; y++)
                   if (x + y < H - 1)
                      printf(" ");
                  else
                      printf("#");
                      printf("\n");

        // Create Right Aligned Pyramid
           for (int y = 0; y < H; y++)
                if (x-y>=0)

                       printf(" "); //Space in Between both Pyramids
                       printf("#");

                 else
                      printf(" ");
                     printf("\n");
    }

}

A: Let's start with the first problem: You really should be using curly-braces to explicitly encapsulate your loops and if-else statements, otherwise only the subsequent statement will be a part of it.  For example:
if (condition)
    goto fail;
    goto fail;

Only the first goto fail; is a part of the if-statement; the second one is in actuality a separate entity even though it is indented as if it were a part of the if-statement.  (See this for a breakdown of the real-life bug in Apple code this example is based on: https://dwheeler.com/essays/apple-goto-fail.html )
So get your braces right and indenting right so the code does what it looks like it is doing.
Secondly, you're printing a newline between your logic that prints the first pyramid and second pyramid, so they could never exist side-by-side.  That newline is where you should be inserting that extra space character, not in the logic of your second pyramid.
#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int H;
    //Ask for Height of Pyramid
    do {
        H = get_int("Height Please: ");

    } while (H<=0 || H > 8);

    for(int x = 0; x < H; x++) {
        // Create left Aligned Pyramid
        for(int y = 0; y < H; y++) {
            if (x + y < H - 1) {
                printf(" ");
            }
            else {
                printf("#");
            }
        }

        printf(" ");    // With the curly braces and indentation fixed, we can clearly see this is not part of the logic of the first pyramid, but rather between the first and second pyramids where a space should be

        // Create Right Aligned Pyramid
        for(int y = 0; y < H; y++) {
            if (x - y >= 0) {
                printf("#");
                // remove the space character that did not belong here and was causing compile errors when you failed to use curly braces
            }
            else {
                printf(" ");
            }
        }

        printf("\n");   // Much easier to see where this logic comes into play with curly braces and indentation fixed.

    }
}

Sample output (hardcoded H=4):
   # #
  ## ##
 ### ###
#### ####


text:
Q: How to monitor older query history and query plan in Azure Synapse Dedicated pool I am trying to query the dmv's sys.dm_pdw_exec_requests and sys.dm_pdw_sql_requests. But they don't seem to be showing historic queries. I want see the queries which ran yesterday, analyze there query plan, resource class and memory used etc.

A: Not sure if you still need an answer to this but sys.dm_pdw_exec_requests only keeps information for the most recent 10,000 queries. Depending on the workloads your running that could mean it only is holding a few hours worth and pause and unpause will blow that out as well.
For long term tracking we were able to keep some of that information using this synapse tool box - https://github.com/microsoft/Azure_Synapse_Toolbox
It won't help with everything you want to look back on such as the query plans but it is useful. Once you get the dashboard setup along with log analytics you can at least get some insight into what happened the prior day(s). Using this we found concurrency to be one of our major issues that we needed to resolve.


text:
Q: Yii2 give array fields names and save to database Can I give each item that will be saved to an array and then to a database a name.
For example say I have three form fields which will be saved to the same array.
Can I setup my fields like below or if below is not correct what is the best way to do it?
echo $form->field($model, 'arrayfields')->textinput([
    'name'=>'field1inarray[]',
]);

echo $form->field($model, 'arrayfields')->textinput([
    'name'=>'field2inarray[]',
]);

echo $form->field($model, 'arrayfields')->textinput([
    'name'=>'field3inarray[]',
]);

Also how do I go about saving the array to my database in my controller/model?

A: I used the below in my view
<?= $form->field($model, 'example[arrayfield1]')->textInput(['maxlength' => 255])->label('Array Field 1') ?>

<?= $form->field($model, 'example[arrayfield2]')->textInput(['maxlength' => 255])->label('Array Field 2') ?>

And then within my controller to save to database did the following
    public function actionCreate()
{
    $model = new someModel();

    if ($model->load(Yii::$app->request->post())) {
        $array = $_POST['someModel']['example'];
        $model->stockists = json_encode($array);
        $model->save();
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

Open to code improvements, need to add some validation to check whether or not a post value exists.
Now I need to work a way for the value to be populated in my update form.


text:
Q: PHP - Looking for a two way obfuscation method for storing phone numbers I'm looking to store (in mySQL) an obfuscated version of a phone number, where the number is used for authentication (I need to be able to get back the original number).
I've thought about an arbitrary scheme like storing the number * 15 or some constant only my app knows.
What are some better ways of doing this?
EDIT: Some things I'd like to clarify:

*

*The phone numbers that are saved can be used to log into an iPhone app - so I want users to be able to see which number they have connected to the service incase they want to log into the app with a different number later. This means I cannot hash the value.

*Essentially I am looking for a way to protect the data if someone lifts my database that they don't have a bunch of phone numbers in raw form. So I'd like to obfuscate them so I can use them for authentication, but be able to get one back in its original form without storing it raw.
EDIT: To clarify, I am not authenticating on JUST the phone number. If implemented, it would be phone number + a password! Enter a single string of digits that may exist and you're in? lol - my apologies if I have misled some folks.

A: Store where? In a database? Use an encryption function rather than rolling your own system.
In MySQL it'd be as simple as:
INSERT INTO users (phone) VALUES (AES_ENCRYPT('yourkey', '867-5309'));

of course, now you're changed the problem from hiding the phone numbers to "where the @$@#$@# can I hide this key?". Obvious solution: hide the key under a rock outside your server's front-door. Which changes the problem into "where the @#@#$@#@% can I hide this rock?". Obvious solution: cover your front yard with a steel cage with a padlock on the door. New problem: how to hide the padlock key... and so on.

A: How about actual encryption? In this scenario, a good symmetric encryption algorithm is trivial, since the length of the payload is limited to, what, 10 digits, so you can get by with a key that's also 10 decimal digits long; using such a key, all you need to do is something like XOR or increment / mod 10 on each digit. Of course, the weak link in this scheme then is the way you store the key.
I am curious, however, why you need to get them back out - if it's for authentication:

*

*you shouldn't be using phone numbers, as these are easy to look up, even automatically

*you should be storing secure one-way hashes with individual salts, so you couldn't even get them back out youself if you wanted to (except by brute-forcing)

A: Using the Cipher Class you can do this:
$phone = '...';
$key = 'secret.for.each.number';
$phone = Cipher::encrypt($phone, $key);

Before you store it in the database. Then later you can pull it out and do this:
$phone = Cipher::decrypt($phone, $key);

A: A better way would be not doing that. There is a reason one-way encryption is used to store passwords.
If you need to get back the original value, you should not be using it for authentication, since it will invariably be easy for an attacker to find it.
If you feel you need to hide the value by obfuscating it, you probably need to change something fundamental about how you're storing the data.

A: This isn't a very good approach to security. Several things jump out at me:

*

*Phone numbers are very easy to guess: just program something to start guessing random combinations. Encrypted or not, your program is validating using these numbers, so it will eventually work on some. You need an extra layer of security like a password known only to the user in question. I would recommend anti-brute-force attack measures as well.

*Any two-way encryption can be cracked, it is as simple as that. If you need to be able to decrypt data in the database easily, the only benefit from encrypting it is if someone hacks into your database and grabs the information. As others have pointed out, if that happens, you have bigger issues. The other scenario is for staffers who could have valid access to the DB. If you are hiding the data from them, it is important to encode the information in some way. But multiplying the phone number by a "unknown" constant is not ideal. Use a better method.

*Surely I know my friend's numbers, so I could hack into anyone's account, correct? You need to add a password component if you haven't already. The password should be 1-way encryption using a strong and unique SALT. Once added, you only need to encrypt phone numbers in the DB if you don't want your staffers to see them. Otherwise you are wasting time encrypting them.

A: There is no point in this question.
Just leave these phone numbers as is. You will gain no security improvement from such obfuscation


text:
Q: Android: How to tell whether month comes before day Application: a digital clock. I want to know whether the current date should be displayed as mm.dd.yy or dd.mm.yy for the current locale. Bonus points for identifying yy.mm.dd cases. (I an perfectly content to not support non-Gregorian calendars).
So for example: Should January 31, 2019 be displayed as 01.31.19, or 31.01.19.
Being able to get a short date format string would suffice.  i.e.  "MM/dd/yy", or "yy.MM.dd".
I've rummaged through DateFormat, and SimpleDateFormat (the latter of which has what I need in the pattern private member, but doesn't provide public access). But as usual, date support in Java is infuriatingly... complicated. :-(


text:
Q: Array, avoid pulling Duplicates, simple code, C++ Its a card game, I draw 2 cards from the deck (the array) with the help of two functions.
Each element of the array represent one card with a symbol Spades, Hearts, Diamonds or Clubs.
These numbers in the array \5 \4 \3 \6, represent Clubs, Dimaond, Heatrs, spades (just if ur curious)
The problem!
When I draw a card two times I sometimes get Duplicates.. The same card twice.
How do I make sure the same card cant be drawn twice?
How do I avoid getting duplicates??
This is how the code Looks like.
Some INFO about the array...
The further in, in the array, the higher value the element has.
I have shortened the array... for easy testing of a solution... later the array will be 52 elements.
array<string, 3> cards = { "Ess \5", "Ess \4", "Ess \3" };

//The function.
pair<string, int> draw_card()
{
    int random_index = rand() % 52;
    string card = cards[random_index];
    return { card, random_index };
}

int main()
{
// Seed, random.
 srand((unsigned int)time(NULL));

// Calling the function 2 times.
    pair<string, int> you_drew = draw_card();
    cout << "You drew: " << you_drew.first << endl;

    pair<string, int> comp_drew = draw_card();
    cout << "Computer drew: " << comp_drew.first << endl;

// Deciding the winner.
    int your_score{ 0 };
    int the_computers_score{ 0 };

    if (you_drew.second > comp_drew.second) {
        cout << "You Won!" << endl;
        your_score++;
    }
    else if (you_drew.second < comp_drew.second) {
        cout << "You Lost!" << endl;
        the_computers_score++;
    }

        return 0;
   }

Everything is working fine, EXCEPT sometimes I get duplicates... I want to make sure I can Not get that...
Somehow when I draw a card the element in the array should not be able to be drawn.. I want to avoid getting duplicates. Please help me!
Shouldnt something like this work? its not but.. shouldnt it?
pair<string, int> comp_drew = draw_card();

        if (you_drew == comp_drew) {
            bool run8 = true;
            while (run8) {
                pair<string, int> comp_drew = draw_card();

                if (comp_drew != you_drew) {
                     cout << "Computer drew: " << comp_drew.first << endl;
                    run8 = false;
                }
            }

        }

Or maybe another solution..
Perhaps after calling the function one time i can delete the return index from the array?

A: You can swap the drawn card to the end and only choose an index smaller than 51 the next time.
int array_len = 52; // global variables are not great, but it's easier here
pair<string, int> draw_card()
{
    int random_index = rand() % array_len;
    --array_len;
    string card = cards[random_index];
    std::swap(cards[random_index], cards[array_len]);

    return { card, random_index };
}

A: There are many different ways to do this.
std::random_shuffle
#include <iostream>
#include <algorithm>

using namespace std;

class CardMachine {
    static unsigned constexpr DECK_SIZE = 4;
    int cards[DECK_SIZE] = {1,2,3,4};
    int lastUsedCardIndex = -1;
public:
    int getCard() {
        if (lastUsedCardIndex == DECK_SIZE - 1)
            shuffle();
        return cards[++lastUsedCardIndex];
    }

    void shuffle() {
        random_shuffle(begin(cards), end(cards));
    }
};

int main()
{
    CardMachine cardMachine = CardMachine();

    cout << "unhsuffled - 1,2,3,4 without duplicates:" << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;

    cout << "Shuffled. Random order, and still no duplicates:" << endl;
    cardMachine.shuffle(); // or call getCard which can shuffle
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;

    return EXIT_SUCCESS;
}

Mark Card as Taken
#include <iostream>
#include <random>

using namespace std;

class CardMachine {
    static unsigned constexpr DECK_SIZE = 4;
    inline static int constexpr cards[DECK_SIZE] = {1,2,3,4};
    bool cardIsGone[DECK_SIZE] = {false, false, false, false};
public:
    int getCard() {
        while(true) {
            int const RANDOM_INDEX = rand()%DECK_SIZE;
            if(!cardIsGone[RANDOM_INDEX]) {
                cardIsGone[RANDOM_INDEX] = true;
                return cards[RANDOM_INDEX];
            }
        }
    }

    void shuffle() {
        for(bool &isGone : cardIsGone)
            isGone = false;
        lastUsedCardIndex = -1;
    }
};

int main()
{
    CardMachine cardMachine = CardMachine();

    cout << "Shuffled - Random order, and still no duplicates:" << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;

    cout << "Shuffled. Random order, and still no duplicates:" << endl;
    cardMachine.shuffle(); // Causes infinite loop if you call getCard DECK_SIZE + 1 times
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;

    return EXIT_SUCCESS;
}

It's not the most efficient solution, but with small values like 52, it should be instant.
Swap Used Cards to Back and Keep Track of Range
#include <iostream>
#include <random>

using namespace std;

class CardMachine {
    static unsigned constexpr DECK_SIZE = 4;
    int cards[DECK_SIZE] = {1,2,3,4};
    int lastCardIndexExlusive = DECK_SIZE;
public:
    int getCard() {
        int const RANDOM_INDEX = rand()%lastCardIndexExlusive;
        swap(cards[RANDOM_INDEX],cards[lastCardIndexExlusive - 1]);
        return cards[--lastCardIndexExlusive];
    }

    void shuffle() {
        lastCardIndexExlusive = DECK_SIZE;
    }
};

int main()
{
    CardMachine cardMachine = CardMachine();

    cout << "Shuffled - Random order, and still no duplicates:" << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;

    cout << "Shuffled. Random order, and still no duplicates:" << endl;
    cardMachine.shuffle(); // Causes exception if getCard DECK_SIZE + 1 times
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;

    return EXIT_SUCCESS;
}

Remember Last Card
#include <iostream>
#include <random>

using namespace std;

class CardMachine {
    static unsigned constexpr DECK_SIZE = 4;
    int cards[DECK_SIZE] = {1,2,3,4};
    int lastCard = -1;
public:
    int getCard() {
        int const RANDOM_INDEX = rand()%DECK_SIZE;
        if (lastCard == RANDOM_INDEX) {
            return getCard();
        }
        lastCard = cards[RANDOM_INDEX];
        return lastCard;
    }

    void shuffle() {
        lastCard = -1;
    }
};

int main()
{
    CardMachine cardMachine = CardMachine();

    cout << "Shuffled - Random order, and still no duplicates, but only able to produce 2:" << endl;
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;

    cout << "Shuffled. Random order, and still no duplicates:" << endl;
    cardMachine.shuffle(); // Causes potential duplicates if getCards 3+ times
    cout << cardMachine.getCard() << endl;
    cout << cardMachine.getCard() << endl;

    return EXIT_SUCCESS;
}

All of these solutions make use of a class to hold state for use in getCard to make sure we get the right behavior.


text:
Q: initializing variables in swiftUI I am new to swiftUI and heard it's the shortest path to app development. But I'm having some difficulties with assigning a value to a variable. The following snippet is where I'm perplexed.
self.phone = fetcher.customer!.phone
print( self.phone )                <-- Empty string
print( fetcher.customer!.phone )   <-- 555-555-5555

And full view:
struct WithCustomer: View {
    @ObservedObject var fetcher: CustomerFetcher
    @State private var first_name: String = ""
    @State private var last_name: String  = ""
    @State private var email: String      = ""
    @State private var phone: String      = ""

    init( fetcher: CustomerFetcher ) {
        self.fetcher    = fetcher
        self.first_name = fetcher.customer!.first_name
        self.last_name  = fetcher.customer!.last_name
        self.email      = fetcher.customer!.email
        self.phone      = fetcher.customer!.phone
        print( self.phone )
        print( fetcher.customer!.phone )
    }
    var body: some View {
        NavigationView {
            Form {
                TextField("First name", text: self.$first_name)
                TextField("Last name",  text: self.$last_name )
                TextField("email", text: self.$email )
                TextField( "phone", text: self.$phone )
            }.navigationBarTitle(Text("Profile"))
        }
    }

}

I'm sure I'm just forgetting to force a coercive unwrap  on the views second instantiation of the super class or something but any help would be appreciated. Thanks.

A: State properties should be initialised differently. Here is an example for phone
struct WithCustomer: View {
    @ObservedObject var fetcher: CustomerFetcher

    // ... other state should be declared similarly

    @State private var phone: String   // << no assign, only declare

    init( fetcher: CustomerFetcher ) {
        self.fetcher    = fetcher

        // ... other state should be initialised similarly

        self._phone = State(initialValue: fetcher.customer!.phone)
    }

    // .. other code


text:
Q: I'm trying to call the selected class in the class method So, I am working on a school project and it's all going well except I have to call a function that requires a class as an argument. I need the function in a class method and I was wondering how do you fill in the argument? I will leave a sample code below
#include <iostream>

using namespace std;

class x
{
public:
    int x = 0;
    void f();
};

void g(x aux)
{
    cout << aux.x << endl;
}

void x::f()
{
    g(); //Here is the problem
}

int main()
{
    x a;
    a.f();
    return 0;
}

A: Do you have successfully compile? Your member of class was named as class - X.


text:
Q: How to interpret Law of conservation of strangeness? Is there a recent explanation of Law of conservation of strangeness? and why does it not work for reactions taking long times like $10^{-10}$ seconds?

A: It isn't true that processes that change the strangeness can't be faster than $10^{-10}$ seconds. For example a top quark can decay into a strange quark, which changes the strangeness by $+1$, and that takes around $5 \times 10^{-25}$ seconds. However it is mostly true, and this is why.
Incidentally you might want to have a look at the Wikipedia article on strangeness, where the conservation of strangeness is discussed.
Strangeness is the net number of strange quarks i.e. the number of strange quarks minus the number of antistrange quarks. There are no processes involving the strong and electromagnetic forces that can change the net number of strange quarks, or indeed any other types of quark. They can only create or destroy strange-antistrange pairs, and this leaves the strangeness unchanged.
Weak interactions can change the net number of strange quarks, but they are usually (relatively) slow. So for example the strange quark decay to an up quark and $W^-$ boson via the weak force takes around $10^{-10}$ seconds. This is the reason for the time limit that you mention. Most processes that take less than $10^{-10}$ seconds involve only the strong and EM forces and therefore those processes can't change the strangeness.

A:
How to interpret Law of conservation of strangeness?

There is no such law. See the Wikipedia article: "Noting that collisions seemed to always produce pairs of these particles, it was postulated that a new conserved quantity, dubbed 'strangeness', was preserved during their creation, but not conserved in their decay".

Is there a recent explanation of Law of conservation of strangeness? and why does it not work for reactions taking long times like $10^{−10}$ seconds?

I don't currently know of a satisfactory explanation for the preservation of strangeness during particle creation. Because I can't currently explain what strangeness is. Strangeness was introduced because some particles such as kaons took longer to decay than others. As for how this actually works, I can't say in a fashion that will satisfy you. The Wikipedia article says this: "The strange antiquark of the kaon transmutes into an up antiquark by the emission of a W+ boson; the W+ boson subsequently decays into a down antiquark and an up quark". But there's no explanation of how or why this happens, and no explanation of how it can happen when the W+ boson has a mass of 80GeV, which is far more than the kaon or the resultant pions. And there's no explanation as to why a billionth of a second later, all the strangeness is gone. Sorry.


text:
Q: Trouble with edit button for To Do App JavaScript I tried creating an edit button for editing a created task, and it works for the very first task that i create.

*

*However for subsequent tasks, the edit button for the respective tasks focus on editing the input on my first task again.

*For every new task created, it changes the first task back to the very first original task that was written.

     To-Do List

TO-DO APP

CREATE A TO-DO

     <form id="todo-form">

                 <input class="form-control" name="newTask" type="text" placeholder="eg. Do the laundry">

CATEGORY

                 <input type="radio" class="btn-check" name="category" id="option1" value="Work">
                 Work

                 <input type="radio" class="btn-check" name="category" id="option2" value="Personal">
                 Personal

<button type="submit" class="btn btn-secondary p-2 w-100 add-task" active>ADD TO-DO</button>

     </form>

TO-DO LIST

Javascript
const todoForm = document.getElementById("todo-form")

window.addEventListener("load", () => {
    todos = JSON.parse(localStorage.getItem("todos")) || []

    todoForm.addEventListener("submit", (e) => {
        e.preventDefault()
        if (e.target.elements.newTask.value != "") {
            const todo = {
                task: e.target.elements.newTask.value,
                category: e.target.elements.category.value
            }

            todos.push(todo);

            localStorage.setItem("todos", JSON.stringify(todos));

            e.target.reset()

            showList()
        }
    })

    showList();
})

function showList() {
    let outPut = '';
    let taskListShow = document.querySelector(".todoList")
    const taskName = document.querySelector(".todoContent")

    todos.forEach((data, index)=> {

        outPut += `

                <input class="todoContent no-border text-white text-center" value="${data.task}" readonly>

                        <button type="button" class="btn btn-secondary col-12" onClick="editItem()">Edit</button>

                        <button type="button" class="btn btn-danger col-12" onClick="deleteItem(${index})">Delete</button>

`
    });
    taskListShow.innerHTML = outPut;
}

function deleteItem(index) {
    todos.splice(index, 1)
    localStorage.setItem("todos", JSON.stringify(todos))
    showList()
}

function editItem() {
    const taskName = document.querySelector(".todoContent")
    taskName.removeAttribute('readonly')
    taskName.focus()
    taskName.addEventListener("blur", (e) => {
        taskName.setAttribute('readonly', true)
        taskName = e.target.value
        localStorage.setItem('todos', JSON.stringify(todos))
        showList()
    })
}

How can make this work?

A: Since all of the input class will have todoContent and when you look for a class using querySelector then JS will return you the first matching element with class todoContent.
const taskName = document.querySelector(".todoContent")

CODESANDBOX LINK
What you can do is look for all of the element with class todoContent and then take the particular input on which you have clicked by using the index of the clicked edit button as:
function editItem ( index ) {  // RECEVIVE INDEX
const taskAllName = document.querySelectorAll( ".todoContent" );
const taskName = taskAllName[index];  // USE SPECIFC ELEMENT

So you have to pass the index to function editItem as:
onClick="editItem(${index})">Edit</button>


text:
Q: Quartz run job again N minutes after completed I have some repeating quartz jobs that use SimpleScheduleBuilder.repeatMinutelyForever(60). Lets say the job initially gets scheduled at 10:02am and runs for 5 minutes completing at 10:07am.
Right now it is getting scheduled to run again at 11:02am but I want it to run again 60 minutes after completing so it should be scheduled at 11:07am instead.
Is there any way to change the scheduling to do this? Or should I use a one time job that creates a new job each time it completes?

A: Use TriggerListener - see here for some examples in Quartz cookbook.
You will override triggerComplete and in there you will add your rescheduling code:
public void triggerComplete(Trigger trigger, JobExecutionContext context, CompletedExecutionInstruction triggerInstructionCode) {
    // check here the triggerInstructionCode value and reschedule your job
    super.triggerComplete(trigger, context, triggerInstructionCode);
}

Example for registering a TriggerListener with the scheduler to listen to a specific trigger:
scheduler.getListenerManager().addTriggerListener(myTriggerListener, keyEquals(triggerKey("myTriggerName", "myTriggerGroup")));

See also this answer.


text:
Q: Angular - Button disabled if input is empty not working I have inputs like this:
<mat-form-field *ngFor="let d of data">
    <mat-label>Item</mat-label>
    <input [(ngModel)]="d.item" matInput required>
</mat-form-field>`

I have tried this:
 <form #inputForm="ngForm">
        <mat-form-field *ngFor="let d of data">
            <mat-label>Item</mat-label>
            <input [name]="d.item" [(ngModel)]="d.item" matInput required>
        </mat-form-field>
    </form>

<button class="confirmButton" [disabled]="!inputForm.valid" mat-button [mat-dialog-close]="data">Send</button>

but when I type something just in one of inputs button is enabled, any soultion to this?

A: You should use reactive forms for dynamically created forms.

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a basic form control, progress to using multiple controls in a group, validate form values, and create dynamic forms where you can add or remove controls at run time.

See here

A: In your html:
<form [formGroup]="testForm" (ngSubmit)="onSubmit()">
    <label>
    Required Field:
    <input type="text" formControlName="requiredField" required>
  </label>

    <button type="submit" [disabled]="!testForm.valid">Submit</button>
</form>

Then in your component:
  testForm = this.fb.group({
    requiredField: ['', Validators.required]
  });

  constructor(private fb: FormBuilder) { }


text: Q: Is there a way to keep column height unaffected in HTML table? I have an HTML table with two columns with some text in them. Clicking a link on the right column renders some content dynamically that increases the column length to more than double. This in-turn causes the text on the left column to expand and look ugly. Is there a way to keep the text on the left column in-tact despite the increased right column length?


text:
Q: Why is my Zimbra mail going into the spam folder of yahoo, hotmail etc.? All mail from my new Zimbra mail server is going into spam and junk folder of Yahoo or Hotmail. Any suggestion to deliver them direct into inbox?
Below is the header part of my mail from yahoo...
X-Virus-Scanned: amavisd-new at
X-Spam-Flag: NO
X-Spam-Score: -1.963
X-Spam-Level: X-Spam-Status: No, score=-1.963 tagged_above=-10 required=6.6 tests=[AWL=-0.083, BAYES_00=-2.599, RCVD_IN_SORBS_WEB=0.619, RDNS_NONE=0.1] autolearn=no
Received: from mail.sara.co.in ([127.0.0.1]) by localhost (mail.sara.co.in [127.0.0.1]) (amavisd-new, port 10024) with ESMTP id QLBlyaY6ENGi; Fri, 19 Mar 2010 16:52:09 +0530 (IST)
Received:from mail.sara.co.in (mail.sara.co.in [192.168.1.1]) by mail.sara.co.in (Postfix) with ESMTP id 0FC6C3538001; Fri, 19 Mar 2010 16:52:08 +0530 (IST)
Date:   Fri, 19 Mar 2010 16:52:08 +0530 (IST)

A: I don't see any public IP addresses in your header...  Did you send one to yourself?  If so, that won't work.  We need to see the headers after it arrives at Yahoo or Hotmail.
One thing I do see is that your mail server thinks you are on a SORBS Blacklist.  If you are, then Yahoo and Hotmail will most certainly tag your emails as spam...
Update:  You are on 5 blacklists according to: MXTOOLBOX.  This is for sure the reason you are getting put in the junk folder at Yahoo and Hotmail.


text:
Q: loop through multiple input fields on a form and push to firebase I have a form with a lot of inputs and values. I want to push all the data to a firebase database. I could assign variables to each field value as:
let name = $("#field1").val();
let surname = $("#field2").val();

etc etc, but this feels very inefficient.
I want to create a object and loop through all input fields and map their name and value, something like this:
const collection = {};

$('form input').each(function () {
    collection[$(this).attr('name')] = $(this).val();
});

Then I want to push all the data to firebase. But how do I push the entire object to firebase?

A: That's as simple as:
firebase.database().ref().push(collection);

Of if you want it under a specific location/path in the database:
firebase.database().ref("specific/place").push(collection);

Btw: I highly recommend reading the Firebase documentation on reading/writing lists of data.


text:
Q: DriverManager.getConnection in Java by using relative path I'm making a program for someone's business in Java.
In order to make the database connection. All i know is to use the absolute path. Which means C:/users/documents/netbeansprojects/project/database.sqlite
How I can use a relative path. Like ../../project/database.sqlite or something.
I dont want to go on his computer looking what is the exact username and location to use the absolute path. Its kinda weird though.
Can somebody help me how to use a relative path in Java to my sqlite database.
So that on no matter what machine, it will anytime find connection with the database, without interfering with the java code...

A: You can use :
getClass().getResource("../../project/database.sqlite")