text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How do I use variables in a select query? I have this following select query that uses a scalar function to get full name. I want to eliminate the redundancy by using variable but so far there is no success. My query is
select
a.Id,
a.UserName,
getFullName(a.UserName),
a.CreateTime
from DataTable;
I don't want to retrieve 'a.User' two times. I would prefer if I can save a.User in a variable and then pass it to the function hence improving the efficiency.
Currently the work around I came up with is as following
select
Id,
UserName,
getFullName(UserName),
CreateTime
from (select a.Id, a.UserName, a.CreateTime from DataTable) temp
This solves the performance issue but adds the overhead to write same select two time. Any other suggestions would be great.
DataTable looks like this
+----+----------+------------+
| Id | UserName | CreateTime |
+----+----------+------------+
| 1 | ab | 10:00 |
| 2 | cd | 11:00 |
| 3 | ef | 12:00 |
+----+----------+------------+
Here is the NamesTable used to get the full names
+----------+----------+
| UserName | FullName |
+----------+----------+
| ab | Aa BB |
| cd | Cc Dd |
| ef | Ee Ff |
+----------+----------+
Here is the function that gets the full name
Create function [dbo].[getFullName](@user varchar(150)) returns varchar(500)
as
begin
declare @Result varchar(500);
select @Result = FullName from dbo.NamesTable where UserName = @user;
return @Result;
end;
A: You're solving a problem that doesn't exist. You seem to think that
select
a.Id,
a.UserName,
getFullName(a.UserName),
a.CreateTime
from DataTable;
Has some relatively expensive process behind it to get UserName that is happening twice. In reality, once the record is located, getting the UserName value is an virtually instant process since it will probably be stored in a "variable" by the SQL engine behind the scenes. You should have little to no performance difference between that query and
select
a.Id,
getFullName(a.UserName),
a.CreateTime
from DataTable;
The scalar function itself may have a performance issue, but it's not because you are "pulling" the UserName value "twice".
A better method would be to join to the other table:
select
a.Id,
a.UserName,
b.FullName,
a.CreateTime
from DataTable a
LEFT JOIN dbo.NamesTable b
ON a.UserName = b.UserName
A: As D Stanley says, you're trying to solve some problem that doesn't exist. I would further add that you shouldn't be using the function at all. SQL is meant to perform set-based operations. When you use a function like that you're now making it perform the same function over and over again for every row - a horrible practice. Instead, just JOIN in the other table (a set-based operation) and let SQL do what it does best:
SELECT
DT.Id,
DT.UserName,
NT.fullname,
DT.CreateTime
FROM
DataTable DT
INNER JOIN NamesTable NT ON NT.username = DT.username;
Also, DataTable and NamesTable are terrible names for tables. Of course they're tables, so there's no need to put "table" on the end of the name. Further, of course the first one holds "data", it's a database. Your table names should be descriptive. What exactly does DataTable hold?
If you're going to be doing SQL development in the future then I strongly suggest that you read several introductory books on the subject and watch as many tutorial videos as you can find.
A: Scalar UDF will execute for every row,but not defintely the way you think.below is sample demo and execution plan which proves the same..
create table testid
(
id int,
name varchar(20)
)
insert into testid
select n,'abc'
from numbers
where n<=1000000
create index nci_get on dbo.testid(id,name)
select id,name,dbo.getusername(id) from dbo.testid where id>4
below is the execution plan for above query
Decoding above plan:
Index seek outputs id,name
Then compute scalar tries to calculate new rows from existing row values.in this case expr1003 which is our function
Index seek cost is 97%,compute scalar cost is 3% and as you might be aware index seek is not an operator which goes to table to get data.so hopefully this clears your question
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36871217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C# RazorPg - Check if form field is empty and mark as unchanged I have a form field that allows users to change their email address.
If the user doesn't enter anything in the field I want to send "unchanged" to the API. Not blank "" or null.
I've came up with this code:
if (!String.IsNullOrEmpty(Request.Form["Email"].ToString())) // Null or blank check
{
if (Request.Form["Email"].ToString() != user.Email) // Don't update email if it's the same as the existing one
{
user.Email = Request.Form["Email"];
}
else
{
user.Email = "unchanged"; // I don't want to pass null or blank to the API.
}
}
else
{
user.Email = "unchanged";
}
It just looks very messy to me. I have 10 fields on the page so I'd be listing that 10 times in my controller.
Is there a nicer way of doing this?
A: I think you can initialize the Email property in your User model :
public string Email { get; set; } = "unchanged";
you can do it also in the default constructor .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74737844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Execute SQL Task in TSQL I have multiple SQL tasks that execute stored procedures. I intend to call these SQL tasks in some other stored procedure. How do I do this ?
In these SQL tasks, all I have is exec sp statement.All these SQL tasks need to start in a stored procedure only.
A: You can't call individual SSIS tasks, but you can call an SSIS package from a stored procedure. The procedure so is not totally straight-forwards and I won't put instructions here, as there are many sites which do so.
However, if all these tasks do is call an SP, why not just call the sp?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29318695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: ARCore plugin for UE4 - repository doesn't exist? I wanted to download arcore plugin for unreal engine 4 but link provided in main page (link) of project settings for unreal doesn't exist. Who knows why? Or this is because of preview version of ARCore? Thanks :)
A: Did you tried to clone it ?
git clone -b 4.17-arcore-sdk-preview https://github.com/google-ar-unreal/UnrealEngine.git
A: That repository is actually private. So you cannot access/clone it. What you can do is fork the repository on the link you provided and then clone your fork.
Edit
So the guide here at time of writing is incorrect.
You have to follow the steps to become part of the Epic Organisation on github. When you follow these steps you'll see a private repos which you need to fork.
TL;DR: The clone command in the guide doesn't work now because the repository is private. Forking it works after become part of Epic organisation @ Github!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46052130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Return newly allocated pointer or update the object through parameters? I'm actually working on pointers to user-defined objects but for simplicity, I'll demonstrate the situation with integers.
int* f(){
return new int(5);
}
void f2(int* i){
*i = 10;
}
int main(){
int* a;
int* b = new int();
a = f();
f2(b);
std::cout << *a << std::endl; // 5
std::cout << *b << std::endl; // 10
delete b;
delete a;
return 0;
}
Consider that in functions f() and f2() there are some more complex calculations that determine the value of the pointer to be returned(f()) or updated through paramteres(f2()).
Since both of them work, I wonder if there is a reason to choose one over the other?
A: From looking at the toy code, my first thought is just to put the f/f2 code into the actual object's constructor and do away with the free functions entirely. But assuming that isn't an option, it's mostly a matter of style/preference. Here are a few considerations:
The first is easier to read (in my opinion) because it's obvious that the pointer is an output value. When you pass a (nonconst) pointer as a parameter, it's hard to tell at a glance whether it's input, output or both.
Another reason to prefer the first is if you subscribe to the school of thought that says objects should be made immutable whenever possible in order to simplify reasoning about the code and to preclude thread safety problems. If you're attempting that, then the only real choice is for f() to create the object, configure it, and return const Foo* (again, assuming you can't just move the code to the constructor).
A reason to prefer the second is that it allows you to configure objects that were created elsewhere, and the objects can be either dynamic or automatic. Though this can actually be a point against this approach depending on context--sometimes it's best to know that objects of a certain type will always be created and initialized in one spot.
A: If the allocation function f() does the same thing as new, then just call new. You can do whatever initialisation in the object's construction.
As a general rule, try to avoid passing around raw pointers, if possible. However that may not be possible if the object must outlive the function that creates it.
For a simple case, like you have shown, you might do something like this.
void DoStuff(MyObj &obj)
{
// whatever
}
int Func()
{
MyObj o(someVal);
DoStuff(o);
// etc
}
A: f2 is better only because the ownership of the int is crystal clear, and because you can allocate it however you want. That's reason enough to pick it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23549054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: AVSampleBufferDisplayLayer not rendering frames anymore in iOS10 The following setup has been working on all recent iOS versions until iOS10:
I am using AVSampleBufferDisplayLayer to render raw frames from a custom source.
I have a pixel buffer pool set up using CVPixelBufferPoolCreate, and have the kCVPixelBufferIOSurfacePropertiesKey set to @{} as instructed by Apple.
I use CVPixelBufferPoolCreatePixelBuffer to obtain a pixel buffer from the pool and then copy my data to the buffer by using CVPixelBufferLockBaseAddress and CVPixelBufferUnlockBaseAddress.
My raw frames use the NV12 format kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange.
Here is a code snippet showing how I convert the pixel buffer to a CMSampleBufferRef and enqueue it to the display layer:
CMSampleTimingInfo sampleTimeinfo{
CMTimeMake(duration.count(), kOneSecond.count()),
kCMTimeInvalid,
kCMTimeInvalid};
CMFormatDescriptionRef formatDescription = nullptr;
CMVideoFormatDescriptionCreateForImageBuffer(nullptr, pixelBuffer, &formatDescription);
CMSampleBufferRef sampleBuffer = nullptr;
CMSampleBufferCreateForImageBuffer(
nullptr, pixelBuffer, true, nullptr, nullptr, formatDescription, &sampleTimeinfo, &sampleBuffer));
CFArrayRef attachmentsArray = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, YES);
const CFIndex numElementsInArray = CFArrayGetCount(attachmentsArray);
for (CFIndex i = 0; i < numElementsInArray; ++i) {
CFMutableDictionaryRef attachments = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(attachmentsArray, i);
CFDictionarySetValue(attachments, kCMSampleAttachmentKey_DisplayImmediately, kCFBooleanTrue);
}
if ([avfDisplayLayer_ isReadyForMoreMediaData]) {
[avfDisplayLayer_ enqueueSampleBuffer:sampleBuffer];
}
CFRelease(sampleBuffer);
CFRelease(formatDescription);
pixelBuffer is of type CVPixelBufferRef, and avfDisplayLayer_ AVSampleBufferDisplayLayer.
This next snippet shows how I construct the display layer:
avfDisplayLayer_ = [[AVSampleBufferDisplayLayer alloc] init];
avfDisplayLayer_.videoGravity = AVLayerVideoGravityResizeAspectFill;
I am not getting any warning or error messages, the display layer status does not indicate a failure and isReadyForMoreMediaData is returning true.
The problem is that my frames do not show on the screen. I have also set a background color on the display layer, just to make sure the layer is composited correctly (which it is).
Something must have changed in iOS10 with regards to the AVSampleBufferDisplayLayer, but I am unable to figure out what it is.
A: It turns out that with iOS10, the values for CMSampleTimingInfo are apparently parsed more stringently.
The above code was changed to the following to make rendering work correctly once more:
CMSampleTimingInfo sampleTimeinfo{
CMTimeMake(duration.count(), kOneSecond.count()),
kCMTimeZero,
kCMTimeInvalid};
Please note the kCMTimeZero for the presentationTimeStamp field.
@Sterling Archer: You may want to give this a try to see if it addresses your problem as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38364656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Project Euler N2 - Fibonacci algorithm isnt working properly
Each new term in the Fibonacci
sequence is generated by adding the
previous two terms. By starting with 1
and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued
terms in the sequence which do not
exceed four million.
Int64[] Numeros = new Int64[4000005];
Numeros[0] = 1;
Numeros[1] = 2;
Int64 Indice = 2;
Int64 Acumulador = 2;
for (int i = 0; i < 4000000; i++)
{
Numeros[Indice] = Numeros[Indice - 2] + Numeros[Indice - 1];
if (Numeros[Indice] % 2 == 0)
{
if ((Numeros[Indice] + Acumulador) > 4000000)
{
break;
}
else
{
Acumulador += Numeros[Indice];
}
}
Indice++;
}
Console.WriteLine(Acumulador);
Console.ReadLine();
My program isn't functioning as it should be I guess because on Project Euler they say my answer is incorrect. Maybe I'm overlooking something. Any help?
A: This line
if ((Numeros[Indice] + Acumulador) > 4000000)
is checking for the sum being greater than 4MM. You need to check that the term (Numeros[Indice]) is greater than 4MM. So changing that to this...
if (Numeros[Indice] > 4000000)
is probably a good place to start.
A: And also man your test condition in for loop is useless.. i wil never reach the value of 4000000.
simply a
while(1){
//code
}
will also do, no need of i as u never use it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1385781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Nuxt SSR on plesk have to restart every ≈5minutes I have a server.js file who start my nuxt SSR website. First load of the website is a bit slow but it's ok. The time to start and finish the 'npm run start' command take around 8secs then the app is ready for every other users.
Around 5 minutes laters, if nobody come on the website, it's seems to go in standby...
New users will have to wait around 8 seconds, the time the 'npm run start' need to be ready again.
So my question, how can i keep my nuxt.js website awake so it nobody have to wait for the restart?
The server.js file is below.
I use plesk (windows).
const express = require("express");
const {
loadNuxt
} = require("nuxt");
const config = require("./nuxt.config.js");
const app = express();
config.dev = false;
async function start() {
const nuxt = await loadNuxt("start");
app.use(nuxt.render);
app.listen(process.env.PORT || 3000);
}
start();
A: Well, i solved my problem...
It was not a nuxt problem but a plesk/ IIS problem ( idle timeout iisnode exactly).
If you have similar issue, have a look at this page : iisnode making the node process always working
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68807582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mobile Safari. Sudden movement in form inside of iframe I have a form inside of iframe.
I see the sudden movement of the viewport after I turn on the fields of this form by clicking on the arrows on the virtual keyboard IOS
I noticed this problem in mobile Safari(ios8), and only when the form in the frame.
The "Run code" button not visible if open stack-overflow in iOS, therefore link to working example in here.
Code snippets here:
.a { background-color: #f00 }
.b { background-color: #0f0 }
.c { background-color: #00f }
.d { background-color: #ff0 }
.e { background-color: #0ff }
.f { background-color: #f0f }
.g { background-color: #0a0 }
.h { background-color: #a00 }
.z { background-color: #00a }
<input class="a" placeholder="A" type="text"><br>
<input class="b" placeholder="B" type="text"><br>
<input class="c" placeholder="C" type="text"><br>
<input class="d" placeholder="D" type="text"><br>
<input class="e" placeholder="E" type="text"><br>
<input class="f" placeholder="F" type="text"><br>
<input class="g" placeholder="G" type="text"><br>
<input class="h" placeholder="H" type="text"><br>
<input class="z" placeholder="Z" type="text"><br>
IT REPRODUCE ONLY IF THIS CODE OPEN IN IFRAME
To check this:
*
*open the website,
*click on the first field
*go through the fields by pressing on ">" button(on the virtual keyboard of ios).
After some pressing start twitching movement, and positioning of the screen in the wrong places.
Who faced? How to fix this bug with JS/CSS ?
A: This problem haven't solves for long time
discussions.apple.com/message/23671694
A: It is due to the scrollbar that appears on the iframe due to the length of the form in the viewport. If you do not have anything else on the page other than the iframe, turn the body's scroll bar off by using body { overflow: hidden }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30840843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Difference between "Missing Reference Exception" and "Null Reference Exception" in Unity C# In the Unity manual there's an explanation for Null Reference Exceptions but not for Missing Reference Exceptions. Are there any differences?
A: NullReferenceException is thrown when you try to access member of a variable set to null.
MissingReferenceException is thrown when you try to access a GameObject that has been destroyed by some logic in your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53194985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: R Clusplot: How to represent clusters as numbers rather than shapes I want to plot my k means cluster on a 2d plot using clusplot(). However, the points are represented as different shapes on my plot (triangle, square, circle, etc) and it's not easy to see what each shape represents. Is there a way to either generate a legend or change the plot such that it's plotting the cluster assignment rather than a shape?
clusplot(data, myclus$cluster, color=TRUE, shade=TRUE, labels=2, lines=0)
A: get help from ?clusplot.default(), you can get more information,
you just need add a synatx in your command like this :
clusplot(data, myclus$cluster, color=TRUE, shade=TRUE, labels=2, lines=0, plotchar=FALSE),
the points will be represented as same shapes on your plot !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24259723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to loop through a text file with lines consisting of multiple numbers, while counting the numbers The file looks something like:
John Smith
100 90 80 90
50 60 80 99 40 20
But there can be any number of people/grades in the file. I know how to loop through and get the first and last name of the person, but how can I loop through the first line of numbers, add them to their own total, then loop through the second line and add them to another total?
I've not found a way to check for the end of a line in Go, so I don't know how to distinguish the first line of numbers from the second line.
This is what I've tried:
package main
import (
"fmt"
"os"
"log"
"bufio"
//"unicode"
//"container/list"
)
type Student struct {
FirstName string
LastName string
}
func main(){
fmt.Println("What is the name of your file?\n")
var filename string
fmt.Scan(&filename)
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanWords)
//var scanCount int = 0
//var studentCount = 1
//var gradeSum = 0
//var gradeAvg = 0
var students [100]Student
for scanner.Scan() {
students[0].FirstName = scanner.Text()
students[0].LastName = scanner.Text()
fmt.Println(students[0].FirstName)
//count ++
}
}
This is what I have so far. Everything I've tried involving the numbers has not worked so I've removed it.
A: The easiest approach is to loop through the file by lines. Something like this:
package main
import (
"bufio"
"fmt"
"log"
"strconv"
"strings"
)
type Student struct {
FirstName string
LastName string
}
func main() {
fmt.Println("What is the name of your file?\n") var filename string
fmt.Scan(&filename)
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if len(line) == 0 {
// skip blank lines
continue
}
if '0' <= line[0] && line[0] <= '9' {
sum := 0
for _, field := range strings.Fields(line) {
n, err := strconv.Atoi(field)
if err != nil {
log.Fatal(err)
}
sum += n
}
fmt.Println(sum)
} else {
fields := strings.Fields(line)
if len(fields) != 2 {
log.Fatal("don't know how to get first name last name")
}
fmt.Println("First:", fields[0], "Last:", fields[1])
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
See it on the playgrOund.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56843108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: need group by data in mysql in mysql:
Have data in data:
ColA | ColB | Rank
1 2 0
1 3 1
2 1 0
3 1 0
3 2 1
Keeping Col A as key field, need to get data on base of highest rank i.e.,
output:
ColA | ColB | Rank
1 3 1
2 1 0
3 2 1
any ideas..
A: You can do it this way:
SELECT T1.ColA, T2.ColB, T1.Rank
FROM TableName T2 JOIN
(SELECT ColA,MAX(Rank) as Rank
FROM TableName
GROUP BY ColA) T1 ON T1.ColA=T2.ColA AND T1.Rank=T2.Rank
Explanation:
*
*Inner query (T1) selects records with highest rank for each values of ColA.
*Outer query (T2) is used to select ColB with respect to the values of ColA and Rank from T2.
Result:
ColA ColB Rank
--------------------
1 3 1
2 1 0
3 2 1
See result in SQL Fiddle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31109711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: server side includes: can I compute something inside a variable I'm trying to calculate the current index of my slides depending on the page that is shown.
So far I got this:
<!--#set var="page" value="0" -->
<!--#set var="slidesPerPage" value="4" -->
<!--#if expr="$QUERY_STRING = /p=1/" -->
<!--#set var="page" value="1" -->
<!--#elif expr="$QUERY_STRING = /p=2/" -->
<!--#set var="page" value="2" -->
<!--#endif -->
Now I want to "calculate" the current index like this:
<!--#set var="currentIndex" value="${$page * $slidesPerPage + 1}" -->
But this doesn't work.
Is this even possible?
A: after poking around some more and trying things on my own, I found a "solution" that kind of works:
<!--#exec cmd="printf $(($page * $slidesPerPage + 1))" -->
This just prints the output to page and doesn't store it in a variable, but it's enough for me right now.
If someone has a better/nicer solution, please let me know.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22408202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IOS UIWebview alternative - Does it have a webkit browser we can use as a webview different than Safari? I'm looking for an alternative for safari webview I could use like a UIWebview and to communicate with javascript of his webview.
Is it possible? Is Apple tolerant of this?
A: Your question touches on something deeply fundamental in Apple's entire iOS strategy:
At least not yet. Even Google had to rely on embedding the standard (albeit tweaked) UIWebView to implement Chrome for iOS. We can expect Apple to be very reluctant to allow this since allowing other web renderers (possibly even with alternative JS implementations, e.g. V8) kind of breaks Apple's monopoly on control of the development environment for iOS. Allowing an alternative would essentially mean allowing an alternative runtime getting a foothold on the platform.
Although me personally, I think they will have a hard time in the long run to keep this level of purity.
A: Although still inspired by Safari, starting from iOS8 there is WKWebView, a WebKit-based component that provides more powerful, higher-performance APIs than the older UIWebView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22055392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Verifiy if an xls file contains VBA macros without opening it in MS Excel I have a big set of .xls (Excel 97-2003 Workbook) files. A few of them contain VBA macros inside, I would like to find a way to filter them out automatically without opening them one by one in MS Excel.
There is an old post which is similar to my question, I have downloaded the OLE Doc viewer, but cannot open the .zip file, it seems that it is out of date...
Does anyone know if there is any API or tool to check if an .xls file contains VBA macros without opening it in MS Excel? In the first place, I don't bother to know the content of the macros.
PS: for a .xlsx or .xlsm file, we can change their file extension to .zip which contain some .xml files and eventually vbaProject.bin for VBA macros. However, this approach does not work for .xls file, renaming it does not make a valid .zipfile.
A: Here is a simple Python 2.7 solution I've cooked for you:
It depends only on the OleFileIO_PL module which is availble from the project page
The good thing with OleFile parser is that it is not aware of the "excel-specific" contents of the file ; it only knows the higher level "OLE storage". So it is quick in analyzing the file, and there is no risk that a potentially harmful macro would execute.
import OleFileIO_PL
import argparse
if __name__=='__main__':
parser = argparse.ArgumentParser(description='Determine if an Excel 97-2007 file contains macros.', epilog='Will exit successfully (0) only if provided file is a valid excel file containing macros.')
parser.add_argument('filename', help="file name to analyse")
args=parser.parse_args()
# Test if a file is an OLE container:
if (not OleFileIO_PL.isOleFile(args.filename)):
exit("This document is not a valid OLE document.")
# Open an OLE file:
ole = OleFileIO_PL.OleFileIO(args.filename)
# Test if known streams/storages exist:
if (not ole.exists('workbook')):
exit("This document is not a valid Excel 97-2007 document.")
# Test if VBA specific streams exist:
if (not ole.exists('_VBA_PROJECT_CUR')):
exit("This document does not contain VBA macros.")
print("Valid Excel 97-2007 workbook WITH macros")
I tested it on a couple of files with success. Let me know if it's suitable for you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17550648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I prevent Ace Editor from auto-completing as I type? I want the suggestion to show up only when I use Cntrl-Spacebar. Their documentation is a bit lacking.
A: You need to set these following variables :
enableBasicAutocompletion:true
enableLiveAutocompletion:false
for achieving auto-completion only on pressing Cntrl - Spacebar.
Check this snippet for live demo :
var langTools = ace.require("ace/ext/language_tools");
var editor = ace.edit("editor");
editor.setOptions({
enableBasicAutocompletion: true,
enableLiveAutocompletion: false
});
<html>
<body>
<div id="editor" style="height: 500px; width: 800px">Type in a word like "will" below and press ctrl+space to get "auto completion"</div>
<div id="commandline" style="position: absolute; bottom: 10px; height: 20px; width: 800px;"></div>
</body>
<script src="https://rawgithub.com/ajaxorg/ace-builds/master/src/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="https://rawgithub.com/ajaxorg/ace-builds/master/src/ext-language_tools.js" type="text/javascript" charset="utf-8"></script>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31298936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React Filtering Data with Hooks I'm working with a dataset and want to implement a filtering option to only display what is selected (as filters do :) ). Here's the data and my code so far:
// Movies data =
[
{
name: "a",
genre: "comedy",
year: "2019",
},
{
name: "b",
genre: "drama",
year: "2019",
},
{
name: "c",
genre: "suspense",
year: "2020",
},
{
name: "d",
genre: "comedy",
year: "2020",
},
{
name: "e",
genre: "drama",
year: "2021",
},
{
name: "f",
genre: "action",
year: "2021",
},
{
name: "g",
genre: "action",
year: "2022",
},
]
and in my code, I'm have a piece of state for the API response (all data) as well as filtered data per year
import { useEffect, useState, useMemo } from 'react';
const MovieData = () => {
const [movies, setMovies] = useState([]); // all data. This will not change after API call
const [results setResults] = useState([]); // this will change based on selection
const [year, setYear] = useState({
y2019: false,
y2020: false,
y2021: false
});
// making API call
useEffect(() => {
fetch("myapiep")
.then(response => response.json())
.then(data => setMovies(data))
}, []);
// get subsets of data
const {m2019, m2020, m2021} = useMemo(() => {
const m2019 = movies.filter(m => m.year === '2019');
const m2020 = movies.filter(m => m.year === '2020');
const m2021 = movies.filter(m => m.year === '2021');
return {m2019, m2020, m2021}
});
// So far so good. Now this is where things get tricky for me
// I want to, based on the selection, modify my results array
useEffect(() => {
// update results based on movie year selected
if (year.y2019) setResults([...results, ...m2019]);
// HELP: filter out results when year is unselected
// this is not working
else {
const newArr = results.filter((movie) => !m2019.includes(movie));
}
if (year.y2020) setResults([...results, ...m2020]);
else {
const newArr = results.filter((movie) => !m2020.includes(movie));
}
if (year.y2021) setResults([...results, ...m2021]);
else {
const newArr = results.filter((movie) => !m2021.includes(movie));
}
// if none are selected, just return all movies
if (!year.y2019 && !year.y2020 && !year.y2021) {
setResults(movies);
}
}, [year]);
// I'm suppressing the logic to toggle years (y20xx) true/false for simplicity, but can add it if folks judge necessary
return (
<div>
{results.map((movie) => (
<Movie
key={uuidv4()}
name={movie.name}
genre={movie.genre}
year={movie.year}
/>
))}
</div>
)
}
What works: set filter works, for instance, setting the filter to movies made in 2019 returns
[
{
name: "a",
genre: "comedy",
year: "2019",
},
{
name: "b",
genre: "drama",
year: "2019",
},
]
What doesn't: unset the filter.
A: The below code snippet achieves the necessary logic (sans the React Hooks, API, and other items):
const movies = [{
name: "a",
genre: "comedy",
year: "2019",
},
{
name: "b",
genre: "drama",
year: "2019",
},
{
name: "c",
genre: "suspense",
year: "2020",
},
{
name: "d",
genre: "comedy",
year: "2020",
},
{
name: "e",
genre: "drama",
year: "2021",
},
{
name: "f",
genre: "action",
year: "2021",
},
{
name: "g",
genre: "action",
year: "2022",
}
];
const filterMyMovies = (byField = 'year', value = '2020', myMovies = movies) => (
(myMovies || [])
.filter(mov => !byField || !mov[byField] || mov[byField] === value)
);
console.log('movies in year 2020:\n', filterMyMovies());
console.log('movies in year 2019:\n', filterMyMovies('year', '2019'));
console.log('movies in genre drama:\n', filterMyMovies('genre', 'drama'));
console.log('movies with name d:\n', filterMyMovies('name', 'd'));
console.log('movies with NO FILTER:\n', filterMyMovies(null, null));
Explanation
Fairly-straightforward filtering of an array of objects, with only 1 column & 1 value. May be improvised for multi-column & multi-value filtering.
How to use this
The way to use this within React-Hooks is to invoke the 'filterMyMovies' method with the appropriate parameters when the filter-criteria changes. Suppose, the year is set to 'no-filter', then simply make call to the 'filterMyMovies' method with the first & second params as null.
Suppose we need to filter by year and then by genre as well, try something like this:
filterMyMovies('genre', 'comedy', filterMyMovies('year', '2019'));
This will return 2019 comedy movies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70704728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Merge array by value of a value cell (no doubles) I was wondering if it's possible to merge an array by a value of a cell (no doubles) right of the php box.
To clarify this is my current array :
Array
(
[0] => Array
(
[Score] => 90
[Name] => David,
)
[1] => Array
(
[Score] => 90
[Name] => Eric,
)
[2] => Array
(
[Score] => 77
[Name] => Eva,
)
[3] => Array
(
[Score] => 77
[Name] => Gila,
)
)
So we have:
2 persons (David and Eric) that have the same score (90)
2 persons (Eva and Gila) that have the same score (77)
So by the end of the day (in that case) I want to get only 2 rows (merged by score) and the names will be added to the same line that merged by score.
This is what I'm expecting to get :
Array
(
[0] => Array
(
[Score] => 90
[Name] => David,Eric,
)
[1] => Array
(
[Score] => 77
[Name] => Eva,Gila,
)
)
Here is my php code :
<?php
header("Content-Type:text/plain");
$myArray=array();
$myArray[]=array('Score'=>'90','Name'=>'David,');
$myArray[]=array('Score'=>'90','Name'=>'Eric,');
$myArray[]=array('Score'=>'77','Name'=>'Eva,');
$myArray[]=array('Score'=>'77','Name'=>'Gila,');
print_r($myArray);
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27859450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reading the medusa_s3_credentials not work on medusa Describe the bug
Python rises an error during the initialization of medusa container
Environment:
```
apiVersion: v1
kind: Secret
metadata:
name: medusa-bucket-key
type: Opaque
stringData:
medusa_s3_credentials: |-
[default]
aws_access_key_id = xxxxxx
aws_secret_access_key = xxxxxxxx
```
*
*medusa-operator version:
0.12.2
*Helm charts version info
apiVersion: v2
name: k8ssandra
type: application
version: 1.6.0-SNAPSHOT
dependencies:
* name: cass-operator
version: 0.35.2
* name: reaper-operator
version: 0.32.3
* name: medusa-operator
version: 0.32.0
* name: k8ssandra-common
version: 0.28.4
*Kubernetes version information:
v1.23.1
*Kubernetes cluster kind:
EKS
*Operator logs:
MEDUSA_MODE = GRPC sleeping for 0 sec Starting Medusa gRPC service INFO:root:Init service [2022-05-10 12:56:28,368] INFO: Init service DEBUG:root:Loading storage_provider: s3 [2022-05-10 12:56:28,368] DEBUG: Loading storage_provider: s3 DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): 169.254.169.254:80 [2022-05-10 12:56:28,371] DEBUG: Starting new HTTP connection (1): 169.254.169.254:80 DEBUG:urllib3.connectionpool:http://169.254.169.254:80 "PUT /latest/api/token HTTP/1.1" 200 56 [2022-05-10 12:56:28,373] DEBUG: http://169.254.169.254:80 "PUT /latest/api/token HTTP/1.1" 200 56 DEBUG:root:Reading AWS credentials from /etc/medusa-secrets/medusa_s3_credentials [2022-05-10 12:56:28,373] DEBUG: Reading AWS credentials from /etc/medusa-secrets/medusa_s3_credentials Traceback (most recent call last): File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main "**main**", mod_spec) File "/usr/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/cassandra/medusa/service/grpc/server.py", line 297, in <module> server.serve() File "/home/cassandra/medusa/service/grpc/server.py", line 60, in serve medusa_pb2_grpc.add_MedusaServicer_to_server(MedusaService(config), self.grpc_server) File "/home/cassandra/medusa/service/grpc/server.py", line 99, in **init** self.storage = Storage(config=self.config.storage) File "/home/cassandra/medusa/storage/**init**.py", line 72, in **init** self.storage_driver = self._connect_storage() File "/home/cassandra/medusa/storage/**init**.py", line 92, in _connect_storage s3_storage = S3Storage(self._config) File "/home/cassandra/medusa/storage/s3_storage.py", line 40, in **init** super().**init**(config) File "/home/cassandra/medusa/storage/abstract_storage.py", line 39, in **init** self.driver = self.connect_storage() File "/home/cassandra/medusa/storage/s3_storage.py", line 78, in connect_storage profile = aws_config[aws_profile] File "/usr/lib/python3.6/configparser.py", line 959, in **getitem** raise KeyError(key) KeyError: 'default'
Which could be the problem?
thanks
Cristian
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72201170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does a defaulted default constructor depend on whether it is declared inside or outside of class? In the following example, struct A does not have default constructor. So both struct B and struct C inherited from it cannot get compiler-generated default constructor:
struct A {
A(int) {}
};
struct B : A {
B() = default; //#1
};
struct C : A {
C();
};
C::C() = default; //#2
#1. In struct B, defaulted default constructor is declared inside the class, and all compilers accept it, with only Clang showing a warning saying that explicitly defaulted default constructor is implicitly deleted [-Wdefaulted-function-deleted]
#2. But defaulted default constructor declared outside of struct C generates a compiler error. Demo: https://gcc.godbolt.org/z/3EGc4rTqE
Why does it matter where the constructor is defaulted: inside or outside the class?
A: Note that if you actually try and instantiate B then you'll also get the error that B::B() is deleted: https://gcc.godbolt.org/z/jdKzv7zvd
The reason for the difference is probably that when you declare the C constructor, the users of C (assuming the definition is in another translation unit) have no way of knowing that the constructor is in fact deleted. At best this would lead to some confusing linker error, at worst it'd just crash at runtime. In the case of B all users of B will immediately be able to tell that the default constructor is deleted so it does no harm (even if it makes no sense as warned by clang) to declare it as defaulted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71969651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: sql statements and pdo There is a pdo wrapper class that has turns off emulation or prepared statements using:
setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
I am seeing where some of the sql statements are written using standard non parameterized methods such as seen below:
select * from table where name = '".$name."'.
Are these kind of statements protected against sql injections even though a pdo wrapper is employed?
A: Your idea of protecting from injections is quite wrong.
It is not PDO just by it's presence (which can be interfered by some wrapper) protects your queries, but prepared statements.
As long as you are using prepared statements, your queries are safe, no matter if it's PDO or wrapper, or even poor old mysql ext.
But if you are putting your data in the query directly, like in your example, there is no protection at all
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16748364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's a good use case for the arg in a vue.js directive? Can someone help me understand a good use case for a Vue.js directive's arg and modifiers? Since we can already pass data as an object in the value of the directive I'm having a hard time seeing the value of arg and modifiers.
For example I could do the following:
<div v-myDirective:foo.a.b="some value"> ...
But I could just as easily accomplish the same thing like this:
<div v-myDirective="{arg: 'foo', a:true, b:true, value: 'some value'}"> ...
So what's the point of the arg? I realize that the first use case is less verbose, but it seems like a very specific use case and I don't see what the point is of all the extra options making the directives specification that much more complex.
Is there an obvious use case that I'm missing?
A: The use case for both are the same. But the first one is just a short-hand code:
<div v-myDirective:foo.a.b="some value">
But remember foo.a.b has a and b modifier and the directives returns true for them when it presents inside the directive.
When you just use foo.a, then the b modifier is not present and it returns false.
if (binding.modifiers.a) {
// do something a
}
if (binding.modifiers.b) {
// do something b
}
But in an object syntax, you can do more thing rather than just a true value check.
<div v-myDirective="{arg: 'foo', a:'some string', b:100, value: 'some value'}">
This way, you can check if a has 'some string' and b has 100 in your directive function.
if (binding.value.a == 'some string') {
// do something a
}
if (binding.value.b == 100) {
// do something b
}
Most of us prefer short-hand syntax and I do as well. So, whenever you need to check if modifier is present or not, use short-hand syntax. And use object syntax when you need more complex check than just true value check.
A: Programming usability/convenience, that's all.
The reason one would prefer v-directive:foo="bar" instead of v-directive="{foo: bar}" is the same people prefer :prop="val" instead of v-bind:prop="val". Convenience.
Same with v-on:click and @click.
Using the declarative way (instead of the "value" way) can be much more readable and make much more sense for the end user (the programmer). The declarative way separates much better what is "metadata" and what is "payload" for the directive.
If the end user is a designer (not used to JavaScript's object notation), I'd argue this makes an even greater difference.
The "value" notation becomes much more error prone the more you have options:
v-directive="{a: 1, b: '123', c: message, d: 'false'}"
Will people really remember to quote '123' correctly so it means a string? Will they do it while not quoting a's value? Will they always remember they should quote one but not the other? Is it clear to the user that message there will be the value of this.message and not the string "message"? If d is a boolean property, how bad is it to quote it (by accident)?
Lastly, another important point that may have directed Vue's designers is that they try to make available to custom directives the very behaviors available on native directives. And all those modifiers/args exist in native directives (e.g. v-bind:address.sync="myAddressProp").
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49713419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Managing bower file with Angular files Ok, I think that this is an easy question. I am new to Bower, and I am trying to keep my bower.json file in sync with the multiple libraries that Angular now provides. I am using angular-resource, angular-cookies, angular-sanitize, angular-animate, and then the main angular library. In my bower.json file I have all of these listed as dependencies, but I am having to update 1.2.4 to 1.2.5 for each of these items.
I am sure there is an easier way, and as I understand it I can do "~1.2" for each item and get all of the 1.2.x updates when doing a bower install. But if I want to get specific versions, do I have to update all of the strings to 1.2.5 or can I have a variable somewhere in the bower.json that I can reference, and just update that one variable?
A: You can't have variables in your bower.json file, so its not supported out of the box.
See: https://groups.google.com/forum/#!msg/twitter-bower/OvMPG6KS3OM/eo6L2VadxI8J
As a workaround if you have sed you can run something like:
# update 1.2.5 -> 1.2.7 in test.json
sed -i '' 's/1.2.5/1.2.7/' test.json
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20983264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't get the right data I send My code is :
String str= (char)255 + (char)255 +"1" ;
byte[] sendbuf = str.getBytes();
outputPacket = new DatagramPacket(sendbuf,sendbuf.length,remoteIP,2280);
logSocket.send(outputPacket);
the result I get is "0x35 0x31 0x30 0x31"
but what I want is :0xff 0xff 0x31
How to do this?
A: Your str is adding the two chars first, so it's basically this:
String str = (char)(255 + 255) + "1"; // 5101
What you want is (something like) this:
String str = (char) 255 + "" + (char) 255 + "1";
Or, using String.format:
String str = String.format("%c%c%d", 255, 255, 1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13264613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: POST :create rspec controller testing error, wrong number of arguments 2 for 0 I'm trying to test my Post_comments#create action in the controller specs with rspec and I keep getting this error message:
Failure/Error: post :create, :post_id => post.to_param, :post_comment => attributes_for(:post_comment, comment: "New")
ArgumentError:
wrong number of arguments (2 for 0)
# ./spec/controllers/post_comments_controller_spec.rb:95:in `block (4 levels) in <top (required)>'
My Post Comments controller:
class PostCommentsController < ApplicationController
before_action :find_todo_list
def index
@post_comment = @post.post_comments.all
end
def show
@post_comment = @post.post_comments.find(params[:id])
end
def new
@post_comment = @post.post_comments.new
end
def edit
@post_comment = @post.post_comments.find(params[:id])
end
def create
@post_comment = @post.post_comments.new(post_comment_params)
if
@post_comment.save
redirect_to post_post_comments_path
flash[:success] = "Comment added successfully!"
else
flash.now[:error] = "Comment could not be saved"
render 'new'
end
end
def update
@post_comment = @post.post_comments.find(params[:id])
if
@post_comment.update(post_comment_params)
redirect_to post_post_comment_path
flash[:success] = "Comment successfully updated"
else
flash.now[:error] = "Comment could not be updated"
render 'edit'
end
end
def destroy
@post_comment = @post.post_comments.find(params[:id])
@post_comment.destroy
redirect_to post_post_comments_path
flash[:success] = "The comment was successfully deleted"
end
end
private
def find_todo_list
@post = Post.find_by(params[:post_id])
end
def post_comment_params
params.require(:post_comment).permit(:comment)
end
My controller spec that keeps failing:
describe "POST #create" do
context "flash messages" do
let(:post) {create(:post)}
it "sets flash success" do
post :create, :post_id => post.to_param, :post_comment => attributes_for(:post_comment, comment: "New")
expect(flash[:success]).to eq("Comment added successfully!")
end
end
end
I'm using factory girl so here is my factory for post comments, which has a belongs_to association with a post...duh
factory :post_comment do
comment "Post comment"
post
end
Any help would really help me out, thanks!
A: let(:post) {create(:post)}
# ...
post :create
let is a fancy way of defining a method on the current RSpec example. post is now a method that accepts 0 arguments, thus the message wrong number of arguments (2 for 0).
Try naming your Post object something else.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37263130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Create a Table-like Structure in Java GUI I would like to create a table-like structure so that I can display information easily. I would like it to look like this:
What is the best layout manager to achieve this? I am currently using GridBagLayout, but I am having trouble getting the Title to span the whole top row and for the ColumnTitle1 and ColumnTitle2 to span the second row half each. Could someone please provide some code to help.
A: I think GridBagLayout is the best to achieve this design. Here is a full working example for you that will look like this:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.gridx=0;
gc.gridy=0;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weightx = 1.0;
gc.gridwidth = 2;
JLabel title = new JLabel("TITLE");
title.setBackground(Color.RED);
title.setOpaque(true);
title.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(title, gc);
gc.gridx=0;
gc.gridy=1;
gc.weightx = 0.5;
gc.gridwidth = 1;
JLabel col1 = new JLabel("COLUMN 1 TITLE");
col1.setBackground(Color.YELLOW);
col1.setOpaque(true);
col1.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(col1, gc);
gc.gridx=1;
gc.gridy=1;
JLabel col2 = new JLabel("COLUMN 2 TITLE");
col2.setBackground(Color.GREEN);
col2.setOpaque(true);
col2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(col2, gc);
gc.fill = GridBagConstraints.BOTH;
gc.gridx=0;
gc.gridy=2;
gc.weighty = 1.0;
gc.gridwidth = 1;
JLabel info1 = new JLabel("Info 1 Text");
info1.setBackground(Color.CYAN);
info1.setOpaque(true);
info1.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(info1, gc);
gc.gridx=1;
gc.gridy=2;
JLabel info2 = new JLabel("Info 2 Text");
info2.setBackground(Color.MAGENTA);
info2.setOpaque(true);
info2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(info2, gc);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35068296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Finding the certificate thumbprint for a particular website on Chrome through Selenium WebDriver? Let's say I open a particular website on Chrome through Selenium - www.google.com. I can view the certificate thumbprint for this website manually.
But is it possible to get hold of this thumbprint thru any webdriver apis? Or programatically how would I go about getting the certificate thumbprint for a website?
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38243634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS not applied in bootstrap modal on my Rails app Following is my bootstrap setup:
Rails ver: 4.1.1
Gemfile:
gem 'bootstrap-sass', '~> 3.2.0'
gem 'bootstrap3-datetimepicker-rails', '~> 3.0.2'
gem 'bootstrap-validator-rails'
Application.css.scss (first 3 imports, no require directives)
@import "bootstrap-sprockets";
@import "bootstrap";
@import "bootstrap-datetimepicker";
Application.js
//= require jquery
//= require jquery.flexslider
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery-ui/autocomplete
//= require ./plugins/bootstrap-select.js
//= require ./plugins/jquery.form.js
//= require bootstrap-datetimepicker
//= require bootstrapValidator.min
//= require bootstrap-sprockets
//= require_tree .
Modal HTML:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">x</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel"> Title </h4>
</div>
<div class="modal-body">
<%= render partial: 'modal_body' %>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Mark</button>
</div>
</div>
</div>
</div>
I am able to render the modal but the modal takes up the entire width of the window.
A: Instead of Application.css.scss,
rename you file to Application.scss.
mv Application.css.scss Application.scss
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34967523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regex for openfootball Exists string
(1) Thu Jun/12 17:00 Brazil 3-1 (1-1) Croatia @ Arena de São Paulo, São Paulo (UTC-3)
I use regex:
/^\((\d+)\)\s(.*?)\s{2,}(.+?)\ (\d+)-(\d+)\ \(.*?\)\ (.+?)\s{2,}.*UTC-(\d+)/
How to modify regex, that passing also matches without first time result:
(1) Thu Jun/12 17:00 Brazil 3-1 Croatia @ Arena de São Paulo, São Paulo (UTC-3)
?
Upd:
$1=1
$2=Thu Jun/12 17:00
$3=Brazil
$4=3
$5=1
$6=Croatia
$7=3
A: Just make the first time result optional:
/^\((\d+)\)\s(.*?)\s{2,}(.+?) (\d+)-(\d+) (?:\(.*?\) )?(.+?)\s{2,}.*UTC-(\d+)/
# ^^^________^^
A: A set of progressive matches would probably turn out more legible / maintainable, but at least by adding the /x modifier we can allow for insignificant whitespace, which permits formatting of the regex to make it easier to read and understand.
Here's one way to do it:
my @targets = (
q{(1) Thu Jun/12 17:00 Brazil 3-1 (1-1) Croatia @ Arena de São Paulo, São Paulo (UTC-3)},
q{(1) Thu Jun/12 17:00 Brazil 3-1 Croatia @ Arena de São Paulo, São Paulo (UTC-3)}
);
foreach my $target ( @targets ) {
print "($1)($2)($3)($4)($5)($6)($7)\n"
if $target =~ m/
^\(([^)]+)\)\s+ # 1
(\w{3}\s\w{3}\/\d{1,2}\s\d{2}:\d{2})\s+ # Date and Time
(\D+?)\s+ # Team A
(\d+)-(\d+)\s+ # Score A - B
(?:\([^)]+\)\s+)? # Optional
(.+?)\s+@ # Team B
.+\(UTC-(\d+)\)$ # TZ
/x;
}
This produces the following output:
(1)(Thu Jun/12 17:00)(Brazil)(3)(1)(Croatia)(3)
(1)(Thu Jun/12 17:00)(Brazil)(3)(1)(Croatia)(3)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24279633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Telling IPython interact widget to ignore self argument in OOP I'm trying to use the IPython interact widget for a particular method in one of my classes. I would like it to ignore the self & colour arguments, and only adjust the i argument, but it insists that self is a bonafide argument too.
A similar question was asked here, but neither method (using fixed on self or pre-loading self into the method with partial) is appropriate in this case.
from ipywidgets.widgets import interact,fixed
import matplotlib.pyplot as plt
class Profile():
'''self.stages is a list of lists'''
@interact(i=(0,5,1),colour=fixed(DEFAULT_COLOR))
def plot_stages(self, i, colour):
plt.plot(self.stages[i], color=colour)
This returns an error:
ValueError: cannot find widget or abbreviation for argument: 'self'
So how does one tell interact to ignore the self argument?
A: Define an “outer” function that takes the self and the constant arguments. Inside that define an “inner” function that takes only the interactive arguments as parameters and can access self and the constant arguments from the outer scope.
from ipywidgets.widgets import interact
import matplotlib.pyplot as plt
DEFAULT_COLOR = 'r'
class Profile():
'''self.stages is a list of lists'''
stages = [[-1, 1, -1], [1, 2, 4], [1, 10, 100], [0, 1, 0], [1, 1, 1]]
def plot_stages(self, colour):
def _plot_stages(i):
plt.plot(self.stages[i], color=colour)
interact(_plot_stages, i=(0, 4, 1))
p = Profile()
p.plot_stages(DEFAULT_COLOR)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56567251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Unity C# Null Reference Exception I am trying to get data from an int variable in Unity using C# code.
Below is the C# code I am using to get the int.
using UnityEngine;
using System.Collections;
public class endGameMessage : MonoBehaviour {
public static int score2;
void Start () {
GameObject thePlayer = GameObject.FindWithTag("Player");
gameScript game = thePlayer.GetComponent<gameScript>();
score2 = game.score;
}
// Update is called once per frame
void Update () {
Debug.Log (score2);
}
}
Below is the code from the other script I am trying to pull the data from.
using UnityEngine;
using System.Collections;
public class gameScript : MonoBehaviour {
//score
public int score = 0;
void OnTriggerEnter(Collider other) {
if(other.gameObject.tag =="hammer"){
GameObject.FindGameObjectWithTag("pickUpMessage").guiText.text = ("Picked Up A Hammer");
Destroy(other.gameObject);
Debug.Log("collision detected hammer");
audio.PlayOneShot(gotHit);
score = score+10;
}
}
}
I can get the the int value to come across to the other script but its always 0 even if the int was meant to be 10.
My question is how would i keep the value across the scripts? Any help is appreciated.
A: try this
public static int score2
{
get
{
return GameObject.FindWithTag("Player").GetComponent<gameScript>().score;
}
}
A: You have a lot of possibilities.
The first one is to set your Score as a static argument for you gameScript.
*
*So you can access it anywhere just like that :
int myScore = gameScript.Score ;
*And the declaration should be :
public static int score;
The second possibilities is far better if you want to save a lot of differents values from differents script.
In this case, you need to define a gameContext singleton.
If you don't know what is this, you should take a look at singleton in C# :
[https://msdn.microsoft.com/en-us/library/ff650316.aspx]
Singleton will allow you to have a single instance of your gameContext.
In your case, your singleton will have a Score attribute.
And you will be able to get the value from any scene and any scripts.
This is the best way so far.
A: score2 is read once at start and then never again. int is an integral type in C# and thus passed by value i.e. it receives a copy. There several ways to solve this problem.
The easiest solution is to access the gameScript.score directly - it provides read/write access to everyone anyway. To encapsulate it you may choose to define a property.
A better way could be to define a new class GameStatus which holds all relevant things. This can be implemented as singleton for example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14549465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SceneKit get node position after rotation For example I have two SCNNodes with SCNBox geometry positioned one after another increasing x position property:
SCNBox(width: 0, height: 0, length: 0.02, chamferRadius: 0)
Then I want to rotate the first one using rotation property with SCNVector4, but when rotation happens I want my second node to follow the first one and change its position according rotation of the first one.
I found this solution on the web and tried to print node's position, worldPosition and presentation.position but they are all the same value.
Can someone help me to find out how can I obtain node's position after rotation?
A: The position of a node does not change when it rotates. Maybe you could look at connecting the nodes with a physics mechanism such as SCNPhysicsHingeJoint? I found this example which could be useful for your scenario:
http://lepetit-prince.net/ios/?p=3540
Another example:
http://appleengine.hatenablog.com/entry/2017/08/17/154852
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50466931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using npm mysql with angular / electron I am trying to make desktop application using electron, ionic4 --type-angular and npm mysql.
I have established the connection with mysql but with normal html, js, css using the below code in my index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>window.$ = window.jQuery = require('./jquery-2.1.4.js');</script>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<h1>Electron MySQL Example</h1>
<div id="resultDiv"></div>
<!-- All of the Node.js APIs are available in this renderer process. -->
We are using Node.js <script>document.write(process.versions.node)</script>,
Chromium <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
<script>
// You can also require other files to run in this process
require('./renderer.js')
</script>
<script>
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'electron_db'
});
connection.connect();
$sql = 'SELECT `emp_id`,`emp_name` FROM `employee`';
connection.query($sql, function (error, results, fields) {
if (error) throw error;
console.log(results);
$('#resultDiv').text(results[0].emp_name);
});
connection.end();
</script>
</body>
</html>
Now I have made electron app with ionic4. I have installed mysql and jquery using npm install mysql, npm install jquery in my project. I need to know how do I use the above js code in my home.page.ts
Below is my home.page.ts which is giving error
ERROR in src/app/home/home.page.ts(4,18): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Trynpm i @types/node.
declare var $: any;
import { Component } from '@angular/core';
var mysql = require('mysql');
var connection;
var $sql;
connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'electron_db'
});
connection.connect();
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(){
$sql = 'SELECT `emp_id`,`emp_name` FROM `employee`';
connection.query($sql, function (error, results, fields) {
if (error) throw error;
console.log(results);
$('#resultDiv').text(results[0].emp_name);
});
connection.end();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54246086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Passing a predicate to QWaitCondition? I'm writing some threads in Qt and I can't figure out how to pass a predicate to my condition variable to protect against spurious wake up.
Working solution in C++:
std::mutex(mu);
std::condition_variable cond;
std::unique_lock<mutex> alpha_lock(mu);
cond.wait(alpha_lock, [](){ return //some condition;});
alpha_lock.unlock();
//Continue to do stuff...
Qt equivalent:
QMutex mu;
QWaitCondition cond;
QMutexLocker alpha_lock&(mu);
cond.wait(&mu, [](){return //some condition;})
Error:
"no matching member function for call to wait"
Any ideas on how to use a predicate in this Qt code?
A: As the compiler and @xaxxon have already pointed out, there is no such wait() overload in QWaitCondition.
If you want to check a condition before going on you can do it like this
while (!condition()) {
cond.wait(mutex);
}
You can of course put that into a helper function that takes a QWaitCondition, QMutex and std::function if you need this in more places. Or derive from QWaitCondition adding the overload doing the loop above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40445629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to print values of all elements of java.util.Date type Array in R language I am new in R language and i have a problem :
In java i have a method like this
public Date[] getAllDates(String fromDate, String toDate){
ArrayList<Date> dates= new ArrayList<Date>();
-------
Generating dates from fromDate to toDate here and setting into above
arraylist.
------
return dates.toArray(dates.size());
}
Now in R when i am calling this method then it is returning this array
dates= c(classInstance$getAllDates(fromDate,toDate));
Now i am not able to show the dates values present in dates array it is showing as object only.
Case : 1
and if i use print(str(dates[1])) then it displays
List of 1
$ :Formal class 'jrectRef' [package "rJava"] with 4 slots
.. ..@ dimension: int 10
.. ..@ jsig : chr "[Ljava/util/Date;"
.. ..@ jobj :<externalptr>
.. ..@ jclass : chr "[Ljava/util/Date;"
NULL
when i use : print(typeof(dates[1]))
it is showing
"S4"
Case : 2
when i use : print(typeof(dates[1]))
it is showing
"list"
i tried everything but i am not able to show the values from this array.
please help me.Thank you
A: Finally after a lot of search on google(approx 3 days continuously) about R programming and concept and techniques to resolve my above issue, now i am able to give my answer itself.
dates= c(classInstance$getAllDates(fromDate,toDate));
from here
Case : 1 Solution
for(i in 1 : dates$length) {
#Fetching one by one date object using for each loop in R
index = .jevalArray(dates)[[i]]
# Holding an individual array into variable
print(index$toString())
# Now printing using Java toString() method only.
}
Note** : but for "list" type this solution also got stuck. It worked for me when typeof was "S4"
Case : 2 Solution
I found a working solution for this as well
arraysObject = .jnew("java/util/Arrays")
#Just taken a reference of an object of java Arrays classes
for (i in 1:length(indexes[[1]])){
print(arraysObject$toString(indexes[[1]][i]))
#calling Arrays.toString() method of java into R programming
}
OR
arraysObject = .jnew("java/util/Arrays")
print(arraysObject$toString(indexes[[1]]))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37475157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I search for a certain method in android profiler? I get thousands of methods and I can´t locate the one I was looking for.
There is a "find" text field above, which seems to don´t have any effect
A: you are right, the find wont work..
But if you know the method name and package name you can sort the list and search for your method..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21877619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: null values of @id field not fetched in list hibernate @Entity
@Table(name = "CONFIG")
public class ConfigBean implements java.io.Serializable {
private String FEATURE;
private String SUB_FEATURE;
private String STATUS;
private String COMMENTS;
private String HIERARCHY;
private String SEARCHCRITERIA;
private String RULE;
private String CHECK1;
private String CHECK2;
private String CHECK3;
private String CHECK4;
private String CHECK5;
public ConfigBean() {
}
public ConfigBean(String FEATURE, String SUB_FEATURE, String STATUS,
String COMMENTS, String HIERARCHY, String SEARCHCRITERIA,
String RULE, String CHECK1, String CHECK2, String CHECK3,
String CHECK4, String CHECK5) {
this.FEATURE = FEATURE;
this.SUB_FEATURE = SUB_FEATURE;
this.STATUS = STATUS;
this.COMMENTS = COMMENTS;
this.HIERARCHY = HIERARCHY;
this.SEARCHCRITERIA = SEARCHCRITERIA;
this.RULE = RULE;
this.CHECK1 = CHECK1;
this.CHECK2 = CHECK2;
this.CHECK3 = CHECK3;
this.CHECK4 = CHECK4;
this.CHECK5 = CHECK5;
}
@Id
@Column(name = "FEATURE" , nullable = true)
public String getFEATURE() {
return FEATURE;
}
public void setFEATURE(String fEATURE) {
FEATURE = fEATURE;
}
@Column(name = "SUB_FEATURE")
public String getSUB_FEATURE() {
return SUB_FEATURE;
}
public void setSUB_FEATURE(String sUB_FEATURE) {
SUB_FEATURE = sUB_FEATURE;
}
@Column(name = "STATUS")
public String getSTATUS() {
return STATUS;
}
public void setSTATUS(String sTATUS) {
STATUS = sTATUS;
}
@Column(name = "COMMENTS")
public String getCOMMENTS() {
return COMMENTS;
}
public void setCOMMENTS(String cOMMENTS) {
COMMENTS = cOMMENTS;
}
@Column(name = "HIERARCHY")
public String getHIERARCHY() {
return HIERARCHY;
}
public void setHIERARCHY(String hIERARCHY) {
HIERARCHY = hIERARCHY;
}
@Column(name = "SEARCHCRITERIA")
public String getSEARCHCRITERIA() {
return SEARCHCRITERIA;
}
public void setSEARCHCRITERIA(String sEARCHCRITERIA) {
SEARCHCRITERIA = sEARCHCRITERIA;
}
@Column(name = "RULE")
public String getRULE() {
return RULE;
}
public void setRULE(String rULE) {
RULE = rULE;
}
@Column(name = "CHECK1")
public String getCHECK1() {
return CHECK1;
}
public void setCHECK1(String cHECK1) {
CHECK1 = cHECK1;
}
@Column(name = "CHECK2")
public String getCHECK2() {
return CHECK2;
}
public void setCHECK2(String cHECK2) {
CHECK2 = cHECK2;
}
@Column(name = "CHECK3")
public String getCHECK3() {
return CHECK3;
}
public void setCHECK3(String cHECK3) {
CHECK3 = cHECK3;
}
@Column(name = "CHECK4")
public String getCHECK4() {
return CHECK4;
}
public void setCHECK4(String cHECK4) {
CHECK4 = cHECK4;
}
@Column(name = "CHECK5")
public String getCHECK5() {
return CHECK5;
}
public void setCHECK5(String cHECK5) {
CHECK5 = cHECK5;
}
}
Above is my mapping class.
Feature column has many null values in database.
So I am getting
I want all the values to be fetched [0..9] and not [0,1,5,9]
below is fetching code
public List<ConfigBean> fetchSearchCriteria() throws SQLException {
criteriaDAO = new ConfigSearchCriteriaDAO();
// get the checks to perform on the config file.
List<ConfigBean> searchCriteriaList = criteriaDAO
.selectRecordsTable("from ConfigBean");
return searchCriteriaList;
}
public List selectRecordsTable(String queryString) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createQuery(queryString);
query.setMaxResults(10);
List configList = query.list();
session.getTransaction().commit();
return configList;
}
The list is fetched from database is ignoring @ID FEATURE values as some of them are null.
Is it necessary that @id column should be not null?
or is there some other way to get null valued rows included as well ?
A: You are fetching data from underlying CONFIG table here and annotate FEATURE with @Id; i.e. asking hiberanate to fetch only unique records.
You can not distinguish null as a 'unique' value resulting your list only fetching valid unique values.
Just for checking--
*
*Try having FEATURE column only 2 values repeating at multiple positions ; you will get only 2 distinct values in your list.
*Try to insert values into FEATURE through java, use one of the value as null; you will get unique constraint voilation exception.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31061839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you center the MKMapView map visually when a user location is known or changes? I have read and followed the instructions on How do I zoom an MKMapView to the users current location without CLLocationManager?
However, while I do get the current user location, I am unable to actually make the map visually center there.
For example, in the viewDidLoad function, how can I cause the map to center visually around the users known location? I have pasted the code from CurrentLocation below (See the XXX comment in viewDidLoad
#import "MapViewController.h"
#import "PlacemarkViewController.h"
@implementation MapViewController
@synthesize mapView, reverseGeocoder, getAddressButton;
- (void)viewDidLoad
{
[super viewDidLoad];
// XXX HERE: How can I cause self.mapView to actually recenter itself at self.mapview.userLocation.location?
mapView.showsUserLocation = YES;
}
- (void)viewDidUnload
{
self.mapView = nil;
self.getAddressButton = nil;
}
- (void)dealloc
{
[reverseGeocoder release];
[mapView release];
[getAddressButton release];
[super dealloc];
}
- (IBAction)reverseGeocodeCurrentLocation
{
self.reverseGeocoder =
[[[MKReverseGeocoder alloc] initWithCoordinate:mapView.userLocation.location.coordinate] autorelease];
reverseGeocoder.delegate = self;
[reverseGeocoder start];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSString *errorMessage = [error localizedDescription];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Cannot obtain address."
message:errorMessage
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
PlacemarkViewController *placemarkViewController =
[[PlacemarkViewController alloc] initWithNibName:@"PlacemarkViewController" bundle:nil];
placemarkViewController.placemark = placemark;
[self presentModalViewController:placemarkViewController animated:YES];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
// we have received our current location, so enable the "Get Current Address" button
[getAddressButton setEnabled:YES];
}
@end
A: It looks like you can simply use the centerCoordinate property of the MKMapView class - the docs say:
Changing the value in this property centers the map on the new coordinate without changing the current zoom level. It also updates the values in the region property to reflect the new center coordinate and the new span values needed to maintain the current zoom level.
So basically, you just do:
self.mapView.centerCoordinate = self.mapView.userLocation.location.coordinate;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4915033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: FormData constructor isn't getting any values from the form I must be making a very stupid mistake, but I can't figure out why this isn't working:
<html>
<head>
<title>Form test</title>
</head>
<body>
<h1>Test a form</h1>
<form id="myform" name="myform" action="/server">
<input type="text" name="username" value="johndoe">
<input type="number" name="id" value="123456">
<input type="submit" onclick="return sendForm(this.form);">
</form>
<script>
function sendForm(form) {
var formData = new FormData(form);
console.log("as json: " + JSON.stringify(formData));
return false; // Prevent page from submitting.
}
</script>
</body>
</html>
According to the documentation of FormData, if you give it a form object in the constructor, it will populate itself with the form values, but when I do this, I get an empty result in the console. Any ideas what I'm doing wrong in this? I tried in both Chrome and Firefox and got the same results. This is based on the example from html5rocks XHR2.
Thank you
A: You are doing nothing wrong here. You need to use the methods like .entires(), .get(), .getAll() and so on to access the values, or keys. I had the same issue some time ago, and if you need to convert your FormData to JSON, you need to write some code, which does this for you, JSON.stringify()
does not work in this case.
Have a look here
Or, if you need a jQuery solution: SO
A: I figured out what I need to do. It's simple:
console.log("Here it is: " + JSON.stringify($('#myform').serializeArray()[0]));
Gives the expected result: a JSON string containing name / value pairs from the form. I can then send this using XMLHttpRequest. No reason to use a FormData object in this case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42062605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Designer duplicating datasource in DataGridViewComboBoxColumn I have a custom control that inherits from a DataGridView. It has pre-defined columns.
One of the columns is a ComboBox column. I want it so that users can select an hour of the day, so it binds to a datasource that is an array of integers, from 0 to 24.
Everything is OK at design time (when I drop the control onto a form). The problem I get is that run-time, the designer tries to add the datasource twice, and then causes an error.
Here is the salient code:
//Constructor for teh usercontrol
public OutageGrid()
{
base.AutoGenerateColumns = false; //Hidden from intellisense, but needed to prevent columns being duplicated by the designer.
InitializeComponent();
}
private int[] Hours = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
/// <summary>
/// This is called after the usercontrol is added to another container (form). This is used to add the columns to the
/// control, to avoid the issue where the columns get duplicated at runtime.
/// </summary>
protected override void InitLayout()
{
//base.InitLayout();
SetColumns();
}
private void SetColumns()
{
base.Columns.Clear();
base.Columns.Add("ID", "ID");
base.Columns.Add("IAPCode", "IAPCode");
base.Columns.Add("Venture", "Venture");
DataGridViewComboBoxColumn startHourColumn = new DataGridViewComboBoxColumn();
startHourColumn.HeaderText = "Start Hour";
startHourColumn.DataSource = Hours;
startHourColumn.ValueType = typeof(int);
base.Columns.Add(startHourColumn);
}
You can see that I generate the columns in the BeginInit() event, as I was finding that if I try to do it directly from the constructor, the columns were getting duplicated at runtime.
When I try to actually compile and run the program, the designer creates this code (this is from my Form.Designer):
//
// dataGridViewComboBoxColumn16
//
this.dataGridViewComboBoxColumn16.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
this.dataGridViewComboBoxColumn16.DataSource = new int[] {
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24};
dataGridViewCellStyle8.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.dataGridViewComboBoxColumn16.DefaultCellStyle = dataGridViewCellStyle8;
this.dataGridViewComboBoxColumn16.HeaderText = "Start Hour";
this.dataGridViewComboBoxColumn16.Items.AddRange(new object[] {
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24});
this.dataGridViewComboBoxColumn16.Name = "dataGridViewComboBoxColumn16";
this.dataGridViewComboBoxColumn16.Width = 61;
You can see that it has set the DataSource to be the array of hours, but then it then tries to add a range of values. This causes an exception:
Additional information: Items collection cannot be modified when the DataSource property is set.
I dutifully go into the designer and delete this code. Re-run and it compiles, until I make a change to my control or project.
Anyone know what's going on, and how to avoid this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38819159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get the opposite of a join? I am trying to get the rows that don't exist in one table where one table called schedules (match_week, player_home_id, player_away_id) and the other table called match (match_week, Winner_id, Defeated_id) are joined. The players look at their schedule and play a match. I am trying to get a list of the scheduled matches that do not exist in the match table. The IDs in the match table can be in either column Winner_id or Defeated_id.
I have reviewed a number of Stack Exchange examples, but most use "IS NULL" and I don't have null values. I have used a Join that does give the output of the matches played. I would like the matches that have not been played.
CSV - wp_schedule_test
+----+------------+--------------+--------------+-----------------+-----------------+
| ID | match_week | home_player1 | away_player1 | player1_home_id | player1_away_id |
+----+------------+--------------+--------------+-----------------+-----------------+
| 1 | WEEK 1 | James Rives | Dale Hemme | 164 | 169 |
| 2 | WEEK 1 | John Head | David Foster | 81 | 175 |
| 3 | WEEK 1 | John Dalton | Eric Simmons | 82 | 23 |
| 4 | WEEK 2 | John Head | James Rives | 81 | 164 |
| 5 | WEEK 2 | Dale Hemme | John Dalton | 169 | 82 |
| 6 | WEEK 2 | David Foster | Eric Simmons | 175 | 23 |
| 7 | WEEK 3 | John Dalton | James Rives | 82 | 164 |
| 8 | WEEK 3 | John Head | Eric Simmons | 81 | 23 |
| 9 | WEEK 3 | Dale Hemme | David Foster | 169 | 175 |
| 10 | WEEK 4 | Eric Simmons | James Rives | 23 | 164 |
| 11 | WEEK 4 | David Foster | John Dalton | 175 | 82 |
| 12 | WEEK 4 | Dale Hemme | John Head | 169 | 81 |
+----+------------+--------------+--------------+-----------------+-----------------+
CSV - wp_match_scores_test
+----+------------+------------+------------+
| ID | match_week | player1_id | player2_id |
+----+------------+------------+------------+
| 5 | WEEK 1 | 82 | 23 |
| 20 | WEEK 1 | 164 | 169 |
| 21 | WEEK 2 | 164 | 81 |
| 25 | WEEK 2 | 82 | 169 |
| 61 | WEEK 3 | 175 | 169 |
| 62 | WEEK 4 | 175 | 82 |
| 69 | WEEK 2 | 175 | 23 |
| 85 | WEEK 3 | 164 | 82 |
| 86 | WEEK 4 | 164 | 23 |
+----+------------+------------+------------+
The output from the mysql query are the matches that have been played. I am trying to figure out how to list the matches that have not been played from the table Schedule.
CSV - MySQL Output
+------------+------------+------------+
| match_week | player1_id | player2_id |
+------------+------------+------------+
| WEEK 1 | 164 | 169 |
| WEEK 1 | 82 | 23 |
| WEEK 2 | 164 | 81 |
| WEEK 2 | 82 | 169 |
| WEEK 2 | 175 | 23 |
| WEEK 3 | 175 | 169 |
| WEEK 3 | 164 | 82 |
| WEEK 4 | 175 | 82 |
| WEEK 4 | 164 | 23 |
+------------+------------+------------+
MYSQL
select DISTINCT ms.match_week, ms.player1_id , ms.player2_id FROM
wp_match_scores_test ms
JOIN wp_schedules_test s
ON (s.player1_home_id = ms.player1_id or s.player1_away_id =
ms.player2_id)
Order by ms.match_week
The expected output is:
CSV - Desired Output
+------------+----------------+----------------+
| match_week | player_home_id | player_away_id |
+------------+----------------+----------------+
| WEEK 1 | 81 | 175 |
| WEEK 3 | 81 | 23 |
| WEEK 4 | 169 | 81 |
+------------+----------------+----------------+
The added code I would like to use is
SELECT s.*
FROM wp_schedules_test s
WHERE NOT EXISTS
(select DISTINCT ms.match_week, ms.player1_id , ms.player2_id FROM
wp_match_scores_test ms
JOIN wp_schedules_test s
ON (s.player1_home_id = ms.player1_id or s.player1_away_id =
ms.player2_id)
Order by ms.match_week)
Unfortunately, the output yields "No Rows"
A: You can use a LEFT JOIN to achieve the desired results, joining the two tables on matching player ids (noting that player id values in wp_match_scores_test can correspond to either player1_home_id or player1_away_id in wp_schedules_test). If there is no match, the result table will have NULL values from the wp_match_scores_test table values, and you can use that to select the matches which have not been played:
SELECT sch.*
FROM wp_schedule_test sch
LEFT JOIN wp_match_scores_test ms
ON (ms.player1_id = sch.player1_home_id
OR ms.player2_id = sch.player1_home_id)
AND (ms.player1_id = sch.player1_away_id
OR ms.player2_id = sch.player1_away_id)
WHERE ms.ID IS NULL
Output:
ID match_week home_player1 away_player1 player1_home_id player1_away_id
2 Week 1 John Head David Foster 81 175
8 Week 3 John Head Eric Simmons 81 23
12 Week 4 Dale Hemme John Head 169 81
Note that you can also use a NOT EXISTS query, using the same condition as I used in the JOIN:
SELECT sch.*
FROM wp_schedule_test sch
WHERE NOT EXISTS (SELECT *
FROM wp_match_scores_test ms
WHERE (ms.player1_id = sch.player1_home_id
OR ms.player2_id = sch.player1_home_id)
AND (ms.player1_id = sch.player1_away_id
OR ms.player2_id = sch.player1_away_id))
The output of this query is the same. Note though that conditions in the WHERE clause have to be evaluated for every row in the result set and that will generally make this query less efficient than the LEFT JOIN equivalent.
Demo on dbfiddle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57702795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HTTP Connection fails but returns an error code of 0 I'm writing an HTTP requester for a library in MQL4. This is what I have so far:
#define INTERNET_OPEN_TYPE_PRECONFIG 0
#define INTERNET_OPEN_TYPE_DIRECT 1
#define INTERNET_FLAG_NO_UI 0x00000200
#define INTERNET_FLAG_SECURE 0x00800000
#define INTERNET_FLAG_NO_CACHE_WRITE 0x04000000
#define INTERNET_SERVICE_HTTP 3
#define INTERNET_SERVICE_HTTPS 6
HttpRequester::HttpRequester(const string verb, const string host, const string resource,
const int port, const bool secure, const string referrer = NULL) {
m_ready = false;
ResetLastError();
// First, set the secure flag if we want a secure connection and define the service
int service = INTERNET_SERVICE_HTTP;
int flags = INTERNET_OPEN_TYPE_DIRECT | INTERNET_OPEN_TYPE_PRECONFIG | INTERNET_FLAG_NO_CACHE_WRITE;
if (secure) {
flags |= INTERNET_FLAG_SECURE;
service = INTERNET_SERVICE_HTTPS;
}
// Next, report to Windows the user agent that we'll request HTTP data with. If this fails
// then return an error
m_open_handle = InternetOpenW(GetUserAgentString(), flags, NULL, NULL, 0);
if (m_open_handle == INTERNET_INVALID_HANDLE) {
SetUserError(INTERNET_OPEN_FAILED_ERROR);
return;
}
// Now, attempt to create an intenrnet connection to the URL at the desired port;
// if this fails then return an error
m_session_handle = InternetConnectW(m_open_handle, host, port, "", "", service, flags, 1);
if (m_session_handle == INTERNET_INVALID_HANDLE) {
SetUserError(INTERNET_CONNECT_FAILED_ERROR);
return;
}
// Finally, open the HTTP request with the session variable, verb and URL; if this fails
// then log and return an error
string accepts[];
m_request_handle = HttpOpenRequestW(m_session_handle, verb, resource, NULL, referrer,
accepts, INTERNET_FLAG_NO_UI, 1);
if (m_request_handle == INTERNET_INVALID_HANDLE) {
SetUserError(INTERNET_OPEN_REQUEST_FAILED_ERROR);
return;
}
m_ready = true;
}
When calling this code, the issue I'm having is that InternetConnectW returns a handle of 0, but GetLastError also returns 0. I have verified the host ("https://qh7g3o0ypc.execute-api.ap-northeast-1.amazonaws.com") and port (443). What is going on here and how do I fix this?
A: I found the issue. It turns out that I was setting my flags and service improperly.
First, according to this, INTERNET_OPEN_TYPE_DIRECT and INTERNET_OPEN_TYPE_PRECONFIG conflict with each other. So, I removed INTERNET_OPEN_TYPE_DIRECT to tell Windows that I would like to use the network settings stored in the registry.
Next, I looked at the Windows documentation, here, and found out that, although INTERNET_SERVICE_HTTPS is defined, both HTTP and HTTPS requests are defined by the INTERNET_SERVICE_HTTP service flag.
Finally, I was not including the INTERNET_FLAG_SECURE flag in the right place. I discovered, from this question, that this flag needs to be included on the call to HttpOpenRequestW and including it anywhere else would be redundant.
After making all these changes, my code looks like this:
HttpRequester::HttpRequester(const string verb, const string host, const string resource,
const int port, const bool secure, const string referrer = NULL) {
m_ready = false;
ResetLastError();
// First, report to Windows the user agent that we'll request HTTP data with. If this fails
// then return an error
int flags = INTERNET_OPEN_TYPE_PRECONFIG | INTERNET_FLAG_NO_CACHE_WRITE;
m_open_handle = InternetOpenW(GetUserAgentString(), flags, NULL, NULL, 0);
if (m_open_handle == INTERNET_INVALID_HANDLE) {
SetUserError(INTERNET_OPEN_FAILED_ERROR);
return;
}
// Next, attempt to create an intenrnet connection to the URL at the desired port;
// if this fails then return an error
m_session_handle = InternetConnectW(m_open_handle, host, port, "", "", INTERNET_SERVICE_HTTP, flags, 0);
if (m_session_handle == INTERNET_INVALID_HANDLE) {
SetUserError(INTERNET_CONNECT_FAILED_ERROR);
return;
}
// Now, if we want a secure connection then add the secure flag to the connection
if (secure) {
flags |= INTERNET_FLAG_SECURE;
}
// Finally, open the HTTP request with the session variable, verb and URL; if this fails
// then log and return an error
string accepts[];
m_request_handle = HttpOpenRequestW(m_session_handle, verb, resource, NULL, referrer,
accepts, flags, 0);
if (m_request_handle == INTERNET_INVALID_HANDLE) {
SetUserError(INTERNET_OPEN_REQUEST_FAILED_ERROR);
return;
}
m_ready = true;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75577659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Oracle: Calculate time difference in HH:MM:SS between 2 dates I have 2 dates with following format:
ST_DT = Sun Dec 29 11:55:29 EST 2013
ED_DT = Tue Dec 30 20:21:34 EST 2013
I want to find the difference between these 2 dates in HH:MM:SS format. Now my problem is that i don't know how to parse the above date format in Oracle.
A: Are the dates in varchar2 type? Then, you can first convert it into timestamp format. Since it has timezone also, use the to_timestamp_tz function.
SQL> select to_timestamp_tz('Sun Dec 29 11:55:29 EST 2013','Dy Mon dd hh24:mi:ss TZR yyyy') from dual;
TO_TIMESTAMP_TZ('SUNDEC2911:55:29EST2013','DYMONDDHH24:MI:SSTZRYYYY')
---------------------------------------------------------------------------
29-DEC-13 11.55.29.000000000 AM EST
Once the dates are in timestamp type, subtracting them will give you the difference in interval day to second type.
SQL> select to_timestamp_tz ('Mon Dec 30 20:21:34 EST 2013','Dy Mon dd hh24:mi:ss TZR yyyy')
2 - to_timestamp_tz ('Sun Dec 29 11:55:29 EST 2013','Dy Mon dd hh24:mi:ss TZR yyyy') from dual;
TO_TIMESTAMP_TZ('MONDEC3020:21:34EST2013','DYMONDDHH24:MI:SSTZRYYYY')-TO_TI
---------------------------------------------------------------------------
+000000001 08:26:05.000000000
Then use extract to get the individual components from the interval.
SQL> select extract(day from intrvl) as dd,
2 extract(hour from intrvl) as hh24,
3 extract(minute from intrvl) as mi,
4 extract(second from intrvl) as ss
5 from (
6 select to_timestamp_tz ('Mon Dec 30 20:21:34 EST 2013','Dy Mon dd hh24:mi:ss TZR yyyy')
7 - to_timestamp_tz ('Sun Dec 29 11:55:29 EST 2013','Dy Mon dd hh24:mi:ss TZR yyyy') as intrvl
8 from dual
9 );
DD HH24 MI SS
---------- ---------- ---------- ----------
1 8 26 5
A: I figured out one solution but it will work only for same time zone dates.
with tab as (
select to_date(replace(substr('Sun Dec 28 23:59:59 EST 2013', 4), 'EST '), 'Mon DD HH24:MI:SS RRRR') start_date,
to_date(replace(substr('Tue Dec 30 20:21:34 EST 2013', 4), 'EST '), 'Mon DD HH24:MI:SS RRRR') end_date
from dual),
tab_sec as
(select ((end_date - start_date) * 24 * 60 * 60) sec from tab)
select lpad(trunc(sec / (60*60)), 2, '0')||':'||
lpad(trunc((sec - (trunc(sec / (60*60)) * 60 * 60))/60), 2, '0')||':'||
lpad(mod(sec, 60), 2, '0') diff
from tab_sec;
A: You can use NUMTODSINTERVAL
For example
with x as (
select to_date('01/01/2014 10:00:00','dd/mm/yyyy hh24:mi:ss') d1 ,
to_date('01/01/2014 12:00:00','dd/mm/yyyy hh24:mi:ss') d2
from dual
union all
select to_date('02/01/2014 10:00:00','dd/mm/yyyy hh24:mi:ss') d1 ,
to_date('01/01/2014 12:00:00','dd/mm/yyyy hh24:mi:ss') d2
from dual
union all
select to_date('01/01/2014 10:30:00','dd/mm/yyyy hh24:mi:ss') d1 ,
to_date('01/01/2014 12:00:00','dd/mm/yyyy hh24:mi:ss') d2
from dual
union all
select to_date('01/01/2014 10:00:30','dd/mm/yyyy hh24:mi:ss') d1 ,
to_date('01/01/2014 12:00:00','dd/mm/yyyy hh24:mi:ss') d2
from dual
union all
select to_date('01/01/2014 10:00:30','dd/mm/yyyy hh24:mi:ss') d1 ,
to_date('02/01/2014 12:20:10','dd/mm/yyyy hh24:mi:ss') d2
from dual
)
select d1 , d2 , numtodsinterval(d2 - d1, 'day') as interval_diff
from x
D1 D2 INTERVAL_DIFF
------------------- ------------------- ---------------------------------
01/01/2014 10:00:00 01/01/2014 12:00:00 +000000000 02:00:00.000000000
02/01/2014 10:00:00 01/01/2014 12:00:00 -000000000 22:00:00.000000000
01/01/2014 10:30:00 01/01/2014 12:00:00 +000000000 01:30:00.000000000
01/01/2014 10:00:30 01/01/2014 12:00:00 +000000000 01:59:30.000000000
01/01/2014 10:00:30 02/01/2014 12:20:10 +000000001 02:19:39.999999999
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20867220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Conflicted with the FOREIGN KEY in One to One Relationship Entity Framework Code First While I am going to add-migration it's ok but while I am going to run update-database I am getting this type of error in package manager console
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.ServiceTypes_dbo.Services_ServiceTypeID". The conflict occurred in database "Otaidea", table "dbo.Services", column 'ServicesID'.
My two model:
public class Services
{
[Key]
public int ServicesID { get; set; }
[DisplayName("Register Date")]
public DateTime RegisterDate { get; set; }
public int ServiceTypeID { get; set; }
public string ApplicationUserID { get; set; }
public virtual ServiceType ServiceType { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
my another Table:
public class ServiceType
{
[ForeignKey("Services")]
public int ServiceTypeID { get; set; }
public string NAME { get; set; }
public virtual Services Services { get; set; }
}
A: Your relationship in your models are wrong. Services has a "Type", so the Foreign Key goes from ServiceType to Service. You don't need to reference Services inside ServiceType
You should create your model like this:
Services
public class Services
{
[Key]
public int ServicesID { get; set; }
[DisplayName("Register Date")]
public DateTime RegisterDate { get; set; }
public string ApplicationUserID { get; set; }
[ForeignKey("ServiceType")]
public int ServiceTypeID { get; set; }
public virtual ServiceType ServiceType { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
ServiceType
public class ServiceType
{
[Key]
public int ServiceTypeID { get; set; }
public string NAME { get; set; }
}
I would also do the same with the ApplicationUserID property, but since you didn't post about it I let it as is.
Also, it would be better if you drop your database and let Entity Framework create it again for you. Because you had a wrong model relationship things got "messy".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34462651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: implicit conversion from a class to any one of its direct or indirect base classes this is the MSDN's idea about implicit casting .
Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
but I'm wondering how casting from derived class to base class is possible because the derived class has more members than it's base class so it is bigger and it doesn't make any sense to me how this is possible?sorry for bad English.
A: The extra members are still there. No data is lost. You just can not access them from a variable of the base type. This behavior is a property of polymorphism.
When you implicitly (or explicitly) cast Derived to Base, you are not creating a new instance of Base, or altering the existing instance of Derived, you are simply creating a different view to Derived, treating it as if it were a Base.
To access the derived members again, you will need to explicitly cast back to a derived type to access them.
Assuming Derived has field Foo while Base does not:
Derived d = new Derived();
Console.WriteLine(d.Foo);
Base b = d;
Console.WriteLine(b.Foo); //compile error
Derived d2 = (Derived)b; //or Derived d2 = b as Derived;
Console.WriteLine(d2.Foo); //valid
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24107041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: updating records in table A from table B if column XYZ ( checksum ) changes in table B I am having a table A and table B.
Table A is created from Table B ( and few other table join operation ).
Table A has all of its column which are subset of column in table B.
There is a column called as check_sum in table A and table B. This is basically a calculated column and if any column value changes then check_sum ( calculated value ) changes as well.
For example:
Table A ( schema ):
cust_id ( pk ), cust_name, cust_location, check_sum ... other columns ( no need to worry about them )
Table B ( schema ) :
cust_id ( pk ), cust_name, cust_location, check_sum
Initially table B and A have entries like below:
Table A: ( sample record )
1, John, USA, abc222abc, ... other columns
Table B: ( sample record )
1, John, USA, abc222abc
Now lets say John changes his country location to UK, then corresponding entry in TABLE A looks like this
Table A: ( sample record )
1, John, UK, checkSumChanged, ... other columns
Now i need to update my table B accordingly, so that instead of location of John as USA it should have it as UK.
Column checksum is helpful here, since its value changes in Table A if any column changes.
This is the part i am stuck at. Not able to update just "CHANGED" rows from Table A to Table B. I have following query below. It is updating all rows instead of just the changed rows.
Here is the query.
UPDATE tableB
SET
tableB.cust_name = tableA.cust_name,
tableB.cust_location = tableA.cust_location,
tableB.check_sum = tableA.check_sum
FROM
tableA inner join tableB
on tableA.cust_id = tableB.cust_id
and tableA.check_sum != tableB.check_sum
Any ideas or suggestion how can i correct my query to just update the changed record.
Thanks in advance!!!
A: Do it without a join:
update B
SET cust_name = a.cust_name, checksum = a.checksum, cust_location = a.cust_location
FROM a
WHERE a.custid = b.custid AND a.checksum != b.checksum;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31615984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: angular ng-repeat if property is defined I'm trying to ng-repeat through an array, but need to hide if a property is undefined.
I tried doing to do is this:
<div ng-repeat="person in people | filter:search" ng-if="last == undefined">
{{person.last}}, {{person.first}}
</div>
Heres a basic jsfiddle of what I'm trying to do:
http://jsfiddle.net/HB7LU/4556/
Thank you!
A: <div ng-controller="MyCtrl">
<div ng-repeat="person in people | filter:search" ng-show="person.last">
{{person.last}}, {{person.first}}
</div>
Try testing for person.last instead of just 'last'.
I used ng-show instead of ng-if as well.
A: If you want to just hide the rows, then mccainz's answer will work. If you want to actually remove them from the DOM, then create a filter:
$scope.fullNameFilter = function(person){
return person.last;
};
HTML
<div ng-repeat="person in people | filter: fullNameFilter">
JSFIddle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24415443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Suggestions for a good VBScript IDE what would be a good IDE for VB Script ?
Currently using Notepad++. Also have Sublime Text, VS Code installed.
I was wondering if i could discover a hidden gem through stack overflow !
A: *
*Brackets (free)
*VBSEdit (paid)
*Systemscripter (paid)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59262252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Log in with the MercadoLibre API without having to type user and password? Is there any way to login with the MercadoLibre API without having to ask for user and password?
I need to make a request that is of the form:
https://auth.mercadolibre.com.uy?user="someone"&&password="secret"
It's an example, it does not really matter the verb / type of request
The idea is that the request returns an access token and with it can perform tasks such as answering questions asked by customers to a seller, without the need to log in by manually entering the user and the password of that seller. Since my system must handle several of them.
Additional data: It is to integrate an authentication system with vTiger CRM, so I am using the MercadoLibre SDK for the PHP language.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45761456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python Cannot return the final value I have stuck with this assignment.
I tried to do different combination with my code to get the return but failed.
The question asks find radiation exposure within a period of time by using recursion.
Problem: I can get all the calculations correctly [I checked it using online python executor] but when the process comes to the final return, the result is None. I don't know why my code can't return the final calculation result. I wish: some guru out there can give me some clues thanks.
global totalExposure
totalExposure=0
def f(x):
import math
return 10*math.e**(math.log(0.5)/5.27 * x)
def radiationExposure(start, stop, step):
time=(stop-start)
newStart=start+step
if(time!=0):
radiationExposure(newStart, stop, step)
global totalExposure
totalExposure+=radiation
radiation=f(start)*step
else:
return totalExposure
Test case 1:
>>> radiationExposure(0, 5, 1)
39.10318784326239
A: It seems you forgot the return in the if clause. There's one in the else but none in the if.
A: @furas' code made iterative instead of recursive:
def radiationExposure2(start, stop, step):
totalExposure = 0
time = stop - start
newStart = start + step
oldStart = start
while time > 0:
totalExposure += f(oldStart)*step
time = stop - newStart
oldStart = newStart
newStart += step
return totalExposure
Converted to a for-loop:
def radiationExposure3(start, stop, step):
totalExposure = 0
for time in range(start, stop, step):
totalExposure += f(time) * step
return totalExposure
Using a generator expression:
def radiationExposure4(start, stop, step):
return sum(f(time) * step for time in range(start, stop, step))
A: As Paulo mentioned, your if statement had no return. Plus, you were referencing the variable radiation before it was assigned. A few tweaks and I am able to get it working.
global totalExposure
totalExposure = 0
def f(x):
import math
return 10 * math.e**(math.log(0.5)/5.27 * x)
def radiationExposure(start, stop, step):
time = (stop-start)
newStart = start+step
if(time!=0):
radiationExposure(newStart, stop, step)
global totalExposure
radiation = f(start) * step
totalExposure += radiation
return totalExposure
else:
return totalExposure
rad = radiationExposure(0, 5, 1)
# rad = 39.1031878433
A: Cleaner version without global
import math
def f(x):
return 10*math.e**(math.log(0.5)/5.27 * x)
def radiationExposure(start, stop, step):
totalExposure = 0
time = stop - start
newStart = start + step
if time > 0:
totalExposure = radiationExposure(newStart, stop, step)
totalExposure += f(start)*step
return totalExposure
rad = radiationExposure(0, 5, 1)
# rad = 39.1031878432624
A: As other mentioned, your if statement had no return. It seems you forgot the return in the if clause. There's one in the else but none in the if.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22083416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Elascticsearch error while Searching for percolation I use elasticsearch for percolation. And i find some error in log file:
Elascticsearch error IllegalArgumentException[Less than 2 subSpans.size():1]
[2016-08-04 10:24:53,673][DEBUG][action.percolate ] [test_node01] [liza_index][0], node[Qp9QPap1Tb6Q-wSd58ncYA], [P], v[10], s[STARTED], a[id=KaTXb5JUTV
O99cxcvRlJBg]: failed to execute [org.elasticsearch.action.percolate.PercolateRequest@7137f122]
RemoteTransportException[[test_node01][192.168.69.142:9300][indices:data/read/percolate[s]]]; nested: PercolateException[failed to percolate]; nested: Percolate
Exception[failed to execute]; nested: IllegalArgumentException[Less than 2 subSpans.size():1];
Caused by: PercolateException[failed to percolate]; nested: PercolateException[failed to execute]; nested: IllegalArgumentException[Less than 2 subSpans.size():
1];
at org.elasticsearch.action.percolate.TransportPercolateAction.shardOperation(TransportPercolateAction.java:181)
at org.elasticsearch.action.percolate.TransportPercolateAction.shardOperation(TransportPercolateAction.java:56)
at org.elasticsearch.action.support.broadcast.TransportBroadcastAction$ShardTransportHandler.messageReceived(TransportBroadcastAction.java:282)
at org.elasticsearch.action.support.broadcast.TransportBroadcastAction$ShardTransportHandler.messageReceived(TransportBroadcastAction.java:278)
at org.elasticsearch.transport.RequestHandlerRegistry.processMessageReceived(RequestHandlerRegistry.java:75)
at org.elasticsearch.transport.TransportService$4.doRun(TransportService.java:376)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: PercolateException[failed to execute]; nested: IllegalArgumentException[Less than 2 subSpans.size():1];
at org.elasticsearch.percolator.PercolatorService$4.doPercolate(PercolatorService.java:583)
at org.elasticsearch.percolator.PercolatorService.percolate(PercolatorService.java:254)
at org.elasticsearch.action.percolate.TransportPercolateAction.shardOperation(TransportPercolateAction.java:178)
... 9 more
Caused by: java.lang.IllegalArgumentException: Less than 2 subSpans.size():1
at org.apache.lucene.search.spans.ConjunctionSpans.<init>(ConjunctionSpans.java:38)
at org.apache.lucene.search.spans.NearSpansOrdered.<init>(NearSpansOrdered.java:54)
at org.apache.lucene.search.spans.SpanNearQuery$SpanNearWeight.getSpans(SpanNearQuery.java:232)
at org.apache.lucene.search.spans.SpanOrQuery$SpanOrWeight.getSpans(SpanOrQuery.java:166)
at org.apache.lucene.search.spans.SpanWeight.scorer(SpanWeight.java:134)
at org.apache.lucene.search.spans.SpanWeight.scorer(SpanWeight.java:38)
at org.apache.lucene.search.LRUQueryCache$CachingWrapperWeight.scorer(LRUQueryCache.java:628)
at org.elasticsearch.common.lucene.Lucene.exists(Lucene.java:248)
at org.elasticsearch.percolator.PercolatorService$4.doPercolate(PercolatorService.java:571)
... 11 more
Does it mean, i have a broken stored query or a broken sended text?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38762261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing data from a Java page to JSP page I'm trying to pass an Object type from Java class to Jsp page.
After going through many sites am bit confused on how to go about with this. My Java file has this content :
Object categoryelements;
Iterator it=elements.iterator();
while (it.hasNext())
{
JSONObject innerObj= (JSONObject)it.next();
categoryelements= innerObj.get("category");
System.out.println(categoryelements);
}
I want to pass this categoryelements to JSP page.
Is it possible to do so? Am making use of JSP page, Servlet and a Java page
Can you please provide a solution for this?
A: Your HTTPRequest object will be having setAttribute, getAttribute & removeAttribute methods, it will internally hold a map [Map<String,Object>] to keep the attributes, you can set the key & value pair and get it in the JSP using the implicit request object
A: If categoryelements contains plain string then set the request attribute like this,
request.setAttribute("categoryelements", categoryelements.toString());
And in JSPfetch the value in for example a div like this,
<div>${categoryelements}</div>
Edit:-
To access the request attribute in dropdownlist you can use the JSTL library which is helpful in handling the flow of execution in JSP or HTML. You can add this library in your JSP page like this,
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
And then use them to iterate the list as follows,
<select name="selectFieldName">
// following line of code works as Java for loop and here 'listRequestAttribute' can be any list type object e.g. List<String>
<c:forEach items="${listRequestAttribute}" var="currentListItem">
// '${currentListItem}' will hold the current object in the loop iteration.
<option value="${currentListItem}" >
${currentListItem}
</option>
</c:forEach>
</select>
A: in Java:
Object categoryelements;
List<String> result = new ArrayList<String>();
Iterator it=elements.iterator();
while (it.hasNext())
{
JSONObject innerObj= (JSONObject)it.next();
result.add(innerObj.get("category"));
}
request.setAttribute("result", result);
in JSP:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<jsp:useBean id="result" class="java.lang.List" scope="request" />
...
<c:forEach var="item" items="${result}" >
<c:out value="${item}"/>
</c:forEach>
This is just a simple example. You might consider using classes other than Object to provide better control over your output. The Gson library might help you here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28082843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Spaces replaced by =20 after extracting text from email I tried to get the text of a received gmail, using the email and imaplib modules in python. After decoding with utf-8 and after getting the payload of the message, all the spaces are still replaced by =20. Can I use another decoding step in order to fix this?
The code is the following: (I got it from a youtube tutorial - https://youtu.be/Jt8LizzxkPU )
``
import email
import imaplib
username = "abc"
password = "123"
mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login(username,password)
mail.select("inbox")
result, data = mail.uid("search", None,"ALL")
inbox_item_list = data[0].split()
for item in inbox_item_list:
#most_recent = inbox_item_list[-1]
#oldest = inbox_item_list[0]
result2, email_data = mail.uid('fetch',item,'(RFC822)')
raw_email = email_data[0][1].decode("utf-8")
email_message = email.message_from_string(raw_email)
to_ = email_message['To']
from_ = email_message['From']
subject_ = email_message['Subject']
counter = 1
for part in email_message.walk():
if part.get_content_maintype() == "multipart":
continue
filename = part.get_filename()
if not filename:
ext = ".html"
filename = "msg-part-%08d%s" %(counter, ext)
counter += 1
#save file
content_type = part.get_content_type()
print(subject_)
print (content_type)
if "plain" in content_type:
print(part.get_payload())
elif "html" in content_type:
print("do some beautiful soup")
else:
print(content_type)
``
A: Try to import quopri, and then when you get the content of the email body (or whatever text that has the =20s inside), you can use quopri.decodestring()
I do it like this
quopri.decodestring(part.get_payload())
But do keep in mind that this is if you quite specifically want to decode from quoted-printable. Normally I would say the answer of @jfs is neater.
A: Here's a complete code example of how a simple email (that contains both a literal =20 as well as =20 sequence that should be replaced by a space) could be decoded:
#!/usr/bin/env python3
import email.policy
email_text = """Subject: =?UTF-8?B?dGVzdCDwn5OnID0yMA==?=
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo=
oooooooooooooooooooooooooooooong=20word
=3D20
^ line starts with =3D20
emoji: <=F0=9F=93=A7>"""
msg = email.message_from_string(
email_text, policy=email.policy.default
)
print("Subject: <{subject}>".format_map(msg))
assert not msg.is_multipart()
print(msg.get_content())
Output
Subject: <test =20>
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word
=20
^ line starts with =20
emoji: <>
msg.walk(), part.get_payload(decode=True) could be used to traverse more complex EmailMessage objects. See email Examples.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60240054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Add many rows at once I'm just starting out with WPF and MVVM framework. I have a Window with telerik RadGridView and I would like to add data from multipul rows in the same time. Has anyone got any advice or examples ,I've tried numerous ways but none seem to work out.
Thank you
My ViewModel
private IList<Ligne> _CurrentLigne;
public IList<Ligne> CurrentLigne
{
get { return _CurrentLigne; }
set
{
_CurrentLigne= value;
OnPropertyChanged("CurrentLigne");
}
}
var _ligne = Currentligne as Ligne;
foreach (Ligne ligne in CurrentLigne)
{
if (Currentligne!= null)
_ligneBLL.InsetLigne(ligne);
}
My View
<telerik:RadGridView x:Name="GridView"
AutoGenerateColumns="False"
ItemsSource="{Binding ListeLigne}"
SelectedItem="{Binding CurrentLigne, Mode=TwoWay}"
SelectionMode="Multiple" >
A: I recommend that you read the Data Binding Overview page on MSDN so that you can get a better idea on data binding. For now, I can give you a few tips. Firstly, in WPF, your property should really have used an ObservableCollection<T>, like this:
private ObservableCollection<Ligne> _ListeLigne = new ObservableCollection<Ligne>();
public ObservableCollection<Ligne> ListeLigne
{
get { return _ListeLigne; }
set
{
_ListeLigne = value;
OnPropertyChanged("ListeLigne");
}
}
Then your selected item like this:
private Ligne _CurrentLigne = new Ligne();
public Ligne CurrentLigne
{
get { return _CurrentLigne; }
set
{
_CurrentLigne= value;
OnPropertyChanged("CurrentLigne");
}
}
With properties like this, your XAML would be fine. Lastly, to add your items, you simply do this:
ListeLigne = new ObservableCollection<Ligne>(SomeMethodGettingYourData());
Or just...:
ListeLigne = SomeMethodGettingYourData();
... if your data access method returns an ObservableCollection<Ligne>. If you want to select a particular element in the UI, then you must select an actual item from the data bound collection, but you can do that easily using LinQ.
using System.Linq;
CurrentLigne = ListeLigne.First(l => l.SomeLigneProperty == someValue);
Or just:
CurrentLigne = ListeLigne.ElementAt(someValidIndexInCollection);
Oh... and I've got one other tip for you. In your code:
foreach (Ligne ligne in CurrentLigne)
{
if (Currentligne!= null) // this is a pointless if condition
_ligneBLL.InsetLigne(ligne);
}
The above if condition is pointless because the program execution will never enter the foreach loop if the collection is null.
A: Try This !!
foreach (Ligne ligne in ListLigne)
{
var _ligne = ligne as Ligne;
_ligneBLL.InsetLigne(ligne);
}
A: I think you want to use a BindingList. It is the list I always use, but remember you will need to post your notifyChange events.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24249016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add more labels to colorbar legend in ggplot I'm making some plots in ggplot with a colorbar legend like below. By default the legend has only 4 labels showing the value of specific colors. There are theme elements which can change the size of the colorbar, but not the number of labels. How can I increase the number of labels?
library(ggplot2)
ggplot(mtcars, aes(x=mpg, y=carb, color=disp)) +
geom_point(size=3) +
theme(legend.key.height = unit(2,'cm'))
A: You just need to specify the breaks in scale_color_continous()
g1 <- ggplot(mtcars, aes(x=mpg, y=carb, color=disp)) +
geom_point(size=3) +
theme(legend.key.height = unit(2,'cm'))
g1 + scale_color_continuous(breaks=seq(50,500,25))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48431647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C# - Function that replaces a certain character with another I want to create a function that will replace every dot with a comma in a provided string.
My code looks like this:
public void replaceDot(ref string str) {
for(int i = 0; i < str.Length; i++) {
if (str[i] == '.') {
str[i] = ','; //readonly error here
}
}
}
Any ideas how to make it work? I also tried using foreach loop but it also didn't work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65810572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tool Tips from stored content and implementing site wide In my ASP.NET MVC application, we want our Admins of the application to manage tool tips for controls on the page for instance: text boxes, list boxes, etc. The tool tips will stored in a table structure and each view will load the respective tool tip data.
So I created the following table, Admin users will go to the admin menu and add/update tool tips for a given controller/model fields.
Entity : ToolTip
public class ToolTip
{
public int ID { get; set; }
public string ControllerName { get; set; }
public string ToolTipMessage { get; set; }
public string FormField { get; set; }
}
I need some advice on the design. For instance every time I add a new field I would have to update the tool tip admin page and add the new field. I see allot of maintenance for this tool. Also as far as retrieving a tool tip when a user hovers on the respective user control, I have seen some examples where people load via AJAX tool tip content but I was wondering if that is a good approach. Every time a user hovers on a control an AJAX request has to be made to the server.
I was thinking when a model is rendered, I could fetch the tool tip data and hidden fields and then the control can pick it up. What do you guys think about my approach
or
instead of creating a seperate admin menu to manage these tool tips, i can enable the admins to manage the tool tip in the views itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20578079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can i create a file for JSONmodel programmatically and automatically create its Codable struct How can i build a function that takes string as a parameter, that string will be my JSONObject and then this function will create a file in project that contains a struct which have keys of my model like this page does https://app.quicktype.io
I will pass this kind of string to function:
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}]
It will create a file in project like:
import Foundation
// MARK: - UserInfoModelElement
struct UserInfoModelElement: Codable {
let id: Int
let name, username, email: String
let address: Address
let phone, website: String
let company: Company
}
// MARK: - Address
struct Address: Codable {
let street, suite, city, zipcode: String
let geo: Geo
}
// MARK: - Geo
struct Geo: Codable {
let lat, lng: String
}
// MARK: - Company
struct Company: Codable {
let name, catchPhrase, bs: String
}
typealias UserInfoModel = [UserInfoModelElement]
A: I'm building exactly this as an open source project on GitHub juliofruta/CodableCode. Feel free to submit a Pull request since this does not support all cases as specified in the comments. I'm copy and pasting my current solution here:
import Foundation
enum Error: Swift.Error {
case invalidData
}
let identation = " "
extension String {
var asType: String {
var string = self
let firstChar = string.removeFirst()
return firstChar.uppercased() + string
}
var asSymbol: String {
var string = self
let firstChar = string.removeFirst()
return firstChar.lowercased() + string
}
mutating func lineBreak() {
self = self + "\n"
}
func makeCodableTypeArray(anyArray: [Any], key: String, margin: String) throws -> String {
var types = Set<String>()
var existingTypes = Set<String>()
var structCodeSet = Set<String>()
try anyArray.forEach { jsonObject in
var type: String?
// check what type is each element of the array
switch jsonObject {
case _ as String:
type = "String"
case _ as Bool:
type = "Bool"
case _ as Decimal:
type = "Decimal"
case _ as Double:
type = "Double"
case _ as Int:
type = "Int"
case let dictionary as [String: Any]:
let objectData = try JSONSerialization.data(withJSONObject: dictionary, options: [])
let objectString = String(data: objectData, encoding: .utf8)!
let dummyTypeImplementation = try objectString.codableCode(name: "TYPE", margin: "")
// if the existing type does not contain the dummy type implementation
if !existingTypes.contains(dummyTypeImplementation) {
// insert it
existingTypes.insert(dummyTypeImplementation)
// keep a count
if existingTypes.count == 1 {
type = key.asType
} else {
type = key.asType + "\(existingTypes.count)"
}
// and get the actual implementation
let typeImplementation = try objectString.codableCode(name: type!, margin: margin + identation)
structCodeSet.insert(typeImplementation)
}
default:
type = ""
assertionFailure() // unhandled case
}
if let unwrappedType = type {
types.insert(unwrappedType)
}
}
// write type
var swiftCode = ""
if types.isEmpty {
swiftCode += "[Any]"
} else if types.count == 1 {
swiftCode += "[\(types.first!)]"
} else {
swiftCode += "\(key.asType)Options"
// TODO: Instead of enum refactor to use optionals where needed.
// TODO: Build Swift Build package plugin
// Use diffing algorithm to introduce optionals?
// Introduce strategies:
// create
// 1. enum withassociated types
// 2. optionals where needed
// 3. optionals everywhere
// add support to automatically fix when reserved keywords have reserved words for example:
// let return: Return // this does not compile and is part of the bitso api
// so add support for coding keys
//
// struct Landmark: Codable {
// var name: String
// var foundingYear: Int
// var location: Coordinate
// var vantagePoints: [Coordinate]
//
// enum CodingKeys: String, CodingKey {
// case name = "return"
// case foundingYear = "founding_date"
//
// case location
// case vantagePoints
// }
// }
// create enum
swiftCode.lineBreak()
swiftCode.lineBreak()
swiftCode += margin + identation + "enum \(key.asType)Options: Codable {"
types.forEach { type in
swiftCode.lineBreak()
// enum associatedTypes
swiftCode += margin + identation + identation + "case \(type.asSymbol)(\(type))"
}
swiftCode.lineBreak()
swiftCode += margin + identation + "}"
}
// write implementations
structCodeSet.forEach { implementation in
swiftCode.lineBreak()
swiftCode.lineBreak()
swiftCode += implementation
swiftCode.lineBreak()
}
return swiftCode
}
/// Compiles a valid JSON to a Codable Swift Type as in the following Grammar spec: https://www.json.org/json-en.html
/// - Parameter json: A valid JSON string
/// - Throws: Not sure if it should throw right now. We can check if the JSON is valid inside
/// - Returns: The string of the type produced by the JSON
public func codableCode(name: String, margin: String = "") throws -> String {
var swiftCode = ""
swiftCode += margin + "struct \(name.asType): Codable {"
guard let data = data(using: .utf8) else {
throw Error.invalidData
}
if let dictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
try dictionary
.sorted(by: { $0.0 < $1.0 })
.forEach { pair in
let (key, value) = pair
swiftCode.lineBreak()
swiftCode += margin + identation + "let \(key.asSymbol): "
switch value {
case _ as Bool:
swiftCode += "Bool"
case _ as String:
swiftCode += "String"
case _ as Decimal:
swiftCode += "Decimal"
case _ as Double:
swiftCode += "Double"
case _ as Int:
swiftCode += "Int"
case let jsonObject as [String: Any]:
let objectData = try JSONSerialization.data(withJSONObject: jsonObject, options: [])
let objectString = String(data: objectData, encoding: .utf8)!
swiftCode += "\(key.asType)"
swiftCode.lineBreak()
swiftCode.lineBreak()
swiftCode += try objectString.codableCode(name: key, margin: margin + identation)
swiftCode.lineBreak()
case let anyArray as [Any]:
swiftCode += try makeCodableTypeArray(anyArray: anyArray, key: key, margin: margin)
// TODO: Add more cases like dates
default:
swiftCode += "Any"
}
}
}
swiftCode.lineBreak()
swiftCode += margin + "}"
return swiftCode
}
public var codableCode: String? {
try? codableCode(name: "<#SomeType#>")
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57159151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to reset/clear AudioUnit/AudioSession settings/properties in iOS? I am writing a VoIP app that uses AudioUnit for it's audio related tasks. Here, a lot of properties of AudioUnit and AudioSession are being set from a lot of places using the following two method
AudioComponentInstance audioUnit;
AudioComponent inputComponent;
AudioComponentDescription audioComponentDescription;
AudioStreamBasicDescription audioStreamBasicDescription;
AudioUnitSetProperty(audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
kOutputBus,
&audioStreamBasicDescription,
sizeof(audioStreamBasicDescription));
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryEnableBluetoothInput,
sizeof(allowBluetoothInput),
&allowBluetoothInput);
But at some point i want to clear all of my AudioUnit and AudioSession properties. And want to bring back all default settings. But i couldn't figure out how to do that. I tried with the following codes but none of those could do what i wanted.
AudioComponentInstance audioUnit;
AudioOutputUnitStop(audioUnit);
[[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
AudioUnitUninitialize(audioUnit);
Can anyone help me in this purpose ? Any code example would be very much helpful and appreciated. Solutions need to be from iOS 7 to upper.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36857835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to fetch only the documents that have 3 different values in mongodb? I have the following data in mongodb:
{
"_id" : ObjectId("111"),
"id" : "111",
"classification" : [
{
"annotator" : "annotatorName1",
"category" : "white"
},
{
"annotator" : "annotatorName2",
"category" : "white"
},
{
"annotator" : "annotatorName3",
"category" : "black"
}
]
}
{
"_id" : ObjectId("222"),
"id" : "222",
"classification" : [
{
"annotator" : "annotatorName1",
"category" : "white"
},
{
"annotator" : "annotatorName2",
"category" : "blue"
},
{
"annotator" : "annotatorName3",
"category" : "black"
}
]
}
{
"_id" : ObjectId("333"),
"kind" : "youtube#video",
"etag" : "tagvalue",
"id" : "333"
}
Please note that the classification label does not exists in all my records, as shown in record with id: "333".
I need to get all the records from my database that have different category values.
So, I need a query that when I run it, I will only get the record that has the classification label, and has exactly 3 different category values, in this case, I want a query that will only return this to me:
{
"_id" : ObjectId("222"),
"id" : "222",
"classification" : [
{
"annotator" : "annotatorName1",
"category" : "white"
},
{
"annotator" : "annotatorName2",
"category" : "blue"
},
{
"annotator" : "annotatorName3",
"category" : "black"
}
]
}
What command should I enter in my terminal in order to get all the records that have 3 unique category values under classification, IFF classification exists?
Thank you for your help.
A: The below aggregate can be used to find out the "id"s which have exactly 3 unique categories:
db.collectionName.aggregate([
{$match : {classification : {$exists : true}}},
{$unwind: "$classification"},
{$group: { _id: "$id", uniqueCategories: {$addToSet: "$classification.category"}}},
{$project: {_id : 1, numberOfCategories: {$size: "$uniqueCategories"}} },
{$match: {numberOfCategories: 3} }
])
Explanation: We start with matching documents which have the classification element. Then we $unwind it so as to deconstruct the embedded array into separate documents. Then it is grouped by id, and using $addToSet the categories are collected into an array - this takes care of eliminating any dupes. Then we project its $size and match on 'equal to 3'.
This aggregate will yield documents with the _id set to the id field of the documents in your collection that have 3 unique categories, which you can use to get to the documents. If your collection size is quite large, you should consider adding another $match stage in the beginning to restrict the dataset. As it stands now, it will be doing a collection scan.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53200682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does Keras convert the input shape from (3,3) to (?,3,3)? I am currently trying to get custom keras layers to work, you can see a simplified version here:
class MyLayer(Layer):
def __init__(self, **kwargs):
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
print("input_shape: "+str(input_shape))
self.kernel = self.add_weight(name='kernel',
shape=(input_shape[1], self.output_dim),
initializer='uniform',
trainable=True)
super(MyLayer, self).build(input_shape)
def call(self, x):
print("input tensor: "+str(x))
return K.dot(x, self.kernel)
inputs = Input(shape=(3,3), dtype='float', name='inputs')
results = MyLayer(input_shape=(3,3))(inputs)
The resulting console output is this:
input_shape: (None, 3, 3)
input tensor: Tensor("inputs:0", shape=(?, 3, 3), dtype=float32)
As you can see, the input_shape that the layer gets is not (3,3) as I specified but actually (None,3,3). Why is that?
The shape of the input tensor is also shaped ( ?, 3,3) which I thought to be a consequence of the weird input_shape ( None, 3,3). But the input tensor also has this shape with a third dimension if you replace super(MyLayer, self).build(input_shape) with super(MyLayer, self).build((3,3)). What is this mysterious third dimension keras automatically adds and why does it do that?
A: It is nothing mysterious, it is the batch dimension, since keras (and most DL frameworks), make computations on batches of data at a time, since this increases parallelism, and it maps directly to batches in Stochastic Gradient Descent.
Your layer needs to support computation on batches, so the batch dimension is always present in input and output data, and it is automatically added by keras to the input_shape.
A: This newly added dimension refers to the batch dimension, i.e., in your case, you will be passing batches of 3x3 dimensional tensors. This additional None dimension refers to the batch dimension, which is unknown during the creation of the graph.
If you have a look at the Input layer explanation in Core Layers webpage for Keras,
https://keras.io/layers/core/, you will see that the shape argument you are passing when creating the Input layer is defined as the following:
shape: A shape tuple (integer), not including the batch size. For instance, shape=(32,) indicates that the expected input will be batches of 32-dimensional vectors.
A: If you want to specify the batch size, you can do this instead:
inputs = Input(batch_shape=(batch_size,height,width,channel))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60743308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS rotate3d property behaving unexpectedly I was reading about the CSS rotate3d() property to rotate an element. I thought that the first three parameters in the function are multipliers and the fourth one is the degree magnitude.
The value of multipliers has to be between 0 and 1. This means that rotate3d(1, 0, 0, 90deg) will only result in rotateX(90deg). To get more range of rotations I changed it to rotate3d(0.25, 0, 0, 360deg) but it produces entirely different result.
I also noticed that transform: rotateX(45deg) rotateY(45deg); is not the same as transform: rotate3d(1,1,0, 45deg);. etc. If we cannot simply change the multiplier of required dimensions to get desired rotations, how should I calculate the value of three multipliers?
Thanks.
A: When using rotate3d(x, y, z, a) the first 3 numbers are coordinate that will define the vector of the rotation and a is the angle of rotation. They are not multiplier of the rotation.
rotate3d(1, 0, 0, 90deg) is the same as rotate3d(0.25, 0, 0, 90deg) and also the same as rotate3d(X, 0, 0, 90deg) because we will have the same vector in all the cases. Which is also the same as rotateX(90deg)
.box {
margin:30px;
padding:20px;
background:red;
display:inline-block;
}
<div class="box" style="transform:rotate3d(1,0,0,60deg)"></div>
<div class="box" style="transform:rotate3d(99,0,0,60deg)"></div>
<div class="box" style="transform:rotate3d(0.25,0,0,60deg)"></div>
<div class="box" style="transform:rotate3d(100,0,0,60deg)"></div>
<div class="box" style="transform:rotate3d(-5,0,0,60deg)"></div>
<div class="box" style="transform:rotateX(60deg)"></div>
From this we can also conclude that rotate3d(0, Y, 0, a) is the same as rotateY(a) and rotate3d(0, 0, Y, a) the same as rotate(a). Note the use of 0 in two of the coordinates which will make our vector always in the same axis (X or Y or Z)
rotate3d(1,1,0, 45deg) is not the same as rotateX(45deg) rotateY(45deg). The first one will perform one rotation around the vector defined by (1,1,0) and the second one will perform two consecutive rotation around the X and Y axis.
In other words, rotate3d() is not a combination of the other rotation but a rotation on its own. The other rotation are particular cases of rotate3d() considering predefined axis.
The multiplier trick apply to the coordinate if you keep the same angle. rotate3d(x, y, z, a) is equivalent to rotate3d(p*x, p*y, p*z, a) because if you multiply all the coordinates with the same value, you keep the same vector direction and you change only the vector dimension which is irrelevant when defining the rotation. Only the direction is relevant.
More details here: https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate3d
You can clearly notice that using values in the range of [-1,1] for x,y,z is enough to define all the combination. In the other hand, any combination of x,y,z can be reduced to values inside the range [-1,1]
Examples:
.box {
margin:30px;
padding:20px;
background:red;
display:inline-block;
}
<div class="box" style="transform:rotate3d(10,5,-9,60deg)"></div>
<div class="box" style="transform:rotate3d(1,0.5,-0.9,60deg)"></div>
<div class="box" style="transform:rotate3d(25,-5,-8,60deg)"></div>
<div class="box" style="transform:rotate3d(1,-0.2,-0.32,60deg)"></div>
We simply divide by the biggest number.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60465621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to count word frequency of words in dictionary? I have a dictionary like below:
[{'mississippi': 1, 'worth': 1, 'reading': 1}, {'commonplace': 1, 'river': 1, 'contrary': 1, 'ways': 1, 'remarkable': 1}, {'considering': 1, 'missouri': 1, 'main': 1, 'branch': 1, 'longest': 1, 'river': 1, 'world--four': 1}, {'seems': 1, 'safe': 1, 'crookedest': 1, 'river': 1, 'part': 1, 'journey': 1, 'uses': 1, 'cover': 1, 'ground': 1, 'crow': 1, 'fly': 1, 'six': 1, 'seventy-five': 1}, {'discharges': 1, 'water': 1, 'st': 1}, {'lawrence': 1, 'twenty-five': 1, 'rhine': 1, 'thirty-eight': 1, 'thames': 1}, {'river': 1, 'vast': 1, 'drainage-basin:': 1, 'draws': 1, 'water': 1, 'supply': 1, 'twenty-eight': 1, 'states': 1, 'territories': 1, 'delaware': 1, 'atlantic': 1, 'seaboard': 1, 'country': 1, 'idaho': 1, 'pacific': 1, 'slope--a': 1, 'spread': 1, 'forty-five': 1, 'degrees': 1, 'longitude': 1}, {'mississippi': 1, 'receives': 1, 'carries': 1, 'gulf': 1, 'water': 1, 'fifty-four': 1, 'subordinate': 1, 'rivers': 1, 'navigable': 1, 'steamboats': 1, 'hundreds': 1, 'flats': 1, 'keels': 1}, {'area': 1, 'drainage-basin': 1, 'combined': 1, 'areas': 1, 'england': 1, 'wales': 1, 'scotland': 1, 'ireland': 1, 'france': 1, 'spain': 1, 'portugal': 1, 'germany': 1, 'austria': 1, 'italy': 1, 'turkey': 1, 'almost': 1, 'wide': 1, 'region': 1, 'fertile': 1, 'mississippi': 1, 'valley': 1, 'proper': 1, 'exceptionally': 1}]
And I want to change it to my desired output like below to calculate score of similarity between two target words:
river 4
ground: 1
journey: 1
longitude: 1
main: 1
world--four: 1
contrary: 1
cover: 1
delaware: 1
remarkable: 1
vast: 1
forty-five: 1
crookedest: 1
territories: 1
spread: 1
country: 1
longest: 1
fly: 1
atlantic: 1
crow: 1
supply: 1
seems: 1
idaho: 1
seaboard: 1
states: 1
ways: 1
degrees: 1
part: 1
twenty-eight: 1
pacific: 1
branch: 1
water: 1
considering: 1
six: 1
safe: 1
commonplace: 1
draws: 1
drainage-basin: 1
uses: 1
seventy-five: 1
slope--a: 1
missouri: 1
mississippi 3
area: 1
steamboats: 1
germany: 1
reading: 1
france: 1
proper: 1
fifty-four: 1
turkey: 1
exceptionally: 1
areas: 1
carries: 1
combined: 1
flats: 1
receives: 1
england: 1
italy: 1
scotland: 1
wales: 1
almost: 1
navigable: 1
austria: 1
region: 1
wide: 1
spain: 1
subordinate: 1
drainage-basin: 1
hundreds: 1
keels: 1
portugal: 1
water: 1
gulf: 1
ireland: 1
rivers: 1
valley: 1
fertile: 1
worth: 1
water 3
steamboats: 1
spread: 1
country: 1
states: 1
longitude: 1
fifty-four: 1
pacific: 1
vast: 1
subordinate: 1
carries: 1
keels: 1
flats: 1
supply: 1
receives: 1
atlantic: 1
forty-five: 1
river: 1
rivers: 1
idaho: 1
mississippi: 1
seaboard: 1
navigable: 1
discharges: 1
degrees: 1
twenty-eight: 1
drainage-basin: 1
hundreds: 1
st: 1
gulf: 1
draws: 1
delaware: 1
territories: 1
slope--a: 1
drainage-basin 2
area: 1
spread: 1
country: 1
states: 1
mississippi: 1
longitude: 1
france: 1
proper: 1
vast: 1
turkey: 1
forty-five: 1
areas: 1
combined: 1
germany: 1
exceptionally: 1
valley: 1
supply: 1
fertile: 1
atlantic: 1
italy: 1
river: 1
idaho: 1
wales: 1
almost: 1
seaboard: 1
spain: 1
austria: 1
region: 1
degrees: 1
twenty-eight: 1
wide: 1
england: 1
portugal: 1
water: 1
ireland: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
scotland: 1
slope--a: 1
area 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
england: 1
turkey: 1
exceptionally: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
journey 1
ground: 1
seems: 1
part: 1
cover: 1
crow: 1
crookedest: 1
six: 1
safe: 1
uses: 1
seventy-five: 1
river: 1
fly: 1
seems 1
ground: 1
journey: 1
part: 1
cover: 1
crow: 1
crookedest: 1
six: 1
safe: 1
uses: 1
seventy-five: 1
river: 1
fly: 1
states 1
spread: 1
country: 1
degrees: 1
longitude: 1
twenty-eight: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
slope--a: 1
river: 1
idaho: 1
slope--a 1
spread: 1
country: 1
states: 1
degrees: 1
longitude: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
twenty-eight: 1
river: 1
idaho: 1
remarkable 1
contrary: 1
river: 1
commonplace: 1
ways: 1
vast 1
spread: 1
country: 1
states: 1
degrees: 1
longitude: 1
twenty-eight: 1
drainage-basin: 1
pacific: 1
forty-five: 1
water: 1
seaboard: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
slope--a: 1
river: 1
idaho: 1
forty-five 1
spread: 1
longitude: 1
country: 1
states: 1
degrees: 1
slope--a: 1
drainage-basin: 1
vast: 1
pacific: 1
water: 1
seaboard: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
twenty-eight: 1
river: 1
idaho: 1
crookedest 1
ground: 1
journey: 1
seems: 1
part: 1
cover: 1
crow: 1
six: 1
safe: 1
uses: 1
seventy-five: 1
river: 1
fly: 1
carries 1
mississippi: 1
steamboats: 1
navigable: 1
fifty-four: 1
keels: 1
hundreds: 1
subordinate: 1
water: 1
gulf: 1
flats: 1
rivers: 1
receives: 1
germany 1
area: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
longest 1
main: 1
river: 1
world--four: 1
branch: 1
missouri: 1
considering: 1
flats 1
mississippi: 1
steamboats: 1
navigable: 1
carries: 1
fifty-four: 1
keels: 1
hundreds: 1
subordinate: 1
water: 1
gulf: 1
rivers: 1
receives: 1
supply 1
spread: 1
longitude: 1
country: 1
states: 1
degrees: 1
slope--a: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
twenty-eight: 1
river: 1
idaho: 1
receives 1
mississippi: 1
steamboats: 1
navigable: 1
carries: 1
fifty-four: 1
keels: 1
hundreds: 1
subordinate: 1
water: 1
gulf: 1
flats: 1
rivers: 1
crow 1
ground: 1
journey: 1
seems: 1
part: 1
cover: 1
crookedest: 1
six: 1
safe: 1
uses: 1
seventy-five: 1
river: 1
fly: 1
scotland 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
combined: 1
spain: 1
italy: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
country 1
spread: 1
idaho: 1
states: 1
degrees: 1
longitude: 1
twenty-eight: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
slope--a: 1
river: 1
thames 1
thirty-eight: 1
rhine: 1
lawrence: 1
twenty-five: 1
england 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
region: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
navigable 1
mississippi: 1
steamboats: 1
carries: 1
fifty-four: 1
keels: 1
hundreds: 1
subordinate: 1
water: 1
gulf: 1
flats: 1
rivers: 1
receives: 1
austria 1
area: 1
germany: 1
mississippi: 1
france: 1
proper: 1
region: 1
turkey: 1
england: 1
areas: 1
combined: 1
exceptionally: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
rhine 1
thirty-eight: 1
thames: 1
lawrence: 1
twenty-five: 1
part 1
ground: 1
journey: 1
seems: 1
cover: 1
crow: 1
crookedest: 1
six: 1
safe: 1
uses: 1
seventy-five: 1
river: 1
fly: 1
twenty-eight 1
spread: 1
country: 1
states: 1
degrees: 1
longitude: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
slope--a: 1
river: 1
idaho: 1
branch 1
main: 1
longest: 1
river: 1
world--four: 1
missouri: 1
considering: 1
hundreds 1
mississippi: 1
steamboats: 1
navigable: 1
carries: 1
fifty-four: 1
keels: 1
subordinate: 1
water: 1
gulf: 1
flats: 1
rivers: 1
receives: 1
st 1
water: 1
discharges: 1
considering 1
main: 1
longest: 1
river: 1
world--four: 1
branch: 1
missouri: 1
six 1
ground: 1
journey: 1
seems: 1
part: 1
cover: 1
crow: 1
crookedest: 1
fly: 1
safe: 1
uses: 1
seventy-five: 1
river: 1
gulf 1
mississippi: 1
steamboats: 1
navigable: 1
carries: 1
fifty-four: 1
keels: 1
hundreds: 1
subordinate: 1
water: 1
flats: 1
rivers: 1
receives: 1
ireland 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
valley: 1
safe 1
ground: 1
journey: 1
seems: 1
part: 1
cover: 1
crow: 1
crookedest: 1
six: 1
uses: 1
seventy-five: 1
river: 1
fly: 1
commonplace 1
contrary: 1
river: 1
remarkable: 1
ways: 1
draws 1
spread: 1
longitude: 1
country: 1
states: 1
degrees: 1
slope--a: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
supply: 1
delaware: 1
territories: 1
atlantic: 1
twenty-eight: 1
river: 1
idaho: 1
delaware 1
spread: 1
longitude: 1
country: 1
states: 1
degrees: 1
slope--a: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
draws: 1
territories: 1
atlantic: 1
supply: 1
twenty-eight: 1
river: 1
idaho: 1
thirty-eight 1
thames: 1
rhine: 1
lawrence: 1
twenty-five: 1
longitude 1
spread: 1
country: 1
states: 1
degrees: 1
slope--a: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
twenty-eight: 1
river: 1
idaho: 1
world--four 1
main: 1
longest: 1
river: 1
branch: 1
missouri: 1
considering: 1
lawrence 1
thirty-eight: 1
thames: 1
rhine: 1
twenty-five: 1
ground 1
journey: 1
seems: 1
part: 1
cover: 1
crow: 1
crookedest: 1
six: 1
safe: 1
uses: 1
seventy-five: 1
river: 1
fly: 1
steamboats 1
mississippi: 1
navigable: 1
carries: 1
fifty-four: 1
keels: 1
hundreds: 1
subordinate: 1
water: 1
gulf: 1
flats: 1
rivers: 1
receives: 1
spread 1
seaboard: 1
country: 1
states: 1
degrees: 1
longitude: 1
twenty-eight: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
slope--a: 1
river: 1
idaho: 1
idaho 1
spread: 1
country: 1
states: 1
degrees: 1
longitude: 1
twenty-eight: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
slope--a: 1
river: 1
reading 1
mississippi: 1
worth: 1
almost 1
area: 1
germany: 1
austria: 1
france: 1
proper: 1
england: 1
turkey: 1
exceptionally: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
mississippi: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
contrary 1
river: 1
remarkable: 1
commonplace: 1
ways: 1
cover 1
ground: 1
journey: 1
seems: 1
part: 1
crow: 1
crookedest: 1
six: 1
safe: 1
uses: 1
seventy-five: 1
river: 1
fly: 1
france 1
area: 1
germany: 1
austria: 1
mississippi: 1
proper: 1
england: 1
turkey: 1
exceptionally: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
spain 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
combined: 1
scotland: 1
italy: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
pacific 1
spread: 1
longitude: 1
country: 1
states: 1
degrees: 1
slope--a: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
twenty-eight: 1
river: 1
idaho: 1
turkey 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
england: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
fifty-four 1
mississippi: 1
steamboats: 1
navigable: 1
carries: 1
hundreds: 1
keels: 1
subordinate: 1
water: 1
gulf: 1
flats: 1
rivers: 1
receives: 1
subordinate 1
mississippi: 1
steamboats: 1
navigable: 1
carries: 1
fifty-four: 1
keels: 1
hundreds: 1
water: 1
gulf: 1
flats: 1
rivers: 1
receives: 1
territories 1
spread: 1
idaho: 1
states: 1
degrees: 1
longitude: 1
twenty-eight: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
draws: 1
delaware: 1
supply: 1
atlantic: 1
slope--a: 1
river: 1
country: 1
combined 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
exceptionally 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
england: 1
turkey: 1
region: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
region 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
twenty-five 1
thirty-eight: 1
thames: 1
lawrence: 1
rhine: 1
rivers 1
mississippi: 1
steamboats: 1
navigable: 1
carries: 1
fifty-four: 1
keels: 1
hundreds: 1
subordinate: 1
water: 1
gulf: 1
flats: 1
receives: 1
fly 1
ground: 1
journey: 1
seems: 1
part: 1
cover: 1
crow: 1
crookedest: 1
six: 1
safe: 1
uses: 1
seventy-five: 1
river: 1
atlantic 1
spread: 1
longitude: 1
country: 1
states: 1
degrees: 1
slope--a: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
river: 1
supply: 1
twenty-eight: 1
idaho: 1
italy 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
combined: 1
scotland: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
main 1
world--four: 1
longest: 1
river: 1
branch: 1
missouri: 1
considering: 1
areas 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
england: 1
turkey: 1
exceptionally: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
seaboard 1
spread: 1
country: 1
states: 1
degrees: 1
longitude: 1
twenty-eight: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
slope--a: 1
river: 1
idaho: 1
fertile 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
ways 1
contrary: 1
river: 1
remarkable: 1
commonplace: 1
discharges 1
water: 1
st: 1
degrees 1
spread: 1
country: 1
states: 1
longitude: 1
twenty-eight: 1
drainage-basin: 1
vast: 1
forty-five: 1
water: 1
seaboard: 1
pacific: 1
draws: 1
delaware: 1
territories: 1
atlantic: 1
supply: 1
slope--a: 1
river: 1
idaho: 1
wide 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
proper 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
england: 1
turkey: 1
exceptionally: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
keels 1
mississippi: 1
steamboats: 1
navigable: 1
water: 1
fifty-four: 1
hundreds: 1
subordinate: 1
carries: 1
gulf: 1
flats: 1
rivers: 1
receives: 1
portugal 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
ireland: 1
valley: 1
worth 1
mississippi: 1
reading: 1
uses 1
ground: 1
journey: 1
seems: 1
part: 1
cover: 1
crow: 1
crookedest: 1
six: 1
safe: 1
fly: 1
seventy-five: 1
river: 1
seventy-five 1
ground: 1
journey: 1
seems: 1
part: 1
cover: 1
crow: 1
crookedest: 1
six: 1
safe: 1
uses: 1
river: 1
fly: 1
valley 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
wales: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
missouri 1
main: 1
longest: 1
river: 1
branch: 1
world--four: 1
considering: 1
wales 1
area: 1
germany: 1
austria: 1
mississippi: 1
france: 1
proper: 1
exceptionally: 1
turkey: 1
england: 1
areas: 1
combined: 1
scotland: 1
italy: 1
spain: 1
almost: 1
fertile: 1
region: 1
wide: 1
drainage-basin: 1
portugal: 1
ireland: 1
valley: 1
the first line is the target word and its frequency in the whole dictionary. Underneath is the associated words and their frequency in same sentence with target word. Like the first dictionary, the profile associated with "mississippi" will contain references to "worth" and "reading" and their word frequency in sentence is 1, but the word frequency of mississippi is 3 in entire dictionary. And I want to sort the word frequency of target word in descending order. Anyone can help?
A: It's not exactly clear neither from your desired output nor from your code what exactly are you trying to achieve but if it's just counting words in individual sentences then the strategy should be:
*
*Read your common.txt into a set for a fast lookup.
*Read your sample.txt and split on . to get individual sentences.
*Clear up all non-word characters (you'll have to define them or to use regex \b to capture word boundaries) and replace them with whitespace.
*Split on whitespace and count the words not present in the set from Step 1.
So:
import collections
with open("common.txt", "r") as f: # open the `common.txt` for reading
common_words = {l.strip().lower() for l in f} # read each line and and add it to a set
interpunction = ";,'\"" # define word separating characters and create a translation table
trans_table = str.maketrans(interpunction, " " * len(interpunction))
sentences_counter = [] # a list to hold a word count for each sentence
with open("sample.txt", "r") as f: # open the `sample.txt` for reading
# read the whole file to include linebreaks and split on `.` to get individual sentences
sentences = [s for s in f.read().split(".") if s.strip()] # ignore empty sentences
for sentence in sentences: # iterate over each sentence
sentence = sentence.translate(trans_table) # replace the interpunction with spaces
word_counter = collections.defaultdict(int) # a string:int default dict for counting
for word in sentence.split(): # split the sentence and iterate over the words
if word.lower() not in common_words: # count only words not in the common.txt
word_counter[word.lower()] += 1
sentences_counter.append(word_counter) # add the current sentence word count
NOTE: On Python 2.x use string.maketrans() instead of str.maketrans().
This will produce sentences_counter containing a dictionary count for each of the sentences in sample.txt, where the key is an actual word and its associate value is the word count. You can print the result as:
for i, v in enumerate(sentences_counter):
print("Sentence #{}:".format(i+1))
print("\n".join("\t{}: {}".format(w, c) for w, c in v.items()))
Which will produce (for your sample data):
Sentence #1:
area: 1
drainage-basin: 1
great: 1
combined: 1
areas: 1
england: 1
wales: 1
wide: 1
region: 1
fertile: 1
Sentence #2:
mississippi: 1
valley: 1
proper: 1
exceptionally: 1
Keep in mind that (English) language is more complex than this - for example, "A cat wiggles its tail when it's angry so stay away from it." will vastly differ in dependence on how you treat an apostrophe. Also, a dot doesn't necessarily denote the end of a sentence. You should look into NLP if you want to do serious linguistic analysis.
UPDATE: While i don't see the usefulness of reiterating over each word repeating the data (the count won't ever change within a sentence) if you want to print each word and nest all the other counts underneath you can just add an inner loop while printing:
for i, v in enumerate(sentences_counter):
print("Sentence #{}:".format(i+1))
for word, count in v.items():
print("\t{} {}".format(word, count))
print("\n".join("\t\t{}: {}".format(w, c) for w, c in v.items() if w != word))
Which will give you:
Sentence #1:
area 1
drainage-basin: 1
great: 1
combined: 1
areas: 1
england: 1
wales: 1
wide: 1
region: 1
fertile: 1
drainage-basin 1
area: 1
great: 1
combined: 1
areas: 1
england: 1
wales: 1
wide: 1
region: 1
fertile: 1
great 1
area: 1
drainage-basin: 1
combined: 1
areas: 1
england: 1
wales: 1
wide: 1
region: 1
fertile: 1
combined 1
area: 1
drainage-basin: 1
great: 1
areas: 1
england: 1
wales: 1
wide: 1
region: 1
fertile: 1
areas 1
area: 1
drainage-basin: 1
great: 1
combined: 1
england: 1
wales: 1
wide: 1
region: 1
fertile: 1
england 1
area: 1
drainage-basin: 1
great: 1
combined: 1
areas: 1
wales: 1
wide: 1
region: 1
fertile: 1
wales 1
area: 1
drainage-basin: 1
great: 1
combined: 1
areas: 1
england: 1
wide: 1
region: 1
fertile: 1
wide 1
area: 1
drainage-basin: 1
great: 1
combined: 1
areas: 1
england: 1
wales: 1
region: 1
fertile: 1
region 1
area: 1
drainage-basin: 1
great: 1
combined: 1
areas: 1
england: 1
wales: 1
wide: 1
fertile: 1
fertile 1
area: 1
drainage-basin: 1
great: 1
combined: 1
areas: 1
england: 1
wales: 1
wide: 1
region: 1
Sentence #2:
mississippi 1
valley: 1
proper: 1
exceptionally: 1
valley 1
mississippi: 1
proper: 1
exceptionally: 1
proper 1
mississippi: 1
valley: 1
exceptionally: 1
exceptionally 1
mississippi: 1
valley: 1
proper: 1
Feel free to remove the sentence number printing and reduce one of the tab indentations to get something more of a desired output from your question. You can also build a tree-like dictionary instead of printing everything to the STDOUT if that's more what you fancy.
UPDATE 2: If you want, you don't have to use a set for the common_words. In this case it's pretty much interchangeable with a list so you can use list comprehension instead of set comprehension (i.e. replace curly with square brackets) but looking through a list is an O(n) operation whereas set lookup is an O(1) operation and therefore a set is preferred here. Not to mention the collateral benefit of automatic de-duplication in case the common.txt has duplicate words.
As for the collections.defaultdict() it's there just to save us some coding/checking by automatically initializing the dictionary to a key whenever it's requested - without it you'd have to do it manually:
with open("common.txt", "r") as f: # open the `common.txt` for reading
common_words = {l.strip().lower() for l in f} # read each line and and add it to a set
interpunction = ";,'\"" # define word separating characters and create a translation table
trans_table = str.maketrans(interpunction, " " * len(interpunction))
sentences_counter = [] # a list to hold a word count for each sentence
with open("sample.txt", "r") as f: # open the `sample.txt` for reading
# read the whole file to include linebreaks and split on `.` to get individual sentences
sentences = [s for s in f.read().split(".") if s.strip()] # ignore empty sentences
for sentence in sentences: # iterate over each sentence
sentence = sentence.translate(trans_table) # replace the interpunction with spaces
word_counter = {} # initialize a word counting dictionary
for word in sentence.split(): # split the sentence and iterate over the words
word = word.lower() # turn the word to lowercase
if word not in common_words: # count only words not in the common.txt
word_counter[word] = word_counter.get(word, 0) + 1 # increase the last count
sentences_counter.append(word_counter) # add the current sentence word count
UPDATE 3: If you just want a raw word list across all sentences as it seems from your last update to the question, you don't even need to consider the sentences themselves - just add a dot to the interpunction list, read the file line by line, split on whitespace and count the words as before:
import collections
with open("common.txt", "r") as f: # open the `common.txt` for reading
common_words = {l.strip().lower() for l in f} # read each line and and add it to a set
interpunction = ";,'\"." # define word separating characters and create a translation table
trans_table = str.maketrans(interpunction, " " * len(interpunction))
sentences_counter = [] # a list to hold a word count for each sentence
word_counter = collections.defaultdict(int) # a string:int default dict for counting
with open("sample.txt", "r") as f: # open the `sample.txt` for reading
for line in f: # read the file line by line
for word in line.translate(trans_table).split(): # remove interpunction and split
if word.lower() not in common_words: # count only words not in the common.txt
word_counter[word.lower()] += 1 # increase the count
print("\n".join("{}: {}".format(w, c) for w, c in word_counter.items())) # print the counts
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50334763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ngTable with ng-if is not working I'm using ng-table with angularJs as shown below.My problem is when I use ngTable it's rendered same column twice (MyColumn).In other words it doesn't consider the ng-if.How can I get rid of that issue ?
Note : But for the normal table it's working fine.Why is that not working with the ngTable ?
ngTable
<table ng-table="TableParams" class="table" template-pagination="custom/pager">
<tr ng-repeat="item in My.Items">
<td ng-if="(item.Value | uppercase) == 'NO'" data-title="'MyColumn'" sortable="'Value'">{{item.Value}}</td>
<td ng-if="(item.Value | uppercase) == 'YES'" data-title="'MyColumn'" sortable="'Value'">{{item.Value}}</td>
</tr>
</table>
A: I did it as shown below.It works fine. Hurray :D
<tr ng-repeat="item in My.Items">
<td data-title="'MyColumn'" sortable="'Value'">
<span ng-if="(item.Value | uppercase) == 'NO'">{{item.Value}}</span>
<span ng-if="(item.Value | uppercase) == 'YES'">{{item.Value}}</span>
</td>
</tr>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25991645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get the searched text in a string? I want to get a text that it is a part of an string.For example: I have a string like "I am Vahid" and I want to get everything that it's after "am".
The result will be "Vahid"
How can I do it?
A: Try:
Example1
String[] separated = CurrentString.split("am");
separated[0]; // I am
separated[1]; // Vahid
Example2
StringTokenizer tokens = new StringTokenizer(CurrentString, "am");
String first = tokens.nextToken();// I am
String second = tokens.nextToken(); //Vahid
A: Try:
String text = "I am Vahid";
String after = "am";
int index = text.indexOf(after);
String result = "";
if(index != -1){
result = text.substring(index + after.length());
}
System.out.print(result);
A: Just use like this, call the method with your string.
public String trimString(String stringyouwanttoTrim)
{
if(stringyouwanttoTrim.contains("I am")
{
return stringyouwanttoTrim.split("I am")[1].trim();
}
else
{
return stringyouwanttoTrim;
}
}
A: If you prefer to split your sentence by blank space you could do like this :
String [] myStringElements = "I am Vahid".split(" ");
System.out.println("your name is " + myStringElements[myStringElements.length - 1]);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33274880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: sending mail in php with user informations hii evryone plz i need help i want to know why my code send only the attachment but not the others informations of my contact form here is my code php
here is my code the attachement is sent correctly but the other
informations not i dont using any framework it is just php
i use a contact form with attachement
error_reporting(E_ALL);
ini_set("display_errors", 1); //Affichage des erreurs
//Eviter les insertions de scripts dans le cas d'un e-mail HTML
$nom = htmlentities($_POST['firstname']);
$email = htmlentities($_POST['email']);
$nom=$_POST['firstname'];
//$prenom = htmlentities($_POST['prenom']);
//Verifie si le fournisseur prend en charge les r
if(preg_match("#@(hotmail|live|msn).[a-z]{2,4}$#", $email)){
$passage_ligne = "\n";
}else{
$passage_ligne = "\r\n";
}
$email_to = "mon adresse email"; //Destinataire
$email_subject = "Recrutement "; //Sujet du mail
$boundary = md5(rand()); // clé aléatoire de limite
$headers = "MIME-Version: 1.0\r\n";
$headers.= "From: EA\r\n";
$headers.= "Reply-To: EITA" . "\r\n";
$headers.= "MIME-Version: 1.0" . $passage_ligne;
$headers.= 'Content-Type: multipart/mixed; boundary='.$boundary .' '.
$passage_ligne;
//Pièce jointe
if(isset($_FILES["fichier"]) && $_FILES['fichier']['name'] != ""){
//Vérifie sur formulaire envoyé et que le fichier existe
$nom_fichier = $_FILES['fichier']['name'];
$source = $_FILES['fichier']['tmp_name'];
$type_fichier = $_FILES['fichier']['type'];
$taille_fichier = $_FILES['fichier']['size'];
if($nom_fichier != ".htaccess"){ //Vérifie que ce n'est pas un .htaccess
if($type_fichier == "image/jpeg"
|| $type_fichier == "image/pjpeg"
|| $type_fichier == "application/pdf"){ //Soit un jpeg soit un pdf
if ($taille_fichier <= 2097152) { //Taille supérieure à Mo (en octets)
$tabRemplacement = array("é"=>"e", "è"=>"e", "à"=>"a"); //Remplacement des
caractères spéciaux
$handle = fopen($source, 'r'); //Ouverture du fichier
$content = fread($handle, $taille_fichier); //Lecture du fichier
$encoded_content = chunk_split(base64_encode($content)); //Encodage
$f = fclose($handle); //Fermeture du fichier
//$message.='--'.$passage_ligne."\r\n";
$email_message.="Content-Type: pdf; name=".$nom_fichier."\r\n";
$email_message.="Content-Transfer-Encoding: BASE64"."\r\n";
$email_message.="Content-Disposition: attachment;
filename=".$nom_fichier."\r\n\r\n";
$email_message.=
chunk_split(base64_encode(file_get_contents($nom_fichier)))."\r\n";
$email_message.='--'.$passage_ligne.'--'."\r\n";
$email_message .= $encoded_content."n"; //Pièce jointe
//$email_message .="Hello";
}else{
//Message d'erreur
$email_message .= $passage_ligne ."L'utilisateur a tenté de vous envoyer
une pièce jointe mais celle ci était superieure à 2Mo.". $passage_ligne;
}
}else{
//Message d'erreur
$email_message .= $passage_ligne ."L'utilisateur a tenté de vous envoyer
une pièce jointe mais elle n'était pas au bon format.". $passage_ligne;
}
}else{
//Message d'erreur
$email_message .= $passage_ligne ."L'utilisateur a tenté de vous envoyer
une pièce jointe .htaccess.". $passage_ligne;
}
}
$email_message .= $passage_ligne . "--" . $boundary . "--" .
$passage_ligne; //Séparateur de fermeture
$msg.=$email_message.$nom."bonjour";
if(mail($email_to,$email_subject, $msg, $headers)==true){ //Envoi du mail
header('Location: index.php'); //Redirection
}
?>
| {
"language": "fr",
"url": "https://stackoverflow.com/questions/50481354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Expose Serializable Enum attributes in WCF I am trying to to expose an Enum from my WCF class (basically as a mechanism for passing a constant). When I look at the service reference code or the WSDL there is no sign of the Enum and I cannot use it. Why not?
[Serializable]
[DataContract]
public class MyRequest
{
[DataContract]
public enum Constants
{
[EnumMember]
MaxMaxArticles = 1000
}
}
A: I suspect you haven't used the enum anywhere in the contract. Unless you have, there is no reason that it would be included in the graph that it builds by walking members from the root contract type. It will not be included just because it is nested: it needs to be actually used somewhere.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27022212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Array becomes undefined after page reload I am working on Angular WebApi. I have a database response on localhost in JSON format.
When I run my application, I can see the array oData. But when I reload the page then oData becomes undefined.
How can I solve this?
Here is my code from the .ts file:
ngOnInit(): void {
this.mydataser.getDbData().subscribe(data => {
this.oData = data;
});
}
public importData() {
console.log(this.oData)
}
Here is my service:
getDbData(): Observable<DataFactory[]> {
return this.http.get<DataFactory[]>("https://localhost:44216/api/dbdata");
}
P.S. I tried to use localstorage but it does not work.
A: Declare data as an empty array; if you don't do it will be undefined until the API response is completed. If you want to know when the response is actually coming just use tap. So If you want to call importData() after API response is received then call this.importData() method inside subscribe like
// declare as empty array
oData = [];
buttonEnabled = false;
ngOnInit(): void {
this.mydataser.getDbData().pipe(
tap(d => this.buttonEnabled = true)
).subscribe(data => {
this.oData = data;
});
}
importData(): void{
console.log(this.o.Data);
}
In template:
<button [disabled]="!buttonEnabled">Import</button>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69498043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WCF Service Interface - XElement vs. XmlElement vs. xml string I am doing some work which requires a WCF Service interface (in C#). The data exchanged (sent and recieved) will be in the xml format --- I cannot use strong datatypes because the interface needs to support multiple clients which have different requirements.
My question is which one of these is preferable:
XElement MyServiceMethod(XElement inputParam 1)
{
XElement retValue;
//
// Operation occurs here
//
return (retValue);
}
vs
XmlElement MyServiceMethod(XmlElement inputParam 1)
{
XmlElement retValue;
//
// Operation occurs here
//
return (retValue);
}
vs
//
//inputParam is an xml formatted string
//
string MyServiceMethod(string inputParam 1)
{
string retValue;
//
// Operation occurs here
//
//retValue is an xml formatted string
return (retValue);
}
The code will be consumed via SOAP interface primarily, though it may ultimately be consumed via REST as well.
Is there a "best" approach"? Likewise, is there one that is completely not desirous.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31075499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to change color of first text box in every row of table using jquery I am trying to change the background color of first text box in every row in a table and using below code for same purpose.
Somehow it does not seem to be working. Please help.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("tr:text:first").css('background-color','#C0C0C0');
});
</script>
</head>
<body>
<table border="1">
<tr>
<th>text1</th>
<td id="A7x1_1"><input type="text"></td>
<td id="A7x2_1"><input type="text"></td>
</tr>
<tr>
<th>text2</th>
<td id="A7x1_2"><input type="text"></td>
<td id="A7x2_2"><input type="text"></td>
</tr>
<tr>
<th>text3</th>
<td id="A7x1_3"><input type="text"></td>
<td id="A7x2_3"><input type="text"></td>
</tr>
</table>
</body>
</html>
A: Use :first selector with .find() to get input descendants.
$('tr').find(':text:first').css('background-color','#C0C0C0');
Demo
$("tr:text:first") in your code, finds tr with :text(type="text") which is invalid.
<tr> does not have :text
A: Have you tried $("tr input:first-child").css('background-color','#C0C0C0'); ?
A: Also, if you can't get jQuery to work, it would be simple enough to add a class to the first table cell in each table row and style it that way, forgoing the time it would take to load jQuery(if that is an issue, as I have sometimes found it to be).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24525894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does Heroku support foreign key and unique constraints? I'm considering moving a Rails app to Heroku.
In general I add FK constraints with ON DELETE behavior to all FKs. Up to now I've done this by writing raw SQL to add the constraints, as Rails Migrations don't provide a way to do that.
I also add UNIQUE keys where needed.
Will I still be able to add constraints in this way if I move to Heroku?
Another way to put this question would be, do I get direct access to my DB with Heroku, or am I limited to what I can do in migrations?
A: You can execute any SQL you want in a migration using connection.execute, for example:
def up
connection.execute(%q{
alter table t add constraint c check (x in ('a', 'b', 'c'))
})
end
def down
connection.execute('alter table t drop constraint c')
end
You can also use foreigner to add proper FK support to your migrations and schema.rb if you don't want to manage your FKs through raw SQL.
You can use the :unique => true option to add_index to get unique constraints/indexes.
I've done all of this and even added functions (both SQL and Pl/pgSQL) and triggers to a dedicated PostgreSQL database at Heroku. I'm not sure how much is supported on the shared databases but unique indexes certainly will be and I'm pretty sure FKs and CHECKs will be available as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10901606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to declare two data types containing same variable in haskell? In a module, I want to add two classes like this.
data Person = Person { name :: String -- and some other details
}
data PetAnimal = PetAnimal { name :: String
}
I assumed this would work but ghc complains about multiple declrations of name. How do I accomplish this?
A: The problem here, I believe, is that Haskell defines access functions for all the fields in a record, so you get one function
name :: Person -> String
and then one
name :: PetAnimal -> String
which is what the compiler does not like.
You could change one or both of the names, or put them in different modules.
A: Type Classes are another way to achieve a common interface that you may consider.
data Person = Person { personname :: String -- and some other details
}
data PetAnimal = PetAnimal { petanimalname :: String
}
class HasName a where
name :: a -> String
instance HasName PetAnimal where
name = petanimalname
instance HasName Person where
name = personname
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42083081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get current latitude and longitude plus 500 meters Hi friends, I am having one event latitude and longitude, To checkin to this event i must be within 500 meters of that event.
I am getting current location using:
Geolocation.getLocation().then(function(position){
$scope.position = position.coords;
// console.log( $scope.position)
$scope.locationError = null;
});
Have to validate this current location with event latitude longitude coming from Api, if this current location is equal to or less than 500 meters then only user is able to checkin, Any help would be great
A: Hypothetically you need the distance between 2 geo locations. From the event geolocation to the the one calculated.
An identical thread from stackoverflow : Calculate distance between 2 GPS coordinates
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40066985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamically load jade templates I'm working on a small documentation website and the content is stored in files. For instance I have two files chapter1.jade and chapter2.jade in a module1/ directory.
I'd like to read the module1/ directory and dynamically include all the chapterX.jade files in it.
I tried to have do directory = fs.readDirSync('module1/') and then in my view:
each item in directory
include item
But jade include doesn't support dynamic values (even `include #{item}) doesn't work. Do you have any idea how I could implement this ?
EDIT: I'd like to generate some code under the each loop (anchor for easy linking) so the solution would preferabily be in the view. I could obviously manually add the anchor in the included files but it is not ideal.
Thanks
A: Here is the short version of what I've done to make it work. It uses the jade Public API.
var directory = __dirname+'/views/bla/'
, files
, renderedHTML = '';
if( !fs.existsSync(directory) ) {
// directory doesn't exist, in my case I want a 404
return res.status(404).send('404 Not found');
}
// get files in the directory
files = fs.readdirSync(directory);
files.forEach(function(file) {
var template = jade.compile(fs.readFileSync(directory+file, 'utf8'));
// some templating
renderedHTML += '<section><a id="'+file+'" name="'+file+'" class="anchor"> </a>'+template()+'</section>';
});
// render the actual view and pass it the pre rendered views
res.render('view', {
title: 'View',
files: files,
html: renderedHTML
})
And the view just renders the html variable unescaped:
div(class="component-doc-wrap")
!{html}
A: As @user1737909 say, that's not possible using just jade.
The best way to do this (tho) is building a little Express Dynamic (view) Helpers
DEPECATED IN EXPRESS 3.XX
Check these: Jade - way to add dynamic includes
A: in addition to kalemas answer you can also write your includes to a file which is included in jade.
in this example I write my includes to include_all.jade. This file is included in a jade file.
If it does not work, check the path ;-)
e.g.
in your app.js
var includes = "path/to/include1\n";
includes += "path/to/include2";
...
incPath = "path/to/include_all.jade";
fs.open(incPath,'w',function(err,fd){
if(err){
throw 'error open file: ' + incPath +" "+ err;
}
var buffer = new Buffer(includes);
fs.write(fd,buffer,0,buffer.length,null,function(err){
if (err)
throw 'error writing file: ' +err;
fs.close(fd,function(){
console.log('file written ' + incPath);
});
});
});
in your jade file
include path/to/include_all.jade
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16723554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WordPress : Form data is not displaying via echo I have created a form to which I am passing the data. When I try to echo the data it shows couple of errors saying that index is undefined.
<?php /* Template Name: Dummy Practice Page*/?>
<div id="main-content" class="main-content">
<div class="main-content-inner">
<form method='post' enctype='multipart/form-data'>
<input id="name" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required><br>
<input id="designation" type="text" style="height:30px; width: 350px; " maxlength="50" placeholder="Designation" required><br>
<input id="description" type="text" style="height:30px; width: 350px; " maxlength="1000" placeholder="Description" required><br>
<input id="pic" type="file" style="height:30px; width: 350px; "><br><br>
<input name="insert" type='submit' style="height:40px; width: 130px; padding:10px; color:dodgerblue; background-color:black; border-radius:20px; " name='Submit' value='Add Member' /><br><br>
</form>
</div>
</div>
<?php
if(isset($_POST['insert']))
{
echo $namevar = isset($_POST['name']);
echo $descriptionvar = isset($_POST['description']);
echo $designationvar = isset($_POST['designation']);
}
?>
Following are the errors:
Notice: Undefined index: name in C:\xampp\htdocs\wordpress\wp-content\themes\twentyfifteen-child\practicepage.php
Notice: Undefined index: description in C:\xampp\htdocs\wordpress\wp-content\themes\twentyfifteen-child\practicepage.php
Notice: Undefined index: designation in C:\xampp\htdocs\wordpress\wp-content\themes\twentyfifteen-child\practicepage.php
A: The issue is with the names of input fields.
In PHP or any other programming language, You should use the input name="something" to get the input values.
You should give the name for each input fields.
For example,
<input name = "name" id="name" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required><br>
A: <form method='post' enctype='multipart/form-data'>
<input name="name" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required><br>
<input name="designation" type="text" style="height:30px; width: 350px; " maxlength="50" placeholder="Designation" required><br>
<input name="description" type="text" style="height:30px; width: 350px; " maxlength="1000" placeholder="Description" required><br>
<input id="pic" type="file" style="height:30px; width: 350px; "><br><br>
<input name="insert" type='submit' style="height:40px; width: 130px; padding:10px; color:dodgerblue; background-color:black; border-radius:20px;" value='Add Member' /><br><br>
</form>
<?php
if(isset($_POST['insert']))
{
echo $namevar = $_POST['name'];
echo $descriptionvar = $_POST['description'];
echo $designationvar = $_POST['designation'];
}
?>
A: You cannot pass POST data to another page vie using ID.
You should give name to <input>
<input name="name">
<input name="description">
<input name="designation">
Edit
You are defining variables and echoing them same time
Change your code to:
<?php
if(isset($_POST["insert"])){
echo $_POST["name"];
echo $_POST["description"];
echo $_POST["designation"];
}?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57603073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: PyMySQL different updates in one query? So I have a python script that goes through roughly 350,000 data objects, and depending on some tests, it needs to update a row which represents each one of those objects in a MySQl db. I'm also using pymysql as I've had the least trouble with it especially when sending over large select queries (select statements with where column IN (....) clause that can contain 100,000+ values).
Since each update for each row can be different, each update statement is different. For example, for one row we might want to update first_name but for another row we want to leave first_name untouched and we want to update last_name.
This is why I don't want to use the cursor.executemany() method which takes in one generic update statement and you then feed it the values however as I mentioned, each update is different so having one generic update statement doesn't really work for my case. I also don't want to send over 350,000 update statements individually over the wire. Is there anyway I can package all of my update statements together and send them at once?
I tried having them all in one query and using the cursor.execute() method but it doesn't seem to update all the rows.
A: Your best performance will be if you can encode your "tests" into the SQL logic itself, so you can boil everything down to a handful of UPDATE statements. Or at least get as many as possible done that way, so that fewer rows need to be updated individually.
For example:
UPDATE tablename set firstname = [some logic]
WHERE [logic that identifies which rows need the firstname updated];
You don't describe much about your tests, so it's hard to be sure. But you can typically get quite a lot of logic into your WHERE clause with a little bit of work.
Another option would be to put your logic into a stored procedure. You'll still be doing 350,000 updates, but at least they aren't all "going over the wire". I would use this only as a last resort, though; business logic should be kept in the application layer whenever possible, and stored procedures make your application less portable.
A: SQL #1: CREATE TABLE t with whatever columns you might need to change. Make all of them NULL (as opposed to NOT NULL).
SQL #2: Do a bulk INSERT (or LOAD DATA) of all the changes needed. Eg, if changing only first_name, fill in id and first_name, but have the other columns NULL.
SQL #3-14:
UPDATE real_table
JOIN t ON t.id = real_table.id
SET real_table.first_name = t.first_name
WHERE t.first_name IS NOT NULL;
# ditto for each other column.
All SQLs except #1 will be time-consuming. And, since UPDATE needs to build a undo log, it could timeout or otherwise be problematical. See a discussion of chunking if necessary.
If necessary, use functions such as COALESCE(), GREATEST(), IFNULL(), etc.
Mass UPDATEs usually imply poor schema design.
(If Ryan jumps in with an 'Answer' instead of just a 'Comment', he should probably get the 'bounty'.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35139294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Is it possible to apply dbt seed configurations to all projects that use a given package? I built a dbt package for internal use. I'd like to specify the seed configurations in the dbt_project.yml of that package, and have those configurations apply to all projects that use the package. So far, I'm not sure if there's an issue with my syntax or if this just isn't possible.
The package dbt_project.yml includes the following:
seeds:
seed_name:
+quote_columns: false
+column_types:
column_name: varchar(127)
In a project that uses this package, there is a file data/seed_name.csv. When I run dbt seed for that project, I want the configuration defined in the package to apply to this seed. Instead, it seems to be ignored. To be clear, the .csv is included in the project that uses the package, not in the package itself.
It works if I move the above code out of the package and into the project-specific dbt_project.yml. However, this would mean that anyone using my package needs to copy that code into their file, which I'd prefer to avoid.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67005921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: My app runs perfectly while running it on eclipse but maps disapear and it crashes on some actvitys after export Hw can this happen and be solved?
My app runs perfectly while on eclipse, I tried everything before exporting the app.
When I exported the app, the maps showed a grey area and the app crashed while loading one activity.
Running on eclipse none of this happens.
Is this because of the prograd configuration?
How can I debug an exported app?
A: To resolve the Maps grey area issue do the following:
*
*Open Google Developers Console
*Select the project you are working on (or create it if it doesn't exist)
*Select APIs & Auth
*Then Credentials
*Find the section with the title "Key for Android applications"
*Click Edit allowed Android applications
*Execute the keytool command to generate the SHA1 fingerprint for your release keystore file
*Then add the SHA1 and package name to the list of allowed Android applications
And for the crashes, try using crash reporting tool (Crashlytics for example)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26743066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using data (not METAdata) from a SSMS DB to drive biml in SSIS dtsx creation I need to be able to generate tasks in a data flow of a SSIS dtsx based on data stored in a SSMS DB table.
Basically, I have N (unknown, variable) sources and M (unknown, variable) destinations and I have a table T0 with MxN rows. Each row, using a bit B, specifies if I really need to send data from that specific source to that specific destination.
T0 is stored in a basic Database DB0 that is used for configuration.
Ideally, using BIML I want to script a dtsx that has a simple data flow (OLEDB Source -> OLEDB destination) FOR EACH row of T0 with B = 1.
This dtsx generation must be driven by the data i find in T0.
Online I can find how to read METADATA from a DB but I can't find anyone talking about the much basic "reading data from a DB" and using these data in the BIML.
Do I need to handle the DB connection in the C# code in BIMLScript? How do I use/address the connection to DB0 in the c# code? (usually I would have this connection in a config file... in this case I need to refer to the connMgr from the C# script).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42370455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to create table in Oracle I want to create a table in Oracle using the below syntax using %type
Create table emp_avg
(
emp_id HR.employees.emp_id%type,
dept_id HR.employees.dep_id%type
):
When I tried executing it is throwing an error.
A: The given code is not valid. Try the below code.
Create table emp_avg as
Select e.employee_id, e.department_id from HR.employees e where 1=0;
A: That's not valid syntax. The point of an anchored type declaration (the %type syntax) in PL/SQL is that when the underlying data type changes, the PL/SQL code uses the new type automatically. But that doesn't work when you're defining a table where Oracle has to know the actual data type when it writes a data block to disk and can't just dynamically recompile the table when the parent data type changes. When you create a table, you have to specify actual data types.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68781381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: SQLSRV to Excel using php - Missing zero's in data cells I am using SQLSRV to download the data from server to excel based on requirement
When i display the data its fine, but when i try to download using
header("Content-type: application/vnd-ms-excel") the leading zero in the integer are missing.
For example '0012346' gets converted into '12346'.
In my results file i need leading zeros also like - '0012346'.
How can i achieve it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35361645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make checkbox.Checked = True whose corresponding PictureBox is clicked I have 28 CheckBoxes in a windows form. Each box has PictureBox above it. When the user clicks on a PictureBox, I want to change the BackColor of the PictureBox to green, and make its corresponding CheckBox.Checked = True
The code I am using:
Private Sub PictureBox1_Click
PictureBox1.BackColor = Color. Green
CheckBox1.Checked = true
For 28 it will be a lengthy process. Is there any easy solution?
A: Programmatically add MouseClick even handlers to all your PictureBoxes in Form_Load. The event handler will parse the sender (PictureBox) and find the CheckBox based on the fact that the corresponding controls' names end in the same index. Remove the handlers when the form closes.
Private pictureBoxPrefix As String = "PictureBox"
Private checkBoxPrefix As String = "CheckBox"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
AddHandler pb.MouseClick, AddressOf PictureBox_MouseClick
Next
End Sub
Private Sub PictureBox_MouseClick(sender As Object, e As MouseEventArgs)
Dim index = Integer.Parse(pb.Name.Replace(pictureBoxPrefix, ""))
Dim pb = CType(sender, PictureBox)
Dim cb = CType(Me.Controls.Find($"{checkBoxPrefix}{index}", True).First(), CheckBox)
pb.BackColor = Color.Green
cb.Checked = True
End Sub
Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
RemoveHandler pb.MouseClick, AddressOf PictureBox_MouseClick
Next
End Sub
A: In the Load() event of your form, use Controls.Find() to get a reference to both the PictureBoxes and CheckBoxes. Store the CheckBox reference in the Tag() property of each PictureBox. Wire up the Click() event of you PB. In that event, change the color of the PB, then retrieve the CheckBox from the Tag() property and check the box as well:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 1 To 28
Dim PB As PictureBox = Me.Controls.Find("PictureBox" & i, True).FirstOrDefault
Dim CB As CheckBox = Me.Controls.Find("CheckBox" & i, True).FirstOrDefault
If Not IsNothing(PB) AndAlso Not IsNothing(CB) Then
PB.Tag = CB
CB.Tag = PB
AddHandler PB.Click, AddressOf PB_Click
AddHandler CB.CheckedChanged, AddressOf CB_CheckedChanged
End If
Next
End Sub
Private Sub PB_Click(sender As Object, e As EventArgs)
Dim pb As PictureBox = DirectCast(sender, PictureBox)
Dim cb As CheckBox = DirectCast(pb.Tag, CheckBox)
If pb.BackColor.Equals(Color.Green) Then
pb.BackColor = Color.Empty
cb.Checked = False
Else
pb.BackColor = Color.Green
cb.Checked = True
End If
End Sub
Private Sub CB_CheckedChanged(sender As Object, e As EventArgs)
Dim cb As CheckBox = DirectCast(sender, CheckBox)
Dim pb As PictureBox = DirectCast(cb.Tag, PictureBox)
pb.BackColor = If(cb.Checked, Color.Green, Color.Empty)
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56260470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: User List with Role in .Net Core 3.1 Identity Can I get a list of all the users with the associated roles in .Net Core 3.1 from Identity? I haven't found any solution that works.
A: You need to customize Identity Model and add navigation properties.
public class ApplicationUser : IdentityUser
{
public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
}
and then add required configuration.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>(b =>
{
// Each User can have many entries in the UserRole join table
b.HasMany(e => e.UserRoles)
.WithOne(e => e.User)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
});
modelBuilder.Entity<ApplicationRole>(b =>
{
// Each Role can have many entries in the UserRole join table
b.HasMany(e => e.UserRoles)
.WithOne(e => e.Role)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
});
}
and then you can use joins to query users with roles. More information on adding navigation proprieties can be found here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62947889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MomentJS - Intended for input validation? Is MomentJS intended for user input parsing?
I've got moderately close with the easy cases, having it accept dates in the DDMMYYYY order, and it handles some variation.
It doesn't handle invalid dates particularly well when specifying the format - Including having day values too high, or switching year values between 2 and 4 digit.
Examples of year interpretation:
var date1 = moment('30082012', 'DDMMYYYY');
var date2 = moment('30082012', 'DDMMYY'); // Gives wrong year - 2020
var date3 = moment('300812', 'DDMMYYYY'); // Gives wrong year - 1900
var date4 = moment('300812', 'DDMMYY');
Examples of what would hopefully be invalid dates:
var date5 = moment('08302012', 'DDMMYYYY'); // Gives Jun 08 2014
var date6 = moment('08302012', 'DDMMYY'); // Gives Jun 08 2022
var date7 = moment('083012', 'DDMMYYYY'); // Gives Jun 08 1902
var date8 = moment('083012', 'DDMMYY'); // Jun 08 2014
I have created a JS Fiddle with these examples: http://jsfiddle.net/cHRfg/2/
Is there a way to have moment accept a wider array of user input, and reject invalid dates? Or is the library not intended for this?
A: var parsed = moment(myStringDate, 'DD.MM.YYYY');
for Version >= 1.7.0 use:
parsed.isValid()
for Version < 1.7.0 create your own isValid() function:
function isValid(parsed) {
return (parsed.format() != 'Invalid date');
}
checkout the docs:
http://momentjs.com/docs/#/parsing/is-valid/
A: You can try parsing multiple formats. Updated fiddle: http://jsfiddle.net/timrwood/cHRfg/3/
var formats = ['DDMMYYYY', 'DDMMYY'];
var date1 = moment('30082012', formats);
var date4 = moment('300812', formats);
Here are the relevant docs. http://momentjs.com/docs/#/parsing/string-formats/
There is development on adding moment.fn.isValid which will allow you to do validation like in examples 5-8. It will be added in the 1.7.0 release. https://github.com/timrwood/moment/pull/306
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10711787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: All Params Not Being Passed I am using php to create a hyperlink, and pass 3 params when the hyperlink is clicked. My issue with the syntax below is that only the 1st param is passsed, the other 2 are ignored.
What should I alter in the syntax below so that all 3 params are passed?
if($number_of_rows > 0) {
echo '<table border="1">';
echo '<tr>';
echo ' <th bgcolor="#FFFFFF" >Name </th>';
echo ' <th bgcolor="#FFFFFF">User ID </th>';
echo ' <th bgcolor="#FFFFFF">Dollar Amt </th>';
echo ' <th bgcolor="#FFFFFF">Price 1 </th>';
echo ' <th bgcolor="#FFFFFF">Price 2 </th>';
echo ' <th bgcolor="#FFFFFF">Price 3 </th>';
echo ' <th bgcolor="#FFFFFF">Price 4 </th>';
echo ' <th bgcolor="#FFFFFF">Items Sold </th>';
echo ' <th bgcolor="#FFFFFF">Items On Sale</th>';
echo '</tr>';
while ($Row = mssql_fetch_assoc($result))
{
echo '<tr><td>' . $Row['Name'] . '</td><td>' . $Row['User ID'] .
'</td><td>' . "$".round($Row['Dollar Amt']) . '</td><td>' . "$".round($Row['Price 1']) .
'</td><td>'. "$".round($Row['Price 2']) . '</td><td>'. "$".round($Row['Price 3']) .
'</td><td>'. "$".round($Row['Price 4']) . '</td><td>' . $Row['Items Sold'] .
'</td><td><a href="Test.php?name='.$Row['Name'].'"&begin=".$begin"&finish=".$finish>'.$Row['Items On Sale'].'</a></td></tr>';
}
The above runs a sql server stored procedure and I am using echo to create a table and return to my page. That process works as it should. The only issue is that only name is passed into the url when clicked not the 2 dates that I also want to pass.
NOT a duplicate, that is pertinate to mysql and I am using mssql. Also, the linked duplicate talks about returning rows, now passing parameters. My issue is that only the name parameter is passed when clicked. Please remove the duplicate flag.
EDIT
The variables are defined like so:
$begin = $_GET['begin'];
$end = $_GET['end'];
A: You are mixing double-quote " and single-quote '. Replace last line of your code inside while loop with following and it should work as expected.
'</td><td><a href="Test.php?name='.$Row['Name'].'&begin='.$begin.'&finish='.$finish.'">'.$Row['Items On Sale'].'</a></td></tr>';
From your post edit, try this:
'</td><td><a href="Test.php?name='.$Row['Name'].'&begin='.$begin.'&finish='.$end.'">'.$Row['Items On Sale'].'</a></td></tr>';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42457717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Passing and accessing value in Django form I'm trying to pass info to my form and I have a bit of a struggle with that. My code looks as follows:
views.py
class ObjectUpdateView(UpdateView):
template_name = 'manage/object_form.html'
form_class = ObjectEditForm
def get_success_url(self):
#...
def form_valid(self, form):
return super(ObjectUpdateView, self).form_valid(form)
def get_object(self):
return get_object_or_404(Room, pk=self.kwargs['object_id'])
def get_form_kwargs(self, **kwargs):
objectid = self.kwargs['object_id']
object = Object.objects.get(id = objectid)
container = object.container
kwargs['container_id'] = container.id
return kwargs
forms.py
class ObjectEditForm(forms.ModelForm):
class Meta:
model = Object
fields = ['TestField']
def __init__(self, *args, **kwargs):
super(ObjectEditForm, self).__init__(*args, **kwargs)
self.Container_id = kwargs.pop('container_id')
form_page.html
{{fomr.kwarg.Container_id}}
As you can see I'd like to access Container_id value in my form_page.html. Unfortunately, nothing is there. What I also noticed, that with __init__ I had to add, now values are empty in my form. Before I added __init__ all values were properly passed (well, except Container_id).
Could you recommend how I can pass such value to be accessed in the form template?
A: You can render this with:
{{ form.Container_id }}
In your form you should first pop the container_id from the kwargs, like:
class ObjectEditForm(forms.ModelForm):
class Meta:
model = Object
fields = ['TestField']
def __init__(self, *args, **kwargs):
# first pop from the kwargs
self.Container_id = kwargs.pop('container_id', None)
super(ObjectEditForm, self).__init__(*args, **kwargs)
Use the context over the form
That being said, it is a bit strange that you pass this to the form, and not add this to the context data. You can simplify your view a lot to:
class ObjectUpdateView(UpdateView):
template_name = 'manage/object_form.html'
pk_url_kwarg = 'object_id'
form_class = ObjectEditForm
def get_success_url(self):
#...
def get_context_data(self, **kwargs):
objectid = self.kwargs['object_id']
object = Object.objects.get(id = objectid)
context = super().get_context_data()
context.update(container_id=object.container_id)
return context
Django automatically fetches a single element based on the pk_url_kwarg [Django-doc]. You only need to set it correctly, so here that is the object_id.
In that case, we can simply render this with:
{{ container_id }}
and you do not need to store this in the form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56513889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I update environment variable (System.getenv) (not Java system property) variable during runtime in Java U tried various solutions like ProcessBuilder and Runtime to update an environment variable, but none work. I have used reflection, but it does not seem to work as it's an unmodifiableMap.
private void updateEnvVars(Map<String, String> kafkaProps) {
try {
Class[] classes = Collections.class.getDeclaredClasses();
System.out.println("Total Classes : " + classes.length);
Map<String, String> env = System.getenv();
for (Class cl : classes) {
System.out.println("ClassName: " + cl.getFields().toString());
if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
Field field = null;
field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
final Map<String, String> objectObjectHashMap = new HashMap<>();
objectObjectHashMap.putAll(System.getenv());
objectObjectHashMap.putAll(kafkaProps);
Map<String, String> map = (Map<String, String>) obj;
//java.util.Collections.unmodifiableMap<String, String>
//final Map<String, String> stringMap = Collections.unmodifiableMap(map);
map.clear();
map.putAll(objectObjectHashMap);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72360468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rewrite with proof-irrelevant equivalence relations in Agda? I am quite new to type theories and dependently typed programming and is recently experimenting with various features of Agda. The following is a very simplified example I wrote of a record type C which contains multiple component records and some constraints that we can prove things with.
open import Relation.Binary.PropositionalEquality
module Sample (α : Set) where
record A (type : α) : Set where
record B : Set where
field
type : α
record C : Set where
field
b₁ : B
b₂ : B
eq : B.type b₁ ≡ B.type b₂
conv : A (B.type b₁) → A (B.type b₂)
conv a rewrite eq = a
It seems appealing to me that the constraint eq : B.type b₁ ≡ B.type b₂ should be declared irrelevant by adding a . in the front (or, in the latest dev version 2.6.0, to replace by an equivalence relation of sort Prop, e.g.
data _≡_ {ℓ} {α : Set ℓ} (x : α) : α → Prop ℓ where
refl : x ≡ x
), so that two instances of type C with the same components can be directly unified via refl regardless of different proofs eq. However, either way, the program stops to compile because I cannot pattern match on an irrelevant value / Prop.
I would like to know whether it is possible for the same functionality to be implemented in Agda in any way, or that in general why it is impossible to rewrite with proof-irrelevant equivalence relations in Agda (technical support difficulties, or this breaks some parts of Agda's type theory, etc.)?
A: This is currently not yet possible in Agda due to technical limitations: 'rewrite' is just syntactic sugar for a pattern match on refl, and currently pattern matching on irrelevant arguments is not permitted. In our paper at POPL '19 we describe a criterion for which datatypes in Prop are 'natural' and can thus be pattern matched on. I hope to add this criterion to Agda before the release of 2.6.1, but I cannot make any promises (help on the development of Agda is always welcome).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55646606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why toast message are not show in android 4.1 operating system containing mobile I cant see the toast message in android 4.1 mobile. Upto yesterday I was able to see the toast message. From today only I can not see the message. Please help me.
Toast.makeText(getApplicationContext(), "hi", Toast.LENGTH_SHORT).show();
I have tried custom toast message also instead of toast message. But still not working.
Custom toast:
LayoutInflater inflater=getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Please fill Name");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
A: Change to this and check again.
if(first_name.length() == 0)
{
Toast.makeText(NameOfYourActivity.this, "Please fill Name", Toast.LENGTH_SHORT).show();
Utilities.writeIntoLog("Please fill Name");
}
A: just post the google code link here.
Since Jelly Bean, users can disable notifications for a given app via "app details" settings.
A very bad and unwanted side effect is that once notifs are disabled, Toast messages are also disabled, even when the user is running the app!
You encourage to use Toast in your design guidelines, but who will want to use it if the users have the possibility to remove them, especially if the toasted message is an important feedback to display to the user...
I understand at least that Toasts could be disabled when the app is in background, but not if it is the foreground Activity.
A: Toast was not showing with me in Android 4.1 because Show Notifications was checked off in my app's settings. I just went to Settings->Manage Applications->[My App] and toggled on Show Notifications and Toasts started to appear.
A: Toast is working fine in all the version of Android. There can be couple of issues in your code like
*
*Your context is not wrong
*You are trying to display toast in the background thread instead of worker thread.
Edit
In your custom toast don't set the parent in your layout inflater for example use like below
View layout = inflater.inflate(R.layout.toast_layout,null);
A: I had the same problem. When I invoked the code on UI thread the issue resolved for me
public void showToastMessage(final String msg) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(BaseActivity.this, msg, Toast.LENGTH_LONG).show();
}
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12159546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Post-request rejected by server Could anyone help to solve a problem? I'm trying to send data form from authorize user to protected controller method, using fetch and getting 400 error. I'm using NET CORE 5 MVC and on front-en bootstrap 5. If I remove ValidateAntiForgeryToken from AddItemToStore method I'm getting 415 error
C# code
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddItemToStore([FromBody] StoreUser itemsStore)
{
StoreUser str = new StoreUser
{
Id = 1,
UserId = itemsStore.UserId,
CatrgoryId = itemsStore.CatrgoryId
};
return Ok(str);
}
JS-code
var buttonAddOrder = document.getElementById("addToOrder");
buttonAddOrder?.addEventListener("click", function () {
var catId = document.querySelector("#formToStore input[name = 'cardId']").value;
var userId = document.querySelector("#formToStore input[name = 'userId']").value;
var antiForgeryToken = document.querySelector("#formToStore input[name = '__RequestVerificationToken']").value;
var itemsStore = {
__RequestVerificationToken: antiForgeryToken,
UserId: userId,
CatrgoryId: catId,
Payed: false
};
var url = "/CategoriesToUser/AddItemToStore";
var response = fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;'
},
body: {
itemsStore: itemsStore
}
})
.then((response) => {
return response.json();
}).catch((e) => console.log(e.message));
console.log('buttonAddOrder', response);
HTML
<form id="formToStore" method="post" enctype="multipart/form-data">
<input type="hidden" name="cardId" id="cardId" /> @{ var getUser = await UserManager.GetUserAsync(User); }
<input type="hidden" name="userId" asp-for="@getUser.Id" />
<div class="modal-footer">
<button type="button" id="buttonclose" name="buttonclose" class="buttonclose btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" id="addToOrder" name="addToOrder" class="btn btn-primary">
Add to Order
</button>
</div>
</form>
An attempt of using FormData doesn't work, the same error.
buttonAddOrder?.addEventListener("click", function () {
var url = "/CategoriesToUser/AddItemToStore";
const formToStore = document.getElementById('formToStore');
var formOrder = new FormData(formToStore);
let response = fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;'
},
body: formOrder
})
.then((response) => {
return response.json();
}).catch((e) => console.log(e.message));
console.log('buttonAddOrder', response);
});
But If I send data to anonymous post method without using ValidateAntiForgeryToken on beck-end It's work.
Example:
[AllowAnonymous]
[HttpPost]
public IActionResult AddItemToStore([FromBody] StoreUser itemsStore)
{
StoreUser str = new StoreUser
{
Id = 1,
UserId = itemsStore.UserId,
CatrgoryId = itemsStore.CatrgoryId
};
return Ok(str);
}
Screenshots
A: Before coding, you need be sure the following inputs contain value:
<input type="hidden" name="cardId" id="cardId" /> @{ var getUser = await UserManager.GetUserAsync(User); }
<input type="hidden" name="userId" asp-for="@getUser.Id" />
Two ways you could follow:
1.From Body:
View
<form id="formToStore" method="post" enctype="multipart/form-data">
<input type="hidden" name="cardId" id="cardId" value="1" />
<input type="hidden" name="userId" value="466788cb-6aab-4798-81f1-f6b05cb71e32"/>
<div class="modal-footer">
<button type="button" id="buttonclose" name="buttonclose" class="buttonclose btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" id="addToOrder" name="addToOrder" class="btn btn-primary">Add to Order</button>
</div>
</form>
@section Scripts
{
<script>
var buttonAddOrder = document.getElementById("addToOrder");
buttonAddOrder?.addEventListener("click", function () {
var catId = document.querySelector("#formToStore input[name = 'cardId']").value;
var userId = document.querySelector("#formToStore input[name = 'userId']").value;
var antiForgeryToken = document.querySelector("#formToStore input[name = '__RequestVerificationToken']").value;
var itemsStore = {
// __RequestVerificationToken: antiForgeryToken, //remove this....
UserId:userId,
CatrgoryId: catId,
Payed: false
};
var url = "/CategoriesToUser/AddItemToStore";
var response = fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json', //change here...
"X-ANTI-FORGERY-TOKEN": antiForgeryToken, //add this.....
},
body: JSON.stringify(itemsStore) //change here.....
})
.then((response) => {
return response.json();
}).catch((e) => console.log(e.message));
})
</script>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddItemToStore([FromBody] StoreUser itemsStore)
{
//do your stuff....
return Ok(itemsStore);
}
Startup.cs:
services.AddAntiforgery(x => x.HeaderName = "X-ANTI-FORGERY-TOKEN");
2.From Form:
View
<form id="formToStore" method="post" enctype="multipart/form-data">
@*change name="cardId" to name="CatrgoryId"*@
<input type="hidden" name="CatrgoryId" id="cardId" value="1" />
<input type="hidden" name="userId" value="466788cb-6aab-4798-81f1-f6b05cb71e32"/>
<div class="modal-footer">
<button type="button" id="buttonclose" name="buttonclose" class="buttonclose btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" id="addToOrder" name="addToOrder" class="btn btn-primary">Add to Order</button>
</div>
</form>
@section Scripts
{
<script>
var buttonAddOrder = document.getElementById("addToOrder");
buttonAddOrder?.addEventListener("click", function () {
var url = "/CategoriesToUser/AddItemToStore";
const formToStore = document.getElementById('formToStore');
var formOrder = new FormData(formToStore);
let response = fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
//headers: {
// 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;'
//}, //don't need to set the Content-Type header
body: formOrder
})
.then((response) => {
return response.json();
}).catch((e) => console.log(e.message));
})
</script>
}
Controller
Change [FromBody] to [FromForm].
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddItemToStore([FromForm] StoreUser itemsStore)
{
//do your stuff...
return Ok(itemsStore);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72090105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I can not get an image of the URL found with XmlHttpRequest Im trying to get a image url through XmlHttpRequest and use it like 'src' attribute of a 'img' tag. That is my plan:
function populaLista() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://localhost:8080/artes');
ourRequest.onload = function() {
var ourData = ourRequest.responseText.toString();
var jsonResposta = JSON.parse(ourData);
if (ourData.length > 0) {
document.getElementById("paragrafo1").innerHTML = jsonResposta.url;
var tabela = document.createElement("TABLE");
var corpoTabela = document.createElement("TBODY");
var tr = document.createElement("TR");
var td = document.createElement("TD");
var imagem = document.createElement("IMG");
var urlImg = document.createTextNode(jsonResposta.url).toString();
// var urlImg = "https://mir-s3-cdn-cf.behance.net/projects/202/6310ed61231533.Y3JvcCwyNjM1LDIwNjIsMjI3LDA.jpg";
document.getElementById("paragrafo").innerHTML = typeof urlImg;
imagem.setAttribute("src",urlImg);
td.appendChild(imagem);
tr.appendChild(td);
corpoTabela.appendChild(tr);
tabela.appendChild(corpoTabela);
document.getElementById("tabeladeImagens").appendChild(tabela);
} else {
document.getElementById("paragrafo").innerHTML = "item não encontrado";
}
};
ourRequest.send();
The problem is: when I use the result of my request on my img tag, I can't see the image, but if I use the same url in a string var that I created I can see normally.
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body onload="populaLista()">
<p id="paragrafo"></p>
<p id="paragrafo1"></p>
<div id="tabeladeImagens" class="logoHome"></div>
<script src="main.js"></script>
</body>
</html>
The json response:
{id : 38, url : "//mir-s3-cdn-cf.behance.net/projects/202/6310ed61231533.Y3JvcCwyNjM1LDIwNjIsMjI3LDA.jpg"}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51432480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Retrieve all functions that called by a user mode process in kernel mode debug including kernels functions I am trying to find all the functions including both user mode functions and kernel mode functions that wmic.exe calls to execute the diskdrive command. In order to do this I opened wmic.exe in my virtual machine and set breakpoint in kernel mode windbg on WMIC!CParsedInfo::GetUser and WMIC!CExecEngine::ExecuteCommand.
As soon as I input diskdrive debugger breaks on ExecuteCommand, I am in kernel mode through COM port, but I cant use wt command, however I can run instructions line by line and step in to every call and track all function in stack call, but this will take lots of time and it’s not optimized. Is there any way to do something similar to the wt command in the kernel debugger?
Whenever I use the wt command it outputs ^ Unimplemented error in 'wt'.
Some extra info:
*
*I am running Windows 11 Enterprise Build 22000.856 on VMWare and connected to it through the COM port for kernel debugging and the host OS is the latest version of Windows 11 Enterprise.
*Windbg is also the latest version of windbg.
*Both windbg and vmware running as administrator.
*I am able to use all the usual commands I can see registers, see stack calls with single step, see threads and etc.
*wt runs normally on my main OS for user mode processes on my main OS without any problem
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73531848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Snowflake External Table Have a question regarding the Snowflake External Table. As we now the External Tables still a preview feature and still not a General Available. Hence have guys used External table in your production environment and you see any issue ? Snowflake do not recommend to use Preview feature in Production. Any thoughts?
A: External table feature is publicly available feature as per documentation
https://docs.snowflake.com/en/user-guide/tables-external-intro.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63208676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Azure DevOps Server 2020 - FilePath artifacts not always deleted from fileShare We are on ADS 2020.0.1
We are migrating to a new file server, we have noticed that drops on the new file server are not beeing deleted after the build run has been deleted.
I have created a test pipeline, where i drop to the old and new server.
After deleting the build, the artifacts are deleted on the old server, but not the new server.
old build path: 116 chars - new build path: 142 chars
The service account has modify permissions in both the old and new location. I am able to manually delete a file remotely while logged on as this account on one of the build servers.
I can see the cleanup job in the job history, it shows a red X, but i cannot see the details.
Question is, where can i see the logs of the delete artifacts task? i tried in the _oi page, but here it doesn't show anything.
We see this behaviour in classing and YAML pipelines
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68285233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: positioning the child behind the parent of the parent element, ```z-index``` does not work I want the <span> to appear behind the #sideBar i tried z-index: -3 but that didn't work
body {
margin: 0px;
font-family: "Signika Negative", sans-serif;
background-color: #252525;
color: #f8f9fa;
user-select: none;
}
#sideBar{
width: 2vw;
height: 100vh;
background-color: rgb(15, 15, 15);
opacity: .99;
}
.menuBtn{
background: none;
cursor: pointer;
padding: .5vw;
border: none;
padding: none;
color: white;
font-weight: 600;
font-size: 1vmax;
}
.menuBtn .label{
transition: left .5s;
}
.label{
position: absolute;
font-size: .9vmax;
opacity: 1;
left: -2.2vw;
}
svg{
transition: transform .5s;
}
.menuBtn:hover svg{
transform: scale(1.2);
}
.menuBtn:hover .label{
opacity: 1;
left: 2.2vw;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Fira+Mono&family=Signika+Negative:wght@300&display=swap" rel="stylesheet"/>
<style>
@import url("https://fonts.googleapis.com/css2?family=Fira+Mono&family=Signika+Negative:wght@300&display=swap");
</style>
<meta charset="UTF-8" />
<link rel="stylesheet" href="styles.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OverStat</title>
</head>
<body>
<div id="sideBar">
<div class="menuBtn" onclick="clear()"><span class="label" >Clear all games and ranks</span><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="lightgrey" d="M135.2 17.7C140.6 6.8 151.7 0 163.8 0H284.2c12.1 0 23.2 6.8 28.6 17.7L320 32h96c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 96 0 81.7 0 64S14.3 32 32 32h96l7.2-14.3zM32 128H416V448c0 35.3-28.7 64-64 64H96c-35.3 0-64-28.7-64-64V128zm96 64c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16zm96 0c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16zm96 0c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16z"/></svg></div>
<div class="menuBtn"><span class="label">Prefrences</span><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Pro 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. --><path fill="lightgrey" d="M0 416c0-17.7 14.3-32 32-32l54.7 0c12.3-28.3 40.5-48 73.3-48s61 19.7 73.3 48L480 384c17.7 0 32 14.3 32 32s-14.3 32-32 32l-246.7 0c-12.3 28.3-40.5 48-73.3 48s-61-19.7-73.3-48L32 448c-17.7 0-32-14.3-32-32zm192 0a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zM384 256a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zm-32-80c32.8 0 61 19.7 73.3 48l54.7 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-54.7 0c-12.3 28.3-40.5 48-73.3 48s-61-19.7-73.3-48L32 288c-17.7 0-32-14.3-32-32s14.3-32 32-32l246.7 0c12.3-28.3 40.5-48 73.3-48zM192 64a32 32 0 1 0 0 64 32 32 0 1 0 0-64zm73.3 0L480 64c17.7 0 32 14.3 32 32s-14.3 32-32 32l-214.7 0c-12.3 28.3-40.5 48-73.3 48s-61-19.7-73.3-48L32 128C14.3 128 0 113.7 0 96S14.3 64 32 64l86.7 0C131 35.7 159.2 16 192 16s61 19.7 73.3 48z"/></svg></div>
<div class="menuBtn"><span class="label">How to use</span><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Pro 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. --><path fill="lightgrey" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336h24V272H216c-13.3 0-24-10.7-24-24s10.7-24 24-24h48c13.3 0 24 10.7 24 24v88h8c13.3 0 24 10.7 24 24s-10.7 24-24 24H216c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z"/></svg></div>
</div>
</body>
</html>
A: When you put opacity: .99 on the #sidebar, it forms a stacking context on #sidebar and everything inside it is stuck on it even if you put a z-index: -1000.
#sidebar {
opacity: 1;
}
.label {
z-index: -3;
}
Read more about the stacking context.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75545080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do I receive/send information from/to GitHub using android App I have a school project where I am supposed to create an Android application that can get notifications from a GitHub project and also be able to send comments to GitHub using the App. I don't really know where to start but I hope there is some API for Git that I can use.
I'm using Eclipse which is kinda new to me and would really appreciate some help!
A: Github has a number of apis that you can use and I'm sure there are many user created ones as well:
GitHub API
I know they recently rolled out
Webhooks
Some developer guides
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22720577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: React Native FlatList Object displaying I have the below object that I am retrieving from the AsyncStorage, and I want to display it in a FlatList but I am getting the following error:
Invariant Violation: Invariant Violation: Invariant Violation: Invariant Violation: Tried to get frame for out of range index NaN
My JSON format is:
Object {
"44": Object {
"pro_id": "44",
"pro_img": "url",
"pro_name": " S4 ",
},
"52": Object {
"pro_id": "52",
"pro_img": "url",
"pro_name": " S4 ",
},
}
The JSON above is retrieved from AsyncStorage like so:
retrieveData = async () => {
try {
await AsyncStorage.getItem('userFavorites')
.then(req => JSON.parse(req))
.then(json => this.setState({ favPro:json }))
} catch (error) {
}
}
My method for rendering items in the FlatList is defined like this:
fav = ({ item }) => {
return (
<View>
<Text>{item.pro_id+ item.pro_name}</Text>
</View>
)
}
Finally, I render the FlatList as follows:
<FlatList
data={this.state.favPro}
renderItem={this.fav}
keyExtractor={item => item.pro_id}
/>
How I can display my JSON data using the FlatList component?
A: The FlatList component expects an array input for the data prop. Based on your JSON format, it appears you're passing in an object rather than an array.
Consider the following adjustment to your render method:
// Convert object to array based on it's values. If favPro not
// valid (ie during network request, default to an empty array)
const data = this.state.favPro ? Object.values(this.state.favPro) : []
<FlatList
data={data}
renderItem={this.fav}
keyExtractor={item => item.pro_id}
/>
A: You're using async / await incorrectly. Instead of calling .then you assign your call to await to a variable (or don't assign it if it does not return a value) and wrap the call (or calls) to await in a try / catch block. The await keyword will automatically handle resolve and reject so you get the appropriate information.
retrieveData = async () => {
try {
const data = JSON.parse(await AsyncStorage.getItem("userFavorites"))
this.setState({ favPro: data })
} catch (error) {
console.error(error)
this.setState({ favPro: [] })
}
}
You also need to pass an array, the shape of your data looks like an object, but it should be an array of objects. This is not a terribly difficult transformation and I can provide a helper function if you need it.
edit: if you need to convert an object into an array, you can use the reduce function
const data = {
'44': { a: 2 },
'55': { b: 3 },
}
const dataArr = Object.keys(data).reduce(
(arr, key) => arr.concat(data[key]),
[]
)
By using Object.keys we can each object by name. Then call reduce and the array returned by Object.keys, passing a function as the first argument, and an empty array as the second argument. The second argument is automatically passed to the function as the first argument, arr, and the second argument of the function we pass is the key of the object. Then it's just a matter of adding the objects to the array using concat.
Array.reduce can seem a little overwhelming at first but it's a very powerful method and you can get a lot done with it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52842805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java: Two Scanners reading from the same input file. Doable? Useful? I have to read in integers from an input file based on whether or not a string that appears before them is a certain keyword "load". There is no key number telling how many numbers are about to be inputted. These numbers must be saved to an array. In order to avoid creating and updating a new array for each additional number scanned, I'd like to use a second scanner to first find the amount of integers, and then have the first scanner scan that many times before reverting back to testing for strings. My code:
public static void main(String[] args) throws FileNotFoundException{
File fileName = new File("heapops.txt");
Scanner scanner = new Scanner(fileName);
Scanner loadScan = new Scanner(fileName);
String nextInput;
int i = 0, j = 0;
while(scanner.hasNextLine())
{
nextInput = scanner.next();
System.out.println(nextInput);
if(nextInput.equals("load"))
{
loadScan = scanner;
nextInput = loadScan.next();
while(isInteger(nextInput)){
i++;
nextInput = loadScan.next();
}
int heap[] = new int[i];
for(j = 0; j < i; j++){
nextInput = scanner.next();
System.out.println(nextInput);
heap[j] = Integer.parseInt(nextInput);
System.out.print(" " + heap[j]);
}
}
}
scanner.close();
}
My problem seems to be that scanning via loadscan, the secondary scanner only meant for integers, also moves the primary scanner forward. Is there any way to stop this from happening? Any way to make the compiler treat scanner and loadscan as separate objects despite them preforming the same task?
A: You may certainly have two Scanner objects read from the same File object simultaneously. Advancing one will not advance the other.
Example
Assume that the contents of myFile are 123 abc. The snippet below
File file = new File("myFile");
Scanner strFin = new Scanner(file);
Scanner numFin = new Scanner(file);
System.out.println(numFin.nextInt());
System.out.println(strFin.next());
... prints the following output...
123
123
However, I don't know why you would want to do that. It would be much simpler to use a single Scanner for your purposes. I called mine fin in the following snippet.
String next;
ArrayList<Integer> readIntegers = new ArrayList<>();
while (fin.hasNext()) {
next = fin.next();
while (next.equals("load") {
next = fin.next();
while (isInteger(next)) {
readIntegers.Add(Integer.parseInt(next));
next = fin.next();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22723630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use asyncio with a very long list of tasks (generator) I have a small program that loads a pretty heavy CSV (over 800MB, in chunks, using pandas.read_csv to limit memory usage) and performs a few API calls to servers "out in the wild", and finally builds a result object which is then stored in a database.
I have added caching for the network requests where possible, but even then, the code takes over 10 hours to complete. When I profile the code with PySpy, most of it is waiting for network requests.
I tried converting it to use asyncio to speed things up, and have managed to get the code to work on a small subset of the input file. However with the full file, the memory use become prohibitive.
Here is what I have tried:
import pandas as pd
import httpx
async def process_item(item, client):
# send a few requests with httpx session
# process results
await save_results_to_db(res)
async def get_items_from_csv():
# loads the heavy CSV file
for chunk in pd.read_csv(filename, ...):
for row in chunk.itertuples():
item = item_from_row(row)
yield item
async def main():
async with httpx.AsyncClient() as client:
tasks = []
for item in get_items_from_csv():
tasks.append(process_item(item, client))
await asyncio.gather(*tasks)
asyncio.run(main())
Is there a way to avoid creating the tasks list, which becomes a very heavy object with over 1.5M items in it? The other downside of this is that no task seems to be processed until the entire file has been read, which is not ideal.
I'm using python 3.7 but can easily upgrade to 3.8 if needed.
A: I think what you are looking for here is not running in batches but running N workers which concurrently pull tasks off of a queue.
N = 10 # scale based on the processing power and memory you have
async def main():
async with httpx.AsyncClient() as client:
tasks = asyncio.Queue()
for item in get_items_from_csv():
tasks.put_nowait(process_item(item, client))
async def worker():
while not tasks.empty():
await tasks.get_nowait()
# for a server
# while task := await tasks.get():
# await task
await asyncio.gather(*[worker() for _ in range(N)])
I used an asyncio.Queue but you can also just use a collections.deque since all tasks are being added to the queue prior to starting a worker. The former is especially useful when running workers that run in a long running process (e.g. a server) where items may be asynchronously queued.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61333890",
"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.