text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Return MongoDB result to an HTTP request I have a NodeJS route that looks like this:
app.get("/search/:query", (req, res, next) => {
let obj = SearchText(req.params.query);
res.status(200);
res.json(obj);
});
which calls this function:
async function SearchText(query) {
query = "Custom";
let mongoPromise = new Promise((resolve, reject) => {
MongoClient.connect(url,function(err, db) {
if (err) throw err;
var dbo = db.db("FunLibsTest");
dbo.collection("texts").find({"name": { $regex: query }}).toArray(function(err, result) {
if (err) reject(err);
resolve(result);
console.log(result);
db.close();
});
});
})
let results = await mongoPromise;
return results;
}
Expected result is whatever MongoDB finds, but it always returns "FAILED".
I do not believe MongoDB has a synchronous version of "find", but I want it to act synchronously so I can return the response to the HTTP request. How could I do this?
A: EDIT:
This code jumps around to a lot of places when we could just make it very linear.
function SearchText(query) {
return new Promise((resolve, reject) => {
MongoClient.connect(url, (err, db) => {
if (err) throw err;
var dbo = db.db("FunLibsTest");
dbo.collection("texts").find(query).toArray((err, result) => {
if (err) reject(err);
db.close();
resolve(result);
});
});
})
}
Then to use the function
app.get("/search/:query", (req, res, next) => {
SearchText(req.params.query).then((results) => {
res.status(200);
res.json(results);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61942548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can a single solution hold projects from multiple repositories? I've begun setting up SVN repositories to store my code, and am wondering if a single Visual Studio solution can have projects from multiple repositories. I have a shared library with different helper functions, generic custom controls, etc, that are used by multiple projects, and hosted in its own repository. Then I have my project repository, which contains all of the program-specific code such as forms, etc. I know I could copy the shared library into the program's repository, then copy them back when I make changes, but I'd much rather keep them in different repositories so I can hit "Commit" and the general library commits to it's repository, and the program code commits to it. I'm currently using AnkhSVN, but if it's possible with other tools, I'll look into it.
Preemptive clarification for all the "just use one repository" answers: The shared library is hosted in an online repository, viewable by anyone, but the program code is proprietary and resides on our office servers, so they need different repositories.
A: Yes it can, though you'll only be able to commit to projects from one repository at a time. One way of achieving this and making it reproducible by any developer who checks out your project is to use the svn:externals property on your solution's root folder to pull in projects from other repositories.
To edit or add this property, you can either use the svn command line, or TortoiseSVN. You'll find more details on the svn:externals property itself in the Subversion red book.
A: Like David says this is possible.
I would like to add to this that having multiple repositories not only takes away the ability to atomically commit, but also you won't be able to branch/tag the project and its dependencies into a single tag or branch. I wouldn't recommend using multiple repositories for these reasons.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3015138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Add Up/Down buttons to UITableView navigation bar Many apps, including Apple's own native Mail.app on the iPhone implement an Up/Down button in the detail view which allows for quick and easy browsing. I wish to create such an interface in my own app, but am struggling to do so. So far I've setup a segmented control which links to an action in my navigation bar, but I'm struggling with what to put in the action to make the detail view for the table update when the user presses the "Up" button or "Down" button to navigate to the item before or after the current one.
Any help would be appreciated. Thanks.
A: It depends on how you have your data set up, but why can't you hook into your existing code? What are you doing in your existing code to refresh the detail view when a user selects a row in master view table? Can't you just call that method directly?
It's hard to give specific advice without more detailed information on your current design.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4613229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fabric UI Checkbox Label Alignment I'm trying to add a checkbox to an Excel Add-In task pane but even when using a straight copy and paste of the sample code from the MS site, the label for the checkbox is on the line below. How do I make this so that the text is on the same line as the Check Box?
<div class="ms-CheckBox">
<input tabindex="-1" type="checkbox" class="ms-CheckBox-input">
<label role="checkbox" class="ms-CheckBox-field" tabindex="0" aria-checked="false" name="checkboxa">
<span class="ms-Label">Checkbox</span>
</label>
</div>
The task pane is plenty wide enough but the labels always appear on the line below.
A: Set a CSS property for .ms-Checkbox where display: flex; This will default to a row layout which will make the children of .ms-Checkbox to be displayed inline.
.ms-CheckBox {
display: flex;
}
<link href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.components.min.css" rel="stylesheet"/>
<link href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.min.css" rel="stylesheet"/>
<div class="ms-CheckBox">
<input tabindex="-1" type="checkbox" class="ms-CheckBox-input">
<label role="checkbox" class="ms-CheckBox-field" tabindex="0" aria-checked="false" name="checkboxa">
<span class="ms-Label">Checkbox</span>
</label>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56755796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Code signing certificate has to be imported from Java console to view Publisher correctly and avoid signature error We have purchased a code signing certificate, and I have signed an Applet jar with this certificate, using the jarsigner command and certificate in .pfx format. But when the applet is loaded in the browser, it shows the "Publisher Unknown" and "digital signature could not be verified" error.If I import the certificate from Java Control Panel -> Security -> Certificates -> Signer CA, the Publisher starts showing up correctly and "Digital signature is verified" message appears.
My question is that as we are signing the jar with a trusted certificate, then why do I have to still import the certificate to see correct results? Shouldn't it show the Publisher correctly/verify signature correctly , even without having to import it?
A: My issue got resolved.
There was a problem in the certificate (in .pfx format) that I was using to sign the jar.
When this certificate was generated from the site of the CA, the checkbox of "Include All Certificates in the path", was not selected. As a result the certificate did not have the complete chain required for signature verification in the applet jar.
The following command can be used to display the details of the certificates in a .pfx file
openssl pkcs12 -in <pfx_file_name>.pfx -nodes
The certificate that had an issue, had only 1 certificate listed; while the one generated later had the complete chain of 3 certificates.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20954443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Edge detection on colored background using OpenCV I am using following code to detect edges from given document.
private Mat edgeDetection(Mat src) {
Mat edges = new Mat();
Imgproc.cvtColor(src, edges, Imgproc.COLOR_BGR2GRAY);
Imgproc.GaussianBlur(edges, edges, new Size(5, 5), 0);
Imgproc.Canny(edges, edges, 10, 30);
return edges;
}
And then I can find the document from this edges by finding largest contour from this.
My problem is I can find the document from following pic:
but not from following pic:
How can I improve this edge detection?
A: I use Python, but the main idea is the same.
If you directly do cvtColor: bgr -> gray for img2, then you must fail. Because the gray becames difficulty to distinguish the regions:
Related answers:
*
*How to detect colored patches in an image using OpenCV?
*Edge detection on colored background using OpenCV
*OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection
In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(饱和度) channel in HSV color space. For HSV, refer to https://en.wikipedia.org/wiki/HSL_and_HSV#Saturation.
Main steps:
*
*Read into BGR
*Convert the image from bgr to hsv space
*Threshold the S channel
*Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners.
This is the first result:
This is the second result:
The Python code(Python 3.5 + OpenCV 3.3):
#!/usr/bin/python3
# 2017.12.20 10:47:28 CST
# 2017.12.20 11:29:30 CST
import cv2
import numpy as np
##(1) read into bgr-space
img = cv2.imread("test2.jpg")
##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)
##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)
##(4) find all the external contours on the threshed S
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
canvas = img.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)
## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]
## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)
## Ok, you can see the result as tag(6)
cv2.imwrite("detected.png", canvas)
A: In OpenCV there is function called dilate this will darker the lines. so try the code like below.
private Mat edgeDetection(Mat src) {
Mat edges = new Mat();
Imgproc.cvtColor(src, edges, Imgproc.COLOR_BGR2GRAY);
Imgproc.dilate(edges, edges, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(10, 10)));
Imgproc.GaussianBlur(edges, edges, new Size(5, 5), 0);
Imgproc.Canny(edges, edges, 15, 15 * 3);
return edges;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47899132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: sort string with delimiter as string in unix I have some data in the following format::
Info-programNumber!/TvSource/11100001_233a_32c0/13130^Info-channelName!5 USA^Info-Duration!1575190^Info-programName!CSI: ab cd
Delimiter = Info-
I tried to sort the string based on the delimiter in ascending order. But none of my solutions are working.
Expected Result:
Info-channelName!5 USA^Info-Duration!1575190^Info-programName!CSI: ab cd^Info-programNumber!/TvSource/11100001_233a_32c0/13130
Is there any command that will allow me to do this or do i need to write an awk script to iterate over the string and sort it?
A: Temporarily split the info into multiple lines so you can sort:
tr ^ \\n | sort | tr \\n ^
Note: if you have multiple entries, you have to write a loop, which processes it per line.. with huge datasets this is probably not a good idea (too slow), in which case pick a programming language.. but you were asking about the shell...
A: Can be done in awk itself:
awk -F "^" '{OFS="^"; for (i=1; i<=NF; i++) a[i]=$i}
END {n=asort(a, b); for(i=1; i<=n; i++) printf("%s%s", b[i], FS); print ""}' file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17363357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Format date and time in a Windows batch script In a Windows (Windows XP) batch script I need to format the current date and time for later use in files names, etc.
It is similar to Stack Overflow question How to append a date in batch files, but with time in as well.
I have this so far:
echo %DATE%
echo %TIME%
set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%
echo %datetimef%
which gives:
28/07/2009
8:35:31.01
2009_07_28__ 8_36_01
Is there a way I can allow for a single digit hour in %TIME%, so I can get the following?
2009_07_28__08_36_01
A: The following may not be a direct answer but a close one?
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__0%time:~1,2%_%time:~3,2%_%time:~6,2%
else set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%
At least it may be inspiring.
A: REM Assumes UK style date format for date environment variable (DD/MM/YYYY).
REM Assumes times before 10:00:00 (10am) displayed padded with a space instead of a zero.
REM If first character of time is a space (less than 1) then set DATETIME to:
REM YYYY-MM-DD-0h-mm-ss
REM Otherwise, set DATETIME to:
REM YYYY-MM-DD-HH-mm-ss
REM Year, month, day format provides better filename sorting (otherwise, days grouped
REM together when sorted alphabetically).
IF "%time:~0,1%" LSS "1" (
SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-0%time:~1,1%-%time:~3,2%-%time:~6,2%
) ELSE (
SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
)
ECHO %DATETIME%
A: I usually do it this way whenever I need a date/time string:
set dt=%DATE:~6,4%_%DATE:~3,2%_%DATE:~0,2%__%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%
set dt=%dt: =0%
This is for the German date/time format (dd.mm.yyyy hh:mm:ss). Basically I concatenate the substrings and finally replace all spaces with zeros.
The resulting string has the format: yyyy_mm_dd__hh_mm_ss
Short explanation of how substrings work:
%VARIABLE:~num_chars_to_skip,num_chars_to_keep%
So to get just the year from a date like "29.03.2018" use:
%DATE:~6,4%
^-----skip 6 characters
^---keep 4 characters
A: Here is how I generate a log filename (based on http://ss64.com/nt/syntax-getdate.html):
@ECHO OFF
:: Check WMIC is available
WMIC.EXE Alias /? >NUL 2>&1 || GOTO s_error
:: Use WMIC to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF "%%~L"=="" goto s_done
Set _yyyy=%%L
Set _mm=00%%J
Set _dd=00%%G
Set _hour=00%%H
SET _minute=00%%I
SET _second=00%%K
)
:s_done
:: Pad digits with leading zeros
Set _mm=%_mm:~-2%
Set _dd=%_dd:~-2%
Set _hour=%_hour:~-2%
Set _minute=%_minute:~-2%
Set _second=%_second:~-2%
Set logtimestamp=%_yyyy%-%_mm%-%_dd%_%_hour%_%_minute%_%_second%
goto make_dump
:s_error
echo WMIC is not available, using default log filename
Set logtimestamp=_
:make_dump
set FILENAME=database_dump_%logtimestamp%.sql
...
A: @ECHO OFF
: Sets the proper date and time stamp with 24Hr Time for log file naming
: convention ('YYYYMMDD_HHMMSS')
: Scrapes the characters out of their expected permissions in the date/time
: environment variables.
: Expects a date format of '____MM_DD_YYYY'
: Expects a time format of 'HH:MM:SS' or ' H:MM:SS'
SET HOUR=%time:~0,2%
SET dtStamp9=%date:~-4%%date:~4,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2%
SET dtStamp24=%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%
if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)
ECHO %dtStamp%
PAUSE
A: The offset:length formatting supported with the SET command in Windows will not allow you to pad the 0 as you seem to be interested in.
However, you can code a BATCH script to check for the hour being less than 10 and
pad accordingly with a different echo string.
You will find some information on the SET command on this link.
You can also change to other programming methods to get here.
It is quite simple in unix bash (available with Cygwin on Windows) to just say,
date +%Y_%m_%d__%H_%M_%S
And, it always pads correctly.
A: I did it this way:
REM Generate FileName from date and time in format YYYYMMTTHHMM
Time /T > Time.dat
set /P ftime= < Time.dat
set FileName=LogFile%date:~6%%date:~3,2%%date:~0,2%%ftime:~0,2%%ftime:~3,2%.log
echo %FileName%
LogFile201310170928.log
A: I'm really new to batch files and this is my code!! (I am not sure why, but I couldn't combine date /t and time /t together and I couldn't use %date% and %time% directly without a variable...)
@ECHO OFF
set ldt=%date% %time%
echo %ldt%>> logs.txt
EXIT
It is kind of reused from others (the question was to get a formatted timedate to use as filename).
A: ::========================================================================
::== CREATE UNIQUE DATETIME STRING IN FORMAT YYYYMMDD-HHMMSS
::======= ================================================================
FOR /f %%a IN ('WMIC OS GET LocalDateTime ^| FIND "."') DO SET DTS=%%a
SET DATETIME=%DTS:~0,8%-%DTS:~8,6%
The first line always outputs in this format regardles of timezone:
20150515150941.077000+120
This leaves you with just formatting the output to fit your wishes.
A: If PowerShell is installed, then you can easily and reliably get the Date/Time in any format you'd like, for example:
for /f %%a in ('powershell -Command "Get-Date -format yyyy_MM_dd__HH_mm_ss"') do set datetime=%%a
move "%oldfile%" "backup-%datetime%"
Of course nowadays PowerShell is always installed, but on Windows XP you'll probably only want to use this technique if your batch script is being used in a known environment where you know PS is available (or check in your batch file if PowerShell is available...)
You may reasonably ask: why use a batch file at all if you can use PowerShell to get the date/time, but I think some obvious reasons are: (a) you're not all that familiar with PowerShell and still prefer to do most things the old-fashioned way with batch files or (b) you're updating an old script and don't want to port the whole thing to PS.
A: This batch script will do exactly what the O.P. wants (tested on Windows XP SP3).
I also used that clever registry trick described by "jph" previously which IMHO is the simplest way of getting 100% consistent formatting of the date to "yyyy_MM_dd" on any Windows system new or old. The change to one Registry value for doing this is instantaneous temporary and trivial; it only lasts a few milliseconds before it is immediately reverted back.
Double-click this batch file for an instant demo, Command Prompt window will pop up and display your timestamp . . . . .
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: generates a custom formatted timestamp string using date and time.
:: run this batch file for an instant demo.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@ECHO OFF
SETLOCAL & MODE CON:COLS=80 LINES=15 & COLOR 0A
:: --- CHANGE THE COMPUTER DATE FORMAT TEMPORARILY TO MY PREFERENCE "yyyy_MM_dd",
REG COPY "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f 2>nul >nul
REG ADD "HKCU\Control Panel\International" /v sShortDate /d "yyyy_MM_dd" /f 2>nul >nul
SET MYDATE=%date%
:: --- REVERT COMPUTER DATE BACK TO SYSTEM PREFERENCE
REG COPY "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f 2>nul >nul
REG DELETE "HKCU\Control Panel\International-Temp" /f 2>nul >nul
:: --- SPLIT THE TIME [HH:MM:SS.SS] TO THREE SEPARATE VARIABLES [HH] [MM] [SS.SS]
FOR /F "tokens=1-3 delims=:" %%A IN ('echo %time%') DO (
SET HOUR=%%A
SET MINUTES=%%B
SET SECONDS=%%C
)
:: --- CHOOSE ONE OF THESE TWO OPTIONS :
:: --- FOR 4 DIGIT SECONDS //REMOVES THE DOT FROM THE SECONDS VARIABLE [SS.SS]
:: SET SECONDS=%SECONDS:.=%
:: --- FOR 2 DIGIT SECONDS //GETS THE FIRST TWO DIGITS FROM THE SECONDS VARIABLE [SS.SS]
SET SECONDS=%SECONDS:~0,2%
:: --- FROM 12 AM TO 9 AM, THE HOUR VARIABLE WE EXTRACTED FROM %TIME% RETURNS A SINGLE DIGIT,
:: --- WE PREFIX A ZERO CHARACTER TO THOSE CASES, SO THAT OUR WANTED TIMESTAMP
:: --- ALWAYS GENERATES DOUBLE-DIGIT HOURS (24-HOUR CLOCK TIME SYSTEM).
IF %HOUR%==0 (SET HOUR=00)
IF %HOUR%==1 (SET HOUR=01)
IF %HOUR%==2 (SET HOUR=02)
IF %HOUR%==3 (SET HOUR=03)
IF %HOUR%==4 (SET HOUR=04)
IF %HOUR%==5 (SET HOUR=05)
IF %HOUR%==6 (SET HOUR=06)
IF %HOUR%==7 (SET HOUR=07)
IF %HOUR%==8 (SET HOUR=08)
IF %HOUR%==9 (SET HOUR=09)
:: --- GENERATE OUR WANTED TIMESTAMP
SET TIMESTAMP=%MYDATE%__%HOUR%_%MINUTES%_%SECONDS%
:: --- VIEW THE RESULT IN THE CONSOLE SCREEN
ECHO.
ECHO Generate a custom formatted timestamp string using date and time.
ECHO.
ECHO Your timestamp is: %TIMESTAMP%
ECHO.
ECHO.
ECHO Job is done. Press any key to exit . . .
PAUSE > NUL
EXIT
A: There is another easy way of doing it:
set HH=%time:~0,2%
if %HH% LEQ 9 (
set HH=%time:~1,1%
)
A: This bat file (save as datetimestr.bat) produces the datetime string 3 times: (1) long datetime string with day of week and seconds,
(2) short datetime string without them and
(3) short version of the code.
@echo off
REM "%date: =0%" replaces spaces with zeros
set d=%date: =0%
REM "set yyyy=%d:~-4%" pulls the last 4 characters
set yyyy=%d:~-4%
set mm=%d:~4,2%
set dd=%d:~7,2%
set dow=%d:~0,3%
set d=%yyyy%-%mm%-%dd%_%dow%
set t=%TIME: =0%
REM "%t::=%" removes semi-colons
REM Instead of above, you could use "%t::=-%" to
REM replace semi-colons with hyphens (or any
REM non-special character)
set t=%t::=%
set t=%t:.=%
set datetimestr=%d%_%t%
@echo Long date time str = %datetimestr%
set d=%d:~0,10%
set t=%t:~0,4%
set datetimestr=%d%_%t%
@echo Short date time str = %datetimestr%
@REM Short version of the code above
set d=%date: =0%
set t=%TIME: =0%
set datetimestr=%d:~-4%-%d:~4,2%-%d:~7,2%_%d:~0,3%_%t:~0,2%%t:~3,2%%t:~6,2%%t:~9,2%
@echo Datetimestr = %datetimestr%
pause
To give proper credit, I merged the concepts from Peter Mortensen (Jun 18 '14 at 21:02) and opello (Aug 25 '11 at 14:27).
You can write this much shorter, but this long version makes reading and understanding the code easy.
A: I came across this problem today and solved it with:
SET LOGTIME=%TIME: =0%
It replaces spaces with 0s and basically zero-pads the hour.
After some quick searching I didn't find out if it required command extensions (still worked with SETLOCAL DISABLEEXTENSIONS).
A: To generate a YYYY-MM-DD hh:mm:ss (24-hour) timestamp I use:
SET CURRENTTIME=%TIME%
IF "%CURRENTTIME:~0,1%"==" " (SET CURRENTTIME=0%CURRENTTIME:~1%)
FOR /F "tokens=2-4 delims=/ " %%A IN ('DATE /T') DO (SET TIMESTAMP=%%C-%%A-%%B %CURRENTTIME%)
A: I like the short version on top of @The lorax,
but for other language settings it might be slightly different.
For example, in german language settings (with natural date format: dd.mm.yyyy) the month query has to be altered from 4,2 to 3,2:
@ECHO OFF
: Sets the proper date and time stamp with 24h time for log file naming convention i.e.
SET HOUR=%time:~0,2%
SET dtStamp9=%date:~-4%%date:~3,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2%
SET dtStamp24=%date:~-4%%date:~3,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%
if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)
ECHO %dtStamp%
: Outputs= 20160727_081040
: (format: YYYYMMDD_HHmmss; e.g.: the date-output of this post timestamp)
PAUSE
A: As has been noted, parsing the date and time is only useful if you know the format being used by the current user (for example, MM/dd/yy or dd-MM-yyyy just to name two). This could be determined, but by the time you do all the stressing and parsing, you will still end up with some situation where there is an unexpected format used, and more tweaks will be be necessary.
You can also use some external program that will return a date slug in your preferred format, but that has disadvantages of needing to distribute the utility program with your script/batch.
There are also batch tricks using the CMOS clock in a pretty raw way, but that is tooo close to bare wires for most people, and also not always the preferred place to retrieve the date/time.
Below is a solution that avoids the above problems. Yes, it introduces some other issues, but for my purposes I found this to be the easiest, clearest, most portable solution for creating a datestamp in .bat files for modern Windows systems. This is just an example, but I think you will see how to modify for other date and/or time formats, etc.
reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f
reg add "HKCU\Control Panel\International" /v sShortDate /d "yyMMdd" /f
@REM reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f
A: This is my 2 cents for adatetime string. On MM DD YYYY systems switch the first and second %DATE:~ entries.
REM ====================================================================================
REM CREATE UNIQUE DATETIME STRING FOR ADDING TO FILENAME
REM ====================================================================================
REM Can handle dd DDxMMxYYYY and DDxMMxYYYY > CREATES YYYYMMDDHHMMSS (x= any character)
REM ====================================================================================
REM CHECK for SHORTDATE dd DDxMMxYYYY
IF "%DATE:~0,1%" GTR "3" (
SET DATETIME=%DATE:~9,4%%DATE:~6,2%%DATE:~3,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
) ELSE (
REM ASSUMES SHORTDATE DDxMMxYYYY
SET DATETIME=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
)
REM CORRECT FOR HOURS BELOW 10
IF %DATETIME:~8,2% LSS 10 SET DATETIME=%DATETIME:~0,8%0%DATETIME:~9,5%
ECHO %DATETIME%
A: set hourstr = %time:~0,2%
if "%time:~0,1%"==" " (set hourstr=0%time:~1,1%)
set datetimestr=%date:~0,4%%date:~5,2%%date:~8,2%-%hourstr%%time:~3,2%%time:~6,2%
A: Create a file called "search_files.bat" and place the contents below into the file. Then double click it. The temporary %THH% variable was put in place to handle the AM appropriately. If there is a 0 in the first 2 digits of the time, Windows ignores the rest of the file name of the LOG file.
CD .
SET THH=%time:~0,2%
SET THH=%THH: =0%
dir /s /b *.* > %date:~10,4%-%date:~4,2%-%date:~7,2%@%THH%.%time:~3,2%.%time:~6,2%.LOG
A: You may use these...
Parameters:
%date:~4,2% -- month
%date:~7,2% -- days
%date:~10,4% -- years
%time:~1,1% -- hours
%time:~3,2% -- minutes
%time:~6,2% -- seconds
%time:~9,2% -- mili-seconds
%date:~4,2%%date:~7,2%%date:~10,4% : MMDDYYYY
%date:~7,2%%date:~4,2%%date:~10,4% : DDMMYYYY
%date:~10,4%%date:~4,2%%date:~7,2% : YYYYMMDD
A: I ended up with this script:
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%
set year=%date:~-4%
echo year=%year%
:: On WIN2008R2 e.g. I needed to make your 'set month=%date:~3,2%' like below ::otherwise 00 appears for MONTH
set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
echo month=%month%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
echo day=%day%
set datetimef=%year%%month%%day%_%hour%%min%%secs%
echo datetimef=%datetimef%
A: If you don't exactly need this format:
2009_07_28__08_36_01
Then you could use the following 3 lines of code which uses %date% and %time%:
set mydate=%date:/=%
set mytime=%time::=%
set mytimestamp=%mydate: =_%_%mytime:.=_%
Note: The characters / and : are removed and the character . and space is replaced with an underscore.
Example output (taken Wednesday 8/5/15 at 12:49 PM with 50 seconds and 93 milliseconds):
echo %mytimestamp%
Wed_08052015_124950_93
A: I tried the accepted answer and it works pretty well. Unfortunately the US Time Format appears to be H:MM:SS.CS, and the missing 0 on the front was causing parsing problems before 10 am. To get over this hurdle and also allow parsing of most any of the world time formats, I came up with this simple routine that appears to work quite well.
:ParseTime
rem The format of %%TIME%% is H:MM:SS.CS or (HH:MM:SS,CS) for example 0:01:23.45 or 23:59:59,99
FOR /F "tokens=1,2,3,4 delims=:.," %%a IN ("%1") DO SET /A "%2=(%%a * 360000) + (%%b * 6000) + (%%c * 100) + %%d"
GOTO :EOF
The nice thing with this routine is that you pass in the time string as the first parameter and the name of the environment variable you want to contain the time (in centiseconds) as the second parameter. For example:
CALL :ParseTime %START_TIME% START_CS
CALL :ParseTime %TIME% END_CS
SET /A DURATION=%END_CS% - %START_CS%
(*Chris*)
A: Maybe something like this:
@call:DateTime
@for %%? in (
"Year :Y"
"Month :M"
"Day :D"
"Hour :H"
"Minutes:I"
"Seconds:S"
) do @for /f "tokens=1-2 delims=:" %%# in (%%?) do @for /f "delims=" %%_ in ('echo %%_DT_%%$_%%') do @echo %%# : _DT_%%$_ : %%_
:: OUTPUT
:: Year : _DT_Y_ : 2014
:: Month : _DT_M_ : 12
:: Day : _DT_D_ : 17
:: Hour : _DT_H_ : 09
:: Minutes : _DT_I_ : 04
:: Seconds : _DT_S_ : 35
@pause>nul
@goto:eof
:DateTime
@verify errorlevel 2>nul & @wmics Alias /? >nul 2>&1
@if not errorlevel 1 (
@for /f "skip=1 tokens=1-6" %%a in ('wmic path win32_localtime get day^,hour^,minute^,month^,second^,year /format:table') do @if not "%%f"=="" ( set "_DT_D_=%%a" & set "_DT_H_=%%b" & set "_DT_I_=%%c" & set "_DT_M_=%%d" & set "_DT_S_=%%e" & set "_DT_Y_=%%f" )
) else (
@set "_DT_T_=1234567890 "
)
@if errorlevel 1 (
@for %%? in ("iDate" "sDate" "iTime" "sTime" "F" "Y" "M" "D" "H" "I" "S") do @set "_DT_%%~?_=%%~?"
@for %%? in ("Date" "Time") do @for /f "skip=2 tokens=1,3" %%a in ('reg query "HKCU\Control Panel\International" /v ?%%~? 2^>nul') do @for /f %%x in ('echo:%%_DT_%%a_%%') do @if "%%x"=="%%a" set "_DT_%%a_=%%b"
@for /f "tokens=1-3 delims=%_DT_T_%" %%a in ("%time%") do @set "_DT_T_=%%a%%b%%c"
)
@if errorlevel 1 (
@if "%_DT_iDate_%"=="0" (set "_DT_F_=_DT_D_ _DT_Y_ _DT_M_") else if "%_DT_iDate_%"=="1" (set "_DT_F_=_DT_D_ _DT_M_ _DT_Y_") else if "%_DT_iDate_%"=="2" (set "_DT_F_=_DT_Y_ _DT_M_ _DT_D_")
@for /f "tokens=1-4* delims=%_DT_sDate_%" %%a in ('date/t') do @for /f "tokens=1-3" %%x in ('echo:%%_DT_F_%%') do @set "%%x=%%a" & set "%%y=%%b" & set "%%z=%%c"
@for /f "tokens=1-3 delims=%_DT_T_%" %%a in ("%time%") do @set "_DT_H_=%%a" & set "_DT_I_=%%b" & set "_DT_S_=%%c"
@for %%? in ("iDate" "sDate" "iTime" "sTime" "F" "T") do @set "_DT_%%~?_="
)
@for %%i in ("Y" ) do @for /f %%j in ('echo:"%%_DT_%%~i_%%"') do @set /a _DT_%%~i_+= 0 & @for /f %%k in ('echo:"%%_DT_%%~i_:~-4%%"') do @set "_DT_%%~i_=%%~k"
@for %%i in ("M" "D" "H" "I" "S") do @for /f %%j in ('echo:"%%_DT_%%~i_%%"') do @set /a _DT_%%~i_+=100 & @for /f %%k in ('echo:"%%_DT_%%~i_:~-2%%"') do @set "_DT_%%~i_=%%~k"
@exit/b
A: Use REG to save/modify/restore what ever values are most useful for your bat file. This is windows 7, for other versions you may need a different key name.
reg save "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg /y
reg add "HKEY_CURRENT_USER\Control Panel\International" /v sShortDate /d "yyyy-MM-dd" /f
set file=%DATE%-%TIME: =0%
reg restore "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg
set file=%file::=-%
set file=%file:.=-%
set file
A: In situations like this use a simple, standard programming approach:
Instead of expending a huge effort parsing an unknown entity, simply save the current configuration, reset it to a known state, extract the info and then restore the original state. Use only standard Windows resources.
Specifically, the date and time formats are stored under the registry key
HKCU\Control Panel\International\ in [MS definition] "values": "sTimeFormat" and "sShortDate".
Reg is the console registry editor included with all Windows versions.
Elevated privileges are not required to modify the HKCU key
Prompt $N:$D $T$G
::Save current config to a temporary (unique name) subkey, Exit if copy fails
Set DateTime=
Set ran=%Random%
Reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp%ran%" /f
If ErrorLevel 1 GoTO :EOF
::Reset the date format to your desired output format (take effect immediately)
::Resetting the time format is useless as it only affect subsequent console windows
::Reg add "HKCU\Control Panel\International" /v sTimeFormat /d "HH_mm_ss" /f
Reg add "HKCU\Control Panel\International" /v sShortDate /d "yyyy_MM_dd" /f
::Concatenate the time and (reformatted) date strings, replace any embedded blanks with zeros
Set DateTime=%date%__%time:~0,2%_%time:~3,2%_%time:~6,2%
Set DateTime=%DateTime: =0%
::Restore the original config and delete the temp subkey, Exit if restore fails
Reg copy "HKCU\Control Panel\International-Temp%ran%" "HKCU\Control Panel\International" /f
If ErrorLevel 1 GoTO :EOF
Reg delete "HKCU\Control Panel\International-Temp%ran%" /f
Simple, straightforward and should work for all regions.
For reasons I don't understand, resetting the "sShortDate" value takes effect immediately in
a console window but resetting the very similar "sTimeFormat" value does NOT take effect
until a new console window is opened. However, the only thing changeable is the delimiter -
the digit positions are fixed.Likewise the "HH" time token is supposed to prepend leading zeros but it doesn't.
Fortunately, the workarounds are easy.
A: Using % you will run into a hex operation error when the time value is 7-9. To avoid this, use DelayedExpansion and grab time values with !min:~1!
An alternate method, if you have PowerShell is to call that:
for /F "usebackq delims=Z" %%i IN (`powershell Get-Date -format u`) do (set server-time=%%i)
A: This script use a WMI interface accessed primary via WMIC tool, which is an integral part of Windows since Windows XP Professional (Home edition is supported too, but the tool is not installed by default). The script also implements a workaround of missing WMIC tool by creating and calling a WSH vbscript for access a WMI interface and write to console output the time with same format as WMIC tool provide.
@ECHO OFF
REM Returns: RETURN
REM Modify: RETURN, StdOut
REM Required - mandatory: none
REM Required - optionaly: format strings delimited by a space to format an output delimited by predefined delimiter
REM YYYY = 4-digit year
REM MM = 2-digit month
REM DD = 2-digit day
REM hh = 2-digit hour
REM mm = 2-digit minute
REM ss = 2-digit second
REM ms = 3-digit millisecond
CALL :getTime %*
ECHO %RETURN%
GOTO :EOF
REM SUBROUTINE
REM Returns: RETURN
REM Modify: RETURN
REM Required - mandatory: none
REM Required - optionaly: format strings delimited by a space to format an output delimited by predefined delimiter
REM YYYY = 4-digit year
REM MM = 2-digit month
REM DD = 2-digit day
REM hh = 2-digit hour
REM mm = 2-digit minute
REM ss = 2-digit second
REM ms = 3-digit millisecond
:getTime
SETLOCAL EnableDelayedExpansion
SET DELIM=-
WHERE /Q wmic.exe
IF NOT ERRORLEVEL 1 FOR /F "usebackq skip=1 tokens=*" %%x IN (`wmic.exe os get LocalDateTime`) DO (SET DT=%%x & GOTO getTime_Parse)
SET _TMP=%TEMP:"=%
ECHO Wscript.StdOut.WriteLine (GetObject("winmgmts:root\cimv2:Win32_OperatingSystem=@").LocalDateTime)>"%_TMP%\get_time_local-helper.vbs"
FOR /F "usebackq tokens=*" %%x IN (`cscript //B //NoLogo "%_TMP%\get_time_local-helper.vbs"`) DO (SET DT=%%x & GOTO getTime_Parse)
:getTime_Parse
SET _RET=
IF "%1" EQU "" (
SET _RET=%DT:~0,4%%DELIM%%DT:~4,2%%DELIM%%DT:~6,2%%DELIM%%DT:~8,2%%DELIM%%DT:~10,2%%DELIM%%DT:~12,2%%DELIM%%DT:~15,3%
) ELSE (
REM Not recognized format strings are ignored during parsing - no error is reported.
:getTime_ParseLoop
SET _VAL=
IF "%1" EQU "YYYY" SET _VAL=%DT:~0,4%
IF "%1" EQU "MM" SET _VAL=%DT:~4,2%
IF "%1" EQU "DD" SET _VAL=%DT:~6,2%
IF "%1" EQU "hh" SET _VAL=%DT:~8,2%
IF "%1" EQU "mm" SET _VAL=%DT:~10,2%
IF "%1" EQU "ss" SET _VAL=%DT:~12,2%
IF "%1" EQU "ms" SET _VAL=%DT:~15,3%
IF DEFINED _VAL (
IF DEFINED _RET (
SET _RET=!_RET!%DELIM%!_VAL!
) ELSE (
SET _RET=!_VAL!
)
)
SHIFT
IF "%1" NEQ "" GOTO getTime_ParseLoop
)
ENDLOCAL & SET RETURN=%_RET%
GOTO :EOF
A: A nice single-line trick to avoid early variable expansion is to use cmd /c echo ^%time^%
cmd /c echo ^%time^% & dir /s somelongcommand & cmd /c echo ^%time^%
A: So the problem with %DATE% is that it depends on locale. So most of the previous answers did not work for me. If you are not picky about the exact format and just want a timestamp to differentiate the files you can do this:
set _date=%DATE%-%TIME%
set _date=%_date:/=-%
set _date=%_date: =-%
set _date=%_date::=-%
set _date=%_date:.=-%
echo %_date%
This should work for most locales. If it doesn't add another line set _date=%_date:<offending_char>=-% to remove the offending character. ie: a character which is not compatible with filenames or something you don't want in the file name.
Please note this doesn't meet the exact criteria laid down by the question.
A: :: =============================================================
:: Batch file to display Date and Time seprated by undescore.
:: =============================================================
:: Read the system date.
:: =============================================================
@SET MyDate=%DATE%
@SET MyDate=%MyDate:/=:%
@SET MyDate=%MyDate:-=:%
@SET MyDate=%MyDate: =:%
@SET MyDate=%MyDate:\=:%
@SET MyDate=%MyDate::=_%
:: =============================================================
:: Read the system time.
:: =============================================================
@SET MyTime=%TIME%
@SET MyTime=%MyTime: =0%
@SET MyTime=%MyTime:.=:%
@SET MyTime=%MyTime::=_%
:: =============================================================
:: Build the DateTime string.
:: =============================================================
@SET DateTime=%MyDate%_%MyTime%
:: =============================================================
:: Display the Date and Time as it is now.
:: =============================================================
@ECHO MyDate="%MyDate%" MyTime="%MyTime%" DateTime="%DateTime%"
:: =============================================================
:: Wait before close.
:: =============================================================
@PAUSE
:: =============================================================
A: Split the results of the date command by slash, then you can move each of the tokens into the appropriate variables.
FOR /F "tokens=1-3 delims=/" %%a IN ("%date:~4%") DO (
SET _Month=%%a
SET _Day=%%b
SET _Year=%%c
)
ECHO Month %_Month%
ECHO Day %_Day%
ECHO Year %_Year%
A: For a very simple solution for numeric date for use in filenames use the following code:
set month=%date:~4,2%
set day=%date:~7,2%
set curTimestamp=%month%%day%%year%
rem then the you can add a prefix and a file extension easily like this
echo updates%curTimestamp%.txt
A: *
*set xtime=%time%
*if "%xtime:~0,1%" == " " set xtime=0%xtime:~1,7%
*set isodate=%date:~-4%%date:~3,2%%date:~0,2%_%xtime:~0,2%%xtime:~3,2%%time:~6,2%
A: Hope this helps:
set MM=%date:~4,2%
set DD=%date:~7,2%
set YYYY=%date:~10,4%
echo %DD%_%MM%_%YYYY%
This will print 05_06_2021
A: for /f "tokens=1-4 delims=/ " %%I in ("%DATE%") do set curdate=%%K_%%J_%%I
for /f "tokens=1-4 delims=:," %%I in ("%TIME: =0%") do set curtime=%%I_%%J_%%K
echo %curdate%__%curtime%
replace delims symbols if your system uses another (used for slicing to %%I,%%J...)
also edit curdate if your system uses another D/M/Y order
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1192476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "237"
} |
Q: Java error loading images from a jar I know there are many threads for this, but im still to silly to fix this problem..
Im loading my images by the following:
ImageIO.read(new File(this.getClass().getResource("../" + src).toString().substring(5)));
I read in some threads (in german) that with this method you can load images from a jar, but also run it correct from eclipse.
But anyway im getting this error, when trying to open the jar:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.NullPointerException
at game.Sound.<init>(Sound.java:17)
at game.GUI.<init>(GUI.java:34)
at game.GUI.main(GUI.java:115)
... 5 more
Im running this from console with: java -jar CastleNightmare.jar
What im making ewrong?
Thank you!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17883377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sending email with Mandrill using PHP I'm trying to send email using Mandrill and PHP and I can't get it to send.
I've downloaded the PHP API wrapper from here:https://packagist.org/packages/mandrill/mandrill
Mandrill.php is in my root and the Mandrill folder is in the same directory.
Here's my code:
<?php
require_once 'Mandrill.php';
$mandrill = new Mandrill('MY API KEY IS USUALLY HERE');
$message = array(
'subject' => 'Test message',
'from_email' => '[email protected]',
'from_name' => 'Sender person',
'html' => '<p>this is a test message with Mandrill\'s PHP wrapper!.</p>',
'to' => array(array('email' => '[email protected]', 'name' => 'Recipient 1')),
'merge_vars' => array(array(
'rcpt' => '[email protected]',
'vars' =>
array(
array(
'name' => 'FIRSTNAME',
'content' => 'Recipient 1 first name'),
array(
'name' => 'LASTNAME',
'content' => 'Last name')
))));
//print_r($mandrill->messages->sendTemplate($template_name, $template_content, $message));
echo ("hello");
?>
But it won't send. I'm not sure where the failure is. Is it something obvious I'm missing?
I see the issue now.
I see what's going on now!
I changed
$mandrill->messages->sendTemplate($template_name, $template_content, $message));
to
$mandrill->messages->send($message, $async=false, $ip_pool=null, $send_at=null);
And it works!
A: Instead of calling the sendTemplate() function I should have used
$mandrill->messages->send($message, $async=false, $ip_pool=null, $send_at=null);
Once I changed the function call the mail was sent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22647687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: populate static items into c# WPF combo box I am trying to add the static values in to my combo box which is being written in WPF c#. I have following xaml piece of code which adds the items into my combo box.
<ComboBox Text="MyCombo">
<ComboBoxItem Name="115200">Item1</ComboBoxItem>
<ComboBoxItem Name="57600">Item2</ComboBoxItem>
<ComboBoxItem Name="38400">Item3</ComboBoxItem>
</ComboBox>
But is there any way that I can use "ItemSource" property of the combo box in to my xaml code to populate the combo box or any other UI method to add the static values into combo box.
Note: I do not want to do it in coding way to populate the values. I would like find the way of xaml or UI addition only.
A: You can bind your Combo box items from your view model using item source.
See the example below:
First, you want to set the DataContext of your Window.
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
Next,
public class ViewModel
{
public ObservableCollection<string> CmbContent { get; private set; }
public ViewModel()
{
CmbContent = new ObservableCollection<string>
{
"Item 1",
"Item 2",
"Item 2"
};
}
}
Finally,
<Grid>
<ComboBox Width="200"
VerticalAlignment="Center"
HorizontalAlignment="Center"
x:Name="MyCombo"
ItemsSource="{Binding CmbContent}" />
</Grid>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57073409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: python error message AttributeError: 'Bird' object has no attribute 'unsetflapped' so i am learning to code games from a video coding tutorial series. And my current problem is that when i run the game I get the following error:
File "/home/dev/PycharmProjects/Game6_Flappy_Bird/modules/sprites/bird.py", line 33, in update
self.unsetflapped()
AttributeError: 'Bird' object has no attribute 'unsetflapped'
The code from the "bird class sprites file code:
self.is_flapped = False
self.down_speed = 0
self.up_speed = 9
self.bird_idx = idx
self.bird_idx_cycle = itertools.cycle([0,1,2,1])
self.bird_idx_change_count = 0
def update(self, boundary_values, time_passed):
if self.is_flapped:
self.up_speed -= 60 * time_passed
self.rect.top -= self.up_speed
if self.up_speed <= 0:
self.unsetflapped()
self.up_speed = 9
self.down_speed = 0
else:
self.down_speed += 40*time_passed
self.rect.bottom += self.down_speed
is_dead = False
if self.rect.bottom > boundary_values[1]:
is_dead = True
self.up_speed = 0
self.down_speed = 0
self.rect.bottom = boundary_values[1]
if self.rect.top < boundary_values[0]:
is_dead = True
self.up_speed = 0
self.down_speed = 0
self.rect.top = boundary_values[1]
self.bird_idx_change_count +=1
if self.bird_idx_change_count%5 == 0:
self.bird_idx = next(self.bird_idx_cycle)
self.image = list(self.images.values())[self.bird_idx]
self.bird_idx_change_count = 0
return is_dead
def setFlapped(self):
if self.is_flapped:
self.up_speed = max(12, self.up_speed+1)
else:
self.is_flapped = True
def unsetFlapped(self):
self.is_flapped = False
I have checked this against the source code provided by the tutor and it matches exactly so I'm hoping someone can point me in the direction of what i'm doing wrong.
A: Please note: I figured out my problem. Capitalisation of lettering. I needed to change a small "f" to a capital "F"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68698001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MVC Linq for multiple selects that allow multiple selections I have a MVC web application with multiple selects that allow multiple selections that the user can use to filter data. For example: A car database where the user can select by make, color and body style. A possible search would be (Red OR Blue) AND (Chevy OR Ford) AND (SUV). I have all the selects returned in my viewmodel as array of strings and all gets returned to my controller correctly. I have the Color array with 'Red' and 'Blue', the Model array with 'Chevy' and 'Ford' and the BodyStyle array with 'SUV'. Now that I have the model posted to the controller, how do I construct the linq statement that will allow and of these criteria to me blank or contain multiple selections?
Model:
public class SearchViewModel
{
public string[] Model { get; set; }
public string[] Color { get; set; }
public string[] Body { get; set; }
}
Controller:
public ActionResult Search(SearchViewModel search)
{
//TODO: Create linq for all search criteria
List<Cars> cars = db.Cars.Where(car => car.Model == search.Model[0]);
return View(cars);
}
A: var list = new List<string> { "red", "orange"};
from c in DB.Cars
where list == null || list.Contains(c.Color)
select c;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25126590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: angular 4 programmatic animation How to add animation programatically ?
@Component({
moduleId: module.id,
selector: 'my-toolbar',
templateUrl: './my-toolbar.component.html',
styleUrls: ['./my-toolbar.component.scss'],
encapsulation: ViewEncapsulation.None,
animations: [
trigger('myToolbarState', [
state('initial', style({top: '*'})),
state('up', style({top: '-50px')),
transition('initial => up, up => initial',
animate(HEADER_SHRINK_TRANSITION))
])
]
})
How to achieve the same without annotation ? My underlying goal is to create a dynamic trigger function that uses different values based on some @Input.
It is important to note that the animations or the triggers must have at-least one variable. That makes this question different from how do I reuse animations.
A: I ended up with following factory class as shown below being used for animations[]:-
This is used as below:
@Component({
selector: 'my-app-header',
moduleId: module.id,
templateUrl: './app-header.component.html',
styleUrls: ['./app-header.component.scss'],
animations: [
MyToolbarAnimator.createTrigger('appHeaderState', '50px', '0')
]
})
Defined MyToolbarAnimator with a static method createTrigger which returns AnimationTriggerMetadata as shown below
MyToolbarAnimator
import {trigger, state, style, animate, transition, AnimationTriggerMetadata} from '@angular/animations';
export const HEADER_SHRINK_TRANSITION = '250ms cubic-bezier(0.4,0.0,0.2,1)';
export class MyToolbarAnimator {
static createTrigger(triggerName: string, initialTop: string, upTop: string): AnimationTriggerMetadata {
return trigger(triggerName, [
state('initial', style({top: initialTop})),
state('up', style({top: upTop})),
transition('initial => up, up => initial',
animate(HEADER_SHRINK_TRANSITION))
]);
}
}
UPDATE:
Or if your animation parameters are very dynamic and changes based on the component behavior use https://angular.io/api/animations/AnimationBuilder#usage-notes
This
// import the service from BrowserAnimationsModule
import {AnimationBuilder} from '@angular/animations';
// require the service as a dependency
class MyCmp {
width = 100;
constructor(private _builder: AnimationBuilder) {}
changeWidth(aWidth:number) {
this.width = aWidth;
}
makeAnimation(element: any) {
// first define a reusable animation
const myAnimation = this._builder.build([
style({ width: 0 }),
animate(1000, style({ width: `${this.width}px` }))
]);
// use the returned factory object to create a player
const player = myAnimation.create(element);
player.play();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46165023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to restore and backup database I need to restore the MySQL database that I used which is a service based database, when I click the button 'RESTORE DATABASE'. I'm using VB.Net 2010. I already did a research for any solution, but I can't come up with any idea how to make it work. Do you have any ideas in mind that might help? I'm currently doing how to backup the database, so any help would be really much appreciated.
Here is the sample code:
Private Sub cmdrestore_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdrestore.Click
Dim s As System.IO.StreamWriter
Try
Dim portfolioPath As String = My.Application.Info.DirectoryPath
FileCopy(portfolioPath & "\Backup\Database1.mdf", "C:\Payroll System\Database1.Mdf")
MsgBox("Restore completed successfully", vbInformation, "DBBES-B Payroll System")
Catch ex As Exception
Dim MessageString As String = "Report this error to the system administrator: " & ControlChars.NewLine & ex.Message
Dim TitleString As String = "Employee Master Details Data Load Failed"
MessageBox.Show(MessageString, TitleString, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
A: First you will want to create a batch file that successfully restores the database. There are plenty of examples when you search Google (MySQL database restore script).
Then your button will call your batch file using the Process class, like in the example found HERE. You will use a .bat of course not .exe.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22577704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The default value for a column in not set when copy file using rest api (SharePoint 2013 standalone) I am trying to copy files from one folder to another folder using SharePoint REST API. Some columns inside the destination folder have defined a default value. Even though the files are copied successfully, some files do not get the default value for the columns.
On a closer look, I found that the new office documents types (.docx, .xlsx, .pptx etc.) get the default values, while the old office document types (.doc, .xls, .ppt) do not get the values.
Also the old office documents get the values only when they are coming from a source folder which already contains the columns in the destination folder.
I am wondering why the old office documents do not get the values and if anything can be done.
Is it a bug in SharePoint Server or am I missing any configuration to make all files work?
A: My understanding is that this is expected. Because you are copying files, the copy includes not only the file itself but also its metadata. If the file in the source folder doesn't have values in those columns, it does make sense that if you copy it to a destination folder, those same columns shouldn't have values either. Now, why some files (docx, pptx, etc.) do have values in the destination? Probably because of the SharePoint document parser feature (Document Property Promotion and Demotion). So in your case what you can do is, instead of copying the files, download/upload them using for instance code like this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44666057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to disable a specific row to be draggable in AG table? I am using the Managed Dragging of AG Grid React table and want to disable a specific row, if it matches the condition.
In Docs I couldn't find enough information how to do that. As it describes here, it is possible to add the draggable feature conditionally, like this
rowDrag: params => !params.node.group
In params object, I couldn't find the row data to implement my condition.
In the code example described below, I want to disable the row to be draggable if the name==='John.
Also, how to that if you have row draggable for entire row: rowDragEntireRow={true}?
Sandbox demo and code
import React from "react";
import { AgGridReact } from "ag-grid-react";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
function App() {
const [gridApi, setGridApi] = React.useState(null);
const [gridColumnApi, setGridColumnApi] = React.useState(null);
const onGridReady = (params) => {
setGridApi(params.api);
setGridColumnApi(params.columnApi);
};
const defaultColDef = {
flex: 1,
editable: true
};
const columnDefs = [
{
headerName: "Name",
field: "name",
rowDrag: (params) => {
console.log("params", params);
return !params.node.group;
}
},
{ headerName: "stop", field: "stop" },
{
headerName: "duration",
field: "duration"
}
];
const rowData = React.useMemo(
() => [
{
name: "John",
stop: 10,
duration: 5
},
{
name: "David",
stop: 15,
duration: 8
},
{
name: "Dan",
stop: 20,
duration: 6
}
],
[]
);
return (
<div>
<h1 align="center">React-App</h1>
<div>
<div className="ag-theme-alpine" style={{ height: "700px" }}>
<AgGridReact
columnDefs={columnDefs}
rowData={rowData}
defaultColDef={defaultColDef}
onGridReady={onGridReady}
rowDragManaged={true}
//rowDragEntireRow={true}
></AgGridReact>
</div>
</div>
</div>
);
}
export default App;
Any help will be appreciated
A: Update your rowDrag definition in the name column definition to the following:
rowDrag: (params) => {
if (params.data.name == "John") {
return false;
}
return true;
}
Demo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71394990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Embed Bokeh server with multiple roots in Django I have a bokeh app with multiple roots. Inside the bokeh template, I use
{{embed(roots.plot1)}}
{{embed(roots.plot2)}}
# etc
to load the plots. This works fine. Now, I'd like to get the plots to load inside a web page I'll be serving from a Django app. Since my plots are generated using Holoviews, the Bokeh server is essential.
The bokeh documentation https://github.com/bokeh/bokeh/tree/master/examples has examples of how to autoload all plots from a Bokeh server, and it also has examples of how to embed multiple static plots using components(), but none of these seem to cover this use case.
Here's what I've tried:
# The following function is a function-based Django view
def django_view(request):
bokeh_url = 'http://localhost:5006/experiment'
roots = {root.name: root for root in session.document.roots}
with pull_session(url=bokeh_url) as session:
# I was hoping that these will generate separate autoload scripts for each model.
# Unfortunately they each embed all the models.
script1 = server_session(session_id=session.id, url=bokeh_url, model=roots['plot1'])
script2 = server_session(session_id=session.id, url=bokeh_url, model=roots['plot2'])
return render(request, "template.html", {"script1": script1, "script2: script2})
Excerpt from template.html:
{{ script1 | safe }}
{{ script2 | safe }}
The result is that each script tag loads all the plots on top of eachother. How can I get each plot embedded exactly once, where I want it? How should I be doing this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52861629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: simplexml_load_file() with a variable I'm currently having an issue with simplexml_load_file(); my xml path is a url, that is rendered as a variable
$xurl = "domain/pathto/myfile.xml"; // This is actually a variable that returns the entire URL to where my xml file is -- this will change from file to file
$xmlpath = parse_url($xurl, PHP_URL_PATH); // to get the path of my xml file ex. /pathto/myfile.xml
$xmlpath = mb_substr($xmlpath, 1); // returns pathto/myfile.xml
here is where my problem is, when I put it into :
simplexml_load_file($xmlpath);
In my function, I get nothing appearing from the XML file
However, in my same function if I change it to
simplexml_load_file("pathto/myfile.xml");
My function works fine.
I did an echo on $xmlpath and it returns the pathto/myfile.xml just fine.
<?php echo $xmlpath; ?> // returns pathto/myfile.xml
What am I doing wrong?
EDIT: Phil
echo strcmp("pathto/myfile.xml", $xmlpath)
returns a 0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21717258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: VBA Transpose to Another target Sheet In the pictures below, I have a source page that is formatted with a device and attributes. I would like to create a macro which copies that source data and pastes it in the format of the target sheet. Ultimately the target sheet would be empty and would populate only when running the macro.
Source page and target page
I am a newb at this. I've tried using the following code from another stack overflow question, but it doesn't do what I want.
Sub ColumnCopy()
Dim lastRow As Long
Dim lastRow As Long
Dim lastCol As Long
Dim colBase As Long
Dim tRow As Long
Dim source As String
Dim target As String
source = "source" 'Set your source sheet here
target = "target" 'Set the Target sheet name
tRow = 2 'Define the start row of the target sheet
'Get Last Row and Column
lastRow = Sheets(source).Range("A" & Rows.Count).End(xlUp).Row
lastCol = Sheets(source).Cells(2, Columns.Count).End(xlToLeft).Column
tRow = 2
colBase = 2
Do While colBase < lastCol
For iRow = 2 To lastRow
Sheets(target).Cells(tRow, 1) = Sheets(source).Cells(1, tRow)
Sheets(target).Cells(tRow, 2) = Sheets(source).Cells(2, tRow)
Sheets(target).Cells(tRow, 3) = Sheets(source).Cells(3, tRow)
Sheets(target).Cells(tRow, 4) = Sheets(source).Cells(4, tRow)
Sheets(target).Cells(tRow, 5) = Sheets(source).Cells(5, tRow)
Sheets(target).Cells(tRow, 6) = Sheets(source).Cells(6, tRow)
tRow = tRow + 1
Next iRow
colBase = colBase + 1 'Add 4 to the Column Base. This shifts the loop over to the next Row set.
Loop
End Sub
Thanks,
MJ
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38316683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How Strict is the rule no dom manipulation inside controller in AngularJS? I know in AngularJS We are not supposed to do any dom manipulation inside a controller. But If i need to do a dom manipulation on click of an element then how am i supposed to handle it. For example while building a menu i need to show submenu on click how do i accomplish it without dom manipulation in the controller?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19923018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What are the differences between class diagram and physical class diagram? What are the differences between class diagram and physical class diagram?
A: There is nothing like a Physical Class Diagram, just class diagrams (you may consult Superstructures if you like). What you probably mean is the difference between class model and physical model. The latter focuses on the concrete implementation of a class model. It shows libs, hardware and things you'd need to implement your more abstract class model on some real hardware. With the MDA this part is called PSM (platform specific model) in contrast to the PIM (platform independent model).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29925058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to do you insert array typeof data into apche ignite I am trying to create a table with array data type in apache ignite using following query.
create table test(id int,word varchar,vector array,primary key(id));
with this above query i am able to create a table test.
0
: jdbc:ignite:thin://127.0.0.1/> !tables
+--------------------------------+--------------------------------+--------------------------------+--------------------------------+----------------+
| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | REM |
+--------------------------------+--------------------------------+--------------------------------+--------------------------------+----------------+
| | wordVectorCache | WORDTOVECTORBASICDETAILS | TABLE | |
| | PUBLIC | TEST | TABLE | |
+--------------------------------+--------------------------------+--------------------------------+--------------------------------+----------------+
if i tried same with following query
create table test1(id int,word varchar,vector char[],primary key(id));
i got following error,
0: jdbc:ignite:thin://127.0.0.1/> create table test2(id int,word varchar,vector char[],primary key(id));
Error: Failed to parse query. Syntax error in SQL statement "CREATE TABLE TEST2(ID INT,WORD VARCHAR,VECTOR CHAR[[*]],PRIMARY KEY(ID)) "; expected "(, FOR, UNSIGNED, INVISIBLE, VISIBLE, NOT, NULL, AS, DEFAULT, GENERATED, ON, NOT, NULL, AUTO_INCREMENT, BIGSERIAL, SERIAL, IDENTITY, NULL_TO_DEFAULT, SEQUENCE, SELECTIVITY, COMMENT, CONSTRAINT, PRIMARY, UNIQUE, NOT, NULL, CHECK, REFERENCES, ,, )"; SQL statement:
create table test2(id int,word varchar,vector char[],primary key(id)) [42001-197] (state=42000,code=1001)
java.sql.SQLException: Failed to parse query. Syntax error in SQL statement "CREATE TABLE TEST2(ID INT,WORD VARCHAR,VECTOR CHAR[[*]],PRIMARY KEY(ID)) "; expected "(, FOR, UNSIGNED, INVISIBLE, VISIBLE, NOT, NULL, AS, DEFAULT, GENERATED, ON, NOT, NULL, AUTO_INCREMENT, BIGSERIAL, SERIAL, IDENTITY, NULL_TO_DEFAULT, SEQUENCE, SELECTIVITY, COMMENT, CONSTRAINT, PRIMARY, UNIQUE, NOT, NULL, CHECK, REFERENCES, ,, )"; SQL statement:
create table test2(id int,word varchar,vector char[],primary key(id)) [42001-197]
at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.sendRequest(JdbcThinConnection.java:750)
at org.apache.ignite.internal.jdbc.thin.JdbcThinStatement.execute0(JdbcThinStatement.java:212)
at org.apache.ignite.internal.jdbc.thin.JdbcThinStatement.execute(JdbcThinStatement.java:475)
at sqlline.Commands.execute(Commands.java:823)
at sqlline.Commands.sql(Commands.java:733)
at sqlline.SqlLine.dispatch(SqlLine.java:795)
at sqlline.SqlLine.begin(SqlLine.java:668)
at sqlline.SqlLine.start(SqlLine.java:373)
at sqlline.SqlLine.main(SqlLine.java:265)
Now i tried to insert data into test table, using following query
insert into test values(1,'ramoji',{'123','234'});
this time i faced an issue:
0: jdbc:ignite:thin://127.0.0.1/> insert into test values(1,'ramoji',{'123','234'});
Error: Failed to parse query. Syntax error in SQL statement "insert into test values(1,'ramoji',{'123','234'})[*]" [42000-197] (state=42000,code=1001)
java.sql.SQLException: Failed to parse query. Syntax error in SQL statement "insert into test values(1,'ramoji',{'123','234'})[*]" [42000-197]
at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.sendRequest(JdbcThinConnection.java:750)
at org.apache.ignite.internal.jdbc.thin.JdbcThinStatement.execute0(JdbcThinStatement.java:212)
at org.apache.ignite.internal.jdbc.thin.JdbcThinStatement.execute(JdbcThinStatement.java:475)
at sqlline.Commands.execute(Commands.java:823)
at sqlline.Commands.sql(Commands.java:733)
at sqlline.SqlLine.dispatch(SqlLine.java:795)
at sqlline.SqlLine.begin(SqlLine.java:668)
at sqlline.SqlLine.start(SqlLine.java:373)
at sqlline.SqlLine.main(SqlLine.java:265)
Can any one please help me how should i use array data type in apache ignite & how to insert data with proper example.
Thank you very much for your help & Support in advance.
I will be keep looking for your answers, Please help .....
My sample data for one record is:
insert into text values(
1,'in',"['0.070312', '0.086914', '0.087891', '0.062500', '0.069336', '-0.108887', '-0.081543', '-0.154297', '0.020752', '0.131836', '-0.113770', '-0.037354', '0.069336', '0.078125', '-0.103027', '-0.097656', '0.044189', '0.102539', '-0.060791', '-0.036133', '-0.045410', '0.047363', '-0.120605', '-0.063965', '0.002258', '0.037109', '-0.002914', '0.117676', '0.061768', '0.063965', '0.081055', '-0.068848', '-0.021362', '0.055176', '-0.085449', '0.068848', '-0.127930', '-0.033203', '0.098633', '0.175781', '0.110840', '-0.034668', '-0.047119', '-0.008484', '0.035889', '0.103027', '0.026978', '-0.028687', '-0.005127', '0.106445', '0.059814', '0.094238', '0.033691', '-0.027100', '-0.094238', '0.001030', '-0.048340', '0.034424', '0.081055', '-0.113281', '-0.088867', '0.035889', '-0.145508', '-0.244141', '-0.061523', '0.052979', '0.056885', '0.179688', '0.061035', '0.086914', '0.124023', '-0.040283', '0.022583', '0.177734', '-0.029663', '-0.029663', '0.117188', '0.031128', '-0.096191', '0.066406', '0.004700', '-0.080078', '0.062988', '-0.020630', '-0.054688', '-0.135742', '-0.063477', '0.083496', '-0.063965', '0.021484', '0.077148', '-0.037109', '-0.033691', '-0.183594', '-0.072754', '0.015869', '0.093262', '-0.061523', '-0.014221', '-0.003448', '0.011108', '-0.158203', '-0.017090', '0.006195', '-0.008728', '-0.080566', '-0.015259', '-0.087891', '0.003479', '-0.016113', '-0.012329', '0.097656', '-0.139648', '-0.085938', '-0.026855', '0.053955', '0.132812', '0.112793', '0.121094', '0.085449', '-0.007111', '0.044678', '-0.145508', '-0.003204', '-0.117676', '-0.065430', '0.071289', '-0.094238', '-0.030273', '0.120117', '0.080078', '-0.094727', '-0.162109', '-0.077637', '0.021240', '-0.081543', '0.003937', '-0.157227', '-0.098145', '0.039795', '0.039307', '-0.009094', '0.103027', '0.067871', '-0.042725', '0.063477', '-0.049072', '0.020874', '-0.166992', '0.093262', '0.093750', '0.006866', '0.053711', '0.052490', '-0.024414', '-0.032471', '-0.061523', '-0.005554', '0.096191', '0.037842', '0.012207', '-0.043945', '-0.007477', '0.105469', '0.020386', '0.145508', '0.082031', '0.005768', '0.004578', '-0.092773', '-0.138672', '-0.057373', '-0.051514', '-0.130859', '-0.139648', '-0.020508', '-0.027100', '0.032715', '0.104980', '-0.002335', '-0.022583', '0.000504', '-0.110840', '0.084961', '-0.129883', '-0.017456', '-0.000359', '0.107910', '0.088867', '0.044678', '0.025146', '0.023804', '0.081055', '0.023682', '-0.109863', '0.005371', '-0.017700', '-0.033936', '-0.032959', '-0.164062', '0.095703', '-0.018311', '0.005310', '-0.034424', '-0.044189', '-0.066406', '-0.017944', '-0.029663', '-0.007599', '-0.051270', '-0.054199', '0.089355', '-0.071777', '0.015259', '-0.082520', '-0.031738', '0.035645', '-0.021240', '-0.059326', '-0.013062', '0.046875', '0.023071', '0.020996', '-0.078613', '-0.008057', '0.019531', '-0.005554', '0.041504', '0.027832', '0.013611', '0.034668', '-0.182617', '0.120117', '0.074219', '-0.041016', '-0.009949', '0.042969', '-0.007294', '0.123047', '0.057617', '-0.053467', '-0.032227', '-0.009094', '-0.046631', '0.043945', '-0.050781', '0.068848', '0.002991', '-0.004181', '-0.044189', '0.073730', '-0.012756', '0.067383', '0.006287', '0.075195', '-0.037842', '0.004883', '0.044678', '-0.067383', '0.009705', '0.004730', '0.020508', '0.071289', '0.170898', '0.173828', '0.055664', '0.091309', '-0.037354', '0.049805', '-0.039307', '0.044189', '0.062500', '0.048584', '-0.053223', '0.048828', '-0.130859', '-0.028931', '-0.036133', '-0.060791', '-0.057373', '0.123047', '-0.082520', '-0.011902', '0.125000', '0.001358', '0.063965', '-0.106445', '-0.143555', '-0.042236', '0.024048', '-0.168945', '-0.088867', '-0.080566', '0.064941', '0.061279', '-0.047363', '-0.058838', '-0.047607', '0.014465', '-0.062500']");
How do i insert this much big data for my third column which should be of type Array.
A: Apache Ignite's SQL does not have syntax for reading or writing arrays. You can store arrays in text form if you like (for example, you can store JSON snippets in VARCHAR columns), or you can store arrays as fields in POJO objects using Ignite's Java APIs (they will not be accessible as SQL table columns in this case).
You can create an ARRAY column, but there is no way to populate it with array literal currently.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59170763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: QLPreviewController playback video I've found strange behaviour on the QLPreviewController modal where Im trying to preview a video and QLPreviewController carries on playing a video after I've dismissed the modal via the "done" button which is provided by default.
Any ideas on why this could be happening or how I can stop the playback?
A: Found the problem. I extended QLPreviewController and in viewWillDisappear i didn't call [super viewWillDisappear] which was causing the video to still playback in the background.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31612330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: RedirectToAction is Taking Too much Time in Production? I am Trying to redirect from one Controller Action to other controller Index Method.the redirection itself taking 20sec. how can i reduce the time its consuming? Actually it is a direct call it should not consume that much of time?
Is there any other way to Redirect?
here is my code
public ActionResult LaunchSeletedService(int serviceId)
{
//some fuctionality
if (Request.IsAjaxRequest())
{
return new JavaScriptResult() { Script = "document.location.replace('" + Url.Action("Index", "Home", new { area = Area }) + "');" };
//return RedirectToAction("Index", "Home", new { area = Area });
}
else
{
return RedirectToAction("Index", "Home", new { area = Area });
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34398430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Perpendicular Lines at Regular Intervals along Lines with Multiple Nodes I am attempting to sample along multiple lines (roads) at regular intervals and am struggling to obtain exact perpendicular angles for each road segment. I have split each road into points giving the node at which each line changes orientation and what I have so far creates a point within a straight segment of each road and appears to be working fine.
This is the code I am using to produce perpendicular angles for each node segment.
# X and Y for 3 points along a line
road_node <- matrix(
c(
381103, 381112, 381117,
370373, 370301, 370290
),
ncol = 2,
)
road_node <- as.data.frame(road_node)
angle_inv <- c()
for (i in 2:nrow(road_node) - 1) {
n1 <- road_node[i, ]
n2 <- road_node[i + 1, ]
x <- as.numeric(n1[1] - n2[1])
y <- as.numeric(n1[2] - n2[2])
ang <- atan2(y, x) + 1 / 2 * pi
if (!is.na(ang) && ang < 0) {
ang <- 2 + ang
}
angle_inv <- rbind(angle_inv, ang)
}
Where road_node gives the coordinates of each node.
From this I take the mid points and the inverse angles to create two points either side of the mid points, to produce a line segment.
# X Y and Angles (angles for one segment are the same
mids <- matrix(
c(
381374.5, 381351.0, 381320.5,
371590.5,371560.0, 371533.590,
2.3, 2.3, 2.3
),
nrow = 3,
)
mids <- as.data.frame(mids)
pts <- c()
for (i in 1:nrow(mids)) {
x1 <- mids[i, 1] + 10 * cos(mids[i, 3])
y1 <- mids[i, 2] + 10 * sin(mids[i, 3])
x2 <- mids[i, 1] - 10 * cos(mids[i, 3])
y2 <- mids[i, 2] - 10 * sin(mids[i, 3])
p1 <- cbind(x1, y1)
p2 <- cbind(x2, y2)
pair <- rbind(p1, p2)
pts <- rbind(pts, pair)
}
Some line segments appear to be correctly perpendicular to the node they are associate with, however some are not. Each appear to correctly share the same length.
I believe the problem lies with either how I am selecting my angles using atan2, or with how I am selecting my points either side of the node segment.
A: Firstly, there's no need to use trigonometry to solve this. Instead you can use the inverse reciprocal of the slope intercept form of the line segment equation, then calculate points on a perpendicular line passing through a give point.
See Equation from 2 points using Slope Intercept Form
Also your mid points appear incorrect and there are only 2 mid points as 3 points = 2 line segments.
This code appears to work fine
# Function to calculate mid points
mid_point <- function(p1,p2) {
return(c(p1[1] + (p2[1] - p1[1]) / 2,p1[2] + (p2[2] - p1[2]) / 2))
}
# Function to calculate slope of line between 2 points
slope <- function(p1,p2) {
return((p2[2] - p1[2]) / (p2[1] - p1[1]))
}
# Function to calculate intercept of line passing through given point wiht slope m
calc_intercept <- function(p,m) {
return(p[2] - m * p[1])
}
# Function to calculate y for a given x, slope m and intercept b
calc_y <- function(x,m,b) {
return(c(x, m * x + b))
}
# X and Y for 3 points along a line
road_node <- matrix(
c(
381103, 381112, 381117,
370373, 370301, 370290
),
ncol = 2,
)
road_node <- as.data.frame(road_node)
perp_segments <- c()
for (i in 2:nrow(road_node) - 1) {
n1 <- road_node[i, ]
n2 <- road_node[i + 1, ]
# Calculate mid point
mp <- mid_point(n1,n2)
# Calculate slope
m <- slope(n1,n2)
# Calculate intercept subsituting n1
b <- calc_intercept(n1,m)
# Calculate inverse reciprocal of slope
new_m <- -1.0 / m
# Calculate intercept of perpendicular line through mid point
new_b <- calc_intercept(mp,new_m)
# Calculate points 10 units away in x direction at mid_point
p1 <- rbind(calc_y(as.numeric(mp[1])-10,new_m,new_b))
p2 <- rbind(calc_y(as.numeric(mp[1])+10,new_m,new_b))
# Add point pair to output vector
pair <- rbind(p1,p2)
perp_segments <- rbind(perp_segments,pair)
}
This is how it looks geometrically (image)
I hope this helps.
Edit 1:
I thought about this more and came up with this simplified function. If you tink of the problem as a right isosceles triangle (45,45,90), then all you need to do is find the point which is the required distance from the reference point interpolated along the line segment, then invert its x and y distances from the reference points, then add and subtract these from the reference point.
Function calc_perp
Arguments:
p1, p2 - two point vectors defining the end points of the line segment
n - the distance from the line segment
interval - the interval along the line segment of the reference point from the start (default 0.5)
proportion - Boolean defining whether the interval is a proportion of the length or a constant (default TRUE)
# Function to calculate Euclidean distance between 2 points
euclidean_distance <-function(p1,p2) {
return(sqrt((p2[1] - p1[1])**2 + (p2[2] - p1[2])**2))
}
# Function to calculate 2 points on a line perpendicular to another defined by 2 points p,p2
# For point at interval, which can be a proportion of the segment length, or a constant
# At distance n from the source line
calc_perp <-function(p1,p2,n,interval=0.5,proportion=TRUE) {
# Calculate x and y distances
x_len <- p2[1] - p1[1]
y_len <- p2[2] - p1[2]
# If proportion calculate reference point from tot_length
if (proportion) {
point <- c(p1[1]+x_len*interval,p1[2]+y_len*interval)
}
# Else use the constant value
else {
tot_len <- euclidean_distance(p1,p2)
point <- c(p1[1]+x_len/tot_len*interval,p1[2]+y_len/tot_len*interval)
}
# Calculate the x and y distances from reference point to point on line n distance away
ref_len <- euclidean_distance(point,p2)
xn_len <- (n / ref_len) * (p2[1] - point[1])
yn_len <- (n / ref_len) * (p2[2] - point[2])
# Invert the x and y lengths and add/subtract from the refrence point
ref_points <- rbind(point,c(point[1] + yn_len,point[2] - xn_len),c(point[1] - yn_len,point[2] + xn_len))
# Return the reference points
return(ref_points)
}
Examples
> calc_perp(c(0,0),c(1,1),1)
[,1] [,2]
point 0.5000000 0.5000000
1.2071068 -0.2071068
-0.2071068 1.2071068
> calc_perp(c(0,0),c(1,1),sqrt(2)/2,0,proportion=FALSE)
[,1] [,2]
point 0.0 0.0
0.5 -0.5
-0.5 0.5
This is how the revised function looks geometrically with your example and n = 10 for distance from line:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56771058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access a custom field from and RSS feed in WordPress I am trying to access a custom field from an RSS feed in WordPress (using SimplePie), but I am not able to
// get HCBC feed
$media_rss = fetch_feed('feed.theplatform.com/f/IfSiAC/VfW_gmOIG_yI');
if(!is_wp_error($media_rss)) {
// get limit of 5 items
$max_items = $media_rss->get_item_quantity(5);
// add items to indexed array starting at 0
$rss_items = $media_rss->get_items(0, $max_items);
}
foreach($rss_items as $item) {
$public_url = $item->get_item_tags('plmedia', 'publicUrl');
print_r($public_url);
}
you can see in the RSS that the namespace and tag are there, but for some reason $public_url is always empty. I'm not sure what I am doing wrong.
A: Turns out I didn't understand what the namespace was supposed to be. The following is correct:
foreach($rss_items as $item) {
$public_url = $item->get_item_tags('http://xml.theplatform.com/media/data/Media', 'publicUrl');
print_r($public_url);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36747681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Spotify API OAuth 2.0 - Why is the GET request to /callback renewing the code query param everytime I refresh the website? I'm using TypeScript, Node, and Express along with TSOA and Swagger to generate self-writing docs.
When the user makes a GET request to /login, they are redirected to this link: http://localhost:{PORT}/callback?code={code}, which gives them the access token along with the other information:
access_token "randomized access token"
token_type "Bearer"
expires_in 3600
refresh_token "randomized refresh_token"
scope "ugc-image-upload user-re…ition user-read-private"
This is great, and it's exactly what I want, but refreshing this link http://localhost:{PORT}/callback?code={code} gives me the following:
error "invalid_grant"
error_description "Invalid authorization code"
This is odd because it didn't happen before, refreshing the link kept the same access token and other information for up to 3600 seconds. I looked around more, and it seems like it's because I'm getting a new code query parameter every single time i redirect to any route within the app. I'm not sure why this is happening, and I'd like to retain the same code query parameter for up to 3600 seconds for each user before it refreshes. Here is my code:
loginController.ts
import { Controller, Route, Get, Tags, Request } from 'tsoa';
import express from 'express';
import querystring from 'querystring';
import * as dotenv from 'dotenv';
const SCOPE =
'user-read-recently-played user-read-email user-read-private user-read-recently-played user-read-playback-position user-read-playback-state ugc-image-upload';
dotenv.config({ path: '.env' });
export const REDIRECT_URI = 'http://localhost:8888/callback';
const { CLIENT_ID } = process.env;
@Route('/login') // route name => localhost:xxx/login
@Tags('LoginController') // => Under LoginController tag
export class LoginController extends Controller {
@Get() //specify the request type
public Login(@Request() request: express.Request): void {
const callbackLogin =
'https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: CLIENT_ID,
scope: SCOPE,
redirect_uri: REDIRECT_URI,
});
request.res?.redirect(callbackLogin);
}
}
callbackController.ts
import { Controller, Route, Get, Tags, Request } from 'tsoa';
import * as dotenv from 'dotenv';
import express from 'express';
import { fetchSpotifyToken } from './routes/fetchSpotifyToken';
dotenv.config({ path: '.env' });
export const REDIRECT_URI = 'http://localhost:8888/callback';
const { CLIENT_ID, CLIENT_SECRET } = process.env;
interface Body {
access_token: string;
token_type: string;
scope: string;
expires_in: string;
}
@Route('/callback') // route name => localhost:xxx/callback
@Tags('CallbackController') // => Under CallbackController tag
export class CallbackController extends Controller {
@Get() //specify the request type
public async Callback(@Request() request: express.Request): Promise<Body> {
if (CLIENT_ID === undefined) {
throw new Error('CLIENT_ID is undefined');
} else if (CLIENT_SECRET === undefined) {
throw new Error('CLIENT_SECERET is undefined');
} else {
const COMBINED_IDS = `${CLIENT_ID}:${CLIENT_SECRET}`;
try {
const spotifyResponse = await fetchSpotifyToken<Body>({
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${Buffer.from(COMBINED_IDS).toString(
'base64',
)}`,
},
credentials: 'include', // Don't forget to specify this if you need cookies
method: 'POST',
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
body: `code=${request.query['code']}&redirect_uri=${REDIRECT_URI}&grant_type=authorization_code`,
});
request.res?.setHeader(
'Set-Cookie',
`accessToken=${spotifyResponse.access_token}; Max-Age=3000; HttpOnly, Secure`,
);
return spotifyResponse;
} catch (error) {
throw new Error(JSON.stringify(error));
}
}
}
}
export const getToken = new CallbackController();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73179757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to disable Javers from creating Tables when starting application I am trying to work on an application which fails to start up due to Javers table creation errors(Issue is due to application DB problems). Is there a way I can prevent javers from creating tables during application start up (tables such as jv_commit)so I can work on the app while DBA fixes DB issues(this will take time)?
I have added following in application.yml, (not sure if its the right way to go)
Javers:
sqlSchemaManagementEnabled: false
auditableAspectEnabled: false
springDataAuditableRepositoryAspectEnabled: false
I have commented out @JaversSpringDataAuditable in all repository classes as well.
Javers dependency used
<dependency>
<groupId>org.javers</groupId>
<artifactId>javers-spring-jpa</artifactId>
<version>5.7.0</version>
</dependency>
Error log
2019-10-16 16:51:32,796 25724 INFO [main] o.p.core.schema.SchemaManagerImpl [SchemaManagerImpl.java:51] --- creating entity with name jv_commit using ddl:
CREATE TABLE jv_commit (
commit_pk NUMBER NOT NULL,
author VARCHAR2(200),
commit_date TIMESTAMP,
commit_date_instant VARCHAR2(30),
commit_id NUMBER(22,2),
CONSTRAINT jv_commit_pk PRIMARY KEY(commit_pk)
)
2019-10-16 16:51:33,903 25724 WARN [main] o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext [AbstractApplicationContext.java:557] --- Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'javers' defined in class path resource [com/common/audit/JaversSpringJpaApplicationConfig.class]: Invocation of init method failed; nested exception is org.polyjdbc.core.exception.SchemaManagerException: [DDL_ERROR] Failed to run DDL:
CREATE TABLE jv_commit (
commit_pk NUMBER NOT NULL,
author VARCHAR2(200),
commit_date TIMESTAMP,
commit_date_instant VARCHAR2(30),
commit_id NUMBER(22,2),
CONSTRAINT jv_commit_pk PRIMARY KEY(commit_pk)
)
2019-10-16 16:51:33,935 25724 INFO [main] o.s.o.j.LocalContainerEntityManagerFactoryBean [AbstractEntityManagerFactoryBean.java:597] --- Closing JPA EntityManagerFactory for persistence unit 'default'
2019-10-16 16:51:33,938 25724 INFO [main] com.zaxxer.hikari.HikariDataSource [HikariDataSource.java:350] --- HikariPool-1 - Shutdown initiated...
2019-10-16 16:51:36,487 25724 INFO [main] com.zaxxer.hikari.HikariDataSource [HikariDataSource.java:352] --- HikariPool-1 - Shutdown completed.
2019-10-16 16:51:36,493 25724 INFO [main] o.a.catalina.core.StandardService [DirectJDKLog.java:173] --- Stopping service [Tomcat]
2019-10-16 16:51:36,496 25724 INFO [main] c.v.u.c.filter.AuditLoggingFilter [AuditLoggingFilter.java:195] --- in Filter destroy method
2019-10-16 16:51:36,516 25724 WARN [main] o.a.c.loader.WebappClassLoaderBase [DirectJDKLog.java:173] --- The web application [ROOT] appears to have started a thread named [RxIoScheduler-1 (Evictor)] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
sun.misc.Unsafe.park(Native Method)
java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
2019-10-16 16:51:36,528 25724 INFO [main] o.s.b.a.l.ConditionEvaluationReportLoggingListener [ConditionEvaluationReportLoggingListener.java:135] ---
A: The sqlSchemaManagementEnabled switch is managed by the JaVers Spring Boot starter, see https://javers.org/documentation/spring-boot-integration/
If you don't use the starter the switch won't be read, but still you can set this switch when building a Javers instance:
def javers = JaversBuilder.javers()
.registerJaversRepository(sqlRepository()
.withConnectionProvider({ DriverManager.getConnection("jdbc:h2:mem:empty-test") } as ConnectionProvider)
.withSchemaManagementEnabled(false)
.withDialect(getDialect())
.build()).build()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58412204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can I use the rpois to produce the random number under the different mean I want to write a function to do some calculate. And in this function I want to use the rpois to produce the random number y1 under the different mean n1*2.4. I find this function cannot get my aim, so I want to know how I should edit my function.
myfunC1 <- function(t1) {
t1 = seq(1, 3000, 1)
n1 <- 13.8065 / (1 + exp(-(t1 - 11.8532) / 26.4037))
y1 <- rpois(1, n1 * 2.4)
c <- log(2.7 / 2.4) * (y1 / n1 - (2.7 - 2.4) / (log(2.7) - log(2.4)))
result <- c
}
And I also want to know how I should write a function to calculate the following statement without using the for loop. The y and Lt is already known in this statement.
G[t]=max{0,0.85*G[t−1]+L[t]}
A: Your function with some change:
myfunC1<-function(t1) {
n1<-13.8065/(1+exp(-(t1-11.8532)/26.4037))
y1<-unlist(lapply(n1*2.4, rpois, n=1))
c<-log(2.7/2.4)*(y1/n1-(2.7-2.4)/(log(2.7)-log(2.4)))
return(c)
}
Your output:
t1<-seq(1,10,1)
myfunC1(t1)
[1] -0.043210706 0.076575495 0.006905820 -0.139863770 -0.045328088 0.006866088 -0.037032547 -0.079171724
[9] -0.083574188 0.018280450
About the second part of your question, you can use an approach like this one:
L<-runif(10,1,10)
G<-runif(10,1,10)
myfunC2<-function(G,L,t)
{
return(max(0,0.85*G[t−1]+L[t]))
}
unlist(lapply(rep(1:length(L)),myfunC2, G=G, L=L))
[1] 0.000000 14.094739 7.489582 14.268056 16.318365 9.115776 11.729936 7.091494 16.030881 9.289892
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49193943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get cell formatting Is there a function to get the activecell formatting? e.g. background color, font, font color, cell border, font size etc.
I want to update the format of an entire worksheet based on a formatted cell before action (i.e. the format I want to change) by another formatted cell (i.e. the format I want to apply).
Sub Rep_all_format()
Dim fmt_bef As CellFormat
Dim fmt_aft As CellFormat
Dim rngReplace As Boolean
Dim msg As String
Dim Sh As Worksheet
Dim Rg As Range
Dim ppos1 As Range
Dim ppos2 As Range
Dim Find As String
Dim Remplace As String
Set ppos1 = Application.InputBox(Prompt:="Select the cell format you wanna change", Title:="Remplace", Default:=ActiveCell.Address, Type:=8)
Set ppos2 = Application.InputBox(Prompt:="Select the cell format you wanna apply", Title:="Select", Type:=8)
Find = ppos1.FormatConditions 'this is theorical I do not know the function
Remplace = ppos2.FormatConditions 'this is theorical I do not know the function
Application.ScreenUpdating = False
Set fmt_bef = Application.FindFormat
Set fmt_aft = Application.ReplaceFormat
For Each Sh In ThisWorkbook.Worksheets
Set Rg = Sh.UsedRange
With fmt_bef
.Clear
.FormatConditions = Find
End With
With fmt_aft
.Clear
.FormatConditions = Remplace
End With
Rg.Replace What:="", Replacement:="", _
SearchFormat:=True, ReplaceFormat:=True
Next
fmt_bef.Clear
fmt_aft.Clear
Application.ScreenUpdating = True
MsgBox ("The desired format has been applied through all the workbook")
End Sub
A: Assuming, from the code that you have provided, that your cell has been formatted using Conditional Formatting, you need to access is the Range.DisplayFormat property.
Note that I showed only some of the formatting options for a cell. There is documentation online for other formatting options (eg other borders, numberformat, etc) but this should get you started.
For example:
Option Explicit
Sub foo()
Dim R As Range, C As Range
Dim fc As FormatCondition
Set R = Range(Cells(1, 1), Cells(5, 1))
For Each C In R
With C.DisplayFormat
Debug.Print .Interior.Color
Debug.Print .Font.Name
Debug.Print .Font.Color
Debug.Print .Borders(xlEdgeLeft).LineStyle ' etc
Debug.Print .Font.Size
End With
Stop
Next C
End Sub
If the cell has been formatted manually, or directly using code, then just access the various properties directly, not using the DisplayFormat property eg:
For Each C In R
With C
Debug.Print .Interior.Color
Debug.Print .Font.Name
Debug.Print .Font.Color
Debug.Print .Borders(xlEdgeLeft).LineStyle ' etc
Debug.Print .Font.Size
End With
Stop
Next C
A: What you are looking for are the Range.Interior and Range.Font properties etc.
You can see some examples in the links below:
https://learn.microsoft.com/en-us/office/vba/api/excel.font(object)
https://learn.microsoft.com/en-us/office/vba/api/excel.interior(object)
https://learn.microsoft.com/en-us/office/vba/api/excel.border(object)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58603723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "Unable to locate package build-essential" while Docker build on Debian Jessie I'm trying to run a Dockerfile that had worked very well until few days ago:
FROM python:2.7
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && apt-get install -y build-essential xorg libssl-dev libxrender-dev wget gdebi
RUN wget http://download.gna.org/wkhtmltopdf/0.12/0.12.2.1/wkhtmltox-0.12.2.1_linux-jessie-amd64.deb
RUN gdebi --n wkhtmltox-0.12.2.1_linux-jessie-amd64.deb
EXPOSE 80
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt
RUN ["sh", "-c", "python", "manage.py", "db", "upgrade"]
CMD ["python", "server.py"]
The problem happens during the apt-get install:
E: Unable to locate package build-essential
E: Unable to locate package xorg
E: Unable to locate package gdebi
I checked the python:2.7 Dockerfile, they build it with a buildpack-deps:jessie image, which is a debian:jessie image.
I changed nothing since the day it worked well and this Dockerfile run on Amazon Elastic Beanstalk, so it's not some kind of network problem.
I tried locally and I got the same errors, so I guess it comes from some changes made in the docker OS images, from the Debian or the buildpack-deps team.
Here is the source.list (from python:2.7):
deb http://httpredir.debian.org/debian jessie main
deb http://httpredir.debian.org/debian jessie-updates main
deb http://security.debian.org jessie/updates main
Also, I don't know how to find in which repo I can find those packages, they say nothing about that on the Debian doc... (https://packages.debian.org/fr/jessie/build-essential)
EDIT
After a new full test on local machine, it worked well, So I guess the problem come from Amazon itself...
A: It seems fixed on Amazon side, there is no more apt-get install failling on Amazon for me, even on load-balanced :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33916083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: handle url through iframe I have a facebook application written in angularjs, it all works like a charm
except for the fact that as I go trough the various links of the application
such as http://[baseurl]/#/item/25 this does not reflect the url shown in the navigation bar that still remains http://apps.facebook.com/MyTestApp/
So the thing that I'd need here, would be the ability to reflect the angularjs routing outside the iframe that contains my app.
A: In the end I've managed the situation by parsing a parameter in the url something like
http://apps.facebook.com/MyTestApp/index.php?p=goto#item/48
so, by one hand, as soon as I land on the index.php, via php I check for the $_GET['vairable'] and use that as a trigger to get the hash string to feed a javascript variable that is directly executed, before the angluar is included. So as soon as the mainController (the angular controller associated with the index) is executed the variable with the path is already instantiated.
At this point angular detects that there is a variable that forces the path to go somewhere and it will get the routing there.
here's some code
the index.php in the tag, right after the jquery lib inclusion and right before
the angular includes
<script language="javascript" type="text/javascript">
var redirect_to = null;
$(function() {
<?php
// redirecting rulez
if(isset($_GET['p'])) {
?>
redirect_to = window.parent.location.hash.substring(1);
<?php
}
?>
});
</script>
the mainControl.js that is the one that get hit al the times that you load the index.php
if(redirect_to != null)
$location.path(redirect_to);
in the other controllers
if(redirect_to != null)
window.parent.location.hash = "#" + $location.path();
repeat for all the other controllers. enjoy
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15414356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Font causing SSL issues I'm in panic, since I installed a theme based on bootstrap 3, I run into security issues over my HTTPS protocole caused by unsecured content calls.
Here is an example :
Insecure URL: http://www.materieldirect.com/themes/theme867/fonts/glyphicons-halflings-regular.eot
Found in: https://www.materieldirect.com/themes/theme867/css/bootstrap.min.css
Both of my CDN and SSL provider say it comes from my CSS files making unsecured calls.
After a closer look in my bootstrap.min.css I see these lines :
@font-face{font-family:'Glyphicons Halflings';
src:url('../fonts/glyphicons-halflings-regular.eot');
src:url('../fonts/glyphicons-halflings-regular.eot?#iefix')
What do you guys suggest to solve this issue ?
I red somewhere I should use relative paths, shall I in this case use :
src:url('/glyphicons-halflings-regular.eot');
instead of
src:url('../fonts/glyphicons-halflings-regular.eot');
My major concern is about general site performance and offer best browsing experience to my visitors.
I'd like my content to be delivered over SSL only when it's required on HTPPS pages, and not make constant calls for HTTPS content to be displayed on HTTP pages as well.
Your help would be much appreciated !
Thanks in advance
A: A little feedback about my issue, I was looking at wrong place and should have open my eyes wider. I had a non relative link for an external font :
<link href='http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic&subset=latin,cyrillic-ext,greek-ext,greek,vietnamese,latin-ext,cyrillic' rel='stylesheet' type='text/css'>
Changed to <link href='//fonts...
No more issues
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21305810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Refresh_token using oauth.io Hi I am student of Computer Science and doing some experiments on oauth.io. but i am facing problem to get refresh_token after getting code successfully. After getting the code i am writing the follwing line of code but its giving me Internal server error..
The code is
$.ajax("https://oauth.io/auth/access_token", {
type: "post",
data: {
code: result.code,
key: '5WeOrrR3tP6RyShR1',
secret: '2_q3tb_D_qgDwSGpt' },
success: function (data) {
console.log("result", data);
}
});
Which url used to get refresh_token? please someone help me.
thanks
A: there was a bug recently in the js sdk when you set the response type server-side (to get the code & refresh_token), so you may have to redownload oauth.js if you use a static version.
I guess your jquery code is server side (because of the nodejs tag and the use of a code), but i had an error "no transport" that i fixed with a new XMLHttpRequest. Here is my full test:
var jsdom = require('jsdom').jsdom;
var win = jsdom().createWindow();
var $ = require('jquery')(win);
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
$.support.cors = true;
$.ajaxSettings.xhr = function () {
return new XMLHttpRequest;
}
$.ajax("https://oauth.io/auth/access_token", {
type: "post",
data: {
code: process.argv[2],
key: 'xxxxxxxxxxxx',
secret: 'yyyyyyyyyyyy' },
success: function (data) {
console.log("result", data);
},
error: function() {
console.error(arguments);
}
});
and my result looks like:
{ access_token: 'xxxxxxxxxxx',
request:
{ url: '{{instance_url}}',
required: [ 'instance_url' ],
headers: { Authorization: 'Bearer {{token}}' } },
refresh_token: 'yyyyyyyyyyyyy',
id: 'https://login.salesforce.com/id/00Db0000000ZbGGEA0/005b0000000SSGXAA4',
instance_url: 'https://eu2.salesforce.com',
signature: 'zzzzzzzzzzzzz',
state: 'random_string',
provider: 'salesforce' }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21218345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unity test ads are showing up only in editor In my case its seems like the unity's test ads are showing up only in editor. I dont see any test ads window in my device(Samsung S7). Anyone know fixes for this? I post the code here and I called the PlayInterstitialAd() methid when the game is over. I'm using unity 2019.3.10 and unity monetization 3.4.4
Many Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Advertisements;
public class AdsManager : MonoBehaviour, IUnityAdsListener
{
private string playStoreID = "123";
private string apsStoreId = "123";
private string interstitialAd = "video";
private string rewardedVideoAd = "rewardedVideo";
public bool isTargetPlayStore;
public bool isTestAd;
private void Start()
{
Advertisement.AddListener(this);
InitAds();
}
public void InitAds()
{
if (isTargetPlayStore)
{
Advertisement.Initialize(playStoreID, isTestAd);
return;
}
Advertisement.Initialize(apsStoreId, isTestAd);
}
public void PlayInterstitialAd()
{
if (!Advertisement.IsReady(interstitialAd))
{
return;
}
Advertisement.Show(interstitialAd);
}
public void PlayRewardedAd()
{
if (!Advertisement.IsReady(rewardedVideoAd))
{
return;
}
Advertisement.Show(rewardedVideoAd);
}
public void OnUnityAdsReady(string placementId)
{
//throw new System.NotImplementedException();
}
public void OnUnityAdsDidError(string message)
{
// throw new System.NotImplementedException();
}
public void OnUnityAdsDidStart(string placementId)
{
// throw new System.NotImplementedException();
}
public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{
// throw new System.NotImplementedException();
}
}
A: This is probably because the package is outdated.
In my case it didn't work because I used the unity monetization version of the asset store instead of the one in the unity package editor, cause since version 2018.3 it stopped working.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61863498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When I try to output an element in a position in main(), an exception is thrown I create a partition and union structure. It can make a set and return the position of that set. In my code, my partition class has a listSet class.
The problem is I cannot output element in the main() after I return the position of a set, but in the function makeSet(), I can output the element. I do not know if my data type of makeSet() correct or not.
How could I fix the bug? Should I return a pointer in makeSet()?
#ifndef LISTSET_H
#define LISTSET_H
#include <iostream>
#include <vector>
using namespace std;
template<typename E>
class Partition
{
public:
typedef typename vector<E>::iterator Itr; //create an iterator
public:
template <typename E>
class listSet //create an class listSet
{
private:
vector<E> L;
int size;
public:
listSet() { size = 1; }
int getSize() { return size; }
Itr insert(E e) /*return a position*/
{
L.push_back(e);
Itr p = L.begin();
//cout << *p << endl; //OK
return p;
}
};
public:
Itr makeSet(E e);
};
template<typename E>
typename Partition<E>::Itr Partition<E>::makeSet(E e)
{
listSet<E> set;
Itr p = set.insert(e);
cout << *p << endl; //OK
return p;
}
#endif
int main()
{
Partition<int> set1;
Partition<int>::Itr p1, p2, p3;
p1 = set1.makeSet(1);
p2 = set1.makeSet(2);
cout << *p1 << endl; //error is here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72739351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML position sidebar next to content i am currently trying to move my sidebar from below the content box to the right of it alongside it. No matter what i try it stays at a certain point no going up any higher. My website is VAGUE LINES, where if you scroll down a bit u will be able to see exactly what i am saying.
Below is my css code thanks alot:
h1
{
text-align:center;
font-family:sans-serif;
letter-spacing:12px;
padding-bottom:6px;
border-top:1px solid rgb;
margin-top:35px;
color:#544E4F;
font-weight:lighter;
}
hr
{
display:overline-block;
width:200px;
}
#header
{
background: #FFFFFF;
text-align: center;
}
#navigation ul
{
margin: 0;
padding: 0;
list-style-type: none;
text-align: center;
}
#navigation ul li
{
display: inline;
padding-right: 30px;
}
#navigation ul li a
{
text-decoration: none;
padding: .3em 5em;
color: #000000;
background-color: #FFFFFF;
font-family: courier;
}
#navigation ul li a:hover
{
text-decoration: line-through;
}
.centeredImage
{
float: none;
margin: 4% 0 2% 9%;
text-align: center;
padding-bottom: 25px;
}
#main-content hr
{
width :66%;
margin-left: 9%;
}
#main-content
{
width:80%;
padding-left: 113px;
padding-top: 20px;
}
#page-wrap {
background: white;
min-width: 780px;
max-width: 1260px;
margin: 10px auto;
}
#page-wrap #inside {
margin: 10px 10px 0px 10px;
padding-top: 10px;
padding-bottom: 10px;
}
#sidebar{
border-top: 1px solid #99CC33;
border-left: 1px solid #99CC33;
height: 300px;
width: 200px;
margin-right: 5px;
padding: 5px 0 0 5px;
position:absolute;
}
#main-content p
{
margin-left: 10%;
font-family: courier;
font-size: 14px;
}
#heading p
{
margin-left: 10%;
font-family: sans-serif;
font-size: 14px;
}
#sidebar p
{
margin-left: 10%;
font-family: courier;
font-size: 14px;
font-weight:bold;
}
A: Try this:
#main-content
{
float: left; // float element to the left side
width:80%;
padding-left: 113px;
padding-top: 20px;
}
#sidebar{
border-top: 1px solid #99CC33;
border-left: 1px solid #99CC33;
height: 300px;
width: 200px;
margin-right: 5px;
padding: 5px 0 0 5px;
position:absolute;
right: 0; // position element to the right
}
EDIT: Sorry. You wanted sidebar on the right.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15063913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: filling a circle gradually from bottom to top android I have created a circle with a stroke and white background using xml. How can this be filled gradually from bottom to top on user actions(e.g. on successive button press)?
Is there any free library which can be used to achieve similar thing?
A: I created a Custom View class that will do what you want. There are four custom attributes that can be set in your layout xml:
*
*fillColor, color - Sets the color of the fill area. Default is Color.WHITE.
*strokeColor, color - Sets the color of the bounding circle. Default is Color.BLACK.
*strokeWidth, float - Sets the thickness of the bounding circle. Default is 1.0.
*value, integer: 0-100 - Sets the value for the fill area. Default is 0.
Please note that these attributes must have the custom prefix in lieu of the android prefix in your layout xml. The root View should also contain the custom xml namespace. (See the example below.) The other standard View attributes - such as layout_width, background, etc. - are available.
First, the CircleFillView class:
public class CircleFillView extends View
{
public static final int MIN_VALUE = 0;
public static final int MAX_VALUE = 100;
private PointF center = new PointF();
private RectF circleRect = new RectF();
private Path segment = new Path();
private Paint strokePaint = new Paint();
private Paint fillPaint = new Paint();
private int radius;
private int fillColor;
private int strokeColor;
private float strokeWidth;
private int value;
public CircleFillView(Context context)
{
this(context, null);
}
public CircleFillView(Context context, AttributeSet attrs)
{
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CircleFillView,
0, 0);
try
{
fillColor = a.getColor(R.styleable.CircleFillView_fillColor, Color.WHITE);
strokeColor = a.getColor(R.styleable.CircleFillView_strokeColor, Color.BLACK);
strokeWidth = a.getFloat(R.styleable.CircleFillView_strokeWidth, 1f);
value = a.getInteger(R.styleable.CircleFillView_value, 0);
adjustValue(value);
}
finally
{
a.recycle();
}
fillPaint.setColor(fillColor);
strokePaint.setColor(strokeColor);
strokePaint.setStrokeWidth(strokeWidth);
strokePaint.setStyle(Paint.Style.STROKE);
}
public void setFillColor(int fillColor)
{
this.fillColor = fillColor;
fillPaint.setColor(fillColor);
invalidate();
}
public int getFillColor()
{
return fillColor;
}
public void setStrokeColor(int strokeColor)
{
this.strokeColor = strokeColor;
strokePaint.setColor(strokeColor);
invalidate();
}
public int getStrokeColor()
{
return strokeColor;
}
public void setStrokeWidth(float strokeWidth)
{
this.strokeWidth = strokeWidth;
strokePaint.setStrokeWidth(strokeWidth);
invalidate();
}
public float getStrokeWidth()
{
return strokeWidth;
}
public void setValue(int value)
{
adjustValue(value);
setPaths();
invalidate();
}
public int getValue()
{
return value;
}
private void adjustValue(int value)
{
this.value = Math.min(MAX_VALUE, Math.max(MIN_VALUE, value));
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
center.x = getWidth() / 2;
center.y = getHeight() / 2;
radius = Math.min(getWidth(), getHeight()) / 2 - (int) strokeWidth;
circleRect.set(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
setPaths();
}
private void setPaths()
{
float y = center.y + radius - (2 * radius * value / 100 - 1);
float x = center.x - (float) Math.sqrt(Math.pow(radius, 2) - Math.pow(y - center.y, 2));
float angle = (float) Math.toDegrees(Math.atan((center.y - y) / (x - center.x)));
float startAngle = 180 - angle;
float sweepAngle = 2 * angle - 180;
segment.rewind();
segment.addArc(circleRect, startAngle, sweepAngle);
segment.close();
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawPath(segment, fillPaint);
canvas.drawCircle(center.x, center.y, radius, strokePaint);
}
}
Now, for the custom xml attributes to work, you will need to put the following file in the /res/values folder of your project.
attrs.xml:
<resources>
<declare-styleable name="CircleFillView" >
<attr name="fillColor" format="color" />
<attr name="strokeColor" format="color" />
<attr name="strokeWidth" format="float" />
<attr name="value" format="integer" />
</declare-styleable>
</resources>
Following are the files for a simple demonstration app, where the CircleFillView's value is controlled with a SeekBar.
The layout file for our Activity, main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.example.circlefill"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<com.example.circlefill.CircleFillView
android:id="@+id/circleFillView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ffffff"
custom:fillColor="#6bcae2"
custom:strokeColor="#75b0d0"
custom:strokeWidth="20"
custom:value="65" />
<SeekBar android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
And, the MainActivity class:
public class MainActivity extends Activity
{
CircleFillView circleFill;
SeekBar seekBar;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
circleFill = (CircleFillView) findViewById(R.id.circleFillView);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setProgress(circleFill.getValue());
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
if (fromUser)
circleFill.setValue(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
}
);
}
}
And a screenshot of the demo app:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24858531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: SQLAlchemy Enums Code Representation _and_ DB Representation This is a follow up to the very interesting answers of best-way-to-do-enum-in-sqlalchemy. Cito extends Zzzeeks answer to include ordering which is very nice. Cito also leaves a tantalizing bit of code near the end.
class DeclEnumType(SchemaType, TypeDecorator):
"""DeclEnum augmented so that it can persist to the database."""
This is exactly what I am attempting to do build a Python Enum that is represented in its own table in the db. Where the EmployeeType.full_time is usable in Python code and has its own table in the DB (for this simple example just a idx and name).
However, I'm not sure I understand how to use Cito's DeclEnumType example as the following doesn't create a EmployeeType table in the database.
class EmployeeType(DeclEnum):
# order will be as stated: full_time, part_time, contractor
full_time = EnumSymbol("Full Time")
part_time = EnumSymbol("Part Time")
contractor = EnumSymbol("Contractor")
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
name = Column(String(60), nullable=False)
type = Column(DeclEnumType(EmployeeType))
Any ideas on how to get this dual representation?
A: If I'm not mistaken, doing:
type = Column(EmployeeType.db_type())
instead of
type = Column(DeclEnumType(EmployeeType))
should do it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15033177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to handle two "Iot hub" devices in "stream analytics job"? I am using "stream analytics jobs" to visualize the data that comes from two different devices of an "iot hub", the device1 and the device2; the device1 sends the following message:
{"messageId": 5576, "deviceId": "Raspberry Pi Web", "rpm": 22.80972122577826, "torque": 72.65678451219686}
The device2 sends the following message:
{"messageId": 1272, "deviceId": "Raspberry Pi Web Client", "temperature": 23.815921380797004, "humidity": 78.7491052866882}
The messages are sent at the same time and when I want to visualize the data in power bi, I only see the keys of one of the messages, messageId, temperature, humidity, PartitionId. these keys belong to the message sent by the device2; but the messageId, rpm, torque, PartitionId keys that correspond to device1 do not appear.
The query I am using in the stream analytics job is the following:
SELECT
*
INTO
output
FROM
input
My devices are simulated devices that I use and configure from the following link: https://azure-samples.github.io/raspberry-pi-web-simulator/#Getstarted
How can I see messages from two different devices in the same iot hub with stream analytics job?
Note: I am using F1 level in "IoT Hub"
I appreciate your help
A: In PowerBI, one dataset represents a single source of data and has to be in a format:
There are literally hundreds of different data sources you can use
with Power BI. But regardless of where you get your data from, that
data has to be in a format the Power BI service can use to create
reports and dashboards.
Reference: dataset concept and data source for Power BI.
For your issue you can route two devices events to two Power BI dataset.(two outputs in ASA job).
The query looks like this:
SELECT
*
INOT
powerbi
FROM
iothubevents
WHERE
deviceId = 'Raspberry Pi Web'
SELECT
*
INOT
powerbidevice2
FROM
iothubevents
WHERE
deviceId = 'Raspberry Pi Web Client'
See these snapshots:
In stream analytics job:
In Power BI:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50339654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change image sky with time of handler tick Recently I put a post about How to change the image sky with time
here
But, for the change of image I use the setTimeout function, I need to use the handler tick, to change image.
This HTML
<a-scene>
<a-sky id="ou" material="opacity:1; src: ./3D/letras/Horizonte.jpg" foo>
<a-animation id="fadeout-animation" attribute="material.opacity" dur="1000" direction="forward" from="1" to="0" begin="fadeout"></a-animation>
<a-animation id="fadein-animation" attribute="material.opacity" dur="1000" direction="forward" from="0" to="1" begin="fadein"></a-animation>
</a-sky>
<!--<a-sky material="opacity:1; src: ./3D/letras/Horizonte.jpg" foo></a-sky>-->
</a-scene>
This my component
AFRAME.registerComponent("foo", {
init: function () {
//Math.floor(time);
var self = this.el;
var fadeOutAnim = document.querySelector("#fadeout-animation");
var images = ["./3D/letras/Agua.jpg", "./3D/letras/Aire.jpg", "./3D/letras/hector.jpg"];
var index = 0;
fadeOutAnim.addEventListener("animationend", (e) => {
self.setAttribute("material", "src", images[index]);
index++;
self.emit('fadein');
});
},
tick: function (time, timeDelta) {
time = Math.floor(time);
console.log(time);
var el = this.el;
var fadeInAnim = document.querySelector("#fadein-animation");
fadeInAnim.addEventListener("animationend", (e) => {
if (time >= 5000 && time <= 5030) {
el.emit('fadeout');
}
});
if (time >= 5000 && time <= 5030) {
el.emit('fadeout');
}
},
}
);
Question:
Is there any way to use tic time, to change?
Thanks one more time
code working
A: You could have a temporary variable which will count the time using dt, and when it exceeds the time limit (5s ?) then set it back to 0;
AFRAME.registerComponent("foo", {
init: function() {
this.timer = 0
this.flip = false
},
tick(function(time, dt) {
this.timer += dt
if (this.timer > 1000) {
console.log("second has passed")
if (flip)
//fadein
else
//fadeout
this.flip = !this.flip
this.timer = 0
}
}
}
live fiddle here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49786022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Codeigniter controller created when image not found I have a problem in CodeIgniter, and that is that when an image is not found on the server, the instance of a controller is created (besides the one that called the view).
I know all this can sound confusing, so this is the code to observe what I'm saying. I did this changes to a clean 2.1.0 CI version:
Add a controller to override the 404 error page, I added this one:
// add application/controllers/Errors.php
Class Errors extends CI_Controller {
public function error_404() {
echo 'error';
}
}
// change routes.php
$route['404_override'] = 'Errors/error_404';
Use a controller that isn’t the default one with an unexisting image, I used this:
// add application/controllers/Foo.php
Class Foo extends CI_Controller {
public function index() {
echo '<img src="doesntexist.png" />';
}
}
I couldn’t figure out another way of debugging it, so I created a log to write the events on CodeIgniter.php:
// add on CodeIgniter.php line 356
$path = 'log.txt'; //Place log where you can find it
$file = fopen($path, 'a');
fwrite($file, "Calling method {$class}/{$method} with request {$_SERVER['REQUEST_URI']}\r\n");
fclose($file);
With this, the log that generates visiting the index function is the following:
Calling method Foo/index with request /test/index.php/Foo
Calling method Errors/error_404 with request /test/index.php/doesntexist.png
Which is the problem I have, an instance of the Error class is created.
A: that is that when an image is not found on the server, the instance of a controller is created
Not really. What I believe is happening is that, since you're using a relative path for the image (and calling it directly inside a controller, which is wrong because you're ouputting something before headers), your browser attach the image directly to the CI url, thus making this request to the server:
index.php/doesntexist.png
Which is (correctly) interpreted by CI as a request to a controller, which doesn't exists, and therefore it issues the error class.
You could do, in your actual code (I'd put the images in a view, though):
echo '<img src="/doesntexist.png" />'
using an absoluth path, or using the base_url() method from the url helper:
echo '<img src="'.base_url().'doesntexist.png" />
This should tell the server to fetch the right request (/test/doesntexist.png) and won't trigger that error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9582175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Function to check mathematical expression not working The Function to check mathematical expression not working.
I debugged this on chrome, and i saw that when it gets to the first pop (stack.pop()!== chars[i]), it returns false, but it shouldn't.
var smarter_validate = function(str) {
var chars = str.split('');
var stack = [];
var lookup = {
'(': ')',
'[': ']',
'{': '}',
'<': '>'
};
var left = Object.keys(lookup);
var right = Object.keys(lookup).map(function(key) {
return lookup[key]
});
for (var i = 0; i < chars.length; i++) {
if (left.indexOf(chars[i]) !== (-1)) {
stack.push(chars[i]);
} else if (right.indexOf(chars[i]) !== (-1)) {
if ((stack.length === 0) || (stack.pop() !== chars[i])) {
return false;
}
}
}
return (stack.length === 0);
};
console.log("SMART VALIDATE" + smarter_validate('(3+4[*2{6+8}])'));
A: You actually have to compare the popped value's corresponding closing character with chars[i], not the popped value itself.
So you need to do
if (stack.length === 0 || lookup[stack.pop()] !== chars[i]) {
Now, when you { from the stack, you will look for the corresponding closing character from the lookup and compare it with the current closing character.
Alternatively you can simply push the expected closing character in the stack so that you don't have do the lookup during the comparison, like this
stack.push(lookup[chars[i]]);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34753932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Bullets in a Xaml Tooltip Everything is in the title. I'd like to be able to add some bullet list in a Tooltip but so far haven't found any simple way.
thanks in advance!
A: You want to use the BulletDecorator as part of the ToolTip. Example:
<ToolTip>
<BulletDecorator>
<BulletDecorator.Bullet>
<Ellipse Height="10" Width="10" Fill="Blue"/>
</BulletDecorator.Bullet>
<TextBlock>Text with a bullet!</TextBlock>
</BulletDecorator>
</ToolTip>
For more information, see http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.bulletdecorator(v=vs.100).aspx
A: you must have a custom tooltip for this
a nice blog example
http://stevenhollidge.blogspot.co.il/2012/04/custom-tooltip-and-popup.html
microsoft info
http://msdn.microsoft.com/en-us/library/ms745107.aspx
just put somekind of rich textbox or listbox in the content...
A: Just a guess:
Why don't use unicode characters (0x2981 for example) and \r\n for lie breaks?
A: I got it displaying correctly with the following:
<ListView
x:Name="listView"
Margin="0,-5,0,0"
BackgroundColor="Transparent"
HasUnevenRows="True"
HeightRequest="50"
HorizontalOptions="CenterAndExpand"
ItemsSource="{Binding TradingHoursList}"
SeparatorColor="Transparent">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<RelativeLayout>
<Label Text="•"/>
<Label
Margin="10,0,0,0"
FontAttributes="Italic"
FontFamily="Arial Black"
FontSize="15"
HorizontalOptions="Start"
Text="{Binding}"
VerticalOptions="Start"/>
</RelativeLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19699415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android Studio remember keystore and password Whenever I build a signed apk this dialog appears:
Every time I have to enter the same texts (path, passwords, alias).
My question: how to save and remember them, across projects? Ticking "Remember passwords" does not help.
My keystore file has been generated a while ago and used in Eclipse many times.
A: Go to file -->project structure-->click on app-->and on the right side 4tabs will appear and select build in that and enter your detail. That's it
Also important are these in your build.gradle file
android {
signingConfigs {
ProdSigningKey {
keyAlias 'any alias name'
keyPassword 'your actual password'
storeFile file('keystore file path on your computer')
storePassword 'your actual password'
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31355671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to find all sums in an int array I have an array of integers, example
{2,3,7}
and I need to find how to find a number as a sum of these numbers
For example, let's say I need to find 17
I could do 7+2+2+3+3, 7+2+2+2+2+2, 7+3+7, 3+3+3+2+2+2+2, etc.
But looping through everything is very inefficient, it would be O(N^N) in the best case...
How would i solve a problem like this in an optimized way?
A: I believe you're asking StackOverflow to help you solve the knapsack problem. If you manage to find a polynomial solution, you can go claim a million dollars reward for solving P=NP. Good luck !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64966933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't get some user's last tracks with Soundcloud SDK I currently have an issue with the Soundcloud Javascript SDK.
When using the method : SC.get('/users/USER_ID/tracks', [params])
It work perfectly fine for some users, but I get an empty array with other.
The account and tracks are all public.
I read somewhere that apparently it could be the label who block the access on the tracks.
To explain RTMP, even if a track is set to public and streamable by the artist, if the artist is under a major label, this label can further control those streaming permissions. So, it looks like it should stream correctly, however it doesn't.
Does someone have an idea why this doesn't work for some users?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36339698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use jgit to clone the existing repositories to new github instance? We have two separate GitHub instance running. One GitHub instance is https://github.dev.host.com and other github instance is https://github.host.com. I have various repositories in https://github.dev.host.com which I need to migrate to this new github instance https://github.host.com.
I am using JGit as I am working with Java. For example - Below are the repositories that are present in https://github.dev.host.com instance which I need to migrate to new github instance https://github.host.com
https://github.dev.host.com/Database/ClientService
https://github.dev.host.com/Database/Interest
As I am using JGit so I want to create these two above repositories in my new GitHub instance through Java code. And after running my Java code, I should see all the above respositories and all its branches and contents from my https://github.dev.host.com into my new Github instance https://github.host.com as shown something like below -
https://github.host.com/Database/ClientService
https://github.host.com/Database/Interest
I just need to iterate the all the repositories list which I have in my old github instance and create those if they don't exit with all its contents and branches in my new github instance. And if they already exists, then overwrite all the changes from old to new instance.
Is this possible to do this using JGit? I also have https access to my both the github instances through my username and password.
As of now I can only do basic stuff as shown below which I learnt going through the tutorial.
public class CreateNewRepository {
public static void main(String[] args) throws IOException {
// prepare a new folder
File localPath = File.createTempFile("TestGitRepository", "");
localPath.delete();
// create the directory
Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
repository.create();
System.out.println("Having repository: " + repository.getDirectory());
repository.close();
FileUtils.deleteDirectory(localPath);
}
}
Any suggestions will be of great help as this is my first time working with JGit.
A: A viable approach would be to clone the repositoy from the source server to a temporary location and from there push it to the destination server.
You can clone a repository with JGit like this:
Git.cloneRepository()
.setCredentialsProvider( new UsernamePasswordCredentialsProvider( "user", "password" ) );
.setURI( remoteRepoUrl )
.setDirectory( localDirectory )
.setCloneAllBranches( true )
.call();
To transfer the just cloned repositoy to the destination, you have to create a repository on the destination server first. Neither JGit nor Git support this step. GitHub offers a REST API that lets you create repositories. The developer pages also list the language bindings that are available for this API with Java among them.
Once the (empty) repository is there, you can push from the temporary copy to the remote:
Git git = Git.open( localDirectory );
git.push()
.setCredentialsProvider( new UsernamePasswordCredentialsProvider( "user", "password" ) );
.setRemote( newRemoteRepoUrl )
.setForce( true )
.setPushAll()
.setPushTags()
.call()
More information about authentication can be found here
Note that if the source repository contains tags, these have to be fetched into the temporary repository separately after cloning.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28380719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alternative to ->operator() Is there a nicer syntax than calling objp->operator()(x, y, z) if objp is a pointer? &objp(x, y, z) does not work. Because of all the symbols, this is hard to Google. Sorry of this is silly.
A: (*objp)(x, y, z); would be the obvious alternative. I'm not sure if you consider that nicer or not though.
A: You can use (*objp)(x, y, z); as an alternative.
A: Do it in two lines;
MyType& functorRef = *objp; // Use the appropriate type name.
functorRef(x, y, z);
Or in C++11 you can use auto.
auto& functorRef = *objp;
functorRef(x, y, z);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31757675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: winForm app isn't creating an .exe.config.deploy file (winForms) I created a winForms app (c#), and it works great from the vs and from the appName/bin/debug/appName.exe, the problem occours when I copy the .exe file to another folder - it doesn't open. When I published it and try to install - it showed the messege "cannot find the appName.exe.config.deploy file". But I checked the folder and that file really exists there!
Does anyone have an idea what can it be and how can I fix it?
Thank you all!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70785702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Qlik sense only show values on trend graph I have a trend graph line..and these values show as time differences for orders per customers
This is the sort of question to ask how to stop showing 0 however
This measure is worked out using an if statement.. within the if statement there is sum difference between two time stamps.
if("CheckDate" < StartCheckDate , max({$<[Temperature]={'<=0'}>} CheckDate) - min({$<[Temperature]={'>0'}, CheckNumber = {1}>} CheckDate), max({$<[Temperature]={'<=0'}>} CheckDate) - min({$<[Temperature]={'>0'}, CheckNumber = {2}>} CheckDate))
However some customers are showing up as 00:00:00 how do I in the measure say don't show these customers.. that have 00:00:00
please help..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46573415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Expand React Bootstrap Table for more granular data I have a react bootstrap table that displays information about a manager's sales, grouped by manager so I can see their overall performance. I would like to add the capability of clicking on a row and having the table expand to include the data at the sales rep level.
Data:
const SALES = [
{
manager: 'Mgr 1', revenue: 49.98, repName: 'Rep 1', forecast: 81.00,
},
{
manager: 'Mgr 1', revenue: 10, repName: 'Rep 1', forecast: 91.00,
},
{
manager: 'Mgr 1', revenue: 9.99, repName: 'Rep 13', forecast: 82.00,
},
{
manager: 'Mgr 2', revenue: 99.99, repName: 'Rep 3', forecast: 101.00,
},
{
manager: 'Mgr 2', revenue: 9.99, repName: 'Rep 5', forecast: 89.00,
},
{
manager: 'Mgr 3', revenue: 199.99, repName: 'Rep 6', forecast: 77.00,
},
];
The following function groups/aggregates my data for my initial table:
function groupByTotal(arr, groupByCols, aggregateCols, counter) {
const subSet = (o, keys) => keys.reduce((r, k) => (r[k] = o[k], r), {})
let grouped = {};
arr.forEach(o => {
const values = groupByCols.map(k => o[k]).join("|");
if (grouped[values]) {
aggregateCols.forEach(col => grouped[values][col] += o[col])
if (counter) { grouped[values].Count++ }
} else {
grouped[values] = subSet(o, groupByCols);
if (counter) { grouped[values].Count = 1 }
aggregateCols.forEach(col => grouped[values][col] = o[col])
}
})
return Object.values(grouped);
}
const groupedSales = groupByTotal(SALES, ['manager'], ['revenue','forecast']);
Building the Table:
const columns = [{
dataField: 'manager',
text: 'Sale Owner',
}, {
dataField: 'revenue',
text: 'Revenue',
}, {
dataField: 'forecast',
text: 'Forecast',
}];
const expandRow = {
renderer: row => (
// Add rep level data to table below the appropriate manager
),
showExpandColumn: true
};
return (
<BootstrapTable
keyField='manager'
data={ groupedSales }
columns={ columns }
expandRow={ expandRow }
/>
)
The ideal solution would have it looking something like this:
Can anyone help me create the appropriate expandRow or suggest another way? Thanks.
A: Have a look at this, it might solve your problem.
http://allenfang.github.io/react-bootstrap-table/example.html#expand
A: You can easily access row data using the dot notation:
const expandRow = {
renderer: row => (
<div>
<p>Manager: {row.manager}</p>
<p>Revenue: {row.revenue}</p>
<p>Forecast: {row.forecast}</p>
</div>
)
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58327571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why svg text disappears when setting x and y to 0? I just started reading about svg and I came up with the following question
I am creating a simple svg with a text inside as shown below.
From my reading I understood that x and y of the text tag declares the position of the text inside the svg space.
Why when I set both x and y to 0 the text does not appear and when I change x and y to 10 for example it is displayed? Isn't x=0 and y=0 meaning the top left corner of the svg tag?
Thanks
<svg width="200" height="100">
<text x="0" y="0">hello</text>
</svg>
A: You're correct, (0,0) is indeed the top left corner of the SVG area (at least before you start transforming the coordinates).
However, your text element <text x="0" y="0">hello</text> is positioned with the leftmost end of its baseline at (0,0), which means the text will appear entirely off the top of the SVG image.
Try this: change your text tag to <text x="0" y="0">goodbye</text>. You should now be able to see the descending parts of the 'g' and 'y' at the top of your SVG.
You can shift your text down by one line if you provide a y coordinate equal to the line height, for example:
<svg width="200" height="100">
<text x="0" y="1em">hello</text>
</svg>
Here's a JSFiddle link for you to play with.
A: To make <text> behave in a more standard way, you can use dominant-baseline: hanging like so:
<text x="0" style="dominant-baseline: hanging;">Hello</text>
You can see examples of different values of this property here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21777376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Could not find default endpoint element that references contract - Hosting wcf I have one wcf service on this site http://wswob.somee.com/wobservice.svc
I try to consume that service with my winform app. This is the error I receive when I create an instant of the service
com.somee.wobservice.IwobserviceClient myservice = new com.somee.wobservice.IwobserviceClient();
error:
Could not find default endpoint element that references contract
'com.somee.wobservice.Iwobservice' in the ServiceModel client configuration section. This
might be because no configuration file was found for your application, or because no
endpoint element matching this contract could be found in the client element.
I searched and modified my app.config file:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="wobservice">
<clientVia />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint
name="wobservice"
address="http://wswob.somee.com/wobservice.svc"
binding="webHttpBinding"
contract="com.somee.wobservice"
behaviorConfiguration="wobservice" />
</client>
</system.serviceModel>
</configuration>
And my web.config in wcf folder:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="Web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
<baseAddressPrefixFilters>
<add prefix="http://wswob.somee.com/"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
<bindings>
<webHttpBinding>
<binding>
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
<add binding="basicHttpBinding" scheme="http"/>
</protocolMapping>
<services>
<service name="wobwcf.wobservice">
<endpoint address=""
binding="webHttpBinding"
behaviorConfiguration="Web"
contract="wobwcf.Iwobservice" />
</service>
</services>
</system.serviceModel>
I don't really sure which part I got wrong. My experience of wcf is just a week...
A: Copy system.serviceModel section from the app.config in your library project and put it in your web.config and refresh service reference. See also this answer. Could not find default endpoint element
A: Add "WSHttpBinding" end point in your WCF service web.config file like below
<endpoint address="web" behaviorConfiguration="jsonBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="DataService.IDataService"/>
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpBinding" contract="DataService.IDataService" />
and in your app.config file write code like below
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IDataService" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost/pricedataservice/DataService.svc" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IDataService" contract="DataService.IDataService"
name="WSHttpBinding_IDataService" />
</client>
I am sure this will fix your problem and below blog will help you to understand different type of binding in WCF service
http://www.dotnet-tricks.com/Tutorial/wcf/VE8a200713-Understanding-various-types-of-WCF-bindings.html
A: Add client definition in your client web.config file like below;
<system.serviceModel>
/////
<client>
<endpoint address="referencedurl"
binding="webHttpBinding" bindingConfiguration=""
contract="MemberService.IMemberService"
name="MemberServiceEndPoint"
behaviorConfiguration="Web">
</endpoint>
</client>
////
</system.serviceModel>
AND Service Reference Name must same as the Interfaces prefix. contract="ReferenceName.IMemberService"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24050224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Recursive query on jsonb data stored in Postgres I have a table in postgres named 'books' with one jsonb column called 'j' with the following data:
{
"entity": "Book",
"processes": [
{ "process": [
{ "processname": "Buy",
"option": "none",
"processes": [
{ "process": [
{ "processname": "Order",
"option": "none"
}
]
},
{ "process": [
{ "processname": "Arrive",
"option": "none"
}
]
},
{ "process": [
{ "processname": "Enter",
"option": "none"
}
]
}
]
}
]
},
{ "process": [
{ "processname": "Use",
"option": "none",
"processes": [
{ "process": [
{ "processname": "Lend",
"option": "*",
"processes": [
{
"process": [
{
"processname": "Borrow",
"option": "none"
}
]
},
{
"process": [
{
"processname": "Return",
"option": "none"
}
]
}
]
}
]
}
]
}
]
},
{ "process": [
{ "processname": "Scrap",
"option": "none",
"processes": [
{ "process": [
{ "processname": "Sold",
"option": "0"
}
]
},
{ "process": [
{ "processname": "Scrap",
"option": "0"
}
]
}
]
}
]
}
]
}
I want to retrieve all the processnames together with the processnames of their parents (i.e. path taken to reach them).
I have the following code so far but the union part is not working.
with recursive jsonrecursion as
(
select process -> 'processname' as processname, '{}'::int[] as superior, 0 as lv
from books, jsonb_array_elements(j-> 'processes') processes, jsonb_array_elements(processes-> 'process') process
where process -> 'processes' is NULL
union all
select process -> 'processname' as processname, superior || process -> 'processname', lv+1
from books, jsonrecursion
where not process -> 'processname' = any(superior)
)
SELECT processname, superior, lv
FROM jsonrecursion;
Can someone kindly help please?
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61142177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I create and return object in return statement? I want to create and return an object in this return call:
var Zones = _ZoneService.GetZones();
var userZones = _ZoneService.GetUserZones(user);
return Ok(//Here I need to return both Zones and userZones);
How can I create new on the go object to return these two.
Thanks...
A: What about Anonymous Types? Something like this:
return Ok(new { Zones, userZones });
A: I think that the best way to go is to creat a list, add the object to your list, and return the list. This way is also easyer if you need to work with these object.
To create a list, first we need to code a propper class:
public class Item {
public int Id { get; set; }
public Object MyObj { get; set; }
}
Now we can create and populate the list:
List<Item> items = new List<Item>()
{
new Item{ Id=1, MyObj= Zones},
new Item{ Id=2, MyObj= userZones}
}
Now you can return your list using: return items
A: You could also use anout parameter, like:
public Zones GetZones(..., out Zones userZones)
{
uzerZones = _ZoneService.GetUserZones(user);
return _ZoneService.GetZones();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52495498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: how to acess my database elements using the for loop? I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
A: *
*First of all, you should use database access drivers to connect to your database.
*Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
*To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
A: I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
A: for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
A: Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
A: I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17058147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: slider on angularjs data I need to add slider that is auto moving with a speed of 4 seconds , scrolling by one element.I used bower component, angular-slick from vasyabigi.github.io/angular-slick/ , it is working fine with static data, but I am fetching data from server in controller with $http. It is not working with dynamic data.
landing.html
<div ng-repeat="cat in barsubData">
<span> {{cat.subCategoryId.name | uppercase}} </span>
</div>
controller.js
// get subcat bar function
var getsubcatdetails = function () {
services.webscreensucatService($scope, function (data) {
$scope.barsubData = data.data.stock;
console.log($scope.barsubData);
});
}
getsubcatdetails();
service.js
// webscreen subcat service
this.webscreensucatService = function ($scope, callback) {
// var data = {};
// data.email = $scope.login.username;
// data.password = $scope.login.password;
$http({
method: 'GET',
url: constants.BASEURL + '/api/BranchManager/lcdScreenDataSubCategory?accessToken=xxxxxxxxx',
contentType: 'application/json',
}).success(function (data) {
if (data.statusCode == constants.SUCCESS) {
// console.log(data);
callback(data);
} else {
$scope.loading = 0;
factories.invalidDataPop(data.message);
}
}).error(function (error) {
factories.invalidDataPop("Invalid accessToken");
});
};
Kind of DATA I am getting from server
{
"statusCode": 200,
"message": "Success",
"data": {
"_id": "57a87e09cae4c29148233157",
"stock": [
{
"startingPrice": 120,
"currentPrice": 153,
"lowPrice": 120,
"highPrice": 153,
"basePrice": 120,
"currentStock": 99,
"totalStock": 100,
"_id": "57a87f49cae4c29148233165",
"Date": "2016-08-08T12:47:05.975Z",
"subCategoryId": {
"_id": "57a87e81cae4c2914823315d",
"name": "Sauvignon Blanc"
},
"categoryId": {
"_id": "57a87e48cae4c29148233159",
"imageURL": {
"thumbnail": "s3-us-west-2.amazonaws.com/barsupply/profileThumb_12JURVq.png",
"original": "s3-us-west-2.amazonaws.com/barsupply/profilePic_12JURVq.png"
},
"name": "Wine"
}
}]
Please help me working with slider. I am free to use any angularjs slider which is working.
Thank you for the help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39033967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: foreach line and add something else hello i have something with this code bellow
$text = nl2br($_POST['inputtext']);
foreach(explode("<br />",$text) as $ok){
echo "944".$OK."<BR />";
}
what i have tried is
when i enter something in the text area and i click change look the result
944test
944 test
anyway way the first result is good but the second one i get space between the number and the word i do not no why is that happen i tried it before and i did not get anything like that
A: Possibly could be that it is looking through your text and say you have:
test \n
test
You then explode the words and you will get
"test<br />"
" test<br/>"
This is because of the space that you are not removing between the first word and the enter key or \n. Use the following and it should work fine for you:
foreach (explode("<br />", $text) as $ok) {
echo "944" . ltrim($ok) . "<BR />";
}
A: nl2br does not replace newline characters with <br />, it simply inserts them before newline characters. The existing newline characters may be causing you problems. You may have to write your own function. Something like:
function nl2br2($string) {
return str_replace(array("\r", "\n", "\r\n"), "<br />", $string);
}
Alternatively, you can just trim space off the resulting array as well.
foreach (array_map('trim', explode('<br />', nl2br2($text))) as $ok) {
echo "944". $ok ."<br />";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17129542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to order a queryset in Django model by relational foreign key I have the following models
models.py
class Category(models.Model):
label = models.CharField(max_length=100, unique=True)
description = models.CharField(max_length=255, blank=True)
class Expense(models.Model):
description = models.CharField(max_length=255, blank=True)
amount = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
category = models.ForeignKey(
Category,
on_delete=models.CASCADE,
null=True,
related_name='category'
)
class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.order_by("-expense__expense")
I'm struggling to how to return a Category list ordered by the most picked category in the Expense model like:
<Expense category=3>
<Expense category=3>
<Expense category=2>
<Expense category=3>
<Expense category=1>
<Expense category=1>
I want to return in this order:
<Category id=3>
<Category id=1>
<Category id=2>
Solution is using annotate:
queryset = Category.objects.annotate(
expense_count=Count('category')).order_by('-expense_count')
A: Use Django's lovely aggregation features.
queryset = Category.objects.annotate(expense_count=Count('expense')).order_by('-expense_count')
A: We can use annotate to achieve this:
from django.db.models import Count
...
queryset = Category.objects.annotate(expense_count=Count('expense')).order_by('-expense_count')
A: from django.db.models import Count
Category.objects.annotate(expense_count=Count('category')).order_by('-expense_count')
This is based on your model definition yet I suggest that the related_name should be modified to a term that related to Expense, such as expenses. Since the related_name indicate the name you are using for reverse querying.
A: Just add .distinct('field-name') at end of the query. like this
queryset = Category.objects.order_by("-expense__expense").distinct('category')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59894326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Identifying an Event based on a Jump in Rolling Variance in Python I am trying to figure out a way, in Python, how to identify when an event occurs, based on a jump in the rolling standard deviation.
As shown in the plot below, around the 12000th sample, an event occurs. In my Python script, I am currently using a threshold of 0.00051 to signify when that event occurs. However, sometimes the event occurs at 0.0005 and other times the event occurs at 0.000495.
My question is - how can I algorithmically, in Python, detect this jump in the rolling standard deviation to create the event altert? Because if I have a threshold set too low, I don't want it to be triggered too early. And if I run another test, and the threshold is too high, then I don't want the event to not be triggered at all.
Any advice is greatly appreciated!
def animate(i):
data = pd.read_csv("C:\\Users\\Desktop\\data.txt", sep="\[|\]\[|\]",engine = 'python', header = None)
data = data.iloc[0, ::4]
data = data.astype(str).apply(lambda x: x.split(',')[-1]).astype(float)
data.pop(0)
xar = range(len(data))
yar = pd.DataFrame(data)
# Starting from sample 1050 to get rid of any initial noise
yar = yar[1050:12500]
xar = xar[1050:12500]
std = yar.rolling(window=2500).std()
if (np.any(std>.00051)):
choices = ["Confirm Event"]
reply = easygui.buttonbox("Event Alert!, image, choices)
if reply == "Confirm Event":
sys.exit(0)
ax1.clear()
ax1.plot(xar,std)
ax1.set_title('Rolling Standard Deviation')
fig, (ax1) = plt.subplots(1, sharex = True)
ani = animation.FuncAnimation(fig, animate, interval=.01)
plt.show()
EDIT w/ Code
import pandas as pd
import scipy
import sys
import numpy as np
import easygui
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def animate(i):
data = pd.read_csv("C:\\Users\\Desktop\\data.txt", sep="\[|\]\[|\]",engine = 'python', header = None)
data = data.iloc[0, ::4]
data = data.astype(str).apply(lambda x: x.split(',')[-1]).astype(float)
data.pop(0)
xar = range(len(data))
#yar = data.as_matrix()
yar = pd.DataFrame(data)
L=2500
# Starting from sample 1050 to get rid of any initial noise
yar = yar[1050:len(data)]
xar = xar[1050:len(data)]
std = yar.rolling(window=2500).std()
std = std.as_matrix()
#s = [np.std(yar[ii:ii+L]) for ii in range(1050,len(data))]
yar = data.as_matrix()
yar = yar[1050:len(data)]
d = np.diff(yar)
d2 = d*d
## rolling mean of the diff squared:
SS = [np.mean(d2[ii:ii+L]) for ii in range(1050, len(d2)-L)]
# compute the F statistic
F = np.array([SS[ii]/SS[ii+L] for ii in range(1050, len(SS)-L)])
w = np.where(np.less(F,1))
F[w]=1/F[w]
# the x coordinate of the point where shift happens is offset by L from the computed F:
xi = np.arange(0,len(F))+L
ax1.clear()
ax2.clear()
ax3.clear()
ax1.plot(xar, std)
ax2.plot(xi, F)
ax3.plot(xar, yar)
ax1.set_title('Rolling Standard Deviation')
ax2.set_title('F - values')
ax3.set_title('Original Data')
fig, (ax1, ax2, ax3) = plt.subplots(3, sharex = True)
fig.subplots_adjust(hspace=1.5)
ani = animation.FuncAnimation(fig, animate, interval=.01)
plt.show()
And my data looks like the following:
[0.013671875, -0.9599609375, -0.005859375][0.013671875, -0.9599609375, -0.005859375][0.013671875, -0.9599609375, -0.005859375][0.0068359375, -0.8193359375, -0.0029296875][0.0068359375, -0.8193359375, -0.0029296875][0.0068359375, -0.8193359375, -0.0029296875][0.0068359375, -0.8193359375, -0.0029296875][0.0068359375, -0.8193359375, -0.0029296875][0.0068359375, -0.8193359375, -0.0029296875][0.0068359375, -0.8193359375, -0.0029296875][0.0068359375, -0.8193359375, -0.0029296875][0.0087890625, -0.990234375, -0.0048828125][0.0087890625, -0.990234375, -0.0048828125][0.0087890625, -0.990234375, -0.0048828125][0.0087890625, -0.990234375, -0.0048828125][0.0087890625, -0.990234375, -0.0048828125][0.0087890625, -0.990234375, -0.0048828125][0.0068359375, -0.951171875, -0.00390625][0.0068359375, -0.951171875, -0.00390625][0.0068359375, -0.951171875, -0.00390625][0.0068359375, -0.951171875, -0.00390625][0.0068359375, -0.951171875, -0.00390625][0.0068359375, -0.951171875, -0.00390625][0.0068359375, -0.951171875, -0.00390625][0.0068359375, -0.951171875, -0.00390625][0.009765625, -0.9560546875, -0.0048828125][0.009765625, -0.9560546875, -0.0048828125][0.009765625, -0.9560546875, -0.0048828125][0.009765625, -0.9560546875, -0.0048828125][0.009765625, -0.9560546875, -0.0048828125][0.009765625, -0.9560546875, -0.0048828125][0.009765625, -0.9560546875, -0.0048828125][0.009765625, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0068359375, -0.9560546875, -0.0048828125][0.0068359375, -0.9560546875, -0.0048828125][0.0068359375, -0.9560546875, -0.0048828125][0.0068359375, -0.9560546875, -0.0048828125][0.0068359375, -0.9560546875, -0.0048828125][0.0068359375, -0.9560546875, -0.0048828125][0.0068359375, -0.9560546875, -0.0048828125][0.0068359375, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.005859375][0.0087890625, -0.9560546875, -0.005859375][0.0087890625, -0.9560546875, -0.005859375][0.0087890625, -0.9560546875, -0.005859375][0.0087890625, -0.9560546875, -0.005859375][0.0087890625, -0.9560546875, -0.005859375][0.0087890625, -0.9560546875, -0.005859375][0.0087890625, -0.9560546875, -0.005859375][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0087890625, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0087890625, -0.955078125, -0.0048828125][0.0087890625, -0.955078125, -0.0048828125][0.0087890625, -0.955078125, -0.0048828125][0.0087890625, -0.955078125, -0.0048828125][0.0087890625, -0.955078125, -0.0048828125][0.0087890625, -0.955078125, -0.0048828125][0.0087890625, -0.955078125, -0.0048828125][0.0087890625, -0.955078125, -0.0048828125][0.0068359375, -0.9560546875, -0.00390625][0.0068359375, -0.9560546875, -0.00390625][0.0068359375, -0.9560546875, -0.00390625][0.0068359375, -0.9560546875, -0.00390625][0.0068359375, -0.9560546875, -0.00390625][0.0068359375, -0.9560546875, -0.00390625][0.0068359375, -0.9560546875, -0.00390625][0.0068359375, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0078125, -0.955078125, -0.00390625][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0087890625, -0.9560546875, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.955078125, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.00390625][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125][0.0078125, -0.9560546875, -0.0048828125]
A: I thought about this for quite some time. In fact, I believe you are asking the wrong question (sorry). As was made clear in the comments, the "event" you are looking for is "something that increases the noise in my signal by a significant amount". The correct way to detect this, then, is to do a statistical test of the difference in the standard deviation (variance) between two sets of data.
There is a thing called the F-test that does exactly this. Without boring you with the details, if you have two samples and compute their variance, you can answer the question "is the variance different" with the F test. To do this, you need the test statistic, (the ratio of the variances) and the number of degrees of freedom (the number of samples minus one). You can then calculate the probability that the difference is due to chance ("how often would you see a jump this big in two random samples from the same distribution?) - something called the p value. If the p value is small enough, you can say "this wasn't just by chance". Of course when you run 1000 comparisons, you will "by chance" get a 0.1% probability event happening on average one time; so you need to be prepared for some false positives (or accept that you will only see big changes that are VERY unlikely to occur by chance).
I implemented this approach - and the Python code is below. The plots show that the signal changes "in a way that is hard to see"; but after analysis, the point where the change occurs stands out above the others (even though I increased the standard deviation by only 10%).
A thing to note: I am using the diff of the sequence as my input to the calculation; this largely takes out the effect of a slowly changing underlying value so you are really looking at the pure noise. This works best if the sampling is such that subsequent samples are independent (i.e. it only really works if the samples have not been low-pass filtered; otherwise, just don't take the diff).
I hope the code is fairly self-explanatory; let me know if you need further clarification. Your threshold can now be set probabilistically, depending on how many false positives you are willing to accept.
# detect a sudden change in standard deviation of a sequence of measurmeents
import numpy as np
import matplotlib.pyplot as plt
import scipy
# a sequence of values with a mean and standard deviation
# and then a sudden change in the standard deviation
mu = 1000 # mean of signal
sigma = 100 # standard deviation of signal
increase = 1.1 # increase in standard deviation
N1 = 10000 # number of datapoints before change
L = 2500 # size of rolling window
# create a series with a slight increase in noise:
before = np.random.normal(mu,sigma,N1)
after = np.random.normal(mu, increase*sigma, N1)
sequence = np.concatenate((before, after), axis=0)
twoD_img = np.histogram2d(range(0,2*N1), sequence, bins=(50,100))
plt.figure();
plt.subplot(4,1,1)
plt.imshow(twoD_img[0].T,aspect='auto', extent = (0, 2*N1, np.min(sequence), np.max(sequence)));
plt.title('input signal')
# rolling standard deviation
s = [np.std(sequence[ii:ii+L]) for ii in range(0,2*N1-L)]
plt.subplot(4,1,2)
plt.plot(s)
plt.title('rolling standard deviation')
# take the differences, and compute the average noise from that
d = np.diff(sequence)
d2 = d*d
## rolling mean of the diff squared:
SS = [np.mean(d2[ii:ii+L]) for ii in range(0, len(d2)-L)]
# compute the F statistic
F = np.array([SS[ii]/SS[ii+L] for ii in range(0, (len(d2)-2*L))])
w = np.where(np.less(F,1))
F[w]=1/F[w]
# the x coordinate of the point where shift happens is offset by L from the computed F:
xi = np.arange(0,len(F))+L
plt.subplot(4,1,3)
plt.plot(xi, F);
plt.title('F values')
plt.xlabel('datapoint #')
# compute log of probability that this is by chance:
logProb = np.log(1-scipy.stats.f.cdf(F, dfn=L-1, dfd=L-1))
plt.subplot(4,1,4)
plt.plot(xi, logProb)
plt.title('log probability plot')
plt.xlabel('datapoint #')
# make some space for the labels
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.1, hspace=0.4)
# and draw the result:
plt.show()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45487229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: npm install permission denied (macOS) To install a Bootstrap theme I want to run npm install. However I always receive a permission denied error.
I already tried nvm and then switched with nvm use 10.9.0 to run npm install.
I also tried sudo chown -R $(whoami) ~/.npmand sudo chown -R $USER /usr/local/lib/node_modules. Neither solved it and now I am bit out of ideas how I can continue. I use macOS High Sierra.
Marcs-MBP-3:masterclass Marc$ npm install
npm WARN deprecated [email protected]: Since gulp-sourcemaps now works, use gulp-uglify instead
npm WARN deprecated [email protected]: Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!
npm WARN deprecated [email protected]: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm WARN checkPermissions Missing write access to /Users/Marc/Desktop/Dev/masterclass/node_modules
npm ERR! path /Users/Marc/Desktop/Dev/masterclass/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/Users/Marc/Desktop/Dev/masterclass/node_modules'
npm ERR! { [Error: EACCES: permission denied, access '/Users/Marc/Desktop/Dev/masterclass/node_modules']
npm ERR! stack:
npm ERR! 'Error: EACCES: permission denied, access \'/Users/Marc/Desktop/Dev/masterclass/node_modules\'',
npm ERR! errno: -13,
npm ERR! code: 'EACCES',
npm ERR! syscall: 'access',
npm ERR! path: '/Users/Marc/Desktop/Dev/masterclass/node_modules' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/Marc/.npm/_logs/2018-08-22T12_46_51_786Z-debug.log
A: For me it was,
npm cache clean --force
rm -rf node_modules
npm install
I tried deleting manually but didn't help
A: Check permissions of your project root with ls -l /Users/Marc/Desktop/Dev/masterclass/. If the owner is not $USER, delete your node_modules directory, try changing the owner of that directory instead and run npm install again.
cd /Users/Marc/Desktop/Dev
rm -rf ./masterclass/node_mdoules/
chown -R $USER ./masterclass/
cd masterclass
npm install
A: I tried everything in this thread with no luck on Big Sur, but then I tried this:
sudo npm install -g yarn
And it worked!
A: I did this for nodemon and it work
sudo chown -R $USER /usr/local/lib/node_modules
then install the packages that you need
A: KIndly run the below commands:
*
*To check the location of the package:
npm config get prefix
*Then run this :
sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}
*Enter the password and run installation commands
It worked for me.
A: For Mac;
Run this on the Terminal >
sudo chown -R $USER /usr/local/lib/node_modules
A: I was having a similar issue, but the accepted answer did not work for me, so I will post my solution in case anyone else comes along needing it.
I was running npm install in a project cloned from GitHub and during the clone, for whatever reason the write permission was not actually set on the project directory. To check if this is your problem, pull up Terminal and enter the following:
cd path/to/project/parent/directory
ls -l
If the directory has user write access, the output will include a w in the first group of permissions:
drwxr-xr-x 15 user staff 480 Sep 10 12:21 project-name
This assumes that you're trying to access a project in the home directory structure of the current user. To make sure that the current user owns the project directory, follow the instructions in the accepted answer.
A: I entered the following:
cd /Users/Marc/Desktop/Dev
rm -rf ./masterclass/node_mdoules/
chown -R $USER ./masterclass/
cd masterclass
npm install
once this was completed the results indicated warnings and one notice instead of previous result of no permission and error.
I then entered the following:
% sudo npm install --global firebase-tools
my result was success upon completion of the last terminal entry.
A: I have same problem because i install it from pkg, and i solve this problem use below step:
1. sudo rm -rf /usr/local/lib/node_modules/npm/
2. brew doctor
3. brew cleanup --prune-prefix ( or sudo rm -f /usr/local/include/node)
4. brew install node
A: i use this command :
sudo npm install -g @angular/cli
Gave password and worked for mw. Took 10 secs to install angular
A: NPM_CONFIG_PREFIX=~/.npm-global
Copy this line into ur terminal, then hit enter. Then install the necessary packages you need WITHOUT the term "sudo" in front of npm.
i.e.,
npm install -g jshint
A: the only thing that work on me sudo npm i -g clasp --unsafe-perm
A: Just do :
sudo npm install -g @sanity/cli && sanity init
it will ask sudo password and you are good to go
A: That is because you dont have the "node modules". You can install with this code:
npm install -g node-modules
then, create your react app with npm init react-app my-app
A: For Macs running Big Sur or Monterey:
sudo chown -R $USER /usr/local/bin
A: Run on macOS Terminal:
sudo chown -R $USER /usr/local/bin
It will ask for the password then you're good to go!
Hope this helps.
A: Ok my problem was that I thought I was installing on the path:
/Users/mauro/Documents/dev/react
Where my project was setup, but instead I was doing it on:
Users/mauro/Documents/dev/
One path higher and that is why it did not perform the installation in my case.
I simply did: cd react and voila I was able to install without problem
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51967335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
} |
Q: how to pass a parameter to char*? As in the code below, I can't pass this parameter, how do I fix it?
E0167 The "const char *" type argument is incompatible with the "char *" type parameter
Code example:
#include <iostream>
using namespace std;
int PrintString(char* s)
{
cout << s << endl;
}
int main(int argc, char* argv[])
{
PrintString("TESTEEEE");
return 0;
}
I've already tried PrintString(L"TESTEEEE");
I've also tried setting the Project -> Properties -> General -> Character Set option to use Multi-Byte Character Set.
A: This literal "TESTEEEE" is of type char const[9]. When used as an argument to a function, it can decay to char const* but not to char*. Hence to use your function, you have to make the parameter fit to your argument or the opposite as follows
#include <iostream>
using namespace std;
int PrintString(const char* s)
{
cout << s << endl;
}
int main(int argc, char* argv[])
{
PrintString("TESTEEEE");
return 0;
}
live
OR
#include <iostream>
using namespace std;
int PrintString( char* s)
{
cout << s << endl;
}
int main(int argc, char* argv[])
{
char myArr[] = "TESTEEEE";
PrintString(myArr);
return 0;
}
live
A: You have incorrect constness, it should be:
void PrintString(const char* s)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62459667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: 'let' doesn't memoize values in rsepc I have a user model, who have a many-to-many relationship whit itself: user A add user B as a friend, and automatically, user B becomes friend of user A too.
Performing the following steps in the rails console:
1) Create two users and save them:
2.3.1 :002 > u1 = User.new(name: "u1", email: "[email protected]")
=> #<User _id: 5788eae90640fd10cc85f291, created_at: nil, updated_at: nil, friend_ids: nil, name: "u1", email: "[email protected]">
2.3.1 :003 > u1.save
=> true
2.3.1 :004 > u2 = User.new(name: "u2", email: "[email protected]")
=> #<User _id: 5788eaf80640fd10cc85f292, created_at: nil, updated_at: nil, friend_ids: nil, name: "u2", email: "[email protected]">
2.3.1 :005 > u2.save
=> true
2) Add user u2 as friend of u1:
2.3.1 :006 > u1.add_friend u2
=> [#<User _id: 5788eaf80640fd10cc85f292, created_at: 2016-07-15 13:54:04 UTC, updated_at: 2016-07-15 13:55:19 UTC, friend_ids: [BSON::ObjectId('5788eae90640fd10cc85f291')], name: "u2", email: "[email protected]">]
3) Check their friendship:
2.3.1 :007 > u1.friend? u2
=> true
2.3.1 :008 > u2.friend? u1
=> true
As we can see, the "mutual friendship" works. But in my tests that doesn't happen. Here are my tests:
require 'rails_helper'
RSpec.describe User, type: :model do
let(:user) { create(:user) }
let(:other_user) { create(:user) }
context "when add a friend" do
it "should put him in friend's list" do
user.add_friend(other_user)
expect(user.friend? other_user).to be_truthy
end
it "should create a friendship" do
expect(other_user.friend? user).to be_truthy
end
end
end
Here are the tests result:
Failed examples:
rspec ./spec/models/user_spec.rb:33 # User when add a friend should create a friendship
The only reason that I can see to the second test is failing is because my let is not memoizing the association to use in other tests. What am I doing wrong?
Here is my User model, for reference:
class User
include Mongoid::Document
include Mongoid::Timestamps
has_many :posts
has_and_belongs_to_many :friends, class_name: "User",
inverse_of: :friends, dependent: :nullify
field :name, type: String
field :email, type: String
validates :name, presence: true
validates :email, presence: true
index({ email: 1 })
def friend?(user)
friends.include?(user)
end
def add_friend(user)
friends << user
end
def remove_friend(user)
friends.delete(user)
end
end
A: You need to move the creation of the relationship into a before block:
context "when add a friend" do
before do
user.add_friend(other_user)
end
it "should put him in friend's list" do
expect(user.friend? other_user).to be_truthy
end
it "should create a friendship" do
expect(other_user.friend? user).to be_truthy
end
end
In your code, you are only running it within the first it block, to the second one starts from scratch and it's not run.
With the before block, it is run once before each of the it blocks, so the spec should pass then.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38398273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SpringBoot-remove runtime exception from logs for Custom exception handler I have a SpringBoot 2.2 Rest controller that needs exception handling to return correct response to the caller.
Is there any way to remove the runtime exception from logs for custom exception handler in SpringBoot?
I first had:
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "hardcoded reason")
public class InvalidTypeException extends RuntimeException {
}
but I needed to return the error message to the so I revised to:
public class InvalidTypeException extends RuntimeException{
public InvalidTypeException(String message) {
super("InvalidTypeException error: {}"+message);
}
So now the caller is getting the error message, but my logs now are cluttered with the reams from the runtime exception.
ERROR org.springframework.boot.web.servlet.support.ErrorPageFilter [http-nio-8080-exec-5] Forwarding to error page from request [...
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:204)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:128)
at org.springframework.boot.web.servlet.support.ErrorPageFilter.access$000(ErrorPageFilter.java:66)
at org.springframework.boot.web.servlet.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:103)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:121)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:688)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1639)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
I do not want this logging. Is there any way to remove this?
Edit:
I added the following line to my ServletInitializer:
setRegisterErrorPageFilter(false);
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
setRegisterErrorPageFilter(false);
return application.sources(BrokeradaptorApplication.class);
}
Now the runtime error are gone from my logs but now I am returning the following blurb to the caller:
<!doctype html>
<html lang="en">
<head>
<title>HTTP Status 500 – Internal Server Error</title>
<style type="text/css">
body {
font-family: Tahoma, Arial, sans-serif;
}
h1,
h2,
h3,
b {
color: white;
background-color: #525D76;
}
h1 {
font-size: 22px;
}
h2 {
font-size: 16px;
}
h3 {
font-size: 14px;
}
p {
font-size: 12px;
}
a {
color: black;
}
.line {
height: 1px;
background-color: #525D76;
border: none;
}
</style>
</head>
<body>
<h1>HTTP Status 500 – Internal Server Error</h1>
<hr class="line" />
<p><b>Type</b> Exception Report</p>
<p><b>Message</b> Request processing failed; nested exception is
com.example.myservice.exceptions.MyCustomException: error :
{"serviceResult":}
</p>
<p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.
</p>
<p><b>Exception</b></p>
<pre>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.example.myservice.exceptions.MyCustomException: error : {"serviceResult":}
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:204)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
</pre>
<p><b>Root Cause</b></p>
<pre>org.example.myservice.exceptions.MyCustomException: error : {"serviceResult":}
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:204)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
</pre>
<p><b>Note</b> The full stack trace of the root cause is available in the server logs.</p>
<hr class="line" />
<h3>Apache Tomcat/9.0.31</h3>
</body>
</html>
A: You can think of having @ControllerAdvice or @RestControllerAdvice for exception handling. Here you will have complete control over how you want to handle exception/error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60744397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting Cookie between two subdomains I'm currently testing my react+laravel(9) frontend, backend API configuration on actual URLs(Hostinger shared hosting) using laravel sanctum SPA authentication.
These are two subdomains of example.com:
React is using "front.example.com".
Laravel API is using "back.example.com".
When react sends an axios request to "sanctum/csrf-cookie" to set cookies on the "front.example.com". In fact, it does respond with a set-cookie response header that contains 3 cookies which are "XSRF-TOKEN", "example_session", and "RaDdkfd..."(random string).
However, it doesn't save them on the browser's Application/cookie storage. I'm not sure what I did wrong. Please Help!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73491679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Combining arbitrary property path, distinct, and count I have the bellow SPARQL query and would like to get the sum of ?myInt for all the unique ?z values. Is it possible to express such a query in SPARQL 1.1?
SELECT ?z SUM(xsd:int(?myInt))
where{
?x property1+ ?y
?x property2 ?k
?k property3 ?z
?x property4 ?myInt
} group by distinct(?z)
I run this in Jena ARQ and get the following error:
Exception in thread "main" com.hp.hpl.jena.query.QueryParseException: Encountered " "sum" "SUM "" at line 1, column 11.
Here also an example data:
<http://a.com/6> <http://aq.com/p> <http://e.com/c5>.
<http://a.com/6> <http://aq.com/q> <http://a.com/5>.
<http://e.com/c5> <http://aq.com/a> <http://eoq.com/u1>.
<http://a.com/6> <http://aq.com/num> "10"^^<http://www.w3.org/2001/XMLSchema#integer> .
<http://a.com/5> <http://aq.com/p> <http://e.com/c4>.
<http://a.com/5> <http://aq.com/q> <http://a.com/4>.
<http://e.com/c4> <http://aq.com/a> <http://eoq.com/u1>.
<http://a.com/5> <http://aq.com/num> "10"^^<http://www.w3.org/2001/XMLSchema#integer>.
A: You can't select expressions directly, you have to select them as variables. I.e., you need to do:
SELECT ?z (SUM(xsd:int(?myInt)) as ?sum)
This is a common mistake because some endpoints (e.g., the public DBpedia endpoint, which is running Virtuoso) do allow your original form, even though it's not legal SPARQL.
As mentioned in a comment, you should group by ?zero, not by distinct(?z).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38475649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to configure maven-release-plugin to use maven-scm-provider-gitexe 'shallow' option I'm trying to configure the maven release plugin to make use of the new shallow option provided by maven-scm-provider-gitexe.
My pom looks like the following
<properties>
<shallow>true</shallow>
</properties>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-release-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.maven.scm</groupId>
<artifactId>maven-scm-provider-gitexe</artifactId>
<version>1.10.0</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
But this causes the following error
Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.3.2:perform (default-cli) on project dory-interfaces: Execution default-cli of goal org.apache.maven.plugins:maven-release-plugin:2.3.2:perform failed: An API incompatibility was encountered while executing org.apache.maven.plugins:maven-release-plugin:2.3.2:perform: java.lang.NoSuchFieldError: SHALLOW
-----------------------------------------------------
realm = plugin>org.apache.maven.plugins:maven-release-plugin:2.3.2
strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
urls[0] = file:.m2/repository/org/apache/maven/plugins/maven-release-plugin/2.3.2/maven-release-plugin-2.3.2.jar
urls[1] = file:.m2/repository/org/apache/maven/scm/maven-scm-provider-gitexe/1.10.0/maven-scm-provider-gitexe-1.10.0.jar
urls[2] = file:.m2/repository/commons-io/commons-io/2.2/commons-io-2.2.jar
urls[3] = file:.m2/repository/commons-lang/commons-lang/2.6/commons-lang-2.6.jar
have also tried with version maven-release-plugin version 2.5.3
A: Maybe just add the missing dependency
<plugin>
<artifactId>maven-release-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.maven.scm</groupId>
<artifactId>maven-scm-api</artifactId>
<version>1.10.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.scm</groupId>
<artifactId>maven-scm-provider-gitexe</artifactId>
<version>1.10.0</version>
</dependency>
</dependencies>
</plugin>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50633906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: EXSLT extension "dyn:evaluate($expr)" failing in XSLT 1.0 in TIBCO BW I've been trying to implement dynamic evaluation of an expression using Exslt extension dyn:evaluate($expression) in XSLT1.0, but I'm getting the below error.
BW-XML-100006 Job-261000 Error in [Transform_MCIN_XML/Dyn.process/Transform XML]
The [net.sf.saxon.trans.XPathException] occurred during XSLT transformation:
net.sf.saxon.trans.XPathException:
Cannot find a matching 1-argument function named {http://exslt.org/dynamic}evaluate()
caused by: ; SystemID: tibcr://; Line#: 6; Column#: -1
net.sf.saxon.trans.XPathException:
Cannot find a matching 1-argument function named {http://exslt.org/dynamic}evaluate()
I'm able to do the same using saxon:evaluate($expr) in Saxon-B XSLT 2.0 engine. However I need to do this in XSLT 1.0.
How to resolve this error and implement the same in XSLT 1.0 in Tibco BW?
Any suggestions would be highly appreciated.
Thank you.
Sample XSLT:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:dyn="http://exslt.org/dynamic"
extension-element-prefixes="dyn">
<xsl:variable name="expr" select="not(1=1)"/>
<xsl:template match="/">
<eval>
<xsl:value-of select="dyn:evaluate($expr)"/>
</eval>
</xsl:template>
</xsl:stylesheet>
A: Use tib:evaluate instead of dyn:evaluate.
Depending on what else your BW process contains, you may need to add the namespace below to the process in order to use the tib:evaluate() function:
namespace=http://www.tibco.com/bw/xslt/custom-functions
prefix=tib
To do that you would select the process, click the "namespace registry" button, and add the namespace above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19930219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Determine the max value of a group, and display that row I've got a few thousand rows in an excel spreadsheet, which (simplified) looks like this:
ID Category Animal Version Value
100 A Dog 1 20
100 B Cat 2 50
100 C Dog 3 50
200 A Dog 1 100
200 A Cat 2 100
300 B Cat 1 80
400 C Dog 1 80
I need to have the row with the highest/max version for each group of ids listed.
So in other words, I'd want these showing:
ID Category Animal Version Value
100 C Dog 3 50
200 A Cat 2 100
300 B Cat 1 80
400 C Dog 1 80
Is this possible?
A: Finding and showing the maxima/minima for grouped data with a single formula in only one cell can be done with the following formula:
=UNIQUE(FILTER(MyArray,MMULT(((ValueRange>TRANSPOSE(ValueRange))+(ValueRange=TRANSPOSE(ValueRange))-(GroupRange=TRANSPOSE(GroupRange)))*(GroupRange=TRANSPOSE(GroupRange)),SEQUENCE(ROWS(GroupRange),1,1,0))=0),FALSE,FALSE)
For an example, see this screenshot: Link
The output automatically adjusts for any number of groups in the data array.
With the operator > used in the formula, it will return the maximum. By using < it will return the minimum.
Note that the UNIQUE() function will only show distinct rows for each group maximum (see group 'Alpha' in screenshot).
If there is more than one maximum in a group and more than just the group and value column, the UNIQUE() function will show all distinct rows taking into account all columns (as can be seen for group 'Alpha' and 'Gamma' here: Link).
A: For a list without duplicates you can put this in cell G2 ARRAY-FORMULA: CTRL + SHIFT + ENTER
=IFERROR(INDEX(A:A,MATCH(1,(COUNTIF(G$1:G2,A$1:A$99)=0)*(A$1:A$99<>""),0)),"")
This gives you a list with unique ID's. Now you can use the max formula to get the max version number of each ID. ARRAY-FORMULA: CTRL + SHIFT + ENTER
=MAX(IF($A$2:$A$2000=G3,$D$2:$D$2000,0))
The rest can be done with INDEX/MATCH formulas.
A: You can use the Advanced Filter with a formula criteria:
=D9=AGGREGATE(14,6,1/(A9=Table1[ID])*Table1[Version],1)
where D9 is the location of the first entry in the Value Column
Before applying Filter
After applying Filter
A:
Suppose your data is in range A1:E8,
In cell A11, put in the following formula to find unique ID, drag it down until there is a #N/A error:
=INDEX($A$2:$A$8,MATCH(0,INDEX(COUNTIF($A$10:A10,$A$2:$A$8),0),0))
In cell B11, put in the following formula and drag it down to find the latest Version:
=AGGREGATE(14,6,$D$2:$D$8/($A$2:$A$8=A11),1)
In cell C11, D11 and E11, put in the following formulas respectively and drag them down to find the corresponding Category, Animal and Value:
=INDEX($B$2:$B$8,MATCH(1,INDEX(($A$2:$A$8=A11)/($D$2:$D$8=B11),0),0))
=INDEX($C$2:$C$8,MATCH(1,INDEX(($A$2:$A$8=A11)/($D$2:$D$8=B11),0),0))
=INDEX($E$2:$E$8,MATCH(1,INDEX(($A$2:$A$8=A11)/($D$2:$D$8=B11),0),0))
Let me know if there is any question. Cheers :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58456539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to access the searchbar using Firefox addon SDK? Is it possible to access the searchbar using Firefox's addon SDK?
I've seen examples on how to access the menu, context menu and the bookmark sidebar. But I can't find any documentation or tutorial on how to access the search bar.
A: const winUtils = require("sdk/deprecated/window-utils");
var searchbar = winUtils.activeBrowserWindow.document.getElementById("searchbar");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14017569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TFS - Find In Files My team has just migrated from VSS to TFS 2013. On VSS, we would often search the entire database for the occurrence of some string (usually a table or procedure name) to find out everywhere it is used. This functionality is clearly not available in TFS.
I have seen some alternatives, none of which sound very viable in our environment. As a result, I started tinkering with creating an app (or extension) to do it directly from TFS. However, the only way I found to do it is to download and search each file one at a time (I also could not find a way to filter the return from GetItems with a list of file extensions), which is slow and undesired.
Is there a faster way, through the API, to search through the source files in a TFS server?
A: Microsoft has announced that they are working on this exact feature, and it should be coming to Visual Studio Online in Q1 2015, and to on-premise TFS sometime after that.
You can read about it at the bottom of this blog post:
http://blogs.msdn.com/b/bharry/archive/2014/11/12/news-from-connect.aspx
Also the estimated timeline is publicized here:
http://www.visualstudio.com/en-us/news/release-archive-vso.aspx
A: You can use TFS Administrators Toolkit, here is the description of search feature:
http://mskold.blogspot.se/2012/09/find-in-files-new-feature-of-tfs.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28478578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: My spring boot app quits without error as soon as it loads I am converting a maven spring boot app into a bazel based app. I finally got it compile correctly, but as soon as I run it, it just quits. The server doesn't start but it prints the sprint boot start up message.
I think it has to do with spring not being able to find a servlet, but I am very new to java so I don't know where to look.
I am not able to get any usable info from the JVM as to why it just quits. Is there a way I can increase spring's logging verbosity?
Here's my Application.java
package com.example.abc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AbcClient {
public static void main(String[] args) {
SpringApplication.run(AbcClient.class, args);
}
}
My WORKSPACE file
maven_jar(
name = "org_springframework_spring_core",
artifact = "org.springframework:spring-core:jar:5.1.1.RELEASE"
)
maven_jar(
name = "org_springframework_spring_beans",
artifact = "org.springframework:spring-beans:jar:5.1.1.RELEASE"
)
maven_jar(
name = "org_springframework_spring_context",
artifact = "org.springframework:spring-context:jar:5.1.1.RELEASE"
)
maven_jar(
name = "org_springframework_spring_aop",
artifact = "org.springframework:spring-aop:jar:5.1.1.RELEASE"
)
maven_jar(
name = "org_springframework_spring_expression",
artifact = "org.springframework:spring-expression:jar:5.1.1.RELEASE"
)
maven_jar(
name = "org_springframework_boot_spring_boot",
artifact = "org.springframework.boot:spring-boot:jar:2.0.6.RELEASE"
)
maven_jar(
name = "org_springframework_boot_spring_boot_autoconfigure",
artifact = "org.springframework.boot:spring-boot-autoconfigure:jar:2.0.6.RELEASE"
)
maven_jar(
name = "org_springframework_boot_spring_boot_starter_aop",
artifact = "org.springframework.boot:spring-boot-starter-aop:jar:2.0.6.RELEASE"
)
maven_jar(
name = "org_springframework_boot_spring_boot_starter_web",
artifact = "org.springframework.boot:spring-boot-starter-web:jar:2.0.6.RELEASE"
)
maven_jar(
name = "org_springframework_boot_spring_boot_starter_test",
artifact = "org.springframework.boot:spring-boot-starter-test:jar:2.0.6.RELEASE"
)
maven_jar(
name = "org_apache_tomcat_embed_tomcat_embed_core",
artifact = "org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.12"
)
maven_jar(
name = "org_apache_tomcat_embed_tomcat_embed_jasper",
artifact = "org.apache.tomcat.embed:tomcat-embed-jasper:jar:9.0.12"
)
maven_jar(
name = "org_springframework_boot",
artifact = "org.springframework.boot:spring-boot-starter-tomcat:jar:2.0.6.RELEASE"
)
maven_jar(
name = "javax_servlet_jstl",
artifact = "javax.servlet:jstl:jar:1.2"
)
maven_jar(
name = "javax_servlet_javax_servlet_api",
artifact = "javax.servlet:javax.servlet-api:jar:4.0.1"
)
maven_jar(
name = "commons_logging_commons_logging",
artifact = "commons-logging:commons-logging:jar:1.2"
)
maven_jar(
name = "javax_servlet_jsp_javax_servlet_jsp_api",
artifact = "javax.servlet.jsp:javax.servlet.jsp-api:jar:2.3.3"
)
and my BUILD file
java_binary(
name = "AbcClient",
srcs = glob(["src/main/java/com/example/abc/*.java"]),
deps = [
"@org_springframework_spring_core//jar",
"@org_springframework_spring_beans//jar",
"@org_springframework_spring_aop//jar",
"@org_springframework_spring_expression//jar",
"@org_springframework_boot_spring_boot//jar",
"@org_springframework_boot_spring_boot_autoconfigure//jar",
"@org_springframework_spring_context//jar",
"@org_springframework_boot_spring_boot_starter_aop//jar",
"@org_springframework_boot_spring_boot_starter_web//jar",
"@org_apache_tomcat_embed_tomcat_embed_core//jar",
"@org_apache_tomcat_embed_tomcat_embed_jasper//jar",
"@javax_servlet_jstl//jar",
"@javax_servlet_javax_servlet_api//jar",
"@javax_servlet_jsp_javax_servlet_jsp_api//jar",
"@commons_logging_commons_logging//jar",
],
resources = glob([
"src/main/java/resources/*",
"src/main/java/webapp/resources/**"
])
)
A: It should be enough to have spring-boot-starter-web dependency, this by default includes Tomcat. You might be missing the dependencies when running the application e.g. see that SpringBootServletInitializer is present and running.
Take a look at bazel-springboot-rule project and springboot.bzl
Packager which package Spring Boot application as runnable JAR using Bazel (in similar way it's done by Maven and Gradle). It's more or less:
load("//tools/springboot:springboot.bzl",
"springboot",
"add_boot_web_starter"
)
add_boot_web_starter(app_deps)
springboot(
name = "spring-boot-sample",
boot_app_class = "com.main.Application",
deps = app_deps
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53009654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android BLE SCAN getting stopped in 30 secs in Foreground Service after sending the app to background We have BLE scan implemented in a ForegroundService our app, when we target the app from targetSDKVersion 31 (Android 12) and try to scan when app is in background, the scan is getting stopped exactly after 30 secs ..
Note:- We have used the permissions
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-feature android:name="android.hardware.bluetooth" android:required="true"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<uses-permission android:name="android.permission.REQUEST_COMPANION_START_FOREGROUND_SERVICES_FROM_BACKGROUND"/>
<permission android:name="android.permission.START_ACTIVITIES_FROM_BACKGROUND"
android:protectionLevel="signature|privileged|vendorPrivileged|oem|verifier" />
Do we need to change the way we are scanning or do we add any permissions or settings ???
Please help
A: If you want to scan in the background, you need to add the ACCESS_BACKGROUND_LOCATION to your permissions (both in the manifest file and at runtime). There are a few other restrictions when it comes to scanning in the background; the articles below do a good job covering them and how to temporarily overcome them:-
*
*Restrictions when scanning background in Android 10
*ACCESS_BACKGROUND_LOCATION permission
*Beacond detection with Android 8
*Background BLE scan in DOZE mode
*Android BLE scan stops after a couple of minutes in the background
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75182551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Mutable reference to an item using 'find' in Rust How can I get a mutable reference to an item found in a vector?
I've tried the following which works if I don't make the iterator mutable using .iter():
fn main() {
let mut vec = vec![1, 2, 3, 4];
let mut wrong = -1;
let working = match vec.iter().find(|&c| *c == 2) {
Some(c) => c,
None => &wrong
};
println!("Result: {}", working);
}
But when I try to get a mutable reference using a mutable iterator .iter_mut(),
fn main() {
let mut vec = vec![1, 2, 3, 4];
let mut wrong = -1;
let mut error = match vec.iter_mut().find(|&c| *c == 2) {
Some(c) => c,
None => &mut wrong
};
println!("Result: {}", error);
}
I get the following error:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:5:48
|
5 | let mut error = match vec.iter_mut().find(|&c| *c == 2) {
| ^-
| ||
| |hint: to prevent move, use `ref c` or `ref mut c`
| cannot move out of borrowed content
I also tried to make the type in the closure mutable with |&mut c| but that gives the following error:
error[E0308]: mismatched types
--> src/main.rs:5:48
|
5 | let mut error = match vec.iter_mut().find(|&mut c| *c == 2) {
| ^^^^^^ types differ in mutability
|
= note: expected type `&&mut {integer}`
found type `&mut _`
= help: did you mean `mut c: &&&mut {integer}`?
A: Rust's .find passes the callback the type &Self::Item, and since you are using .iter_mut(), you've created an iterator where each item is &mut T. That means the type passed to your find callback is &&mut T. To get that to typecheck, you can do either
vec.iter_mut().find(|&&mut c| c == 2)
or
vec.iter_mut().find(|c| **c == 2)
with the second one being preferable.
The error you are getting is because the middle-ground you've chosen by using &c would set c to a value of &mut T, and one of Rust's big rules is that multiple things can't own a mutable reference to an item at the same time. Your non-mutable case works because you are allowed to have multiple immutable references to an item.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48551026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Textblocks aren't added? I'm trying to generate some UI Elements dynamically. The whole thing works, except it seems like the textblocks are invisible.
Grid pGrid = this.createPodiumGrid();
//create textblocks etc
TextBlock bTijd = new TextBlock();
bTijd.Text = currentGig.BeginTijd;
bTijd.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
bTijd.Foreground = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
Grid.SetColumn(bTijd, 0);
Grid.SetRow(bTijd, 0);
pGrid.Children.Add(bTijd);
TextBlock pName = new TextBlock();
pName.Text = currentGig.Podium.Naam;
pName.Margin = new Thickness(20, 0, 0, 0);
pName.Foreground = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
Grid.SetColumn(pName, 1);
Grid.SetRow(pName, 0);
pGrid.Children.Add(pName);
Image favImg = new Image();
favImg.Source = new BitmapImage(new Uri("/Images/thumb.png", UriKind.RelativeOrAbsolute));
favImg.Width = 50;
favImg.Height = 50;
favImg.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
Grid.SetColumn(favImg, 2);
Grid.SetRow(favImg, 0);
pGrid.Children.Add(favImg);
podiumStackPanel.Children.Add(pGrid);
The last image, does show on the right location. Am I missing something here? Text color is black on a white background. But I can't see the text. I'm 100% positive that the value is filled.
A: Change your code to the following:
bTijd.Foreground = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
You have set the color to transparent by adding the first '0'.
A: You have made their Foreground transparent by setting a zero alpha value in Color.FromArgb.
Set the Foreground to Colors.Black instead, e.g.
bTijd.Foreground = new SolidColorBrush(Colors.Black);
or of course
bTijd.Foreground = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
A: pName.Foreground = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
The first parameter of Color.FromArgb is the alpha channel. That is, the opacity. And you're setting it to 0, which explains why the TextBlock is invisible. Just set it to 255 instead:
pName.Foreground = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
Or use the Colors enumeration:
pName.Foreground = new SolidColorBrush(Colors.Black);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20967905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Autoscale WinForms Has a program written in a notebook with a resolution of 1600x900, all the elements are placed normally, and the same program on a monitor with 1920x1080 scale from 125% windows are placed incorrectly. How on WinForms c# consider it and how to redraw?
A: You need to consider using the anchor and Dock properties this is how you position your controls on the form and control their positions in various scales
you can find here very useful article about using
anchoring and docking
A: By making use of anchors and docks then you should be able to create a WinForm which scales to any size monitor.
It would be helpful if you could edit your question and include the designer code so we can see what's happening.
A: In order to make the form resize as you want, You can use table layout panels to set your layout and then you can use the anchor property of the controls to set, where they should move when the form is resized.
The anchor property simply anchors the control to a location, for example if you anchor a text box to may be left, then on resize it will be at left. Or if you anchor it to say both left and right, if will expand in both directions. Just explore them and it should work fine for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21648977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any way to find out whether we have opened page in Touch UI or classic UI in javascript Is there any way to find out whether we have opened this page in Touch UI or classic UI in javascript
like we have in classic UI to find out whether page is in edit mode or design mode.
CQ.WCM.editMode
Please suggest.
A: If you are not restricting to determine ui mode within javascript, here are other ways:
*
*If you have a model class for your component, check for this
condition:
AuthoringUIMode.TOUCH.equals(AuthoringUIMode.fromRequest(getRequest()))
*To check from JSP, use this code:
Placeholder.isAuthoringUIModeTouch(slingRequest)
A: You can simply read the cookie value of cq-authoring-mode. It can either be CLASSIC or TOUCH.
var isTouch = $.cookie('cq-authoring-mode') === 'TOUCH'
The other way would be to look for an outstanding JS objects like Granite.UI. This might be painful in the future when the clientlib that created the object will be attached to the other mode (e.g. via an AEM hotfix or unconsciously during the development).
var isTouch = Granite.UI != null
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34553802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: app.get('/') not being called when site opened Whenever I open my site (i.e. http://127.0.0.1:8090), a GET request to / is not made.
app.use(session({
//session stuff
}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('client'));
app.get('/', async function(req, res){
console.log(req);
}
module.exports = app;
app.listen(8090);
This is not being called and I am unsure why - what can I do to fix this? My other app.get() functions are called when the relevant pages are opened.
A: When you open your site (i.e. http://127.0.0.1:8090) it sends a GET request but doesn't send back to the browser any response. That is why it seems GET request wasn't made. Send a response in the app.get and it'll send a response.
app.get('/', async function(req, res){
console.log(req);
res.send('Hello World');
}
A: express.static('client') suggest from where your static files are to be loaded. Here 'client' is treated as your root path.
If your 'client' directory has some 'abcd.img' file then, http://127.0.0.1:8090/abcd.img will load 'abcd.img'. 'index.html' in your 'client' directory will be loaded by default when you point to root path. That means 'http://127.0.0.1:8090/' will load your index.html file.
Express has a very good documentation on this part. I am pasting it for your reference.
Express documentation for serving static files
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55791707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How stop setTimeout after 1 min which is repeating every 1 second Here is Original Question
Following function is doing one thing. "repeating every 1 sec infinitely."
But I want this function repeat every x second just for 1 min. After 1 min, it should stop forever.
var repeater;
function doWork() {
$('#more').load('exp1.php');
repeater = setTimeout(doWork, 1000);
}
doWork();
A: One way would be to keep a counter that's incremented on every call, and call the recursive setTimeout only when that counter is below 60:
let count = 0;
function doWork() {
$('#more').load('exp1.php');
count++;
if (count < 60) setTimeout(doWork, 1000);
}
doWork();
Note that there's no need for the repeater variable since you aren't using clearTimeout anywhere.
Or, using setInterval and clearInterval:
const interval = setInterval(doWork, 1000);
setTimeout(() => clearInterval(interval), 59500);
doWork();
A: I would pass in a value to the setTimeout duration as a multiplier. Assuming the lifecycle of the function exists beyond this duration, it would simply increment the value passed in.
So, you would multiply 1000 by an integer that would increment inside the function itself. Starting from 1 and going to 60. Then wrap the instructions inside an if statement. If the value of the increment integer is less than 60, do work.
A: Just try this one,
var count = 60;
function doWork() {
var interval = setInterval(function(){
$('#more').load('exp1.php');
count--;
if (count ==0) clearInterval(interval);
},1000);
}
doWork();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53235935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++ pointers reverting back There are 3 linked lists with 2 already in order. The 2 linked lists are sorted into the 3rd(headZ). If I pass headZ as a pointer like it already is it reverts back to an empty list at the exit of the function. If I pass by reference, it exits and headZ only contains 1 number. I cannot figure out how to get it to work.
void SortedRecur(Node*& headX, Node*& headY, Node* headZ){
if (headX == NULL && headY == NULL)
return;
else if (headX == NULL && headY != NULL)
{
if (headZ == 0)
{
headZ = headY;
headY = headY->link;
headZ->link = NULL;
}
else
{
headZ->link = headY;
headY = headY->link;
headZ = headZ->link;
headZ->link = NULL;
}
SortedRecur(headX, headY, headZ);
}
else if (headX != NULL && headY == NULL)
{
if (headZ == 0)
{
headZ = headX;
headX = headX->link;
headZ->link = NULL;
}
else
{
headZ->link = headX;
headX = headX->link;
headZ = headZ->link;
headZ->link = NULL;
}
SortedRecur(headX, headY, headZ);
}
if (headX != NULL && headY != NULL)
{
if (headX->data > headY->data)
{
if (headZ == NULL)
{
headZ = headY;
headY = headY->link;
headZ->link = NULL;
}
else
{
headZ->link = headY;
headY = headY->link;
headZ = headZ->link;
headZ->link = NULL;
}
}
else
{
if (headZ == NULL)
{
headZ = headX;
headX = headX->link;
headZ->link = NULL;
}
else
{
headZ->link = headX;
headX = headX->link;
headZ = headZ->link;
headZ->link = NULL;
}
}
SortedRecur(headX, headY, headZ);
}
cout << "ListZ: "; ShowAll(cout, headZ);} //Test contents of headZ
A: If you don't pass headZ as a reference, then headZ pointer will not be changed when it is passed to this function. So for example if you do something like this:
Node* resultHead = NULL;
Node* inputA = GetInitialAList(); // (hypothetical function to get the inital value)
Node* inputB = GetInitialBList();
SortedRecur(inputA, inputB, resultHead);
then the value of resultHead will be unchanged, and thus it will still be NULL.
On the other hand, if you changed SortedRecur to take headZ as a reference, then the final value of headZ will point to the last element in your list, because every time you add a new element you also do headZ = headZ->link; - and so headZ is always pointing to the end of the list. The start of the list is lost.
I think the easiest way to solve the problem is to keep your current implementation of SortedRecur, but rather than passing a NULL pointer for headZ, use an initial value which points to an actual node. That way, SortedRecur can add the sorted list to the end of your headZ and it won't matter that the initial headZ pointer is unchanged. For example, here's a kludge way to do it:
Node dummyNode;
dummyNode.link = NULL;
Node* resultHead = &dummyNode;
Node* inputA = GetInitialAList(); // (hypothetical function to get the inital value)
Node* inputB = GetInitialBList();
SortedRecur(inputA, inputB, resultHead);
// At this point, the value of resultHead is unchanged,
// but the dummyNode now points to the sorted list.
// All we have to do now is discard the dummyNode.
resultHead = dummyNode.link;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19968994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Including Moment.js in LiveCycle Designer For few days I've been trying to include the actual Moment.js library in my dynamic PDF which I've created with Adobe Livecycle Designer.
We've used an older version (1.7.2) without any problems but now I only get a 'Function not exist' error.
Does anyone have any expierience with this?
Thanks in advance.
A: How to include Moment.js in an Adobe LiveCycle Form:
*
*Download the minified script
*In LiveCycle Designer open your form and create a Script Object called MOMENTJSMIN
*Copy the minified script into that Script Object
*In the Script Editor window of LiveCycle Designer, edit MOMENTJSMIN Script Object in the following manner:
*Remove all the script up to but not including the second curly brace { :
!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):a.moment=b()}(this,function()
*Remove the rounded parenthesis and semicolon from the end of the minified script
*Add this line to the beginning of the minified script:
if (xfa.momentjs == undefined) xfa.momentjs = function()
*In the MOMENTJSMIN Script Object add this function after the end of the script:
function getMomentJS(){
return xfa.momentjs();
}
Now your MOMENTJSMIN script object is set up to provide Moment.js to scripts throughout your form.
To use Moment.js in any of your script, start your script object or event script with this line:
var moment = MOMENTJSMIN.getMomentJS();
Now you can use moment() anywhere in the script that starts with that line. eg:
var moment = MOMENTJSMIN.getMomentJS();
var jan07 = moment([2007, 0, 29]);
app.alert(moment().format("dddd, MMMM Do YYYY, h:mm:ss a"));
app.alert(jan07.format("dddd, MMMM Do YYYY") + " was " + jan07.fromNow());
app.alert(moment.isDate(new Date()));
A: What I would check first:
*
*Make sure your script is fully loaded before trying to invoke functions from it. (check the event, where you call the function-calculate, form:readty etc.)
*Check the script referencing. Right path? Right name?
*Check if the function really exists
*Check function parameters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26587484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Ruby#index Method VS Binary Search Given an element and an array, the Ruby#index method returns the position of the element in the array. I implemented my own index method using binary search expecting mine would outperform the built-in one. To my surprise, the built-in one ran approximately three times as fast as mine in an experiment.
Any Rubyist knows the reason why?
A: The built-in #index is not a binary search, it's just a simple iterative search. However, it is implemented in C rather than Ruby, so naturally it can be several orders of magnitude faster.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7436155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Maximum pool size error in C# using MySQL Do you have any suggestion on how I will manage my application to run properly? It basically updates all rows (203 rows but can be more) in a table of my database. And I need to run it all day. After an hour of running, it prompts an error:
MySqlException: error connecting: Time out expired. The timeout period elapsed prior and max pool size was reached to obtaining a connection from the pool. This may have occurred because all pooled connection were in use.
I close my connection using conn.Close().
I'm not sure if increasing the pool size will be the best solution for this since it will run all day and possibly it may reach the pool size I set.
Here's my code:
public static class Globals
{
//Global Variable
public static String update;
public static String update2;
public const String connectionString = "server=localhost; uid=root; pwd=; database=it_map;";
public static int totalruntime = 0;
}
static void Main(string[] args)
{
while (true)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread t = new Thread(new ThreadStart(pingLaptop));
Thread t2 = new Thread(new ThreadStart(pingDesktop));
//Thread t3 = new Thread(new ThreadStart(pingPhone));
//Thread t4 = new Thread(new ThreadStart(pingLaptop));
Console.WriteLine("\nUpdating all status...\n");
t.Start();
t2.Start();
//t3.Start();
//t4.Start();
t.Join();
t2.Join();
//t3.Join();
//t4.Join();
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine("\nRunTime " + elapsedTime);
Console.WriteLine("\nNext run will start after 1 second...");
Thread.Sleep(1000);
}
}
static void pingLaptop()
{
String sql = "SELECT * FROM tbl_units WHERE Category=\"Laptop\"";
MySqlConnection conn, conn2;
MySqlCommand command, command2;
MySqlDataReader reader;
PingReply reply;
Ping myPing;
String netbios_name;
try
{
conn = new MySqlConnection(Globals.connectionString);
command = new MySqlCommand(sql, conn);
conn.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
myPing = new Ping();
netbios_name = reader.GetString("NetBios_Name");
Console.WriteLine("Laptop: " + netbios_name);
try {
reply = myPing.Send(netbios_name, 2000);
if (reply != null) {
string status = reply.Status.ToString();
//Updates the 'Status' of a unit in the database
Console.WriteLine(netbios_name + " Status: "+status);
if(status.Equals("Success")) {
Globals.update = "UPDATE tbl_units SET Status=\"Online\" WHERE NetBios_Name = @name";
}
else if (status.Equals("TimedOut")) {
Globals.update = "UPDATE tbl_units SET Status=\"Offline\" WHERE NetBios_Name= @name";
}
//Builds another connection to database
using (conn2 = new MySqlConnection(Globals.connectionString)) {
command2 = new MySqlCommand(Globals.update, conn2);
command2.Parameters.AddWithValue("@name", netbios_name);
conn2.Open();
command2.ExecuteNonQuery();
}
}
}
catch (PingException e) {
Console.WriteLine("Status: Host is unreachable.");
Globals.update = "UPDATE tbl_units SET Status=\"X\" WHERE NetBios_Name= @name";
using (conn2 = new MySqlConnection(Globals.connectionString)) {
command2 = new MySqlCommand(Globals.update, conn2);
command2.Parameters.AddWithValue("@name", netbios_name);
conn2.Open();
command2.ExecuteNonQuery();
}
}
}
}
catch (MySqlException ex)
{
Console.WriteLine("Laptop");
Console.WriteLine(ex.ToString());
}
}
I'm now using using() instead of conn.Close. I have another function which is pingDesktop, it does the same with different query.
A: You didn't close
conn.Open();
Add conn.Close in try-catch's finally
finally
{
conn.Close();
}
Add max pool size in your connection string
Like this
public const String connectionString = "server=localhost; uid=root; pwd=; database=it_map;max pool size=5;";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31174278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Parse impersonate user I need to debug some user issues which can only be debugged by actually being the user. Is there a way I can impersonate a user without knowing their password? I'd rather not have to reset their password in the DB as that will lose the original one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29712309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get the deleted file name using Microsoft graph's delta query I am running a delta query against SharePoint site drive root. For the removed files I am just getting "deleted" property and DriveItem Id and the name property is always null. Whenever doing a separate DriveItem request with the corresponding DriveItem Id for the removed file getting 404. Any ideas on how can we retrieve the properties of the deleted file?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75615639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get only the value of the first data object from a JSON response when there are more data objects with the same name? I want a value from a JSON request to be filled in an source url as in the code I currently have below:
function Source() {
$.ajax({
type: "GET",
dataType: "json",
url: "https://api.hitbox.tv/media/video/chairstream/list?filter=recent",
success: function(data) {
var idvid = data.media_id;
document.getElementById("latest").src = "http://www.hitbox.tv/#!/embedvideo/" + idvid() + "?autoplay=true";
}
});
Problem is that the variable idvid isn't doing his work in the url.
Another problem is that there are more data objects named "media_id" in the JSON response and I wan't to know how to get only the value of the first media_id. I'll be very happy when both problems could be solved.
A: Not sure why you have braces after idvid but it should just be
"http://www.hitbox.tv/#!/embedvideo/" + idvid + "?autoplay=true";
To get the media_id of the first object in the data array:
var idvid = data.video[0].media_id;
A: I called the URL and got it using this
data.video[0].media_id
so (dropping the () from the var too as suggested by Andy):
success: function(data) {
$("#latest").attr("src","http://www.hitbox.tv/#!/embedvideo/" +
data.video[0].media_id +
"?autoplay=true");
}
var data = {
"request": {
"this": "\/media\/video\/chairstream\/list"
},
"media_type": "video",
"video": [{
"media_user_name": "chairstream",
"media_id": "783994",
"media_file": "2c767c827c6c84a4714b9379983de69449c5a1c1-5658c80c2b938",
"media_user_id": "871797",
"media_profiles": "[{\"url\":\"\\\/chairstream\\\/2c767c827c6c84a4714b9379983de69449c5a1c1-5658c80c2b938\\\/chairstream\\\/index.m3u8\",\"height\":\"800\",\"bitrate\":0}]",
"media_type_id": "2",
"media_is_live": "1",
"media_live_delay": "0",
"media_date_added": "2015-11-27 23:16:04",
"media_live_since": null,
"media_transcoding": null,
"media_chat_enabled": "1",
"media_countries": null,
"media_hosted_id": null,
"media_mature": null,
"media_hidden": null,
"media_offline_id": null,
"user_banned": null,
"media_name": "2c767c827c6c84a4714b9379983de69449c5a1c1-5658c80c2b938",
"media_display_name": "chairstream",
"media_status": "Chairstream.com - Nov 27th #5",
"media_title": "Chairstream.com - Nov 27th #5",
"media_description": "",
"media_description_md": null,
"media_tags": "",
"media_duration": "6262.0000",
"media_bg_image": null,
"media_views": "9",
"media_views_daily": "2",
"media_views_weekly": "9",
"media_views_monthly": "9",
"category_id": null,
"category_name": null,
"category_name_short": null,
"category_seo_key": null,
"category_viewers": null,
"category_media_count": null,
"category_channels": null,
"category_logo_small": null,
"category_logo_large": null,
"category_updated": null,
"team_name": null,
"media_start_in_sec": "0",
"media_duration_format": "01:44:22",
"media_thumbnail": "\/static\/img\/media\/videos\/2c7\/2c767c827c6c84a4714b9379983de69449c5a1c1-5658c80c2b938_mid_000.jpg",
"media_thumbnail_large": "\/static\/img\/media\/videos\/2c7\/2c767c827c6c84a4714b9379983de69449c5a1c1-5658c80c2b938_large_000.jpg",
"channel": {
"followers": "0",
"user_id": "871797",
"user_name": "chairstream",
"user_status": "1",
"user_logo": "\/static\/img\/channel\/chairstream_5602c1d59d02e_large.png",
"user_cover": "\/static\/img\/channel\/cover_53e89056cf3ef.jpg",
"user_logo_small": "\/static\/img\/channel\/chairstream_5602c1d59d02e_small.png",
"user_partner": null,
"partner_type": null,
"user_beta_profile": "0",
"media_is_live": "0",
"media_live_since": "2015-11-30 12:35:33",
"user_media_id": "206125",
"twitter_account": null,
"twitter_enabled": null,
"livestream_count": "1"
}
}]
}
console.log(data.video[0].media_id)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33999990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Curl giving unauthorized response in production but not in localhost I am using Curl to get contents of a website but I'm getting a 403 access denied response on production. However, on my local machine (localhost), it works fine.
I'm essentially using Curl to login to a website and then access the content after login.
I think it has something to do with setting headers but I'm not quite sure, since the headers work on localhost.
Here's my code for the curl request:
$email = "[email protected]";
$password = "password";
$ch = curl_init();
$options = [
CURLOPT_URL => 'https://auth.example.com/ajax/',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => "email=$email&password=$password",
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HEADER => 0,
CURLOPT_REFERER => 'https://my-website.com',
CURLOPT_COOKIEFILE => dirname(__FILE__) . '/cookie.txt',
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2117.157 Safari/537.36',
CURLOPT_COOKIEJAR => dirname(__FILE__) . '/cookie.txt',
CURLOPT_RETURNTRANSFER => true,
];
curl_setopt_array($ch, $options);
curl_exec($ch);
//change URL
curl_setopt($ch, CURLOPT_URL, "https://example.com/logged-in");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
// do stuff with content
I'm also very interested in how this works in localhost and not in production.
Any help is greatly appreciated!
A: Your cookie jar is likely not writable by the server user in your production environment. Libcurl can't throw an error about this, so you're getting a 403 when your second request fires.
If you have command line access, run chmod 777 on your script's directory to test it. If it works, fix up your webserver permissions and undo the 777 permissions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58177050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ doesn't compile my custom data type including a vector in it I tried to do a custom list, which has intern a private vector.
yet I allways get this Error-message, and have no idea where even start to look for the problem. I use Qt, windows and "CONFIG += c++11" within my project.
...myPath\c++\bits\stl_construct.h:75: Error: call of overloaded 'myDataType()' is ambiguous
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^
What does this errormessage tries to tell me here? Where should I start to look?
thanks for any hint.
Edit: Constructors for lists:
/***********************************************************************
* Constructors and a Destructor
* *********************************************************************/
datatype_collection::datatype_collection(){
std::vector<datatype> erg (0);
m_datatype_list = erg;
}
datatype_collection::~datatype_collection(){
}
for datatype:
/***********************************************************************
* Constructors and a Destructor - Implemented because of the rule of 3
* *********************************************************************/
datatype::datatype(float value)
: m_datatype( to_datatype(value) ){
}
datatype::datatype(int32_t value)
: m_datatype(value){
}
fix_point::~fix_point(){
}
Edit2: There is a lot of more text, but it isn't directly marked as the error:
...\mingw482_32\i686-w64-mingw32\include\c++\vector:62: In file included from
.../mingw482_32/i686-w64-mingw32/include/c++/vector:62:0,
...\QtCreator\bin\myFolder\datatype_collection.h:25: from ..\myFolder\datatype_collection.h:25,
...\QtCreator\bin\myFolder\datatype_collection.cpp:1: from ..\myFolder\datatype_collection.cpp:1:
...\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_construct.h:-1: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = fix_point; _Args = {}]':
...\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_uninitialized.h:495: required from 'static void std::__uninitialized_default_n_1<_TrivialValueType>::__uninit_default_n(_ForwardIterator, _Size) [with _ForwardIterator = fix_point*; _Size = unsigned int; bool _TrivialValueType = false]'
...\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_uninitialized.h:544: required from 'void std::__uninitialized_default_n(_ForwardIterator, _Size) [with _ForwardIterator = fix_point*; _Size = unsigned int]'
...\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_uninitialized.h:605: required from 'void std::__uninitialized_default_n_a(_ForwardIterator, _Size, std::allocator<_Tp>&) [with _ForwardIterator = fix_point*; _Size = unsigned int; _Tp = fix_point]'
...\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_vector.h:1225: required from 'void std::vector<_Tp, _Alloc>::_M_default_initialize(std::vector<_Tp, _Alloc>::size_type) [with _Tp = fix_point; _Alloc = std::allocator<fix_point>; std::vector<_Tp, _Alloc>::size_type = unsigned int]'
...\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_vector.h:271: required from 'std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>::size_type, const allocator_type&) [with _Tp = fix_point; _Alloc = std::allocator<fix_point>; std::vector<_Tp, _Alloc>::size_type = unsigned int; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<fix_point>]'
...\QtCreator\bin\Aufgabe2Punkt1\datatype_collection.cpp:8: required from here
...\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_construct.h:75: Error: call of overloaded 'datatype()' is ambiguous
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^
...\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_construct.h:75: candidates are:
...\QtCreator\bin\myFolder\datatype_collection.h:24: In file included from ..\myFolder\datatype_collection.h:24:0,
...\QtCreator\bin\myFolder\datatype_collection.cpp:1: from ..\myFolder\datatype_collection.cpp:1:
...\QtCreator\bin\myFolder\datatype.hpp:48: datatype::datatype(int32_t)
datatype(int32_t value=0); //constructor with default value
...\QtCreator\bin\myFolder\fixpoint.hpp:47: datatype::datatype(float)
datatype(float value=0); //constructor with default value
^
Update:
I found what causes the trouble, but I have no idea why it causes the problems:
/****************************************************************
* overloading of the []-operator
* *************************************************************/
const datatype& datatype_collection::operator[](int value) const{ //read-only
return m_datatype_list[value];
}
This method causes the error as seen above.
A: Solved by Hi-Angel:
the problem is that you have two constructors with a default values. The call datatype() at the line 8 is ambiguous: which one should be chosen? As far as I know, you couldn't resolve this by anything with an exception of just removing one of a default values.
Disclaimer: this was extracted from the question and posted here on the OP's behalf.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27321914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: need a dictionary like this i want to use an ordered dictionary which its iterate action looks like list
seq.append(2)
seq.append(3)
seq.append(1)
print(seq)# the list should be 2,3,1
dic[2] = '22222'
dic[3] = '333333'
dic[1] = '111111'
print(dic)# should be {2:'22222',3,'333333',1:'111111'} not {1...2...3}
i don't know if there is already a class in python standard library.or i need a list to keep the order,that's would be too complicated, tell me the simplest way you know how to do it.
A: The Python OrderedDict collection will help you here:
"dict subclass that remembers the order entries were added"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12505531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wordpress reverse date format for display but not db I have a events page using a custom wp_query so that I can split post into upcoming events and past events. To do this I need the date to be stored in the database Y/m/d format but would like it to display on the front ends d/m/y. Any help on how I should do this, I could reverse it with jquery but there might be a better way?
thanks
A: That page is probably using the_date() function.
If so, modify it using format parameter to something like this:
the_date('d/m/Y');
Check also this Codex page about formatting the date and time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16558323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Writing a function that checks if a string is a palindrome I need to write a function that determines if a given string is a palindrome. Here is what I wrote so far:
def isPalindrome(string):
found = False
for i in range(len(string)):
if string[i] == string[len(string) - 1 - i]:
found = True
if found == True:
print("Inserted string is a palindrome. ")
else:
print("Inserted string is not a palindrome. ")
return
I iterate over the string, and check if forward and backward iteration gives equal characters. But if I apply this program by executing isPalindrome("hello") , it says this is a palindrome. It doesn't give me the correct output. Could someone please point out any mistake I made, so that I may learn from that.
A: You set found to true the moment you find any character that is equal to the 'mirror' character. For a word with an odd number of characters, that is always going to be true (the middle character is equal to the middle character), for example, but other words are going to generate a false match too. Take the word winner for example, the two ns in there are in mirror positions and your function will proclaim it a palindrome while clearly it is not.
Instead of setting found to true, exit early if you find a mismatch:
found = True
for i in range(len(string)):
if string[i] != string[len(string) - 1 - i]:
found = False
break
So you start out assuming it is a palindrome, and you exit when you find evidence to the contrary.
Note that you could stop checking when you have checked half the string:
for i in range((len(string) + 1) // 2):
if string[i] != string[len(string) - 1 - i]:
found = False
break
or you could just test if the string is equal to its reverse; the [::-1] gives you the string reversed:
string == string[::-1]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33335318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: please help me to define a perl regular expression I'm new to everything. Please help. I'm trying to crawl every
<div class="name"><a href="/v/name/idlike123123ksajdfk">name</a></div>
in a webpage. I want to catch the /v/name/idlike123123ksajdfk part. (Knowing that the
<div class="name"><a href="/v/
part is fixed) So I wrote the regular expression (can make you laugh):
~m#<div class="name"><a href="(/v/.*?)">#
It will be very helpful if you correct my stupid code.
A: Using a robust HTML parser (see http://htmlparsing.com/ for why):
use strictures;
use Web::Query qw();
my $w = Web::Query->new_from_html(<<'HTML');
<div class="name"><a href="/v/name/idlike123123ksajdfk">name</a></div>
<div class="name"><a href="/v/name/idlike123123ksajdfk">name</a></div>
<div class="name"><a href="/v/name/idlike123123ksajdfk">name</a></div>
<div class="name"><a href="/v/name/idlike123123ksajdfk">name</a></div>
<div class="name"><a href="/v/name/idlike123123ksajdfk">name</a></div>
HTML
my @v_links = $w->find('div.name > a[href^="/v/"]')->attr('href');
A: There are plenty of Perl modules that extract links from HTML. WWW::Mechanize, Mojo::DOM, HTML::LinkExtor, and HTML::SimpleLinkExtor can do it.
A: Web scraping with Mojolicious is probably simplest way to do it in Perl nowadays
http://mojolicio.us/perldoc/Mojolicious/Guides/Cookbook#Web_scraping
A: You should not use regex for parsing HTML, as there are many libraries for such parsing.
Daxim's answer is good example.
However if you want to use regex anyway and you have your text assigned to $_, then
my @list = m{<div class="name"><a href="(/v/.*?)">}g;
will get you a list of all findings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10651849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add Bootstrap CDN to my Wordpress I want to use Bootstrap framework for my Wordpress.. how to edit in the functions.php ? i find somewhere tell the code like this
function enqueue_my_scripts() {
wp_enqueue_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', array('jquery'), '1.9.1', true); // we need the jquery library for bootsrap js to function
wp_enqueue_script( 'bootstrap-js', '//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js', array('jquery'), true); // all the bootstrap javascript goodness
}
add_action('wp_enqueue_scripts', 'enqueue_my_scripts');
and what is that mean of first paragraph function enqueue_my_scripts() and add_action('wp_enqueue_scripts', 'enqueue_my_scripts'); in the last paragraph ?
A: Those are called "hooks" and you can read about them here: http://codex.wordpress.org/Plugin_API
Otherwise your code is essentially correct, with one mistake. You have jQuery as a dependency to jQuery, which means it is never loaded and subsequently bootstrap is never loaded:
wp_enqueue_script(
'jquery',
'//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js',
array( 'jquery' ), // <-- Problem
'1.9.1',
true
);
Solution:
wp_enqueue_script(
'jquery',
'//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js',
array(), // <-- There we go
'1.9.1',
true
);
But, there's one more thing. WordPress already has jQuery ready for you to enqueue (i.e. wp_enqueue_script( 'jquery' ); will load the local copy of jQuery). It isn't necessary but I think it is best practice to enqueue a CDN version of a script with a suffix, i.e.:
wp_enqueue_script(
'jquery-cdn',
'//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js',
array(),
'1.9.1',
true
);
// And then update your dependency on your bootstrap script
// to use the CDN jQuery:
wp_enqueue_script(
'bootstrap-js',
'//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js',
array( 'jquery-cdn' ),
true
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37494517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Angular lifecycle hook When I use the firebase js sdk and make an angular project and implements the lifecycle hooks (for example afterviewinit) and write something on the console, the console message repeat again for infinity time. I would like that the message only once will be appeared on console.
Thanks the resolve for this problem
AppModule {
constructor(){
firebase.initializeApp(environment.firebase);
}
}
import { Component, DoCheck } from '@angular/core';
import { UserService } from ...;
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html'
})
export class NavbarComponent implements DoCheck {
public isCollapsed = true;
isLoggedIn = false;
constructor(public userService: UserService) {}
ngDoCheck(){ console.log("navbar docheck"); }
}
A: As I understand you, you have put a console.log() in all the lifecycle-hooks.
If you have also done it in ngAfterContentChecked / ngAfterViewChecked, you have to keep in mind that it is executed constantly, every time the change detection is run (application state change) and if you have a console.log(), it will appear infinitely
ngDoCheck is a callback method that performs change-detection, invoked after the default change-detector runs, and again, every time the change detection is run (application state change), if you have a console.log(), it will appear infinitely.
If you want it to only run once, use ngOnInit, ngAfterContentInit or ngAfterViewInit
angular.io/guide/lifecycle-hooks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56972487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to /clr compile "servprov.h" (IServiceProvider) I want to /clr compiling a project that need to "servprov.h" (IServiceProvider)
I faced to this ERROR:
Error 2 error C2872: 'IServiceProvider' : ambiguous symbol 116
it's part of code:
#ifndef __IServiceProvider_FWD_DEFINED__
#define __IServiceProvider_FWD_DEFINED__
typedef interface IServiceProvider IServiceProvider;
1- I changed all IServiceProvider to ::IServiceProvider
at this part
typedef /* [unique] */ __RPC_unique_pointer ::IServiceProvider *LPSERVICEPROVIDER;
I faced to this error:
Error 1 error C3699: '*' : cannot use this indirection on type
'System::IServiceProvider' 92
2- I changenged it to:
typedef /* [unique] */ __RPC_unique_pointer System::IServiceProvider ^ LPSERVICEPROVIDER;
and again I have error :( at this part of code:
typedef interface ::IServiceProvider IServiceProvider;
Error 2 error C2371: 'IServiceProvider' : redefinition; different
basic types 99
3- I chenged it to:
typedef interface ::IServiceProvider IServiceProvider2;
and now I have this error:
Error 3 error LNK2028: unresolved token (0A0001CA) "public: __thiscall
cComponentManager::~cComponentManager(void)"
(??1cComponentManager@@$$FQAE@XZ) referenced in function "public: void
* __thiscall cComponentManager::`scalar deleting destructor'(unsigned int)"
(??_GcComponentManager@@$$FQAEPAXI@Z) C:....\OpenSmileCLI\OpenSmileCLI\OpenSmileCLI.obj
Error 67 error LNK2001: unresolved external symbol "public: virtual
void __thiscall ConfigValueObj::copyFrom(class ConfigValue const *)"
(?copyFrom@ConfigValueObj@@UAEXPBVConfigValue@@@Z) C:...\OpenSmileCLI\OpenSmileCLI\OpenSmileCLI.obj
Is my changed correct?
what I should do?
"servprov.h" used by OpenSmileLibrary
and I want to create CLI between C# and openSmileLibrary!
solution:
I change debug mode to release (cause of OpenSmileLibrary) and change position of using System after #include "servprov.h".
for LNK error :
remove space in path directory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30583001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Should .rvm and all its subdirectories be owned by user instead of root? I have a ~/.rvm file that has some subdirectories owned by user (anthony) and some owned by root. This is causing issues when I am trying to gem install.
I am tempted to run sudo chown -R anthony:staff ~/.rvm so I have full user control over the entire .rvm folder.
Is this ok/desired?
Thanks!
A: all files / directores should be owned by user, to fix it run:
rvm fix-permissions
to avoid this problem in future just try to avoid using sudo or rvmsudo it should be never required (rvm uses sudo internally when it is required).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19442322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to build a Interface like Evernote. One Page, Columns Evernote just released a new web interface which is interesting. It's one page, columns are resizable with the mouse etc.
Screenshot: http://blog.evernote.com/wp-content/uploads/2011/03/evernote_web_new8.jpg
What's the best way to build something like this with jQuery? Also, any idea what Evernote used to build this interface? I couldn't find anything in firebug with hints.
Thank you
A: If you're curious about this sort of stuff you should play around with Chrome Developer Tools, the Firefox Firebug Addon or the Safari's 'Developer' menu. They're really great at giving you an insight as to what is going on in a webpage
As to "how did they build this" there's many, many different technologies being used up and down the web application stack. Keep in mind the servers storing, caching and fetching all this data are just as much a part of the web application as the frontend. But I imagine your question is asking how "how did they get this webpage to do all this interactive stuff".
Basically it looks like it's all traditional HTML/CSS--no "HTML5" canvas shenanigans or Flash.
The interactivity comes from their custom Javascript code. I tried to figure out if they're using some popular 3rd party Javascript Framework (like jQuery or Prototype) but they are importing so many scripts it's hard to follow. Interestingly enough jQuery and $ are not defined variables on the Evernote page, so it looks like they're not using jQuery at the least. They have clearly written a lot of Javascript to get this thing up and running so it's not that big of a stretch to imagine they they would just decide to keep all their code in-house.
FYI: The three columns are just absolutely positioned and sized <div>s.
<div style="position: absolute; overflow-x: hidden; overflow-y: hidden; left: 0px; top: 0px; bottom: 0px; width: 220px; ">...</div>
<div style="position: absolute; overflow-x: hidden; overflow-y: hidden; left: 220px; top: 0px; bottom: 0px; width: 360px; ">...</div>
<div style="position: absolute; overflow-x: hidden; overflow-y: hidden; left: 580px; top: 0px; right: 0px; bottom: 0px; ">...</div>
The scrolling that you see in those columns is done in child <div>s.
A: webapps like this are usually built with a javascript framework such as backbone, angularjs, ember, etc. here is a reference site which lists them:
http://todomvc.com/
Its hard to see what js framework they are using if any but there are using jQuery 1.8
They are using http://icanhazjs.com/ which is a javascript client side template library.
They are using http://requirejs.org/
A: Well, at the very basic evernote has accomplished its note app workflow using custom javascript, although there are lot of others frameworks they have used for backend work. One way is to see it using Chrome web Inspector nad if on Firefox ,then they have upgraded there web inspector and its much cooler now, but if you prefer the much popular firebug, it will do.
For detailed info, on what are the resources they have used to build, on way is to track it using a web analyzer tool like www.buitwith.com
here, is the link for the homepage of the evernote site , searched over Builtwith.com : http://builtwith.com/?https%3a%2f%2fwww.evernote.com
However the app, that is built upon comprises a lot of custom code. Hard to specify the exact usage, but if we check the code, it doesn't show any of specific use of AngularJS , they do use requireJS for loading modules.
As your question is front-end specific, it can be done using HTML5, with some javascript or if you prefer a framework to ease the process, then checkout this link from JQueryUI.
https://jqueryui.com/resizable/
They are still the kings of UI development, if AngularJS and ReactJS are not mentioned to be overwhelmed.
And also , if you try to do it using plain vanilla JavaScript, that will give you an edge to the learning curve a loads.
A: They use Angular.js, HTML5, CSS3, custom Javascript, and JQuery (and lots of other stuff as others have noted).
From: http://evernote.com/careers/job.php?job=om2qXfwv
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5503276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Flutter: Container's color change when i add box shadow (Opacity and BoxShadow doesn't work well) I'm trying to make a simple container with shadow effect. It is a Opaque container with a box-shadow effect. But i dont think '.withOpacity' and 'boxShadow' work well together. Because every time i add 'boxShadow' to my container it make my container's color change.
Here is my code
return Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/background/bg_app_background.png"),
fit: BoxFit.cover,
),
),
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: const Text("TEST"),
),
body: SafeArea(
child: Container(
margin:
const EdgeInsets.symmetric(horizontal: 20.0, vertical: 30.0),
alignment: Alignment.center,
width: double.infinity,
height: 200,
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF).withOpacity(0.4),
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
border: Border.all(
color: const Color(0xFFFFFFFF),
width: 1.0,
style: BorderStyle.solid),
boxShadow: <BoxShadow>[
BoxShadow (
color: const Color(0xFF000000).withOpacity(0.16),
offset: const Offset(0.0, 3.0),
blurRadius: 6.0,
//blurStyle: BlurStyle.outer
),
],
),
),
),
),
);
This is what i want
But this is what i receive (it's darker, right?)
Yes i have tried 'blurStyle: BlurStyle.outer' but it make my container's border look so bad
Is there any way to make Opacity and BoxShadow work together?
A: I think this is using BackdropFilter
class GlassMorphism extends StatelessWidget {
GlassMorphism({
Key? key,
required this.blur,
required this.opacity,
required this.child,
required this.color,
BorderRadius? borderRadius,
}) : _borderRadius = borderRadius ?? BorderRadius.circular(12),
super(key: key);
final Color color;
final double blur;
final double opacity;
final Widget child;
final BorderRadius _borderRadius;
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: _borderRadius,
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: blur,
sigmaY: blur,
),
child: Container(
decoration: BoxDecoration(
color: color.withOpacity(opacity),
borderRadius: _borderRadius,
border: Border.all(
color: color,
),
),
child: child,
),
),
);
}
}
And using it
class GSX extends StatelessWidget {
const GSX({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (context, constraints) => Container(
width: constraints.maxWidth,
height: constraints.maxHeight,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.amber.shade100,
Colors.blue.shade100,
],
),
),
child: Column(
children: [
GlassMorphism(
color: Colors.white,
blur: 1,
opacity: .4,
child: Container(height: 200, width: 100, child: Text("AA")),
),
],
),
),
),
);
}
}
A: return Container(
decoration: const BoxDecoration(
gradient: LinearGradient(colors:[Color(0xFFd9a7c7),Color(0xFF30E8BF),]),
),
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(title: const Text("TEST")),
body: SafeArea(
child: Container(
margin:
const EdgeInsets.symmetric(horizontal: 20.0, vertical: 30.0),
alignment: Alignment.center,
width: double.infinity,
height: 200,
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF).withOpacity(0.5),
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
border: Border.all(
color: const Color(0xFFFFFFFF),
width: 1.0,
style: BorderStyle.solid),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.black12.withOpacity(0.1),
offset: Offset(2.0, 4.0),
blurRadius: 6.0,
//blurStyle: BlurStyle.outer
),
],
),
),
),
),
);
A: You can create a custom box shadow like this:
class CustomBoxShadow extends BoxShadow {
final BlurStyle blurStyle;
const CustomBoxShadow({
super.color,
super.offset,
super.blurRadius,
this.blurStyle = BlurStyle.normal,
});
@override
Paint toPaint() {
final Paint result = Paint()
..color = color
..maskFilter = MaskFilter.blur(blurStyle, blurSigma);
assert(() {
if (debugDisableShadows) {
result.maskFilter = null;
}
return true;
}());
return result;
}
}
and then use it like this:
CustomBoxShadow(
blurRadius: 10,
color: Colors.white.withOpacity(.3),
offset: const Offset(0, 5),
blurStyle: BlurStyle.outer, //<--- this will give shadow outwards
),
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73216278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.