text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Composer debug dependencies I should figure out, how to debug such situations?
I try to send mail throw Mailgun package.
How to figure out why the class is not found? Error: Class 'Mailgun\Messages\MessageBuilder' not found in /vendor/boundstate/yii2-mailgun/Message.php:239
but IDE shows me that class exist in package mailgun/mailgun-php
Take a look on a slice of composer.json:
"boundstate/yii2-mailgun": "0.0.4",
"Mailgun/Mailgun-php": "^1.0",
ADD:
I have required autoload.php Also, composer use psr4. I see the correct path to classes. Take a look:
'boundstate\\mailgun\\' => array($vendorDir . '/boundstate/yii2-mailgun'),
'Mailgun\\' => array($vendorDir . '/mailgun/mailgun-php/src'),
A: Usually, such things happen when you didn't require vendor/autoload.php, or autoload wasn't generated. IDE may show you that everything is OK just because it parsed your composer.json.
Try to:
*
*composer update
*get sure you required vendor/autoload.php in your script
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62831244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Handling date from list of times I have a list of time.
time_list = ['7pm', '8pm', '9pm', '10pm', '11pm', '12am', '1am', '2am']
and from there a list of floats as well
fl_list = ['1.0', '0.0', '0.0', '0.0', '0.0', '0.0', '11', '12.0']
Upon inserting in the database,
I set the date of time 7pm-12am to date today, and 1am-2am to date tomorrow.
date_today = datetime.datetime.utcnow()
date_tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
My code is like this:
has_tomorrow_record = all(any(x in y for y in time_list) for x in ["12am", "1am"])
then to get the date I have to do the below condition
for t in time_list:
if has_tomorrow_record and "am" in t:
if t != "12am":
date = date_tomorrow
Is there a cleaner way to determine the dates for the time_list?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56635876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Include of non-modular header inside framework module 'AppLovinSDK' - Archive only error I get this error only when I try to archive, building for simulator or other test device works. Previously, I had this problem when trying to build for a test device, but I started over and reinstalled the pod and it worked. I have tried setting 'Allow non-modular Includes in Frameworks' to yes in both my project and Target, but this has NOT worked. Any ideas on how to get out of this would be greatly appreciated!
A: I got the same error (for archiving only) for my Swift framework with C code inside.
Only this remedy helped me.
Add -Xcc -Wno-error=non-modular-include-in-framework-module in Other Swift Flags (build settings of framework). This flag forces the compiller count that error as a warning.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54878219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Invalid label in mozilla firefox I've a JSP page like this with name test.jsp
<%@ page language="java" contentType="text/json; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
response.setContentType("application/x-javascript");
%>
{"feed": "test"}
and an html page where i use jquery for reading the json object.
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
$.getJSON("localhost:8080/test.jsp?callback=?",{test:"test"}, function(data){alert("here");});
})
</script>
</head>
</body>
something here
</body>
</html>
but it shows an error as invalid label in firefox. Can anyone explain me the reason for this error.
I've tried google but could not find a solution or explanation to my problem. What needs do be done for this. Please help me out.
Thanks
A: I've found the solution to the problem by some hit & trial.
It is because when we make getJSON() call on cross domain then response should be wrapped inside a function name. This function is our callback handler for the response in the script.eg
html file :
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
$.getJSON("localhost:8080/test.jsp?callback=?");
}
function test(data){
alert(data.feed);
}
And the jsp test.jsp
<%@ page language="java" contentType="text/json; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
response.setContentType("application/x-javascript");
out.write("test({\"feed\": \"test\"})");
%>
hope if anybody has the same problemm this will help.you can pass the callback function name as a parameter and make jsp at the server such that it uses that name to wrap the response.
A: I have encountered the same issue which was actually because of the some issue with json or ajax call. In your json call it should be {"test":"test"} instead of {test:"test"}.
Try it should work if this is the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3786894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Importing Json field from csv to MySQL 5.7.19-0ubuntu0.16.04.1 I have MySQL table consisting of 3 columns having type of (cookie vachar, userdata json, userprefernce json). I am trying to load the data from csv but it gives the following error :
Error:
Error Code: 3140 Invalid JSON text: Invalid value at position 0 in value for column userdata'
I have tried to validate the JSON it looks fine. Now I couldn't understand what is the problem
Sample Row:
ZwpBHCrWObHE61rSOpp9dkUfJ, '{"bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}, "models": {"Grand Cherokee": 1, "XC90": 1}}', '{"bodystyle": "SUV/MUV", "budgetsegment": "EP", "models": "Grand Cherokee,XC90"}'
A: I can't reproduce the problem:
File: /path/to/file/data.csv
ZwpBHCrWObHE61rSOpp9dkUfJ, '{"bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}, "models": {"Grand Cherokee": 1, "XC90": 1}}', '{"bodystyle": "SUV/MUV", "budgetsegment": "EP", "models": "Grand Cherokee,XC90"}'
MySQL Command Line:
mysql> \! lsb_release --description
Description: Ubuntu 16.04.2 LTS
mysql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.7.19 |
+-----------+
1 row in set (0.00 sec)
mysql> DROP TABLE IF EXISTS `table`;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `table` (
-> `cookie` VARCHAR(25) NOT NULL,
-> `userdata` JSON NOT NULL,
-> `userprefernce` JSON NOT NULL
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> LOAD DATA LOCAL INFILE '/path/to/file/data.csv'
-> INTO TABLE `table`
-> FIELDS TERMINATED BY ', '
-> OPTIONALLY ENCLOSED BY '\''
-> LINES TERMINATED BY '\n';
Query OK, 1 row affected (0.00 sec)
Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
mysql> SELECT
-> `cookie`,
-> `userdata`,
-> `userprefernce`
-> FROM
-> `table`\G
*************************** 1. row ***************************
cookie: ZwpBHCrWObHE61rSOpp9dkUfJ
userdata: {"models": {"XC90": 1, "Grand Cherokee": 1}, "bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}}
userprefernce: {"models": "Grand Cherokee,XC90", "bodystyle": "SUV/MUV", "budgetsegment": "EP"}
1 row in set (0.00 sec)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45606258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Makefile and Shell Script (Bash) What is the relationship between Makefile and Bash?
Example in Makefile you have:
CC = gcc
But if you type this in the shell, you get error:
~# CC = gcc
-bash: CC: command not found
Understandably, because there are spaces. But it works in Makefile.
Also, in Makefile you use command substitution $()
$(CC) $(LDFLAGS) -o $@ $(OBJS) $(LIBS)
which should be variable substitution $CC or ${CC} in bash.
So Makefile syntax and bash syntax are different, but they do seem related, for example $@.
A: There's no relationship - make and bash are two separate programs that parse distinct syntaxes. That they have similar or overlapping syntactic elements is likely due to having been developed around the same time and for some similar purposes, but they don't rely on the same parser or grammar.
Many distinct languages have shared language features either for ease of adoption or from imitation. Most languages use + to mean addition, for example, but that doesn't make the languages related.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38046550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python: run python script as subprocess and get the output I have a python script calculate.py with a function in it like below
def mytest():
Y_pred = {}
Y_pred['a'] = [1,2,3]
Y_pred['b'] = [45,54,77]
return Y_pred
Now from python console I want to run the python script using subprocess and get the return value `Y_pred' into a variable. So I want something like the pseudocode below from the terminal
python3
>>> import subprocess
>>> returned_val = subprocess.call([run calculate.py here and call mytest() ])
In the end, I want the returned value of mytest() to a variable returned_val.
A: You need to do a few things.
First, in calculate.py call the mytest function, add the following at the end:
if __name__ == '__main__':
print(mytest())
Now when you execute the calculate.py script (e.g. with python3 /path/to/calculate.py), you'll get the mytest's return value as output.
Okay, now you can use subprocess.check_output to execute the script, and get output:
returned_bin = subprocess.check_output('/usr/bin/python3 /path/to/calculate.py'.split())
Replace the paths accordingly.
The value of returned_val would be binary string. You need to decode it to get the respective text string:
returned_val = returned_bin.decode('utf-8') # assuming utf-8
Now, as the returned value from myfunc is a dict and in returned_val is a string,
you can use json.loads(returned_val) to get the same dict representation back.
A: subprocess.check_output
import subprocess
[ print(i) for i in subprocess.check_output(['ls']).split() ]
output, my current directory:
b'a.sh'
b'app'
b'db'
b'old.sh'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48875596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get all edges of a cuboid (3D NumPy array) Having a 3-dimensional numpy array A I want to get all the edges (imagine this array as a cuboid).
Well, A[0, 0, :] would give me one edge, A[0, -1, :] second one and A[:, -1, -1] yet another one... so all I'd have to do is get all permutations of 0, -1 and : and use them as indices. Zero and minus one are easy, but how would I do this with colon?
I can solve it the long way, but it's ugly and I bet there is some neat numpy solution to this. Something like:
for indices in permutations([0, -1, ':']):
edge = A[indices]
...
What I want to do in the end is numpy.any() on the set of all edges to see if all edge-values are zero.
A: : is same as slice(None, None, None)
A[0, -1, :] is same as
obj = (0, -1, slice(None, None, None))
A[obj]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48530710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get only git diff output in tab I want to get only output of git diff of whole repository, not just a file, in a tab, Not Split With The Commit Message!
In the issues I found a:
command GdiffInTab tabedit %|Gdiff
But this one opens an split view with commit message, the thing I want is to show only git diff in new tab when editing git commit message.
Is it possible? Or should I try doing it myself, something like:
function GitDiffTab()
exe "tab new %"
exe "%!git diff"
exe "se ft=diff"
endfunction
But it doesn't work when editing commit message.
A: Use :terminal (requires Vim 8.1+)
:-tab terminal git --no-pager diff
Using fugitive.vim we can create a command:
command! -bang Tdiff execute '-tab terminal ' . call(fugitive#buffer().repo().git_command, ['--no-pager', 'diff'] + (<bang>0 ? ['--cached'] : []))
Use :Tdiff to do git diff and :Tdiff! to do git diff --cached
For more help see:
:h :tab
:h :terminal
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54378200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQL Query, get only the line where a value appear 4 time I've got a table Customer (ID, Ref, LastName, FirstName).
I have to bring out all lines whose reference is the same at least four times.
I tried this unsuccessfully :
SELECT * from MyTable Where (select count(ref) from MyTable Group By ref) >= 4
Of course it is wrong, but I don't know how to do this in one query.
A: You need to use HAVING clause like below
SELECT * from Customer
Where ref in (select ref from Customer Group By ref having count(*) >= 4)
SQL Demo
A: If I understand correctly, you can use the Having clause in the query:
SELECT Ref, LastName, FirstName
from MyTable
group by Ref, LastName, FirstName
having count(*) >= 4
I have omitted ID, since this is possibly a primary key and probably not required here as the grouping wouldn't work.
EDIT: Since the above query will not return your result...You can also use a join...
SELECT *
FROM Customer c
INNER JOIN ( SELECT ref
FROM Customer
GROUP BY ref
HAVING COUNT(*) >= 4
) t ON c.ref = t.ref
A: SELECT * from MyTable Group By ref HAVING COUNT(*) >= 4
A: SELECT Ref, LastName, FirstName
from YourTable
group by Ref, LastName, FirstName
having count(*) >= 4
A: assuming records with the same Reference associate to the same customer then something meaningful can be got from :
select ID , max(Ref) as the_Ref , count(Ref) as count_ref from Customer group by Ref having count(Ref) >= 4;
If , however , Ref refers to something which occurs independently of the existence of customers ( maybe its used to refer to customer orders ) I'd recommend you consider normalising (http://en.wikipedia.org/wiki/Database_normalization) the data model a little more into two tables instead of one viz :
Customer( ID , firstName , LastName )
Customer_Order ( Ref , Customer_ID)
whats known as a foreign key relationship can then be set up between these two tables
A: As a lover of INNER JOIN, I would prefer the following way.
SELECT *
FROM Customer C
INNER JOIN (
SELECT Ref, LastName, FirstName, COUNT(1) AS NumberOfRef
FROM Customer
GROUP BY Ref, LastName, FirstName
) T ON T.Ref = C.Ref AND T.LastName = C.LastName AND T.FirstName = C.FirstName AND T.NumberOfRef >= 4
However, after I did it, I started to feel the table Customer to be a bit strange. Even though we normalize it, as @diarmuid suggested, what should we use as the primary key for Customer_Order?
Customer(ID , FirstName, LastName )
Customer_Order (Ref, CustomerID)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20494641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linq ToDictionary Not Defined? I have this code
var contacts = dr.mktDoctorContacts
.GroupBy(x => x.ContactType)
.Select(zb => new
{
Key = zb.Key,
GroupWiseContacts = zb.Select(x => x.Contact).ToList()
})
.ToDictionary<string,List<string>>(y => y.Key, y => y.GroupWiseContacts)
I don't know what is wrong with this code.
Compile time error msg says:System.Generic.IEnumerable does not contain definition of and best extension method overloads has some invalid arguments. i can see only two overloads of ToDictionary Method in my visual studio tooltip sort of documentation whereas i have come across more than two overloads of ToDictionary on the web
Edit Here is exact Error message at compile time
Error 13 'System.Collections.Generic.IEnumerable<AnonymousType#1>'
does not contain a definition for
'ToDictionary' and the best extension
method overload
'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>,
System.Func<TSource,TKey>,
System.Collections.Generic.IEqualityComparer<TKey>)'
has some invalid arguments
A: The compiler message makes the error clear: There is no method ToDictionary which can accept the arguments and types specified.
The mistake here is in specifying the type arguments on ToDictionary. The MSDN documentation defines the extension method as ToDictionary<TKey, TSource>. The source in your example is IEnumerable<AnonymousType#1>, but you have specified a type of List<string>.
To correct the error, omit the type arguments; the compiler will infer the correct types. You can additionally combine the Select and ToDictionary transformations into a single statement:
var contacts = dr.mktDoctorContacts
.GroupBy(x => x.ContactType)
.ToDictionary(
y => y.Key,
y => y.Select(x => x.Contact).ToList());
A: Rewrote your code (and added .AsEnumerable()):
var dictionary = dr.mktDoctorContacts
.GroupBy(x => x.ContactType)
.AsEnumerable()
.ToDictionary(
i => i.Key,
i => i.Select(x => x.Contact).ToList()
)
);
A: Don't run that group operation in the database, it'll cause the elements of each group to be fetched in separate roundtrips.
ILookup<string, string> contacts = dr.mktDoctorContacts
.ToLookup<Contact, string, string>(x => x.ContactType, x => x.Contact);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5104509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Scaffolding feature for winforms or wpf application I'd like to build a new winforms or wpf application, in which I'd like to use the concept of scaffolding like I saw for the Asp.net mvc5 application
Introduction To Scaffolding in Visual Studio 2013 RC
I need to know if this feature exists for the desktop applications like winforms or wpf
A: It is not possible to make common code for all application. There are various type of windows application for example Database Application, Client Server Application, System Utilities, etc So, the mechanism of all applications are different then how we can define a common code template for all application. It is up to you that what you want to use Database or TcpIP Socket for your application. I know my answer is not clear. Because it is very hard to define that why we could not create scaffolding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24820667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Insert value in variable I have a really easy (maybe stupid) question. I have following code to detect aruco markers with the aruco library:
MarkerDetector MDetector;
vector<Marker> Markers;
this->TheCameraParameters.readFromXMLFile(CAMERA_PARAM_FILE);
this->TheCameraParameters.resize(frame.size());
MDetector.detect(frame,Markers, this->TheCameraParameters, MARKER_SIZE);
This code gives me a vector (Markers) that consists of different detected markers. If I print Markers out I get following:
24=(304.631,14.2414) (358.085,12.8291) (358.957,69.6651) (306.197,71.0909) Txyz=0.0540816 -0.892379 2.30182 Rxyz=-2.99629 0.0430742 -0.0213533
But now I want to get the pixel values of the marker. With Markers[0].id,Markers[0].Tvec,Markers[0].Rvec I can extract the id, translation and rotation matrix, but I cant find a way to get the pixel values. Can someone help me with this?
A: I found the answer after an intensive search in the library.
In following output
24=(304.631,14.2414) (358.085,12.8291) (358.957,69.6651) (306.197,71.0909) Txyz=0.0540816 -0.892379 2.30182 Rxyz=-2.99629 0.0430742 -0.0213533
The first element (24) is the id of the marker. The next 4 elements are the pixel coordinates of the 4 corners. With Markers[0][0].x and Markers[0][0].y you get the x- and y-coordinate of the top left corner.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48589460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamic string parsing in C# I'm implementing "type-independent" method for filling DataRow with values.
Intended functionality is quite straight forward - caller passes the collection of string representations of column values and DataRow that needs to be filled:
private void FillDataRow(List<ColumnTypeStringRep> rowInput, DataRow row)
ColumnTypeStringRep structure contains the string representation of value, column name, and - what's of most importance - column data type:
private struct ColumnTypeStringRep
{
public string columnName; public Type type; public string stringRep;
public ColumnTypeStrinRep(string columnName, Type type, string stringRep)
{
this.columnName = columnName; this.type = type; this.stringRep = stringRep;
}
}
So what's that "type-independency"? Basically I don't care about the data row schema (which always be a row of some typed data table), as long as passed column names match DataRow's colum names and column data types match those of DataRow I'm fine. This function needs to be as flexible as possible (and as simple as possible - just not simpler).
Here it is (almost):
private void FillDataRow(List<ColumnTypeStrinRep> rowInput, DataRow row)
{
Debug.Assert(rowInput.Count == row.Table.Columns.Count);
foreach (ColumnTypeStrinRep columnInput in rowInput)
{
Debug.Assert(row.Table.Columns.Contains(columnInput.columnName));
Debug.Assert(row.Table.Columns[columnInput.columnName].DataType == columnInput.type);
// --> Now I want something more or less like below (of course the syntax is wrong) :
/*
row[columnInput.columnName] = columnInput.type.Parse(columnInput.stringRep);
*/
// --> definitely not like below (this of course would work) :
/*
switch (columnInput.type.ToString())
{
case "System.String":
row[columnInput.columnName] = columnInput.stringRep;
break;
case "System.Single":
row[columnInput.columnName] = System.Single.Parse(columnInput.stringRep);
break;
case "System.DateTime":
row[columnInput.columnName] = System.DateTime.Parse(columnInput.stringRep);
break;
//...
default:
break;
}
*/
}
}
Now You probably see my problem - I don't want to use the switch statement. It would be perfect, as in the first commented segment, to somehow use the provided column type to invoke Parse method of particular type that returns the object of that type constructed from string representation.
The switch solutions works but it's extremely non flexible - what if in future I'll be filling not the DataRow but some other custom type with "columns" that can be of custom type (of course every such type will need to expose Parse method to build itself from string representation).
Hope you got what I mean - its like "dynamic parsing" kind of functionality. Is there a way to achieve this in .NET?
Example of FillDataRow call could look like this:
List<ColumnTypeStrinRep> rowInput = new List<ColumnTypeStrinRep>();
rowInput.Add(new ColumnTypeStringRep("colName1", Type.GetType("System.Int32"), "0"));
rowInput.Add(new ColumnTypeStringRep("colName2", Type.GetType("System.Double"), "1,11"));
rowInput.Add(new ColumnTypeStringRep("colName3", Type.GetType("System.Decimal"), "2,22"));
rowInput.Add(new ColumnTypeStringRep("colName4", Type.GetType("System.String"), "test"));
rowInput.Add(new ColumnTypeStringRep("colName5", Type.GetType("System.DateTime"), "2010-01-01"));
rowInput.Add(new ColumnTypeStringRep("colName6", Type.GetType("System.Single"), "3,33"));
TestDataSet.TestTableRow newRow = this.testDataSet.TestTable.NewTestTableRow();
FillDataRow(rowInput, newRow);
this.testDataSet.TestTable.AddTestTableRow(newRow);
this.testDataSet.TestTable.AcceptChanges();
Thank You!
A: The TypeConverterclass is the generic .NET way for converting types. The System.ComponentModel namespace includes implementation for primitive types and WPF ships with some more (but I am not sure in which namespace). Further there is the static Convert class offering primitive type conversions, too. It handles some simple conversions on itself and falls back to IConvertible.
A: First off, your using a struct to pass a complex data around. That is a really bad idea. Make that a class instead.
That said, it sounds like you need a factory to create instances of a parser interface:
interface IColumnTypeParser
{
// A stateles Parse method that takes input and returns output
DataColumn Parse(string input);
}
class ColumnTyeParserFactory
{
IColumnTypeParser GetParser(Type columnType)
{
// Implementation can be anything you want...I would recommend supporting
// a configuration file that maps types to parsers, and use pooling or caching
// so you are not constantly recreating instances of your parsers (make sure your
// parser implementations are stateless to support caching/pooling and reuse)
// Dummy implementation:
if (columnType == typeof(string)) return new StringColumnTypeParser();
if (columnType == typeof(float)) return new FloatColumnTypeParser();
// ...
}
}
Your FillDataRow implementation would hten use the factory:
m_columnTypeParserFactory = new ColumnTypeParserFactory();
private void FillDataRow(List<ColumnTypeStrinRep> rowInput, DataRow row)
{
foreach (ColumnTypeStrinRep columnInput in rowInput)
{
var parser = m_columnTypeParserFactory.GetParser(columnInput.type);
row[columnInput.columnName] parser.Parse(columnInput.stringRep);
}
}
A: In short there is nothing like that - no automagical conversion. You have to specify conversion yourselves. That said
static class Converters{
static Dictionary<Type, Func<string, object>> Converters = new ...
static Converters{
Converters.Add(typeof(string), input => input);
Converters.Add(typeof(int), input => int.Parse(input));
Converters.Add(typeof(double), double => double.Parse(input));
}
}
void FillDataRow(IList<string> rowInput, row){
for(int i = 0; i < rowInput.Length; i++){
var converter = Converters.Converters[Column[i].DataType];
row[i] = converter(rowInput[i])
}
}
A: How about Convert.ChangeType?
You might consider something fancy with generics btw.
foreach (ColumnTypeStrinRep columnInput in rowInput)
{
Debug.Assert(row.Table.Columns.Contains(columnInput.columnName));
Debug.Assert(row.Table.Columns[columnInput.columnName].DataType == columnInput.type);
...
row[columnInput.columnName] = Convert.ChangeType(columnInput.stringRep, columnInput.type);
}
More on Convert.ChangeType:
http://msdn.microsoft.com/en-us/library/dtb69x08.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2328997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DataBindingUtil plus NavHostFragment back navigation not working I had posted a question earlier regarding NavHostFragment not working on back press. The question was not answered by anyone, hence putting a couple of days effort into it, I finally managed to figure out the issue.(I am only adding new code missing in the earlier question and changed code here, to reduce question length)
The navigation graph is changed to following:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/launch_navigation_graph"
app:startDestination="@id/splashFragment">
<fragment android:id="@+id/splashFragment" android:name="com.myapp.android.SplashFragment"
android:label="fragment_splash" tools:layout="@layout/fragment_splash">
<action android:id="@+id/action_splashFragment_to_fragment1"
app:destination="@id/fragment1"
app:popUpTo="@+id/splashFragment"
app:popUpToInclusive="true"/>
</fragment>
<fragment android:id="@+id/fragment1"
android:name="com.myapp.android.Fragment1"
android:label="fragment1" tools:layout="@layout/fragment_register_msisdn">
<action android:id="@+id/action_fragment1_to_fragment2"
app:destination="@id/fragment2" app:popUpTo="@+id/fragment1"
app:popUpToInclusive="false"/>
</fragment>
<fragment android:id="@+id/fragment2"
android:name="com.myapp.android.Fragment2"
android:label="fragment_fragment2" tools:layout="@layout/fragment_fragment2"/>
</navigation>
Some information which was missing from the previous question. The fragment binding was earlier done like this(Code below is for Fragment1, same is done in Fragment2):
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: Fragment1Binding =
DataBindingUtil.setContentView(activity!!, R.layout.fragment1)
binding.lifecycleOwner = this
val fragment1ViewModel = ViewModelProviders.of(this).get(Fragment1ViewModel::class.java)
binding.viewModel = fragment1ViewModel
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment1, container, false)
}
The above code, with the navigation graph, now doesn't crash, but the back button simply refuse to work. It doesn't pop fragment, just exit on second back press.
Now I figured out that inflating the UI using DataBindingUtil.setContentView was the reason why my code was not working. I figured it out by creating another sample project step by step until I figured out when it stops working. I made the sample project work using data binding by using DataBindingUtil to bind to view inflated in OnCreateView like following. I remove the oncreate override.
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val rootView = inflater.inflate(R.layout.fragment1, container, false)
val binding = DataBindingUtil.bind<Fragment1Binding>(rootView)
binding?.lifecycleOwner = viewLifecycleOwner
val fragment1ViewModel = ViewModelProviders.of(this).get(Fragment1ViewModel::class.java)
binding.viewModel = fragment1ViewModel
return rootView
}
Now, this code works in the sample project, but when I place the same on my final project(In sample project I simply place buttons and click to navigate where as in my original project I have webservice calls and view model observing for navigating), the above code crashes with following exception when pressing back from Fragment2(similar crash in Fragment1 back press as well if I press back from Fragment1).
2019-04-30 14:00:47.043 18087-18087/com.selfcare.safaricom E/InputEventSender: Exception dispatching finished signal.
2019-04-30 14:00:47.043 18087-18087/com.selfcare.safaricom E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
2019-04-30 14:00:47.047 18087-18087/com.selfcare.safaricom E/MessageQueue-JNI: java.lang.IllegalArgumentException: navigation destination com.selfcare.safaricom:id/action_fragment1_to_fragment2 is unknown to this NavController
at androidx.navigation.NavController.navigate(NavController.java:803)
at androidx.navigation.NavController.navigate(NavController.java:744)
at androidx.navigation.NavController.navigate(NavController.java:730)
at androidx.navigation.NavController.navigate(NavController.java:718)
at com.myapp.android.Fragment2.handleLaunchStatus(Fragment2.kt:53)
at com.myapp.android.Fragment2.access$handleLaunchStatus(Fragment2.kt:18)
at com.myapp.android.Fragment2$attachLaunchObserver$1.onChanged(Fragment2.kt:46)
at com.myapp.android.Fragment2$attachLaunchObserver$1.onChanged(Fragment2.kt:18)
at androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:126)
at androidx.lifecycle.LiveData$ObserverWrapper.activeStateChanged(LiveData.java:424)
at androidx.lifecycle.LiveData$LifecycleBoundObserver.onStateChanged(LiveData.java:376)
at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:361)
at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:188)
at androidx.lifecycle.LiveData.observe(LiveData.java:185)
at com.myapp.android.Fragment2.attachLaunchObserver(Fragment2.kt:45)
at com.myapp.android.Fragment2.onViewCreated(Fragment2.kt:37)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:895)
at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2092)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1866)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1822)
at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:298)
at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:241)
at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:288)
at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:241)
at androidx.fragment.app.FragmentActivity$1.handleOnBackPressed(FragmentActivity.java:144)
at androidx.activity.OnBackPressedDispatcher.onBackPressed(OnBackPressedDispatcher.java:136)
at androidx.activity.ComponentActivity.onBackPressed(ComponentActivity.java:283)
at android.app.Activity.onKeyUp(Activity.java:3083)
at android.view.KeyEvent.dispatch(KeyEvent.java:2716)
at android.app.Activity.dispatchKeyEvent(Activity.java:3366)
at androidx.core.app.ComponentActivity.superDispatchKeyEvent(ComponentActivity.java:80)
at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:84)
at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:98)
at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:558)
at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2736)
at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:342)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:5037)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4905)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4426)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4479)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4445)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4585)
at android.view.ViewRootImpl$InputStage.apply(Vie
I googled with the exception but found nothing useful in this particular context that can solve my issue. Please help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55916907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rest with spring-boot : Content Negotiation failed! No converter found for return value of type I am trying to get the content of a java POJO on the browser in JSON format using spring-boot 2.1.9 and spring REST. Very basic example! But I get the exception shown on the title of this post. When I annotate the POJO class with @XmlRootElement, I get the XML content on the browser. But when I try to get a list of POJOs on the browser I get the same error as with JSON. Why is the content negotiation working partially for XML and not working at all for JSON ? Thanks for every Answer.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Oct 03 15:17:06 CEST 2019
There was an unexpected error (type=Internal Server Error, status=500).
No converter found for return value of type: class com.mayo.vina.restapi4.domain.Limit
org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.mayo.vina.restapi4.domain.Limit
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:234)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:181)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:123)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:798)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
I've already tried all the answers provided in Stackoverflow. Extending the POM file with jackson-databind, using @ResponseBody, @GetMapping instead of @RequestMapping, using produces = "application/json"...
Nothing worked for me.
package com.mayo.vina.restapi4;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Restapi4Application {
public static void main(String[] args) {
SpringApplication.run(Restapi4Application.class, args);
}
}
-------------------------------------------------------------------------
package com.mayo.vina.restapi4.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mayo.vina.restapi4.domain.Limit;
@RestController
public class LimitController
{
@RequestMapping("/limit")
public Limit limit()
{
return new Limit(1, 10000);
}
}
---------------------------------------------------------------------------
package com.mayo.vina.restapi4.domain;
//@XmlRootElement
public class Limit
{
private int minimum;
private int maximum;
public Limit()
{
}
public Limit(int minimum, int maximum)
{
this.minimum = minimum;
this.maximum = maximum;
}
public int getMinimum()
{
return minimum;
}
public void setMinimum(int minimum)
{
this.minimum = minimum;
}
public int getMaximum()
{
return maximum;
}
public void setMaximum(int maximum)
{
this.maximum = maximum;
}
}
--------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mayo.vina</groupId>
<artifactId>restapi4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>restapi4</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
A: You can try with :
@GetMapping(value = '/limit')
@ResponseBody
public Limit limit()
{
return new Limit(1, 10000);
}
A: The following solved my problem:
So yes, just to reiterate, going into my maven repo and deleting the fasterxml folder and re-running maven is what fixed the issue for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58221237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Latest modified row for each item I have a sql table containing multiple rows with a memberid and lastmodified date. I need to get latest modified row for each member id. This is what I have tried in EFCore 3.1.1:
var a = context.Members
.Include(m => m.Histories.OrderByDescending(h => h.LastModifiedDate)
.FirstOrDefault());
and it gives error: Lambda expression used inside Include is not valid
What am I missing?
UPDATE:
I tried this as well that didn't work either:
var a = context.Histories
.GroupBy(h => h.MemberId)
.Select(g => g.OrderByDescending(p => p.LastModifiedDate).FirstOrDefault()).ToList();
The LINQ expression '(GroupByShaperExpression:
KeySelector: (o.MemberId),
ElementSelector:(EntityShaperExpression:
EntityType: History
ValueBufferExpression:
(ProjectionBindingExpression: EmptyProjectionMember)
IsNullable: False
)
)
.OrderByDescending(p => p.LastModifiedDate)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
A: While newer versions of EF Core do support some filtering via adding Where clauses, it's best to think of entities as a "complete" or "complete-able" representation of your data state. You either use the complete state of data, or you project to get the details you want.
For example, if you just want the last modified date for each member:
var lastModifiedDetails = context.Members
.Select(m => new
{
m.MemberId,
LastModifiedDate = m.Histories.OrderByDescending(h => h.LastModifiedDate)
.Select(h => h.LastModifiedDate)
.FirstOrDefault()
}).ToList();
This would give you a collection containing the MemberId and it's LastModifiedDate.
Alternatively, if you want the complete member and a quick reference to the last modified date:
var memberDetails = context.Members
.Select(m => new
{
Member = m,
LastModifiedHistory = m.Histories.OrderByDescending(h => h.LastModifiedDate)
.FirstOrDefault()
}).ToList();
Here instead of trying to get the last modified date or the latest history through a Member entity, you get a set of anonymous types that project down that detail. You iterate through that collection and can get the applicable history and/or modified date for the associated Member.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72987573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Moving WPF application to Android Im not sure if this is the best place for this question so please let me know if not. I have recently created a pretty simple WPF application that has a link to a SQL Database and allows information to be added, updated and deleted.
I want to port the application so I can use it on my Android phone but am unsure about the easiest way to do this. Im aware I could write a completely new application but Im wondering if there is a way I could easily use all the code ive already written or my Windows app? That way it would also make any updates/code changes easier?
Any thoughts
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27118303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't drop foreign key (using constraint name) check column/key exists I've tried to find a solution myself but haven't had any luck. I'm using MySQL version 8.0.14 and my problem is:
When trying to drop a foreign key...
alter table Employee drop foreign key fk_Employee_Contact1;
It fails...
Error Code: 1091. Can't DROP 'fk_Employee_Contact1'; check that column/key exists
I search for the constraint...
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME='Employee';
Which brings up (partial table)...
CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE
'fk_Employee_Contact1', 'RRAS Test Database', 'Employee', 'FOREIGN KEY'
But if I search...
SHOW CREATE TABLE Employee;
It shows it as a key...
KEY `fk_Employee_Contact1_idx` (`idContactDets`),
But not as a CONSTRAINT.
I have also tried...
alter table Employee drop foreign key fk_Employee_Contact1_idx;
Which fails with the same error code. And...
alter table Employee drop column idContactDets;
Which gives...
Error Code: 1828. Cannot drop column 'idContactDets': needed in a foreign key constraint 'fk_Employee_Contact1'
Is there any way to fix this? I'm very new to databases so please explain in simple terms if possible. Thank you. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54371765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP Webhook Request I am running a WordPress site with a WooCommerce checkout. At the checkout page I am using the webhook woocommerce_thankyou as a boarding point for my code. At this Point I am selecting some data from the new my order to send the data to another website via a webhook.
I integrated the code over a custom WordPress plugin. At the moment the webhook gives me back this following error: "DigiMember - Webhook Checkout (#1): the E-Mail-Adress would not send as GET- or POST-Parameter."
What could be the problem?
<?php
function test ($order_id) {
?>
<span>
woocommerce_thankyou
<?php echo $order_id;
$order=wc_get_order($order_id);
echo $order->get_meta('digi_first_name');
echo $order->get_meta('digi_last_name');
echo $order->get_meta('digi_email');
?>
</span>
<?php
//The url you wish to send the POST request to
$url = 'https://traumjob-campus.de/member?dm_webhook=1_DCqtx6Xre1oM7tuKyon5rVzAIUWvVVXofMqTRQjE9JVDgf7gLI3M198bIeD5';
//The data you want to send via POST
$fields = [
'digi_first_name' => 'user',
'digi_last_name' => 'test',
'digi_email' => '[email protected]'
];
//url-ify the data for the POST
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
echo $result;
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59717391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Search specific words in pdf and return only pdf link where words were found (Python) I am trying to search for multiple words in many PDFs. Links to these PDFs are saved in a dataframe. The goal is for python to return a text stating "The words are located in pdf link"). Here is the code I have so far: (FYI g7 is the name of the dataframe where the links are saved).The issue here is that the code returns the same link multiple times for every time the word is found.
The dataframe (named g7) looks like this:
URL
0 https://westafricatradehub.com/wp-content/uploads/2021/07/RFA-WATIH-1295_Senegal-RMNCAH-Activity_English-Version.pdf
1 https://westafricatradehub.com/wp-content/uploads/2021/07/RFA-WATIH-1295_Activit%C3%A9-RMNCAH-S%C3%A9n%C3%A9gal_Version-Fran%C3%A7aise.pdf
2 https://westafricatradehub.com/wp-content/uploads/2021/08/Senegal-Health-RFA-Webinar-QA.pdf
3 https://westafricatradehub.com/wp-content/uploads/2021/02/APS-WATIH-1021_Catalytic-Business-Concepts-Round-2.pdf
4 https://westafricatradehub.com/wp-content/uploads/2021/02/APS-WATIH-1021_Concepts-d%E2%80%99Affaires-Catalytiques-2ieme-Tour.pdf
5 https://westafricatradehub.com/wp-content/uploads/2021/06/APS-WATIH-1247_Research-Development-Round-2.pdf
The code is as follows:
import glob
import pathlib
import PyPDF2
import re
import os
for i in range(g7.shape[0]):
pdf_link=g7.iloc[i,0]
download_file(pdf_link, f"pdf_{i}")
text = textract.process(f"/Users/fze/pdf_{i}.PDF")
# open the pdf file
object = PyPDF2.PdfFileReader(f"/Users/fze/pdf_{i}.PDF")
all_files = glob.glob('/Users/fze/*.pdf') #User input: give path to your downloads folder file path
latest_pdf_path = max(all_files, key=os.path.getctime)
path = pathlib.PurePath(latest_pdf_path)
latest_pdf_name=path.name
print(latest_pdf_name)
# get number of pages
NumPages = object.getNumPages()
# define keyterms
search_word = 'organization'
# extract text and do the search
for i in range(0, NumPages):
page = object.getPage(i)
text = page.extractText()
search_text = text.lower().split()
for word in search_text:
if search_word in word:
print("The word '{}' was found in '{}'".format(search_word,pdf_link))
Thank you !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69395489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change a View with a procedure This is the source of a view , i use this view as the base of a procedure named buscacancelados:
SELECT NUMERO FROM dbo.CTRC
WHERE (EMITENTE = 504) AND (MONTH(EMISSAODATA) = 3)
AND (YEAR(EMISSAODATA) = 2013)
This procedure returns the missing numbers in a set
alter proc buscarcancelado (@emp int) as
begin
set nocount on;
declare @min int --- declare the variavels to be used
declare @max int
declare @I int
IF OBJECT_ID ('TEMP..#TempTable') is not null -- Controls if exists this table
begin
drop table #TempTable -- If exist delete
end
create table #TempTable
(TempOrderNumber int)-- create a temporary table
SELECT @min = ( SELECT MIN (numero)
from controlanum with (nolock)) -- search the min value of the set
SELECT @max = ( SELECT Max (numero)
from controlanum with (nolock)) -- search the max value of the set
select @I = @min -- control where begins the while
while @I <= @max -- finish with the high number
begin
insert into #TempTable
select @I
select @I = @I + 1
end
select tempordernumber from #TempTable
left join controlanum O with (nolock)
on TempOrderNumber = o.numero where o.numero is null
end
I want to change the view controlanum with this procedure
create proc filtraperiodo (@emp int,@mes int,@ano int)as
select numero from ctrc where
EMITENTE = 504
and MONTH (EMISSAODATA ) = 3 and YEAR (EMISSAODATA)=2013
I want something like this
SELECT @min = ( SELECT MIN (numero) from filtraperiodo 504,2,2013
A: Create controlanum as a table-valued function instead of a view
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE ID = OBJECT_ID('[dbo].[controlanum]') AND XTYPE IN ('FN', 'IF', 'TF'))
DROP FUNCTION [dbo].[controlanum]
GO
CREATE FUNCTION [dbo].[controlanum] (
@emp int
,@mes int
,@ano int
)
RETURNS @numeros TABLE (numero int)
AS
BEGIN
INSERT @numeros
SELECT numero
FROM ctrc WITH (NOLOCK)
WHERE EMITENTE = @emp
AND MONTH (EMISSAODATA ) = @mes
AND YEAR (EMISSAODATA) = @ano
RETURN
END
GO
Everywhere you reference controlanum, pass it your 3 filter values. For instance:
--...other code here...
SELECT @min = MIN(numero)
FROM dbo.controlanum(@emp, @mes, @ano)
SELECT @max = MAX(numero)
FROM dbo.controlanum(@emp, @mes, @ano)
--...other code here...
SELECT tempordernumber
FROM #TempTable A
LEFT JOIN dbo.controlanum(@emp, @mes, @ano) O
ON A.TempOrderNumber <> O.numero
WHERE O.numero IS NULL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16308153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python method to get integers from a string with limitation (in some range) Is there a module in python to get integers from string in given range (with limit/restriction) ?
It can be useful to make code cleaner.
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int | bool: # (or False directly)
try:
number = int("".join(filter(str.isdigit, string)))
if low_boundary < number < high_boundary:
return number
else:
return False
except ValueError: # Empty message or out of limit
return False
Usage:
...
if not amount := get_int_from_str(string=input(), low_boundary = 10, high_boundary = 20)
...
...
A: Don't fight exceptions. If you can't parse a string as an integer, let the ValueError be raised. If the number is out of range, raise a different ValueError. Otherwise, return a value that is guaranteed to be in the requested range.
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int:
x = int(str) # May raise
if x < low_boundary or x > high_boundary:
raise ValueError(f"Value '{x}' is out of range {low_boundary}-{high_boundary}")
return x
The caller knows better than your function what to do if the string cannot produce an in-range integer, and raising an exception forces them to consider the worst-case scenario, rather than letting them assume the function worked and encountering an error later.
As a conventional alternative, you can return None to indicate the lack of a suitable int value. Unlike False, None cannot be confused with 0, but it can still be ignored altogether to cause problems later. (And None by itself doesn't tell you if the string wasn't parseable or if the parsed number was simply out of range.)
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]:
try:
x = int(str)
except ValueError:
return None
if x < low_boundary or x > high_boundary:
return None
return x
or, to avoid repeating the return None statement:
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]:
try:
x = int(str)
if x < low_boundary or x > high_boundary:
raise ValueError
except ValueError:
return None
return x
A: def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int | False:
number = "".join(filter(str.isdigit, string))
if number:
number = int(number)
if low_boundary < number < high_boundary:
return number
return False
Note: Using not operator with the output of the function does not distinguish between False and 0 as not False and not 0 will evaluate to True. Here you can differentiate by checking the output with amount is not False condition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70625715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do I make links that were in the menu be on the nav bar on bigger screens? There are links that were shown on the side of the page as a menu when a button that was in the header was clicked. I want the button to be hidden and for those links to show up in the header instead. But if hide the button, the links do not show up, regardless of if I make the display: block or not. The only thing that happens is that the button is gone, but so are the links.
I have JavaScript code that hides and shows the links when the button is clicked
How do I change the position of the links?
header {
height: 3.4rem;
display: grid;
align-items: center;
}
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
}
.right i {
margin-right: 1rem;
}
.menu {
display: none;
position: fixed;
top: 0;
right: 0;
z-index: 1;
background-color: #000;
/* margin-left: 4rem; */
margin-top: 0;
}
@media screen and (min-width: 992px) {
.right i {
display: none;
}
.menu {
display: block;
}
.top-menu {
display: flex;
top: 0;
}
.header-container {
display: flex;
}
}
<header>
<div class="header-container">
<div class="left">
<img src="img/logo.jpg" alt="">
</div>
<div class="right">
<img src="img/user.png" alt="">
<i class="fa-solid fa-bars fa-xl"></i>
</div>
</div>
</header>
<nav class="menu">
<div class="menu-container">
<i class="fa-solid fa-xmark fa-xl"></i>
<div class="top-menu">
<a href="">Premium</a>
<a href="">Support</a>
<a href="">Download</a>
<div class="menu-line"></div>
</div>
<div class="bottom-menu">
<a href="">Account</a>
<a href="">Log out</a>
</div>
<img src="img/logo.jpg" alt="">
</div>
</nav>
A: You want links on Nav Bar to show when the site is viewed via PC or Laptop screen. And you want the links to collapse in button when site is viewed via mobile.
When viewed on PC Screen:
I did it with Bootstrap, you can also use jQuery for simplicity.
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="container-fluid">
<div class="row">
<nav class="navbar navbar-expand-md navbar-light">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarToggler1" aria-controls="navbarToggler1" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggler1">
<div id="right-menu" class="col-md-3">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#features">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Blog</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#footer">Contact</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
</div>
</div>
Using simple jQuery
#show{
display:none;
}
#content{
display:none;
}
@media only screen and (max-width: 600px)
{
div{
display:none;
}
#show{
display:inline;
}
}
<button id="show">Show</button>
<div id="content">
<ul>
<li>
pricing
</li>
<li>
features
</li>
</ul>
</div>
<div>
<ul>
<li>
pricing
</li>
<li>
features
</li>
</ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$("#show").click(function()
{
$("#content").toggle();
});
</script>
Live Result with Code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72156272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to stop thinking "relationally" At work, we recently started a project using CouchDB (a document-oriented database). I've been having a hard time un-learning all of my relational db knowledge.
I was wondering how some of you overcame this obstacle? How did you stop thinking relationally and start think documentally (I apologise for making up that word).
Any suggestions? Helpful hints?
Edit: If it makes any difference, we're using Ruby & CouchPotato to connect to the database.
Edit 2: SO was hassling me to accept an answer. I chose the one that helped me learn the most, I think. However, there's no real "correct" answer, I suppose.
A: It's all about the data. If you have data which makes most sense relationally, a document store may not be useful. A typical document based system is a search server, you have a huge data set and want to find a specific item/document, the document is static, or versioned.
In an archive type situation, the documents might literally be documents, that don't change and have very flexible structures. It doesn't make sense to store their meta data in a relational databases, since they are all very different so very few documents may share those tags. Document based systems don't store null values.
Non-relational/document-like data makes sense when denormalized. It doesn't change much or you don't care as much about consistency.
If your use case fits a relational model well then it's probably not worth squeezing it into a document model.
Here's a good article about non relational databases.
Another way of thinking about it is, a document is a row. Everything about a document is in that row and it is specific to that document. Rows are easy to split on, so scaling is easier.
A: In CouchDB, like Lotus Notes, you really shouldn't think about a Document as being analogous to a row.
Instead, a Document is a relation (table).
Each document has a number of rows--the field values:
ValueID(PK) Document ID(FK) Field Name Field Value
========================================================
92834756293 MyDocument First Name Richard
92834756294 MyDocument States Lived In TX
92834756295 MyDocument States Lived In KY
Each View is a cross-tab query that selects across a massive UNION ALL's of every Document.
So, it's still relational, but not in the most intuitive sense, and not in the sense that matters most: good data management practices.
A: Document-oriented databases do not reject the concept of relations, they just sometimes let applications dereference the links (CouchDB) or even have direct support for relations between documents (MongoDB). What's more important is that DODBs are schema-less. In table-based storages this property can be achieved with significant overhead (see answer by richardtallent), but here it's done more efficiently. What we really should learn when switching from a RDBMS to a DODB is to forget about tables and to start thinking about data. That's what sheepsimulator calls the "bottom-up" approach. It's an ever-evolving schema, not a predefined Procrustean bed. Of course this does not mean that schemata should be completely abandoned in any form. Your application must interpret the data, somehow constrain its form -- this can be done by organizing documents into collections, by making models with validation methods -- but this is now the application's job.
A: may be you should read this
http://books.couchdb.org/relax/getting-started
i myself just heard it and it is interesting but have no idea how to implemented that in the real world application ;)
A: I think, after perusing about on a couple of pages on this subject, it all depends upon the types of data you are dealing with.
RDBMSes represent a top-down approach, where you, the database designer, assert the structure of all data that will exist in the database. You define that a Person has a First,Last,Middle Name and a Home Address, etc. You can enforce this using a RDBMS. If you don't have a column for a Person's HomePlanet, tough luck wanna-be-Person that has a different HomePlanet than Earth; you'll have to add a column in at a later date or the data can't be stored in the RDBMS. Most programmers make assumptions like this in their apps anyway, so this isn't a dumb thing to assume and enforce. Defining things can be good. But if you need to log additional attributes in the future, you'll have to add them in. The relation model assumes that your data attributes won't change much.
"Cloud" type databases using something like MapReduce, in your case CouchDB, do not make the above assumption, and instead look at data from the bottom-up. Data is input in documents, which could have any number of varying attributes. It assumes that your data, by its very definition, is diverse in the types of attributes it could have. It says, "I just know that I have this document in database Person that has a HomePlanet attribute of "Eternium" and a FirstName of "Lord Nibbler" but no LastName." This model fits webpages: all webpages are a document, but the actual contents/tags/keys of the document vary soo widely that you can't fit them into the rigid structure that the DBMS pontificates from upon high. This is why Google thinks the MapReduce model roxors soxors, because Google's data set is so diverse it needs to build in for ambiguity from the get-go, and due to the massive data sets be able to utilize parallel processing (which MapReduce makes trivial). The document-database model assumes that your data's attributes may/will change a lot or be very diverse with "gaps" and lots of sparsely populated columns that one might find if the data was stored in a relational database. While you could use an RDBMS to store data like this, it would get ugly really fast.
To answer your question then: you can't think "relationally" at all when looking at a database that uses the MapReduce paradigm. Because, it doesn't actually have an enforced relation. It's a conceptual hump you'll just have to get over.
A good article I ran into that compares and contrasts the two databases pretty well is MapReduce: A Major Step Back, which argues that MapReduce paradigm databases are a technological step backwards, and are inferior to RDBMSes. I have to disagree with the thesis of the author and would submit that the database designer would simply have to select the right one for his/her situation.
A: One thing you can try is getting a copy of firefox and firebug, and playing with the map and reduce functions in javascript. they're actually quite cool and fun, and appear to be the basis of how to get things done in CouchDB
here's Joel's little article on the subject : http://www.joelonsoftware.com/items/2006/08/01.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1043830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Why would you use Ramda's lenses over evolve/path? Is there some functionality that lenses offer that you cannot get with path/assocPath/evolve/adjust?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56528914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cocos2D: Multiple actions: CCMoveTo CCAnimate I don´t understand, I absolutely cannot get this to work, I want a sequence of actions that plays an animation and moves the sprite using the CCAnimate ans CCMoveTo classes. Is there a bug or something special about these classes, cause it will not move nor animate when stringing it together in a CCSequence of actions like this.
action = [CCSequence actions:
[CCMoveTo actionWithDuration:moveDuration position:touchLocation],
[CCAnimate actionWithAnimation:self.walkingAnim],
[CCCallFunc actionWithTarget:self selector:@selector(objectMoveEnded)], nil];
[self runAction:action];
I
A: If you want the move and animate action to run paralel you can use:
Option1: use CCSpawn instead of a CCSequence. CCSequence is needed because you would like to call a function after completion.
id action = [CCSpawn actions:
[CCMoveTo actionWithDuration:moveDuration position:touchLocation],
[CCAnimate actionWithAnimation:self.walkingAnim],
nil];
id seq = [CCSequence actions:
action,
[CCCallFunc actionWithTarget:self selector:@selector(objectMoveEnded)],
nil];
[self runAction:seq];
Option2: just add any action multiple times and will be run in paralel. Because of the func-call a CCSequence again needed:
id action = [CCSequence actions:
[CCMoveTo actionWithDuration:moveDuration position:touchLocation],
[CCCallFunc actionWithTarget:self selector:@selector(objectMoveEnded)],
nil];
[self runAction:action];
[self runAction:[CCAnimate actionWithAnimation:self.walkingAnim]];
A: What this sequence does is:
*
*move self to the destination
*once arrived at destination, play the walking animation
*when the walk animation is finished, run the selector
I bet you meant to run the move and animate actions separately and at the same time (each with their own call to runAction) and not within a sequence.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16449079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Could not display data from php mysql in listview java Please help im new in java...
im not able to display data in listview
PHP side
<?
$objConnect = mysql_connect("my server","username here"," my password");
$objDB = mysql_select_db("db");
$strSQL = "SELECT * FROM image WHERE 1 ";
$objQuery = mysql_query($strSQL);
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
$arrCol = array();
for($i=0;$i<$intNumField;$i++)
{
$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
}
array_push($resultArray,$arrCol);
}
mysql_close($objConnect);
echo json_encode($resultArray);
?>
I have 3 layout
main layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3E70D" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dip" >
<TextView
android:id="@+id/tvordername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textStyle="bold"
android:text="TextView" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
</ScrollView>
Second layout
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/ColImgPath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/ColImgID"
android:text="Column 1" />
<TextView
android:id="@+id/ColImgDesc"
android:text="Column 2" />
</TableRow>
</TableLayout>
Third layout is use to display more detail and single record
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp" >
<ImageView
android:id="@+id/fullimage"
android:layout_width="match_parent"
android:layout_height="245dp"/>
<TextView
android:id="@+id/custom_full_order"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
>
</TextView>
</LinearLayout>
Java side my complete code
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.android.library.DatabaseHandler;
import com.example.android.library.UserFunctions;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class OrderActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
//listview
final ListView lstview1 = (ListView)findViewById(R.id.listView1);
String url = "my server address http:";
try{
JSONArray data = new JSONArray(getJSONUrl(url));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String>map;
for(int i= 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("ImageID", c.getString("ImageID"));
map.put("ImageDesc", c.getString("ImageDesc"));
map.put("ImagePath", c.getString("ImagePath"));
MyArrList.add(map);
}
lstview1.setAdapter(new ImageAdapter(this,MyArrList));
final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
lstview1.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
View layout = inflater.inflate(R.layout.custom_fullorder_dialog, (ViewGroup) findViewById(R.id.fullimage));
ImageView image = (ImageView) layout.findViewById(R.id.fullimage);
try
{
image.setImageBitmap(loadBitmap(MyArrList.get(position).get("Imagepath")));
} catch (Exception e){
//if get error
image.setImageResource(android.R.drawable.ic_menu_report_image);
}
imageDialog.setIcon(android.R.drawable.btn_star_big_on);
imageDialog.setTitle("View : " + MyArrList.get(position).get("comment"));
imageDialog.setView(layout);
imageDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
imageDialog.create();
imageDialog.show();
}
});
} catch(JSONException e){
e.printStackTrace();
}
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public ImageAdapter(Context c, ArrayList<HashMap<String, String>> list){
context = c;
MyArr = list;
}
public int getCount() {
// TODO Auto-generated method stub
return MyArr.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null){
convertView = inflater.inflate(R.layout.activity_column, null);
}
//colimage
ImageView imageView =(ImageView) convertView.findViewById(R.id.ColImgPath);
imageView.getLayoutParams().height= 100;
imageView.getLayoutParams().width= 100;
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
try
{
imageView.setImageBitmap(loadBitmap(MyArr.get(position).get("ImagePath")));
} catch (Exception e){
//if get error
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
//colposition
TextView txtPosition = (TextView) convertView.findViewById(R.id.ColImgID);
txtPosition.setPadding(10, 0, 0, 0);
txtPosition.setText("ID : " + MyArr.get(position).get("ImageID"));
//colpicname
TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgDesc);
txtPicName.setPadding(50, 0, 0, 0);
txtPicName.setText("DEesc : " + MyArr.get(position).get("ImageDesc"));
return convertView;
}
}
//get json code from url
public String getJSONUrl(String url){
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if(statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while((line = reader.readLine()) != null){
str.append(line);
}
} else {
Log.e("Log", "Failed to download file...");
}
} catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
//get image resource from url
private static final String TAG = "ERROR";
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static Bitmap loadBitmap(String url){
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in,out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSamplesize=1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
} catch (IOException e){
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static void closeStream(Closeable stream){
if(stream != null) {
try{
stream.close();
} catch (IOException e){
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1){
out.write(b, 0, read);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.order, menu);
return true;
}
}
my logcat
01-26 21:58:35.594: W/System.err(14298): org.json.JSONException: Value <? of type java.lang.String cannot be converted to JSONArray
01-26 21:58:35.594: W/System.err(14298): at org.json.JSON.typeMismatch(JSON.java:111)
01-26 21:58:35.594: W/System.err(14298): at org.json.JSONArray.<init>(JSONArray.java:96)
01-26 21:58:35.594: W/System.err(14298): at org.json.JSONArray.<init>(JSONArray.java:108)
01-26 21:58:35.594: W/System.err(14298): at com.example.androidjhfong.OrderActivity.onCreate(OrderActivity.java:77)
01-26 21:58:35.594: W/System.err(14298): at android.app.Activity.performCreate(Activity.java:5231)
01-26 21:58:35.599: W/System.err(14298): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-26 21:58:35.599: W/System.err(14298): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
01-26 21:58:35.599: W/System.err(14298): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)
01-26 21:58:35.599: W/System.err(14298): at android.app.ActivityThread.access$800(ActivityThread.java:144)
01-26 21:58:35.599: W/System.err(14298): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
01-26 21:58:35.599: W/System.err(14298): at android.os.Handler.dispatchMessage(Handler.java:102)
01-26 21:58:35.599: W/System.err(14298): at android.os.Looper.loop(Looper.java:136)
01-26 21:58:35.599: W/System.err(14298): at android.app.ActivityThread.main(ActivityThread.java:5139)
01-26 21:58:35.599: W/System.err(14298): at java.lang.reflect.Method.invokeNative(Native Method)
01-26 21:58:35.599: W/System.err(14298): at java.lang.reflect.Method.invoke(Method.java:515)
01-26 21:58:35.599: W/System.err(14298): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
01-26 21:58:35.599: W/System.err(14298): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
01-26 21:58:35.599: W/System.err(14298): at dalvik.system.NativeStart.main(Native Method)
01-26 21:58:35.719: I/Timeline(14298): Timeline: Activity_idle id: android.os.BinderProxy@423fd758 time:785573323
A: You have real mess in your code. Firstly you shouldn't connect to web in main thread (it blocks app, cause "application not responding"). For fetching JSON I would recommend RoboSpice.
Secondly in ImageAdapter.getItem you should return MyArr.get(position) not position.
A: I think greenapps and MAGx2 have the right hints for the solution.
I'd like to add that it might be better to use a few open source libraries for the other things.
*
*picasso for image downloading + displaying
*gson for json parsing
*okhttp for normal downloads
Also, don't use things like this:
imageView.getLayoutParams().height= 100;
It really messes up when you view on other devices with different DPI
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28151451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Image(Absolute Positioned) Horizontally center in a Relative Positioned container I want to center an absolute positioned image horizontally in a relative positioned container. I tried to do with css. But I could't and i did in Jquery
http://jsfiddle.net/CY6TP/ [This is i tried to do in Jquery]
**Guys can anyone help me to do this in CSS.**
Thanks in advance
A: try this:
var width=$('.main').width();
var height=$('.main').height();
$('a').css(
{
"position":"absolute",
"bottom":"50%",
"margin-top":(height/2),
"left":(width/2)-50
});
DEMO
UPDATE
In CSS
.main a{
bottom:50%;
margin-top:-150px;
position:absolute;
left:75px;
}
DEMO
A: You can set all in css like this :
a{
position : absolute ;
height : 10px;
width : 100px;
top : 50%;
margin-top : -5px;
left : 50%;
margin-left : -50px;}
Demo
A: try this to make it horizontally center
a{
position: absolute;
text-align: center;
width: 100%;
}
OR this to make it horizontally and vertically both center
a {
height: 100%;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
}
A: .main img { top:50%; left:50%; margin: -11px 0 0 -50px; position: absolute;}
Is this you want?
A: If your height is fixed, you could use something like this maybe?
CSS:
#div1 {
width:100%;
height:100px;
text-align:center;
}
#div1 img {
line-height:100px;
}
HTML:
<div id="div1">
<img src="yourimage.jpg" />
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20628676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: geom_bar: stack without adding I want a bar chart that looks stacked, but that the values are the actual values rather than being additive. I'm graphing things at ages, and ages don't "add".
The data below show that the oldest animal lives to be 31 days old. However, the graph indicates a value in the 60s because it is adding the days together.
x <- data.frame(species = c("Alpha", "Alpha", "Alpha","Beta", "Beta", "Beta","Gamma", "Gamma", "Gamma"), lifestage = factor(c("infant", "juvenile", "adult", "infant", "juvenile", "adult", "infant", "juvenile", "adult"),levels = c("infant", "juvenile", "adult")), age = c(10, 20, 30, 11, 21, 31, 9, 19, 29))
ggplot(x, aes(x = reorder(species, -age), y = age, fill = lifestage)) +
geom_bar(stat = "identity", position = position_stack(reverse = TRUE)) +
coord_flip()
How can I show the actual ages at which these events happen?
A: Figured it out - it's not a stacked graph I want, but a dodged graph with full overlap / no offset. position_dodge to the rescue!
ggplot(x, aes(x = reorder(species, -age), y = age, fill = lifestage)) +
geom_bar(stat="identity", position = position_dodge(width = 0), width = 2) +
coord_flip()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50414221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Change NavigationPage Backbutton color from DynamicResource Found this for change to change the color of the backbutton .
NavigationPage.SetIconColor(this, Color.FromHex("#FFFF00"));
The backgroudcolor of the page i change with DynamicResource.
Invul.xaml.cs
App.Current.Resources["defaultBackgroundColor"] = Preferences.Get("BackgroundColor", "#1D252D");
For the Backcolor of the backbutton i tryed this but not working because Color.FromHex i think ,can i change the FromHex part in to ?
NavigationPage.SetIconColor(this, Color.FromHex("{DynamicResource defaultBackgroundColor}"));
A: If you want to use color from ResourceDictionary , you can access it first and pass the result color to the second parameter of method NavigationPage.SetIconColor.
Please refer to the following code:
Color color = (Color)Application.Current.Resources["defaultBackgroundColor"];
NavigationPage.SetIconColor(this, color);
The defaultBackgroundColor is a color in Application.Resources:
<Application.Resources>
<ResourceDictionary>
<!-- Colors -->
<Color x:Key="defaultBackgroundColor">Red</Color>
<Color x:Key="Yellow">#ffd966</Color>
</ResourceDictionary>
</Application.Resources>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70113474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Join related Issue New to SQL
Suppose we have two tables
One has got the ID and Name column :
+----+-------+
| ID | Name |
+----+-------+
| 1 | Sam |
| 1 | Dan |
+----+-------+
and the second one has also got two columns as follow :
+----+------------+
| ID | Relatives |
+----+------------+
| 1 | Uncle |
| 2 | Aunty |
+----+------------+
If we do inner join we would only get the rows where the condition satisfies. But i want the output to be Like
+------+------------+
| ID | Relatives |
+------+------------+
| 1 | Uncle |
| NULL | Aunty |
+------+------------+
once only the value in the ID column should be shown. If the occurrence is twice or thrice it should come as null.
Just tell me if it is possible or not? and How for both the cases.
A: Try this:
SELECT
T1.Id,
T2.Relatives
FROM SecondTable T2
LEFT JOIN FirstTable T1
ON T1.ID = T2.ID
GROUP BY T1.Id,
T2.Relatives
This is what I get exactly:
CREATE TABLE #a (
id int,
name varchar(10)
)
CREATE TABLE #b (
id int,
name varchar(10)
)
INSERT INTO #a
VALUES (1, 'sam')
INSERT INTO #a
VALUES (1, 'Dan')
INSERT INTO #b
VALUES (1, 'Uncle')
INSERT INTO #b
VALUES (2, 'Aunty')
SELECT
T1.Id,
T2.name
FROM #b T2
LEFT JOIN #a T1
ON T1.ID = T2.ID
GROUP BY T1.Id,
T2.name
DROP TABLE #a
DROP TABLE #b
Output:
Id name
NULL Aunty
1 Uncle
Hope, this is what you ask in your question.
A: As your question is not clear, so assuming that you need to retrieve id from table a and name from table b and you also want to avoid duplicate rows, then an option could be to use distinct along with left join:
select distinct a.id, b.name
from b
left outer join a
on b.id = a.id
order by id desc
Result:
+------+-------+
| id | name |
+------+-------+
| 1 | Uncle |
| NULL | Aunty |
+------+-------+
DEMO
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47865507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating data.frame of multiple random samples from a vector in R? I have the vector X and I would like to generate a data.frame of 6 integer samples of size 4. In other words, I would like to have a data.frame of 6 * 4 dimension. I tried the following the following but its throwing out lenght argument error.
set.seed(123)
X <- c(4,10,15,100,50,31,311,225,85,91)
S <- replicate(X, sample.int(n = 6, size = 4))
A: We may need
replicate(4, sample(X, size = 6))
Or
replicate(6, sample(X, size = 4))
A: Another base R solution.
set.seed(123)
X <- c(4,10,15,100,50,31,311,225,85,91)
dat <- as.data.frame(lapply(1:4, function(i) sample(X, size = 6))) %>%
setNames(paste0("V", 1:4))
dat
# V1 V2 V3 V4
# 1 15 50 50 85
# 2 91 100 15 15
# 3 10 31 85 225
# 4 225 225 4 10
# 5 31 4 100 311
# 6 85 10 311 4
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69948643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to configure EC2 security group to permit loopback via public IP address? I have to run a program on an EC2 that reads the host's public IP address from config (which I don't appear to be able to easily change), and then connects to it, i.e. it's looping back to the instance via the public IP address.
I can't find out how to create a security group that can loopback to the the EC2 instance. My rules are:
outbound: 0.0.0.0/0 all tcp
inbound: [private IP/32, 127.0.0.1/32, public IP/32] all tcp 4440 (the port I need)
None of the inbound IPs work. I'm testing this by telnetting on the host to the public IP: telnet x.x.x.x 4440, and I'm never able to (where x.x.x.x is my public IP). I can do it by specifying 127.0.0.1 though, so the server I'm connecting to is online and bound correctly. I can also access the server through my browser. I just can't loopback. The connection hangs, which is why I think it's a security group issue.
How can I allow this program - which tries to connect to the public IP from the instance - to connect to the same instance by its public IP address?
A: I just did a test (using ICMP rule) , you have to add a rule in the security group as you said. you should add it normally, and set the source to 1.2.3.4/32 (following your example). please note that I am using Elastic IP in my tests.
A: According to the docs, it should also be possible to list that security group as its own source. This would permit the loopback even if the IP address changes due to a stop/start.
Another security group. This allows instances associated with the specified security group to access instances associated with this security group. This does not add rules from the source security group to this security group. You can specify one of the following security groups:
*
*The current security group
*A different security group for the same VPC
*A different security group for a peer VPC in a VPC peering connection
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34614609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Airflow 2.0.2 - SnowflakeHook can't read query located in directory we're moving to airflow 2.0 and I noticed the below error, it seems SnowflakeHook can't read the query located in our 'sql' directory, this was running fine in airflow 1.x:
snowflake.connector.errors.ProgrammingError: 001003 (42000):
019c5ac7-0602-31b5-0000-01b526e4fa46: SQL compilation error: syntax
error line 1 at position 0 unexpected 'sql'.
During handling of the above exception, another exception occurred:
common.snowflake.exceptions.SQLCompilationSnowflakeException: 001003
(42000): 019c5ac7-0602-31b5-0000-01b526e4fa46: SQL compilation error:
syntax error line 1 at position 0 unexpected 'sql'. Error occured
while processing query(019c5ac7-0602-31b5-0000-01b526e4fa46):
sql/my_query.sql
Below is the class we've created:
class SnowQueryOperator(BaseOperator):
template_fields = ['sql']
@apply_defaults
def __init__(self,
sql,
params=None,
warehouse=Variable.get('default_snowflake_warehouse'),
*args,
**kwargs):
super().__init__(*args, **kwargs)
self.sql = sql
self.params = params
self.warehouse = warehouse
def execute(self, context):
sf_hook = SnowflakeHook(warehouse=self.warehouse)
sf_hook.execute_query(self.sql)
and this is how we use it:
t4 = SnowQueryOperator(
task_id='running_snowflake_query',
sql='sql/my_query.sql',
retries=0,
pool='airflow')
A: I don't think this code worked on Airflow 1.10
you are missing template_ext that will allow you to read from .sql files.
class SnowQueryOperator(BaseOperator):
template_fields = ('sql')
template_ext = ('.sql',)
I'm not clear on why you implemented this operator on your own. Airflow has Snowflake provider which has SnowflakeOperator.
You can install it with pip install apache-airflow-providers-snowflake and then import the operator as from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67608655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Anyone know whats wrong with my code. Its not displaying anything in the console Getting the average grade and displaying the letter grade accordingly
const grade = [70, 90, 50] / 3;
switch (grade) {
case grade < 60:
console.log("F");
break;
case grade >= 60 && grade < 70:
console.log("D");
break;
case grade >= 70 && grade < 80:
console.log("C");
break;
case grade >= 80 && grade < 90:
console.log("B");
break;
case grade >= 100:
console.log("Congrats on your A!");
}
Thanks to anyone who can help!
A: This line const grade = [70, 90, 50] / 3; returns NaN So other condition with switch case will not work as you expected. I think you want to achieve this after calculating the average of the 3 subjects. You can find the sum of 3 subjects using Array.prototype.reduce() and Then use switch...case syntax properly. See more about switch-case
So try like this way,
const grade = [70, 90, 50].reduce((a, b) => a + b, 0) / 3;
switch (true) { // see this line
case grade < 60:
console.log("F");
break;
case grade >= 60 && grade < 70:
console.log("D");
break;
case grade >= 70 && grade < 80:
console.log("C");
break;
case grade >= 80 && grade < 90:
console.log("B");
break;
case grade >= 100:
console.log("Congrats on your A!");
}
OR Less typing with if..else if version without using break; though.
const grade = [70, 90, 50].reduce((a, b) => a + b, 0) / 3;
if(grade < 60)
console.log("F");
else if (grade >= 60 && grade < 70)
console.log("D");
else if (grade >= 70 && grade < 80)
console.log("C");
else if (grade >= 80 && grade < 90)
console.log("B");
else if (grade >= 100)
console.log("Congrats on your A!");
A: To get the average, you need to first add all the values in the array together before dividing them by the amount of grades there is:
const average = grades.reduce((acc, val) => acc + val, 0) / grades.length;
After that, you should use if/else-if blocks instead of switch to compare the values.
const grades = [70, 90, 50]
const average = grades.reduce((acc, val) => acc + val, 0) / grades.length;
console.log(average)
if (average < 60) console.log("F");
else if (average < 70) console.log("D");
else if (average < 80) console.log("C");
else if (average < 90) console.log("B");
else console.log("Congrats on your A!");
You don't need to check for the prior condition not applying (average >= 60 && and so on), since this uses else id, this also means that you don't need to specify a condition for the A grade, since all other conditions don't aplly.
A: If you put expressions in the case labels, then the switch value needs to be true or false (usually true).
That said, while you can put expressions in the case labels (in JavaScript, unlike many other languages), if...else if...else is more common.
Additionally, this line:
const grade = [70, 90, 50] / 3;
...sets grade to NaN, because the / coerces the array to a number, which goes by way of converting it to a string first ("70,90,50") and then "70,90,50" can't be implicitly converted to a number, so the result is NaN. NaN / 3 is NaN because any math operation with NaN results in NaN.
Finally, the last grade >= 100 condition looks dodgy. It means you aren't handling 90...99. You probably just want default (or else) there.
I assume you wanted to get the average grade instead, which you can do with reduce (or a simple loop):
const grade = [70, 90, 50].reduce((a, b) => a + b) / 3;
So doing that and using switch (true):
const grade = [70, 90, 50].reduce((a, b) => a + b) / 3;
switch (true) {
case grade < 60:
console.log("F");
break;
case grade >= 60 && grade < 70:
console.log("D");
break;
case grade >= 70 && grade < 80:
console.log("C");
break;
case grade >= 80 && grade < 90:
console.log("B");
break;
default:
console.log("Congrats on your A!");
}
You don't need those grade >= 60 && and such, since each case label is tested in source code order and the first one wins.
const grade = [70, 90, 50].reduce((a, b) => a + b) / 3;
switch (true) {
case grade < 60:
console.log("F");
break;
case grade < 70:
console.log("D");
break;
case grade < 80:
console.log("C");
break;
case grade < 90:
console.log("B");
break;
default: // Made this default instead
console.log("Congrats on your A!");
}
Or the if...else if...else version:
const grade = [70, 90, 50].reduce((a, b) => a + b) / 3;
if (grade < 60) {
console.log("F");
} else if (grade < 70) { //
console.log("D");
} else if (grade < 80) {
console.log("C");
} else if (grade < 90) {
console.log("B");
} else {
console.log("Congrats on your A!");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52261802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: mongodb-schema MongoDB Schema is used to validate if the incoming data is valid or not. | {
"language": "en",
"url": "https://stackoverflow.com/questions/64003704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Prettify JSON object alert I have a JSON object and when i alert it i get this:
and i want to get this:
function getNameById(id){
return usersArray.find(item => item.id === id).name;
}
var usersArray = [
{"id":"135","name":"Jenny"},
{"id":"162","name":"Kelly"}
];
$("#submit").click(function (e) {
var errors = {};
$(".validation").each(function(){
var worker_id = $(this).attr('id').replace(/[^\d]/g, '');
var w_name = getNameById(worker_id);
if(!errors[w_name]) errors[w_name] = [];
if ( $(this).val() == "" ) {
errors[w_name].push( $(this).attr('id').replace(/[^a-zA-Z]/g, '') + " must be filled!");
//errors[w_name].push("second number must be smaller than first");
}
if ( $(this).attr('id') == "second-"+worker_id && ($(this).val() > $('#first-'+worker_id+'').val())) {
errors[w_name].push("second number must be smaller than first");
}
});
alert(JSON.stringify(errors, null, 2));
e.preventDefault();
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
First<input id="first-135" class="validation" name="first" type="text" value="5"><br>
Second<input id="second-135" class="validation" name="second" type="text" value="8"><br>
Signature<input id="signature-135" class="validation" name="signature" type="text"><br>
<input id="submit" type="submit" value="Submit">
</form>
How can i achieve that?
A: Transform your object to a string like this
let obj = {
"Jenny" : [
"Second number must be smaller than first",
"Signature must be filled !"
]
};
let str = "";
Object.keys(obj).forEach(k => {
str += k + ":\n";
str += obj[k].join(",\n");
});
console.log(str);
A: Extract the data from the JSON data that you have in errors instead of running JSON.stringify directly. You should be able to get the data like this: errors["Jenny"] to get a list of the errors. Then combine them into a string according to your liking.
A: I honestly don't think your question has absolutely anything to do with JSON. The only reason why some JSON even shows up is because you're generating it for the alert():
alert(JSON.stringify(errors, null, 2));
// ^^^^^^^^^^^^^^ This generates JSON
If you want to concatenate some array items you can use a combination of the concatenation operator (+) and Array.join():
alert(w_name + ":\n" + errors[w_name].join(",\n"));
Tweak format to your liking.
var w_name = "Jenny";
var errors = {};
errors[w_name] = [];
errors[w_name].push("Second number must be smaller than first");
errors[w_name].push("Signature must be filled!");
alert(w_name + ":\n" + errors[w_name].join(",\n"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42830381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Homebrew broken and unable to install anything ~ % brew install curl
==> Downloading https://ghcr.io/v2/homebrew/core/brotli/manifests/1.0.9
Already downloaded: /Users/currentuser/Library/Caches/Homebrew/downloads/922ce7b351cec833f9bd2641f27d8ac011005f8b1f7e1119b8271cfb4c0d3cd7--brotli-1.0.9.bottle_manifest.json
Error: curl: Failed to download resource "brotli_bottle_manifest"
The downloaded GitHub Packages manifest was corrupted or modified (it is not valid JSON):
/Users/currentuser/Library/Caches/Homebrew/downloads/922ce7b351cec833f9bd2641f27d8ac011005f8b1f7e1119b8271cfb4c0d3cd7--brotli-1.0.9.bottle_manifest.json
My Homebrew is broken and is unable to install anything. A typical output is above
A: The problem was resolved after delete /Users/currentuser/Library/Caches/Homebrew/downloads/922ce7b351cec833f9bd2641f27d8ac011005f8b1f7e1119b8271cfb4c0d3cd7--brotli-1.0.9.bottle_manifest.json
and run brew install curl again
A: It might be using the installed curl instead of system curl.
From man brew
set HOMEBREW_FORCE_BREWED_CURL
A: I have also this problem with brew install php
the problem persists even after deleting all the files from
/Users/currentuser/Library/Caches/Homebrew/downloads/
and
brew install php again
i have also tried
HOMEBREW_FORCE_BREWED_CURL=1 brew install openssl
A: This command fixed the issue for me:
brew cleanup
A: same for brew install python
but I deleted folder under my username, don't know and searched right now whether or not exist Users/currentuser folder but result is ok
homebrew says ;
[email protected]
Python has been installed as
/usr/local/bin/python3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73300645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Lost internet in Azure VNET We ware moving couple of our VMs from one subnet to another via CLI not being sure what we were doing we did something and we lost outgoing internet access on all our VMs within a VNET. Luckily we use VPN to connect to our environment and we have access to our VMs via local IP addresses. But no any old or even new created VM has internet access, unless it has a public ip associated with it.
Our VNG and VMs are in the same VNET. Here is our effective routes and effective security rules on one of the VM. Would someone give me a hint where to look for?
UPDATE: Actually I just realized that there is an internet since when I curl google.com I get the following result ~$> curl google.com <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> <TITLE>301 Moved</TITLE></HEAD><BODY> <H1>301 Moved</H1> The document has moved <A HREF="http://www.google.com/">here</A>. </BODY></HTML> but the ping doesn't go through. What is it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53548566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Discord.py tasks.loop does not work and it returns no errors I've been trying to make loops in Discord.py, but I keep failing. What makes it harder is that it returns no errors.
This is the code;
import discord
import datetime
import time
import threading
import os
import json
import random
import asyncio
from discord.ext import commands
from discord.ext.commands import has_permissions
from discord.ext.tasks import loop
import keep_alive
prefix = "s."
token = str(os.getenv("TOKEN"))
client = commands.Bot(command_prefix = prefix)
client.remove_command("help")
os.chdir(r".")
ownerId = [219567539049594880]
logChn = 705181132672729098
secondsUp = 0
@loop(seconds=1)
async def add_second():
secondsUp+=1
print("+1 Second")
The console does not print anything. No errors. Is there anything I'm missing?
A: In discord.py, you must call the .start() method on every loop that you create. In this case, add_seconds.start(). Also, try adding global secondsUp to the top of your function definition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61946454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Failed to instantiate module myModule
Uncaught Error: [$injector:modulerr] Failed to instantiate module
myModule due to: Error: [$injector:nomod] Module 'myModule' is not
available! You either misspelled the module name or forgot to load it.
If registering a module ensure that you specify the dependencies as
the second argument.
<head>
<script src="Scripts/angular.js"></script>
<script src="Scripts/Script.js"></script>
</head>
<body ng-controller="myController">
<div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Likes</th>
<th>DisLikes</th>
<th>Likes/DisLikes</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="technology in technologies">
<td>{{ technology.name }}</td>
<td>{{ technology.likes }}</td>
<td>{{ technology.dislikes }}</td>
<td>
<input type="button" value="Like" ng-click="incrementLikes(technology)">
<input type="button" value="Dislike" ng-click="incrementDislikes(technology)">
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
var app = angular.module("myModule", [])
app.controller("myController", function($scope){
var technologies = [{name:"C#", likes:0, dislikes:0},
{name:"ASP.NET", likes:0, dislikes:0},
{name:"SQL Server", likes:0, dislikes:0},
{name:"Angular JS", likes:0, dislikes:0},];
$scope.technologies = technologies;
$scope.incrementLikes = function(technology){
technology.likes++;
}
$scope.incrementDislikes = function(technology){
technology.dislikes++;
}
});
A: You have not defined ng-app="myModule" in your html template.
Either define it in html or body tag then it should start working.
A: Just add ng-app="myModule" to your HTML ,
<body ng-app="myModule" ng-controller="myController">
DEMO
var app = angular.module("myModule", [])
app.controller("myController", function($scope){
var technologies = [{name:"C#", likes:0, dislikes:0},
{name:"ASP.NET", likes:0, dislikes:0},
{name:"SQL Server", likes:0,dislikes:0},
{name:"Angular JS", likes:0, dislikes:0},];
$scope.technologies = technologies;
$scope.incrementLikes = function(technology){
technology.likes++;
}
$scope.incrementDislikes = function(technology){
technology.dislikes++;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myModule" ng-controller="myController">
<div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Likes</th>
<th>DisLikes</th>
<th>Likes/DisLikes</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="technology in technologies">
<td>{{ technology.name }}</td>
<td>{{ technology.likes }}</td>
<td>{{ technology.dislikes }}</td>
<td>
<input type="button" value="Like" ng-click="incrementLikes(technology)">
<input type="button" value="Dislike" ng-click="incrementDislikes(technology)">
</td>
</tr>
</tbody>
</table>
</div>
</body>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46138615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I avoid passing a reference to a parent object when constructing a new instance of a class? I have two classes defined as follows.
First one:
internal class Content {
internal Content(Master master) {
// code omitted
}
// code omitted
}
second one:
public class Master {
internal Content content { get; set; }
internal Master() {
// code omitted
}
// code omitted
}
Exposing the Content Class as property of the Master I need to do something like this:
Master M = new Master();
M.content = new Content(M);
Is there a way to do not pass the Master (M) in the Content Consctructor?
A: Presumably Content needs a Master ? Actually, constructors are a fairly good way of managing this, but if that is a problem, you could also do something like:
internal class Content {
internal void SetMaster(Master master) {this.master = master; }
//...
}
internal class Master {
internal void SetContent(Content content) {
if(content == null) throw new ArgumentNullException("content");
// maybe handle double-calls...
this.content = content;
content.SetMaster(this);
}
}
...
Master M = new Master();
M.SetContent(new Content());
or have Master create the Content by default. Frankly, though, I'd leave it "as is" until there is an actual "this is a problem".
A: Why not use lazy initialisation idom?
public class Master
{
private Content _content;
internal Content content
{
get
{
if (_content == null)
{
_content = new Content(this);
}
return _content;
}
}
}
If Master always has to have content property set then create Content member during construction:
public class Master
{
internal Content content
{
get; private set;
}
internal Master()
{
content = new Content(this);
}
}
You may also use mixed approach:
public class Master
{
internal Content content
{
get; private set;
}
internal Content GetOrCreateContent()
{
if (content == null)
{
content = new Content(this);
}
return content;
}
internal Master()
{
}
}
A: Since the the code inside the classes is not shown, I have to make some assumptions what you intended to do. As I could see from your code, the Content needs a Master and the Master can't live without a Content.
With the solution I have made for you, you can do the following:
void Main()
{
Master M1 = new Master(); // content instantiated implicitly
Master M2 = new Content().master; // master instantiated implicitly
}
So you can either instantiate the Master and Content within is instantiated, or vice versa: Instantiate a Content and the Master is implicitly instantiated.
No matter which alternative you've chosen: The corresponding other object is always instantiated and available via the property variable.
The classes in this example are defined as follows:
internal class Content {
internal Master master { get; set; }
internal Content(Master pmaster) {
master=pmaster;
}
internal Content() {
master = new Master() { content = this };
}
}
public class Master {
internal Content content { get; set; }
internal Master() {
content = new Content(this);
}
// this is optional and can be omitted, if not needed:
internal Master(Content pcontent) {
content = pcontent;
}
}
Note that I kept the structure you gave in you question as closely as possible, while you have now extra flexibility.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11608628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: gvim Systemverilog syntax matching :is there way to match `ifdef `ifndef `else and `endif I have used standard SystemVerilog syntax packages but not able to match(with % move the cursor between) these strings. This is in the context of matchit function in Vim(https://www.vim.org/scripts/script.php?script_id=39).
The problem seems to be with backtick.
I tried:
\u0060
and
`ifdef\>|`ifndef\>:`endif\>,
but it does not work.
A: I'm assuming you have a file that looks like this:
stuff
`ifdef
some code
`endif
stuff
With the cursor on `ifdef (or `ifndef), you want to jump to `endif with % then back to `ifdef if you press % again. I'm also assuming you're using the matchit plugin.
Solution:
:let b:match_words='`ifdef\>\|`ifndef\>:`endif\>'
Notice that the | has to be escaped with a backslash. Also, you need quotation marks '. So the backticks were not the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66160327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: C++ Builder: interface that was marshalled for a different thread In order to use a COM object from a thread, I inserted CoInitialize(NULL) into the thread Execute function and CoUninitialize() into the Terminate function.
Everything works fine, except if the user aborts the thread by calling the Terminate function from the calling form.
It seems that the Terminate function called by a form is considered as another thread (Error message: 'The application called an interface that was marshalled for a different thread').
On the other hand I cannot put the code into a specific function to call by using Synchronize. This way makes the program still until the COM process of called function ends.
I know that functions to readdress the COM marshaling exist. But don't know exactly what to do. I did not find examples in C++, too.
Before asking help, I tried various ways to overcome the problem. Unfortunately I am here.
Here is my code:
class TThreadCamera : public TThread
{
private:
Variant Camera;
protected:
void __fastcall Execute();
public:
void __fastcall Terminate(TObject *Sender);
public:
__fastcall TThreadCamera();
};
-
__fastcall TThreadCamera::TThreadCamera()
: TThread(false)
{
}
//---------------------------------------------------------------------------
void __fastcall TThreadCamera::Execute()
{
FreeOnTerminate = true;
OnTerminate = &Terminate;
CoInitialize(NULL);
Camera = Variant::CreateObject("ASCOM.Simulator.Camera");
Camera.OlePropertySet("Connected", true);
Camera.OleProcedure("StartExposure", 60, true);
while ((! (bool) Camera.OlePropertyGet("ImageReady")))
Sleep 100;
}
//---------------------------------------------------------------------------
void __fastcall TThreadCamera::Terminate(TObject *Sender)
{
if (Camera.OlePropertyGet("CameraState") == 2) // Exposure currently in progress
Camera.OleProcedure("AbortExposure");
CoUninitialize();
}
//---------------------------------------------------------------------------
A: You need to call CoInitialize and CoUninitialize on the same thread, since they act on the calling thread. The OnTerminate event is always executed on the main thread.
So, remove your OnTerminate event handler, move that code into the thread, and so call CoUninitialize from the thread:
void __fastcall TThreadCamera::Execute()
{
FreeOnTerminate = true;
CoInitialize(NULL);
Camera = Variant::CreateObject("ASCOM.Simulator.Camera");
// code to operate on the camera goes here
CoUninitialize();
}
It would probably be prudent to protect the uninitialization inside a finally block.
A: In Delphi, if you need to call a thread termination code in the thread context, you should override the protected TThread.DoTerminate method instead of writing OnTerminate event handler.
A: The TThread.OnTerminate event is called in the context of the main UI thread. The virtual TThread.DoSynchronize() method, which the worker thread calls after Execute() exits, uses TThread.Synchronize() to call OnTerminate. DoTerminate() is always called, even if Execute() exits due to an uncaught exception, so overriding DoTerminate() is a good way to perform thread-specific cleanup.
CoInitialize() and CoUninitialize() must be called in the same thread. So, you must call CoUninitialize() inside of Execute(), or override DoTerminate(). I prefer the latter, as it reduces the need for using try/catch or try/__finally blocks in Execute() (an RAII solution, such as TInitOle in utilscls.h, is even better).
An apartment-threaded COM object can only be accessed in the context of the thread that creates it. So you must call the camera's CameraStateproperty and AbortExposure() procedure inside of Execute(), or override DoTerminate(), as well.
The TThread.Terminate() method simply sets the TThread.Terminated property to true, it does nothing else. It is the responsibility of Execute() to check the Terminated property periodically and exit as soon as possible. Your while that waits for the camera's ImageReady property to be true can, and should, check the thread's Terminated property so it can stop waiting when requested.
Try something more like this:
class TThreadCamera : public TThread
{
private:
bool init;
protected:
void __fastcall Execute();
void __fastcall DoTerminate();
public:
__fastcall TThreadCamera();
};
__fastcall TThreadCamera::TThreadCamera()
: TThread(false)
{
FreeOnTerminate = true;
}
void __fastcall TThreadCamera::Execute()
{
init = SUCCEEDED(CoInitialize(NULL));
if (!init) return;
Variant Camera = Variant::CreateObject("ASCOM.Simulator.Camera");
Camera.OlePropertySet("Connected", true);
Camera.OleProcedure("StartExposure", 60, true);
while (!Terminated)
{
if ((bool) Camera.OlePropertyGet("ImageReady"))
return;
Sleep(100);
}
if (Camera.OlePropertyGet("CameraState") == 2) // Exposure currently in progress
Camera.OleProcedure("AbortExposure");
}
void __fastcall TThreadCamera::DoTerminate()
{
if (init) CoUninitialize();
TThread::DoTerminated();
}
Or:
class TThreadCamera : public TThread
{
protected:
void __fastcall Execute();
public:
__fastcall TThreadCamera();
};
#include <utilcls.h>
__fastcall TThreadCamera::TThreadCamera()
: TThread(false)
{
FreeOnTerminate = true;
}
void __fastcall TThreadCamera::Execute()
{
TInitOle oleInit;
Variant Camera = Variant::CreateObject("ASCOM.Simulator.Camera");
Camera.OlePropertySet("Connected", true);
Camera.OleProcedure("StartExposure", 60, true);
while (!Terminated)
{
if ((bool) Camera.OlePropertyGet("ImageReady"))
return;
Sleep(100);
}
if (Camera.OlePropertyGet("CameraState") == 2) // Exposure currently in progress
Camera.OleProcedure("AbortExposure");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33720684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Will this code send a notification on this day every month? I have this code that should send a notification to the user on the same day every month. However I'm can't simulate this, so I can't test it. I was wondering if any of you could proof check it, to ensure it does send a notification every month.
Thanks
static func addNotification(){
let center = UNUserNotificationCenter.current()
let addRequest = {
let content = UNMutableNotificationContent()
content.title = "Test"
content.subtitle = "Test"
content.sound = UNNotificationSound.default
var dateComponents = DateComponents()
dateComponents.day = 31
dateComponents.hour = 12
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "", content: content, trigger: trigger)
center.add(request)
}
center.getNotificationSettings { settings in
if settings.authorizationStatus == .authorized{
addRequest()
}
else{
center.requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success{
addRequest()
}
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74950091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting a linux SDL2 program to run on a computer that does not have SDL2 installed? I recently developed a small SDL2 game. The game ran fine on my computer because I have SDL, SDL_image, SDL_mixer, and SDL_ttf installed. However, everyone who downloaded the game did not have SDL2 and the extensions installed, so they could not run the application. How can I make the application usable even for people who don't have SDL2 installed?
A: You can pass the -rpath option to ld to specify search directories for dynamic libraries.
Using -rpath . (-Wl,-rpath . to pass it from GCC) will enable loading the libraries from the executable's directory. Just put the appropriate .so files there and they will be found.
A: You could statically link you libs, that way no need to have SDL installed.
A way to do it :
g++ -o program [sources.cpp] -Wl,-Bstatic -lSDL2 -lSDL2_image \
-lSDL2_mixer -lSDL2_ttf -Wl,-Bdynamic [dynamically linked libs]
Note : If you use SDL2, you must use the SDL2 builds of peripheral libs otherwise you risk all kinds of errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33332053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: wrap each line into span tags (IE7) I got a script right now that works all browsers GTE IE8
And i need it to work in IE7 aswell can somebody tell me what i did wrong in this script
In this picture you see How it works in all other browsers and you see the dark area in IE7 is the bugged area cause the background is on the div and not on the line
Kode from IE7 and Chrome
last but not least my script to make this happen:
function padSubsequentLines(element) {
var words = element.innerHTML.split(' ');
element.innerHTML = '';
for (var i = 0; i < words.length; i++) {
element.innerHTML += '<span>' + words[i] + '</span> ';
}
var spans = element.childNodes;
var currentOffset = spans[0].offsetTop;
var html = '<span class="line">';
for (var i = 0; i < spans.length; i++) {
if (spans[i].nodeType === 3)
continue;
if (spans[i].offsetTop > currentOffset) {
html += '</span><span class="line">';
currentOffset = spans[i].offsetTop;
}
html += spans[i].innerHTML + ' ';
}
html += '</span>';
element.innerHTML = html;
}
Body tag htmlscript
<body onload="padSubsequentLines(document.getElementById('question_heading'));">
A: It's not really clear from the question exactly what you are trying to achieve. By reading through the code it seems you are wrapping each word in a span, and then using that span's location to work out whether or not it is on a new line, this then leads to each word on the same line being merged together inside a new span, each with class="line".
Whilst reading the offset position of a newly formed span — formed in the same block of code — could be causing your IE7 issue, because it's location information may not be recalculated yet... It really does beg the question as to why you are doing this? Especially if you take the name of your function padSubsequentLines into account.
If all you are doing is padding between lines of words you should use line-height: in your style/css.
update
I'd recommend — assuming you don't have direct access to the markup, which would have to be very likely — that you just stick with your first part of the code. This would be the part that wraps each word with a span. On these spans I'd then apply the class that applies the background colour you want, there should be no need to combine them into their constituent lines. This will remove the need to calculate offsetTop, and should even work for IE7. As I stated before, if you require padding between lines, use line-height.
function padSubsequentLines(element) {
var
words = element.innerHTML.split(' '),
count = words.length,
html = '',
i
;
for (i=0; i<count; i++) {
html += '<span class="background">' + words[i] + ' </span>';
}
element.innerHTML = html;
}
Note: You will need to make sure the spaces between words are kept within the spans, so that the background colour appears seemless.
After the above, if you still have problems with regard to the background colour stretching to fill the space in IE7, I'd look to your CSS definition for your span elements and make sure they aren't being overflow:hidden, zoom:1 or display:block.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15924407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: django built-in support for MongoDB I'm trying to find any information if official django is going to support any noSQL DBMS, especially MongoDB. I found a fork of django 1.3 the django-nonrel (a fork of official django) and some other not very reliable projects (failures occur often, according to comments I found on the web). Is django going to support noSQL officially at all?
A: Perhaps, there are other ways to achieve your goals, besides going noSQL.
In short, if you just need dynamic fields, you have other options. I have an extensive writeup about them in another answer:
*
*Entity–attribute–value model (Django-eav)
*PostgreSQL hstore (Django-hstore)
*Dynamic models based on migrations (Django-mutant)
Yes, that's not exactly what you've asked for, but that's all that we've currently got.
A: As you said, forked code is never the best alternative: changes take longer to get into the fork, it might break things... And even with django-nonrel, is not really Django as you loose things like model inheritance, M2M... basically anything that will need to do a JOIN query behind the scenes.
Is Django going to support NoSQL? As far as I know, there's no plans on the roadmap for doing so in the short run. According to Russell Keith-Magee on his talk on PyCon Russia 2013, "NoSQL" is on the roadmap but in the long term, as well as SQLAlchemy. So if you wanna wait, is going to take a long time, I'm afraid.
Anyway, even if it's not ideal, you still can use Django but use something else as a ORM. Nothing stops you from use vanilla Django and something like MongoDB instead of Django ORM.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16132692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: possible to run sql query without any user action? I want to know if it possible to run sql query when the other server send data to my server with post method. there is no user action. it direct send data from server to server.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$servername = "localhost";
$username = "test";
$password = "test123";
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$selected = mysql_select_db("test",$conn) or die("Could not select examples");
$sql = "INSERT INTO `tablename`.`test` (`id`, `startdate`, `enddate`) VALUES (NULL, '2016-09-08', '2016-09-09');";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
}
?>
It is possible to run query without any user action? Thanks.
A: There is a backend - frontend way how to comunicate between client and server. I know it doesn't sound like what you want but it is.
How does it work:
Because backend get request from client and base on this request he do something (e.g. make SQL Select).
In your case your client will be another server. And request will not come from some .js but instead from another .php file. However it still works same way.
Very basic example:
This is server which send data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/server.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1");
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
this is server which wait for request:
if(isset($_POST['postvar1'])) {
$data = $_POST['postvar1'];
// Here comes your logic..
}
A: Yes you can run a query without a user doing anything. You also don't want to use mysql_*. You might want to look at mysqli_* functions, or PDO.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39383942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: how to replace the deprecated android.text.format class? how can i implement the code below using the GregorianCalendar.
Thanks.
Time dayTime = new Time();
dayTime.setToNow();
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(),dayTime.gmtoff);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36900433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Which version of Javascript Note: I know this is probably a simple and basic question but I just started to learn Javascript a couple of year ago when all these changes started taking place and it seems I learned the old version.
I'm confused with Javascript. I'm trying to implement a basic MEAN stack. I'm using es6 Javascript with Nodejs (6.x) on the server side. Then for the client side, I'm using Angular 1.5 in es5 Javascript, but it seems to not be working.
Is is possible to mix es6 on server-side and use es5 on client-side OR is all or nothing... all es6 on both server/client or vice versa?
UPDATE Thanks for all the info. I've been looking at ES6(ES2015) and it doesn't seem that hard, I've even written some code in it with success. However, I just got a handle on Angular 1 a while back and then it seems like Angular 1.6 and up came out and was quite different. Angular 1 had quite the learning curve, how hard would it be to update my Angular 1 code into 1.6 or above? Is the newer Angular written in ES6? All frontend JS written in ES6 needs a tranpiler or can browsers handle ES6 now?
A:
Is is possible to mix es6 on server-side and use es5 on client-side
Yes you could mix both. But be aware that sharing code between both could be tricky.
is all or nothing... all es6 on both server/client or vice versa?
That's not the case here, but I would recommended to use on both sides es6 and convert to es5 for the browser, eg with Babel
A:
Is is possible to mix es6 on server-side and use es5 on client-side OR is all or nothing... all es6 on both server/client or vice versa?
It's possible to mix entirely separate languages on the server and client, such as PHP or Java or Ruby or C# on the server and JavaScript on the client. So yes, it's just fine if you want to use ES2015 (aka "ES6") and later features in your server-side Node code and restrict yourself to ES5 and earlier features in your client-side browser code.
You don't have to, though, and it's surprisingly hard once you get used to writing let and const and arrow functions to make yourself not write them in your client-side code by accident. So for that reason, you might consider using ES2015+ plus both server-side and client-side, and "transpiling" your client-side code from ES2015+ down to ES5 for use on older browsers. There are multiple transpilers, such as Babel. You can develop with an up-to-date browser such as Chrome or Firefox or Edge, and then have your build tool make the "production" build pass all the client-side code through Babel (perhaps with Webpack or Browserify or similar) for use on older browsers such as IE11.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43664851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I replace substring in a file name? I'm attempting to replace the substring "Dog_1" with "Dog_2" for every file in my directory using sed.
The file names look like this: Dog_1_interictal_segment_0472.csv
Here is the command I'm using:
sed -i '' s/Dog_1/Dog_2/g *.csv
For some reason the substring isn't being replaced.
A: Oh, you're trying to rename the files? You can't use sed for that; that changes the contents of the files, without renaming them. Here's how I might do the renaming:
for a in Dog_1*.csv; do
mv "$a" "Dog_2${a#Dog_1}"
done
A: Since the question regards renaming of files, you may be better off renameing them.
This application has syntax quite similar to sed's:
rename 's/Dog_1/Dog_2/' *.csv
And you may as well perform global renamings, if that is the case:
rename 's/Dog_1/Dog_2/g' *.csv
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26644213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sum and multiplication of values in JTable I can not view each value on the same line. It is displayed per column. Every dealer in the total column line should display the sum of all values.
I do not know how to display line by line.
String[]entete= {"Revendeur/Montant","5000","3000","1500","800","600","500","400","REMISE","TOTAL","CREANCE"};
Object [][]donnees= {{"Patrick",0,0,0,0,0,0,0,0,0,""},
{"Marie",0,0,0,0,0,0,0,0,0,""},
{"Christian",0,0,0,0,0,0,0,0,0,""},
{"Fabian",0,0,0,0,0,0,0,0,0,""},
{"TOTAL",0,0,0,0,0,0,0,0,0,""}};
private void setTableModelListener() {
tableModelListener = new TableModelListener() {
public void tableChanged(TableModelEvent e) {
int lastRow = model.getRowCount()-1 ;
int lastColumn = model.getColumnCount()-2 ; //Colonne total
int rowCount = model.getRowCount();
if (e.getType() == TableModelEvent.UPDATE && e.getColumn() < lastColumn && e.getFirstRow() < lastRow && e.getLastRow() < lastRow ) {
int row = rowCount;
int value = 0;// on initialise le résultat
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int value6 = 0;
for (int i = 0; i < row; i++) {
value += 5000*(int) model.getValueAt(i, 1); // cumul montant
value1 += 3000*(int) model.getValueAt(i, 2);
value2 += 1500*(int) model.getValueAt(i, 3);
value3 += 800*(int) model.getValueAt(i, 4);
value4 += 600*(int) model.getValueAt(i, 5);
value5 += 500*(int) model.getValueAt(i, 6);
value6 += 400*(int) model.getValueAt(i, 7);
}
model.setValueAt(value, 0, lastColumn);
model.setValueAt(value1, 1, lastColumn);
}
}
};
}
A: Override getValueAt() in your TableModel to return the correct value for cells in the TOTAL row and column. The correct value may be calculated by invoking getValueAt() in a loop, as shown in your TableModelListener example. In this complete example, the value shown in each row of the second column depends on the value chosen in the third column of the same row.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33912942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I generate both XML and HTML reports from the Findbugs plugin in Gradle Right now I have FindBugs in my build.gradle as follows
apply plugin: 'findbugs'
findbugs {
ignoreFailures = true
}
tasks.withType(FindBugs) {
reports {
xml.enabled = false
html.enabled = true
}
}
But if I try to enable both the HTML report (for developers to view on their machines) and the XML report (for my jenkins CI machines) I get the following
FindBugs tasks can only have one report enabled, however more than
one report was enabled. You need to disable all but one of them.
is there some way / hack to enable me to generate both - even via two different tasks?
A: You probably can, but in the current state of the plugin, it looks like you have to define a separate task that extends from the FindBugs one, but has a different configuration than the standard one.
The problem is that you will run FindBugs twice indeed, and that can be a performance penalty with any decently-sized codebase.
Obviously you can't use tasks.withType(FindBugs) { ... } to configure your tasks, you have to do it by task name explicitly.
Note: if you are running this on e.g. Jenkins, you would want your build.gradle to generate the xml report, and let Jenkins generate the html report from the xml one. That way it is not executed twice in your build.
A: I solved this by configuring my Gradle script so that it generates findbugs tasks for XML and HTML reports then generates a task which depends on the other two.
def findbugsTask = task('findbugs') {
group 'Verification'
}
[ 'Html', 'Xml' ].each { reportType ->
findbugsTask.dependsOn task("findbugs${reportType}", type: FindBugs) {
dependsOn 'compileJavaWithJavac'
reports {
html.enabled = reportType == 'Html'
xml.enabled = reportType == 'Xml'
}
}
}
Note that this will run the Findbugs tool twice, which generally shouldn't be an issue for continuous integration (unless your code base is huge).
A: You can generate both reports without running FindBugs twice, but it isn't intuitive. If you look at how FindBugs generates its html report, you'll find it actually generates the xml first and just uses xslt to transform it into html. Knowing this, and subsequently resourcing a spotbugs issue that documented a workaround, I got the same approach working with FindBugs.
In my build.gradle file I am generating just the xml report, and running a new task afterwards that converts the xml report to html using one of the FindBugs provided stylesheets.
import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource
import static org.gradle.api.tasks.PathSensitivity.NONE
configurations {
findbugsStylesheets { transitive false }
}
dependencies {
findbugsStylesheets 'com.google.code.findbugs:findbugs:3.0.1'
}
tasks.withType(FindBugs) {
maxHeapSize = "6g"
reports {
xml.enabled = true
xml.withMessages true
html.enabled = false
html.stylesheet resources.text.fromArchiveEntry(configurations.findbugsStylesheets, 'fancy.xsl')
}
task "${it.name}HtmlReport" {
def input = reports.xml.destination
inputs.file reports.html.stylesheet.asFile() withPropertyName 'findbugsStylesheet' withPathSensitivity NONE
inputs.files fileTree(input) withPropertyName 'input' withPathSensitivity NONE skipWhenEmpty()
def output = file(input.absolutePath.replaceFirst(/\.xml$/, '.html'))
outputs.file output withPropertyName 'output'
doLast {
def factory = TransformerFactory.newInstance('net.sf.saxon.TransformerFactoryImpl', getClass().classLoader)
def transformer = factory.newTransformer(new StreamSource(reports.html.stylesheet.asFile()));
transformer.transform(new StreamSource(input), new StreamResult(output))
}
}
it.finalizedBy "${it.name}HtmlReport"
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39398755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to compare different values in two Excel files I have two Excel files 2A.xlsx and Purchase Register.xlsx
2A.xlsx looks like this:
Purchase Register.xlsx look like this::
I want to have my filtered output (in new Excel file) in format like this: [ Sample filtered data][3]
[3]: https://i.stack.imgur.com/1Iuhc.png
Here "Exact" are the doc numbers which have same tax amount
"Mismatch" means those doc numbers which have different tax amount
"Addition in 2A" means that those doc numbers which doesn't have any information in their corresponding Purchase Register (PR) file
"Addition in PR" means that those doc numbers which doesn't have any information in their corresponding 2A file
How can I do this in Python? I was using pandas library for it but was unsuccessful, really struggling with this problem for a week. Does anyone know how can I do this?
A: Using Pandas (as you suggested), you can do an outer-join style merge of the two tables, keyed on the document ID. This will give you a dataframe where each row contains all of the information you need.
import pandas as pd
df1 = pd.DataFrame([[1, 1, "Desc 1"], [2, 2, "Desc 1"], [3, 3, "Desc 3"]],
columns=["Doc Number", "Tax Amount 2A", "Description 2A"])
df2 = pd.DataFrame([[1, 1, "Desc 4"], [2, 20, "Desc 5"], [4, 4, "Desc 6"]],
columns=["Doc Number", "Tax Amount PR", "Description PR"])
combined = pd.merge(df1, df2, how="outer", on="Doc Number")
combined.head()
Doc Number Tax Amount 2A Description 2A Tax Amount PR Description PR
1 1.0 Desc 1 1.0 Desc 4
2 2.0 Desc 1 20.0 Desc 5
3 3.0 Desc 3 NaN NaN
4 NaN NaN 4.0 Desc 6
From there, you can apply a function to each row and do the comparison of the values to produce the appropriate rule.
def case_code(row):
if row["Tax Amount 2A"] == row["Tax Amount PR"]:
return "exact"
elif pd.isna(row["Tax Amount 2A"]):
return "Addition in PR"
elif pd.isna(row["Tax Amount PR"]):
return "Addition in 2A"
elif row["Tax Amount 2A"] != row["Tax Amount PR"]:
return "mismatch"
codes = combined.apply(case_code, axis="columns")
codes
Doc Number
1 exact
2 mismatch
3 Addition in 2A
4 Addition in PR
dtype: object
The key part is to apply to each row (with axis="columns") instead of the default behavior of applying to each column.
The new codes can be added to the combined dataframe. (The 2nd line just makes the new codes the first column to match your example by re-arranging the columns and not strictly-speaking required.)
answer = combined.assign(**{"Match type": codes})
answer[["Match type"] + [*combined.columns]]
Match type Doc Number Tax Amount 2A Description 2A ...
exact 1 1.0 Desc 1 ...
mismatch 2 2.0 Desc 2 ...
Addition in 2A 3 3.0 Desc 3 ...
Addition in PR 4 NaN NaN ...
(Final table isn't showing all the columns because I couldn't get it to format correctly.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69356183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Interstitial Ads not getting displayed after every 7 swipe I am new to android, I have added facebook interstitial ads code to display ads after every 7 swipe but my code only displays Interstitial ads once. Could you please help me out how to fix this issues? Banner ads are working fine. But I am not able to troubleshoot the Interstitial ads any suggestion or help is highly appreciated.
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.facebook.ads.*;
import com.abc.shareactionprovider.content.ContentItem;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// The items to be displayed in the ViewPager
private final ArrayList<ContentItem> mItems = getSampleContent();
// Keep reference to the ShareActionProvider from the menu
private ShareActionProvider mShareActionProvider;
private InterstitialAd interstitialAd;
//final int counter = 0;
private AdView adView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set content view (which contains a CheeseListFragment)
setContentView(R.layout.sample_main);
// Retrieve the ViewPager from the content view
ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
// Set an OnPageChangeListener so we are notified when a new item is selected
//vp.setOnPageChangeListener(mOnPageChangeListener);
vp.addOnPageChangeListener(mOnPageChangeListener);
// Finally set the adapter so the ViewPager can display items
vp.setAdapter(mPagerAdapter);
adView = new AdView(this, "1111122222333333", AdSize.BANNER_HEIGHT_50);
LinearLayout adContainer = (LinearLayout) findViewById(R.id.banner_container);
adContainer.addView(adView);;
// Start loading the ad in the background.
adView.loadAd();
interstitialAd = new InterstitialAd(this, "33333344444444");
interstitialAd.loadAd();
}
// BEGIN_INCLUDE(get_sap)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu resource
getMenuInflater().inflate(R.menu.main_menu, menu);
// Retrieve the share menu item
MenuItem shareItem = menu.findItem(R.id.menu_share);
// Now get the ShareActionProvider from the item
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
// Get the ViewPager's current item position and set its ShareIntent.
int currentViewPagerItem = ((ViewPager) findViewById(R.id.viewpager)).getCurrentItem();
setShareIntent(currentViewPagerItem);
return super.onCreateOptionsMenu(menu);
}
// END_INCLUDE(get_sap)
/**
* A PagerAdapter which instantiates views based on the ContentItem's content type.
*/
private final PagerAdapter mPagerAdapter = new PagerAdapter() {
LayoutInflater mInflater;
@Override
public int getCount() {
return mItems.size();
}
@Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Just remove the view from the ViewPager
container.removeView((View) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// Ensure that the LayoutInflater is instantiated
if (mInflater == null) {
mInflater = LayoutInflater.from(MainActivity.this);
}
// Get the item for the requested position
final ContentItem item = mItems.get(position);
// The view we need to inflate changes based on the type of content
switch (item.contentType) {
case ContentItem.CONTENT_TYPE_TEXT: {
// Inflate item layout for text
TextView tv = (TextView) mInflater
.inflate(R.layout.item_text, container, false);
// Set text content using it's resource id
tv.setText(item.contentResourceId);
// Add the view to the ViewPager
container.addView(tv);
return tv;
}
case ContentItem.CONTENT_TYPE_IMAGE: {
// Inflate item layout for images
ImageView iv = (ImageView) mInflater
.inflate(R.layout.item_image, container, false);
// Load the image from it's content URI
iv.setImageURI(item.getContentUri());
// Add the view to the ViewPager
container.addView(iv);
return iv;
}
}
return null;
}
};
private void setShareIntent(int position) {
// BEGIN_INCLUDE(update_sap)
if (mShareActionProvider != null) {
// Get the currently selected item, and retrieve it's share intent
ContentItem item = mItems.get(position);
Intent shareIntent = item.getShareIntent(MainActivity.this);
// Now update the ShareActionProvider with the new share intent
mShareActionProvider.setShareIntent(shareIntent);
}
// END_INCLUDE(update_sap)
}
/**
* A OnPageChangeListener used to update the ShareActionProvider's share intent when a new item
* is selected in the ViewPager.
*/
private final ViewPager.OnPageChangeListener mOnPageChangeListener
= new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// NO-OP
if(interstitialAd.isAdLoaded()) {
if (position % 7 == 0) {
interstitialAd.show();
}
}
}
@Override
public void onPageSelected(int position) {
setShareIntent(position);
}
@Override
public void onPageScrollStateChanged(int state) {
// NO-OP
}
};
/**
* @return An ArrayList of ContentItem's to be displayed in this sample
*/
static ArrayList<ContentItem> getSampleContent() {
ArrayList<ContentItem> items = new ArrayList<ContentItem>();
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i1.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i2.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i3.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i4.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i5.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i6.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i7.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i8.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i9.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i10.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i11.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i12.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i13.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i14.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i15.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i16.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i17.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i18.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i19.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i20.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i21.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i22.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i23.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i24.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i25.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i26.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i27.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i28.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i29.jpg"));
items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "i30.jpg"));
return items;
}
}
A: Yes it shows only once because you are loading the ads at once only in the onCreate() than you will displayed it once. But when you are displaying the ads once than after you have to load it again for display them after next 7 views. So please create one method for that and call each and every time before your ads will gonna be to display/show.
This is the example code :-
public void loadInterstitial() {
// Instantiate an InterstitialAd object
AdSettings.addTestDevice("350cf676a5848059b96313bdddc21a35");
interstitialAd = new InterstitialAd(MainActivity.this, getString(R.string.ins_ads_id));
interstitialAd.loadAd();
// Set listeners for the Interstitial Ad
interstitialAd.setAdListener(new InterstitialAdListener() {
@Override
public void onInterstitialDisplayed(Ad ad) {
Log.v("OkHttp", ad.toString());
}
@Override
public void onInterstitialDismissed(Ad ad) {
Log.v("OkHttp", ad.toString());
}
@Override
public void onError(Ad ad, AdError adError) {
Log.v("OkHttp", ad.toString() + " " + adError.getErrorCode() + " " + adError.getErrorMessage());
}
@Override
public void onAdLoaded(Ad ad) {
Log.v("OkHttp", ad.toString());
showInterstitial();
}
@Override
public void onAdClicked(Ad ad) {
Log.v("OkHttp", ad.toString());
}
@Override
public void onLoggingImpression(Ad ad) {
Log.v("OkHttp", ad.toString());
}
});
}
public void showInterstitial() {
interstitialAd.show();
}
And Put this ad id into your string.xml of the project.
<string name="ins_ads_id">222591425151579_222592145151XXX</string>
Change your onPageScrolled code to this.
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// NO-OP
if (position % 7 == 0) {
loadInterstitial();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50480507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change line properties on a plot from a different function I'm stuck with something which is probably easy to fix, but I couldn't find anybody having this same issue on the internet.
I'm using matplotlib to plot some datas.
def drawFigure(self):
global figure
figure = plt.figure()
canvas = FigureCanvas(figure)
graph = figure.add_subplot(111)
line = graph.plot(...,...,'-',linewidth=2)
canvas.draw()
plt.setp(line, linewidth=10) #Works fine
def changeLineThickness(self):
plt.setp(line, linewidth=1) #Nothing changes
The function drawFigure is called first. The linewidth is set to 2 and then immediatly set to 10, so this plt.setp code works fine.
However, when I call after drawFigure the changeLineThickness function, the plt.setp does nothing and the thickness remains 10.
What am I doing wrong here?
A: Ok so could make this work by redrawing the canvas in the function.
I don't really understand why the line got updated after the canvas.draw() call in the first function and why I have to redraw in the second function.
def changeLineThickness(self):
plt.setp(line, linewidth=1)
canvas.draw()
Maybe there is a faster way to do this rather than redrawing the whole canvas.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30169756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Scraping into different pages Im trying to scrap a web page, and after following some tutorials, i found how to scrap different products, and how to change the page, but not at the same time. I tryed some ways to do it, but couln't find out.
This is my scraping code:
const puppeteer = require('puppeteer');
const xlsx = require("xlsx");
async function getPageData(url,page){
await page.goto(url);
const h1 = await page.$eval(".product_main h1", h1 => h1.textContent);
const price = await page.$eval(".price_color", price => price.textContent);
const instock = await page.$eval(".instock.availability", instock => instock.innerText);
return {
title: h1,
price: price,
instock: instock
}
//await browser.close();
};
async function getLinks(){
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.goto('https://books.toscrape.com/');
const links = await page.$$eval('.product_pod .image_container a', allAs =>
allAs.map(a => a.href));
}
async function main(){
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
const data = await getPageData("https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html",page);
console.log(data);
}
main();
And here is my code to change the page:
const puppeteer = require('puppeteer');
const xlsx = require("xlsx");
(async () => {
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.goto('https://books.toscrape.com/');
while(await page.$(".pager .next a")){
await page.click(".pager .next a");
await page.waitForTimeout(3000);
}
})();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72095854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Function of Fullcalendar plugin dont insert correctly on mysql table Im using FullCalendar plugin to have a web calendar and show/insert events from my mysql table. It shows correctly the events from the bd but dont insert the date of the event in the correct format. (YYYY-MM-DD). Both columns of the mysql table are DATE type with the same format of the event that will be insert.
This is my JS script to show events and insert via ajax to mysql
$(document).ready(function() {
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yyyy = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
editable: true,
events: "http://localhost/test-fullcalendar/php/eventos.php",
lang: "es",
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
var title = prompt('Evento a insertar:');
if (title) {
start = $.fullCalendar.moment('yyyy mm dd');
end = $.fullCalendar.moment('yyyy mm dd');
$.ajax({
url: 'http://localhost/test-fullcalendar/php/add_evento.php',
data: 'title='+ title+'&start='+ start +'&end='+ end ,
type: "POST",
success: function(json) {
alert('OK');
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true
);
}
calendar.fullCalendar('unselect');
}
});
});
The problem is with the function moment() of Fullcalendar on lines:
start = $.fullCalendar.moment('yyyy mm dd');
end = $.fullCalendar.moment('yyyy mm dd');
The function dont receive correctly the actual date and only insert "0000-00-00" on my table. I try to pass the date in the moment() argument like:
var date = yyyy + '-' + mm + '-' + dd;
start = $.fullCalendar.moment(date);
But it insert "0000-00-00" too.
A: the javascript function date.getMonth() would return 2 for the month March, but you want '03'
so use this:
var mm = date.getMonth()+1;
mm=(mm<=9)?'0'+mm:mm;
A: Your formatting is incorrect so you are actually returning NaN.
Where you are passing 'yyyy mm dd', you should instead be passing the start variable, so:
$.fullCalendar.moment('yyyy mm dd');
should be
$.fullCalendar.moment(start).format('YYYY MM DD');
Additionally, note that your date format needs to be uppercase, per the Moment.js site, and can more simply be written as moment(start).format('YYYY MM DD');
DEMO
$('#fullCal').fullCalendar({
header: {
left: '',
center: 'prev title next today',
right: ''
},
selectable: true,
select: function(start, end, allDay) {
var title = prompt('Evento a insertar:');
if (title) {
start = moment(start).format('YYYY MM DD');
end = moment(end).format('YYYY-MM-DD'); /* w/ dashes if that is what you need */
alert('start: ' + start + ' end: ' + end);
/*rest of your code... */
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.1.1/fullcalendar.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.1.1/fullcalendar.min.js"></script>
<div id="fullCal"></div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29064377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Typescript: Type guards not working as expected when using nested readonly property Quality can be good or bad, depending upon the type. Here type guards are working fine
enum GoodBad {
Good = 'Good',
Bad = 'Bad'
}
interface IQuality {
readonly type: GoodBad;
}
interface GoodQuality extends IQuality {
readonly type: GoodBad.Good;
}
interface BadQuality extends IQuality {
readonly type: GoodBad.Bad;
}
type Quality = GoodQuality | BadQuality;
let quality: Quality;
if (quality.type == GoodBad.Good) {
let goodQuality: GoodQuality = quality; // No Problem. Working good.
let badQuality: BadQuality = quality; // Throw error. Working good.
}
But now when I wrap quality in Product then
interface IProduct {
readonly quality: Quality;
}
interface GoodProduct extends IProduct {
readonly quality: GoodQuality;
}
interface BadProduct extends IProduct {
readonly quality: BadQuality;
}
type Product = GoodProduct | BadProduct;
let product: Product;
if (product.quality.type == GoodBad.Good) {
let goodProduct: GoodProduct = product; // Throw error. Working Bad.
// let badProduct: BadProduct = product; // Throw error. Working fine.
}
Type guard don't work as intended.
*
*Whats the difference b/w this if block and previous if block?
*let goodProduct: GoodProduct = product; why it is throwing error?
*One solution is to create another readonly type: GoodBad on IProduct. But this is extra, can this be eliminated?
A: The type guard will affect the quality field, not the product variable. Type-guards only impact the field that owns the discriminating field; it does not affect the owner.
So this works:
type Product = GoodProduct | BadProduct;
let product!: Product;
if (product.quality.type == GoodBad.Good) {
let goodQuality: GoodQuality = product.quality; // Ok
let badQuality: BadQuality = product.quality; // Err
let goodProduct: GoodProduct = product; // Err, product not affected
let badProduct: BadProduct = product; // Err, product not affected
}
Your solution of adding an extra field is a good one, another would be to create a custom type guard:
function isGoodProduct(p: Product) : p is GoodProduct {
return p.quality.type === GoodBad.Good
}
if (isGoodProduct(product)) {
let goodProduct: GoodProduct = product; // OK
let badProduct: BadProduct = product; // Err
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49939573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Insert text at cursor position failing on blank lines I'm using this native javascript method in GWT to insert text at the cursor position of a RichTextArea. It works sometimes but often gives me this error message: "refNode.insertData is not a function. It seems to happen whenever the cursor is on a blank line.
public native void insertText(String text, int pos) /*-{
var elem = [email protected]::getElement()();
var refNode = elem.contentWindow.getSelection().getRangeAt(0).endContainer;
refNode.insertData(pos, text);
}-*/;
So I need to debug this javascript and don't know where to begin. I know very little about javascript and only got this method I'm using off a stack question. I'm getting the cursor position from another native method I copied from this question.
I read that this error is because refNode isn't the correct type of object. I figured somebody would know what type of object it actually is and can help me handle this situation.
A: I am assuming that the problem is the refNode is not the correct type. One possible solution is to check the type of refNode, and if it is not of type TEXT_NODE, create a text node and add it to refData. The code would look something like:
public native void insertText(String text, int pos) /*-{
var elem = [email protected]::getElement()();
var refNode = elem.contentWindow.getSelection().getRangeAt(0).endContainer;
if(refNode.nodeType == 3){
var newTxtNode = document.createTextNode(text);
refNode.appendChild(newTxtNode);
} else {
refNode.insertData(pos, text);
}
}-*/;
The nodeType can be found here.
A: So I have this working I think. I changed Matthew's answer a bit and it seems to work in all my tests. When refNode equals Element type, I guess the pos value was always the index of the child node element where I needed to insert before.
public native void insertText(String text, int pos) /*-{
var elem = [email protected]::getElement()();
var refNode = elem.contentWindow.getSelection().getRangeAt(0).endContainer;
if (refNode.nodeType == 1) {
var newTextNode = document.createTextNode(text);
refNode.insertBefore(newTextNode, refNode.childNodes[pos]);
} else {
refNode.insertData(pos, text);
}
}-*/;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17112095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cannot start ClickOnce application from Microsoft Edge Beta (Chromium version) on one computer
*
*I downloaded the insider version of Microsoft Edge (Version 79.0.309.25).
*Enabled ClickOnce: edge://flags/#edge-click-once
*Tried to start ClickOnce Application from a browser.
This has worked as expected on 4 computers now, but not my own computer (even though it works with the stable version of Edge 44.18362.449.0).
I can see from the developer tool's network tab that the request is sent, and the request/response headers looks the same as in stable Edge (except user-agent). The console gives me the following warning message which I suspect is (part) of the reason it does not work:
Resource interpreted as Document but transferred with MIME type
application/x-ms-application: "_my_clickonce_url_".
UPDATE: Apparently this does show for working computers aswell, I was mistaken.
I do not get this message on the other computers that are working fine.
Searching for this message gives me alot of hits (but for other mime-types), for example:
*
*Resource interpreted as Document but transferred with MIME type
application/zip
*Chrome says: “Resource interpreted as Document but transferred with MIME type application/vnd.openxmlformats-officedocument.wordprocessingml.document”
*Correct headers, but Chrome says “Resource interpreted as Document”
They suggest fixes such as adding a download attribute to the link (which does not work in my case), or changing the returned content-type (which should be correct in my case). There seems to be some code related changes, but I suspect my issue is environmental since it only fails on one computer out of 5.
One answer also suggested to check the regestry editor for Computer\HKEY_CLASSES_ROOT\, but this also looks the same as other computer that works (.application maps to content type application/x-ms-application).
I suspect this might be more of a Microsoft support ticket than a stack overflow question, but I guess it depends on where the problem is. So I thought I'd start here.
running SystemInfo.exe in cmd gives following (large chunk redacted):
OS Name: Microsoft Windows 10 Enterprise
OS Version: 10.0.18362 N/A Build 18362
System Manufacturer: Hewlett-Packard
System Model: HP Z230 Tower Workstation
System Type: x64-based PC
Hotfix(s): 6 Hotfix(s) Installed.
[01]: KB4506991
[02]: KB4503308
[03]: KB4506472
[04]: KB4509096
[05]: KB4524569
[06]: KB4524570
Comparison of request headers of a working version:
:authority: _redacted_host_
:method: GET
:path: _path_/_AppName_.application?url=https://_redacted_host_:443/_redacted_endpoint_
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
referer: _redacted_url_
sec-fetch-mode: navigate
sec-fetch-site: same-origin
sec-fetch-user: ?1
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.36 Safari/537.36 Edg/79.0.309.25
and a my non-working version:
:authority: _redacted_host_
:method: GET
:path: _path_/_AppName_.application?url=https://_redacted_host_:443/_redacted_endpoint_
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
accept-encoding: gzip, deflate, br
accept-language: sv,en;q=0.9,en-GB;q=0.8,en-US;q=0.7
referer: _redacted_url_
sec-fetch-mode: navigate
sec-fetch-site: same-origin
sec-fetch-user: ?1
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.36 Safari/537.36 Edg/79.0.309.25
And as you can see, they are exactly the same except for the accept-language.
Update:
Running Process Monitor (procmon.exe) and comparing results between working and non-working machine I find that the ClickOnce Launcher process (dfsvc.exe) never starts on my computer.
msedge.exe goes and checks the following registry key:
HKCR\MIME\Database\Content Type\application/x-ms-application\Extension
=> ".application"
and then continues to find what seems to be the file extension handler:
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.application
=> "msedge.exe"
The non-working browser never reaches the second step.
A: after long research, we found out, that this behavior sources in the smart screen filter.
if smartscreen is disabled, then it just won't work (with no error and no message). as soon as smartscreen is enabled, everything works as designed.
according to microsoft, this is by design and won't be changed (as large companies would ever allow smartscreen -.-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58932466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: count of matching rows in R below is the sample table/Data frame. The third attribute (count) will give the count of similar rows(attribute1+attribute2)
╔════╦═════════════╦═════════════╦══════════════════════════════╗
║ ID ║ Attribute 1 ║ Attribute 2 ║ count(Attribute1+Attribute2) ║
╠════╬═════════════╬═════════════╬══════════════════════════════╣
║ 1 ║ A ║ AA ║ 3 ║
║ 2 ║ B ║ CC ║ 1 ║
║ 3 ║ C ║ BB ║ 2 ║
║ 4 ║ A ║ AA ║ 3 ║
║ 5 ║ C ║ BB ║ 2 ║
║ 6 ║ D ║ AA ║ 1 ║
║ 7 ║ B ║ AA ║ 1 ║
║ 8 ║ C ║ DD ║ 1 ║
║ 9 ║ A ║ AB ║ 1 ║
║ 10 ║ A ║ AA ║ 3 ║
╚════╩═════════════╩═════════════╩══════════════════════════════╝
Update :
Thanks akrun and danas.zuokas for the help.
the final output I am expecting would look something like this. where I am choosing 50% from each count group .ex : for ID 1,4,10 the count is 3. I would need to choose only 2 (50%) for each count group hence I should get (A,AA) twice .
ID Attribute 1 Attribute 2 count(Attribute1+Attribute2)
1 A AA 3
2 B CC 1
3 C BB 2
4 A AA 3
6 D AA 1
7 B AA 1
8 C DD 1
9 A AB 1
A: Given your data is in df:
library(data.table)
dt <- as.data.table(df)
dt[, count := .N, by = list(Attribute1, Attribute2)]
A: We can try
library(dplyr)
df1 %>%
group_by(attribute1, attribute2) %>%
mutate(Count= n())
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34633520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: anaconda - path environment variable in windows I am trying to run python from the windows command prompt (windows 10). So the result is the typical one when the path environment variable is not configured
c:\windows\system32>python
'python' is not recognized as an internal or external command, operable
program or batch file
however, I am not sure which is the right directory I should set up in the path variable.
I tried a few variations, and none of them work, including:
c:\users\xxx\anaconda3
c:\users\xxx\anaconda3\Scripts
c:\users\xxx\anaconda3\libs\python34
and none of them works.
Does anyone have experience with this particular system constellation (windows, anaconda). Thanks.
A: it turns out I was mistaken.
Solution is: in anaconda (as well as in other implementations), set the path environment variable to the directory where 'python.exe' is installed.
As a default, the python.exe file in anaconda is in:
c:\.....\anaconda
after you do that, obviously, the python command works, in my case, yielding the following.
python
Python 3.4.3 |Anaconda 2.2.0. (64|bit)|(default, Nov 7 2015), etc, etc
A: C:\Users\\Anaconda3
I just added above path , to my path environment variables and it worked.
Now, all we have to do is to move to the .py script location directory, open the cmd with that location and run to see the output.
A: C:\Users\<Username>\AppData\Local\Continuum\anaconda2
For me this was the default installation directory on Windows 7. Found it via Rusy's answer
A: In windows 10 you can find it here:
C:\Users\[USER]\AppData\Local\conda\conda\envs\[ENVIRONMENT]\python.exe
A: Instead of giving the path following way:
C:\Users\User_name\AppData\Local\Continuum\anaconda3\python.exe
Do this:
C:\Users\User_name\AppData\Local\Continuum\anaconda3\
A: To export the exact set of paths used by Anaconda, use the command echo %PATH% in Anaconda Prompt. This is needed to avoid problems with certain libraries such as SSL.
Reference: https://stackoverflow.com/a/54240362/663028
A: You can also run conda init as below,
C:\ProgramData\Anaconda3\Scripts\conda init cmd.exe
or
C:\ProgramData\Anaconda3\Scripts\conda init powershell
Note that the execution policy of powershell must be set, e.g. using Set-ExecutionPolicy Unrestricted.
A: Try path env var for system (on windows)
C:\ ...\Anaconda3\
C:\ ...\Anaconda3\scripts
C:\ ...\Anaconda3\Library\bin
Must solve! It worked for me.
A: The default location for python.exe should be here: c:\users\xxx\anaconda3
One solution to find where it is, is to open the Anaconda Prompt then execute:
> where python
This will return the absolute path of locations of python eg:
(base) C:\>where python
C:\Users\Chad\Anaconda3\python.exe
C:\ProgramData\Miniconda2\python.exe
C:\dev\Python27\python.exe
C:\dev\Python34\python.exe
A: I want to mention that in some win 10 systems, Microsoft pre-installed a python. Thus, in order to invoke the python installed in the anaconda, you should adjust the order of the environment variable to ensure that the anaconda has a higher priority.
A: You could also just re-install Anaconda, and tick the option add variable to Path.. This will prevent you from making mistakes when editing environment variables. If you make mistakes here, your operating system could start malfunctioning.
A: Provide the Directory/Folder path where python.exe is available in Anaconda folder like
C:\Users\user_name\Anaconda3\
This should must work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34030373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "62"
} |
Q: Issue in finding rmse in PCA Reconstruction in python I am trying to find the root mean squared error between an original sample from Xdata and a reconstructed sample recon for different numbers of components. However when I use the code below:
components = [2,6,10,20]
for n in components:
pca = PCA(n_components=n)
recon = pca.inverse_transform(pca.fit_transform(Xdata[0].reshape(1, -1)))
rmse = math.sqrt(mean_squared_error(Xdata[0].reshape(1, -1), recon))
print("RMSE: {} with {} components".format(rmse, n))
I always get an RMSE of 0.0 for each component?
For reference, this is what Xdata[0] holds:
array([-8.47058824e-06, -6.12352941e-05, -3.18529412e-04, -1.09905882e-03, -2.64370588e-03, -4.39111765e-03, -8.70000000e-03, -2.35560000e-02, -6.03388235e-02, -1.52837471e-01, -3.48945353e-01, -4.86196588e-01, -5.51568706e-01, -5.38629706e-01, -5.34948000e-01, -5.70773824e-01, -5.45583000e-01, -4.30446353e-01, -2.76558000e-01, -1.10208882e-01, -4.35031765e-02, -2.09613529e-02, -1.25080588e-02, -9.00317647e-03, -5.04900000e-03, -2.75576471e-03, -1.03394118e-03, -1.78058824e-04, -7.53529412e-05, -2.54647059e-04])
A: PCA is a type dimension reduction and I quote wiki:
It is commonly used for dimensionality reduction by projecting each
data point onto only the first few principal components to obtain
lower-dimensional data while preserving as much of the data's
variation as possible.
To me, your data X[0] and only 1 dimension.. How much more can you reduce it?
If it is a case of testing the rmse for the first entry, you still need to fit the pca on the full data (to capture the variance), and only subset the rmse on 1 data point (though it might be meaningless, because for n=1 it is not rmse but square of residuals)
You can see below:
import numpy as np
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.metrics import mean_squared_error
iris = datasets.load_iris()
Xdata = iris.data
components = [2,3]
for n in components:
pca = PCA(n_components=n)
recon = pca.inverse_transform(pca.fit_transform(Xdata))
rmse = mean_squared_error(Xdata[0], recon[0],squared=False)
print("RMSE: {} with {} components".format(rmse, n))
The output:
RMSE: 0.014003180182090432 with 2 components
RMSE: 0.0011312185356586826 with 3 components
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64823789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Running tests with Spring Boot So I'm trying to test Spring boot MVC app that I wrote:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = PetClinicApplication.class)
@WebAppConfiguration
public class OwnerControllerTests {
@Mock
private OwnerService ownerService;
@InjectMocks
private OwnerController ownerController;
private MockMvc mockMvc;
public void setup(){
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(ownerController).build();
}
@Test
public void testOwnerList() throws Exception{
List<Owner> owners = new ArrayList<>();
owners.add(new Owner());
owners.add(new Owner());
when(ownerService.getAll()).thenReturn((List<Owner>) owners);
mockMvc.perform(get("/ownerList"))
.andExpect(status().isOk())
.andExpect(view().name("ownerList"))
.andExpect(model().attribute("ownerList", List.class));
}
}
And im gettin in line
when(ownerService.getAll()).thenReturn((List<Owner>) owners);
in debugger mode ownerService=null
this is OwnerService.class
@Transactional
public Collection<Owner> getAll() {
return ownerDao.getAll();
}
this method should return list of Owner.class objects
owner controller snippet
@Controller
public class OwnerController {
@Autowired
private OwnerService ownerService;
@RequestMapping("/addOwner")
public String addOwner(Model model) {
model.addAttribute("Owner", new Owner());
return "addOwner";
}
@RequestMapping(value = "addOwner.do", method = RequestMethod.POST)
public String addOwnerDo(@Valid @ModelAttribute(value = "Owner") Owner owner, BindingResult result) {
if (result.hasErrors())
return "addOwner";
ObjectBinder.bind(owner);
ownerService.add(owner);
return "redirect:addOwner";
}
@RequestMapping("/ownerList")
public String ownerList(Model model) {
model.addAttribute("ownerList", ownerService.getAll());
return "ownerList";
}
@RequestMapping("/ownerList/{id}")
public String ownerDetails(@PathVariable(value = "id") int id, Model model) {
Owner owner = ownerService.get(id);
model.addAttribute("owner", owner);
return "ownerDetail";
}
// to refactor
@RequestMapping(value = "/ownerList/{id}.do")
public String ownerDetailsDo(@ModelAttribute(value = "owner") Owner owner, BindingResult result,
@RequestParam(value = "action") String action, Model model) {
switch (action) {
case "update":
ObjectBinder.bind(owner);
ownerService.update(owner);
return "ownerDetail";
case "delete":
ownerService.remove(owner.getId());
model.addAttribute("ownerList", ownerService.getAll());
return "ownerList";
}
model.addAttribute("owner", owner);
return "ownerDetail";
}
}
A: You forgot to annotate your setup method with @Before such that mockito do not create and inject the mocks, try this:
@Before
public void setup(){
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38974958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C# wpf multiple windows on task bar I created a C# project which have multiple windows. When I do some other stuff, some of the windows are lost focus. Then I have to bring them to front by clicking the task bar one by one.
I am wondering is there are OnTaskBarClick Event on C# wpf window?
Then What I need to do is to set all sub windows with "ShowInTaskbar="False"". Then when ever my mainwindow is clicked on the task bar, I bring all the windows to the front.
A: You'll want to use the Window.Activated event to detect when your application's window is brought into focus:
From the documentation:
A window is activated (becomes the foreground window) when:
*
*The window is first opened.
*A user switches to a window by selecting it with the mouse, pressing ALT+TAB, or from Task Manager.
*A user clicks the window's taskbar button.
Or you could use the Application.Activated event.
Clicking on a control of an already active window can also cause the Window.Activated event to fire, so if the issue is that it's firing too often, you'll probably want to watch for when the application toggles between being active and deactive.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Application.Current.Activated += CurrentOnActivated;
Application.Current.Deactivated += CurrentOnDeactivated;
}
private bool isDeactivated = true;
private void CurrentOnDeactivated(object sender, EventArgs eventArgs)
{
isDeactivated = true;
//handle case where another app gets focus
}
private void CurrentOnActivated(object sender, EventArgs eventArgs)
{
if (isDeactivated)
{
//Ok, this app was in the background but now is in the foreground,
isDeactivated = false;
//TODO: bring windows to forefont
MessageBox.Show("activated");
}
}
}
A: I think what you are experiencing is the window Owner not being set on your child window.
Please refer to Window.Owner Property
When a child window is opened by a parent window by calling
ShowDialog, an implicit relationship is established between both
parent and child window. This relationship enforces certain behaviors,
including with respect to minimizing, maximizing, and restoring.
-
When a child window is created by a parent window by calling Show,
however, the child window does not have a relationship with the parent
window. This means that:
*
*The child window does not have a reference to the parent window.
*The behavior of the child window is not dependent on the behavior of the parent window; either window can cover the other, or be
minimized, maximized, and restored independently of the other.
You can easily fix this by setting the Owner property in the child window when before calling Show() or ShowDialog()
Window ownedWindow = new Window();
ownedWindow.Owner = this; // this being the main or parent window
ownedWindow.Show();
Note : if conforming to an MVVM pattern, this can become a little
more cumbersome, however there is plenty of resources on how to link owner and parent windows.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48575450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pass the previously assigned pointer value to a loop I've got a string pointer string* ifxPtr;, what I'm trying to do is to set this pointer to point to the user input and then loop through each character of it.
string* ifxPtr;
void Expression::GetInfix(string data) // This method runs first and it's setting the pointer to point to previously passed user input
{
ifxPtr = &data;
ConvertToPostfix();
}
void Expression::ConvertToPostfix()
{
for (int i = 0; i < *ifxPtr->length; i++) // Here's the struggle, compiler is complaining about *ifxPtr with message Cannot apply binary '<' to 'int' and 'unassigned() const'
{
//Do something here
}
}
A: *
*length is a function and it should be length()
*You
don't need to deference the pointer if you use ->
*The result
returned from length() is size_t
Here is what I would use:
int length = static_cast<int>((*ifxPtr).length());
A: foo-> is shorthand for (*foo).. Don't double up operators, also it should be length():
for (int i = 0; i < ifxPtr->length(); i++)
Also, be careful with that design, possibility of running into Undefined Behaviour with a simple mistake is big.
A: if you use and *before it means using the value which is pointed by the pointer.
string s,*p;
p=&s;
here *p.lenght() is same as s.length if you want to access through pointer you have to use it like this p->length().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36970007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Quick.db unwarn command unwarns all the warns in a member I am coding my own discord bot, and making warn system with quick.db package, and having a problem. If I warn a person 2 times, and unwarn him, It removes all the warns of the user. The code is:
//I have imported discord.js and others. This is only the part of warn and unwarn command.
if(command === "warn" ) {
const db = require('quick.db')
const Wuser = message.mentions.users.first();
const member = message.guild.member(Wuser)
if(!message.member.hasPermission("MANAGE_MESSAGES"))
return message.channel.send("You dont have the permission to warn anyone").then(msg => {
msg.delete({ timeout: 10000 })
})
if (!Wuser) return;
if(Wuser.id === message.author.id) return message.channel.send("You cant warn yourself").then(msg => {
msg.delete({ timeout: 10000 })
})
if(Wuser.id === client.user.id) return message.channel.send("You cant warn me").then(msg => {
msg.delete({ timeout: 10000 })
})
db.add(`warn.${Wuser.id}`, 1);
const data = db.get(`warn.${Wuser.id}`);
if(data === undefined ) {
let data = 0
}
message.channel.send(`${Wuser} you are warned. Additional infractions may result in a mute. You have ${data} warns.`)
logchannel.send(`${Wuser} is warned. He have ${data} warns. He is warned by ${message.author}.`)
blogchannel.send(`${Wuser} is warned. He have ${data} warns. He is warned by ${message.author}.`)
}
if(command === "unwarn" ) {
if(!message.member.hasPermission("MANAGE_MESSAGES"))
return message.channel.send("You dont have the permission to unwarn anyone").then(msg => {
msg.delete({ timeout: 10000 })
})
const db = require('quick.db')
let Wuser = message.mentions.users.first();
let member = message.guild.member(Wuser)
if (!Wuser) return;
if(Wuser.id === message.author.id) return message.channel.send("You cant unwarn yourself").then(msg => {
msg.delete({ timeout: 10000 })
})
if(Wuser.id === client.user.id) return message.channel.send("You cant unwarn me").then(msg => {
msg.delete({ timeout: 10000 })
})
db.delete(`warn.${Wuser.id}`)
const data = db.get(`warn.${Wuser.id}`)
message.channel.send(`${Wuser} is unwarned. `)
logchannel.send(`${Wuser} is unwarned by ${message.author}.`)
blogchannel.send(`${Wuser} is unwarned by ${message.author}.`)
}
if(command === "userlog") {
if(!message.member.hasPermission("MANAGE_MESSAGES"))
return message.channel.send("Why are you looking other's user log?").then(msg => {
msg.delete({ timeout: 10000 })
})
let Wuser = message.mentions.users.first()
let member = message.guild.member(Wuser)
if (!Wuser) return message.channel.send("User not specified").then(msg => {
msg.delete({ timeout: 10000 })
})
const db = require('quick.db')
const data = db.get(`warn.${Wuser.id}`)
let logEmbed = new MessageEmbed()
.setTitle(`Log of ${Wuser.tag}`)
.setDescription(`${Wuser} currently have ${data} warns.`)
.setThumbnail(member.user.displayAvatarURL)
message.channel.send(logEmbed)
logchannel.send(`${message.author.tag} used **.userlog** command.`)
}
What I have to edit the code? Thanks in advance.
A: In the unwarn command
db.delete(`warn.${Wuser.id}`)
Instead of this add to the db
db.add(`warn.${Wuser.id}`, -1);
or subtract from the value
db.subtract(`warn.${Wuser.id}`, 1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65661262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding a New field too slow I want to add a new field to my index which includes more than 20m documents. I have dictionary like this Template : [Catalog_id : {Keyword: Sold Count}]
Sold Counts = {1234: {Apple:50}, 3242: {Banana:20}, 3423: {Apple:23}, ...}
In the index, there are many documents which share the same catalog_id. According to each document's catalog_id, I want to add a new field.
_id: 12323423423, catalog_id: 1234, name: '....', **Sold Count: [Apple,50]**
What is the best way to insert a new field in this situtation?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72349582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding CustomBusinessHour to DateTimeIndex in vectorized manner Suppose I have a DateTimeIndex which I wish to add a CustomBusinessHour to. My CustomBusinessHour keeps indexes the same that fall between 0900 and 2000 on the same day, it moves indexes that fall between 0000 and 0900 to 0900 the same day, and moves indexes after 2000 to 0900 the next business day; taking into account some holidays.
The following code works as I intend
import pandas as pd
import numpy as np
from pandas.tseries.offsets import CustomBusinessHour
idxs = pd.DatetimeIndex(['2018-08-14 21:54:00', '2018-08-28 21:48:00',
'2018-10-02 23:13:00', '2019-06-26 10:59:00'])
custom_days = CustomBusinessHour(
holidays=[pd.Timestamp("2019/01/01"),
pd.Timestamp("2018/12/25"),
pd.Timestamp("2018/12/26")],
weekmask='Mon Tue Wed Thu Fri',
start="09:00", end="20:00")
moved_idx = idxs + 0*custom_days
However, I get the following warning
PerformanceWarning: Non-vectorized DateOffset being applied to Series
or DatetimeIndex
How can I convert custom_days to a numpy array to add this to idxs in a vectorized manner to remove this warning?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56770177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: why do i keep getting an error 404 when fetching images from a backend folder in webpack 5 I would appreciate if someone knows the answer!!
I am defining the image src from the backend using an object key for my image.Maybe this is the problem because i think i have imported properly and used the file loader in webpack.config.js
index.js
import ProductScreen from "./screens/ProductScreen.js";
import Error404Screen from "./screens/Error404Screen.js";
import { parseRequestUrl } from "./utils.js";
import '../styles/style.css';
import myImage from './images/product-1.jpg';
const routes = {
"/":HomeScreen,
"/product/:id":ProductScreen,
}
const router = async () => {
const request = parseRequestUrl();
const parseUrl =
(request.resource ? `/${request.resource}` : '/' ) +
(request.id ? '/:id' : '') +
(request.verb ? `/${request.verb}` : '');
const screen = routes[parseUrl] ? routes[parseUrl] : Error404Screen;
const main = document.getElementById('main-container');
main.innerHTML = await screen.render();
};;
window.addEventListener('load',router);
window.addEventListener('hashchange',router);
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const fileLoaderPlugin = require('file-loader');
const { truncate } = require('fs');
module.exports = {
mode:'development',
target:'web',
entry:{
main : path.resolve(__dirname, 'src/index.js'),
},
output:{
path:path.resolve(__dirname,'frontend'),
filename:'[name][content.hash].js',
assetModuleFilename:'[name]'
},
devServer:{
static:{
},
port:3000,
open:true,
hot:true,
compress:true,
historyApiFallback:true,
},
module:{
rules:[
{
test:/\.css$/,
use:
['style-loader','css-loader','sass-loader',],
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
generator: {
filename: 'images/[name][ext]'
},
use: [
'file-loader',
{
loader: 'image-webpack-loader',
options: {
bypassOnDebug: true, // [email protected]
disable: true,
esModule: false, // [email protected] and newer
},
},
],
}
]
},
plugins:[
new HtmlWebpackPlugin({
title:'Webpack App',
filename:'index.html',
template:'frontend/index.html',
}),
new fileLoaderPlugin({
}),
]
}
HomeScreen.js that use on render method
const HomeScreen = {
render:async () => {
// const { products } = data;
const response = await fetch("http://localhost:5000/api/products",{
headers:{
"Content-Type":"application/json",
},
});
if(!response || !response.ok){
return `<div>Error in getting data</div>`;
}
const products = await response.json();
return `
<ul class = 'products'>
${products.map(product => `
<li>
<div class="product">
<a href="/#/product/1">
<img src="require${product.image}" alt="${product.name}" />
</a>
<div class="product-name">
<a href="/#/product/${product._id}">
${product.name}
</a>
</div>
<div class="product-brand">
${product.brand}
</div>
<div class="product-price">
${product.price} €
</div>
</div>
</li>
`).join('\n')}
</ul>
`
}
}
export default HomeScreen;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74135874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use "FB.Canvas.setAutoResize" with the php SDK? I want to make the scrollbars in my iFrame application disapear. So I checked the "Auto-resize" radio button under "Facebook Integration" and I understand I need to call "setAutoResize" so the canvas will grow to the height of my page.
But I can't find any documentation about the php SDK or explanation of how and where shall I call this function (and on what object). I can only find relevent documentation abput the JS SDK which is very different.
A: <script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: 'your apikey', status: true, cookie: true, xfbml: true});
FB_RequireFeatures(["CanvasUtil"], function(){ FB.XdComm.Server.init("xd_receiver.htm");
FB.CanvasClient.startTimerToSizeToContent(); });
FB.Canvas.setAutoResize(true,500);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
A: FB.Canvas.setAutoResize function will be removed on January 1st, 2012 as announced in this blog post. Please use FB.Canvas.setAutoGrow instead.
You can read more about here.
FB.Canvas.setAutoGrow (Working perfect!)
Note: this method is only enabled when Canvas Height is set to "Settable (Default: 800px)" in the Developer App.
Starts or stops a timer which will grow your iframe to fit the content every few milliseconds. Default timeout is 100ms.
Examples
This function is useful if you know your content will change size, but you don't know when. There will be a slight delay, so if you know when your content changes size, you should call setSize yourself (and save your user's CPU cycles).
window.fbAsyncInit = function() {
FB.Canvas.setAutoGrow();
}
If you ever need to stop the timer, just pass false.
FB.Canvas.setAutoGrow(false);
If you want the timer to run at a different interval, you can do that too.
FB.Canvas.setAutoGrow(91); // Paul's favourite number
Note: If there is only 1 parameter and it is a number, it is assumed to be the interval.
A: You cant do that with PHP SDk (i think)
You should use the magic javascript provided by Facebook in order to resize according to the contents :
<div id="FB_HiddenIFrameContainer" style="display:none; position:absolute; left:-100px; top:-100px; width:0px; height: 0px;">
</div>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>
<script type="text/javascript">
FB_RequireFeatures(["CanvasUtil"], function(){ FB.XdComm.Server.init("xd_receiver.htm");
FB.CanvasClient.startTimerToSizeToContent(); });
</script>
http://developers.facebook.com/docs/reference/oldjavascript/FB.CanvasClient.startTimerToSizeToContent
A: The solution with FB_HiddenIFrameContainer doesn't work for me. Try http://fbforce.blogspot.com/2011/01/how-to-use-fbcanvassetautoresize.html. This works.
<body style="overflow: hidden">
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.Canvas.setAutoResize();
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
<div style="height:2000px; width:500px; background:blue;">
test page
</div>
</body>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4849579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: paramiko expect timing out Thinking about making a move from Perl to Python running scripts to automate certain tasks on remote servers and devices. We need to be able to use Expect to check for certain results and get the data back. Taking a look at Paramiko-Expect and I like it, but it's timing out every time.
import paramiko
from paramikoe import SSHClientInteraction
HOSTNAME = "HOST IP"
PASSWORD = "PWORD"
USERNAME = "UNAME"
PROMPT = "(node name)#"
command = "show command"
print PROMPT
file = open("testlog.txt","w")
def main():
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(HOSTNAME, port=22, username=USERNAME, password=PASSWORD)
interact = SSHClientInteraction(client, timeout=10, display=True)
interact.send(command)
interact.expect(PROMPT)
file.write(interact.current_output_clean)
client.close()
return
main()
file.close()
This is the traceback I get:
Traceback (most recent call last):
File "python_test.py", line 40, in <module>
main()
File "python_test.py", line 28, in main
interact.expect(PROMPT)
File "/usr/local/lib/python2.7/site-packages/paramikoe.py", line 122, in expect
buffer = self.channel.recv(self.buffer_size)
File "/usr/local/lib/python2.7/site-packages/paramiko/channel.py", line 598, in recv
raise socket.timeout() socket.timeout
I've tried multiple versions of the PROMPT to expect, from directly putting in the text of the node I'm trying it on to full regex. Nothing works. It always times out when it gets to the client.expect. Paramiko-expect documentation does not help and the only other place I see this question is different enough that it doesn't help.
Any advice is appreciated.
A: Put prompt to something you expect, as... prompt. Here is paramiko interaction example. Please note lines 21, and 37 -
PROMPT = 'vagrant@paramiko-expect-dev:~\$\s+'
interact.expect(PROMPT)
So, when I've updated part of your code to:
interact = SSHClientInteraction(client, timeout=10, display=True)
interact.expect(PROMPT)
interact.send("ls")
interact.expect(".*Maildir.*")
file.write(interact.current_output_clean)
client.close()
I have testlog.txt filled with listing of the home directory, of remote host.
As a side note - switch to python 3. If you are starting, it is better to use tool that is not well known to be outdated soon. Also you can use ipython, or jupyter - code will be more interactive, faster to test. Maybe netmiko will be interested for you?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47165043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Running Python script from PHP but its not working HI I am using PHP to execute python script:
pdf.py
import pdfkit
pdfkit.from_url('https://www.google.co.in/','google.pdf');
data.php
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_DEPRECATED);
exec("python pdf.py");
I tried executing ython file using php with above data, But script not run .
A: Maybe try exec("python pdf.py", $response, $error_code); and see if anything useful is returned in $response or $error_code?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66874231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RxJS filter and get first element - Typescript error getStep$(step): Observable<number> {
return of([1,2,3]).pipe(
filter((res: number) => step === res),
first()
) as Observable<number>;
}
I expect for number. Like filter(res => res.step === step)[0]
But Webstorm throws typescript's error.
Argument of type 'MonoTypeOperatorFunction<number>' is not assignable to parameter of type 'OperatorFunction<number[], number>'. Types of parameters 'source' and 'source' are incompatible. Type 'Observable<number[]>' is not assignable to type 'Observable<number>'. Type 'number[]' is not assignable to type 'number'.
A: You look for this, using map operator and not filter
getStep$(step): Observable<number> {
return of([1,2,3]).pipe(
map((res: number[]) => res.filter((r) => step === r)[0])
) as Observable<number>;
}
The error you get is because you forgot to add [] to the type of the filter operator, and still this is not what you tried to achieve anyway.
getStep$(step): Observable<number> {
return of([1,2,3]).pipe(
// HERE I ADDED [] to number
filter((res: number[]) => step === res),
first()
) as Observable<number>;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67776041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dart: How to use the dot notation, uncaught TypeError Problem I have the following code in dart, which decodes a string into a JSON object.
import 'dart:convert';
void main(){
var stringValue = "{\"last_supported\": \"2.00\", \"current\": \"2.00\"}";
var newValue = json.decode(stringValue);
print(newValue["last_supported"]);
}
The above code works fine, but when I change print statement to:
print(newValue.last_supported);
It gives me the following exception:
Uncaught TypeError: C.C_JsonCodec.decode$1(...).get$last_supported is not a function
Is it possible to use dot annotation to access properties, and how?
A: I'm guessing you come from a java-script background.
in dart object keys cannot be accessed through the . dot notation.
rather they are accessed like arrays with ['key_name'].
so that's why this line doesn't work
print(newValue.last_supported)
and this one does
print(newValue["last_supported"]);
dot notation in dart only works on class instances, not Map (similar to JavaScript objects).
look at the following :
class User {
final String name;
final int age;
// other props;
User(this.name, this.age);
}
Now when you create a new user object you can access its public attributes with the dot notation
final user = new User("john doe", 20); // the new keyword is optional since Dart v2
// this works
print(user.name);
print(user.age);
// this doesn't work because user is an instance of User class and not a Map.
print(user['name]);
print(user['age]);
For more about the new keyword you can read the v2 release notes here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61043168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Delay adding a class for 2 seconds in hover() How do I use easing or time delay on addClass();?
$("#date_1").hover(
function () {
$(this).addClass("door");
$(this).addClass("doorstatic", "slow"); // after 2seconds i want to add this class during the hover
},
function () {
$(this).removeClass("door");
$(this).removeClass("doorstatic"); // both classes are instantly removed when hover off
}
);
A: The setTimeout method of javascript can be used to run code you specify after a set delay in miliseconds.
Try this:
var timeout;
$("#date_1").hover(
function () {
$(this).addClass("door");
timeout = setTimeout(function() { $(this).addClass("doorstatic"); }, 2000);
}, function () {
clearTimeout(timeout);
$(this).removeClass("door doorstatic");
}
);
A: Actually you can just append a call to jQuery's delay to you addClass call.
Something like
$(this).addClass("door").delay(2000).addClass("doorstatic", "slow");
should do the trick.
A: $("#date_1").hover(
function () {
var $this = $(this);
$this.addClass("door");
setTimeout(function() {
$this.addClass("doorstatic");
}, 2000); // 2000 is in mil sec eq to 2 sec.
},
function () {
$(this).removeClass("door doorstatic");
}
);
You can group your classes like removeClass("door doorstatic")
The problem here is that if you mouseover and before two seconds mouse out you will still have the class doorstatic on you element.
The fix:
$("#date_1").hover(
function () {
var $this = $(this),
timer = $this.data("timer") || 0;
clearTimeout(timer);
$this.addClass("door");
timer = setTimeout(function() {
$this.addClass("doorstatic");
}, 2000); // 2000 is in mil sec eq to 2 sec.
$this.data("timer", timer);
},
function () {
var $this = $(this),
timer = $this.data("timer") || 0;
clearTimeout(timer);
$this.removeClass("door doorstatic");
}
);
Created a live example of the solution at jsFiddle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8444618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Can i create application in Windows for Linux platform? I have around of 4 years experience in C#.Net programming and i am developing a client server application. The server application will be insalled on CentOS and client application will be installed in Windows OS. But, i don't have much knowledge about c++ programming on linux platform. So, my question is that can i create a console application in Windows OS and compile it for linux platform. it is not necessary that compile it on Windows. but, it should be executed in linux platform. I am new in linux programming.
Presently i am using TC++ editor. Can i use Visual Studio 2010 to build server application for linux platform?
if there are another approach then please suggest me.
Thanks.
A: Maybe you can use VS as an editor ; Make sure that you do not include any windows specific libs; There is an option of using cygwin and doing a cross compilation. Check the links
How to cross compile from windows g++ cygwin to get linux executable file
I guess it will be more of a pain. Better use Virtual Box --> linuxMint/Ubuntu + Eclipse with C++ plugin or some other C++ editor...
A: You can develop the client in C# and the server in C++, if you prefer. Consider that unlike C#, there is no standard socket library yet, and you'll have to rely on either system calls or their higher level wrappers (like boost).
I've to tell you that Windows uses BSD sockets (its own version, with some modifications though), therefore with a few preprocessors checks, you can make your application portable.
In your case, I'd suggest you to go for boost.asio which will hide all low-level stuff for you. It's even cross-platform.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21770767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Font face with Google Chrome Since some days, my Google Chrome browser doesn't show special fonts : CSS with font-face.
@font-face {
font-family: 'Babel Sans';
src: url('../fonts/babelsans.eot');
src: url('../fonts/babelsans.eot?#iefix') format('eot'),
url('../fonts/babelsans.woff') format('woff'),
url('../fonts/babelsans.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
All working fine with Safari, Firefox and IE, and it worked fine the last week.
Someone has the same problem and someone know how I can resolve it ?
Thanks,
A: I'm experiencing the same issue since Chrome 20 update. This thing happen in Windows Xp and Mac Os X 10.6.8.
Safari and Mobile Safari (that share WebKit engine with Chrome) works perfectly like Firefox and IE.
My css code is exactly like yours.
Looking in the inspector it seems that the font doesn't get downloaded.
Sometimes while navigating different pages (that share the same css external file) in my website the font loads and get displayed properly.
Still trying to solve this...
EDIT:
I managed to solve this issue.
I don't know why, but using this worked:
http://www.fontsquirrel.com/fontface/generator/
I uploaded my font, got the css and converted files, uploaded them to my server and replaced font-face declaration...bling! It works! Hope that works for you too!
A: It's working now, I think Google has update the browser.
A: Since there was an update of Chrome for about a week, you may try using an older version to find out if it's a bug (I myself didn't notice any problems). Get one at http://www.oldapps.com/google_chrome.php.
Also check if you're using this font in addion to other font-related CSS values (if so, deactivate them). There were some problems in the past which actually have been solved, but you never know...
A: First: Convert you font using this service as Mr Stefano suggest:
Later use this CSS code to use your font in your project:
@font-face {
font-family: 'aljazeeraregular';
src: url('aljazeera-webfont.eot');
src: url('aljazeera-webfont.eot?#iefix') format('eot'),
url('aljazeera-webfont.woff') format('woff'),
url('aljazeera-webfont.ttf') format('truetype'),
url('aljazeera-webfont.svg') format('svg');
font-weight: normal;
font-style: normal;
}
body {
background-color: #eaeaea;
font-family: 'Aljazeera';
font-size: 14px;
}
Note that when you call font-family in your site you have to use its original name not like what you declare it in @font-face.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11336103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I want to search list elements in txt file I want to search for list elements in txt file. However with this code I don't get the desired result. I have tried several solutions, but none of them really worked.
def run(self):
hostname = self.queue.get()
with open('allhosts.txt', "r+") as file1:
fileline1 = file1.readlines()
for x in hostname:
for line in fileline1:
if x in line:
self.found.emit(hostname)
else:
self.notFound.emit(hostname)
A: Use regx in this case
import re
str = open('a.txt', 'r').read()
m = re.search('(?<=hostname)(.*)', str)
print ("hostname",(m.groups()))
If you dont get output. please drop text file screenshot
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66596633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to remove port from x-forwarded-for header in azure webapp? I have a Joomla app on azure's WebApp on Linux.
I want to get the client ip in order to be able to block by ip with the Admin Tools extension.
The admin tools has an option to get the client ip from the x-forwarded-for header, the problem azure is adding a random port to the client ip by so making blocking impossible.
How can I get rid of the port?
A: You can use Azure Application Gateway.
https://learn.microsoft.com/en-gb/azure/application-gateway/features#rewrite-http-headers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50889876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C Random Number Generation (pure C code, no libraries or functions) I need to generate some random numbers in C for testing and debugging the system. The system is a custom hardware (SoC) with a limited set of functions so I can only use basic mathematical operations.
And no, I can't use random number generators in stdlib or math.h. I need to write it myself. So is there some sort of algorithm for generating random numbers?
I know that a simple solution is to generate the numbers here on my workstation and embed them into the module, but I don't want to do that.
A: Just dig up the article by Park and Miller in the Oct 88 issue of CACM.
The general algorithm they propose is:
a = 16807;
m = 2147483647;
seed = (a * seed) mod m;
random = seed / m;
Though the article includes several refinements.
A: A random number generator is basically a special* hash function which runs recursively from a starting seed.
I've used the MurmurHash2 algorithm in my C# code to good effect. It's extremely fast and simple to implement and has been tested to be very well distributed with low collision rates. The project has several different open source hash functions written in C++ which should be easily convertible to C.
* By special I mean that running the hash function on a value should return another seemingly random (but determinate) value, so that the output doesn't appear to form patterns. Also, the distribution of the returned value should have a uniform distribution.
A: A linear congruential generator would be simple to implement. A nice implementation in pure C is available here.
A: You can try Multiply-with-carry by George Marsaglia.
Code from Wikipedia:
#include <stdint.h>
#define PHI 0x9e3779b9
static uint32_t Q[4096], c = 362436;
void init_rand(uint32_t x)
{
int i;
Q[0] = x;
Q[1] = x + PHI;
Q[2] = x + PHI + PHI;
for (i = 3; i < 4096; i++)
Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i;
}
uint32_t rand_cmwc(void)
{
uint64_t t, a = 18782LL;
static uint32_t i = 4095;
uint32_t x, r = 0xfffffffe;
i = (i + 1) & 4095;
t = a * Q[i] + c;
c = (t >> 32);
x = t + c;
if (x < c) {
x++;
c++;
}
return (Q[i] = r - x);
}
A: Check the source code of the gsl library, a couple of well tested algorithms are implemented in it.
A: You may want to look for Mersenne Twister. There are lots of algorithms of higher quality. A good article with an overview you find here:
http://en.wikipedia.org/wiki/Pseudorandom_number_generator
A: You might try Isaac which is also available as part of CCAN here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9492581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: MissingSchema: Invalid URL '/': No schema supplied. Perhaps you meant http:///? for l in l1:
r = requests.get(l)
html = r.content
root = lxml.html.fromstring(html)
urls = root.xpath('//div[@class="media-body"]//@href')
l2.extend(urls)
while running the above code this error coming. any solution??
MissingSchemaTraceback (most recent call last)
MissingSchema: Invalid URL '/': No schema supplied. Perhaps you meant http:///?
A: urls = root.xpath('//div[1]/header/div[3]/nav/ul/li/a/@href')
These HREFs aren't full URLs; they're essentially just pathnames (i.e. /foo/bar/thing.html).
When you click on one of these links in a browser, the browser is smart enough to prepend the current page's scheme and hostname (i.e. https://host.something.com) to these paths, making a full URL.
But your code isn't doing that; you're trying to use the raw HREF value.
Later on in your program you use urljoin() which solves this issue, but you aren't doing that in the for l in l1: loop. Why not?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39756016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Using git and svn I have been trying to solve this problem on my own. However I did not find a solution that really works. All my attempts ended with conflicts, many rebases, etc. etc.
So, I have the following setup:
Git is my main CVS for all my projects.
For one of the projects I am using the wp7 silverlight toolkit from codeplex.com.
However for my project I need to change some lines of code in the toolkit.
So, I would like to have the following scenario:
*
*In Git I would need to have a clone of the SVN repo from codeplex.
So, I could easily work on it.(Btw the SVN repo is read-only)
*However, from time to time I would need to fetch the latest updates
from the SVN repo.
How can I accomplish this scenario?
Thank you for your help!
A: Within your project could the toolkit be in a subfolder which is managed by svn?
A simplistic approach (which misses out the opportunity to import the svn version history git-svn which basicxman mentions) would be to manage the whole project using git including the contents of the folders updated by svn. You may wish to exclude the .svn directories through.
Try adding a line to .git/info/exclude for your project to ignore files or folders called .svn
A: You are making changes to the codeplex code. Make those changes on a branch. Keep master up to date with the codeplex svn repo using git-svn. After an update, merge master into your changes branch.
Then share your codeplex repo with your main repo as a submodule as suggested before.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7434096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: var Hoisting in JavaScript Consider the following code in JavaScript-
var DEFAULT_RATE=0.01;
var rate=0.04;
function getRate() {
if(!rate) {
var rate=DEFAULT_RATE;
}
return rate;
}
console.log(`Rate is`,getRate());
The output of the following code is 0.01
My takeaway from this is that vars are hoisted(and declared undefined) to the top of the scope pertaining to the where they are used. In case of let and const, they go into TDZ but that is a different thing entirely.
But I also learnt that var has a global scope. Then var show not allow variable redeclaration.
Isn't the global scope mean the scope containing the entire code? Have I understood it wrongly?
A: When using var to declare variables, the variable can take on either function or global scope. If var is used within a function, it has function scope, if var is used outside of any function, the variable has Global scope.
So, your statement of:
But I also learnt that var has a global scope. Then var show not allow
variable redeclaration.
Is actually, not really accurate because it depends on where var is used and redeclaration (more correctly known as variable "hiding") is possible in any smaller scope than the first declaration was made.
When declaring with var, the declaration is hoisted to the top of the scope.
I've written another answer that describes and demonstrates this in detail.
A: In JavaScript, function declarations are hoisted before var declarations, and assignments are not hoisted.
So the sample code from the question:
var DEFAULT_RATE=0.01;
var rate=0.04;
function getRate() {
if(!rate) {
var rate=DEFAULT_RATE;
}
return rate;
}
has this effective ordering:
// hoisted function
function getRate() {
var rate = undefined; // <- hoisted local variable
if(!rate) { // <- always true
rate = DEFAULT_RATE; // <- always executed
}
return rate; // <- always returns DEFAULT_RATE (0.01)
}
// hoisted vars
var DEFAULT_RATE;
var rate;
// not-hoisted assignments
DEFAULT_RATE = 0.01;
rate = 0.04;
// not-hoisted function call
console.log(`Rate is`,getRate());
Since getRate() contains var rate, the function-scoped rate is hoisted to the beginning of getRate(), with a value of undefined.
Therefore if(!rate) evaluates to if(!undefined), which is always true, and getRate() always returns DEFAULT_RATE (0.01).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65874608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Creating AppDomain using .net Framework 4 gives OutOfMemoryException I'm trying to create an appdomain in VB / VS2015 using .net Framework 4, 64-bit, but am getting an OutOfMemoryException.
domain = AppDomain.CreateDomain("mydomain")
It works fine if I do it in a Windows Form Application, but I'm trying to do it in a class library (to be called from a 3rd-party application), and it fails every time.
I'd like to know if it is legal to create an appdomain in these circumstances (after all, I'm not creating an application), and the error message is misleading, or is there something else I'm missing (security evidence?).
Microsoft admit to a bug in Framework 4.5 which gives this error (see this), but I'm using Framework 4.
To give a bit more background, I'm using an appdomain to dynamically load and unload a dll which I am creating, so I can unload, recompile and reload during development, as the 3rd-party application which calls my dll is very slow to boot up and load documents. I'd like to get as close as possible to Edit and Continue!
A: I got the same error and tracked it down a little bit inside clr.dll.
The function internally calls GetSystemInfo (kernel32) to check the allocation granularity.
A quick and dirty fix for this issue: Detour GetSystemInfo
see example code here ( I used Process.NET for the detour, it’s quick and easy)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.IO;
using ProcessDotNet;
using ProcessDotNet.Applied.Detours;
namespace Bootstrap
{
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
public delegate void GetSystemInfoDelegate(ref SYSTEM_INFO info);
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_INFO
{
public ushort processorArchitecture;
ushort reserved;
public uint pageSize;
public IntPtr minimumApplicationAddress;
public IntPtr maximumApplicationAddress;
public IntPtr activeProcessorMask;
public uint numberOfProcessors;
public uint processorType;
public uint allocationGranularity;
public ushort processorLevel;
public ushort processorRevision;
}
class Loader
{
static void GetSystemInfoDetoured(ref SYSTEM_INFO info)
{
info = new SYSTEM_INFO();
GetSystemInfoDetour.Disable();
GetSystemInfo(ref info);
info.allocationGranularity = 1000000;
GetSystemInfoDetour.Enable();
}
static Detour GetSystemInfoDetour;
static GetSystemInfoDelegate GetSystemInfo;
static void Main(string[] args)
{
TestDomainCreation();
}
static void TestDomainCreation()
{
AppDomainSetup setup = new AppDomainSetup();
ProcessSharp s = new ProcessSharp(Process.GetCurrentProcess(), ProcessDotNet.Memory.MemoryType.Local);
GetSystemInfo = s["kernel32"]["GetSystemInfo"].GetDelegate<GetSystemInfoDelegate>();
DetourManager dtm = new DetourManager(s.Memory);
GetSystemInfoDetour = dtm.CreateAndApply(GetSystemInfo, new GetSystemInfoDelegate(GetSystemInfoDetoured), "GetSystemInfoDetour");
var tempDomain = AppDomain.CreateDomain("HappyDomain", null, setup);
GetSystemInfoDetour.Disable();
GetSystemInfoDetour.Dispose();
}
}
}
Regards
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37609771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DataTable From Session Memory has No Columns Im trying to retrieve a datatable that I put into a session variable, however when i do it apears that there are no columns...
I have done this before in VB.NET, I'n now using C#, and it worked perfectly, and as far as i can see there is no change in the code other than the obvious syntax changes.
EDIT:
The dt (in part 2) variable has the right data when i look in the data visulization window, but i have noticed that the other properties associated with a datatable are abscent. When i hover over a normal looking datatable with my mouse it looks like the following: " dt ----- {System.Data.DataTable}" but in the class im working on it just looks like "dt ----- {}". Also, after I return the session variable into the dt I clone it (dtclone = dt.clone(); ) and the clone is empty in the data visulizer.... what on earth!
EDIT 2:
I have now also tried converting the first datatable to a dataset, putting this in the session variable, and recoverting it back to a datatable in the class.
Am starting to wonder if it is a probelm with:
dt.Load(sqlReader);
The data does appear after this step though in the dataset visualiser, but not after being cloned.
Code below.
All help very welcome!
Thanks in advance
Chris
1) SQL command in a webhandler, the results of which populate the datatable to be put into the session variable.
DataTable dt = new DataTable();
SqlDataReader sqlReader= default(SqlDataReader);
SqlDataAdapter sqlAdapter = new SqlDataAdapter();
sqlReader = storedProc.ExecuteReader(CommandBehavior.CloseConnection);
dt.Load(sqlReader);
System.Web.HttpContext.Current.Session["ResultsTable"] = dt;
2) Part of the code in a class which performs calculations on the table:
DataTable dt = (DataTable)HttpContext.Current.Session["ResultsTable"];
A: did you call DataTable dispose after setting Session Var?
Because if you do this, solution is like this:
System.Web.HttpContext.Current.Session["ResultsTable"] = dt.Copy();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4725914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: replacing escape character with double qoutes in c# I have the following string in a variable called,
s:
[{\"roleIndex\":0,\"roleID\":\"c1_r0_23\",\"roleName\":\"Chief Executive\"},
{\"roleIndex\":1,\"roleID\":\"c1_r1_154\",\"roleName\":\"Chief Operator\"}]
and I'm trying to replace \" with " with the following command:
s.ToString().Replace("\"", """");
but this is not working.
What is the correct syntax in c#?
A: Try s.ToString().Replace(@"\""", "\"").
The @ tells C# to interpret the string literally and not treat \ as an escape character. "\"" as the second argument uses \ as an escape character to escape the double quotes.
You also don't need to call ToString() if s is already of type string.
Last but not least, don't forget that string replacement is not done in place and will create a new string. If you want to preserve the value, you need to assign it to a variable:
var newString = s.ToString().Replace(@"\""", "\"");
// or s = s.Replace(@"\""", "\""); if "s" is already a string.
A: Update
if you have a string containing ", when you view this string in the Visual Studio immediate window it will display it as \". That does not mean that your string contains a backslash! To prove this to yourself, use Console.WriteLine to display the actual value of the string in a console, and you will see that the backslash is not there.
Here's a screenshot showing the backslash in the immediate window when the string contains only a single quote.
Original answer
Three things:
*
*Strings are immutable. Replace doesn't mutate the string - it returns a new string.
*Do you want to replace a quote "\"" or a backslash followed by a quote "\\\"". If you want the latter, it would be better to use a verbatim string literal so that you can write @"\""" instead.
*You don't need to call ToString on a string.
Try this:
s = s.Replace(@"\""", "\"");
See it on ideone.
A: Ironically, you need to escape your quote marks and your backslash like so:
s.ToString().Replace("\\\"", "\"");
Otherwise it will cat your strings together and do the same as this (if you could actually use single quotes like this):
s.ToString().Replace('"', "");
(your second string has four quotes... that's why you're not getting a compile error from having """)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Merge two Pandas DataFrames based on approximate or exact matches Below is the DataFrames example I want to merge.
#!/usr/bin/env python
import pandas as pd
countries = ['Germany', 'France', 'Indonesia']
rank_one = [1, 5, 7]
capitals = ['Berlin', 'Paris', 'Jakarta']
df1 = pd.DataFrame({'country': countries,
'rank_one': rank_one,
'capital': capitals})
df1 = df1[['country', 'capital', 'rank_one']]
population = ['8M', '82M', '66M', '255M']
rank_two = [0, 1, 6, 9]
df2 = pd.DataFrame({'population': population,
'rank_two': rank_two})
df2 = df2[['rank_two', 'population']]
I want to merge the both DataFrames based on an exact or approximate match.
if rank_two is equal to rank_one
OR
rank_two is the closest and next bigger number from rank_one.
Example :
df1 :
country capital rank_one
0 Germany Berlin 1
1 France Paris 5
2 Indonesia Jakarta 7
df2 :
rank_two population
0 0 8M
1 1 82M
2 6 66M
3 9 255M
df3_result :
country capital rank_one rank_two population
0 Germany Berlin 1 1 82M
1 France Paris 5 6 66M
2 Indonesia Jakarta 7 9 255M
A: By using merge_asof
pd.merge_asof(df1,df2,left_on='rank_one',right_on='rank_two',direction='forward')
Out[1206]:
country capital rank_one rank_two population
0 Germany Berlin 1 1 82M
1 France Paris 5 6 66M
2 Indonesia Jakarta 7 9 255M
A: You can use the pandas 'merge_asof' function
pd.merge_asof(df1, df2, left_on="rank_one", right_on="rank_two", direction='forward')
alternatively if you want to merge by closest and you don't mind if it's higher or lower you can use:
direction="nearest"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52484129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: undefined method `<' for nil:NilClass While creating a bubble sort program i ran into this error:
test.rb:8:in `block in bubble_sort': undefined method `<' for nil:NilClass (NoMethodError)
from test.rb:6:in `downto'
from test.rb:6:in `bubble_sort'
from test.rb:16:in `<main>
does anyone know what does that mean? Here is the code:
def bubble_sort(arr)
length = arr.length
sorted = false
length.downto(0) do |cntr|
if arr[cntr] < arr[cntr + 1]
end
end
end
bubble_sort([2,6,8,1,0,2])
A: The error message undefined method '<' for nil:NilClass means that you are trying to call < on something that is nil.
In your example that must be the if arr[cntr] < arr[cntr + 1] comparison. In a next step we need to find out why arr[cntr] is nil. One reason could be that there is no element in the arr array at the cntr index, another reason might be that the index cntr is out of bounds of the array. In your example it is the second reason that is causing the problem.
Why is the index out of bounds? Let's have a closer look how the loop is build and use an example array [a, b, c] to do so:
length = arr.length # length = 3 # [a, b, c].length
length.downto(0) do |cntr| # 3.downto(0) do |cntr|
if arr[cntr] < arr[cntr + 1] # if arr[3] < arr[4] # in the first iteration
Ops, there aren't not indexes 3 and 4 in the arr array, because indexes start counting with 0 and there are only 3 elements in my example (that makes the last element's index 2).
The fix:
def bubble_sort(array)
(array.length - 2).downto(0).each do |index|
if array[index] < array[index + 1]
# ...
end
end
end
A:
does anyone know what does that mean?
It means that arr[cntr] is nil in this expression
if arr[cntr] < arr[cntr + 1]
Oh, and if this one is nil, then arr[cntr + 1] is definitely nil.
Hint: you're accessing elements out of bounds of the array.
A: In your code length variable value will be 6(length = arr.length).
When you iterate it down to 0 ... in the first iteration cntr variable value will be 6.
so arr[cntr] is getting nil value because you are accessing elements out of bounds of the array. That's why you are getting undefined method < for nil:NilClass (NoMethodError) error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40689956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to scan image taken by camera intent to update gallery in android I have this code in my app but it doesn't seem to be working. Only after restarting my phone then all the images are displayed in the gallery. No i am wondering is there a way to do this as soon as the photo is taken and then update the gallery without the need to restart the phone.
this is what i have:
protected void mediaScan() {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory() + "/" +getResources().getString(R.string.app_name))));
Could anyone please help?
A: Use MediaScannerConnection and its static scanFile() method:
MediaScannerConnection.scanFile(this, new String[] { yourPath }, null, null);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27344885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: change/modify the dropdownlist text by value using jquery i have dropdownlist with the values:
<select id="myddl" name="myddl">
<option value="1">One</option>
<option value="2">Twooo</option>
<option value="3">Three</option>
</select>
I need to change the text Twooo to Two using the value of the dropdownlist option(2). How can i do it in jquery?
A: $('#myddl option[value=2]').text('Two');
A: var myDLLField = $('select[id="myddl"]');
myDLLField.find('option[value="2"]').text("Two");
or, in one line...
$('select[id="myddl"]').find('option[value="2"]').text("Two");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1974256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Unable to register Google Play - Developer console Are we able to be both user of a developer account and owner of a developer console ?
The fact is that my personal Google address is linked to a developer console for my work and I wanted to create my own developer console to publish my personal apps.
Unfortunately, I got the error below while creating my own developer console on Google Play Services. I look for leaving the other account but I wasn't able to find anything like this.
Oh oh ! An error occurred. An unexpected error has occurred. Please retry later.
If possible, I don't want to create a new account but unlink my personal account from my work developer console.
Thanks in advance for your help.
A: After looking at network requests, I saw a request going to Google Payments Services which end to a 500 error. At this moment, I just remember that I've conflict with my Google Payments account. When I solved it, I was totally able to be both member of a Developer Console and owner of my own Developer Console. On the Developer Console UI, I'm able to switch between the 2 accounts thanks to the menu on top right corner.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36536373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Bitbucket - push a new projet to my bitbucket repo I have the folder in my htdocs and I want to push it to an empty bitbucket repo.
So far I've followed the instructions on bitbuket website
git init
git remote add origin https://[email protected]/musica.git
cd /path/to/my/repo
git remote add origin https://[email protected]/musica.git
git push -u origin --all # pushes up the repo and for the first time
But And I'm getting this error
No refs in common and none specified; doing nothing.
Perhaps you should specify a branch such as 'master'.
Everything up-to-date
A: Solved - I've missed a step.
git add -A # to add the brand new folders structure
And
git commit -m 'inicio do projeto'
and finaly
git push -u origin all
A: Try specifying the branch as indicated in the error message.
instead of git push -u origin --all try git push origin master
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28638454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to divide one row in various? I have a column data in a postgresql table that receive data like this: |A|C|F|L|T|U|
The others columns are name, date
Example:
NAME | DATE | DATA
ALYSSON | 2019-01-01 | |A|B|C|
How to create a select that return:
NAME | DATE | DATA
ALYSSON | 2019-01-01 | A
ALYSSON | 2019-01-01 | B
ALYSSON | 2019-01-01 | C
A: You can use string_to_array along with unnest to break your data into first an array and then separate rows.
select * FROM (
select name, date, unnest(string_to_array(data, '|')) as data from stuff
) AS sub
WHERE sub.data != '';
The WHERE clause is required to remove the empty strings at the beginning and end of your data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58417408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can HTTP-header LAST-UPDATED be trusted? I have been using Rex Swain's HTTP Viewer to verify that none of the texts on a certain webpage has been changed recently.
The response was: "Code last updated 21 January 2012", so as I understand it, I can't really assume that anything was actually changed on that date but is it safe to assume that none of the texts on the webpage has been changed since that date?
I am not an HTTP expert, so please use layman terms where possible, thanks :-)
BR
A: A web server typically uses the corresponding file's last updated attribute as the value for the HTTP Last-Modified header, so in general it can be trusted, but it's always possible that the date is wrong, for whatever reason.
The Last-Modified header is usually used for caches, to populate the If-Modified-Since header in subsequent requests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40134830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make a fixed position element appear behind a static position element How can you make an element that has a position: fixed display behind an element with position: static? Changing z-index doesn't seem to matter since they are not absolute.
A: You can use negative z-index on the fixed element.
<div id="fixed">This is fixed</div>
<div id="static">This is static</div>
#fixed {
position:fixed;
z-index:-1;
}
Fiddle Demonstration
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16909230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: TinyMCE editor dislikes being moved around On a page I have, I need to move TinyMCE editors in the DOM tree once in a while. However, for some reason, the editor doesn't like it: it clears itself completely and becomes unusable. As far as I can see, this behavior is consistent between Safari 4 and Firefox 3.6, but not Internet Explorer 7/8. Here's an example.
It truly is annoying to do something that works in Internet Explorer but not with more appreciable browsers. Is there something I missed in the docs about never trying to move an editor in the DOM tree? Is there some kind of workaround?
A: This is a browser bug/issue not a problem with TinyMCE. It's impossible to retain iframe contents in some browsers since once you remove the node from the dom the document/window unloads. I suggest first removing the editor instance then re-adding it instead of moving it in the DOM.
A: Had the same issue and here's how I resolved it...
Create the issue
I use jquery to move the dom element that contains the tinymce editor that causes it to lose all it's contents:
$('.form-group:last').after($('.form-group:first'))
After this point, the editor's iframe contents are removed.
The Solution
var textareaId = 'id_of_textarea';
tinyMCE.get(textareaId).remove();
tinyMCE.execCommand("mceAddEditor", false, textareaId);
There are times when the editor will add the iframe back, but not be visible. If that's the case, unhide the container:
$textarea = $('#' + textareaId)
$textarea.closest('.mce-tinymce.mce-container').show()
Note, this is using tinymce 4.x.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2535569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Subsets and Splits