text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: ReactJS Firebase multiple where clause isn't working I'm developing an application which need's to fetch users based on prefered preferences but the sorting isn't functioning.
export const fetchUsers = (minAge, maxAge, prefer, gender) =>
db.collection('profiles')
.where('age', '>=', minAge)
.where('age', '<=', maxAge)
//.where('gender', '==', prefer)
.get()
.then(snapshot => snapshot.docs.map(doc => ({id: doc.id, ...doc.data()})))
When I use the three where clauses it should return a user but it returns zero. When I only use age or only use gender the query returns the correct data.
Why aren't the three where clauses not returning data and it only works when I use where on age or gender?
I've tried to change the .where clause to .where({...}) but this is incorrect code. Also i've tried to filter on only minAge and gender but also returns zero data, while it should return a user.
A: Firestore queries always work based on one or more indexes. In the case where you have conditions on multiple fields, it often needs a so-called composite index on those fields. Firestore automatically adds indexes for the individual fields, but you will have to explicitly tell it to create composite indexes.
When you try to execute a query for which the necessary index is missing, the SDK raises an error that contain both the fact that an index is missing and a direct link to the Firestore console to create exactly the index that the query needs. All fields are prepopulated, so you just need to click the button start creating the index.
If you don't see the error message/link in your apps logging output yet, consider wrapping the query in a try/catch and logging it explicitly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74388776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VueJs run watcher handler immediatly after triggering Example:
export default {
data() {
return {
data1: 1,
data2: 2
}
},
mounted() {
this.data1 = 2
console.log(this.data2)
},
watch: {
data1: {
handler(newData1) {
this.data2 = newData1 * 3
}
}
}
}
Expected behavior: the browser write number 6 to the console
Current behavior: the browser write number 2 to the console
In this example I try to write the modified data2 after changed data1 value, but it write the data2 value before the watcher handler modify it. Is there a way to immediatly run watcher handler after triggering? I know I can use a computed property in this example but I need data in my project.
I tried to set the watcher immediatly property to true but isn't working.
A:
You can use computed property for data2
export default {
data() {
return {
data1: 1
}
},
mounted() {
this.data1 = 2
console.log(this.data2)
},
computed: {
data2() {
return this.data1 * 3
}
}
}
A: The watcher will not trigger in the middle of your mounted() handler, you need to wait until the handler has finished. This is how Javascript works, it is not a limitation in Vue.
A: I am not sure what the purpose of your code, but below will work
mounted() {
this.data1 = 2
this.$nextTick(() => {
console.log(this.data2)
})
},
A:
Current behavior: the browser write number 2 to the console
It becauses Vue performs DOM updates asynchronously first run into mounted you made change to data1 (also puts console.log(this.data2) to callback queue at this point of time this.data2 = 2 thats why you see log 2) it also triggers watch of data1 If you log data2 here you see value of 6.
In order to wait until Vue.js has finished updating the DOM after a data change, you can use Vue.nextTick(callback) immediately after the data is changed
mounted() {
this.data1 = 2
this.$nextTick(() => {
console.log(this.data2); // 6
})
}
or use Vue.$watch - Watch an expression or a computed function on the Vue instance for changes
data() {
return {
data1: 1,
data2: 2
}
},
watch: {
data1: function(val) {
this.data2 = val * 3
}
},
mounted() {
this.data1 = 2
this.$watch('data2', (newVal) => {
console.log(newVal) // 6
})
}
A: As another answer explains, this is expected default behaviour and can be addressed by using nextTick, most times it's not the case because a computed is used instead, as suggested in yet another answer.
In Vue 3, this can be changed by the use of flush option:
mounted() {
this.data1 = 2
console.log(this.data2) // 6
},
watch: {
data1: {
handler(newData1) {
this.data2 = newData1 * 3
},
flush: 'sync'
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75291672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I change this WooCommerce cart icon into text Need help. How can I change this cart icon?
I want to change it to an image icon. Also, I need it to put the code in my Child-theme stylesheet.
Thank you in advance
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65759414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to format columns dates in python that they are weekly based on eachother? I have a dataframe df that looks similar to this:
identity Start End week
E 6/18/2020 7/2/2020 1
E 6/18/2020 7/2/2020 2
2D 7/18/2020 8/1/2020 1
2D 7/18/2020 8/1/2020 2
A1 9/6/2020 9/20/2020 1
A1 9/6/2020 9/20/2020 2
The problem is that when I extracted the data I only had Start date and End date for every identity it replaced, but I have the data by weeks all identitys have the same amount of weeks some times all identitys can have 5 or 6 weeks but they are always the same. I want to make Stata and end be weekly so when the first week end I add 7 days. And when the week starts again it starts where week ended. A representation would be
identity Start End week
E 6/18/2020 6/25/2020 1
E 6/25/2020 7/2/2020 2
2D 7/18/2020 7/25/2020 1
2D 7/25/2020 8/1/2020 2
A1 9/6/2020 9/13/2020 1
A1 9/13/2020 9/20/2020 2
I tried a simple method that was creating a sevens column and making the sum to get the end of the week I get and error Addition/subtraction of integers and integer-arrays with Timestamp is no longer supported. Instead of adding/subtracting n, use n * obj.freq
Then I would concat start over minus seven but I don't know how to get around this problem. Any help would be magnificent.
A: Similar to your other question:
First convert to datetimes:
df.loc[:, ["Start", "End"]] = (df.loc[:, ["Start", "End"]]
.transform(pd.to_datetime, format="%m/%d/%Y"))
df
identity Start End week
0 E 2020-06-18 2020-07-02 1
1 E 2020-06-18 2020-07-02 2
2 2D 2020-07-18 2020-08-01 1
3 2D 2020-07-18 2020-08-01 2
4 A1 2020-09-06 2020-09-20 1
5 A1 2020-09-06 2020-09-20 2
Your identity is in groups of two, so I'll use that when selecting dates from the date_range:
from itertools import chain
result = df.drop_duplicates(subset="identity")
date_range = (
pd.date_range(start, end, freq="7D")[:2]
for start, end in zip(result.Start, result.End)
)
date_range = chain.from_iterable(date_range)
End = lambda df: df.Start.add(pd.Timedelta("7 days"))
Create new dataframe:
df.assign(Start=list(date_range), End=End)
identity Start End week
0 E 2020-06-18 2020-06-25 1
1 E 2020-06-25 2020-07-02 2
2 2D 2020-07-18 2020-07-25 1
3 2D 2020-07-25 2020-08-01 2
4 A1 2020-09-06 2020-09-13 1
5 A1 2020-09-13 2020-09-20 2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65830784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python plot window not closing after being called from a JavaScript script I have a JavaScript script (open_hist_w_user.js) spawns a python process and passes data to a python script (create_histogram.py). The Python script creates a histogram using the Matplotlib library and displays it. The problem is that even after calling plt.close('all'), the plot window does not close.
Code:
*javascript; open_hisr_w_user.js*
/**
* This script is used to spawn a python process that generates a histogram for the specified username.
*
* @param {string} username - The username for which the histogram is being generated.
*
* @returns {ChildProcess} - The spawned python process.
*/
const { spawn } = require('child_process');
const username = 'some_username';
const pythonProcess = spawn('python', ['./create_histogram.py', username]);
python;create_histogram.py
import matplotlib.pyplot as plt
import sys
import time
def create_histogram(username):
"""
This function creates a histogram of data, with a specified number of bins and range, and displays it.
Parameters
----------
username : str
The username for which the histogram is being generated.
Returns
-------
None
"""
plt.close('all') # close any previous plot windows
# plot the histogram
plt.clf() # clear the previous plot
plt.hist([1, 2, 3, 4, 5], bins=3, range=(0, 5))
plt.xlabel('Total')
plt.ylabel('Frequency')
plt.title(f'Histogram of Total Column for {username}')
plt.show() # show the plot
time.sleep(5) # wait for 5 seconds
plt.close('all') # close the plot window
if __name__ == "__main__":
username = sys.argv[1]
create_histogram(username)
I tried using plt.close('all') to close the plot window, but it did not work. I expected the plot window to close after some delay after the histogram was created. Before you ask why am I not just using a javascript script,I tried porting my code a few days ago using plotly and df3, but couldn't get it working; so here we are passing data through the console.
Expected Result:
insert image of closed window here
Actual Result:
A: Try this:
*javascript; open_hisr_w_user.js*
/**
* This script is used to spawn a python process that generates a histogram for the specified username.
*
* @param {string} username - The username for which the histogram is being generated.
*
* @returns {ChildProcess} - The spawned python process.
*/
const spawn = require('child_process').spawn;
const username = 'some_username';
const pythonProcess = spawn('python', ['./create_histogram.py', username], {
detached: true,
stdio: ['ignore']
});
pythonProcess.unref();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75417447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Returning IPv6 instead of IPv4 in VB I have this function which is querying the IP address.
Dim strHostName As String
Dim strIPAddress As String
Public Function ipconfig()
strHostName = System.Net.Dns.GetHostName()
strIPAddress = System.Net.Dns.GetHostEntry(strHostName).AddressList(0).ToString()
rtb_Output.Text = rtb_Output.Text + "Computer Name: " & strHostName + Environment.NewLine + "IP Address: " &strIpAddress
End Function
It works absolutely fine on my Windows 7 desktop wired connection, and returns the IPv4 address as expected.
When I run it on my Windows 8 tablet, either wired or wirelessly, it returns the IPv6 address instead, whereas I need the IPv4 address. Do you have any ideas why, or how I can get it to return the IPv4 address instead?
A: It seems unlikely, but certainly not impossible, that your Windows 8 machine has only IPv6 addresses. However, it is not uncommon to turn off IPv6 support on network adapters for any OS as it is not commonly supported yet. Check the adapters for each computer to verify the addresses and compare to your result.
Regardless, you would be advised to assume that your query will return multiple addresses of type IPv6, IPv4 and more with multiples of any type as well. If you are looking for specific types then use the AddressFamily property to identify type.
For example, for IPv4 only:
Dim hostEntry = Dns.GetHostEntry(hostNameOrAddress)
Dim addressList As New List(Of IPAddress)
For Each address In hostEntry.AddressList
If address.AddressFamily = Sockets.AddressFamily.InterNetwork Then
addressList.Add(address)
End If
Next
Return addressList
A: You can use this:
System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName).AddressList.First.ToString()
A: You can use LINQ to filter the results:
Dim ipHostEntry = Dns.GetHostEntry(Dns.GetHostName)
Dim ipAddress = ipHostEntry.AddressList.FirstOrDefault(Function(ip) ip.AddressFamily = AddressFamily.InterNetwork)
If ipAdress IsNot Nothing Then
' Output ipAdress.ToString()
Else
' No IPv4 address could be retrieved
End If
Explanation:
IPHostAddress.AddressList returns an Array(Of IPAddress) which implements the IEnumerable interface and can therefore be enumerated by LINQ expressions.
FirstOrDefault will return the first element from the AddressList array that matched the predicate lambda function that is submitted as first and only parameter of FirstOrDefault. The predicate function has to be written to return a boolean.
The array is iterated from the first to the last element, and for each element the lambda function is evaluated, where its parameter ip is the current iteration item. With ip.AddressFamily = AddressFamily.InterNetwork we determine whether the current item is an IPv4 address. If so, the expression evaluates true and the item is returned by FirstOrDefault. If it evaluates to false, the next item from the array is checked and so on. If no element matches the predicate, FirstOrDefault returns the default value, in this case Nothing (N. B.: the extension First works the same way but throws an exception if no item matches the predicate; both First and FirstOrDefault can be called without any arguments, they return the first element of the sequence then).
I prefer the extension methods based notation as above, but you can use the original From In Where Select LINQ notation as well if you prefer:
Dim ipAddress = (From ip In ipHostEntry.AddressList
Where ip.AddressFamily = AddressFamily.InterNetwork
Select ip)(0)
Note that (0) is the argument for another extension method ElementAtOrDefault(index As Integer) in this case.
A: Public Function GetIPv4Address()
GetIPv4Address = String.Empty
Dim strmachine As String = System.Net.Dns.GetHostName()
Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strmachine)
For Each ipheal As System.Net.IPAddress In iphe.AddressList
If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
GetIPv4Address = ipheal
' MsgBox(ipheal.ToString, MsgBoxStyle.Critical, "ERROR")
End If
Next
End Function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19713868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Enterprise Autoscale Application Block (WASABi) up by a variable amount I was looking at the WASABi documentation and I am confused about a particular aspect of this library.
I need to create a custom reactive rule. Say, this rule runs every minute and the "scale" action of this rule should be to scale up by "x" amount. It seems that as though I can set the "scale" action to a particular number (say 1 or 2), but not pass in a variable computed by, say my custom operand.
I understand that I can create a custom operand to check my condition, but I want the custom operand to compute how much the "scale" action should scale the target Worker Role by and then pass this value to the "scale" action.
Is there someway to define these rules outside the XML to achieve this?
Any help would be greatly appreciated!
A: Actions can increment or decrement the count by a number or by a proportion. So if you want a dynamic increment or decrement I think you will need to create a custom action. I think you could pull out the info you need from the IRuleEvaluationContext.
To change the instance count you will need to change the deployment configuration. See https://social.msdn.microsoft.com/forums/azure/en-US/dbbf14d1-fd40-4aa3-8c65-a2424702816b/few-question-regarding-changing-instance-count-programmatically?forum=windowsazuredevelopment&prof=required for some discussion.
You should be able to do that using the Azure Management Libraries for .NET and the ComputeManagementClient. Something like:
using (ComputeManagementClient client = new ComputeManagementClient(credentials))
{
var response = await client.Deployments.GetBySlotAsync(serviceName, slot);
XDocument config = XDocument.Parse(response.Configuration);
// Change the config
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
config.Save(writer);
}
string newConfig = builder.ToString();
await client.Deployments.BeginChangingConfigurationBySlotAsync(serviceName, slot, new DeploymentChangeConfigurationParameters(newConfig));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35500177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Write a title on itextPdf table border I'm using iTextPdf to create a table on an android application.
I need to have the title of the table on its upper border as shown on the image below.
How can I achieve this?
Thanks in advance
A: Please take a look at the CellTitle example. It creates a PDF in which titles are added on the cell border: cell_title.pdf
This is accomplished by using a cell event:
class Title implements PdfPCellEvent {
protected String title;
public Title(String title) {
this.title = title;
}
public void cellLayout(PdfPCell cell, Rectangle position,
PdfContentByte[] canvases) {
Chunk c = new Chunk(title);
c.setBackground(BaseColor.LIGHT_GRAY);
PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS];
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
new Phrase(c), position.getLeft(5), position.getTop(5), 0);
}
}
A cell event can be added to a PdfPCell using the setCellEvent() method:
public PdfPCell getCell(String content, String title) {
PdfPCell cell = new PdfPCell(new Phrase(content));
cell.setCellEvent(new Title(title));
cell.setPadding(5);
return cell;
}
Next time, please show what you've tried before asking a question. Also take a look at the official documentation because everything you needed to answer your question yourself was available on the iText web site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35746651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get the a lambda function by using its ARN in the AWS CLI? I'm using the Azure Toolkit for AWS to create my lambda, and then running some powershell scripts to act on it. After creation, I get the function's ARN as an output. I don't see anywhere in the documentation where I can access the function via the ARN, everything takes the function-name as a parameter.
A: You can use the ARN in the --function-name parameter when executing AWS CLI calls for the AWS lambda API.
Here's an example for the get-function api:
--function-name (string)
The name of the Lambda function, version, or alias.
Name formats
Function name - my-function (name-only), my-function:v1 (with alias).
Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function .
Partial ARN - 123456789012:function:my-function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70454310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I split a column into 2 in the correct way? I am web-scraping tables from a website, and I am putting it to the Excel file.
My goal is to split a columns into 2 columns in the correct way.
The columns what i want to split: "FLIGHT"
I want this form:
First example: KL744 --> KL and 0744
Second example: BE1013 --> BE and 1013
So, I need to separete the FIRST 2 character (in the first column), and after that the next characters which are 1-2-3-4 characters. If 4 it's oke, i keep it, if 3, I want to put a 0 before it, if 2 : I want to put 00 before it (so my goal is to get 4 character/number in the second column.)
How Can I do this?
Here my relevant code, which is already contains a formatting code.
df2 = pd.DataFrame(datatable,columns = cols)
df2["UPLOAD_TIME"] = datetime.now()
mask = np.column_stack([df2[col].astype(str).str.contains(r"Scheduled", na=True) for col in df2])
df3 = df2.loc[~mask.any(axis=1)]
if os.path.isfile("output.csv"):
df1 = pd.read_csv("output.csv", sep=";")
df4 = pd.concat([df1,df3])
df4.to_csv("output.csv", index=False, sep=";")
else:
df3.to_csv
df3.to_csv("output.csv", index=False, sep=";")
Here the excel prt sc from my table:
A: You can use indexing with str with zfill:
df = pd.DataFrame({'FLIGHT':['KL744','BE1013']})
df['a'] = df['FLIGHT'].str[:2]
df['b'] = df['FLIGHT'].str[2:].str.zfill(4)
print (df)
FLIGHT a b
0 KL744 KL 0744
1 BE1013 BE 1013
I believe in your code need:
df2 = pd.DataFrame(datatable,columns = cols)
df2['a'] = df2['FLIGHT'].str[:2]
df2['b'] = df2['FLIGHT'].str[2:].str.zfill(4)
df2["UPLOAD_TIME"] = datetime.now()
...
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46522269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Finding the Intersection of 2 sorted lists I have an assignment for
Given two sorted lists of comparable items,
L1 and L2. You can assume that in L1 and
L2 all elements are different (no duplicates) but t
he interception between L1 and L2 may be
non-empty.
(b)
Implement an efficient method in
Java to compute the symmetric difference(∆)
between L1 and L2, L1 ∆L2. Please remember that in
set theory, the symmetric
difference of two sets A and B is the set of elements either in A or in B but not in both.
Example: Suppose A = {1,3,5,7,9} and B = {1,2,3,4,5}, A ∆ B = {2,4,7,9}.
I wrote this so far but I don't know why it stops the search at the end of the first list and doesn't continue checking the 2nd list for differences. Any help?
public static <AnyType extends Comparable<? super AnyType>>
void symDifference(List<AnyType> L1, List<AnyType> L2,
List<AnyType> Difference)
{
ListIterator<AnyType> iterL1 = L1.listIterator();
ListIterator<AnyType> iterL2 = L2.listIterator();
AnyType itemL1 = null;
AnyType itemL2 = null;
if (iterL1.hasNext() && iterL2.hasNext())
{
itemL1 = iterL1.next();
itemL2 = iterL2.next();
}
while (itemL1 != null && itemL2 != null)
{
int compareResult = itemL1.compareTo(itemL2);
if (compareResult == 0)
{
itemL1 = iterL1.hasNext() ? iterL1.next() : null;
itemL2 = iterL2.hasNext() ? iterL2.next() : null;
}
else if (compareResult < 0)
{
Difference.add(itemL1);
itemL1 = iterL1.hasNext() ? iterL1.next() : null;
}
else
{
Difference.add(itemL2);
itemL2 = iterL2.hasNext() ? iterL2.next() : null;
}
}
}
public static void main(String[] args)
{
LinkedList<Integer> list1 = new LinkedList<>();
LinkedList<Integer> list2 = new LinkedList<>();
LinkedList<Integer> difList = new LinkedList<>();
list1.add(1);
list1.add(3);
list1.add(5);
list1.add(7);
list1.add(9);
list2.add(1);
list2.add(2);
list2.add(3);
list2.add(4);
list2.add(5);
symDifference(list1,list2,difList);
System.out.println(difList);
}
}
A: Well, think about this.
list1 {1, 2, 3, 5}
list2 {1, 5}.
As shmosel said, what happen if your loop runs twice? It exit the loop, and the function.
Ideally, you want to go through all elements on both array.
BTW, I don't think your solution is working as well (you can of cause, but your code will look super ugly, probably takes O(list1.length * list2.length)). Since both lists are sorted, you can compare both element, and loop the smaller element list first. For example, using list1 and list2, compare 1 and 1, both equal, then move to 2 and 5. Then compare 2 and 5, add 2 to the list, and move 2 to 3 ONLY. Which takes O(list1.length + list2.length).
A: It’s a classic pitfall. When one list runs dry, your loop stops (as it should). At this point you will still want to exhaust the other list. So after your while loop insert the logic to copy the remaining elements from the other list. Since you know one list is done and only one has elements remaining, but you don’t know which, the easy solution is just to take the remaining elements from both lists. Since both lists were sorted, you know that the remainder of the list that still has elements in it cannot contain any elements from the run-dry list, so you simply add them all to your result. All in all you will probably add two while loops after the loop you have, one for iterL1 and one for iterL2. Since each of these run in linear time, your time complexity will not get hurt.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39782200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Intechanging node roles in Hyperledger Fabric Can nodes interchange roles in hyperledger fabric?
Is it possible to make an endorsing or committing peer take the role of an orderer when required?
A: *
*Every endorsing peer is also a committing peer.
*An orderer and a peer are totally different binaries, and have completely different APIs, so - you can't have one fill the role of the other.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52457719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Docusign navigate to a Visualforce page upon signing Can we navigate signer who is on a Mobile device (Salesforce 1) to a visualforce page when the document is signed and the submit button is clicked?
A: Yes you can accomplish this. You'll need to use the DocuSign API and more specifically, the Embedding functionality which will allow you to sign through a webview or an iFrame on the mobile device.
With Embedding you can control the redirects URLs based on actions the user takes. For instance, if the user signs you can navigate to the Visual Force page in question. Or, if the user declines to sign then you can navigate them to a different page if you'd like. Same thing for if they hit the X to close the signing window.
To get started with learning DocuSign's APIs check out the DocuSign Developer Center:
http://www.docusign.com/developer-center
And for code samples of Embedded Signing in 6 different language stacks see the bottom 3 API Walkthroughs in the API Tools section:
http://iodocs.docusign.com/apiwalkthroughs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30404676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tickets 3.12A PHP line issue I have a TicketsCAD installation issue. I installed locally, and the install went fine, everything was well. Then, when I went to login to the admin backend, it gave me this error:
Warning: A non-numeric value encountered in C:\xampp\htdocs\tickets\incs\browser.inc.php on line 25
So, I went and checked the file, line 25:
$j=strpos($userAgent, $navigator)+$n+strlen($navigator)+1;
I don't immediately see anything wrong with this syntax. Any help would be much appreciated.
(FYI: I am not a super-programmer, as many of you are. Please go easy on me.)
PHP Version 7.2.4
Here is the entire piece of code:
$l = strlen($userAgent);
for ($i=0; $i<count($browsers); $i++){
$browser = $browsers[$i];
$n = stristr($userAgent, $browser);
if(strlen($n)>0){
$version = "";
$navigator = $browser;
$j = $pos+$n+strlen($navigator)+1;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50034880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Executing a script takes so long on Git Bash I'm currently executing a script on Git Bash on a Windows 7 VM. The same script is executed within 15-20 seconds on my Mac machine, but it takes almost 1 hour to run on my Windows.
The script itself contains packages that extract data from XML files, and does not call upon any APIs or anything of the sort.
I have no idea what's going on, and I've tried solving it with the following answers, but to no avail:
*
*https://askubuntu.com/a/738493
*https://github.com/git-for-windows/git/wiki/Diagnosing-performance-issues
I would like to have someone help me out in diagnosing or giving a few pointers on what I could do to either understand where the issue is, or how to resolve it altogether.
EDIT:
I am not able to share the entire script, but you can see the type of commands that the script uses through previous questions I have asked on Stackoverflow. Essentially, there is a mixture of XMLStarlet commands that are used.
*
*https://stackoverflow.com/a/58694678/3480297
*https://stackoverflow.com/a/58693691/3480297
*https://stackoverflow.com/a/58080702/3480297
EDIT2:
As a high level overview, the script essentially loops over a folder for XML files, and then retrieves certain data from each one of those files, before creating an HTML page and pasting that data in tables.
A breakdown of these steps in terms of the code can be seen below:
Searching folder for XML files and looping through each one
for file in "$directory"*
do
if [[ "$file" == *".xml"* ]]; then
filePath+=( "$file" )
fi
done
for ((j=0; j < ${#filePath[@]}; j++)); do
retrieveData "${filePath[j]}"
done
Retrieving data from the XML file in question
function retrieveData() {
filePath=$1
# Retrieve data from the revelent xml file
dataRow=$(xml sel -t -v "//xsd:element[@name=\"$data\"]/@type" -n "$filePath")
outputRow "$dataRow"
}
Outputting the data to an HTML table
function outputRow() {
rowValue=$1
cat >> "$HTMLFILE" << EOF
<td>
<div>$rowValue</div>
</td>
EOF
}
As previously mentioned, the actual xml commands used to retrieve the relevant data can differ, however, the links to my previous questions have the different types of commands used.
A: Your git-bash installation is out of date.
Execute git --version to confirm this. Are you using something from before 2.x?
Please install the latest version of git-bash, which is 2.24.0 as of 2019-11-13.
See the Release Notes for git for more information about performance improvements over time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58802988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I remove NLP from Tika? I just want to extract data from documents. So I do not think I need OpenNLP.
Is there a way to easily take it out so my Tika is lighter?
A: I have same need just like you.The way I deal with it is that I delete the module directly.In my program I delete the NLP and NL module and it works normally.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49058251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to search for Arabic charterers in recorders of DB2 I have a table in DB2 say premmp wherein a column say name might contain Arabic characters
Dim s As String = "SELECT EMPNO, NAME FROM lib.PRemmp where NAME like '% " & gname.text & " %' ORDER BY RNAME "
where gname.text is a textbox. It does not work, anyone can help me?
I write this code
Adapter.SelectCommand = New OdbcCommand("SELECT EMPNO, NAME FROM lib.PRemmp where NAME like ? ", MyODBCConnection)
Adapter.SelectCommand.Parameters.Add("@NAME", Odbc.OdbcType.NVarChar).Value = "%" & gname.Text
Adapter.SelectCommand.ExecuteNonQuery()
Adapter.Fill(ds, "MyTable")
it solve my problem
thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43997900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Functional object basics. How to go beyond simple containers? On the upside I'm kinda bright, on the downside I'm wracked with ADD. If I have a simple example, that fits with what I already understand, I get it. I hope someone here can help me get it.
I've got a page that, on an interval, polls a server, processes the data, stores it in an object, and displays it in a div. It is using global variables, and outputing to a div defined in my html. I have to get it into an object so I can create multiple instances, pointed at different servers, and managing their data seperately.
My code is basically structured like this...
HTML...
<div id="server_output" class="data_div"></div>
JavaScript...
// globals
var server_url = "http://some.net/address?client=Some+Client";
var data = new Object();
var since_record_id;
var interval_id;
// window onload
window.onload(){
getRecent();
interval_id = setInterval(function(){
pollForNew();
}, 300000);
}
function getRecent(){
var url = server_url + '&recent=20';
// do stuff that relies on globals
// and literal reference to "server_output" div.
}
function pollForNew(){
var url = server_url + '&since_record_id=' + since_record_id;
// again dealing with globals and "server_output".
}
How would I go about formatting that into an object with the globals defined as attributes, and member functions(?) Preferably one that builds its own output div on creation, and returns a reference to it. So I could do something like...
dataOne = new MyDataDiv('http://address/?client');
dataOne.style.left = "30px";
dataTwo = new MyDataDiv('http://different/?client');
dataTwo.style.left = "500px";
My code is actually much more convoluted than this, but I think if I could understand this, I could apply it to what I've already got. If there is anything I've asked for that just isn't possible please tell me. I intend to figure this out, and will. Just typing out the question has helped my ADD addled mind get a better handle on what I'm actually trying to do.
As always... Any help is help.
Thanks
Skip
UPDATE:
I've already got this...
$("body").prepend("<div>text</div>");
this.test = document.body.firstChild;
this.test.style.backgroundColor = "blue";
That's a div created in code, and a reference that can be returned. Stick it in a function, it works.
UPDATE AGAIN:
I've got draggable popups created and manipulated as objects with one prototype function. Here's the fiddle. That's my first fiddle! The popups are key to my project, and from what I've learned the data functionality will come easy.
A: This is pretty close:
// globals
var pairs = {
{ div : 'div1', url : 'http://some.net/address?client=Some+Client' } ,
{ div : 'div2', url : 'http://some.net/otheraddress?client=Some+Client' } ,
};
var since_record_id; //?? not sure what this is
var intervals = [];
// window onload
window.onload(){ // I don't think this is gonna work
for(var i; i<pairs.length; i++) {
getRecent(pairs[i]);
intervals.push(setInterval(function(){
pollForNew(map[i]);
}, 300000));
}
}
function getRecent(map){
var url = map.url + '&recent=20';
// do stuff here to retrieve the resource
var content = loadResoucrce(url); // must define this
var elt = document.getElementById(map.div);
elt.innerHTML = content;
}
function pollForNew(map){
var url = map.url + '&since_record_id=' + since_record_id;
var content = loadResoucrce(url); // returns an html fragment
var elt = document.getElementById(map.div);
elt.innerHTML = content;
}
and the html obviously needs two divs:
<div id='div1' class='data_div'></div>
<div id='div2' class='data_div'></div>
Your 'window.onload` - I don't think that's gonna work, but maybe you have it set up correctly and didn't want to bother putting in all the code.
About my suggested code - it defines an array in the global scope, an array of objects. Each object is a map, a dictionary if you like. These are the params for each div. It supplies the div id, and the url stub. If you have other params that vary according to div, put them in the map.
Then, call getRecent() once for each map object. Inside the function you can unwrap the map object and get at its parameters.
You also want to set up that interval within the loop, using the same parameterization. I myself would prefer to use setTimeout(), but that's just me.
You need to supply the loadResource() function that accepts a URL (string) and returns the HTML available at that URL.
This solves the problem of modularity, but it is not "an object" or class-based approach to the problem. I'm not sure why you'd want one with such a simple task. Here's a crack an an object that does what you want:
(function() {
var getRecent = function(url, div){
url = url + '&recent=20';
// do stuff here to retrieve the resource
var content = loadResoucrce(url); // must define this
var elt = document.getElementById(div);
elt.innerHTML = content;
}
var pollForNew = function(url, div){
url = url + '&since_record_id=' + since_record_id;
var content = loadResoucrce(url); // returns an html fragment
var elt = document.getElementById(div);
elt.innerHTML = content;
}
UpdatingDataDiv = function(map) {
if (! (this instanceof arguments.callee) ) {
var error = new Error("you must use new to instantiate this class");
error.source = "UpdatingDataDiv";
throw error;
}
this.url = map.url;
this.div = map.div;
this.interval = map.interval || 30000; // default 30s
var self = this;
getRecent(this.url, this.div);
this.intervalId = setInterval(function(){
pollForNew(self.url, self.div);
}, this.interval);
};
UpdatingDataDiv.prototype.cancel = function() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
})();
var d1= new UpdatingDataDiv('div1','http://some.net/address?client=Some+Client');
var d2= new UpdatingDataDiv('div2','http://some.net/otheraddress?client=Some+Client');
...
d1.cancel();
But there's not a lot you can do with d1 and d2. You can invoke cancel() to stop the updating. I guess you could add more functions to extend its capability.
A: OK, figured out what I needed. It's pretty straight forward.
First off disregard window.onload, the object is defined as a function and when you instantiate a new object it runs the function. Do your setup in the function.
Second, for global variables that you wish to make local to your object, simply define them as this.variable_name; within the object. Those variables are visible throughout the object, and its member functions.
Third, define your member functions as object.prototype.function = function(){};
Fourth, for my case, the object function should return this; This allows regular program flow to examine the variables of the object using dot notation.
This is the answer I was looking for. It takes my non-functional example code, and repackages it as an object...
function ServerObject(url){
// global to the object
this.server_url = url;
this.data = new Object();
this.since_record_id;
this.interval_id;
// do the onload functions
this.getRecent();
this.interval_id = setInterval(function(){
this.pollForNew();
}, 300000);
// do other stuff to setup the object
return this;
}
// define the getRecent function
ServerObject.prototype.getRecent = function(){
// do getRecent(); stuff
// reference object variables as this.variable;
}
// same for pollForNew();
ServerObject.prototype.pollForNew = function(){
// do pollForNew(); stuff here.
// reference object variables as this.variable;
}
Then in your program flow you do something like...
var server = new ServerObject("http://some.net/address");
server.variable = newValue; // access object variables
I mentioned the ADD in the first post. I'm smart enough to know how complex objects can be, and when I look for examples and explanations they expose certain layers of those complexities that cause my mind to just swim. It is difficult to drill down to the simple rules that get you started on the ground floor. What's the scope of 'this'? Sure I'll figure that out someday, but the simple truth is, you gotta reference 'this'.
Thanks
I wish I had more to offer.
Skip
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5986524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using SqlCommand inside of AddSession in ASP.NET Core I was trying to execute a SqlCommand after the TimeSpan ends. When the IdleTimeout has been called, the user would go into the homepage and need to login again. But in addition. I want to call a command for my Last Login:
//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddControllersWithViews();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
});
services.AddMvc();
services.AddHsts(options =>
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(30);
});
}
I would like to add a SqlConnection and SqlCommand inside of this part of the code:
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
});
I tried many things inside of it, after debugging. When the user logged in it will start the AddSession and I thought it will only execute when the TimeSpan ends. Where can I put the end of the command after Timespan ends?
Here's my scenario:
*
*When User logs in, AddSession starts
*When the user idled for 10 mins, it will execute the SqlCommand with last login
*After executing the last login will update into new DateTime
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73752300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google BigQuery exports numeric data with wrong decimal to Sheets In our workflow we often export results from a query on BigQuery to Google Sheets, e.g. for distribution to customers in .xlsx format.
I'm running into something weird: when explicitly casting the output of a query to numeric, the export in Sheets gives errors in for the decimals.
For example,
select
cast('12.3' as numeric),
cast('12.34' as numeric),
cast(12.056 as numeric),
cast('12.345786' as float64)
Yields the following query result in the WebUI
Row f0_ f1_ f2_ f3_
1 12.3 12.34 12.056 12.345786
However, the result in Google Sheets (again, using the WebUI, option Save to Sheets), is this:
f0_ f1_ f2_ f3_
12.3 1234 12056 12345786
Only pattern I can see is that the decimal sign is erroneously dropped when there are two or more decimals.
I really have no clue what is causing this, let alone how to fix it. Exporting the data to .csv and .json does yield the correct result.
Help, anyone?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52206177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Swift proper way to load xib file I have some strange problem with loading xib file in swift project. It's so frustrating because I already know how to do it in Obj-C. But since swift is swift so you can't do it like you did.. :/
So I have create IconTextFiled.xib and IconTextField.swift. (extends UITextField) In xib I fill field Class in Idenity inspector and in storyboard I do the same for some textFields. So we good to go just add loading from xib to init method? No.
In objc I would do it like this
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"IconTextField" owner:self options:nil];
self = [nib objectAtIndex:0];
}
return self;
}
So I thought if I translate to swift it will be good.
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let nib:NSArray = NSBundle.mainBundle().loadNibNamed("IconTextField", owner: self, options: nil)
self = nib.objectAtIndex(0)
}
But that doeasn't work. I don't know why but it try to create much more object and crash
Finally I found extension
extension IconTextField {
class func loadFromNibNamed(nibNamed: String, bundle : NSBundle? = nil) -> IconTextField? {
return UINib(
nibName: nibNamed,
bundle: bundle
).instantiateWithOwner(nil, options: nil)[0] as? IconTextField
}
}
So in ViewController it looks like
@IBOutlet var password: IconTextField!
override func viewDidLoad() {
super.viewDidLoad()
password = IconTextField.loadFromNibNamed("IconTextField")
}
And again fail. Could you tell me how you load and use xib files?
UPDATE
Ok following after Daniel anwser
My current code
class IconTextField: UITextField {
@IBOutlet var icon: UIImageView!
@IBOutlet weak var view: UIView!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSLog("initWithCoder \(self)")
NSBundle.mainBundle().loadNibNamed("IconTextField", owner: self, options: nil)
self.addSubview(view)
}
}
Those two var are connected to those views
Consoleo output, was a lot bigger and end with EXC_BAD_ACCESS
2014-10-24 10:09:09.984 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7be7bfb0;>
2014-10-24 10:09:09.984 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7be7ddf0;>
2014-10-24 10:09:09.985 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7be7fa20;>
2014-10-24 10:09:09.985 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7be814f0;>
2014-10-24 10:09:09.986 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7be830c0;>
2014-10-24 10:09:10.083 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7d183270;>
2014-10-24 10:09:10.084 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7d187cd0;>
2014-10-24 10:09:10.084 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7d189960;>
It should be only two initWithCoder. It seams that func loadNibNamed is calling initWithCoder
A: This works for me:
class IconTextField: UITextField {
@IBOutlet weak var view: UIView!
@IBOutlet weak var test: UIButton!
required init(coder: NSCoder) {
super.init(coder: coder)
NSBundle.mainBundle().loadNibNamed("IconTextField", owner: self, options: nil)
self.addSubview(view)
assert(test != nil, "the button is conected just like it's supposed to be")
}
}
Once loadNibNamed:owner:options: is called the view and test button are connected to the outlets as expected. Adding the nib's view self's subview hierarchy makes the nib's contents visible.
A: I prefer to load from nib, by implementing loadFromNib() function in a protocol extension as follows:
(as explained here: https://stackoverflow.com/a/33424509/845027)
import UIKit
protocol UIViewLoading {}
extension UIView : UIViewLoading {}
extension UIViewLoading where Self : UIView {
// note that this method returns an instance of type `Self`, rather than UIView
static func loadFromNib() -> Self {
let nibName = "\(self)".characters.split{$0 == "."}.map(String.init).last!
let nib = UINib(nibName: nibName, bundle: nil)
return nib.instantiateWithOwner(self, options: nil).first as! Self
}
}
A: You can use this:
if let customView = Bundle.main.loadNibNamed("MyCustomView", owner: self, options: nil)?.first as? MyCustomView {
// Set your view here with instantiated customView
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26539849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Get property value with Expression without knowing target type at compile time I'm trying to create an expression lambda to pass an object, and then get the value for named property return. However the type is only known at runtime.
I started with the following method to handle types known at compile time:
private static Func<T, object> CreateExpression(string propertyName)
{
var arg = Expression.Parameter(typeof(T));
var expr = Expression.Property(arg, propertyName);
return Expression.Lambda<Func<T, object>>(expr, arg).Compile();
}
Which worked perfect. However, i need to change it to handle types only known at runtime.
I should be able to call the delegate like this:
public object GetPropertyValue(object obj)
{
var propertyDelegate = GetDelegate(typeof(obj));
var propertyValue = propertyDelegate (obj);
return propertyValue;
}
private Func<object, object> GetDelegate(Type type)
{
// Lookup delegate in dictionary, or create if not existing
return CreateDelegate("MyProperty", type);
}
I tried changing the CreateDelegate from before, but it will not work with Func<object, object>:
Func<object,object> CreateDelegate(string propertyName, Type targetType)
{
var arg = Expression.Parameter(type);
var body = Expression.Property(arg, name);
var lambda = Expression.Lambda<Func<object,object>>(body, arg); //ArgumentException
return lambda.Compile();
}
It will not accept the Expresion.Parameter, since it is of type 'targetType', and not of type 'object'.
Do i need a Expression.Convert or something?
NOTE: The delegate will be called many times (Filtering method), so it need to be compiled, to ensure performance.
EDIT: Solution (provided by Marc Gravell)
the variable 'body' should be changed to the following:
var body = Expression.Convert(
Expression.Property(
Expression.Convert(arg, type),
name),
typeof(object));
Inner Convert converts input parameter to object, and the outer Convert converts the return value.
A: Yes:
var arg = Expression.Parameter(typeof(object));
var expr = Expression.Property(Expression.Convert(arg, type), propertyName);
Note: the return type (object) means that many types will need to be boxed. Since you mention you are doing this for filtering: if possible, try to avoid this box by creating instead a Func<object,bool> that does any comparisons etc internally without boxing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27795483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: fork() and waitpid possible outputs My textbook gives the following main routine:
int main()
{
if(fork() == 0)
{
printf("a");
}
else
{
printf("b");
waitpid(-1, NULL, 0);
}
printf("c");
exit(0);
}
It asks what the possible outputs are, and I have found 3:
abcc: The OS chooses the child process to execute first, and prints "a". Then, the OS pauses the child process and resumes the parent process, printing "b". Then the parent must wait until the child is done, and the child prints "c", and finally the parent prints "c".
bacc: The OS chooses the parent process to run first, and prints "b". Then the parent must wait for the child to complete and print "ac". Then the parent prints "c".
acbc: The OS chooses the child to run first until completion, printing "ac". Then the parent runs to completion, printing "bc".
However, there is one more answer listed in the textbook, bcac. I don't understand how this is possible because if b is printed first, then the parent must wait for the child to continue, and print "ac", then the parent would print "c", giving bacc which I've already listed. Is there something I'm missing, or is it correct to say there are only 3 possible outputs?
A: Don't always trust textbooks...
From the errata:
p. 772, Solution to Practice Problem 8.3. The sequence bcac is not
possible. Strike the second to last sentence. The last sentence should
be “There are three possible sequences: acbc, abcc, and bacc.” Please
see Web Aside ECF:GRAPHS on the Web Aside page for an example of the
process graph.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20335081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get values of parameters of javascript function from Java? For my Java application I need to be able of, given a JavaScript string, determine the actual arguments passed into a function call.
For example, given this JavaScript string:
const url = "http://foo.bar?q=" + location.href
const method = "GET"
const isAjax = true
let xmlhttp = new XMLHttpRequest();
xmlhttp.open(method, url, isAjax);
I would like to evaluate this JavaScript in order to get this:
xmlhttp.open("GET", "http://foo.bar?q=someurl", true);
Right now I'm using a regex to look for the parts of the JavaScript I'm interested in (in this example it would be the open method of the XMLHttpRequest object), but I need to be able to compute the actual values of the arguments passed to a function, if they are not hardcoded from the call-side.
I have been searching here but what I found was more related to actually executing the JavaScript code rather than looking at its expressions values (more like evaluating it, getting an AST or something like that).
Any ideas on how to accomplish this?
A: My idea is to add some javascript mocking library like sinon and execute this javascript.
Especially take a look at fake XMLHttpRequest
Javascript code will like this:
let sinon = require('sinon');
let xhr = sinon.useFakeXMLHttpRequest();
let requests = [];
xhr.onCreate = function (xhr) {
requests.push(xhr);
}
const url = "http://foo.bar?q=" + location.href
const method = "GET"
const isAjax = true
let xmlhttp = new XMLHttpRequest();
xmlhttp.open(method, url, isAjax);
console.log(requests[0].url)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50487385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery BlockUI not Unblocking the Page I am having a really weird problem! I used the blockUI JQuery plugin in one of my pages and it worked fine. I did the same for another page and it is not unblocking the page when $unblockUI is called.
Here is the code:
function showCommentBox()
{
$("#commentBox").addClass("modalPopup");
alert($("#commentBox").hasClass("modalPopup"));
$.blockUI( { message: $("#commentBox") } );
}
function cancelComment()
{
alert($("#commentBox").hasClass("modalPopup"));
$.unblockUI();
}
The page that does not work returns "false" when the $("#commentBox").hasClass("modalPopup") is evaluated in the cancelComment function while the page that works correctly returns true.
A: @Azam - There's nothing wrong with the code you posted above. There's no reason why it shouldn't work. I copied the code in the post directly and tested in this jsbin page. See it for yourself.
To keep it as simple as possible this is all I used for the HTML body.
<input type="button" value="Show Comment" onclick="showCommentBox()" />
<div id="commentBox" style="display:none"><br/>
This is the text from the CommentBox Div<br/>
<input type="button" value="Cancel" onclick="cancelComment()" />
</div>
EDIT: After reading some of your other posts, I realized that real reason for the problem is that your are adding the "commentBox" div inside a GridView's ItemTemplate. This causes the creation of the same div with the same ID multiplied by the number of rows in your gridview. Normally, having the same id in multiple HTML elements is bad, but this is what the gridview does.
Here's a workaround that I tested and it works. Change your two functions to this:
function showCommentBox() {
$.currentBox = $("#commentBox");
$.currentBox.addClass("modalPopup");
alert($.currentBox.hasClass("modalPopup"));
$.blockUI( { message: $.currentBox } );
}
function cancelComment() {
alert($.currentBox.hasClass("modalPopup"));
$.unblockUI();
}
Here I'm using a jQuery variable to store a reference to the commentBox DIV and passing that to $.blockUI, in that way the call to $.unblockUI() will work correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/912804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why to use multiple catch blocks? We can use multiple catch block in Try-Catch.
But my Question is : why to use multiple catch blocks when it can be done by using single catch block?
*
*Suppose I want exact cause of my problem, I can get that by Ex.message
*If I want to show customized message to user, I can show it by putting If-Else loop on Ex.Message.
Thanks in advance.
A: To handle the individual exception accordingly.
For example:
If your program is handling both database and files. If an SQLException occurs, you have to handle it database manner like closing the dbConnection/reader etc., whereas if a File handling exception then you may handle it differently like file closing, fileNotFound etc.
That is the main reason in my point of view.
For point numbers 1 and 2:
If showing error message is you main idea then you can use if..else. In case if you want to handle the exception then check the above point of my answer. The reason why I stretch the word handling is because it is entirely different from showing a simple error message.
To add some quotes I prefer Best Practices for Handling Exceptions which says
A well-designed set of error handling code blocks can make a program
more robust and less prone to crashing because the application handles
such errors.
A: This works only if all exceptions share the same base class, then you could do it this way.
But if you do need exception type specific handling, then I would prefer multiple try-catch blocks instead of one with type-depending if-else ...
A: You can also ask why do we need the Switch - Case. You can do it with If - Else.
And why do you need Else at all. You can do it with If (If not the first condition, and...).
It's a matter of writing a clean and readable code.
A: By using single catch clock you can catch Exception type - this practice is strongly discouraged by Microsoft programming guidelines. FxCop has the rule DoNotCatchGeneralExceptionTypes which is treated as CriticalError:
Catching general exception types can hide run-time problems from the library user, and can complicate debugging.
http://code.praqma.net/docs/fxcop/Rules/Design/DoNotCatchGeneralExceptionTypes.html
The program should catch only expected exception types (one ore more), leaving unexpected types unhandled. To do this, we need possibility to have multiple catch blocks. See also:
Why does FxCop warn against catch(Exception)?
http://blogs.msdn.com/b/codeanalysis/archive/2006/06/14/631923.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18733569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Internet explorer some elements dont work In Internet Explorer some elements don't work: Chat, Contact, Tutorial, Survey. These elements work in Firefox and Chrome.
http://hotelpedia.si is the website.
I have this code in the footer. I don't understand why this would cause some elements not to load in Internet Explorer.
{if $is_ie_browser}
<!--[if lt IE 9]><link rel="stylesheet" href="{$smarty.const.DOMAIN}/css/ie.css" type="text/css" /><![endif]-->
<!--[if IE 7]><link rel="stylesheet" href="{$smarty.const.DOMAIN}/css/ie_7.css" type="text/css" /><![endif]-->
{/if}
{/if}
A: Your code checks to see if internet explorer is less than internet explorer 9 and if so display one css. otherwise if internet explorer 7 then use the other css. If you are using internet explorer 10 then you likely do not have a css page (atleast from what we can see in the code that you posted. change that second line to be "if lt IE10" or add a line that uses greater than equal 8 "gte"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18004625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Better ways to implement more secure Play Scala framework session via cookie I really like the idea to keep session data on the users browser but don't like the fact that session cookies are not very secure in play framework. If someones steals the cookie, he/she could use it to permanently access the site since cookie signature is not expiring and cookie expiration doesn't help here because it doesn't stop from reusing the cookie if someone has stolen it.
I've added time stamp to expire the session after 1hr and every 5min to update the time stamp if user is still using the site so the cookie signature is rolling and expiring.
I am pretty new to scala and play framework so any suggestions or better ways to achieve the same would be much appreciated.
trait Secured {
def withAuth(f: => String => Request[AnyContent] => Result) = {
Security.Authenticated(username, onUnauthorized) { user =>
Action(request => {
val sessionRolloverPeriod = 300
val sessionExpiryTime = 3600
val sessionCreationTime: Int = request.session("ts").toInt
val currentTime = System.currentTimeMillis() / 1000L
if(currentTime <= (sessionCreationTime + sessionExpiryTime)) {
if(currentTime >= (sessionCreationTime + sessionRolloverPeriod)) {
f(user)(request).withSession(request.session + ("ts" -> (System.currentTimeMillis() / 1000L).toString))
} else {
f(user)(request)
}
} else {
Results.Redirect(routes.Auth.login()).withNewSession
}
}
)
}
}
}
Cookies produced every 5min:
The cookies produced every 5min:
Cookie:PS="a6bdf9df798c24a8836c2b2222ec1ea4a4251f301-username=admin&ts=1381180064"
Cookie:PS="D7edg7df709b54B1537c2b9862dc2eaff40001c90-username=admin&ts=1381180380"
A: Seems reasonable to me, I probably put it serverside though, give the client a "session-id" and delete the session when a user logs out. Doing it all client side means there is no way to invalidate the session if it has been stolen except to wait for the timeout.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19235043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Error with docpad-plugin-gulp I'm trying to use the gulp docpad plugin and I get the following error when I execute docpad run:
Error: spawn UNKNOWN
at exports._errnoException (util.js:837:11)
at ChildProcess.spawn (internal/child_process.js:298:11)
at Object.exports.spawn (child_process.js:339:9)
at Task.<anonymous> (C:\Projects\docpad-project\node_modules\docpad-plugin-gulp\node_modules\safeps\es5\lib\safeps.js:595:43)
at ambi (C:\Projects\docpad-project\node_modules\ambi\es5\lib\ambi.js:101:14)
at Domain.fireMethod (C:\Projects\docpad-project\node_modules\taskgroup\out\lib\taskgroup.js:397:23)
at Domain.run (domain.js:191:14)
at Task.fire (C:\Projects\docpad-project\node_modules\taskgroup\out\lib\taskgroup.js:435:27)
at Immediate._onImmediate (C:\Projects\docpad-project\node_modules\taskgroup\out\lib\taskgroup.js:452:26)
at processImmediate [as _immediateCallback] (timers.js:374:17)'
Everything works after uninstalling the plugin.
A: Not sure what caused the error, but running Docpad in an elevated command prompt solved the problem for me. I'm working on Windows 10. (I bet this issue is Windows related.)
To open a cmd with admin privileges, hit menu start and type cmd. Then hit ctrl+shift+enter or hit the right mouse button and select 'run as administrator'. The solution works in a Git Bash terminal with extra privileges, as well.
Edit: Today it broke again :/ (to the point that I question whether it did work yesterday...) The quest for an answer has started again...
Edit 2: The error is caused by docpad-plugin-gulp (or its dependencies) for sure; running the Gulp tasks directly works fine.
However, I found a setting in docpad-plugin-gulp called background. Setting this to true will run Gulp in the background. More important is that it removes the experienced errors altogether. This leads me to suspect the issue is caused by rule 64-67 of the plugin (out/gulp.plugin.js) or the functions it calls there:
this.safeps.spawn(command, {
cwd: rootPath,
output: true
}, next);
I hope people more knowledgeable of this topic can confirm my suspicions and/or fix the plugin. For now, updating your docpad.coffee like below should bypass the errors.
docpadConfig = {
# Other docpad settings
plugins:
gulp:
background: true
}
module.exports = docpadConfig
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34160665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Laravel route cache missing entries I have defined a custom service provider:
class DomainServiceProvider extends ServiceProvider implements DeferrableProvider
{
public function boot()
{
$this->tenants()->each(function (Tenant $tenant) {
$this->registerWebRoutes($tenant);
});
}
protected function registerWebRoutes(Tenant $tenant): void
{
Route::group([
'as' => "{$tenant->namespace}.", // e.g. foo.
'domain' => $tenant->domain, // e.g. foo.com
'middleware' => 'web',
], function () use ($tenant) {
$this->loadRoutesFrom(app_path("Domain/{$tenant->name}/Routes/web.php"));
});
}
I can see all the routes using php artisan route:list, however when optimizing with php artisan route:cache, the routes don't get included into the cache. It seems they are removed, and I don't know why.
The namespace and domain are unique.
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73312459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Polymer 2 : component doesn't render I'm trying to create a Polymer element using the CLI. My component is really simple but the demo is blank.
It was working and I can't figure out what I've changed. After searching around the internet I think the problem is a wrong path or a wrong name (case sensitivity ?).
But I haven't found anything.
There isn't any error in the console and since I don't really know what code to link here, I've created a repo to share this little element.
The code is very little. I think sharing the 'hole' element is the easiest way.
repo : https://gitlab.com/mildful/test-polymer.git
Thanks a lot.
A: You are not calling super.ready() in your ready callback.
This is required because the Polymer.Element declares a ready function to initialise the elements template and data system. As you are overriding this function, you need to call the super class function to initialise your element.
See the info on initialisation.
Without super.ready()
With call to super.ready()
I also noticed that in your handleClick function, you have mis-typed the function you wish to call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45854526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: String.replace() Python remove first coincidence Following the Python documentation for string.replace, I'm trying to replace a string, such as "843845ab38". How can I make a string.replace(old,new) only replacing the first coincidence?
example:
a="843845ab38"
a.replace("8","")
print a
The solution that I'm looking for is "43845ab38", replacing the first 8 by a space.
A: str.replace() takes a 3rd argument, called count:
a.replace("8", "", 1)
By passing in 1 as the count only the first occurance of '8' is replaced:
>>> a = "843845ab38"
>>> a.replace("8", "", 1)
'43845ab38'
A: You don't have to use replace function.
Just
a[1:] will be enough
however if you want to replace all "8"s
then you may want to use replace
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15191098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I am trying to pass a print instruction if an item is not in a list in python. It is working for only when the pin is wrong not for wrong account account_name = ['Adetunji Michael', 'Dina Asher-Smith', 'Niyola Davidson', 'John Paul']
valid_accounts= [3455590445, 2871290429, 3599076267, 1234567890]
valid_pins = [34777, 45786, 24055, 12345]
account_balance= [112000, 45700, 2300, 30000]
#This is the introductory aesthetic.
print(" *************************")
print(" ABC BANK OF NIGERIA.\n MARVELLING YOU SINCE 2003\n WELCOME TO THE ATM MACHINE.")
print(" *************************")
#This is the start of the code. Everything here is made on the inference that normal ATM machines do not have any alphabetic input available.
trials=3
while trials!=0:
account= int(input(" PLEASE INPUT YOUR ACCOUNT NUMBER: "))
pin = int(input(" PLEASE INPUT YOUR 5 DIGIT PIN: "))
correct_pin= valid_pins[valid_accounts.index(account)]
if (account not in valid_accounts) or (pin!=correct_pin):
print(" INVALID LOGIN DETAILS. ")
trials= trials-1
print(" YOU HAVE ", trials, " TRIALS LEFT")
elif (account in valid_accounts) and (pin==correct_pin):
print("Welcome")
A: trials=3
while trials!=0:
account= int(input(" PLEASE INPUT YOUR ACCOUNT NUMBER: "))
pin = int(input(" PLEASE INPUT YOUR 5 DIGIT PIN: "))
correct_pin= valid_pins[valid_accounts.index(account)]
if (account not in valid_accounts) or (pin!=correct_pin):
print(" INVALID LOGIN DETAILS. ")
trials= trials-1
print(" YOU HAVE ", trials, " TRIALS LEFT")
elif (account in valid_accounts) and (pin==correct_pin):
print("Welcome")
break
But the program will have some uncovered cases still
*
*If the inputted account is not in the account list you'll get ValueError.
*Converting input() into int() immediately is not a very good practice. if a string is inputted you'll get a ValueError.
Edit:
trials=3
while trials!=0:
try: # Check if the input is convertible to int()
account= int(input(" PLEASE INPUT YOUR ACCOUNT NUMBER: "))
pin = int(input(" PLEASE INPUT YOUR 5 DIGIT PIN: "))
if account in valid_accounts:
# Create correct_pin only after making sure that the account is in valid_accounts.
# Otherwise .index() will not work
correct_pin= valid_pins[valid_accounts.index(account)]
# You need to check the correct pin only when the account is valid
# Makes no sence to check the pin if there is no such account.
if (pin==correct_pin):
print("Welcome")
break
else: # Pin is either correct or not. Else is more suitable than elif.
print(" INVALID LOGIN DETAILS. ")
trials -= 1
print(" YOU HAVE ", trials, " TRIALS LEFT")
else: # Account is either valid or not. Else is more suitable than elif.
print(" INVALID LOGIN DETAILS. ")
trials -= 1
print(" YOU HAVE ", trials, " TRIALS LEFT")
except ValueError:
print(" PLEASE INPUT ONLY INTEGERS")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68178962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java constructor (anti-pattern) super-classing String The intention of the following design is to allow String values to be (in effect) subclassed to enable a number of what would be conflicting constructor methods to be established (e.g. the method signatures would be the same even though the parameter names would be different).
Kindly consider the following (non-functional) design:
Id Interface (an empty - marker interface)
public interface Id {}
Classes Interface (an empty - marker interface)
public interface Classes {}
Title Interface (an empty - marker interface)
public interface Title {}
Tool Class
public Tool(Id id) throws Exception
{
this.span = new Span();
this.span.addAttribute(new Attribute(Attribute.ID, (String)((Object) id)));
}
public Tool(Classes classes) throws Exception
{
this.span = new Span();
this.span.addAttribute(new Attribute(Attribute.CLASS, (String)((Object) classes)));
}
public Tool(Title title) throws Exception
{
this.span = new Span();
this.span.addAttribute(new Attribute(Attribute.TITLE, (String)((Object) title)));
}
public Tool(Id id, Classes classes, Title title) throws Exception
{
this.span = new Span();
this.span.addAttribute(new Attribute(Attribute.ID, (String)((Object) id)));
this.span.addAttribute(new Attribute(Attribute.CLASS, (String)((Object) classes)));
this.span.addAttribute(new Attribute(Attribute.TITLE, (String)((Object) title)));
}
public void Test() throws Exception
{
Tool hammer = new Tool((Id)((Object)"hammer"));
Tool poweredTool = new Tool((Classes)((Object)"tool powered"));
Tool tool = new Tool((Id)((Object)"invention"), (Classes)((Object)"tool powered"), (Title)((Object)"define a new tool"));
}
The approach requires an interface per parameter "type" and the down cast / up cast from the specific interface "type" to Object and then to String...
I am uncomfortable with the approach and I'm hoping that there's a design pattern out there that would alleviate my desire to subclass String (solely for the purpose of constructor method differentiation)...
I have a variadic method that takes an arbitrary collection of name value pairs to provide an alternative to the fixed parameter constructors, but the constructors shown above are the most common combinations and therefore as a convenience to the programmer they are presently being contemplated as being provided...
Thanks!
A: Considering how your constructors look I would suggest you to get rid of them and use a Builder pattern instead:
class Tool {
private Tool() { // Preventing direct instantiation with private constructor
this.span = new Span();
}
... // Tool class code
public static Builder builder() {
return new Builder();
}
public static class Builder {
private final Tool tool = new Tool();
public Builder withId(String id) {
tool.span.addAttribute(new Attribute(Attribute.ID, id));
return this;
}
... // other methods in the same manner
public Tool build() {
// Add some validation if necessary
return tool;
}
}
}
Usage:
Tool tool = Tool.builder()
.withId("id")
.withClasses("classA, classB")
.build();
A: Your basic problem is that constructors have a fixed name (that of the class), so they must be distinguished by parameter types, so you can't have multiple constructors with the same types but which interpret them differently.
There's the builder pattern (see other answer) or this - the factory method pattern:
// private constructor
private Tool() { }
// factory methods with same parameters but different names:
public static Tool forId(String id) throws Exception {
Tool tool = new Tool();
tool.span = new Span();
tool.span.addAttribute(new Attribute(Attribute.ID, id));
return tool;
}
public static Tool forClasses(String classes) throws Exception {
Tool tool = new Tool();
tool.span = new Span();
tool.span.addAttribute(new Attribute(Attribute.CLASS, classes));
return tool;
}
// etc for other interpretations of a String
You could refactor this to make it a little cleaner, but this shows the essence of the approach.
A: What I've used in the past is something like this:
public abstract class StringValue {
private final String value;
protected StringValue(String value) { this.value = value; }
public String toString() { return value; }
}
public class Id extends StringValue {
public Id(String id) { super(id); }
}
public class Classes extends StringValue {
public Classes(String classes) { super(classes); }
}
This way, you get real, object-oriented types. This is particularly powerful if you have specific extra logic for each type (validation logic, conversion logic to represent the value in different ways for different systems integrated with, etc.)
And if you don't have a need for extra logic, it's just a few lines of code to create and extra type.
A: The best solution is to use static factory methods with different method names, as suggested in Bohemian's answer.
Given the hypothetical requirement that overloading cannot be avoided, we must provide different method signatures; more accurately, different signatures under erasure. Therefore it is necessary to define and use custom types like your Id etc.
One way is to have a method parameter just for overloading resolution, without caring for its value:
public Tool(Id id, String value){...}
new Tool( (Id)null, "hammer" );
It might look better with a constant for (Id)null
public static final Id ID = null;
new Tool(ID, "hammer");
If we require that the value must be carried in the parameter, you'll need wrapper types that wraps the values, as in Bolwidt's answer.
In java8, we could also use lambda expression to define the wrapper:
public interface Id extends Supplier<String>{}
public Tool(Id id)
{
String attributeValue = id.get();
...
}
new Tool((Id)()->"hammer");
new Tool((Id)"hammer"::toString);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31173955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Update all values except auto-increment field using PHP / MySql / PDO I have a quick question...I am updating all values in a row using a prepared statement and an array.
When initially inserting, my statement looks like this (and works perfect)
$sql="INSERT INTO $dbtable VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
The first and last values are NULL as the first is an auto increment ID field and last is a timestamp field.
Is there a way to keep my UPDATE statement as simple as my INSERT statement like this...
$sql="UPDATE $dbtable SET (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) WHERE `announcements`.`id` = $id LIMIT 1";
I realize this does not work as is due to the first value being an auto increment field, is there a value I could put into my array to 'skip' this field?
This may not be the best way to describe my question but if you need more info, please let me know!
Thank you in advance!
A: UPDATE has no "implicit columns" syntax like INSERT does. You have to name all the columns that you want to change.
One alternative you can use in MySQL is REPLACE:
REPLACE INTO $dbtable VALUES (?, ?, ?, ?, ?, ...)
That way you can pass the current value for your primary key, and change the values of other columns.
Read more about REPLACE here: https://dev.mysql.com/doc/refman/5.6/en/replace.html
Note that this is internally very similar to @Devon's suggestion of using two statements, a DELETE followed by an INSERT. For example, when you run REPLACE, if you have triggers, both the ON DELETE triggers are activated, and then the ON INSERT triggers. It also has side-effects on foreign keys.
A: The solution I can think of doesn't involve an UPDATE at all.
DELETE FROM $dbtable WHERE id = $id;
INSERT INTO $dbtable VALUES ($id, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
Since you don't want to use the UPDATE syntax, this would delete the row and add a new row with the same id, essentially updating it. I would recommend wrapping it in a transaction so you don't lose your previous row if the insert fails for any reason.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26328474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Printing Environmental variables in Linux I am new to Linux. I came across this piece of code to print environmental variables. It is kind of confusing me. How can this code print the environmental variables?
#include <stdio.h>
extern char **environ;
int main()
{
char **var;
for(var=environ; *var!=NULL;++var)
printf("%s\n",*var);
return 0;
}
what is extern here?
A: If you don't know what extern means, please find a book to learn C from. It simply means 'defined somewhere else, but used here'.
The environ global variable is unique amongst POSIX global variables in that it is not declared in any header. It is like the argv array to the program, an array of character pointers each of which points at an environment variable in the name=value format. The list is terminated by a null pointer, just like argv is. There is no count for the environment, though.
for (var = environ; *var != NULL; ++var)
printf("%s\n", *var);
So, on the first iteration, var points at the first environment variable; then it is incremented to the next, until the value *var (a char *) is NULL, indicating the end of the list.
That loop could also be written as:
char **var = environ;
while (*var != 0)
puts(*var++);
A: From wikipedia http://en.wikipedia.org/wiki/External_variable:
Definition, declaration and the extern keyword
To understand how external variables relate to the extern keyword, it is necessary to know the difference between defining and declaring a variable. When a variable is defined, the compiler allocates memory for that variable and possibly also initializes its contents to some value. When a variable is declared, the compiler requires that the variable be defined elsewhere. The declaration informs the compiler that a variable by that name and type exists, but the compiler need not allocate memory for it since it is allocated elsewhere.
The extern keyword means "declare without defining". In other words, it is a way to explicitly declare a variable, or to force a declaration without a definition. It is also possible to explicitly define a variable, i.e. to force a definition. It is done by assigning an initialization value to a variable. If neither the extern keyword nor an initialization value are present, the statement can be either a declaration or a definition. It is up to the compiler to analyse the modules of the program and decide.
A variable must be defined once in one of the modules of the program. If there is no definition or more than one, an error is produced, possibly in the linking stage. A variable may be declared many times, as long as the declarations are consistent with each other and with the definition (something which header files facilitate greatly). It may be declared in many modules, including the module where it was defined, and even many times in the same module. But it is usually pointless to declare it more than once in a module.
An external variable may also be declared inside a function. In this case the extern keyword must be used, otherwise the compiler will consider it a definition of a local variable, which has a different scope, lifetime and initial value. This declaration will only be visible inside the function instead of throughout the function's module.
The extern keyword applied to a function prototype does absolutely nothing (the extern keyword applied to a function definition is, of course, non-sensical). A function prototype is always a declaration and never a definition. Also, in ANSI C, a function is always external, but some compiler extensions and newer C standards allow a function to be defined inside a function.
An external variable must be defined, exactly once, outside of any
function; this sets aside storage for it. The variable must also be
declared in each function that wants to access it; this states the
type of the variable. The declaration may be an explicit extern
statement or may be implicit from context. ... You should note that we
are using the words definition and declaration carefully when we refer
to external variables in this section. Definition refers to the place
where the variable is created or assigned storage; declaration refers
to places where the nature of the variable is stated but no storage is
allocated.
—The C Programming Language
Scope, lifetime and the static keyword
An external variable can be accessed by all the functions in all the modules of a program. It is a global variable. For a function to be able to use the variable, a declaration or the definition of the external variable must lie before the function definition in the source code. Or there must be a declaration of the variable, with the keyword extern, inside the function.
The static keyword (static and extern are mutually exclusive), applied to the definition of an external variable, changes this a bit: the variable can only be accessed by the functions in the same module where it was defined. But it is possible for a function in the same module to pass a reference (pointer) of the variable to another function in another module. In this case, even though the function is in another module, it can read and modify the contents of the variable—it just cannot refer to it by name.
It is also possible to use the static keyword on the definition of a local variable. Without the static keyword, the variable is automatically allocated when the function is called and released when the function exits (thus the name "automatic variable"). Its value is not retained between function calls. With the static keyword, the variable is allocated when the program starts and released when the program ends. Its value is not lost between function calls. The variable is still local, since it can only be accessed by name inside the function that defined it. But a reference (pointer) to it can be passed to another function, allowing it to read and modify the contents of the variable (again without referring to it by name).
External variables are allocated and initialized when the program starts, and the memory is only released when the program ends. Their lifetime is the same as the program's.
If the initialization is not done explicitly, external (static or not) and local static variables are initialized to zero. Local automatic variables are uninitialized, i.e. contain "trash" values.
The static keyword applied to a function definition prevents the function from being called by name from outside its module (it remains possible to pass a function pointer out of the module and use that to invoke the function).
Example (C programming language)
File 1:
int GlobalVariable; // implicit definition
void SomeFunction(); // function prototype (declaration)
int main() {
GlobalVariable = 1;
SomeFunction();
return 0;
}
File 2:
extern int GlobalVariable; // explicit declaration
void SomeFunction() { // function header (definition)
++GlobalVariable;
}
In this example, the variable GlobalVariable is defined in File 1. In order to utilize the same variable in File 2, it must be declared. Regardless of the number of files, a global variable is only defined once, however, it must be declared in any file outside of the one containing the definition.
If the program is in several source files, and a variable is defined in file1 and used in file2 and file3, then extern declarations are needed in file2 and file3 to connect the occurrences of the variable. The usual practice is to collect extern declarations of variables and functions in a separate file, historically called a header, that is included by #include at the front of each source file. The suffix .h is conventional for header names.
A: Extern defines a variable or a function that can be used from other files... I highly advise reading some of the many articles available on the Internet on C programming: https://www.google.ca/search?client=opera&rls=en&q=learn+c&sourceid=opera&ie=utf-8&oe=utf-8&channel=suggest
A: extern char **environ;
the variable environ comes from your library which you will link.
That variable saved the system environment variables of your current
linux system. That's why you can do so.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9662417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Laravel authentication does not set me as authenticated I'm pretty fresh into laravel. I've used CakePHP a time or two, but not this.
Currently I'm trying to make a authentication system. The registration does work, so does logging in.
When I log in, my view gets displayed. But when I try to secure the controllers functions by using the auth middleware:
public function __construct() {
$this->middleware("auth");
}
it keeps redirecting me to /, but when it isn't there, it all works?
Also, when I try to do var_dump(Auth::check()); in the login function, it shows true, but when I do it in my index (Where i keep getting wrongfully redirected to) it shows false.
This is how I log in my users:
public function postLogin(LoginRequest $request) {
if ($this->auth->attempt($request->only("username", "password"))) {
return redirect("/me");
}
return redirect("/")->withInput()->withErrors([
"username" => "The credentials you entered did not match out system."
]);
}
Is it because of a bug in the code that causes this?
Thanks in advance.
Edit: I'm making use of Laravel 5.2. And also as requested: here are the routes.
Route::group(['middleware' => ['web']], function () {
Route::get('/', 'UnloggedController@index');
Route::get('/me', 'MeController@index');
});
Route::controller('/','Auth\AuthController');
A: You need to move Route::controller definition into the route group that has the web middleware added, otherwise the session will not be enabled for it and the authentication system needs the session in order to work. So it should be like this:
Route::group(['middleware' => ['web']], function () {
Route::get('/', 'UnloggedController@index');
Route::get('/me', 'MeController@index');
Route::controller('/','Auth\AuthController');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35066150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iPhone how to get Magnified effect on certain part of the screen?
Hi all,
The images above are taken from the "Nike Boom" App. I am wondering how to do a magnified effect on the number list as shown in the images. I also want to point out that it is very very smooth animation, so screen capturing certain part of a screen and projected it back on UIView may not work (I tried that)
Thankz in advance,
Pondd
Update:
Hey,
Just so for anyone who might comes across this topic, I've made a simple sample based on Nielsbot's suggestion and posted up on github here
Please feel free to fork it, improve it and pass it on :)
Best,
Pondd
A: It's done with 2 scroll views, one in front of the other. One scroll view (A) contains the small numbers. The second scroll view (B) contains the zoomed numbers. The frame of (B) is the transparent window. When you scroll (A), you scroll (B) programmatically, but you move it farther than (A). (I.e. if (A) scrolls 10 pixels, you might scroll (B) 20 pixels.)
Make sense?
If you've ever used Convert.app from TapTapTap they use a similar effect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5908955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Hiding element space without height constraint
This is a reuseable tableview cell. I want to hide 3. UILabel from the top, both the element and its space when it has no data.
I can't create a height constraint of it because I need to use it multiline depends on the text.
if release.post.isEmpty {
cell.label3.isHidden = true
} else {
cell.label3.isHidden = false
}
So how can I hide its space without a height constraint?
A: You can use the stack view and then hide the required objects i.e label or image. Remember to give the proper constraints to the stack view and select the required properties.
A: I fixed this by dynamically adding the constraint
cell.match.translatesAutoresizingMaskIntoConstraints = false
cell.match.constraints.forEach { (constraint) in
if constraint.firstAttribute == .height
{
constraint.constant = release.post.height(withConstrainedWidth: cell.match.frame.width, font: UIFont.preferredFont(forTextStyle: UIFont.TextStyle.subheadline)) + 15
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60238637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MVC c# - need to do POST only once on submit I am using MVC 3, c# on IE9
In my controller I have the following 2 ActionResuls that is of significance:
public ActionResult EditTrain(String trainid)
{
....
return PartialView(edittrain);
}
[HttpPost]
public ActionResult EditTrain(Train editrain)
{
....
DataContext.SubmitChanges();
return RedirectToAction("Edit", new { id = trainid });
}
On the partial view, I have the following code:
@model Models.EditTrain
@{
ViewBag.Title = "Training";
}
<h2>Train</h2>
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "theForm" }))
{
@Html.ValidationSummary(false)
@Html.HiddenFor(model => model.ID)
<div class="display-label" style="font-weight: normal">
@Html.Label("ID:")
</div>
<div class="display-field">
@Html.DisplayFor(model => model.ID)
</div>
<div class="display-label" style="font-weight: normal">
@Html.Label("KitID:")
</div>
<div class="display-field">
@Html.DisplayFor(model => model.KitID)
</div>
<div class="editor-label">
@Html.Label("Inactive:")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Inactive)
</div>
<div class="editor-label">
@Html.Label("Inactive Date:")
</div>
<div id='datepicker' class="editor-field">
@Html.EditorFor(model => model.InactiveDate)
</div>
......
<div style="clear:left;">
<br />
<p>
<input type="submit" id="submit" value="Submit" />
</p>
</div>
}
<script type="text/javascript">
$.ajaxSetup({ cache: false });
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: url,
data: $('#theForm').serialize()
});
$("#stlist").load('@Url.Action("KitsEdit","Spr")' + '?id=' + '@Model.sprid');
});
});
In the above code, what I like to happen above is that once the user clicks on submit, I like it to go to the following action:
[HttpPost]
public ActionResult EditTrain(Train editrain)
and then return back to the View and run the following code
$("#stlist").load('@Url.Action("KitsEdit","Spr")' + '?id=' + '@Model.sprid');
What is happening though is that it does the above but after it runs
$("#stlist").load('@Url.Action("KitsEdit","Spr")' + '?id=' + '@Model.sprid');
it runs
[HttpPost]
public ActionResult EditTrain(Train editrain)
a second time.
How can I prevent it from going to
[HttpPost]
public ActionResult EditTrain(Train editrain)
after the .load().
A: You should return false from your .click() handler. But looking at your code there is something conceptually wrong with it. You call the .load method immediately after firing off your AJAX request without even waiting for this AJAX request to finish. Also there is very little point in invoking a controller action that does a redirect to another action using AJAX.
A: you can use request.Abort()
$(document).ready(function () {
$("#submit").click(function () {
var request = $.ajax({
type: "POST",
url: url,
data: $('#theForm').serialize()
});
$("#stlist").load('@Url.Action("KitsEdit","Spr")' + '?id=' + '@Model.sprid');
request.Abort()
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11435700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Two errors (Build failed and Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081) keep happening I got two errors (Build failed and command failed). I tried to change my port number or gradle version..etc.. but this two error keep happening :( Please help me I'm soooo exhausted.
/* this is my versions */
buildscript {
ext {
buildToolsVersion = "29.0.2"
minSdkVersion = 16
compileSdkVersion = 29
targetSdkVersion = 29
}
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:3.2.0")
classpath 'com.google.gms:google-services:4.0.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
wrapper {
gradleVersion = '4.6'
/* this is my error */
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.2/userguide/command_line_interface.html#sec:command_line_warnings
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring project ':app'.
> Failed to notify project evaluation listener.
> org.gradle.api.file.ProjectLayout.fileProperty(Lorg/gradle/api/provider/Provider;)Lorg/gradle/api/file/RegularFileProperty;
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 1m 8s
error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
A: Can tell which distribution url you are using ? (can find in ../android/gradle/wrapper/gradle-wrapper.properties)
many time it give error
and if you are using physical device then please check api level of your device if it is old then try in new one
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66486751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get record which have min has_many rec ords(joins data) user.rb
has_many :properties
property.rb
belongs_to :user
I want to get a user who have min properties like wise for max also.
I cant find any query related to that
A: You could use counter_cache.
The :counter_cache option can be used to make finding the number of belonging objects more efficient.
From here
belongs_to :user, counter_cache: true
Then create the migration:
def self.up
add_column :users, :properties_count, :integer, :default => 0
User.reset_column_information
User.find(:all).each do |u|
User.update_counters u.id, :properties_count => u.properties.length
end
end
Then you can fetch user which have max properties_count
User.maximum("properties_count")
Here is an awesome RailsCast about counter_cache
A: To find the user with min properties you can simply do,
User.joins(:properties).group("properties.user_id").order("count(properties.user_id) desc").last
And to find the user with max properties,
User.joins(:properties).group("properties.user_id").order("count(properties.user_id) desc").first
Note: Because its a join operation with properties, so user with no properties will not appear in this query.
A: I think you can do like this by scopes
class User
has_many :properties
scope :max_properties,
select("users.id, count(properties.id) AS properties_count").
joins(:properties).
group("properties.id").
order("properties_count DESC").
limit(1)
scope :min_properties,
select("users.id, count(properties.id) AS properties_count").
joins(:properties).
group("properties.id").
order("properties_count ASC").
limit(1)
And just call User.max_properties and User.min_properties
UPDATED:
It will aslo work like BoraMa suggeted
class User
has_many :properties
scope :max_properties,
select("users.*, count(properties.id) AS properties_count").
joins(:properties).
group("users.id").
order("properties_count DESC").
limit(1)
scope :min_properties,
select("users.*, count(properties.id) AS properties_count").
joins(:properties).
group("users.id").
order("properties_count ASC").
limit(1)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37454694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to convert this json into POJO structure I have a JSON API result to my android app that looks like the following (cut down to size)
{
"Results": [{
"data": [{
"AAA": {
"accessRole": "access.role.owner",
"fullName": "jsddd",
"spaceTotal": null,
"createdDT": "2016-05-29T02:52:11.000000Z",
"updatedDT": "2016-05-29T02:52:11.000000Z"
}
},
{
"AAA": {
"accessRole": "access.role.owner",
"fullName": "jsw",
"createdDT": "2016-05-29T04:48:57.000000Z",
"updatedDT": "2016-05-29T04:48:57.000000Z"
}
},
{
"BBB": {
"archiveId": 1,
"description": "the description here",
"createdDT": "2016-05-29T02:52:11.000000Z",
"updatedDT": "2016-06-01T22:49:01.000000Z"
}
}],
"message": ["Get successful"],
"status": true,
"createdDT": null,
"updatedDT": null
}],
"isSuccessful": true,
"createdDT": null,
"updatedDT": null
}
and am looking to convert the structure into something that is POJO (shown below) in my deserialize function as was defined by running this through jsonschema2pojo.org and then be able to use GSON on it
{
"Results": [{
"data": [{
"AAAs": [{
"accessRole": "access.role.owner",
"fullName": "jsddd",
"spaceTotal": null,
"createdDT": "2016-05-29T02:52:11.000000Z",
"updatedDT": "2016-05-29T02:52:11.000000Z"
},
{
"accessRole": "access.role.owner",
"fullName": "jsw",
"createdDT": "2016-05-29T04:48:57.000000Z",
"updatedDT": "2016-05-29T04:48:57.000000Z"
}],
"BBBs": [{
"archiveId": 1,
"description": "the description here",
"createdDT": "2016-05-29T02:52:11.000000Z",
"updatedDT": "2016-06-01T22:49:01.000000Z"
}]
}],
"message": ["Get successful"],
"status": true,
"createdDT": null,
"updatedDT": null
}],
"isSuccessful": true,
"createdDT": null,
"updatedDT": null
}
Was wondering if there is a way to do this elegantly instead of brute forcing by reading in the objects one by one and rebuilding it from scratch.
Bonus if it could be done w/o having to explicitly code in the data elements (AAA, BBB) as they will be growing in number over time.
Edited:
The output that org.jsonschema2pojo is creating that doesn't match is in it making the elements as a single object not as as array.
package com.example;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
@Generated("org.jsonschema2pojo")
public class Datum {
private AAA aAA;
private BBB bBB;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public AAA getAAA() {
return aAA;
}
public void setAAA(AAA aAA) {
this.aAA = aAA;
}
public BBB getBBB() {
return bBB;
}
public void setBBB(BBB bBB) {
this.bBB = bBB;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37633444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use dompdf in phabricator I want to create new fiture to generate pdf on my phabricator.
I try to import dompdf into my phabricator, but when i try to call the function on my dompdf file it won't return anything and the dompdf->stream wont run
i write my dompdf code below this
<?php require (__DIR__ . '/vendor/autoload.php');
use Dompdf\Dompdf;
function push(){
$html = "hello world";
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'potrait');
$dompdf->render();
$filename = 'doc.pdf';
$dompdf->stream("dompdf_out.pdf");
}
And this is my phabricator function to call it
<?php
$root = dirname(phutil_get_library_root('phabricator'));
require_once $root.'/externals/dompdf/push.php';
final class PhabricatorPeopleGenerateCVController
extends PhabricatorPeopleController {
public function shouldRequireAdmin() {
return false;
}
public function handleRequest(AphrontRequest $request) {
$view_uri = "/p/{$request->getViewer()->getUsername()}/";
push();
return id(new AphrontRedirectResponse())->setURI($view_uri);
}
}
any solution about my problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74064186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get ListPicker SelectedItem value I have a ListPicker bound to Anonymous type List and want to get value of it. This is the code:
Dim listZoneSrc = From zon In listZone
Join joinCZ In listJoinCityZone On
joinCZ.zoneId Equals zon.zoneId
Where joinCZ.cityId = cityId
Select zon.zoneId, zon.zoneName, joinCZ.price
lpickZone.ItemsSource = listZoneSrc.ToList
Is it possible to get value of lpickZone.SelectedItem.zoneId in lpickZone_SelectionChanged Sub?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22407534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Better way to find index of item in ArrayList? For an Android app, I have the following functionality
private ArrayList<String> _categories; // eg ["horses","camels"[,etc]]
private int getCategoryPos(String category) {
for(int i = 0; i < this._categories.size(); ++i) {
if(this._categories.get(i) == category) return i;
}
return -1;
}
Is that the "best" way to write a function for getting an element's position? Or is there a fancy shmancy native function in java the I should leverage?
A: If your List is sorted and has good random access (as ArrayList does), you should look into Collections.binarySearch. Otherwise, you should use List.indexOf, as others have pointed out.
But your algorithm is sound, fwiw (other than the == others have pointed out).
A: Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.
A: There is indeed a fancy shmancy native function in java you should leverage.
ArrayList has an instance method called
indexOf(Object o)
(http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html)
You would be able to call it on _categories as follows:
_categories.indexOf("camels")
I have no experience with programming for Android - but this would work for a standard Java application.
Good luck.
A: ArrayList has a indexOf() method. Check the API for more, but here's how it works:
private ArrayList<String> _categories; // Initialize all this stuff
private int getCategoryPos(String category) {
return _categories.indexOf(category);
}
indexOf() will return exactly what your method returns, fast.
A: the best solution here
class Category(var Id: Int,var Name: String)
arrayList is Category list
val selectedPositon=arrayList.map { x->x.Id }.indexOf(Category_Id)
spinner_update_categories.setSelection(selectedPositon)
A: ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index
int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
Log.e(TAG, "Object not found in List");
} else {
Log.i(TAG, "" + position);
}
Output: List Index : 7
If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.
Done
A: Use indexOf() method to find first occurrence of the element in the collection.
A: The best way to find the position of item in the list is by using Collections interface,
Eg,
List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);
Output : 2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8439037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
} |
Q: Golang regex to parse out repo name from git url I need a way of parsing out the repo name from a git repo url WITHOUT using a split function.
For example I want to be able to do the following
url := "[email protected]:myorg/repo.git"
repoName := parseRepoName(url)
log.Println(repoName) //prints "repo.git"
A: Save yourself the trouble of using a regex where you don't need one and just use:
name := url[strings.LastIndex(url, "/")+1:]
Or if you are not sure that the url is a valid github url:
i := strings.LastIndex(url, "/")
if i != -1 {
// Do some error handling here
}
name := url[i+1:]
A: I am not that much familiar with golang till days. May be you can go with replace instead of split. For example using the following pseudocode.
Make a regex .*/ and then replace it with your string.
reg.ReplaceAllString(url, "")
This will replace anything before the last / and you'll have the repo.git
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42396853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Woocommerce - Guys I'm trying to display 3 random products but skipping the first 3 most recent added products I need your help. I'm trying to display 3 random products but skipping the first 3 most recently added products. Most recent meaning not by query but by global date the product was created.
Heres the code i use to display random products.
$args = array(
'post_type' => 'product',
'orderby' => 'rand',
'posts_per_page' => 3,
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
wc_get_template_part( 'content', 'product' );
endwhile;
}
Adding 'offset' only skips the first 3 random. Is there a way to skip first 3 most recently added products?
A: First, get three last products and get their IDs using wp_get_recent_posts function and map IDs, then add post__not_in argument to WP_query with these three post IDs
$recent_posts = wp_get_recent_posts([
'post_type' => 'product',
'numberposts' => 3
]);
$last_three_posts = array_map(function($a) { return $a['ID']; }, $recent_posts);
$args = array(
'post_type' => 'product',
'orderby' => 'rand',
'posts_per_page' => 3,
'post__not_in' => $last_three_posts,
);
$loop = new WP_Query( $args );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56823478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to show alert box button in vertical orientation in android? I have one image button, when i click it opens 3 dialogbox buttons and they come in horizontal way. I want that alert dialog box button comes to vertical. How?
A: try this simple method
public void verticalAlert (final String item01, final String item02, final String item03){
String[] array = {item01,item02,item03};
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
builder.setTitle("Test")
.setItems(array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
// case item 1 do...
break;
case 1:
// case item 2 do...
break;
case 2:
// case item 3 do...
break;
}
}
});
builder.show();
}
A: You can use View in the Alertdialog's setview method.
In that View,call the View's LAYOUT_INFLATER_SERVICE and use a customized xml as per your requirement.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5857620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Template System with Express and React I would like to migrate an XSLT templating system to React and I've choose Express as the server of the React templates.
The server (Express) will serve to the client a template or another depending on the request hostname, I have JSONs with config of each hostname registered and it tells which template has to return.
The structure is the following:
*
*A folder with a list of react projects:
templates/
template_1/ (React Project)
dist/server/template.js (Built)
package.json
template_2/ (React Project)
dist/server/template.js (Built)
package.json
*
*An express folder for de server:
server/
server.js (Express App)
-> endpoint where depending on the hostname requestor it returns a template or another
-> loads the dist/server/template.js file from the template folder
renderer.jsx (React folder that renders the template for SSR)
builder/
esbuild.server.js
esbuild.template.js
Here I'll share the code of the relevant files:
// esbuild.server.js
require('esbuild')
.build({
entryPoints: ['server.js'],
bundle: true,
format: 'iife',
external: ['express', 'react', 'react-dom', 'react-router-dom'],
// minify: true,
platform: 'node',
outfile: 'dist/server.js',
loader: {'.js': 'jsx'},
logLevel: 'info',
define: {'process.env.NODE_ENV': '"production"'},
})
.catch(() => process.exit(1));
// esbuild.template.js
const {existsSync, readFileSync, mkdirSync, writeFileSync, rmSync} = require('fs');
const {resolve} = require('path');
const {config} = require('dotenv');
config();
const template = process.argv.slice(2)[0] || process.env.npm_config_name;
const CONFIG_FOLDER = process.env.CONFIG_FOLDER || resolve('./config');
if (!template)
throw new Error('No argument template specified, try: "--name=<template>"');
const TEMPLATES_FOLDER = './templates';
const TEMPLATE_PATH = `${TEMPLATES_FOLDER}/${template}`;
if (!existsSync(TEMPLATE_PATH))
throw new Error(`The template ${TEMPLATE_PATH} doesn't exists`);
const getTemplateConfig = () => {
try {
return JSON.parse(readFileSync(`${TEMPLATE_PATH}/.template.json`));
} catch (error) {
return JSON.parse(readFileSync(`${CONFIG_FOLDER}/server/.template.json`));
}
};
const templateConfig = getTemplateConfig();
if (!existsSync(`${TEMPLATE_PATH}/${templateConfig.app}`))
throw new Error(
`The template app ${TEMPLATE_PATH}/${templateConfig.app} doesn't exists`
);
const renderer = readFileSync('./renderer.jsx', 'utf8').replace(
/%TEMPLATE_PATH%/gim,
resolve(`${TEMPLATE_PATH}/${templateConfig.app}`)
);
const rendererFile = `./tmp/renderer_${template}_${new Date().getTime()}.jsx`;
if (!existsSync('./tmp')) mkdirSync('./tmp');
writeFileSync(rendererFile, renderer);
require('esbuild')
.build({
entryPoints: [rendererFile],
bundle: true,
format: 'iife',
minify: true,
platform: 'node',
outfile: `${TEMPLATE_PATH}/dist/server/template.js`,
drop: ['debugger', 'console'],
loader: {'.js': 'jsx'},
logLevel: 'info',
legalComments: 'none',
})
.then((response) => {
if (response.errors.length > 0) console.error(response.errors);
if (response.warnings.length > 0) console.warn(response.warnings);
})
.catch((error) => console.log(error))
.finally(() => {
rmSync(rendererFile);
});
As you can see I use the renderer.jsx as a builder for the templates, I create a renderer_template_1_<date>.js file that contains the template with the renderToPipeableStream for SSR, if I do not have all that in the same compiled file I would have to React instances.
// renderer.jsx
import React from 'react';
import {renderToPipeableStream} from 'react-dom/server';
import {StaticRouter} from 'react-router-dom/server';
import Template from '%TEMPLATE_PATH%';
function App({url}) {
return (
<StaticRouter location={url}>
<Template />
</StaticRouter>
);
}
function renderer({url, res, next, writable}) {
const stream = renderToPipeableStream(<App url={url} />, {
onShellReady() {
res.setHeader('Content-type', 'text/html');
stream.pipe(writable);
},
onShellError(error) {
res.status(500);
if (next) return next(error);
console.error(error);
},
onError(error) {
console.error(error);
},
});
}
export default renderer;
and finally the server endpoint:
const render = require(`${templateDirPath}/dist/server/template.js`).default;
console.log(render);
const writable = new HtmlWritable();
writable.on('finish', () => {
const html = writable.getHtml();
const response = indexHtml.replace(
'<div id="root"></div>',
`<div id="root">${html}</div>`
);
res.send(response);
});
render({req, res, next, writable});
I used the HtmlWritable from: React SSR with custom html
The Problem
The load of the renderer does not work in server.js endpoint, I've got a list of errors:
*
*If I load into a vm.Script:
evalmachine.<anonymous>:1
[...]
Error: Dynamic require of "stream" is not supported
at evalmachine.<anonymous>:1:431
at evalmachine.<anonymous>:41:17631
at evalmachine.<anonymous>:72:19751
at evalmachine.<anonymous>:1:511
at evalmachine.<anonymous>:103:18485
at evalmachine.<anonymous>:1:511
at evalmachine.<anonymous>:531:125320
at evalmachine.<anonymous>:531:126039
at Script.runInThisContext (node:vm:129:12)
at /home/mjcabrer/Workspace/git/mbe-web2/dist/server.js:162:36
*
*If I run it with mjs I get the same error of Error: Dynamic require of "stream" is not supported.
*If I render for none node platform then the renderToPipeableStream is not in the built.
Questions
*
*Is there a way better than that to serve react templates depending on the hostname?
*Is there an standard for doing something like that?
Thanks a lot for your read and interest!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73048580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery/JS – Get font-size in unit set in CSS (vw units) I've set my font sizes using vw but want to retrieve this value in jQuery but when I use $('.textarea').css('font-size'); it returns the px equivalent rather than the vw unit.
Is there any way for it to return the correct stated value?
A: Once you have value in px, multiply it by 100/($(window).width())
For example(in your case):
$('.textarea').css('font-size')*(100/($(window).width()))
Please let me know, if it works
A: When using jQuery .css('font-size'), the value returned will always be the computed font size in pixels instead of the value used (vw, em, %, etc). You will need to convert this number into your desired value.
(The following uses a font size of 24px and a window width of 1920px as an example)
To convert the px into vw, first convert the computed font size into a number.
// e.g. converts '24px' into '24'
fontSize = parseFloat($('.textarea').css('font-size'));
Next, multiply this number by 99.114 divided by the window width.
(Usually when converting px to vw, you would divide 100 by the window width, however I find the results are slightly incorrect when converting for font sizes).
// returns 1.2389249999999998
fontSize = fontSize * (99.114 / $(window).width());
You can optionally clean up the large decimal returned by rounding to the nearest 100th decimal place.
// returns 1.24
fontSize.toFixed(2)
And now you have the final number you need, just manually add 'vw' where desired.
// returns 1.24vw
fontSize = fontSize + 'vw';
Of course, you can put this all together if you want to shorten your code
// returns 1.24vw
newFontSize = (parseFloat($('.textarea').css('font-size'))*(99.114/ $(window).width())).toFixed(2) + 'vw';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45824626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: outlook vba code to display pictures in email By default, my MS Outlook 2013 is set NOT to download images in received HTML e-mail messages. I would like to keep this setting.
There are some senders whose emails are handled by my Outlook VBA code...and filed into specific folders (rather than the INBOX). I do not use the in-built RULES.
These are known senders...and I would like to have the pictures in the emails from these SELECT KNOWN senders downloaded and displayed. I could do this manually for each email... by right clicking etc... but that is a pain... when there are many such emails.
I am unable to figure out the few lines of code (one line ?) required to download / enable display of images / pictures in the email. Something like... MailItem.Display (which does not work... it only displays the mail in an independent window)... or MailItem.DisplayImages (that is not a known method!).
I would include this one line (or lines) in the routine which handles emails from some known senders....so that their emails always have images / pictures downloaded and displayed.
Thanks.
A: You would need to set the PidTagBlockStatus property - see http://msdn.microsoft.com/en-us/library/ee219242(v=exchg.80).aspx.
Note that while you can read/write that property using MailItem.PropertyAccessor.SetProperty, you will not be able to calculate its value correctly - Outlook Object Model rounds off the value of the message delivery time, and you would need the raw Extended MAPI value (accessible in C++ or Delphi only) as the FileTime structure.
If using Redemption (I am its author) is an option, it exposes the RDOMail.DownloadPictures property. Something like the following should do the job (VB script):
set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT
set Item = Session.GetRDOObjectFromOutlookObject(YourOutlookItem)
Item.DownloadPictures = true
Item.Save
A: The Outlook object model doesn't provide any property or method for that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27343550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Facing issue when combining 3 yii2 queries together I have 3 queries in my yii2 project that are working perfectly as individual queries.So i need to combine these 3 queries
$variant_ids1=VariantProducts::find()
->select(['variant_id1'])
->where(['shop_id'=>$searchModel->user_id])
->orWhere(['category_id'=>$searchModel->category_id,'position'=>null])
->groupBy('variant_id1');
$variant_ids2=VariantProducts::find()
->select(['variant_id2'])
->where(['shop_id'=>$searchModel->user_id])
->orWhere(['category_id'=>$searchModel->category_id,'position'=>null])
->groupBy('variant_id2');
$variant_ids3=VariantProducts::find()
->select(['variant_id3'])
->where(['shop_id'=>$searchModel->user_id])
->orWhere(['category_id'=>$searchModel->category_id,'position'=>null])
->groupBy('variant_id3');
These are my 3 queries. For combining them I used union() like below
$variant_ids1->union($variant_ids2);
$variant_ids1->union($variant_ids3);
But this is working fine in the local server(Windows XAMPP), And not working when deployed to my Centos server. In local, I am getting the correct output the same as I want.
What will be the issue?. And are there any other ways to combine them?
When I deployed to the server I am getting MySQL error like see the picture here
A: could be you are using two different version of mysql one <5.7 (localhost) and one >= 5.7 (server)
do the fact you have an improper use of group by () allowed in mysql<5.7 but not allowed, by deafult, in mysql >= 5.7) this could produce an error
You should not use group by without aggregation function , for obtain disticnt row without aggreation function usw ->distinct()
$variant_ids1=VariantProducts::find()
->select(['variant_id1'])
->where(['shop_id'=>$searchModel->user_id])
->orWhere(['category_id'=>$searchModel->category_id,'position'=>null])
->distinct();
$variant_ids2=VariantProducts::find()
->select(['variant_id2'])
->where(['shop_id'=>$searchModel->user_id])
->orWhere(['category_id'=>$searchModel->category_id,'position'=>null])
->distinct();
$variant_ids3=VariantProducts::find()
->select(['variant_id3'])
->where(['shop_id'=>$searchModel->user_id])
->orWhere(['category_id'=>$searchModel->category_id,'position'=>null])
->distinct();
another issue could be related to the IN clause . the length of the in content is limited by max_allowed_packet param so you should check for this param both of your db and eval if these value are compatible with you union result
https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_max_allowed_packet
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66408267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add columns to SQL query output I have searched this site and others, and I am unable to find a clear answer, so here I am. In the below query, I will get an output with a single column for the county. What I would like to do can only be described in Excel parlance as transpose the counties so each county for a brand family is in its own column. I have played around with using pivot, but unfortunately do not fully grasp what would be required. This is not my first query, but I am relatively new to SQL scripting, so please ask any clarification questions and I will do my best to answer.
Some of the brand families have 10 counties and some have 20, so some of the columns would be blank. This is for an in-house DB, not the SO DB, running on SQL Server 2008R2, FWIW.
The script is:
select distinct b.reckey as BrandFamilyKey, b.recname as BrandFamilyName,
g.recname as County
from territories as t
left join dbo.TerritoryBrandFamilies as tbf on tbf.TerritoryNid = t.TerritoryNid
left join Customers as c on c.TerritoryNid = t.TerritoryNid
left join GeographicAreas as g on g.GeoAreaNid = c.GeoAreaNid
left join brandfamilies as b on b.brandfamilynid = tbf.brandfamilynid
where t.activeflag = 1 AND C.GeoAreaNid IS NOT NULL and b.activeflag = 1
order by b.RecName,g.recname
the output would look like
brand family 1 county 1
brand family 1 county 2
brand family 1 county 3
What I would like to see is:
brand family 1 county 1 county 2 county 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41465047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error when running query using mongolite (R and MongoDB) In my localhost y created a database (coches) and a collection (dtc) in MongoDB. My collection contains more than 2 million documents.
I would like to connect a subset of documents into R. The query I ran in MongoDB was the one of this question and I copy/paste here:
db.getCollection("dtc")
.find({
"payload.fields.MDI_CC_DIAG_DTC_LIST": { $exists: true },
"payload.asset": { $exists: true }
})
This subset resulted in 2265 documents.
I loaded the mongolite package in RStudio to connect MongoDB with R.
library(mongolite)
c <- mongo(collection = "dtc", db = "coches")
However, when I tried these queries:
# query 1
c$find('{
"payload.fields.MDI_CC_DIAG_DTC_LIST": { $exists: true },
"payload.asset": { $exists: true }
}')
# query 2
c$find(query = '{
"payload.fields.MDI_CC_DIAG_DTC_LIST": { $exists: true },
"payload.asset": { $exists: true }
}')
I get this error:
Error: Invalid JSON object: { "payload.fields.MDI_CC_DIAG_DTC_LIST": { $exists: true }, "payload.asset": { $exists: true } }
The original documents are JSON embedded files.
What's wrong in the coding? What am I missing?
A: After a while, checking different places, I came across with the problem and therefore could be able to solve it. The problem was that $exists must be enclosed with quotation marks ("$exists"). So the code would be like this:
dtc$find('{
"payload.fields.MDI_CC_DIAG_DTC_LIST" : {
"$exists" : true
},
"payload.asset" : {
"$exists" : true
}
}')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60884511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Select one item from each category on the basis of cost I want to select five item one from each category which are having lowest cost, i am getting an error please help me with this
var packageId = objentity.PackageGalleries.
Where(p => p.ParentCategory != "Indian"
&& p.ParentCategory != "International").
OrderBy(p => p.PackageCost)
.GroupBy(p => p.ParentCategory).FirstOrDefault();
it is only selecting one item from one category
In the view i m passing
@foreach (var item in Model)
{
<a href="javascript:;">
<img src="~/Content/JetJourney/img/@item.FileName" />
<div>
<p>@item.PackageName, Starting Price @item.PackageCost *</p>
<br />
</div>
</a>
}
A: You can group the data by ParentCategory and within that group order the grouped data by PackageCost. This should give you the expected output:-
var packageId = objentity.PackageGalleries
.Where(p => p.ParentCategory != "Indian" &&
p.ParentCategory != "International")
.GroupBy(p => p.ParentCategory)
.Select(x => x.OrderBy(p => p.PackageCost).FirstOrDefault())
.ToList();
Update:
For your issue althought I have never experienced such issue but it may be due to deferred execution of LINQ as per this post. You can force execute the query using ToList() as updated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34806518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Facebook login via Azure AD B2C custom policy I have created custom policy using Identity Experience Framework. I am able to signup and signin user using the local account but when I am trying to use Facebook as social login I am running into some error.
Issue: When I click Facebook login (Social Login) from my custom policy, I am being redirected to FB for login, but after login from FB I am seeing below error from application insights.
{
""Kind"": ""HandlerResult"",
""Content"": {
""Result"": true,
""RecorderRecord"": {
""Values"": [
{
""Key"": ""SendErrorTechnicalProfile"",
""Value"": ""OAuth2ProtocolProvider""
},
{
""Key"": ""Exception"",
""Value"": {
""Kind"": ""Handled"",
""HResult"": ""80131500"",
""Message"": ""An exception was caught when making a request to URL \""https://graph.facebook.com/oauth/access_token\"" using method \""Get\"". The exception status code was \""ProtocolError\"" with the following message: {scrubbed}."",
""Data"": {},
""Exception"": {
""Kind"": ""Handled"",
""HResult"": ""80131509"",
""Message"": ""The remote server returned an error: (400) Bad Request."",
""Data"": {}
}
}
}
]
}
}
},
any thoughts?
<TechnicalProfiles>
<TechnicalProfile Id="Facebook-OAUTH">
<!-- The text in the following DisplayName element is shown to the user on the claims provider selection screen. -->
<DisplayName>Facebook</DisplayName>
<Protocol Name="OAuth2" />
<Metadata>
<Item Key="ProviderName">facebook</Item>
<Item Key="authorization_endpoint">https://www.facebook.com/dialog/oauth</Item>
<Item Key="AccessTokenEndpoint">https://graph.facebook.com/oauth/access_token</Item>
<Item Key="ClaimsEndpoint">https://graph.facebook.com/me?fields=id,first_name,last_name,name,email,picture</Item>
<Item Key="scope">email</Item>
<Item Key="HttpBinding">GET</Item>
<Item Key="client_id">xxxxxxxx</Item>
<Item Key="UsePolicyInRedirectUri">0</Item>
</Metadata>
<CryptographicKeys>
<Key Id="client_secret" StorageReferenceId="B2C_1A_FacebookSecret" />
</CryptographicKeys>
<InputClaims />
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="userId" PartnerClaimType="id" />
<OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="first_name" />
<OutputClaim ClaimTypeReferenceId="surname" PartnerClaimType="last_name" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
<OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" />
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="facebook.com" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" />
<OutputClaim ClaimTypeReferenceId="extension_picture" PartnerClaimType="picture"/>
</OutputClaims>
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName" />
<OutputClaimsTransformation ReferenceId="CreateUserPrincipalName" />
<OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId" />
<OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromAlternativeSecurityId" />
</OutputClaimsTransformations>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin" />
</TechnicalProfile>
</TechnicalProfiles>
A: You must also add the following item to <Metadata />:
<Item Key="AccessTokenResponseFormat">json</Item>
See this blog post for more information.
A: You have add as well...
<Metadata>
<Item Key="AccessTokenResponseFormat">json</Item>
</Metadata>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="identityProviderAccessToken" PartnerClaimType="{oauth2:access_token}" />
</OutputClaims>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50156925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting Docker Windows Containers to start automatically on reboot My OS is Windows 10 and I am running Docker version 17.06.0-ce-win19. I am trying to set up a container so that it will restart automatically on reboot.
When I use the command:
docker run -it microsoft/nanoserver --restart=always
I’m getting the following error:
docker: Error response from daemon: container 35046c88d2564523464ecabc4d48eb0550115e33acb25b0555224e7c43d21e74 encountered an error during CreateProcess: failure in a Windows system call: The system cannot find the file specified. (0x2) extra info: {"ApplicationName":"","CommandLine":"--restart=always","User":"","WorkingDirectory":"C:\","Environment":{},"EmulateConsole":true,"CreateStdInPipe":true,"CreateStdOutPipe":true,"CreateStdErrPipe":false,"ConsoleSize":[30,120]}.
whereas if I leave out the
--restart=always
everything works fine.
Is there something else I need to do to get --restart options working on Windows?
A: Parameters shall be coming before image:tag in CLI
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45609209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jersey Client: adding Cookies does not change Builder My first implementation using the Jersey client code with cookies does not successfully maintain session to next call. What is suspicious to me is that the method
Builder javax.ws.rs.client.Invocation.Builder.cookie(String s, String s1)
does not return a different instance of the builder. Shouldn't it? Either way, my login request is denied with message "Your session expired due to inactivity.", which seems to imply to me that the request isn't arriving with the same session id as previous.
See anything wrong with this code? The culprit in question is method #applyCookies(Builder) which does not return anything different after the cookies have been set.
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.glassfish.jersey.client.filter.HttpBasicAuthFilter;
/**
* A JAX-RS <a href="https://jax-rs-spec.java.net/" /> connector that uses
* Jersey <a href="https://jersey.java.net"/> as the API to create a client that
* will connect to a remote REST service.
*/
public class JerseyConnector extends WebServiceConnector
{
/** Debug logger. */
protected static final Logger logger = Logger.getLogger(JerseyConnector.class);
/**
* Simple test execution method.
*
* @param args
* @throws MessageException
*/
public static void main(String[] args) throws MessageException
{
JerseyConnector conn = new JerseyConnector();
conn.setProviderURL("http://somehost.somewhere.com:7203/rest");
conn.open();
String sessConf = (String)conn.send("initiateSession");
HashMap<String,String> content = new HashMap<String,String>(3);
content.put("sessionConfirmation", sessConf);
content.put("password", "password");
content.put("login", "joe");
String body = JSONMapFormatter.toJSON(content);
String loginResponse = (String)conn.send(new RESTRequest("login", body, HttpMethod.POST));
System.out.println(loginResponse);
}
protected WebTarget webTarget;
protected Map<String,Cookie> cookies;
/**
* Calls the {@link #webTarget} and provides the {@link String} response.
* The request method defaults to {@link HttpMethod#GET}.
* <p>
* If the <code>message</code> is a {@link String}, it is assumed to be the
* suffix URI to append to the provider URL of the {@link #webTarget},
* unless the string begins with a "{", in which case it is assumed to be
* the JSON request body to send.
* <p>
* If the <code>message</code> is a {@link RESTRequest}, the path, body and
* HTTP method will be determined from that.
* <p>
* Otherwise, the <code>toString()</code> version of the message will be
* sent as the body of the message.
*
* @see WebTarget#path(String)
* @see WebTarget#request()
* @see #getProviderURL()
* @see oracle.retail.stores.commext.connector.webservice.WebServiceConnector#send(java.io.Serializable)
*/
@Override
protected Serializable send(Serializable message) throws MessageException
{
RESTRequest request = null;
// determine path and body content if any
if (message instanceof RESTRequest)
{
request = (RESTRequest)message;
}
else
{
request = new RESTRequest();
String messageString = message.toString();
if (messageString.startsWith("{"))
{
request.body = (String)message;
}
else
{
request.path = (String)message;
}
}
// send request, get response
Response response = sendRequest(webTarget, request);
logger.debug("Response received.");
// remember cookies that came in the response
rememberCookies(response);
// return response as a string
return response.readEntity(String.class);
}
/* (non-Javadoc)
* @see oracle.retail.stores.commext.connector.webservice.WebServiceConnector#openConnector()
*/
@Override
protected void openConnector() throws MessageException
{
super.openConnector();
// create a client
logger.debug("Creating new client.");
Client client = ClientBuilder.newClient();
// register the auth creds
if (!Util.isEmpty(getUserName()))
{
logger.debug("Registering user credentials with client.");
client.register(new HttpBasicAuthFilter(getUserName(), getPassword()));
}
else
{
logger.info("No credentials specified for \"" + getName() + "\".");
}
// open the target url
if (logger.isDebugEnabled())
{
logger.debug("Creating webTarget with \"" + getProviderURL() + "\".");
}
webTarget = client.target(getProviderURL());
// construct a new cookie map
cookies = new HashMap<String,Cookie>(3);
}
/**
* Returns the response after invoking the specified request on the specified
* target.
*
* @param target
* @param request
* @return
*/
protected Response sendRequest(WebTarget target, RESTRequest request)
{
// retarget destination
if (request.path != null)
{
target = target.path(request.path);
}
if (logger.isDebugEnabled())
{
logger.debug("Making service request " + request);
}
// build request
Builder builder = target.request(MediaType.APPLICATION_JSON_TYPE);
// apply cookies
builder = applyCookies(builder);
// call webservice and return response as a string
if (HttpMethod.POST.equals(request.httpMethod))
{
return builder.post(Entity.entity(request.body, MediaType.APPLICATION_JSON));
}
else if (HttpMethod.PUT.equals(request.httpMethod))
{
return builder.put(Entity.entity(request.body, MediaType.APPLICATION_JSON));
}
else if (HttpMethod.DELETE.equals(request.httpMethod))
{
return target.request(request.body).delete();
}
// default to HttpMethod.GET
return target.request(request.body).get();
}
/**
* Apply all the cookies in the cookies map onto the request builder.
*
* @param builder
* @return the cookied builder
*/
private Builder applyCookies(Builder builder)
{
if (logger.isDebugEnabled())
{
logger.debug("Applying " + cookies.size() + " cookies: " + cookies);
}
for (Cookie cookie : cookies.values())
{
builder = builder.cookie(cookie.getName(), cookie.getValue());
}
return builder;
}
/**
* Put all the cookies from the response into the map of cookies being
* remembered.
*
* @param response
*/
private void rememberCookies(Response response)
{
Map<String,NewCookie> newCookies = response.getCookies();
if (logger.isDebugEnabled())
{
logger.debug("Remembering " + newCookies.size() + " cookies: " + newCookies);
}
cookies.putAll(newCookies);
}
// -------------------------------------------------------------------------
/**
* Request parameters that can be sent to this connector in order to specify
* the path (URL sub-sequence) and body (contents) of the request message to
* send.
*/
public static class RESTRequest implements Serializable
{
private static final long serialVersionUID = 5675990073393175886L;
private String path;
private String body;
private String httpMethod;
/**
* Internal constructor
*/
private RESTRequest()
{
}
/**
* @param path
* @param body
*/
public RESTRequest(String path, String body)
{
this.path = path;
this.body = body;
}
/**
* @param path
* @param body
* @param httpMethod see values at {@link javax.ws.rs.HttpMethod}
*/
public RESTRequest(String path, String body, String httpMethod)
{
this.path = path;
this.body = body;
this.httpMethod = httpMethod;
}
/**
* @return the path
*/
public String getPath()
{
return path;
}
/**
* @return the body
*/
public String getBody()
{
return body;
}
/**
* @return the httpMethod
* @see javax.ws.rs.HttpMethod
*/
public String getHttpMethod()
{
return httpMethod;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return "RESTRequest[" + httpMethod + ", " + path + ", with body=" + body + "]";
}
}
}
A: The defect was in the bottom of the #sendRequest() method. It was ignoring the Builder object returned and re-using the WebTarget to create a new request (which creates a new builder. The last three lines of code in that method should have been:
return builder.buildDelete().invoke();
}
// default to HttpMethod.GET
return builder.buildGet().invoke();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21492326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Silverlight - Unable to load a lot of data I have a Silverlight application that has a DataGrid and a DataPager. The data source for these controls comes from a database. I am accessing this database through RIA Services.
When I try to load all of the records, I receive an error that says:
"Load operation failed for query 'GetData'. The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error."
By gradually restricting the size of the result set on the server side, I have come to the conclusion that I am getting this error because my data set is too large. My question is, how do I elegantly load large data sets into a DataGrid? I am open to approaches outside of RIA Services.
Thank you!
A: First off, if you have the means and aren't required to write this code yourself, consider buying a UI component that solves you problem (of find an open source solution). For these types of tasks, there's a good chance that someone else has put a lot of effort into solving problems like this one. For reference, there's a teleric grid control for Silverlight with some demos.
If you can't buy a component, here's some approaches I've seen:
*
*Set up a paging system where
the data for the current page is
loaded, and new data isn't loaded
until the pages are switched. You
could probably cache previous results
to make this work more smoothly.
*Load data when needed, so when the user scrolls down/sideways, data is loaded once cells are reached that haven't had data loaded.
One last idea that comes to mind is to gzip the data on the server before sending. If your bottleneck is transmission time, compression speed things up for the type of data you're working with.
A: You should take into consideration that you are possibly exceeding the command timeout on your data source. The default for LINQ to SQL for example is 30 seconds. If you wanted to increase this, one option is to go to the constructor and change it as follows:
public SomeDataClassesDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["SomeConnectionString"].ConnectionString, mappingSource)
{
this.CommandTimeout = 1200;
OnCreated();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2102966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Calling setState without triggering re-render I am storing a UI state in the React component's state, say this.state.receivedElements which is an array. I want re-renders whenever an element is pushed to receivedElements. My question is, can I not trigger rendering when the array becomes empty ?
Or in general, can I call setState() just one time without re-render while re-rendering all other times ? ( are there any options, work-arounds ? )
I've read through this thread: https://github.com/facebook/react/issues/8598 but didn't find anything.
A:
I want re-renders whenever an element is pushed to receivedElements.
Note that you won't get a re-render if you use:
this.state.receivedElements.push(newElement); // WRONG
That violates the restriction that you must not directly modify state. You'd need:
this.setState(function(state) {
return {receivedElements: state.receivedElements.concat([newElement])};
});
(It needs to be the callback version because it relies on the current state to set the new state.)
My question is, can I not trigger rendering when the array becomes empty ?
Yes — by not calling setState in that case.
It sounds as though receivedElements shouldn't be part of your state, but instead information you manage separately and reflect in state as appropriate. For instance, you might have receivedElements on the component itself, and displayedElements on state. Then:
this.receivedElements.push(newElement);
this.setState({displayedElements: this.receivedElements.slice()});
...and
// (...some operation that removes from `receivedElements`...), then:
if (this.receivedElements.length) {
this.setState({displayedElements: this.receivedElements.slice()});
}
Note how we don't call setState if this.receivedElements is empty.
A: What about useRef?
Documentation says:
useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
So if you change ref value inside useEffect it won’t rerender component.
const someValue = useRef(0)
useEffect(() => {
someValue.current++
},[])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46768659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android NavigationDrawer Automatically opens I implemented the material navigation drawer with navigation view, in a fragment (Not a Activity). It works fine, but when i am coming back from anther fragment drawer automatically opens:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/bg_actionbar"
app:layout_scrollFlags="scroll|enterAlways" />
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/header"
app:menu="@menu/navigation_slide_menu" />
</android.support.v4.widget.DrawerLayout>
Here is my main fragment implementation:
navigationView.setNavigationItemSelectedListener(navigationItemSelectedListener);
actionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, mToolBar, R.string.openDrawer, R.string.closeDrawer) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, 0); // this disables the animation
}
};
actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
// Defer code dependent on restoration of previous instance state.
drawerLayout.post(new Runnable() {
@Override
public void run() {
actionBarDrawerToggle.syncState();
}
});
drawerLayout.setDrawerListener(actionBarDrawerToggle);
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
super.onCreateOptionsMenu(menu, inflater);
}
Code for calling new fragment.
NavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener = new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.menu_help:
((MainActivity) getActivity()).setFragment(new HelpFragment(), HelpFragment.getTAG());
return true;
default:
return true;
}
}
};
A: Implement NavigationDrawer in Main Activity instead of a fragment,
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, mToolBar, R.string.openDrawer, R.string.closeDrawer) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, 0); // this disables the animation
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
List<String> menuItemResList = Arrays.asList(getResources().getStringArray(R.array.nav_drawer_items));
ArrayList<String> menuItemResArrayList = new ArrayList<String>(menuItemResList);
final NavigationRecyclerAdapter navigationRecyclerAdapter = new NavigationRecyclerAdapter(MainActivity.this, menuItemResArrayList);
mRecyclerView.setAdapter(navigationRecyclerAdapter);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35053873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sybase DB error 277 in while loop after migration I am new to Sybase products.
The application was run on Windows XP connect with the SYC adaptive server, written in Powerbuilder 10.5.
Once I migrate it to PB12.6, and move the whole DB and application to win 7, one of the stored procedures throws an error 277:
There was a transaction active when exiting the stored procedure '%.*s'. The temporary table '%.*s' was dropped in this transaction either explicitly or implicitly.
in the procedure
...set initiate value of a and b...
...do sth...
print 'check point 1'
while (a=0) and b>0
begin
print 'check point 2'
...do sth...
end
print 'check point 3'
... do sth...
I found that both a and b = 0, after print 'check point 1', it shows 'return status=-1' then error 277.
No 'check point 2' or 'check point 3' can be shown
Has anyone experienced this before? Why the while loop become so strange?
I have checked commit / rollback statement exist before any return
And the stored procedure is no problem in PB10.5 running on Windows XP.
Thank you very much!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36590151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Weird error with has_and_belongs_to_many PG::UndefinedColumn: ERROR: column articles.article_id I have defined two models, an they both refer to each other with has_and_belongs_to_many
class Category < ActiveRecord::Base
has_and_belongs_to_many :articles
end
class Article < ActiveRecord::Base
has_and_belongs_to_many :categories
end
I have one migration added:
class CreateJoinTableArticleCategory < ActiveRecord::Migration
def change
create_join_table :articles, :categories do |t|
t.index [:article_id, :category_id]
t.index [:category_id, :article_id]
end
end
end
And I get this weird error when trying to edit an article in rails admin http://localhost:3000/admin/article/20/edit
Showing /Users/me/.rvm/gems/ruby-2.2.2/gems/rails_admin-0.7.0/app/views/rails_admin/main/_form_filtering_multiselect.html.haml where line #10 raised:
PG::UndefinedColumn: ERROR: column articles.article_id does not exist
A: Try this
class CreateJoinTableArticleCategory < ActiveRecord::Migration
def change
create_join_table :articles, :categories do |t|
t.index :article_id
t.index :category_id
end
end
end
Ref: api doc
Edit: No need to add index and primary key into join table.
Ref: see this answer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40718305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How is the input_matrix * weight_matrix + bias_vector possible in tensorflow? Given an N x M input matrix X, an M x U weight matrix W, and a bias vector b of length U,
how is the affine transformation XW + b possible? If the result R of the matrix multiplication is of shape N x U, how is the bias vector b added to to R? I have tried googling matrix-vector addition but have only found results for matrix-matrix or vector-vector addition. Based on the Matrix Addition Wiki Article, this transformation shouldn't be possible, but clearly I misunderstand something.
Example code below:
import tensorflow as tf
# Define tensors
N = 10
M = 4
input_matrix = tf.random.normal(shape=(N, M))
U = 2
weight_matrix = tf.random.normal(shape=(M, U))
bias_vector = tf.random.normal(shape=(U,))
# Affine transformation
R = tf.matmul(input_matrix, weight_matrix) + bias_vector
print(input_matrix.shape, '*', weight_matrix.shape, '+', bias_vector.shape, '=', R.shape)
>>> (10, 4) * (4, 2) + (2,) = (10, 2)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70028946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is preferred way to code when only header and footer's background is flexible only not content? What is preferred way to code when only header and footer's background is flexible not content?
Currently I use this method? Is there any better way to do this?
<header style="background:red>
<div style="width:950px; margin:0 auto">
</div>
</header>
<div id="content" style="width:950px; margin:0 auto">
</div>
<footer style="background:blue>
<div style="width:950px; margin:0 auto">
</div>
</footer>
I used inline css just for example
actual mark-up is
<header>
<div id="header-inner">
</div>
</header>
<div id="content">
</div>
<footer>
<div id="footer-inner">
</div>
</footer>
I'm making website for Desktop and iPad both. iPad has fixed width but Desktop can be anything.
A: header and footer make 100% width and content fix it a 95% width, so header and footer are flexible.
css:
header {
width:100%;
background:#ccc;
}
footer {
width:100%;
background:#ccc;
}
#content {
width:95%;
margin:0 auto;
}
A: Here's the other way of doing it. Not necessarily better. Your method looks fine.
<div class="wrapper">
<header>
</header>
<div id="content">
</div>
<footer>
</footer>
</div>
.wrapper { width: 950px; margin: 0 auto; }
header, footer { margin: 0px -9999px; padding: 0px 9999px; }
A: Why do you add another <div> in the header and footer?
Also please drop the inline css (if it isn't there just for this example).
Other than that your code looks fine with me
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6980829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Kafka in Kubernetes Cluster- How can services in the K8S cluster be accessed using SASL and services outside the K8S cluster be accessed using SSL I want to deploy the Kafka cluster on the Kubernetes environment and have the services within the Kubernetes cluster connect to Kafka in SASL_PLAINTEXT mode and the services outside the Kubernetes cluster connect to Kafka in SASL_SSL mode. However, I found that after setting this up, external services cannot connect to Kafka. Does Kafka not allow internal services to connect to external services differently? My Kafka version is 2.3.1 and I would be grateful if you could answer my questions.
A: It's possible, yes. You'd need to setup two advertised.listeners and listeners on the brokers with a protocol of and SSL for one set and SASL_SSL / SASL_PLAINTEXT for the other.
It's kubernetes network policies that control how cluster access happens, not only Kafka, but also, you'll need a NodePort or Ingress for any external app to reach services within the cluster. The Strimzi operator covers both, by the way
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73341240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL and H2 database connection to node database in r3 corda If we are trying to host corda node database in a SQL server can we host all of them in a single database? If yes how to do it and what will be its impact.
Can the built in H2 database which gets generated while a node is deployed be stored locally in a system such that data becomes permanent and is not lost in the next build?
A: Sharing an H2 database
As of Corda 3, each node spins up its own H2 database by default.
However, you can point multiple nodes to a single, stand-alone H2 database as follows:
*
*Start a standalone H2 instance (e.g. java -jar ./h2/bin/h2-1.4.196.jar -webAllowOthers -tcpAllowOthers)
*In the node.conf node configuration file, set dataSource.url = "jdbc:h2:tcp://localhost:9092/~/nodeUniqueDatabaseName", where nodeUniqueDatabaseName is unique to that node
For each nodeUniqueDatabaseName, H2 will create a file nodeUniqueDatabaseName.mv.db in the user's home directory.
You can also set a specific absolute path as well (e.g. dataSource.url = "jdbc:h2:tcp://localhost:9092/~/Users/szymonsztuka/IdeaProjects/corda3/nodeUniqueDatabaseName"). This will create a database file under Users/szymonsztuka/IdeaProjects/corda3/.
Note that this approach is not secure since the h2 server is started with -webAllowOthers -tcpAllowOthers, meaning that anyone can log in and modify the database.
Maintaining data across node builds
The H2 database is discarded when re-running deployNodes, because you are considered to be creating an entirely new set of nodes. If you only want to make changes to the installed CorDapps, you can shut down the node, update its CorDapps (by creating the new CorDapp JARs as described here and copying the CorDapp JARs into its cordapps folder) and restart the node. The new CorDapps will be installed, but the old node data will still be present.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52585489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Will you be notified when you specify wrong dtype for columns?
*
*I am working with very large dataset that won't fit on my RAM (which
is 16GB).
*I noticed that the columns dTypes are all float64, but values in the first 10k rows range from -1.0 to +1.0
*To check the full dataset would take too much time
I want to specify the dtype in the read_csv for all columns to float16 to reduce the necessary memory:
types = {}
for column in only_first_row_dataframe.columns:
types[column ] = 'float16'
...
dataframe = pd.read_csv(path, engine="c", dtype = types, lowmemory = False)
After running the above code would I be notified that some values didn't fit into the 16 bit float, and therefor some data were lost?
*
*I am asking this question because I tested only the first 10k rows if they fit into the range (-1.0, +1.0)
*So I want to be sure I won't lose any data.
*When I do run the code I do not have any warnings and the Dataset is loaded into my RAM, but I am not certain if any data were lost.
*According to this answer I will be notified if there is a major error in dtypes, so for example if column A will have string value at the end but I specified the dtype as int. But there is no mention about the problem I am asking here.
A: As you mentioned you will have an error raised if you have a major dtypes error (for example using int64 when the column is float64). However, you won't have an error if for example you use int8 instead of int16 and the range of your values does not match the range of int8 (i.e -128 to 127)
Here is a quick example:
from io import StringIO
import pandas as pd
s = """col1|col2
150|1.5
10|2.5
3|2.5
4|1.2
8|7.5
"""
pd.read_csv(StringIO(s),sep='|', dtype={"col1": "int8"})
And the output is:
col1 col2
0 -106 1.5
1 10 2.5
2 3 2.5
3 4 1.2
4 8 7.5
So as you can see, the first value in the column col1 has been converted from 150 to -106 without any error / warning from pandas.
The same is applied to float types, I just used int for convenience.
EDIT I add an example with floats since this is what you were asking:
from io import StringIO
import pandas as pd
s = """col1|col2
150|32890
10|2.5
3|2.5
4|1.2
8|7.5
"""
If you read it without specifying the dtype:
pd.read_csv(StringIO(s),sep='|'))
col1 col2
0 150 32890.0
1 10 2.5
2 3 2.5
3 4 1.2
4 8 7.5
If you read it with specifying the "wrong" dtype for the columns:
pd.read_csv(StringIO(s),sep='|', dtype={"col1": "int8", "col2": "float16"})
col1 col2
0 -106 32896.000000
1 10 2.500000
2 3 2.500000
3 4 1.200195
4 8 7.500000
If you have a large CSV file and you want to optimize the dtypes, you can load the CSV file column by column (this should not take too much memory) with no dtype then infer the optimal dtype thanks to the values inside the column and load the full CSV with the optimized dtypes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66901375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Correct way making a translation table? We currently use a translation table which looks like this:
| id | type | name | lang | value |
|-----+-------+----------+-------+----------|
| 853 | text | question | en | question |
| 854 | text | question | nl | vraag |
So for each extra translation in another language we would have to add another row
Were thinking about changing it to a table which has a column for each country value (so you would just need to add 1 row).
So it would look like this:
| id | type | name | lang | nl | en |
|-----+-------+----------+-------+---------+------------+
| 853 | text | question | en | vraag | question |
*
*Are there any downsides to doing it the second way compared to the
first one?
*How would you suggest creating a translation table like
this?
A: Why not to join two tables, master one with id,type,name fields and nested with id,master_id,lang,value. For the given example that will be looking like:
ID TYPE NAME
1 text question
ID MASTER_ID LANG TRANSLATION
1 1 en question
2 1 nl vraag
The translation set for one language is given by SQL query:
SELECT * FROM `nested` WHERE `lang` = 'nl'
-- vraag
-- .....
The translation for the given term (e.g. question, having id=1):
SELECT * FROM `nested` WHERE `master_id` = 1 AND `lang` = 'nl'
-- vraag
A: The downside of the second idea is that for every new language you want to add you have to change your database structure (following code changes to reflect that structure change) whereas the first only needs new rows (which keeps the same structure).
another plus for the first idea is that you really only need the space/memory for translations you add to the database. in the second approach you could have lots of empty fields in case you won't translate all texts.
a way to do it could be (an addition to the answer above from @mudasobwa):
Master Table:
| id | type | master_name |
|----+------+-------------|
|853 | text | question |
|854 | text | answer |
Language Table:
| id | language_name |
|----+---------------|
| 1 | english |
| 2 | german |
Translation Table:
| id | master_id | language_id | translation |
|----+-----------+-------------+--------------------|
| 1 | 853 | 1 | question |
| 1 | 854 | 2 | Frage |
| 2 | 853 | 1 | answer |
| 2 | 854 | 2 | Antwort |
So if you have another language, add it to the language table and add the translations for your master texts for that language.
Adding indexes to the ids will help speeding up queries for the texts.
A: Second way is much better:
*
*Keeps less place in Database.
*Loads faster.
*Easy to edit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24805597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Debugging a software verifier written in Scala working as plugin of sbt I'm working with Stainless, a software verifier for Scala programs. I would like to debug the verification process of a sample programme. On a previous post, I solved this integration problem for an interactive theorem prover. But now, I'm facing two problems:
Apparently, the verification software runs at compile time. That is, I enter in the sbt console and run the compile command and then the verification process seems to be done. You may try this with this verified example. This situation is new to me, since I was used to debug the program while executing.
Alternatively, I found out that it was possible (2013) to debug plugins in Intellij Idea and this may be the case with the released (see section on sbt) plugin for using Stainless on Sbt.
So to clarify , I'm looking for a complete set up that would allow me to debug the verification process from the terminal/with some specific software in a way that I can follow the control flow/variables etc, of Stainless and my own project.
Details
This is the current configuration page of stainless.
This is my question on how to solve this problem on Intellij Idea (more challenging I guess)
Pipeline
In case it helps I leave the pipeline of the tool posted here (took it from documentation):
Additional observations
There is an open issue for this in Intellij Idea support.
An alternative I have to experiment with is the Scala REPL.
A: I'm looking for this tools too but I don't found any good. I try logger and there're fine for me.
scala-logger: Simple Scala friendly logging interface.
Logback Project for backend
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51227087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Javascript/Node/Express: res.json needs to wait for a function to finish running before returning... but res.json is impatient? Hello friends! I hope you are well.
So in this snippet of code, I have a list of ten servers I want to query. These ten servers are represented by the ten ports I have defined up top in the const "ports".
The idea is to use forEach() on "ports", and run the query on each server. An object is returned by each run of the query and added into the initially empty array "data".
THEN! After "data" has been loaded with the ten objects containing the status of my servers, I want it dished back to the client side!
However..... this is not what happens. Port.forEach() runs the query just fine, and adds into the array "data"... but not before res.json jumps the gun and sends off an empty data back to my soon to be disappointed client.
So far... I've tried callbacks and async/await... but I haven't figured out the syntax for it.. Any tips would be awesome! Thank you for your time friendos!
module.exports = app => {
app.get("/api/seMapServerStatus", (req, res) => {
const ports = [ "27111", "27112", "27117", "27118", "27119", "27110", "27115", "27116", "27113", "27114" ]
const data = []
function hitServers(port){
Gamedig.query({
type: "aGameType",
host: "theServer'sIP",
port: port
}).then((state) => {
data.push(state)
console.log("this is the server", state)
}).catch((error) => {
console.log("Server is offline");
});
};
ports.forEach(port => {
hitServers(port)
})
});
console.log("and here is the final server list", data)
res.json(data);
}
A: The above code executes synchronously, therefore you return in the same frame before any promise has the chance to resolve.
We can clean the above code up as follows:
module.exports = app => {
app.get("/api/seMapServerStatus", (req, res) => {
const ports = ["27111", "27112", "27117", "27118", "27119", "27110", "27115", "27116", "27113", "27114"]
function hitServers(port) {
return Gamedig.query({
type: "aGameType",
host: "theServer'sIP",
port: port
})
}
// With error handling
function hitServersSafe(port) {
return hitServers(port)
.then(result => {
return {
success: true,
result: result
}
})
.catch(error => {
return {
success: false,
// you probably need to serialize error
error: error
}
})
}
const promises = ports.map(port => hitServers(port))
// With error handling
// const promises = ports.map(port => hitServersSafe(port))
Promise
.all(promises)
.then(data => res.json(data))
.catch(error => {
// do something with error
})
})
}
We map each port to a promise. After we have a list of X promises we wait for all of them to finish.
The calling Promise.all() returns an array of resolved values, or rejects when any promise rejects.
Only after all of the promises have resolved we can move on and send the result to the client.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58509876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how to get only date part from date string in C# i need to get in this format "2015-10-03" , but im getting like this "10/3/2015" and "10/3/2015 12:00:00 AM" both are not working in my query .because my updateddate datatype is date only
Fromdate = Txtbox_AjaxCalFrom.Text.Trim();// 10/3/2015
DateTime frmdt = Convert.ToDateTime(Fromdate);// 10/3/2015 12:00:00 AM
ToDate = Txtbox_AjaxCalTo.Text.Trim();
DateTime todt = Convert.ToDateTime(Fromdate);
i want query like this
updateddate between '2015-10-03' and '2015-10-03'
full query
gvOrders.DataSource = GetData(string.Format("select * from GoalsRoadMap where Activities='{0}' and project ='" + ProjectName + "' and updateddate between '2015-10-03' and '2015-10-03' ", customerId));
A: try this:
DateTime frmdt = Convert.ToDateTime(fromDate);
string frmdtString = frmdt.ToString("yyyy-MM-dd");
or at once:
string frmdt = Convert.ToDateTime(fromDate).ToString("yyyy-MM-dd");
So your code could look like this:
Fromdate = Txtbox_AjaxCalFrom.Text.Trim();// 10/3/2015
string frmdt = Convert.ToDateTime(Fromdate).ToString("yyyy-MM-dd");
ToDate = Txtbox_AjaxCalTo.Text.Trim();
string todt = Convert.ToDateTime(todt).ToString("yyyy-MM-dd");
gvOrders.DataSource = GetData(string.Format("select * from GoalsRoadMap where Activities='{0}' and project ='" + ProjectName + "' and updateddate between '{1}' and '{2}' ", customerId, frmdt, todt ));
A: As mentioned by Christos you can format DateTime to universal Date string (here are examples https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx). But right way to create queries is to use parameters. The following sample for SqlClient, but the idea is the same for other providers.
var cmd=new SqlCommand("UPDATE Table1 SET field1=@value WHERE dateField=@date");
cmd.Parameters.Add("@date",SqlDbType.Date).Value=myDateTime; //myDateTime is type of DateTime
...
And you have an error in SQL, BETWEEN '2015-10-03' AND '2015-10-03' will return nothing. Instead try this one dateField>='2015-10-03' AND dateField<='2015-10-03'
A: You could format your date string as you wish. Let that dt is your DateTime object with the value 10/3/2015 12:00:00 AM. Then you can get the string representation you want like below:
var formatted = dt.ToString("yyyy-MM-dd");
A: If your SQL date items stored as date and time, not just date, then your problem will be that for items between '2015-10-03' and '2015-10-03', it returns nothing.
So you just need to add one day to your toDate.Date that its Time is 12:00:00 AM.
Something like this:
Fromdate = Txtbox_AjaxCalFrom.Text.Trim();// 10/3/2015
string frmdt = Convert.ToDateTime(Fromdate).Date; // 10/3/2015 12:00:00 AM
//Or
//var frmdt = DateTime.Parse(Txtbox_AjaxCalFrom.Text).Date;
ToDate = Txtbox_AjaxCalTo.Text.Trim();
string todt = Convert.ToDateTime(todt).Date.AddDays(1);// 11/3/2015 12:00:00 AM
now if run your query like this, it may works:
var items = allYourSearchItems.Where(x => x.Date >= frmdt && x.Date < todt );
A: None of the above answer worked for me.
Sharing what worked:
string Text="22/11/2009";
DateTime date = DateTime.ParseExact(Text, "dd/MM/yyyy", null);
Console.WriteLine("update date => "+date.ToString("yyyy-MM-dd"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32919509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Controller code to create a record that has two belongs_to relationships I can create a statistic for a given person like this:
@person = Person.find(person.id)
@statistic = @person.statistics.build(:value => @value, :updated => @updated)
There's a one-to-many (has_many/belongs_to) relationship between person and statistic.
The above works fine.
However, I also want the statistic to belong to a race too (race as in running/driving race) i.e. I have changed my statistic model to have two belongs_tos:
belongs_to :person # just had this before
belongs_to :race # this is new
Is the above correct or do I need to use a through in my models somehow? If so, how?
How do I alter my controller code for this change?
Many thanks.
A: If you want statistic to belong to race only, you don't need to use has_many :through. All you need to do is to add the new reference when building a statistic entry by either a new object:
@race = Race.new(....)
@person.statistics.build(value: @value, updated: @updated, race: @race)
or by foreign key (if the referenced race already exists)
@person.statistics.build(value: @value, updated: @updated, race_id: @race.id)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17639026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to access parent $scope variable when use ng-include? My goal is to access parent $scope variable.
This post helps me a lot, however I don't know how to do this in a real case. When I declared controller in child html it throws an error:
areq?p0=ParentController&p1=not a function, got undefined
my project looks like this Plunker
Does this error happens because of nested App declaration?
A: AngularJS $scopes prototypically inherit from each other. Quoting the wiki:
In AngularJS, a child scope normally prototypically inherits from its parent scope. One exception to this rule is a directive that uses scope: { ... } -- this creates an "isolate" scope that does not prototypically inherit.(and directive with transclusion) This construct is often used when creating a "reusable component" directive. In directives, the parent scope is used directly by default, which means that whatever you change in your directive that comes from the parent scope will also change in the parent scope. If you set scope:true (instead of scope: { ... }), then prototypical inheritance will be used for that directive.
This means that assuming you did not pass scope: { ... } you can access properties on the parent's scope directly.
So for example if the parent scope has a x: 5 property - you can simply access it with $scope.x.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23354951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: configure and cross compiling samba v4.17.3 has an error I am cross-compiling samba v4.17.3, i met some questions.
I write auto_config.sh,
root@gyz-thinkcentre-e73:~/third_source/samba-4.17.3# cat auto_config.sh
qemu_binary="qemu-aarch64"
libdir_qemu="/root/niic/SDK/sysroots/aarch64-niic-linux/lib64/"
base_libdir_qemu="/root/niic/SDK/sysroots/aarch64-niic-linux/usr/lib64/"
prefix_path="/root/result/samba"
CROSS_EXEC= "${qemu_binary} -L /root/niic/SDK/sysroots -E LD_LIBRARY_PATH=${libdir_qemu}:${base_libdir_qemu}"
./configure --prefix=${prefix_path} --target=aarch64-niic-linux --host=aarch64-niic-linux samba_cv_CC_NEGATIVE_ENUM_VALUES=yes --cross-exec="${CROSS_EXEC}"
when i run auto_config.sh, a error occured: No such file or directory, but the two path '/root/niic/SDK/sysroots/aarch64-niic-linux/lib64/' and '/root/niic/SDK/sysroots/aarch64-niic-linux/usr/lib64/' are exist.
root@gyz-thinkcentre-e73:~/third_source/samba-4.17.3# ./auto_config.sh
./auto_config.sh: line 7: qemu-aarch64 -L /root/niic/SDK/sysroots -E LD_LIBRARY_PATH=/root/niic/SDK/sysroots/aarch64-niic-linux/lib64/:/root/niic/SDK/sysroots/aarch64-niic-linux/usr/lib64/: No such file or directory
Setting top to : /root/third_source/samba-4.17.3
Setting out to : /root/third_source/samba-4.17.3/bin
Checking for 'gcc' (C compiler) : aarch64-niic-linux-gcc -mcpu=cortex-a55 -fstack-protector-strong -D_FORTIFY_SOURCE=2 -Wformat -Wformat-security -Werror=format-security --sysroot=/root/niic/SDK/sysroots/aarch64-niic-linux
Checking for program 'git' : /usr/bin/git
Checking for c flags '-MMD' : yes
Checking for program 'gdb' : aarch64-niic-linux-gdb
Checking for header sys/utsname.h : yes
Checking uname sysname type : not found
Checking uname machine type : not found
Checking uname release type : not found
Checking uname version type : not found
Checking for header stdio.h : yes
Checking simple C program : not found
The configuration failed False
(complete log in /root/third_source/samba-4.17.3/bin/config.log)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75002622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to open asset URL: file:///android_asset/www/submit?UserName=Admin&Password=super%401234 in Phonegap Android? I am completely new to Phonegap and Javascript. I am trying to save the username value and password value from the login form to sqlite database.
This is my login.html file:-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Login</title>
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="js/iscroll.js"></script>
<script type="text/javascript" src="js/login.js"></script>
</head>
<body>
<div class="wrapper">
<form action="submit" id="login" name="login_form">
<input type="text" id="uName" name = "UserName" placeholder="Username" value="Admin"/>
<br/>
<input type="password" id="password" name = "Password" placeholder="Password" value="super@1234"/>
<br/>
<button type="submit" id="submit" value="Submit">Login</button>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
if($("#uName").val()==""){
alert("Please fill username field.");
//$("#uName").focus();
}
else if($("#password").val()==""){
alert("Please fill password field.");
//$("#password").focus();
}
else {
onDeviceReady();
}
});
});
</script>
</div>
</body>
</html>
and this is my login.js file:-
var db;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
db = window.openDatabase("UserDB", "1.0", "Login", 10000);
db.transaction(populateDB, transaction_err, populateDB_success);
}
function populateDB(tx) {
var userName = document.getElementById("uName").value;
var password = document.getElementById("password").value;
tx.executeSql('CREATE TABLE IF NOT EXISTS users (ID INT, USERNAME VARCHAR UNIQUE, PASSWORD VARCHAR)');
tx.executeSql('INSERT INTO users (ID,USERNAME,PASSWORD) VALUES ("'+1+'","'+userName+'","'+password+'")');
alert("" + userName + " " + password);
}
function transaction_err(tx, error) {
alert("Database Error: " + error);
}
function populateDB_success(tx) {
alert("Data successfully entered.");
window.open("file:///assets/www/view_login.html");
}
My problem is when I am running this code in my android device it gives me application error : There is a network error and
error log is:-
04-30 10:16:35.080 31868-31868/com.itpp.trt D/CordovaWebViewImpl onPageDidNavigate(file:///android_asset/www/submit?UserName=Admin&Password=super%401234)
04-30 10:16:35.080 31868-31934/com.itpp.trt E/AndroidProtocolHandler﹕ Unable to open asset URL: file:///android_asset/www/submit?UserName=Admin&Password=super%401234
04-30 10:16:35.090 31868-31868/com.itpp.trt D/SystemWebViewClient﹕ CordovaWebViewClient.onReceivedError: Error code=-1 Description=There was a network error. URL=file:///android_asset/www/submit?UserName=Admin&Password=super%401234
I cant find where is the problem please help me.
Thanks and sorry for the long question. :)
A: The form is trying to submit the provided data to the url: 'file:///android_asset/www/submit'.
The url is submitted via the action attribute inside the <form> tag:
<form action="submit" id="login" name="login_form">
To prevent this from happening just take the action attribute out of the tag.
Since you are new to Phonegap/Cordova you probably don't know that you shouldn't wait for the document.ready event but instead for the deviceready. Now when you change this, your form submit will probably no longer work. This is because the deviceready event fires once when the App is launched and ready to use. It doesn't wait for a button click or a function declared inside the deviceready function.
How can we get this to work again? That's simple, just call a function that when the submit button is clicked. You will need to do something like this:
<form id="login" name="login_form" onsubmit="mySubmitFunction();">
The called function should look something like this:
function mySubmitFunction(){
$("login").unbind("submit"); //this removes the submit event-handler from the form
if($("#uName").val()==""){
alert("Please fill username field.");
}
else if($("#password").val()==""){
alert("Please fill password field.");
}
else {
//insert into your database
db.transaction(populateDB, transaction_err, populateDB_success);
}
}
Inside the onDeviceReady function just open the database:
function onDeviceReady() {
db = window.openDatabase("UserDB", "1.0", "Login", 10000);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29959598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Access 2010 VBA how to check value of a listbox Alright, just a warning, I'm a complete rookie with VBA and Access, but I'm plugging away at it.
I've got a form with some listboxes on it, what I want to do is hide or show certain listboxes and fields of the form based on the "parent" listbox's selection.
I.e. "location" listbox contains many choices, one of them called "Canada"
When the user selects "Canada" I want the form to show another box called "provinces"
Current code:
Private Sub Form_Load()
MsgBox "Form Loaded"
If Forms![Tickets]![location] = "Canada" Then
MsgBox "location is Canada!"
End If
End Sub
The msgBox is in the if statement simply for me to see if the if statement is being triggered, whenever I figured this out I'll change that to the code I want executed.
I thought I knew how to reference the controls on the forms from VBA but I might be doing that wrong. I come from a PHP/Mysql background so I'm still grasping the language.
Cheers
A: If the SQL of a listbox is set to:
SELECT Id, SomeOtherField FROM aTable
Then the value of the list box is Id, not SomeOtherField.
In this case you should say:
If Me.[location] = 1 Then ''Where 1 is the Id you want.
To check the value of a control, you can click on an item and use ctrl+G to get the immediate window, then type
?Screen.ActiveControl
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22324283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Find elements in list from itertools import permutations as pm
perm = pm([1, 2, 3, 4])
pm_list = []
for i in list(perm):
pm_list.append(i)
print(pm_list)
print(pm_list[0])
gives me:
[(1, 2, 3, 4), (1, 2, 4, 3), ... ]
(1, 2, 3, 4)
How can I work with the numbers in the second row (1, 2, 3, 4)?
I have to address and to work with every single number in the bracket.
print(pm_list[0][0]) doesn't work.
Thanks in advance.
A: To use every number in the first result you can use a for loop.
for number in pm_list[0]:
print (number)
Or if you want to do this for all results:
for result in pm_list:
for number in result:
print (number)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62171188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: attempting to copy non zero rows and also create a report template I have two inclusions I want to include in this code.
The first is to omit zero balance values (in column F in TB New) rows from my TB New and paste rows to TB New Non Zero, I will just change the input worksheet from TB New to TB New Non Zero. I was thinking of just repeating this code but changing it to new variables and just do Cell Value <> 0 but I tried it and it didnt work:
Dim xTb As Range
Dim xTbCell As Range
Dim F As Long
Dim G As Long
Dim H As Long
F = Worksheets("TB New").UsedRange.Rows.Count
G = Worksheets("TB New Non Zero").UsedRange.Rows.Count
If G = 1 Then
If Application.WorksheetFunction.CountA(Worksheets("TB New Non Zero").UsedRange) = 0 Then G = 0
End If
Set xTb = Worksheets("TB New").Range("F1:F" & F)
On Error Resume Next
Application.ScreenUpdating = False
Worksheets("TB New Non Zero").UsedRange.Offset(1).Clear
G = 0
For H = 1 To xTb.Count
If CStr(xTb(H).Value) <> 0 Then
xTb(H).EntireRow.Copy Destination:=Worksheets("TB New Non Zero").Range("F" & G + 1)
G = G + 1
End If
Next
The code above prints just all the rows and omits some rows at the bottom which is not what I want.
The second is to create a for loop where LEFT(column A Value,1) = 0 then copy the rows that are that then the next row Set value to be Expenses and then add 1 to the row then where LEFT(column A Value,1) = 1 then copy the rows then so on.
Essentially Currently it is:
0575 Interest 20
1015 Purchases -50
1680 Repairs -10
2000 Bank 200
2400 Debtors 0
2475 Plant 200
But I want it as
Revenue
0575 Interest 20
Expenses
1015 Purchases -50
1680 Repairs -10
Current Assets
2000 Bank 200
2475 Plant 200
Any help on this code? Thanks,
Function getLastUsedRow(ws As Worksheet) As Long
Dim lastUsedRow As Long: lastUsedRow = 1
On Error Resume Next
lastUsedRow = ws.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
On Error GoTo 0
getLastUsedRow = lastUsedRow
End Function
Function getLastUsedColumn(ws As Worksheet) As Long
Dim lastUsedColumn As Long: lastUsedColumn = 1
On Error Resume Next
lastUsedColumn = ws.Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
On Error GoTo 0
getLastUsedColumn = lastUsedColumn
End Function
Function checkIfWorksheetExists(wb As Workbook, wsName As String) As Boolean
Dim i As Long
Dim found As Boolean
found = False
For i = 1 To wb.Worksheets.Count
If Trim(wb.Worksheets(i).Name) = Trim(wsName) Then
found = True
Exit For
End If
Next i
checkIfWorksheetExists = found
End Function
Public Function inCollection(ByVal inputCollection As Collection, ByVal inputKey As Variant) As Boolean
On Error Resume Next
inputCollection.Item inputKey
inCollection = (Err.Number = 0)
Err.Clear
End Function
Sub CopyRowBasedOnCellValue()
Dim xRg As Range
Dim xCell As Range
Dim A As Long
Dim B As Long
Dim C As Long
A = Worksheets("SQL hl_balance").UsedRange.Rows.Count
B = Worksheets("CY amounts").UsedRange.Rows.Count
If B = 1 Then
If Application.WorksheetFunction.CountA(Worksheets("CY amounts").UsedRange) = 0 Then B = 0
End If
Set xRg = Worksheets("SQL hl_balance").Range("A1:A" & A)
On Error Resume Next
Application.ScreenUpdating = False
Worksheets("CY amounts").UsedRange.Offset(1).Clear
B = 4
For C = 1 To xRg.Count
If CStr(xRg(C).Value) = Worksheets("Client Details").Range("C19").Value Then
xRg(C).EntireRow.Copy Destination:=Worksheets("CY amounts").Range("A" & B + 1)
B = B + 1
End If
Next
If Not checkIfWorksheetExists(ThisWorkbook, "Index") Then
MsgBox "Please create Index sheet, and run macro again!"
Exit Sub
End If
Application.ScreenUpdating = False
Dim i As Long
Dim j As Long
Dim k As Long
Dim wsInputData As Worksheet: Set wsInputData = Worksheets("TB New")
Dim wsInputDataStartingRow As Long: wsInputDataStartingRow = wsInputData.Range("C1").End(xlDown).Row + 1 ' Starting row !
Dim wsInputDataEndingRow As Long: wsInputDataEndingRow = getLastUsedRow(wsInputData) + 10 ' Ending row !
Dim wsInputDataUsedRange As Range: Set wsInputDataUsedRange = wsInputData.Range("A" & CStr(wsInputDataStartingRow) & ":" & "D" & CStr(wsInputDataEndingRow))
Dim wsIndex As Worksheet: Set wsIndex = ThisWorkbook.Worksheets("Index")
Dim wsIndexStartingRow As Long: wsIndexStartingRow = 5
Dim wsIndexEndingRow As Long: wsIndexEndingRow = getLastUsedRow(wsIndex) + 10
Dim wsIndexUsedRange As Range: Set wsIndexUsedRange = wsIndex.Range("A" & CStr(wsIndexStartingRow) & ":" & "H" & CStr(wsIndexEndingRow))
Dim wsIndexSheetCollection As Collection: Set wsIndexSheetCollection = New Collection
Dim wsIndexCellCollection As Collection: Set wsIndexCellCollection = New Collection
Dim wsIndexCellCollection2 As Collection: Set wsIndexCellCollection2 = New Collection
Dim wsIndexStatusCollection As Collection: Set wsIndexStatusCollection = New Collection
For i = wsIndexStartingRow To wsIndexEndingRow
If Trim(wsIndex.Range("A" & CStr(i)).Value2) <> "" And Trim(wsIndex.Range("E" & CStr(i)).Value2) <> "" Then
If wsIndex.Range("E" & CStr(i)).Hyperlinks.Count > 0 Then
If Not inCollection(wsIndexSheetCollection, Trim(wsIndex.Range("A" & CStr(i)).Value2)) Then
wsIndexSheetCollection.Add Trim(wsIndex.Range("E" & CStr(i)).Hyperlinks.Item(1).SubAddress), Trim(wsIndex.Range("A" & CStr(i)).Value2)
wsIndexCellCollection2.Add Trim(wsIndex.Range("E" & CStr(i)).Value2), Trim(wsIndex.Range("A" & CStr(i)).Value2)
End If
Else
If Not inCollection(wsIndexSheetCollection, Trim(wsIndex.Range("A" & CStr(i)).Value2)) Then
wsIndexSheetCollection.Add Trim(wsIndex.Range("E" & CStr(i)).Value2), Trim(wsIndex.Range("A" & CStr(i)).Value2)
wsIndexCellCollection2.Add Trim(wsIndex.Range("E" & CStr(i)).Value2), Trim(wsIndex.Range("A" & CStr(i)).Value2)
End If
End If
End If
If Trim(wsIndex.Range("A" & CStr(i)).Value2) <> "" And Trim(wsIndex.Range("F" & CStr(i)).Value2) <> "" Then
If Not inCollection(wsIndexCellCollection, Trim(wsIndex.Range("A" & CStr(i)).Value2)) Then
wsIndexCellCollection.Add Trim(wsIndex.Range("F" & CStr(i)).Value2), Trim(wsIndex.Range("A" & CStr(i)).Value2)
End If
End If
If Trim(wsIndex.Range("A" & CStr(i)).Value2) <> "" And Trim(wsIndex.Range("H" & CStr(i)).Value2) <> "" Then
If Not inCollection(wsIndexStatusCollection, Trim(wsIndex.Range("A" & CStr(i)).Value2)) Then
wsIndexStatusCollection.Add Trim(wsIndex.Range("H" & CStr(i)).Value2), Trim(wsIndex.Range("A" & CStr(i)).Value2)
End If
End If
Next i
Call Unlock_Sheet
wsIndexUsedRange.ClearContents
wsIndexUsedRange.Cells.Font.Bold = False
wsInputDataUsedRange.Copy
wsIndex.Range("A" & CStr(wsIndexStartingRow)).PasteSpecial xlPasteValuesAndNumberFormats
Application.CutCopyMode = False
wsIndexEndingRow = getLastUsedRow(wsIndex) + 100
For i = wsIndexEndingRow To wsIndexStartingRow Step -1
If Trim(wsIndex.Range("B" & CStr(i)).Value2) = "" Then
wsIndex.Rows(CStr(i) & ":" & CStr(i)).Delete
End If
Next i
wsIndexEndingRow = getLastUsedRow(wsIndex) + 10
For i = wsIndexStartingRow To wsIndexEndingRow
If Trim(wsIndex.Range("A" & CStr(i)).Value2) <> "" Then
If inCollection(wsIndexSheetCollection, Trim(wsIndex.Range("A" & CStr(i)).Value2)) Then
If InStr(1, wsIndexSheetCollection.Item(Trim(wsIndex.Range("A" & CStr(i)).Value2)), "!") <> 0 Then
wsIndex.Hyperlinks.Add Anchor:=wsIndex.Range("E" & CStr(i)), Address:="", SubAddress:=wsIndexSheetCollection.Item(Trim(wsIndex.Range("A" & CStr(i)).Value2)), TextToDisplay:="'" & Trim(wsIndex.Range("A" & CStr(i)).Value2)
wsIndex.Range("E" & CStr(i)).Value2 = "'" & wsIndexCellCollection2.Item(Trim(wsIndex.Range("A" & CStr(i)).Value2))
Else
If checkIfWorksheetExists(ThisWorkbook, Trim(wsIndex.Range("A" & CStr(i)).Value2)) Then
If inCollection(wsIndexCellCollection, Trim(wsIndex.Range("A" & CStr(i)).Value2)) Then
wsIndex.Hyperlinks.Add Anchor:=wsIndex.Range("E" & CStr(i)), Address:="", SubAddress:=Trim(wsIndex.Range("A" & CStr(i)).Value2) & "!" & wsIndexCellCollection.Item(Trim(wsIndex.Range("A" & CStr(i)).Value2)), TextToDisplay:=Trim("'" & wsIndex.Range("A" & CStr(i)).Value2)
wsIndex.Range("E" & CStr(i)).Value2 = "'" & wsIndexCellCollection2.Item(Trim(wsIndex.Range("A" & CStr(i)).Value2))
Else
wsIndex.Hyperlinks.Add Anchor:=wsIndex.Range("E" & CStr(i)), Address:="", SubAddress:=Trim(wsIndex.Range("A" & CStr(i)).Value2) & "!A1", TextToDisplay:="'" & Trim(wsIndex.Range("A" & CStr(i)).Value2)
wsIndex.Range("E" & CStr(i)).Value2 = "'" & wsIndexCellCollection2.Item(Trim(wsIndex.Range("A" & CStr(i)).Value2))
End If
Else
wsIndex.Range("E" & CStr(i)).Value2 = wsIndexSheetCollection.Item(Trim(wsIndex.Range("A" & CStr(i)).Value2))
End If
End If
End If
If inCollection(wsIndexCellCollection, Trim(wsIndex.Range("A" & CStr(i)).Value2)) Then
wsIndex.Range("F" & CStr(i)).Value2 = wsIndexCellCollection.Item(Trim(wsIndex.Range("A" & CStr(i)).Value2))
End If
wsIndex.Range("G" & CStr(i)).Formula = "=IFERROR(IF(OR(C" & CStr(i) & "+D" & CStr(i) & "=INDIRECT(""'""&E" & CStr(i) & "&""'""&""!""& F" & CStr(i) & "),D" & CStr(i) & "-C" & CStr(i) & "=INDIRECT(""'""&E" & CStr(i) & "&""'""&""!""& F" & CStr(i) & "),C" & CStr(i) & "-D" & CStr(i) & "=INDIRECT(""'""&E" & CStr(i) & "&""'""&""!""& F" & CStr(i) & ")),1,0),"""")"
If inCollection(wsIndexStatusCollection, Trim(wsIndex.Range("A" & CStr(i)).Value2)) Then
wsIndex.Range("H" & CStr(i)).Value2 = wsIndexStatusCollection.Item(Trim(wsIndex.Range("A" & CStr(i)).Value2))
End If
End If
Next i
Set wsIndexSheetCollection = Nothing
Set wsIndexCellCollection = Nothing
Set wsIndexStatusCollection = Nothing
Set wsIndex = Nothing
Sheets("Index").Select
Range("A1").Select
MsgBox "Done !", vbInformation
Application.ScreenUpdating = True
End Sub```
[1]: https://i.stack.imgur.com/H1jT6.png
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66682925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to select the date from Excel I have a question about excel. What will be the formula for selecting a data for one criteria. The criteria will be the last day of the month. For example, from this table:
I need to choose automatically the number for 31 january 1994, and after this I need to select the number for the last day of the next month. I have to select the data for each month for 22 years.
A: It's a bit unclear what you mean by "choose automat the number" and "select the number", and you didn't tag with your Excel version. But, if you have Excel 2007 or later, perhaps this will help.
Let's assume your first "Date" value (17-Jan-1994) is located in cell A2.
*
*In cell C2, add the following formula, which will return TRUE if the value in A2 is the last day of the month (otherwise it will return FALSE):
=EOMONTH(A2, 0) = A2
*Formula-copy cell C2 all the way down to the last row in the table.
*On the Ribbon's "Data" tab, in the "Sort & Filter" section, click the "Filter" button (it looks like a funnel).
*Click the dropdown that now exists in column C, click the "FALSE" item so as to remove its checkmark, and then click the "OK" button.
*Your table will be filtered so as to display only rows where the "Date" value represents the last day of the month. You can now select the values in column B and copy/paste them, or do whatever you like with them.
Result:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41001617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: xajax expanding list query As you'll see, I'm a newbie to all this ajax stuff but I can do a bit of php and so I plumped for xajax to take care of the javascript for me.
I've got an array with items listed in different section. I want to use this array to produce an unordered list that expands when someone clicks on a section.
I've adapted a script I found here:
Sliding Draw
My script currently looks like this:
<?php
include ("xajax_core/xajax.inc.php");
$subs = array(
"Mortice" => array("Union Deadlock 2.5", "Union Deadlock 3", "Union Sashlock 2.5", "Union Sashlock 3"),
"Cylinders" => array("30/30 Euro", "30/40 Euro", "30/50 Euro", "30/60 Euro"),
"uPVC" => array("30/92 Fullex", "35/92 Fullex", "Sash jammer")
);
function addsub($show, $key)
{
$objResponse=new xajaxResponse();
if ($show=="true") {
$objResponse->assign("list", "style.display", "block");
$objResponse->replace("$key","innerHTML","true","false");
}
else {
$objResponse->assign("list", "style.display", "none");
$objResponse->replace("$key","innerHTML","false","true");
}
return $objResponse;
}
$xajax = new xajax();
$xajax->registerFunction("addsub");
$xajax->processRequest();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php $xajax->printJavascript() ?>
<title>Expand menu test</title>
<style type="text/css">
.list {display: none;}
</style>
</head>
<body>
<?php
echo "<ul>\n";
foreach ($subs as $key => $group) {
echo "<li id=\"".$key."\" onClick=\"xajax_addsub('true','$key');\">".$key."\n";
echo "<ul class=\"list\" id=\"list\">\n";
while (list($list, $each) = each($group)) {
echo "<li id=\"list\">".$each."</li>\n";
}
echo "</ul>\n</li>\n";
}
echo "</ul>";
?>
</body>
</html>
The idea is that when an element is clicked on it changes the style display to block (thus showing the rest of the list) and sets the function to 'false' so if it's clicked again it will change the display back to none and hide the list.
Needless to say it doesn't work so if someone could point out to me why I'd be eternally grateful.
Cheers,
Nick.
Solved - I sorted it by placing the lists to be shown (or hidden) into <divs> and assigning them each a unique id and setting their style as display: none.
Then I just had to make a request to set the style as block when it was clicked on.
Thanks.
A: I think you should look into jQuery as your default javascript library, it's used by many web professionals and is very good. There you will find the Accordion control, which I think will suite this need very well.
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5006832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: nodejs with mysql , cant get data from db can't get data from mysql db in nodejs in routes '/users'
app.get('/users', function(req,res){
connection.query("select * from users",function(err,rows){
if(!err) {
res.json(rows);
}else{
console.log(err);
res.send('err here !!' + err);
}
connection.end();
});
});
take much time and then response with
ERR_EMPTY_RESPONSE
db connection
var connection = mysql.createConnection({
host : 'localhost',
port : port,
database : 'test',
user : 'root',
password : 'root'
});
can some one help me to track this issue ,
Thanks in advance.
A: This issue has been resolved: I defined the MySql port as 8080 by mistake.
I corrected the port to 3306.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34252767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WCFService calling a Singleton instance from windows service returning empty I have a static (large)data from database that i need to send to clients so i created a singleton class that get the data from the database and populate the list.
I start the service host inside the windows service, so when an outside call the wcf the data comes empty, what should i do?
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class CacheDataService : ICacheDataService
{
public List<Sale> GetDataFromImobDateById(int idImob, DateTime date)
{
return SalesHelper.Instance.GetDataFromImobDate(idImob, date);
}
}
public class SalesHelper
{
static Lazy<SalesHelper> singleton = new Lazy<SalesHelper>(() => new SalesHelper());
public static SalesHelper Instance { get { return singleton.Value; } }
ICacheData<Sale> _cache;
List<Sale> CacheData = new List<Sale>();
public void SetCache(ICacheData<Sale> cacheData)
{
_cache = cacheData;
}
public void ReloadCache()
{
CacheData.Clear();
GetAllData();
}
public void GetAllData()
{
CacheData = _cache.GetAllData();
}
public List<Sale> GetDataFromImobDate(int idImob, DateTime date)
{
var result = (from r in CacheData
where r.Data_Alteracao.Equals(date)
&& r.Id_Imobiliaria.Equals(idImob)
select r).ToList();
return result;
}
}
and in the Service i start the ServiceHost and the cache
_tempSales = new SalesHelper();
ICacheData<Sale> _cacheSale = new Sale();
_tempSales.SetCache(_cacheSale);
_tempSales.GetAllData();
_service = new ServiceHost(typeof(CacheDataService));
A: I think your are missing the initialization of SalesHelper.Instance.
doing this new Lazy<SalesHelper>(() => new SalesHelper()); leads to get an intance of _cache not initialized.
So we have a couple of workaround to chose.
One of them is initilize the Intance:
SalesHelper.Instance.SetCache(_cacheSale);
It should look like this:
//_tempSales = new SalesHelper();
ICacheData<Sale> _cacheSale = new Sale();
//_tempSales.SetCache(_cacheSale);
//_tempSales.GetAllData();
SalesHelper.Instance.SetCache(_cacheSale);
SalesHelper.Instance.GetAllData(); //Now it should return the info
_service = new ServiceHost(typeof(CacheDataService));
The other one is replace your prop Intance with a factory method GetInstance() which should receive the cache and set it if it is needed.
Let me know if the first workaround solve your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41742093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Looking for an implementation of an abstract method I need to make a programm which is like a rally, theres 2 types of vehicles, motorcycle and cars, two types of motorcycle, with and without sidecar, the thing is that I need to verify if there is just a motorcycle in an array list, I mean, two wheels vehicle. That verification should be done in a method called esDe2Ruedas(), which is called by an abstract overrided method called check() that should be the one that verifies if a group of vehicles from an array are able to run in the rally, if its true all the elements of the array must be from the same type.
Here is the code
this is how the program arrays the vehicles
GrandPrix gp1 = new GrandPrix();
gp1.agregar(v1);
//gp1.mostrar(v1);
gp1.agregar(v2);
System.out.println(gp1.check());
GrandPrix gp2 = new GrandPrix();
gp2.agregar(vt1);
gp2.agregar(vt2);
gp2.agregar(m2);
System.out.println(gp2.check());
GrandPrix gp3 = new GrandPrix();
gp3.agregar(vt1);
gp3.agregar(vt2);
gp3.agregar(m1);
System.out.println(gp3.check());
GrandPrix gp4 = new GrandPrix();
gp4.agregar(m1);
gp4.agregar(m2);
System.out.println(gp4.check());
This is the class that is using
import java.util.ArrayList;
public class GrandPrix extends Rally{
ArrayList<Vehiculo> ve = new ArrayList<Vehiculo>();
public void agregar(Vehiculo v) {
ve.add(v);
}
public void agregar(Carro c) {
ve.add(c);
}
public void agregar(Moto m) {
ve.add(m);
}
@Override
boolean check() {// HERE I VERIFY IF THE VEHICLES ARE COMPATIBLE
return false;
}
}
This is the class where everything goes on
public class Vehiculo {
private String Nombre;
private double velocidad_max;
private int peso;
private int comb;
public Vehiculo() {
setNombre("Anónimo");
setVel(130);
setPeso(1000);
setComb(0);
}
public Vehiculo(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
}
double rendimiento() {
return velocidad_max/peso;
}
public boolean mejor(Vehiculo otroVehiculo) {
return rendimiento()>otroVehiculo.rendimiento();
}
public String toString() {
return getNombre()+"-> Velocidad máxima = "+getVel()+" km/h, Peso = "+getPeso()+" kg";
}
/**************************************
---------SET And GET Nombre------------
***************************************/
public String getNombre() {
return Nombre;
}
public void setNombre(String nuevoNombre) {
this.Nombre=nuevoNombre;
}
/**************************************
---------SET And GET velocidad_max------------
***************************************/
public double getVel() {
return velocidad_max;
}
public void setVel(double nuevaVel) {
this.velocidad_max=nuevaVel;
}
/**************************************
---------SET And GET peso------------
***************************************/
public double getPeso() {
return peso;
}
public void setPeso(int nuevoPeso) {
this.peso=nuevoPeso;
}
/**************************************
---------SET And GET comb------------
***************************************/
public int getComb() {
return comb;
}
public void setComb(int comb) {
this.comb = comb;
}
boolean esDe2Ruedas() {
return false;
}
}
This is the class of motorcycles, which is in theory the same as the car's class, without sidecar thing
public class Moto extends Vehiculo{
private boolean sidecar;
public Moto(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(false);
}
public Moto(String string, double d, int i, int j, boolean b) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(b);
esDe2Ruedas(false);
}
public String toString() {
String str = null;
if(isSidecar())
str =super.toString()+", Moto, con sidecar";
else
str =super.toString()+", Moto";
return str;
}
public boolean isSidecar() {
return sidecar;
}
public void setSidecar(boolean sidecar) {
this.sidecar = sidecar;
}
A: I guess what you presented is what is given. If you came up with the design it is ok, but I believe it could be improved. Anyway, I try to respond to what I believe was your question straight away.
Vehiculo is the super type of Moto (which can have a side car and becomes 3 wheeler).
Vehiculo has a method esDe2Ruedas, which returns false.
Moto inherits that method <-- this is wrong, it should override it and, depending on side car, return the expected boolean value.
In the check method you can now distinguish between Moto and "Moto with sidecar" by using that method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68784371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Section Item : Get Section Name on Tap of Item Trying to get Name of Section, when I do tap on any of the Item of that particular Section.
I am following this tutorials, where my UI data is divided into two parts: Section and Item(s)
Now for my knowledge I would like to see the name of Section (once I do tap on any of the Item)
For an example, I have 5 sections, where each of the section contains 5 Items itself and Let assume I have tapped on 4th Item of the Section 2nd
So How Do I know that, as you can see I am getting name of tapped Item, but on Tap I also want to get name of Section (which Item I just tapped) ?
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
....
public SingleItemRowHolder(View view) {
super(view);
.....
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
A: After seeing the link you provided, you simply need to pass and store the section name in SectionListAdapter as below:
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SingleItemModel> itemsList;
private Context mContext;
private String mSectionName;
public SectionListDataAdapter(Context context, String sectionName, ArrayList<SingleItemModel> itemsList) {
mSectionName = sectionName;
this.itemsList = itemsList;
this.mContext = context;
}
@Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
@Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModel singleItem = itemsList.get(i);
holder.tvTitle.setText(singleItem.getName());
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
}
@Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView tvTitle;
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.itemImage);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), mSectionName +" : "+ tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Now in your RecyclerViewDataAdapter simply change the one line of initializing SectionListDataAdapter inside your onBindViewHolder as below:
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {
private ArrayList<SectionDataModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<SectionDataModel> dataList) {
this.dataList = dataList;
this.mContext = context;
}
@Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
@Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String sectionName = dataList.get(i).getHeaderTitle();
ArrayList singleSectionItems = dataList.get(i).getAllItemsInSection();
itemRowHolder.itemTitle.setText(sectionName);
SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, sectionName, singleSectionItems);
itemRowHolder.recycler_view_list.setHasFixedSize(true);
itemRowHolder.recycler_view_list.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.recycler_view_list.setAdapter(itemListDataAdapter);
itemRowHolder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "click event on more, "+sectionName , Toast.LENGTH_SHORT).show();
}
});
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
}
@Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle;
protected RecyclerView recycler_view_list;
protected Button btnMore;
public ItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView) view.findViewById(R.id.itemTitle);
this.recycler_view_list = (RecyclerView) view.findViewById(R.id.recycler_view_list);
this.btnMore= (Button) view.findViewById(R.id.btnMore);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43719398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Excel VBA: error in setting value using find function I'm a fairly inexperienced coder and have a small piece of code that is just falling over each time I run it (although I would swear it worked once and has since stopped!)
I am trying to find a value from a cell (which has a formulas to determine which value I need to find) in a range of cells elsewhere in the spreadsheet.
Originally my code was set as follows (when I think it worked) and I am getting an error message saying "Compile error: object required"
I tried to add the word Set in the appropriate place to stop that but then I get a runtime error 91 message saying object variable or with block variable not set.
My sub is in a class module set as option explicit and the code is as follows;
Dim StartRow As Integer
Dim EndRow As Integer
Set StartRow = Sheets("CHARTS").Range("T2:T9").Find(What:=Sheets("CHARTS").Range("O14").Value, LookIn:=xlValues, Lookat:=xlWhole).row
Set EndRow = Sheets("CHARTS").Range("T2:T9").Find(What:=Sheets("CHARTS").Range("O13").Value, LookIn:=xlValues, Lookat:=xlWhole).row
Any help gratefully received, I just can't see where I've gone wrong...!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46689059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Probability of an event in R I've the following data frame:
and I need to evaluate the probability that a student is a "M", i. e. P("M") equal to the ratio between the number of the "M" and the number of studenti. I did it in this way:
nStudenti <- length(studenti$sesso)
tabellaSesso <- table(studenti$sesso)
nMaschi <- tabellaSesso[names(tabellaSesso) == "M"]
P = nMaschi / nStudenti
Is this the shortest way or there are commands which simply the things?
A: You can use table() to get the absolute frequencies and then use prop.table() to get the probabilities. If you are only interested in a specific value like "M", you can just index that value.
# sample data
studenti <- data.frame(sesso = sample(c("M", "F", NA), 100, replace = TRUE))
# all probabilties
prop.table(table(studenti$sesso))
#>
#> F M
#> 0.530303 0.469697
# specfic probability
prop.table(table(studenti$sesso))["M"]
#> M
#> 0.469697
Created on 2021-10-06 by the reprex package (v2.0.1)
A: You could create a function
#Function
propCond=function(VAR,MODALITY){
PROP=sum(VAR==MODALITY,na.rm=TRUE)/sum(!is.na(VAR),na.rm=TRUE)
return(PROP)
}
#Result
propCond(c("a","a","b"),"a")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69467782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VuePress not hot reloading, but does when config.js is changed I'm using VuePress for the first time, and updating .md files isn't triggering live reloading.
If I update the .vuepress/config.js my browser does reload. If I run:
vuepress dev --debug
I see this line in the output, which seems suspicious:
debug watchFiles [
'.vuepress/config.js',
'.vuepress/config.yml',
'.vuepress/config.toml'
]
Is this the error, or is this correct? Googling vuepress watchfiles doesn't show anything particularly useful.
A: There is an issue discussed in the repository, which hints at a possible problem cause.
A broken connection error may be fixed with hard-refreshing the page. Modifying the templates and the content pages reloads after that.
Check the browser console to see what the actual issue is.
Some actions require manual restart. For example, renaming the template files or adding components will cause an error. Changing the config file also does not trigger the reload.
A: Add the following to config.js
module.exports = {
host: 'localhost',
...
A: just delete the those folders and run again.
.vuepress/.cache
.vuepress/.temp
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61984454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: After recreating BigQuery table streaming inserts are not working? I just came a cross an interesting issue with the BigQuery.
Essentially there is a batch job that recreates a table in BigQuery - to delete the data - and than immediately starts to feed in a new set through streaming interface.
Used to work like this for quite a while - successfully.
Lately it started to loose data.
A small test case has confirmed the situation – if the data feed starts immediately after recreating (successfully!) the table, parts of the dataset will be lost.
I.e. Out of 4000 records that are being fed in, only 2100 - 3500 would make it through.
I suspect that table creation might be returning success before the table operations (deletion and creation) have been successfully propagated throughout the environment, thus the first parts of the dataset are being fed to the old replicas of the table (speculating here).
To confirm this I have put a timeout between the table creation and starting the data feed. Indeed, if the timeout is less than 120 seconds – parts of the dataset are lost.
If it is more than 120 seconds - seems to work OK.
There used to be no requirement for this timeout. We are using US BigQuery.
Am I missing something obvious here?
EDIT: From the comment provided by Sean Chen below and a few other sources - the behaviour is expected due to the way the tables are cached and internal table id is propagated through out the system. BigQuery has been built for append-only type of operations. Re-writes is not something that one can easily accomodate into the design and should be avoided.
A: This is more or less expected due to the way that BigQuery streaming servers cache the table generation id (an internal name for the table).
Can you provide more information about the use case? It seems strange to delete the table then to write to the same table again.
One workaround could be to truncate the table, instead of deleting the it. You can do this by running SELECT * FROM <table> LIMIT 0, and the table as a destination table (you might want to use allow_large_results = true and disable flattening, which will help if you have nested data), then using write_disposition=WRITE_TRUNCATE. This will empty out the table but preserve the schema. Then any rows streamed afterwards will get applied to the same table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36415265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Submit form from Backend in contact form 7 I need help I R & D many contact form plugin's but not found any one working
My requirements are I want contact form to be submitted by Front end as well as backend
[contact-form-7 id="345"]
If I used this above shortcode in backend it display error
Please Help
Is their any way to add new tab on contact form 7 plugin and submit contact form 7 from admin dashboard
Thank You For Help In advance
A: First of all insert a contact form shortcode into your template file directly. You will need to pass the code into do_shortcode() function.
For Example:
<?php echo do_shortcode('[contact-form-7 id="345"]'); ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49002499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Extract an increasing subsequence I wish to extract an increasing subsequence of a vector, starting from the first element. For example, from this vector:
a = c(2, 5, 4, 0, 1, 6, 8, 7)
...I'd like to return:
res = c(2, 5, 6, 8).
I thought I could use a loop, but I want to avoid it. Another attempt with sort:
a = c(2, 5, 4, 0, 1, 6, 8, 7)
ind = sort(a, index.return = TRUE)$ix
mat = (t(matrix(ind))[rep(1, length(ind)), ] - matrix(ind)[ , rep(1, length(ind))])
mat = ((mat*upper.tri(mat)) > 0) %*% rep(1, length(ind)) == (c(length(ind):1) - 1)
a[ind][mat]
Basically I sort the input vector and check if the indices verify the condition "no indices at the right hand side are lower" which means that there were no greater values beforehand.
But it seems a bit complicated and I wonder if there are easier/quicker solutions, or a pre-built function in R.
Thanks
A: One possibility would be to find the cumulative maxima of the vector, and then extract unique elements:
unique(cummax(a))
# [1] 2 5 6 8
A: The other answer is better, but i made this iterative function which works as well. It works by making all consecutive differences > 0
increasing <- function (input_vec) {
while(!all(diff(input_vec) > 0)){
input_vec <- input_vec[c(1,diff(input_vec))>0]
}
input_vec
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30750687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Getting object from array of objects matching values inside and array of dates with lodash i have an array of obejcts that has this structure
let events = [ {
"initDate": "2019-11-20",
"finalDate": "2019-11-22",
"intermediateDates": [
"2019-11-20",
"2019-11-21"
],
"priority": 1
},....]
So, i'm trying to get the object that matches from a given array of dates for example :
let filteredDays = [
"2019-11-20",
"2019-11-21",
"2019-11-22"
]
i'm trying with lodash like this:
let eventsFound= [];
let intersection = _.map( this.events,function(value){
let inter = _.intersection(value.intermediateDates,filteredDates);
console.log(inter);
if(inter != []){
foundEvents.push(value);
return value;
}else{
return false;
}
});
when i console log inter i get the first array with values then the next arrays are empty but it keeps pushing all the events into the foundEvents Array and the returned array is the same as the events array.
A: *
*You're comparing two arrays using !=. In javascript [] != [] is always true. To check if an array is empty, use length property like arr.length == 0.
*Use filter instead of using map like a forEach.
*To check existance use some/includes combo instead of looking for intersections.
So, filter events that some of its intermediateDates are included in filteredDates:
let eventsFound = _.filter(this.events, event =>
_.some(event.intermediateDates, date =>
_.includes(filteredDates, date)
)
);
The same using native functions:
let eventsFound = this.events.filter(event =>
event.intermediateDates.some(date =>
filteredDates.includes(date)
)
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58739642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Memory leak while using C# dll in a C++ The situation is, I wrapped C# dll to use it in a C++ project and when I execute C++ project I can't see any sign about memory leak but the memory increases little by little. I think it's because the GC in C# library doesn't work in C++ project and I don't know how to solve it. Please help me.
My code is below:
*
*C#
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace CSharpLib
{
[Guid("8EA9EAA8-CA3D-4584-B1E0-7B9561757CA4")]
public interface ICSharpLibrary
{
int[] GetData();
string GetName();
bool Init();
}
[Guid("B62A2B51-621D-41AA-8F4F-021E404B593C")]
public class CSharpLibrary : ICSharpLibrary, IDisposable
{
private bool disposed = false;
private int[] data;
private string name = "CSharpLib";
private SafeHandle safeHandle = new SafeFileHandle(IntPtr.Zero, true);
private void MakeData()
{
var list = new List<int>();
var rnd = new Random();
for(var i = 0; i < 1000; i++)
{
list.Add(rnd.Next(0, 255));
}
data = list.ToArray();
}
public int[] GetData()
{
MakeData();
return data;
}
public string GetName()
{
return name;
}
public bool Init()
{
data = null;
return true;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
data = null;
safeHandle.Dispose();
}
disposed = true;
}
}
}
*C++
#pragma once
#ifdef CPLUSLIBRARY_EXPORTS
#define CPLUSLIBRARY_API __declspec(dllexport)
#else
#define CPLUSLIBRARY_API __declspec(dllimport)
#endif
extern "C" CPLUSLIBRARY_API bool Init();
extern "C" CPLUSLIBRARY_API int* GetData();
extern "C" CPLUSLIBRARY_API char* GetName();
#include <Windows.h>
#include "pch.h"
#include "CPlusLibrary.h"
#import "lib/CSharpLibrary.tlb" no_namespace named_guids
ICSharpLibrary* lib = NULL;
int* data = NULL;
bool isWorking = false;
char* name = NULL;
bool Init() {
HRESULT hr = CoInitializeEx(NULL, tagCOINIT::COINIT_MULTITHREADED);
if (!SUCCEEDED(hr))
return false;
hr = CoCreateInstance(CLSID_CSharpLibrary, NULL, CLSCTX_INPROC_SERVER, IID_ICSharpLibrary, reinterpret_cast<void**>(&lib));
if (!SUCCEEDED(hr))
return false;
return true;
}
int* GetData() {
auto raw = lib->GetData();
void* pVoid = NULL;
HRESULT hr = ::SafeArrayAccessData(raw, &pVoid);
if (!SUCCEEDED(hr))
return NULL;
auto result = reinterpret_cast<int*>(pVoid);
return result;
}
char* GetName() {
char str[10];
strcpy_s(str, lib->GetName());
name = str;
return name;
}
*executor
#include <iostream>
#include <CPlusLibrary.h>
#include <CoreWindow.h>
int main()
{
if (!Init())
return 0;
while (true) {
auto name = GetName();
std::cout << name << std::endl;
auto data = GetData();
for (int i = 0; i < 1000; i++) {
std::cout << data[i];
}
std::cout << std::endl;
Sleep(100);
}
}
A: From SafeArrayAccessData documentation
After calling SafeArrayAccessData, you must call the SafeArrayUnaccessData function to unlock the array.
Not sure this is the actual reason for the leak. But when debugging problems, a good first step is to ensure you are following all the rules specified in the documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65733134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: B2C - Sign in with Google account not showing We are in the process of setting Google OAuth to Azure B2C. What are the values to pass for client id and client secret when adding Google as identity provider. See this image: Configure Google as Identity Provider
When users run, sign up and sign in user flow, they are not getting the Sign in with Google option. How to get this?
A: To get the values of Client ID and Client secret, you need to create one Google application as mentioned in below reference.
I tried to reproduce the same in my environment and got below results:
I created one Google application by following same steps in that document and got the values of Client ID and Client secret like this:
Go to Google Developers Console -> Your Project -> Credentials -> Select your Web application
I configured Google as an identity provider by entering above client ID and secret in my Azure AD B2C tenant like below:
Make sure to add Google as Identity provider in your Sign up and sign in user flow as below:
When I ran the user flow, I got the login screen with Google like below:
After selecting Google, I got consent screen as below:
I logged in successfully with Google account like below:
Reference:
Set up sign-up and sign-in with a Google account - Azure AD B2C
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74631238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Close woocomerce frontend and only keep the backend What I'm trying to do:
*
*Only vendors can submit their products.
*They can't see other vendors
products.
I will open the front end of the website when there is enough products submitted.
My question is; Is there any way that I can close the front end of woocomerce website and only keep the back end?
Or any other idea to solve this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61430130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to wait for AJAX requests to complete in JQuery? I have 4 different JQuery AJAX functions, each fetching different information from the last.fm API. This info has to be joined together in a tooltip.
These are my 4 functions:
*
*Gets the album for a given track & artist. Returns track name.
*Gets the artist image. Returns 1 URL.
*Gets the top 3 albums of the artist. Returns array of 3 strings.
*Gets the #1 top track of a given artist. Returns track name.
var getTrackAlbum = function(track, artist) {
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "track.getInfo",
api_key : settings.LASTFM_APIKEY,
track : track,
artist : artist,
format : "json"
},
function(data) {
return data.track.album.title;
});
}
var getArtistImage = function(artist) {
var options = {
artSize: 'medium',
noart: 'images/noartwork.gif',
}
if(options.artSize == 'small'){imgSize = 0}
if(options.artSize == 'medium'){imgSize = 1}
if(options.artSize == 'large'){imgSize = 2}
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "artist.getInfo",
api_key : settings.LASTFM_APIKEY,
artist : artist,
format : "json"
},
function(data) {
return stripslashes(data.artist.image[imgSize]['#text']);
});
}
var getArtistTopAlbums = function(artist) {
var albums = new Array();
var onComplete = function() {
return albums;
}
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "artist.getTopAlbums",
api_key : settings.LASTFM_APIKEY,
artist : artist,
format : "json"
},
function(data) {
$.each(data.topalbums.album, function(i, item){
albums[i] = item.name;
if(i == 2) {
onComplete.call(this);
return;
}
});
});
}
var getArtistTopTrack = function(artist) {
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "artist.getTopTracks",
api_key : settings.LASTFM_APIKEY,
artist : artist,
format : "json"
},
function(data) {
return data.toptracks.track[0].name;
});
}
I have decided against doing all the requests inside a unique method for reuse purposes. However, now I want to wait for ALL the AJAX requests to complete before I set the HTML of my tooltip.
Here's the code of my tooltip:
$('.lfm_info').on('mouseover', function(){
var toolTip = $(this).children('.tooltip');
var trackhtml = $(this).parent().children('.lfm_song').html().split(".");
var track = trackhtml[1].trim();
var artist = $(this).parent().children('.lfm_artist').html();
// needs to wait until the AJAX is done!
toolTip.html('html here');
$('#tracks').mouseleave(function(){
if(toolTip.is(':visible')){
toolTip.fadeOut(500);
};
});
toolTip.fadeIn(500);
});
}
How would I wait for all requests to complete before invoking toolTip.html(...)?
A: Store each request, then use $.when to create a single deferred object to listen for them all to be complete.
var req1 = $.ajax({...});
var req2 = $.ajax({...});
var req3 = $.ajax({...});
$.when( req1, req2, req3 ).done(function(){
console.log("all done")
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13018972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Loop through SQL query result and compare against table values? I have a table (Client_Programs) which contains a list of clients and a government program they're enrolled in. Each client is identified by a unique ClientULink and programs have a ProgramULink. Each entry contains a StartDate and EndDate. So the data may look like this:
ClientULink ProgramULink StartDate EndDate
b0afd171-28d0-48a3-989f-f2b0583c0fxx 46dcdf26-4916-4966-ac81-eaf57c7a26xx 2/2/2017 6:00:00 AM 5/2/2017 6:00:00 AM
A client can be in this table multiple times for the same (or different) programs. I'm being asked to create a query (report) of any client that has NOT re-enrolled into a program. My thinking is to initially start off by running a query to return entries from the Client_Program table between two EndDates (which would be an input parameter in my final stored procedure for this report). For example:
SELECT ClientULink, ProgramULink, StartDate, EndDate FROM Client_Program cp WHERE cast(cp.EndDate as date) BETWEEN '2017-05-01' AND '2017-05-30'
However, I would like to place these into a temp table or memory so that I can then loop through them and check all of these results against the main Client_Program table to see if these clients have any "newer" entries that shows they are re-enrolled or not.
SELECT ClientULink, ProgramULink, StartDate, EndDate FROM Client_Program cp WHERE ClientULink = 'b0afd171-28d0-48a3-989f-f2b0583c0fxx' AND cp.ProgramULink = '46dcdf26-4916-4966-ac81-eaf57c7a26xx' AND CAST(cp.StartDate as DATE) > '2017-05-30'
My question is how do I loop through my first results query? Basically, I'm trying to find any client who has not re-enrolled (doesn't have an entry with a newer StartDate for a program - or specific program as shown in my query) than the EndDate range specified.
Any help in showing this in a stored procedure or query would be very much appreciated and helpful. Thank you for your time!
A: You could use a cursor to do loops, but that is a poorly performaning option compared to a set based operation.
Using not exists() to return all clients in programs that ended in May, that have not re-enrolled:
select
ClientULink
, ProgramULink
, StartDate
, EndDate
from Client_Program cp
where cp.EndDate >= '20170501'
and cp.EndDate < '20170601'
and not exists (
select 1
from Client_Program i
where i.ClientULink = cp.ClientULink
and i.ProgramULink = cp.ProgramULink
and i.StartDate >= cp.EndDate
)
Notes:
*
*Bad habits to kick : mis-handling date / range queries - Aaron Bertrand
*What do between and the devil have in common? - Aaron Bertrand
*Should I use not in(), outer apply(), left outer join, except, or not exists()? - Aaron Bertrand
*The only truly safe formats for date/time literals in SQL Server, at least for datetime and smalldatetime, are: YYYYMMDD and YYYY-MM-DDThh:mm:ss[.nnn] - Bad habits to kick : mis-handling date / range queries - Aaron Bertrand
test setup:
create table Client_Program (ClientULink uniqueidentifier, ProgramULink uniqueidentifier, StartDate datetime, EndDate datetime)
insert into Client_Program values
('00000000-0000-0000-0000-000000000000','00000000-0000-0000-0000-000000000000','2017-02-02T06:00:00','2017-05-02T06:00:00')
,('11111111-1111-1111-1111-111111111111','11111111-1111-1111-1111-111111111111','2017-02-02T06:00:00','2017-05-02T06:00:00')
,('11111111-1111-1111-1111-111111111111','11111111-1111-1111-1111-111111111111','2017-05-02T06:00:00','2017-08-02T06:00:00')
select
ClientULink
, ProgramULink
, StartDate = convert(char(10),StartDate,120)
, EndDate = convert(char(10),EndDate,120)
from Client_Program cp
where cp.EndDate >= '20170501'
and cp.EndDate < '20170601'
and not exists (
select 1
from Client_Program i
where i.ClientULink = cp.ClientULink
and i.ProgramULink = cp.ProgramULink
and i.StartDate >= cp.EndDate
)
rextester demo: http://rextester.com/LYE54567
returns:
+--------------------------------------+--------------------------------------+------------+------------+
| ClientULink | ProgramULink | StartDate | EndDate |
+--------------------------------------+--------------------------------------+------------+------------+
| 00000000-0000-0000-0000-000000000000 | 00000000-0000-0000-0000-000000000000 | 2017-02-02 | 2017-05-02 |
+--------------------------------------+--------------------------------------+------------+------------+
You could also use aggregation and filter in the having clause where max(EndDate) is between some date range (If they re-enrolled, then their max(EndDate) would not be in the date range):
select
ClientULink
, ProgramULink
from Client_Program cp
group by
ClientULink
, ProgramULink
having max(EndDate)>= '20170501'
and max(EndDate) < '20170601'
returns:
+--------------------------------------+--------------------------------------+
| ClientULink | ProgramULink |
+--------------------------------------+--------------------------------------+
| 00000000-0000-0000-0000-000000000000 | 00000000-0000-0000-0000-000000000000 |
+--------------------------------------+--------------------------------------+
A: In general, if you are looping in SQL, you're probably doing it wrong. You can use EXCEPT to achieve this.
SELECT ClientULink
FROM Client_Program
WHERE CAST(EndDate as date) BETWEEN '2017-05-01' AND '2017-05-30'
EXCEPT
SELECT ClientULink
FROM Client_Program
WHERE CAST(StartDate as date) > '2017-05-01'
Edit: If a client Starts and Ends within the DateRange they will be wrongly excluded from the result.
A: Are you certain you are not over-thinking this? Not re-enrolled appears to be the set of IDs (client, program) that have a count of 1. E.g.,
select cp.ClientULink, cp.ProgramULink from dbo.Client_Program as cp
group by cp.ClientULink, cp.ProgramULink
having count(*) = 1
order by cp.ClientULink, cp.ProgramULink ;
What else do you need?
A: If you need the date filter, try something like this:
select ClientULink, ProgramULink, StartDate, EndDate
from Client_Program cp
inner join
(
select ClientULink, ProgramULink, count(*) as Count
from Client_Program cp2
group by ClientULink, ProgramULink
having count(*) = 1
) cp2
on cp.ClientULink = cp2.ClientULink
and cp.ProgramULink = cp2.ProgramULink
where cast(cp.EndDate as date) between '2017-05-01' and '2017-05-30'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44271029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Which function will execute the quickest? i want to know which function will execute the fastest for my project.
Which function will be the best for DB ..
Also is there another method to accomplish the same task?
void function1 ()
{
operation ;
loop ()
{
method insertInDB ( string ) ;
}
}
void insertInDB ()
{
open connection ;
insert;
close ;
}
OR
void function2 ()
{
operation ;
loop ()
{
string [];
}
method insertInDB (array []);
}
void insertInDB ()
{
open connection ;
loop ()
{
insert;
}
close ;
}
A: 2nd. Because you will only open your BD connection one time to insert your data and close. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34495068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Having issues with Crystal Reports not reflecting changes from SQL DB I'm kinda new to creating reports with Crystal Reports on Visual Studio 2017.
I've created a report on VS2017 called PersonnelListingReport.rpt using the setup wizard. Through the wizard I've selected the table for which the report will be based on. Also, I added a filter parameter that will display only the Employees who are active i.e(Active = 1, Inactive = 0). So now in my Main Report Preview window I can see all of the employees with Status = 1. My issue is that when I Add or Delete an item on my GridView, the change does not reflect on my report. Here's what I have in my Page_Load:
Public Class PersonnelListingReportViewer
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim crystalReport As New ReportDocument()
crystalReport.Load(Server.MapPath("PersonnelListingReport.rpt"))
CrystalReportViewer1.ReportSource = crystalReport
End Sub
Here's what I have under my aspx for ReportViewer:
body>
<form id="form1" runat="server">
<div>
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="True" GroupTreeImagesFolderUrl="" Height="1202px" ReportSourceID="CrystalReportSource1" ToolbarImagesFolderUrl="" ToolPanelWidth="200px" Width="1104px" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
<Report FileName="PersonnelListingReport.rpt">
</Report>
</CR:CrystalReportSource>
</div>
</form>
Is there something I am missing in my code? I've tried using Refresh() and Load() as per forum posts with similar issues but to no avail. Ive also read a forum post about creating a Page_Unload then have the report call the Close() and then Dispose() but also to no avail. Ive tried checking the checkbox to Discard Saved Data When Loading Reports but still nothing. I know I'm missing something but not quite sure as this is my first time using Crystal Reports on Visual Studio 2017. Thank guys!
A: Thanks guys for the advice. I was able to resolve the issue by adding this to my Page_Load:
Dim cryRpt As New ReportDocument
Dim crtableLogoninfos As New TableLogOnInfos
Dim crtableLogoninfo As New TableLogOnInfo
Dim crConnectionInfo As New ConnectionInfo
Dim CrTables As Tables
Dim CrTable As Table
cryRpt.Load(Server.MapPath("PersonnelListingReport.rpt"))
With crConnectionInfo
.ServerName = "0.0.0.0"
.DatabaseName = "TestDB"
.UserID = "user"
.Password = "pw"
End With
CrTables = cryRpt.Database.Tables
For Each CrTable In CrTables
crtableLogoninfo = CrTable.LogOnInfo
crtableLogoninfo.ConnectionInfo = crConnectionInfo
CrTable.ApplyLogOnInfo(crtableLogoninfo)
Next
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.RefreshReport()
A: Create a class for setting the Logon values for the Crystal report with a function getreport() which returns a reportdocument of a crystal report in a given report location
Module Logonvalues
Function getpeport(ByVal ReportLocation As String) As ReportDocument
Dim crconnectioninfo As ConnectionInfo = New ConnectionInfo()
Dim cryrpt As ReportDocument = New ReportDocument()
Dim crtablelogoninfos As TableLogOnInfos = New TableLogOnInfos()
Dim crtablelogoninfo As TableLogOnInfo = New TableLogOnInfo()
Dim CrTables As Tables
cryrpt.Load(ReportLocation)
cryrpt.DataSourceConnections.Clear()
crconnectioninfo.ServerName = "ur servername"
crconnectioninfo.DatabaseName = "ur database"
crconnectioninfo.UserID = "ur database username"
crconnectioninfo.Password = "ur database password"
CrTables = cryrpt.Database.Tables
For Each CrTable As CrystalDecisions.CrystalReports.Engine.Table In CrTables
crtablelogoninfo = CrTable.LogOnInfo
crtablelogoninfo.ConnectionInfo = crconnectioninfo
CrTable.ApplyLogOnInfo(crtablelogoninfo)
Next
Return cryrpt
End Function
End Module
Finally we will call the logon value from the form consisting of the crystal reportviewer
Public Sub loadreport()
Crvt_ApplicationReport.ReportSource = Logonvalues.getpeport("yourlocation")
Crvt_ApplicationReport.SelectionFormula = "yourformula if any"
Crvt_ApplicationReport.RefreshReport()
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54859287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.