text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Ignore No Subdomain In htaccess RewriteCond I've got htaccess set up that redirects all subdomains except www to https. However I'd also like it to ignore http://domain.com - currently it redirects to https://domain.com which is no good for what I'm doing.
Any idea what the rewrite condition is for that?
I've tried:
RewriteCond %{HTTP_HOST} !^domain.com [NC]
RewriteCond %{HTTP_HOST} !^http://domain.com [NC]
But neither of those work.
Here's what I'm using at the minute.
# Redirect subdomains to https
RewriteCond %{SERVER_PORT} =80
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^domain.com [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
A: I think your problem is that you need to escape the dot in domain.com, so domain\.com.
# Redirect subdomains to https
RewriteCond %{SERVER_PORT} =80
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^domain\.com [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
You used a 301 (permanent) and not a 302, so you may have your browser not even trying to send requests to the http domain until you close. You should use 302 while testing and put the 301 only wen it's ok.
A: Try this:
RewriteCond %{HTTPS} =off
RewriteCond %{HTTP_HOST} !^(www\.)?domain\.com [NC]
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6328792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: React Lazy loading and infinite scoll to top I am currently working on a messaging platform and previously, we just load all the messages at once as there are not that many messages. Now that that there are many messages, it is starting to take a long time to load everything.
As such, I would like to implement lazy loading but I can't find any documentation explaining how I can do load the latest 20 messages and load more when I scroll up to view the earlier messages (Just like any messaging platform). Is there any way to implement this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73001847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Keeping file permissions with FTP Is there a way I can upload my files from my computer to my server without losing the permissions? Everything is linux.
Thank you!
A: You are aware that ftp is not the program to use on the internet in 2011. The password will be send in cleartext. (In a wired or WPA Enterprise protected wireless network you might be OK as long as all your traffic stays inhouse)
sftp is the secure replacement (based on ssh). put and get commands have the -P option to preserve the permissions.
A: Basically all FTP clients (cute, filezilla, smart, yafc, etc) have the option to set file permissions.
I have not yet seen any feature / option to permanently persist the file permissions from your computer to the server. However you can in filezilla and in cuteftp ( i use these 2) set an advanced property which will auto apply a permission set of your choice to all files uploaded.
Also, i think this is not likely to ever be released as a feature since file permissions are also based on user! Different users on your computers and different users on your server all of which may or may not have differing permissions.
Hope this helped. Cheers.
PS: let me know if you can't find the option in filezilla or cuteftp
A: It depends on your FTP client. I'm sure nearly all FTP clients have this option. For example, my favorite command-line FTP client, Yafc, lets you:
put -p filename
to put while preserving file permissions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6961966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Generate unique ID of an object that stays the same across instances I am generating an object from the database using the following:
$game = $this->game_model->get_by('slug', 'some-title');
I am also using a cache library in Codeigniter where I write to a cache file by:
$this->cache->write($game, $cache);
where $game is the object and $cache is an identifier for that object.
I would like to generate a unique ID for this object to use as the cache name. Something like spl_object_hash but that will stay the same across subsequent instances.
For example if I do:
$cache = spl_object_hash($game);
// Cache object
$this->cache->write($game, $cache);
It will generate 000000006c5ce27300000000564a8706.cache as the unique ID, but if I reload the page, I get a different ID, which defeats the purpose of the cache.
How can I get a consistent unique ID for an object?
A: You can use serialize() and then hash it.
$cache = hash('sha1', serialize($game));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16305786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Update Frame of Rotated UIView I am trying to update the size of rotated UIView. I tried using CGAffineTransform for rotation but whenever I tried updating the size after rotation it messed up the frame.
I somehow managed to update size of rotated view using this stackoverflow answer: rotate-uiimage-and-move which suggests:
*
*Preserving original transform and assigning .identity to the view's transform
*Updating frame of view
*Reassign original transform
Here is my final code which is working perfectly:
func handlePinch(_ gesture: UIPinchGestureRecognizer) {
// Preserve previous transform and assign .identity
let transform = myView.transform
myView.transform = .identity
// Compute new frame
let updatedOrigin = myView.frame.origin.applying(transform.scaledBy(x: gesture.scale, y: gesture.scale))
let updatedSize = CGSize(width: myView.frame.width * gesture.scale, height: myView.frame.height * gesture.scale)
myView.bounds = CGRect(origin: updatedOrigin, size: updatedSize)
// Assign back original transform
textView.transform = transform
gesture.scale = 1
}
Questions:
*
*Is this the right approach to do that? To me it seems like a hack as transform using frame's origin to compute new origin which only works fine when assigned to bounds origin.
*What is the best way to achieve resizing a rotated view?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71476356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bug in Storyboards? I'm trying to follow a YouTube tutorial on using constraints, etc and it gets you to set up a basic Storyboard along with some different coloured views. I can set them up fine, and put the widths, and heights in but as soon as I try to resize a view by the resizing arrows that appear around it's edge, all the other views disappear because their widths/heights are reset to zero. Am I causing this or is it a bug?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27270946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: GWT + JDO + ArrayList I'm getting a Null ArrayList in a program i'm developing. For testing purposes I created this really small example that still has the same problem. I already tried diferent Primary Keys, but the problem persists.
Any ideas or suggestions?
1-Employee class
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Employee {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
private String key;
@Persistent
private ArrayList<String> nicks;
public Employee(ArrayList<String> nicks) {
this.setNicks(nicks);
}
public String getKey() {
return key;
}
public void setNicks(ArrayList<String> nicks) {
this.nicks = nicks;
}
public ArrayList<String> getNicks() {
return nicks;
}
}
2-EmployeeService
public class BookServiceImpl extends RemoteServiceServlet implements
EmployeeService {
public void addEmployee(){
ArrayList<String> nicks = new ArrayList<String>();
nicks.add("name1");
nicks.add("name2");
Employee employee = new Employee(nicks);
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(employee);
} finally {
pm.close();
}
}
/**
* @return
* @throws NotLoggedInException
* @gwt.typeArgs <Employee>
*/
public Collection<Employee> getEmployees() {
PersistenceManager pm = getPersistenceManager();
try {
Query q = pm.newQuery("SELECT FROM " + Employee.class.getName());
Collection<Employee> list =
pm.detachCopyAll((Collection<Employee>)q.execute());
return list;
} finally {
pm.close();
}
}
}
A: Your Employee class did not have detachable = "true".
You should change
@PersistenceCapable(identityType = IdentityType.APPLICATION)
to
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
A: Is it significant that in addEmployee, you obtain the persistenceManager like this:
PersistenceManager pm = PMF.get().getPersistenceManager();
but in getEmployees you call it like this
PersistenceManager pm = getPersistenceManager();
without using PMF.get().
A: I changed the code a bit, and everything is normal now, still I don't know what caused this problem.
I'm using Lists now instead of the collections**(1), I return everything as a simple array trough the RPC(2)** and I changed the way I did the query**(3)**.
(1) List results = (List) query.execute();
(2) return (Employee[]) employees.toArray(new Employee[0]);
(3) Query query = pm.newQuery(Employee.class);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1662467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Show all data in a single object instead of nested object I am using sequelize ORM and for DB I am using MySQL, in which I have associated two tables and getting the data, but I want 2nd data (another table's data) should not come in like nested object instead could we show all data in a single object (both table data).
let me show the screen shot.
What I want to something like.
Ignore the keys and values of data, but my question here, could we here show the data of another table (think like inner join) in the same object, not something like in nested object.
Any suggestion would be appreciable thanks.
A: I'm not sure what you exactly want but according to your input/output I think you want to flatten the nested object(?) and for that you can use the next piece of code-
nested_obj = {"message": "Hey you", "nested_obj": {"id": 1}}
flattened_obj = Object.assign(
{},
...function _flatten(o) {
return [].concat(...Object.keys(o)
.map(k =>
typeof o[k] === 'object' ?
_flatten(o[k]) :
({[k]: o[k]})
)
);
}(nested_obj)
)
console.log(JSON.stringify(flattened_obj));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66765007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Selecting property of anonymous type using LINQ throws exception My Linq query (i want to get list of items sorted by number of orders)
var x = context.Items.Include("Item_qualities").Join(
context.Orders,
i => i.Id,
o => o.Item_id,
(i, o) => new { i, o }
)
.GroupBy(e => new { e.i })
.Select(w => new { w.Key.i, c = w.Count() })
.OrderByDescending(y => y.c)
.ToList().Select(u=>u.i);
Last part Select(u=>u.i) throws exception
The text, ntext, and image data types cannot be compared or sorted,
except when using IS NULL or LIKE operator.
A: That error is pretty clear:
The text data type, which is deprecated as of SQL Server 2005, is not suitable for comparison so it is not possible to do sorting on it. The same goes for image data type. Read this for more details. In other words the database engine cannot do the sorting based on the column you have specified.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42055299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: What's the Return of GetQueuedCompletionStatus when the I/O is cancelled via CancelIoEx? Imagine I have a thread waiting for some I/O packets with GetQueuedCompletionStatus(). Another thread uses CancelIoEx() with lpOverlapped == nullptr to cancel all of the I/Os that the first thread initiated.
Will GetQueuedCompletionStatus() return immediately, and is there an appropriate error-code with GetLastError()? Or will CancelIoEx() prevent the I/Os from ever finishing and GetQueuedCompletionStatus() will remain pending for further I/O?
A: The answers to all of your questions are clearly stated in Microsoft's documentation.
CancelIoEx():
The CancelIoEx function allows you to cancel requests in threads other than the calling thread. The CancelIo function only cancels requests in the same thread that called the CancelIo function. CancelIoEx cancels only outstanding I/O on the handle, it does not change the state of the handle; this means that you cannot rely on the state of the handle because you cannot know whether the operation was completed successfully or canceled.
If there are any pending I/O operations in progress for the specified file handle, the CancelIoEx function marks them for cancellation. Most types of operations can be canceled immediately; other operations can continue toward completion before they are actually canceled and the caller is notified. The CancelIoEx function does not wait for all canceled operations to complete.
If the file handle is associated with a completion port, an I/O completion packet is not queued to the port if a synchronous operation is successfully canceled. For asynchronous operations still pending, the cancel operation will queue an I/O completion packet.
The operation being canceled is completed with one of three statuses; you must check the completion status to determine the completion state. The three statuses are:
*
*The operation completed normally. This can occur even if the operation was canceled, because the cancel request might not have been submitted in time to cancel the operation.
*The operation was canceled. The GetLastError function returns ERROR_OPERATION_ABORTED.
*The operation failed with another error. The GetLastError function returns the relevant error code.
GetQueuedCompletionStatus():
If the GetQueuedCompletionStatus function succeeds, it dequeued a completion packet for a successful I/O operation from the completion port and has stored information in the variables pointed to by the following parameters: lpNumberOfBytes, lpCompletionKey, and lpOverlapped. Upon failure (the return value is FALSE), those same parameters can contain particular value combinations as follows:
*
*If *lpOverlapped is NULL, the function did not dequeue a completion packet from the completion port. In this case, the function does not store information in the variables pointed to by the lpNumberOfBytes and lpCompletionKey parameters, and their values are indeterminate.
*If *lpOverlapped is not NULL and the function dequeues a completion packet for a failed I/O operation from the completion port, the function stores information about the failed operation in the variables pointed to by lpNumberOfBytes, lpCompletionKey, and lpOverlapped. To get extended error information, call GetLastError.
So, this means that CancelIoEx() will simply mark existing asynchronous operations for cancellation, and IF THE DRIVER ACTUALLY CANCELS THEM then completion statuses WILL be posted back to you indicating the operations were cancelled.
If GetQueuedCompletionStatus() returns TRUE, that means an I/O packet with a success status was dequeued.
If GetQueuedCompletionStatus() returns FALSE AND OUTPUTS A NON-NULL OVERLAPPED* pointer, that means an I/O packet with a failure status was dequeued, so all of the output values are valid, and you can use GetLastError() to get the error code for that packet.
If GetQueuedCompletionStatus() returns FALSE AND OUTPUTS A NULL OVERLAPPED* pointer, that means GetQueuedCompletionStatus() itself failed, so all of the output values are indeterminate and should be ignored, and you can use GetLastError() to get the error code for the failure.
A: GetQueuedCompletionStatus return when I/O finished. if initial code of I/O operation was ERROR_IO_PENDING and file bind to IOCP -when I/O finished - packet will be queued to IOCP and GetQueuedCompletionStatus return (for this I/O operation).
so question better be next:
Will I/O will be completed immediately if we call CancelIoEx on file ?
this already depend from concrete diver: are it registered cancel routine (IoSetCancelRoutine) on IRP for which he return STATUS_PENDING.
are this driver immediately IofCompleteRequest when it CancelRoutine called for IRP. any good designed driver must do both. so if you do I/O request on say some built-in windows driver - answer - yes - I/O will be completed immediately.
about error code - usually (almost always) this will be STATUS_CANCELLED - with this status driver complete canceled IRP. the GetQueuedCompletionStatus conver error NTSTATUS to win32 errors. so STATUS_CANCELLED will be converted to ERROR_OPERATION_ABORTED.
so if in short
Will GetQueuedCompletionStatus return immediately
yes (almost always, but depend from driver, from this api - nothing depend)
is there an appropropate error-code ?
yes - almost always this will be ERROR_OPERATION_ABORTED(but again depend from driver and not depend from this api)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64863170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Data-Visualization Python
*Plot 4 different line plots for the 4 companies in dataframe open_prices. Year would be on X-axis, stock price on Y axis, you will need (2,2) plot. Set figure size to 10, 8 and share X-axis for better visualization
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from nsepy import get_history
import datetime as dt
%matplotlib inline
start = dt.datetime(2015, 1, 1)
end = dt.datetime.today()
infy = get_history(symbol='INFY', start = start, end = end)
infy.index = pd.to_datetime(infy.index)
hdfc = get_history(symbol='HDFC', start = start, end = end)
hdfc.index = pd.to_datetime(hdfc.index)
reliance = get_history(symbol='RELIANCE', start = start, end = end)
reliance.index = pd.to_datetime(reliance.index)
wipro = get_history(symbol='WIPRO', start = start, end = end)
wipro.index = pd.to_datetime(wipro.index)
open_prices = pd.concat([infy['Open'], hdfc['Open'],reliance['Open'],
wipro['Open']], axis = 1)
open_prices.columns = ['Infy', 'Hdfc', 'Reliance', 'Wipro']
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
axes[0, 0].plot(open_prices.index.year,open_prices.INFY)
axes[0, 1].plot(open_prices.index.year,open_prices.HDB)
axes[1, 0].plot(open_prices.index.year,open_prices.TTM)
axes[1, 1].plot(open_prices.index.year,open_prices.WIT)
Blank graph is coming.Please help....?!??
A: Below code works fine , I have changed the following things
a) axis should be ax b) DF column names were incorrect c) for any one to try this example would also need to install lxml library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from nsepy import get_history
import datetime as dt
start = dt.datetime(2015, 1, 1)
end = dt.datetime.today()
infy = get_history(symbol='INFY', start = start, end = end)
infy.index = pd.to_datetime(infy.index)
hdfc = get_history(symbol='HDFC', start = start, end = end)
hdfc.index = pd.to_datetime(hdfc.index)
reliance = get_history(symbol='RELIANCE', start = start, end = end)
reliance.index = pd.to_datetime(reliance.index)
wipro = get_history(symbol='WIPRO', start = start, end = end)
wipro.index = pd.to_datetime(wipro.index)
open_prices = pd.concat([infy['Open'], hdfc['Open'],reliance['Open'],
wipro['Open']], axis = 1)
open_prices.columns = ['Infy', 'Hdfc', 'Reliance', 'Wipro']
print(open_prices.columns)
ax=[]
f, ax = plt.subplots(2, 2, sharey=True)
ax[0,0].plot(open_prices.index.year,open_prices.Infy)
ax[1,0].plot(open_prices.index.year,open_prices.Hdfc)
ax[0,1].plot(open_prices.index.year,open_prices.Reliance)
ax[1,1].plot(open_prices.index.year,open_prices.Wipro)
plt.show()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58387520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Recommended video profile We are encoding our videos thinking about being played on Android and iOS native apps, and with bitmovin player on browsers (desktop and mobile). Which video profile should we use? Will the high profile be supported on all devices (Android 4.1+)? We are encoding on h264 and mp4 format.
Thanks a lot!
A: official documentations explains everything (for android)
You can see that H.265 main profile is supported by 5.0+ devices. Also some other profiles are supported by some devices, but their support is implemented by the manufacturers. The documentation lists the formats that are granted to be played. All other formats may be playable, or not depending on the device model and manufacturer. So if you want to support at least most part of the devices, you'll have to follow that table.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38120482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I was training an Ann machine learning model using GridSearchCV and got stuck with an IndexError in gridSearchCV My model starts to train and while executing for sometime it gives an error :-
IndexError: index 37 is out of bounds for axis 0 with size 37
It executes properly for my model without using gridsearchCV with fixed parameters
Here is my code
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
from keras.models import Sequential
from keras.layers import Dense
def build_classifier(optimizer, nb_layers,unit):
classifier = Sequential()
classifier.add(Dense(units = unit, kernel_initializer = 'uniform', activation = 'relu', input_dim = 14))
i = 1
while i <= nb_layers:
classifier.add(Dense(activation="relu", units=unit, kernel_initializer="uniform"))
i += 1
classifier.add(Dense(units = 38, kernel_initializer = 'uniform', activation = 'softmax'))
classifier.compile(optimizer = optimizer, loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])
return classifier
classifier = KerasClassifier(build_fn = build_classifier)
parameters = {'batch_size': [10,25],
'epochs': [100,200],
'optimizer': ['adam'],
'nb_layers': [5,6,7],
'unit':[48,57,76]
}
grid_search = GridSearchCV(estimator = classifier,
param_grid = parameters,
scoring = 'accuracy',
cv=5,n_jobs=-1)
grid_search = grid_search.fit(X_train, y_train)
best_parameters = grid_search.best_params_
best_accuracy = grid_search.best_score_
A: The error IndexError: index 37 is out of bounds for axis 0 with size 37 means that there is no element with index 37 in your object.
In python, if you have an object like array or list, which has elements indexed numerically, if it has n elements, indexes will go from 0 to n-1 (this is the general case, with the exception of reindexing in dataframes).
So, if you ahve 37 elements you can only retrieve elements from 0-36.
A: This is a multi-class classifier with a huge Number of Classes (38 classes). It seems like GridSearchCV isn't spliting your dataset by stratified sampling, may be because you haven't enough data and/or your dataset isn't class-balanced.
According to the documentation:
For integer/None inputs, if the estimator is a classifier and y is
either binary or multiclass, StratifiedKFold is used. In all other
cases, KFold is used.
By using categorical_crossentropy, KerasClassifier will convert targets (a class vector (integers)) to binary class matrix using keras.utils.to_categorical. Since there are 38 classes, each target will be converted to a binary vector of dimension 38 (index from 0 to 37).
I guess that in some splits, the validation set doesn't have samples from all the 38 classes, so targets are converted to vectors of dimension < 38, but since GridSearchCV is fitted with samples from all the 38 classes, it expects vectors of dimension = 38, which causes this error.
A: Take a look at the shape of your y_train. It need to be a some sort of one hot with shape (,37)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58131814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Is there a way to specify an editor on a git command in a one-off style As mentioned above, I am looking for something like this:
$ git commit -m "my first commit" --editor="vim"
that will allow me to one-off swap editor for a single run. Examples where this might be useful is when squashing lengthy histories or writing up messages for a feature commit.
A: You can override EDITOR environment variable just for one git execution:
EDITOR=nano git commit -a
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38576906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Obtain Date value from HTML form and pass it in PHP I'm trying to get a date from an HTML form into PHP, to then pass it to a MYSQL database. In PHP I get the date with a POST method.
$Data = $_POST['Data']; //Data
In HTML i made up this:
<input type="date" name="Data" id="Data" required/>
When I try to send it to my database with the mysqli_query() method, I always get this error:
Incorrect date value: '' for column 'Data' at row 1
Can you please help me?
This is the query if you are interested. All the other variables work.
INSERT INTO 'table_name' ('col1', 'col2', 'col3', Data, 'col5', 'col6')
VALUES ('$var1', '$var2', '$var3', '$Data', '$var5', '$var6')";
EDIT: (Whole Form)
<form action="insert.php">
<div class="banner">
<h1>Prenota pasti al Podere Diamante</h1>
</div>
<div class="item">
<p>Nome</p>
<div class="name-item">
<input type="text" name="Nome" placeholder="Nome" required/>
</div>
</div>
<div class="item">
<p>Numero Telefonico</p>
<input type="text" name="NTelefonico" placeholder="### ### ####" required/>
</div>
<div class="item">
<p>Data di prenotazione</p>
<input type="date" name="Data" id="Data" required/>
<i class="fas fa-calendar-alt"></i>
</div>
<div class="item">
<p>Orario di prenotazione</p>
<input type="time" name="NGruppo" required min="19:00" max="21:30" step="1800"/>
</div>
<div class="item">
<p>Con quante persone sarai?</p>
<input type="number" name="NPersone" min="1" max="150" required/>
</div>
<div class="item">
<p>Note aggiuntive</p>
<textarea rows="3" name="Note"></textarea>
</div>
<div class="btn-block">
<button type="submit" href="/">Invia</button>
</div>
</form>
A: Change
<form action="insert.php">
to
<form action="insert.php" method="post">
The default HTTP method of a form is GET. You must specify POST since you are accessing it using $_POST. Then you should be able to get the value of the Data field in $Data.
If it doesn't fix the errors, try the following:
1 Check the datatype of Data column in your MySQL table, and make sure that your $Data is in correct format.
For example: If your Data column is a DATE column, $Data should be in YYYY-mm-dd format.
Other Date - Time types and format is given here:
Date and Time Types Description
-----------------------------------------------------------------
DATE A date value in CCYY-MM-DD format
-----------------------------------------------------------------
TIME A time value in hh:mm:ss format
-----------------------------------------------------------------
DATETIME A date and time value inCCYY-MM-DD hh:mm:ss format
-----------------------------------------------------------------
TIMESTAMP A timestamp value in CCYY-MM-DD hh:mm:ss format
-----------------------------------------------------------------
YEAR A year value in CCYY or YY format
-----------------------------------------------------------------
Extra Read: Methods GET and POST in HTML forms - what's the difference?http://jkorpela.fi/forms/methods.html
A: In the database you need to set the date field to type date and in the input field of the form you need to capture the correct date format. Or alternatively use a date picker field
<label><strong>Date </strong> </label></div>
<input type="date" name="date">
A: If you need the current date just you the built-in date in php
$now = date('Y-m-d');
Else check your sql date column and make sure it's Varchar then do this
<form action="insert.php"
method="post">
//in your insert try using
'".$Data."' in place of '$Data'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63015747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Changing Alpha of UITableView Section on Cell Select I have an issue when using multiple table view sections. I am trying to change the alpha for a cell when the user taps it. Each section in the table view has one row.
Here is my code.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSIndexPath *indexPathInSection = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
[tableView cellForRowAtIndexPath:indexPathInSection].contentView.alpha = 0.2f;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
NSIndexPath *indexPathInSection = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
[tableView cellForRowAtIndexPath:indexPathInSection].contentView.alpha = 1.0f;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MatchCell *cell = (MatchCell *)[self cellForIdentifier:tableView:@"MatchCell"];
MatchedUser *user = (MatchedUser *)(self.matches)[indexPath.section];
[self configureMatchCell:cell :user :tableView];
NSIndexPath *selection = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
if (selection.section == indexPath.section && cell.isSelected){
cell.contentView.alpha = 0.2f;
}else{
cell.contentView.alpha = 1.0f;
}
return cell;
}
The alpha is applied to the cell that is tapped but other cells are also changed. This is because it is applied according to the row number not the section and row number. How can I specify the cell at the section and row index only?
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27193098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jenkins - shell script - find parameter format not correct
hope one of you can help - I'm running a script in jenkins pipeline, so that I can upload source maps to rollbar, so I need to loop through the minified js files - I'm trying to do this with the FIND command but it keeps giving me an error: find parameter format not correct - script below:
stages {
stage('Set correct environment link') {
steps {
script {
buildTarget = params.targetEnv
if(params.targetEnv.equals("prj1")){
linkTarget = "http://xxx.xxx.xx/xxx/"
} else if(params.targetEnv.equals(.......)..etc.
stage('Uploading source maps to Rollbar') {
steps {
sh ''' #!/bin/bash
# Save a short git hash, must be run from a git
# repository (or a child directory)
version=$(git rev-parse --short HEAD)
# Use the post_server_time access token, you can
# find one in your project access token settings
post_server_item=e1d04646bf614e039d0af3dec3fa03a7
echo "Uploading source maps for version $version!"
# We upload a source map for each resulting JavaScript
# file; the path depends on your build config
for path in $(find dist/renew -name "*.js"); do
# URL of the JavaScript file on the web server
url=${linkTarget}/$path
# a path to a corresponding source map file
source_map="@$path.map"
echo "Uploading source map for $url"
curl --silent --show-error https://api.rollbar.com/api/1/sourcemap \
-F access_token=$post_server_item \
-F version=$version \
-F minified_url=$url \
-F source_map=$source_map \
> /dev/null
done
'''
}
}
stage('Deploy') {
steps {
echo 'Deploying....'
From Bash CLI
A: With the help of @jeb I managed to resolve this FIND issue on jenkins by placing the absolute path for (find) in the shell script - initially it was using the windows FIND cmd, so i needed to point to cygwin find cmd
before: for path in $(find dist/renew -name "*.js"); do
and after: for path in $(/usr/bin/find dist/renew -name "*.js"); do
Thaks to all that commented
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65916274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I deal with app state in a multi-"page" application? I'm having trouble envisioning application state.
For a multi-page application, should each page only load a chunk of the app state?
For example, let's say I have an app that manages my favorite things, books, movies, and games. Each one of those domains will have their own page to manage them. Is the idea that only portions of app state are loaded based on what's needed in the current context?
My app state would look something like this, conceptually.
{
currentUser: { id: 9, userName: 'JUtah' },
books: {},
movies: {},
games: {}
}
However, if I browsed to Books Management, the app state would look like this:
{
currentUser: { id: 9, userName: 'JUtah' },
books: {
1: { title: 'Kung Fu for Kittens', author: 'Dr. Meowrtin Kibble' }
},
movies: {},
games: {}
}
If I browsed to Movie Management, this:
{
currentUser: { id: 9, userName: 'JUtah' },
books: {}
},
movies: {
1: { title: 'John Wick', star: 'Keanu Reeves' }
},
games: {}
}
and so on.
Is this correct? I'm struggling to determine what app state holds at any given time.
A: First of all, React's local state and Redux's global state are different things.
Let's assume you don't use Redux for the moment. State management is up to you totally. But, try to construct your components as pure as possible and use the state where do you really need it. For example, think about a favorites app as you said. The decision is, do you want to show all the favorites categories in the same UI? If yes, then you need to keep all of them in one place, in the App. Then you will pass those state pieces your other components: Book, Movie, etc. Book get the book part of your state for example. They won't have any state, your App does. Here, App is the container component, others are presentational ones or dumb ones.
Is your data really big? Then you will think about other solutions like not fetching all of them (from an API endpoint or from your DB) but fetch part by part then update your state when the client wants more.
But, if you don't plan to show all of them in one place, then you can let your components have their state maybe. Once the user goes to Book component, maybe you fetch only the book data then set its state according to that. As you can see there are pros and cons, in the first method you are doing one fetch and distributing your data to your components, in the second method you are doing multiple fetches. So, think about which one suits you.
I can see you removed the Redux tag, but with Redux you will have one global state in the store. Again, in one point you are doing some fetch then update your state. Then, you will connect your components when they need any data from the state. But again, you can have container/presentational components here, too. One container connects to your store then pass the data to your components. Or, you can connect multiple components to your store. As you examine the examples, you will see best practices about those.
If you are new don't think too much :) Just follow the official documentation, read or watch some good tutorials and try to write your app. When you realize you need to extract some component do it, then think about if you need any state there or not?
So, once the question is very broad then you get an answer which is too broad, some text blocks :) You can't see so many answers like that, because here we share our specific problems. Again, don't bloat yourself with so many thoughts. As you code, you will understand it better.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51851157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Uploading string value into azure storage location as a file content I want to upload a string value as file content into azure storage location but without writing any code and using azure components only. Is there any option available?
A: There are a lot of ways to do this:
*
*Write a string into .txt file and upload the file to a storage container on Azure Portal.
*Generate a long lifetime SAS token on Azure Portal:
and use blob rest API to upload it to a blob, you can do it directly in postman:
Result:
*Use Azure Logic App to do this. Let me know if you have any more questions.
Let me know if you have any more questions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67943128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Dialog dismiss animation not applying I have a DialogFragment whose only child is a StackView. The dialog is launched when a button is clicked in the parent fragment.
I tried to add animations to the fragment via getWindow().setWindowAnimations() but for some reason it was not working.
The approach that I took is to animate the Window's decorView:
public class TrailerDialogFragment extends DialogFragment {
private static final String VIDEOS_EXTRA = "videos extra";
private List<Video> mVideos = new ArrayList<>();
@BindView(R.id.stack_view)
StackView mStackView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Video> videos = getArguments().getParcelableArrayList(VIDEOS_EXTRA);
if (videos != null) {mVideos.addAll(videos);}
}
public static TrailerDialogFragment newInstance(List<Video> videos) {
Bundle bundle = new Bundle();
ArrayList<Video> arrayList = new ArrayList<>();
arrayList.addAll(videos);
bundle.putParcelableArrayList(VIDEOS_EXTRA, arrayList);
TrailerDialogFragment fragment = new TrailerDialogFragment();
fragment.setArguments(bundle);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dialog_stackview, container, false);
ButterKnife.bind(this, rootView);
mStackView.setAdapter(new VideoAdapter(mVideos));
return rootView;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
return dialog;
}
@Override
public void onStart() {
super.onStart();
final View decorView = getDialog()
.getWindow()
.getDecorView();
ObjectAnimator scaleDown = ObjectAnimator.ofPropertyValuesHolder(decorView,
PropertyValuesHolder.ofFloat("scaleX", 0.0f, 1.0f),
PropertyValuesHolder.ofFloat("scaleY", 0.0f, 1.0f),
PropertyValuesHolder.ofFloat("alpha", 0.0f, 1.0f));
scaleDown.setDuration(500);
scaleDown.start();
}
@Override
public void onCancel(DialogInterface dialog) {
final View decorView = getDialog()
.getWindow()
.getDecorView();
ObjectAnimator scaleDown = ObjectAnimator.ofPropertyValuesHolder(decorView,
PropertyValuesHolder.ofFloat("scaleX", 1.0f, 0.0f),
PropertyValuesHolder.ofFloat("scaleY", 1.0f, 0.0f),
PropertyValuesHolder.ofFloat("alpha", 1.0f, 0.0f));
scaleDown.setDuration(500);
scaleDown.start();
super.onCancel(dialog);
}
private static class VideoAdapter extends BaseAdapter {
List<Video> mVideos = new ArrayList<>();
public VideoAdapter(List<Video> videos) {
mVideos.addAll(videos);
}
@Override
public int getCount() {
return mVideos.size();
}
@Override
public Object getItem(int i) {
return mVideos.get(i);
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View resultView;
if (view == null) {
resultView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.dummy_view, viewGroup, false);
} else {
resultView = view;
}
TextView tv = (TextView) resultView.findViewById(R.id.trailer_title);
ImageView image = (ImageView) resultView.findViewById(R.id.trailer_image);
tv.setText(mVideos.get(i).name());
ViewUtil.loadThumbnail(mVideos.get(i).key(), resultView.getContext(), image);
return resultView;
}
}
}
When I click outside of dialog fragment, the onCancel callback is triggered, but for some reason the animation doesn't play. The DialogFragment simply dissappears.
Do you know why this could happen?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38984947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Wordpress xmlrpc SSL Certificate Error (Only On 1 Machine) I'm using the Wordpress xmlrpc Python module on Python 3.6 to automatically write and publish blog posts to my Wordpress site (hosted directly by Wordpress).
The program runs great on one of my Windows machines, but when I try to run it using my second Windows machine, with the exact same code, on the same network, I receive an SSL error. Details below:
import ssl
import wordpress_xmlrpc
from wordpress_xmlrpc import Client
from wordpress_xmlrpc import WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts
from wordpress_xmlrpc.methods.posts import NewPost
from wordpress_xmlrpc.methods.users import GetUserInfo
from wordpress_xmlrpc.methods import posts
from wordpress_xmlrpc.compat import xmlrpc_client
wp = Client("https://website.io/xmlrpc.php", "wordpressusername", "wordpresspassword")
post = WordPressPost()
post.title = "title"
post.content = content
post.post_status = 'publish'
status_draft = 0
status_published = 1
wp.call(NewPost(post))
Here's the error:
File "C:\Python36\Lib\http\client.py", line 964, in send
self.connect()
File "C:\Python36\Lib\http\client.py", line 1400, in connect
server_hostname=server_hostname)
File "C:\Python36\Lib\ssl.py", line 401, in wrap_socket
_context=self, _session=session)
File "C:\Python36\Lib\ssl.py", line 808, in __init__
self.do_handshake()
File "C:\Python36\Lib\ssl.py", line 1061, in do_handshake
self._sslobj.do_handshake()
File "C:\Python36\Lib\ssl.py", line 683, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748)
I've used pip list to view all installed modules on both machines and everything matches exactly. The code is stored on a synced Google Drive folder, so it's literally the exact same .py file both times. I can't understand why it works on one machine but not the other.
I've read the thread here but I don't believe it applies to the wordpress xmlrpc tool. I've read through the documentation here but I can't see anything helpful.
Is this something I have to tweak/delete/refresh the ssl certificates in Chrome or something? Any answers or insight much appreciated. Thanks in advance
A: So, 3 weeks later, I finally found a way to fix this.
I ended up completely uninstalling/deleting Python on my secondary machine and reinstalling everything (along with reinstalling all modules, and confirming via pip list) and now it works (no more SSL error).
For what it's worth, and I can't be sure this is what was causing the issue in the first place, but previously, I was running Python 3.6.1 on the working machine and python 3.6.2 on the other, non-working machine.
When I reinstalled everything, I reinstalled Python 3.6.1 (to match the working machine) and it worked on both.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47115581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When to split users into several Devise models? I have an Rails app with two types of users: customers and suppliers. Each type has access to completely different controllers.
I'm in doubt know if I create one Devise model or two.
Are there any conventions when to use more than one controller in Devise?
I know that this is a general question and very subjective. Nevertheless I would like to know if there is any official guidelines for this? This question has been keeping me thinking for a long time already.
If there eis any forum on SE that is more appropriated for this question, please let me know.
A: I'm guessing that your customers and suppliers have some things in common (username and password, logging in to your site, etc), but they are just able to access different controllers/views/features etc. If you were to create two Devise models, it seems like you'd be creating a bunch of repetition.
This seems like a great fit for role-based authorization. There's a nice description of role-based authorization in the cancan docs: even if you're not using cancan, their docs give some nice examples that could be a starting point for a larger conversation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41270349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R DT datatable - conditional colour format for continuous value I would like to apply conditional formatting using the datatable function in R. Consider the following scenario:
test <- data.frame(
var1 = sapply(1:L, function(x)
paste("<X>",paste0(x,
letters,
LETTERS,
"\n",
collapse=" "))),
var2 = round(rnorm(L),2)
)
test$var2 <- ifelse(test$var2 > 1, 1, test$var2)
test$var2 <- ifelse(test$var2 < -1, -1, test$var2)
test$tmp <- test$var2*255
test$R <- test$G <- 0
test$R <- ifelse(test$tmp < 0, round(abs(test$tmp)), test$R)
test$G <- ifelse(test$tmp > 0, round(test$tmp), test$G)
test$col <- paste0("rgb(",test$R,",",test$G,",0)")
test <- test[,c("var1","var2","col")]
datatable(test)
I would like to font colour of var1 to take values from the col variables (which I don't actually need in the final data table).
Is this possible to achieve?
Many thanks in advance.
A: Take a look to the DT doc
2.9 Escaping table content
You will see that you can put HTML content to your table and by using escape=Fmake it readable in HTML.
and you can do something like this on the varibles of your dataframe.
apply(yourMatrix,2,function(x) ifelse(x>value,
paste0('<span style="color:red">',x,'</span>'),
paste0('<span style="color:blue">',x,'</span>')
)
For example if you have a vector x <- c(1,2,3,4) and want value higher than 0 be red you will have
[1] "<span style=\"color:red\">1</span>"
[2] "<span style=\"color:red\">2</span>"
[3] "<span style=\"color:red\">3</span>"
[4] "<span style=\"color:red\">4</span>"
and then
datatable(yourMatrix, escape = FALSE)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38430713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML5 input type range is not setting to initial value of model AngularJS I am using HTML5 input type of range for slider functionality and binding it to my model.
By default my model will have a value in it, but slider is taking only min and max not value. When I go back from that screen and coming back, slider goes to left end but value remains what I gave last time only.
$scope.maxAmt = $rootScope.maxAmt;
$scope.minAmt = $rootScope.minAmt;
$scope.loanAmt = 5000;
<input type="range" min="{{minAmt}}" max="{{maxAmt}}"
value="{{loanAmt}}" step="500"
ng-model="loanAmt"
>
<output name="loanAmt">{{loanAmt}}</output>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36752572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get single value count across the whole dataset I'm new at pandas and surveying the internet for my learning I've used count(), value_counts() to count values column wise but now I'm stuck in a problem. I've a car crash reporting dataset that has it's empty value replaced with "Not Reported" so I wanted to count the number of cells that have this value across the whole data set and show it column wise.Is there any way for me to achieve such out come?
The dataset has values like this
| Location | Severity | Time | Outcome | Substance Used | Traffic Signal |
| -------- | -------- | ---------- | ----------- | -------------- | -------------- |
| New York | Level 1 | Not Reported | Casualty | Alcohol | Red |
| Texas | Not Reported | 7:00:00 | Minor Injury | Not Reported | Green |
| Not Reported | Level 4 | Not Reported | Not Reported | Smoking | Yellow |
The output required is this.
| Column | Value | Count |
| -------------- | ------------ | ----- |
| Location | Not Reported | 1 |
| Severity | Not Reported | 1 |
| Time | Not Reported | 2 |
| Outcome | Not Reported | 1 |
| Substance Used | Not Reported | 1 |
| Traffic Signal | Not Reported | 0 |
A: You can use:
(df.where(df.eq('Not Reported')).stack(dropna=False)
.groupby(level=1).agg(Value='first', Count='count')
.reset_index()
)
Output:
index Value Count
0 Location Not Reported 1
1 Outcome Not Reported 1
2 Severity Not Reported 1
3 Substance Used Not Reported 1
4 Time Not Reported 2
5 Traffic Signal None 0
A: You can count Not Reported by compare all values by Not Reported with sum, no groupby necessary:
s = df.eq('Not Reported').sum()
print (s)
Location 1
Severity 1
Time 2
Outcome 1
Substance Used 1
Traffic Signal 0
dtype: int64
Your expected ouput is possible get in DataFrame constructor:
df1 = pd.DataFrame({'Column': s.index, 'Value':'Not Reported', 'Count': s.to_numpy()})
print (df1)
Column Value Count
0 Location Not Reported 1
1 Severity Not Reported 1
2 Time Not Reported 2
3 Outcome Not Reported 1
4 Substance Used Not Reported 1
5 Traffic Signal Not Reported 0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74768146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Resolving component from class name in Angular 4 Is it possible to resolve a component from string?
Previously in Angular 2, we are able to do this see here. However, in Angular 4, the same method will throw error.
private resolver: ComponentFactoryResolver
var factories = Array.from(this.resolver['_factories'].keys());
var factoryClass = <Type<any>>factories.find((x: any) => x.name === this.comp);
const factory = this.resolver.resolveComponentFactory(factoryClass);
const compRef = this.vcRef.createComponent(factory);
A: It looks like you might be relying on an implementation detail. However, to get around the error, you can explicitly cast the type to any in order to access the indexer. Assuming there is a _factories property, this should work:
var factories = Array.from((<any>this.resolver)['_factories'].keys());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48300272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Finding the prime numbers used in RSA I got this question in a local hacking event, but I couldn't solve it.
Problem Statement ----
Continuing their snooping habit, NSA kept bugging Alice's communication. Resorting to the age old RSA encryption, Alice used 128-bit RSA encryption to exchange messages. Alice shares her public key as
$0xffffffa95256a837568a41c265f4fe27110814aae19f144762d5cc0bcb931807$
and her public key exponent $\phi(n)$ as $0x11$ with Warden.
However, NSA, with its enormous resource, cracked this 128 bit encryption super easily. Seeing your work on the previous ciphers, NSA decided to offer you a job in their Cryptography group. As a final test, NSA shared this public key which they intercepted from Alice and Warden's conversation. They also gave away the private key that they computed from their message exchange.
$Public$ $Key -
(0xffffffa95256a837568a41c265f4fe27110814aae19f144762d5cc0bcb931807,
0x11)$
$Private$ $Key -
(0xffffffa95256a837568a41c265f4fe27110814aae19f144762d5cc0bcb931807,$
$0xc3c3c3817b3335577e69b9d0e48e2bc1fdf71f1f4f73a38a7d628d39739bbaf1)$
What are the values of $p$ and $q$? (the prime numbers used in key generation)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21347399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Volta with yarn run build system cannot find the path specified This is the first time I'm using Volta, so bear with me.
I have installed globally typescript, node and yarn
yarn -v >> 1.22.10
node -v >> v14.15.4
npm -v >> 6.14.10
These commands work inside and outside my project folder, with the same results.
However if I use yarn build from inside vscode the output is an error stating:
System cannot find the path specified
If I do the same from outside vscode I get the same result:
If I go to the node_modules/.bin folder inside vscode, the command still doesn't work (this time I just only run tsc). The error is the following:
The term tsc is not a cmdlet recognized command, function, script file or executable program. Verify if the name is written correctly or, if there is an access route, verify the route is correct and try again.
But if the command is executed from outside vscode in a cmd window, it works as expected, because tsc is really there:
Additionally, if I run npm run build inside vscode, the command works as expected. This is my package.json:
{
"name": "socket-server",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"license": "MIT",
"scripts": {
"build": "tsc",
"dev": "yarn build --watch --preserveWatchOutput",
"lint": "eslint src --ext js,ts",
"test": "jest"
},
"devDependencies": {
"eslint": "^7.19.0",
"jest": "^26.6.3",
"typescript": "^4.1.3"
},
"volta": {
"node": "14.15.4",
"yarn": "1.22.10"
}
}
I do suspect of volta because volta is managing yarn version, but no npm; but I don't really know what's the issue.
I'm using Windows and my PATH has the following entries:
What am I doing wrong?
Edit: Yes, Shell command shortcut exists:
A: the problem is about vsCode, you should run code . in cmd because if you Open the Command Palette (Ctrl + Shift + P) and type
Shell Command: Install 'code' command in PATH
you won't see noting, after running code . in cmd when you should see like this photo, every things will be fine
A: I’m not sure for Windows, but usually the scripts in node_modules/.bin are symbolic links to scripts. For instance, node_modules/.bin/tsc might point to node_modules/typescript/bin/tsc.
It works outside of the directory because then it uses the global version of tsc.
Seeing your error, I’m suspecting that the symlinks are broken. Maybe just try to remove node_modules directory and redo an npm install.
PS: I’m not familiar with Volta, but it looks more like an NPM problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66041147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: giving a default value for an angular number formcontrol I am working with angular. I am astonished that we cannot give an empty default value for an angular number formcontrol. At the beginning, I set it to 0, but it isn't my requirement, since my input display 0 before entering anything. It must be a solution
A: You can create a FormControl in a reactive form using an empty value, empty string, or even undefined:
Component:
foo = new FormControl();
Template:
<input type="number" [formControl]="foo" />
Here is an example in action that demonstrates the number input being initialized without any value.
Hopefully that helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66375755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: why does tar command in bash script with file list within quotes not work In the code below:
#!/bin/bash
echo AAAAAA > a.txt
echo BBBBBB > b.txt
echo CCCCCC > c.txt
files="a.txt b.txt c.txt"
tar -cvf archive1.tar $files # this line works
tar -cvf archive2.tar "$files" # this line doesn't work - why???
the first tar command works fine, but the 2nd tar line, with "$files" does not. Why is this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73461313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP and OpenSSL stopped working after service change Recently I asked my hosting company to setup a new package and since then my existing package is now giving me errors with anything to do with using openSSL.
For instance, I have a function to generate a GUID:
function generateGUIDV4($data)
{
assert(strlen($data) == 16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
$newID = generateGUIDV4(openssl_random_pseudo_bytes(16));
This now throws an error: Fatal error: Call to undefined function openssl_random_pseudo_bytes(). From what I've researched this has to do with Fatal error: Call to undefined function openssl_random_pseudo_bytes().
Now I'm also getting an error now when I call any web services from my application which again point to the openSSL.
Error:
Objectfaultcode: "WSDL"faultstring: "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://*******'"__proto__: Object
.I've hidden the web service as it's not public. From what I've researched this points to OpenSSL again: SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>.
PHP Ini is showing openSSL IS installed
OpenSSL support enabled
OpenSSL Version OpenSSL 0.9.8b 04 May 2006
Anyone have any ideas or point me in the right direction? I've got the hosting company looking into this.
A: I've fixed this and it had nothing to do with the hosting company.
I published a new version of the site, but in the publish profile I told it to delete all files which deleted the .htaccess file which contained the version of PHP in.
Unfortunately, I needed version 5.4 or above to run my code but since the file was removed it dropped down to 5.2 of PHP.
So I've uploaded a new .htaccess file with the correct version in and everything is working.
Hopefully this may help someone if they're as daft as I am.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41589294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Loop in property in constructor If you have a look at my code below. Is there ANY way to write some kind of loop instead of having repeat Row and ColumnDefinitions?
var grid = new Grid
{
RowSpacing = 12,
ColumnSpacing = 12,
VerticalOptions = LayoutOptions.FillAndExpand,
RowDefinitions =
{
new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
},
ColumnDefinitions =
{
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
}
};
A: You can use loops to create an array of rows and an array of columns beforehand and assign these to the RowDefinitions and ColumnDefinitions properties.
I should have thought you'd need to call RowDefinitions.Add() and ColumnDefinitions.Add() in a loop to do so, though.
A: No, this is not possible because the only way this would work is if you could assign a completely new value to the RowDefinitions property, which you can't:
public RowDefinitionCollection RowDefinitions { get; }
^^^^
The syntax as shown in your question is just a handy way of calling .Add on the object in that property, so there is no way for you to inline in that syntax do this. Your code is just "short" for this:
var temp = new Grid();
temp.RowSpacing = 12;
temp.ColumnSpacing = 12;
temp.VerticalOptions = LayoutOptions.FillAndExpand;
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
... same for columns
Specifically, your code is not doing this:
temp.RowDefinitions = ...
^
You would probably want code like this:
var grid = new Grid()
{
RowSpacing = 12,
ColumnSpacing = 12,
VerticalOptions = LayoutOptions.FillAndExpand,
RowDefinitions = Enumerable.Range(0, 100).Select(_ =>
new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }),
ColumnDefinitions = Enumerable.Range(.....
But you cannot do this as this would require that RowDefinitions and ColumnDefinitions was writable.
The closest thing is like this:
var temp = new Grid
{
RowSpacing = 12,
ColumnSpacing = 12,
VerticalOptions = LayoutOptions.FillAndExpand,
};
for (int index = 0; index < rowCount; index++)
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
... same for columns
var grid = temp;
A: RowDefinitions is RowDefinitionCollection. RowDefinitionCollection is internal which you cannot create outside Grid.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35202799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Difference between Tomcat's extraResourcePaths and aliases to access an external directory Simple question: In Tomcat7, what's the difference between using extraResourcePaths and aliases to access an directory outside the application?
I can use either of these two server.xml snippets and they both seem to work. Both seem to load this URL successfully: http://localhost/app/images/box.jpg. Is there an advantage to using one over the other?
<Context docBase="Eclipse_Project" path="/app"
reloadable="true" source="org.eclipse.jst.j2ee.server:Eclipse_Project"
aliases="/images=D:\path\to\images"/>
or
<Context docBase="Eclipse_Project" path="/app"
reloadable="true" source="org.eclipse.jst.j2ee.server:Eclipse_Project">
<Resources className="org.apache.naming.resources.VirtualDirContext"
extraResourcePaths="/images=D:\path\to\images"/>
</Context>
A: This is the result of having multiple different ways of pulling in resources that aren't part of a WAR or exploded directory. Frankly it is a mess long overdue a clean-up. The 'overlay' (or whatever it ends up being called) feature proposed for Servlet 3.1 (i.e. Tomcat 8) has prompted a major clean-up. All the current implementations will be unified into a single implementation. It isn't pretty though, and it is going to take a while to complete.
Aliases are treated as external to the web application resources. The DirContext checks aliases before it checks its internal resources. Hence when you request the real path you get the original.
If you use extraResourcePaths they are treated as part of the web application resources. It looks like Eclipse has triggered a copy of application resources to the work directory. This is usually done to avoid file locking. Since the extraResourcePaths are treated as part of the webapp, they get copied too and getRealPath() reports the copied location since that is where Tomcat is serving the resources from.
A: After investigating further, I found this difference.
The results of this Java code is different. I still don't know why.
String path = getServletContext().getRealPath("/images");
Using extraResourcePaths, path is below, which is a folder under where Eclipse explodes my web app and not a valid directory.
C:\Projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\Eclipse_Project\images
Using aliases, path is below and is what I actually need.
D:\path\to\images
Now if someone could actually explain this. :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11138701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Invalid results from SQL Server "NOT IN" clause I have run a query on our SQL Server 2012 which returned no results. I discovered that this was incorrect and I SHOULD have gotten 16 records. I changed the query and get the answer expected but I am at a loss to understand why my original query did not work as expected.
So my ORIGINAL query which returned no results was:
SELECT
WPB.[ID number]
FROM
[Fact].[REPORT].[WPB_LIST_OF_IDS] WPB
WHERE
[ID number] NOT IN (SELECT DISTINCT IdNumber
FROM MasterData.Dimension.Customer DC)
The reworked query is this:
SELECT
WPB.[ID number]
FROM
[Fact].[REPORT].[WPB_LIST_OF_IDS] WPB
LEFT JOIN
MasterData.Dimension.Customer DC ON WPB.[ID number] = DC.IdNumber
WHERE
DC.IdNumber IS NULL
Can anyone tell me WHY the first query (which incidentally runs in fractions of a second vs the 2nd which takes a minute) does not work? I don't want to repeat this mistake in the future!
A: Don't use not in with a subquery. It doesn't work the way you expect with NULL values. If any value returned by the subquery is NULL, then no rows are returned at all.
Instead, use not exists. This has the semantics that you expect:
select wpb.[ID number]
from [Fact].[REPORT].[WPB_LIST_OF_IDS] wpb
where not exists (select 1
from MasterData.Dimension.Customer dc
where wpb.[ID number] = dc.IdNumber
);
Of course, the left join method also works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51283226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Return two different sections in my UITableView I'm trying to return two seperate .counts in my UITableView. I kind of know the logic behind it but not using the syntax right. How can I do this? What I want it to do is fill my tableview up with the both .counts. I would also like to put in a label on top of the first section and second section. Anything would help!
Here is what I have so far but I'm only getting the first section of cells. Why isnt it displaying both .counts?
func tableView(tableView: UITableView, numberOfSectionsInTableView: Int) -> Int{
return 2;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 0){
return featSubNames.count
}
else{
return subCatNames.count
}
}
func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
if (section == 0){
????
}
if (section == 1){
????
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
// Configure the cell
switch (indexPath.section) {
case 0:
cell.textLabel?.text = featSubName[indexPath.row]
cell.textLabel?.textColor = UIColor.whiteColor()
case 1:
cell.textLabel?.text = subCatNames[indexPath.row]
cell.textLabel?.textColor = UIColor.whiteColor()
default:
cell.textLabel?.text = "Other"
}
return cell
}
A: Your code seems to be right. To get the UIViews on the header of each section, you can return any object that inherits from a UIView(this doesn't mean that would be nice to). So, you can return a small container with a UIImageView and a UILabel, if you want this for example.
Your code for the viewHeader would be something like this:
func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
// instantiate the view to be returned and placed correctly
let commonLabel = UILabel(frame: CGRectMake(0, 0, tableWidth, 30))
commonLabel.textColor = .blackColor()
commonLabel.textAlignment = .Center
// ... other settings in the properties
if section == 0 {
commonLabel.text = "section1"
// other settings for the first section
}
if section == 1 {
commonLabel.text = "section2"
// other settings ...
}
return commonLabel
}
Notes:
Be sure to set the container view's frame,for sectionHeaders the top view in the hierarchy don't accept auto layout.
Implementing the viewForHeaderInSection method is more accessible to custom UI's, you can use the TitleForHeaderInSection if you wish, but it's limited for more complex stuffs.
EDIT:
If you're using storyboards, you still can use this code, although it's not so elegant in terms of apps that use IB for the UI. For this, you might take a look at this link: How to Implement Custom Table View Section Headers and Footers with Storyboard
. This implements only the view using storyboards, but the delegate part must to be wrote.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28505240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Spring MVC - lookup validators automatically Suppose I have a sample entity class like this:
public class Address {
...
}
and a corresponding validator:
@Component
public AddressValidator implements Validator {
@Override
public boolean supports(Class<?> entityClass) {
return entityClass.equals(Address.class);
}
@Override
public void validate(Object obj, Errors errors) {
...
}
}
When I use a controller like the following, everything works:
@RestController
@RequestMapping("/addresses")
public class AddressController {
@Autowired
private AddressValidator validator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@RequestMapping(method=POST)
public Long addNewAddress(@Valid @RequestBody Address address) {
...
}
}
However, if I omit the validator registering part (i.e. the following), validation is not performed.
@Autowired
private AddressValidator validator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
Having to register validators manually seems pointless. Can I instruct Spring to look up validators automatically (similar to how controllers are looked up)?
It's a Spring Boot based application.
A: You can use my example from gist or below. The idea is to have a main CompositeValidator that will be a holder of all your Validator or SmartValidator instances.
It supports hints and can be also integrate with Hibernate Annotation Validator (LocalValidatorFactoryBean). And also it's possible to have more that one validator per specific Model.
CompositeValidator.java
@Component
public class CompositeValidator implements SmartValidator {
@Autowired
private List<Validator> validators = Collections.emptyList();
@PostConstruct
public void init() {
Collections.sort(validators, AnnotationAwareOrderComparator.INSTANCE);
}
@Override
public boolean supports(Class<?> clazz) {
for (Validator validator : validators) {
if (validator.supports(clazz)) {
return true;
}
}
return false;
}
@Override
public void validate(Object target, Errors errors) {
validate(target, errors, javax.validation.groups.Default.class);
}
@Override
public void validate(Object target, Errors errors, Object... validationHints) {
Class<?> clazz = target.getClass();
for (Validator validator : validators) {
if (validator.supports(clazz)) {
if (validator instanceof SmartValidator) {
((SmartValidator) validator).validate(target, errors, validationHints);
} else {
validator.validate(target, errors);
}
}
}
}
}
SomeController.java
@Controller
@RequestMapping("/my/resources")
public class SomeController {
@RequestMapping(method = RequestMethod.POST)
public Object save(
@Validated(javax.validation.groups.Default.class) // this interface descriptor (class) is used by default
@RequestBody MyResource myResource
) { return null; }
}
Java Config
@Configuration
public class WebConfig {
/** used for Annotation based validation, it can be created by spring automaticaly and you don't do it manualy */
// @Bean
// public Validator jsr303Validator() {
// LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
// // validator.setValidationMessageSource(...);
// return validator;
// }
@Bean
public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
return new WebMvcConfigurerAdapter() {
@Autowired
private CompositeValidator validator;
@Override
public Validator getValidator() {
return validator;
}
}
}
Or XML Config
<!-- used for Annotation based validation, it can be created by spring automaticaly and you don't do it manualy -->
<!--<bean id="jsr303Validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">-->
<!-- <property name="validationMessageSource" ref="messageSource"/>-->
<!--</bean>-->
<mvc:annotation-driven validator="compositeValidator">
//...
</mvc:annotation-driven>
A: You can configure global Validator.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#validation-mvc
If you are using Java based spring configuration with WebMvcConfigurationSupport, you can override getValidator()
/**
* Override this method to provide a custom {@link Validator}.
*/
protected Validator getValidator() {
return null;
}
You may call setValidator(Validator) on the global WebBindingInitializer. This allows you to configure a Validator instance across all @Controller classes. This can be achieved easily by using the Spring MVC namespace:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven validator="globalValidator"/>
</beans>
A: I have not found a build in Spring solution for this, but here is what I do.
I declare my validator beans in the spring java configuration like so:
@Bean
public Validator studentValidator(){
return new StudentValidator();
}
@Bean
public Validator carValidator(){
return new CarValidator();
}
Then I have all controllers extends a base controller like so:
public abstract class BaseController <T> {
public BaseController(List<Validator> validators) {
super();
this.validators = validators;
}
//Register all validators
@InitBinder
protected void initBinder(WebDataBinder binder) {
validators.stream().forEach(v->binder.addValidators(v));
}
}
The concrete class of this controller gets the List injected via dependency injection, like so:
@Controller
public class StudentController extends BaseController<Student>{
@Inject
public StudentController(List<Validator> validators) {
super(validators);
}
}
The base Controller uses the @InitBinder call-back method to register all Validators.
I am surprised that spring doesn't automatically register all objects in class path that implement the Validator interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28915930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Runtime error while working with 2D arrays in a loop C I wrote this piece of code to find the GCD of any two numbers, and as I am working with multiple test cases, I used a 2D array with each testcase as a row and the first two elements in each row to store the numbers. FOr example, a[0][0] stores the first number of the first test case.
It works well up to user input, but the part which calculates the gcd, I'm getting a runtime error. I checked to see if I was trying to access an undefined location in the array, but with no luck.
const int testCase;
scanf("%d", &testCase);
int a[testCase][3], i, j, k;
for(k = 0; k < testCase; k++){
scanf("%d %d", &a[k][0], &a[k][1]);
}
// problem occurs after this
for(j = 0; j < testCase; j++){
for(i = 0; i <= a[j][0] && i <= a[j][1]; i++){
if(a[j][0] % i == 0 && a[j][1] % i == 0){
a[j][2] = i;
}
}
printf("%d\n", a[j][2]);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70554189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP inheritance - methods and properties I'm obviously not understanding inheritance correctly. I'll let my code do the talking:
abstract class Calc {
private $x;
private $y;
public function AddNumbers() {
echo $this->x. " + " .$this->y;
}
}
class myCalc extends Calc {
public function __construct ($x,$y) {
$this->x = $x;
$this->y = $y;
}
}
$calc1 = new myCalc(3,4);
$calc1->AddNumbers();
echo 'done';
exit;
OK, so what's going on here: I'd like to have an abstract class, that would define two properties (x and y) and an abstract method, (nevermind the concatenation of numbers, implementation of the method is out of the scope of my question) which would access there properties.
Then, a concrete class extends that abstract one. As you can see, I can successfully access the properties and set them, but when I call add numbers, it appears as if the properties are not set.
What is going on, why is this not working and how can I fix it?
I could just define a method for adding numbers in concrete class, but I want to have a method in abstract class with a definition that can be reused.
Thanks!
A: The two properties in the abstract class are private, which means they are NOT present and known in any class that extends this one.
So MyCalc does not write to these properties, and you cannot read them in the AddNumbers function. The MyCalc constructor actually creates new, public properties instead.
Make the properties "protected", and it will work.
A: The private keyword defines that only the methods in Calc can modify those variables. If you want methods in Calc and methods in any of its subclasses to access those variables, use the protected keyword instead.
You can access $this->x because PHP will let you create a member variable on the object without declaring it. When you do this the resulting member variable is implicitly declared public but it doesn't relate to the private variable defined in Calc, which is not in scope in myCalc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18772870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to show jquery confirmation dialogue with multiple forms and submit buttons mvc I have a mvc project and on one page there is a table of data with a submit button that is inside its own form tag. I want to have a pop up modal dialogue when the user clicks the delete button to ask for confirmation of the delete. How would you do this with jquery?
A: you can use the ajax.actionlink
@Ajax.ActionLink("Delete", "DeleteUser", new { id = user.user_id }, new AjaxOptions { Confirm = "Are You sure to delete?", UpdateTargetId = "article_1" })
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9955995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Kohana 3 ORM query using NOTIN() Is there a way to use a http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_not-in with Kohana's ORM? Something like:
$products = ORM::factory('products')->notin('contry_id', $csl)->find_all();
A: Use where statement:
$products = ORM::factory('products')->where('contry_id', 'NOT IN', $csl)->find_all();
$csl must be array
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9428991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to focus on form input after appending it to dom? The snippet below adds a form to the page on click:
$(document).ready(function () {
$(".reply").click(function () {
var form = '<form id="rform" action="/sendme" method="POST"><input class="title" name="title" type="text" /><textarea rows="8" name="body"></textarea><input type="submit" value="Submit"></form>';
$(".placeholder").append(form);
});
});
to the html:
<a class="reply" href="#">Reply</a>
<div class="placeholder">
The Reply link can appear anywhere on the page. The problem is that after appending the form, the browser jumps to the top of the page.
I'm wondering how to scroll/focus to the title input field after appending the form.
I've tried adding focus() or scroll() after .append(form) but none worked. I've also searched SO, but could not find useful answers to similar question.
A:
$(document).ready(function() {
$(".reply").click(function(event) {
event.preventDefault();
$('.placeholder').html('');
var form = '<form id="rform" action="/sendme" method="POST"><input class="title" name="title" type="text" /><textarea rows="8" name="body"></textarea><input type="submit" value="Submit"></form>';
$(".placeholder").append(form);
$("input.title").focus();
});
});
input,
textarea {
display: block;
width: 100%;
margin-top: 10px;
box-sizing: border-box;
}
form {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="reply" href="#">Reply</a>
<div class="placeholder"></div>
First , if you donot want it to scroll to top. Use the event.preventDefault();
Second , use $('.placeholder').html(''); if you donot want repeated comment form on click.
third , $("input.title").focus(); works just fine. Already tested
A: Use this code it works
$("[data-scroll-to]").click(function() {
var form = '<form id="rform" action="/sendme" method="POST"><input class="title" id="id2" name="title" type="text" /><textarea rows="8" name="body"></textarea><input type="submit" value="Submit"></form>';
$("#id1").append(form);
var $this = $(this),
$toElement = $this.attr('data-scroll-to'),
$focusElement = $this.attr('data-scroll-focus'),
$offset = $this.attr('data-scroll-offset') * 1 || 0,
$speed = $this.attr('data-scroll-speed') * 1 || 500;
$('html, body').animate({
scrollTop: $($toElement).offset().top + $offset
}, $speed);
if ($focusElement) $($focusElement).focus();
});
https://codepen.io/Thaks123/pen/byWmGo?editors=1111
It works with scroll also.
A: The page is jumping to the top because you are navigating to an anchor. Remove href="#" from the reply link. You could replace it with href="javascript:void(0);"
You should then be able to use .focus() to position the page where you like.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56180552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cast different objects and call a method in same line? I have the code:
foreach(var o in objects)
{
o.Update(time);
if(o is Portal)
{
var a = (Portal)o;
a.Interact(ref player, player.Interact);
}
else if(o is Enemy)
{
var e = (Enemy)o;
e.Update(time, player);
}
}
I don't know if anything like this is possible?
I want to do it in one line.
This is what I have in mind:
(Enemy)o => Update(time, player);
I know it's stupid but I want something similar. The method that has player as a parameter is unique to the Enemy object. I have to parse to call it.
A: You can make your loop simpler (in case you use C# 6 or higher):
foreach(var o in objects)
{
o.Update(time);
(o as Portal)?.Interact(ref player, player.Interact);
(o as Enemy)?.Update(time, player);
}
For C# 5 or lower you should use:
foreach(var o in objects)
{
o.Update(time);
if (o is Portal)
{
((Portal)o).Interact(ref player, player.Interact);
}
else if(o is Enemy)
{
((Enemy)o).Update(time, player);
}
}
In this case you have less lines of code but you cast two times.
You can cast only one time:
foreach(var o in objects)
{
o.Update(time);
var e = o is Portal;
if (e != null)
{
e.Interact(ref player, player.Interact);
}
else
{
((Enemy)o).Update(time, player);
}
}
A: Try this:
((Enemy)o).Update(time, player);
Remember about possible Null Reference Exception if you didn't check a type of this object. In your code everything is fine.
A: You can replace those two lines with a single line as follows:
else if(o is Enemy)
{
((Enemy)o).Update(time, player);
}
A: You call the function in that way:
var a = ((Portal)o).Interact(ref player, player.Interact);
so the type of a will be the returned type of Interact, but in context of your code it won't matter much.
A: To go further than other response, you could use the visitor pattern.
First create a IVisitorClient and a IVisitor interface.
interface IVisitorClient
{
Accept(IVisitor visitor);
}
interface IVisitor
{
Visit(SceneObject o); // here the types of your objects
Visit(Enemy e);
Visit(Portal p);
}
Make your different object implement IVisitorClient.
abstract class SceneObject : IVisitorClient
{
public virtual void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
class Portal : SceneObject
{
...
public override void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
...
}
class Enemy: SceneObject
{
...
public override void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
...
}
Then build an updater that implement IVisitor :
class UpdaterVisitor : IVisitor
{
readonly Player player;
readonly Time time;
public UpdaterVisitor(Player player, Time time)
{
this.player = player;
this.time = time;
}
public void Visit(SceneObject o)
{
e.Update(time);
}
public void Visit(Enemy e)
{
e.Update(time, player);
}
public void Visit(Portal p)
{
p.Interact(ref player, player.Interact);
}
}
Finally, to update the object, the code will look like this.
var updateVisitor = new UpdaterVisitor(player, time);
foreach(var o in objects)
{
o.Accept(updateVisitor);
}
A: Or do it this way to avoid the double cast...
foreach(var o in objects)
{
o.Update(time);
Portal p = o as Portal;
if(p != null)
{
p.Interact(ref player, player.Interact);
}
else
{
Enemy e = o as Enemy;
if (e != null)
{
e.Update(time, player);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41609905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Can a variadic template match a non-variadic template parameter? Consider the following snippet:
template<template<class> class T,class U>
struct apply
{
typedef T<U> type;
};
typedef apply<std::tuple,int>::type tuple_of_one_int; //Should be std::tuple<int>
GCC 4.8.2. says:
type/value mismatch at argument 1 in template parameter list for [...] struct apply
expected a template of type ‘template<class> class T’, got ‘template<class ...> class std::tuple’
Which basically means that a variadic template like std::tuple is not a valid template argument for T in apply.
Is this a GCC bug or does the standard mandates this behaviour?
A: Someone correct me if I'm wrong but it seems like it's correct from this quote:
3 A template-argument matches a template template-parameter (call it P) when each of the template parameters in the template-parameter-list of the template-argument’s corresponding class template or [FI 11] template aliasalias template (call it A) matches the corresponding template parameter in the template-parameter-list of P
A (the given template) has to match each of it's templates parameters to P's the template template.
From the second part of the section we learn the restriction doesn't apply in the reverse, meaning a template template containing a parameter pack can match anything.
When P’s template-parameter-list contains a template parameter pack (14.5.3), the template parameter pack will match zero or more template parameters or template parameter packs in the template-parameter- list of A with the same type and form as the template parameter pack in P
As you probably already knew the way to make it work is
template<template<class> class T,class U>
struct apply
{
typedef T<U> type;
};
template<class T> using tuple_type = std::tuple<T>;
typedef apply<tuple_type,int>::type tuple_of_one_int;
The c++11 standard also has an equivalent example to yours.
template <class ... Types> class C { /∗ ... ∗/ };
template<template<class> class P> class X { /∗ ... ∗/ };
X<C> xc; //ill-formed: a template parameter pack does not match a template parameter
The last comment completely describes your situation, class C would be the equivalent of std::tuple in this case.
A: Your code is ill-formed, there is equivalent example in the standard (under 14.3.3/2):
...
template <class ... Types> class C { /∗ ... ∗/ };
template<template<class> class P> class X { /∗ ... ∗/ };
...
X<C> xc; // ill-formed: a template parameter pack does not match a template parameter
...
A: The fix:
template<template<class...> class T,class U>
struct apply
{
typedef T<U> type;
};
typedef apply<std::tuple,int>::type tuple_of_one_int;
typedef apply<std::vector,int>::type vector_of_int;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20356486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Unable to use Imagick class I have installed imagick version:6.8.6-7 on my PC
Operating system:Windows 7 32-bit
Now i want to use Imagick for my PHP project.I am using Wampserver which provides me PHP version:5.3.10.So i also installed a .dll file,made changes in php.ini,verified if the path is set with php_info() before using Imagick class and everything was ok.
Problem description:
I wrote the script to test if i can use Imagick.Following is the script:
<?PHP
function alist ($array) { //This function prints a text array as an html list.
$alist = "<ul>";
for ($i = 0; $i < sizeof($array); $i++) {
$alist .= "<li>$array[$i]";
}
$alist .= "</ul>";
return $alist;
}
exec("convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"
if(class_exists("imagick") )
{
echo "Ready to use Imagick class";
}
else
{
echo "Cannot use Imagick class";
}
?>
Output
Version return code is 0
Version: ImageMagick 6.8.6-7 2013-07-23 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2013 ImageMagick Studio LLC
Features: DPC OpenMP
Delegates: bzlib djvu fftw fontconfig freetype jng jp2 jpeg lcms lzma openexr pango png ps tiff x xml zlib
Cannot use Imagick class
So even if the Version is properly displayed,i am not able to use Imagick class.How to fix this,help
A: 1: Install ImageMagick software Link
2: Download pecl-5.2-dev.zip (choose the version relevant to your PHP) from http://snaps.php.net/
3: Copy php_imagick.dll from the archive you've downloaded to your PHP extention folder.
4: Add the following line to php.ini (in the exntentions section):
extension=php_imagick.dll
5: Restart your server
A: cmorrissey's link for 2) seems to be broken but dlls can be downloaded here.
If you get a "CORE_RL_wand_.dll is missing" error, the solution is here. In my case, I had to take all the "CORE" dlls from the ImageMagic installation folder and copy them into the /php folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17887372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I plot a predicted vs actual graph for my Logit Model I'm new to R, and was wondering if any of you could help me out with the code to make a predicted vs actual graph. I am trying to predict the direction of stock price movements using a GLM Logit Model. Your help will be appreciated.
cat("\014");
library(readxl);
Smarket = read_excel("C:/Users/Sohaib/Desktop/data.xlsx");
# Download introduction to statistical learning package
library(ISLR)
# Define train and test sample
train = (Smarket$year<2019)
test = Smarket[!train,]
# Fitting the LR model on the data
fit = glm(direction ~ lag1 + open + high + low , data=Smarket, family=binomial, subset=train)
# Predicting against test data
prob = predict(fit, test, type="response")
A: Provided that test also has a column of the variable you are predicting you can just run something like
test$prediction <- prob
Then both the actual outcome as well as your prediction are in the same data.frame and you can easily plot them
test <- test[order(test$prediction, decreasing = TRUE),]
test$id = seq(nrow(test),1)
library(ggplot2)
ggplot(data = test) +
geom_line(aes(x = id, y = prediction)) +
geom_point(aes(x = id, y = direction))
Naturally this is a less beautiful graph than in an ordinary regression model because your dependant variable is binary.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59750790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Eliminating a distinctive blur edge between UINavigationBar and UIVisualEffectView Currently, my view hierarchy consists of a UIViewController (NOT UITableViewController), a UITableView nested in the view controller and a UIVisualEffectView (set to Extra Light) in front of the UITableView, aligned to the bottom of a UINavigationBar. The effect I want to achieve is somewhat similar to that of the App Store's segmented view.
However, I noticed a weird blur edge occurring at the boundary between the navigation bar and the UIVisualEffectView that makes the view look inconsistent, as pictured below (highlighted by the red circle):
Optimally, I would prefer that the UIVisualEffectView blends perfectly with the UINavigationBar's blur.
Thanks.
A: Try to use a UIToolBar instead of a UIVisualEffectView as the background of the segment. The navigation bar has translucent background rather than blur effect. UIToolBar has the same translucent background as navigation bar, so it would look seamless at the edge.
A: Looking to your picture it seems your issue is not attributable to UINavigationBar but to a view where you have added UISegmentedControl.
I don't know your structure but it could be the tableHeaderView (self.tableView.tableHeaderView) so a reasonable way to solve this problem is to change the header color:
Code example:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
var headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.contentView.backgroundColor = UIColor.clearColor()
return header
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38257979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to replace string value with numeric then change string object to numeric? I have a dataset that has numeric values but in some cells it has <0.0001 which is string. How can I replace these with 0.00005. Then I can try to convert to float from string, it won't let me do it since this has to be replaced first. Here is what I have tried and it hasn't worked.
dataframe 'new':
ID
ALL
1
<0.0001
1
<0.0001
1
15.2
1
<0.0001
2
0.030
2
<0.0001
3
<0.0001
new.ALL[new.ALL == '<0.0001'] = '0.00005'
new.select_dtypes(exclude=np.number).replace(to_replace=['<0.0001'],value='0.00005')
neither one works and no error is thrown, it just won't replace it.
A: Does this work:
df['ALL'].str.replace('<0.0001','0.00005').astype('float')
0 0.00005
1 0.00005
2 15.20000
3 0.00005
4 0.03000
5 0.00005
6 0.00005
Name: ALL, dtype: float64
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68007125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: on mouse over show associated div I have a div class "asset-container" with a data-id attribute.
I also have a div class "popover-content" with an associated data-id.
When I hover over "asset-container", I want the "popover-content" show.
There are a lot of these, which is why I have data-id attached to each of the two divs so I can call the associated div to show.
I have tried several iterations of script and am not getting anywhere
js:
$(document).ready(function() {
custom_popover();
});
function custom_popover() {
$(".asset-container").mouseover(function() {
$('.popover-content [data-id=' + this.value + ']').show();
});
}
html:
<ul class="col-xs-4">
<li class="thumnail-video">
<div class="popover-content" data-id="71"></div>
<div class="asset-container">
<video class="img-responsive portrait" type="video/mp4" src="https://ternpro-development.s3.amazonaws.com/media/films/71/mobile/3.mp4" data-id="71"> </video>
</div>
</li>
</ul>
<ul class="col-xs-4">
<li class="thumnail-video">
<div class="popover-content" data-id="69"></div>
<div class="asset-container">
<video class="img-responsive landscape" type="video/mp4" src="https://ternpro-development.s3.amazonaws.com/media/films/69/mobile/2.mp4" data-id="69"></video>
</div>
</li>
</ul>
</div>
A: Change your code to:
$(".asset-container").mouseover(function() {
var id = $(this).children("video").data("id");
$(this).parent().children('.popover-content[data-id=' + id + ']').show();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28225536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Postgresql: Searching a string with similar characters I have a POSTGRESQL Database with names like:
ʿImād ad-Daula Abu ᾽l-Ḥasan
The user may select this value by typing into a text field. But I would like the user to use similar characters. So, that he can type: "imad" or "hasan".
And still get the same result.
It seems a kinda basic problem to me, but I have not found a solution so far.
I tried it with:
SELECT * FROM person WHERE name ILIKE '%hasan%' ORDER BY name ASC
But it doesn't work for these characters.
I would be really greatful for suggestions.
Thanks
A: You can install the extension unaccent:
CREATE EXTENSION unaccent;
And then you are able to do:
SELECT * FROM person WHERE unaccent(name) ILIKE '%hasan%' ORDER BY name ASC
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66456834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to merge df1 & df2 but only keep the new rows of df2 I've been searching up for hours how to resolve my issue but found nothing.
I have 2 dataframes that i want to merge on column X but i want to keep y column from df1 and only add the new rows from df2.
Basically this situation:
df1:
x
y
A
1
B
2
C
3
df2:
x
y
A
45
B
37
D
4
desired result:
x
y
A
1
B
2
C
3
D
4
To achieve this, I have tried ;
pd.merge(df1, df2, on = ['x','y'] , how = 'left')
however this does not yield what I need. I have also tried concat but didn't succeed.
The problem seems trivial but I just can't find how to get around it.
A: I think you should be able to do it with append. You can add the rows from df2 where the 'x' value isn't in df1 already.
df1 = df1.append(df2[~df2['x'].isin(df1['x'])], ignore_index=True)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66789673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQLite DB accessed from multiple threads Consider following: I've got Service, which writes into DB in AsyncTask. And my Activity reads data from DB(consider UI thread for simplicity). I access DB using SQLiteOpenHelper. I create single instance in Application onCreate() and then obtain it in service and activity. Is there any possibility that I would get my DB 'dead locked'? Previously, I used ContentProvider for such operations. Though, it is based on using single SQLiteOpenHelper instance, I decided to simplify my project by excluding ContentProvider.
Consider code:
public class App extends Application {
private OpenHelper openHelper;
@Override
public void onCreate(){
super.onCreate();
openHelper=new OpenHelper();
}
public OpenHelper getHelper(){
return openHelper;
}
}
In Activity:
OpenHelper helper=(App)getApplication().getHelper();
SQLiteDatabase db=helper.getReadableDatabase();
// Do reading
And inside Serice, in separate thread:
OpenHelper helper=(App)getApplication().getHelper();
SQLiteDatabase db=helper.getWritableDatabase();
//Do writing
Would it be safe?
UPD This might be the solution, but not sure how to use it.
A: Late, late answer. You're totally fine. That's the proper way to do it, actually. See my blog post: http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection/. Dig through my profile here. Lots of examples of this. ContentProvdier is just a lot of overhead and not needed unless you're sharing data outside of your app. Transactions are good to speed things up and (obviously) improve consistency, but not needed.
Just use one SqliteOpenHelper in your app and you're safe.
A: My bet: it isn't safe.
To be in safer position you should use SQL transactions. Begin with beginTransaction() or beginTransactionNonExclusive() and finish with endTransaction(). Like shown here
A: This is my solution
I created a class and a private static object to syncronize all db access
public class DBFunctions {
// ...
private static Object lockdb = new Object();
/**
* Do something using DB
*/
public boolean doInsertRecord(final RecordBean beanRecord) {
// ...
boolean success = false;
synchronized (lockdb) {
// ...
//
// here ... the access to db is in exclusive way
//
// ...
final SQLiteStatement statement = db.compileStatement(sqlQuery);
try {
// execute ...
statement.execute();
statement.close();
// ok
success = true;
} catch (Exception e) {
// error
success = false;
}
}
return success;
}
}
I tryed using ASYNC task and it works fine .
I hope is the right way to solve the problem.
Any other suggestions ???
A: Good question. My first thought is it wouldn't be safe. However, according to the SQLite docs, SQLite can be used in 3 modes. The default mode is "serialized" mode:
Serialized. In serialized mode, SQLite
can be safely used by multiple threads
with no restriction
So I assume this it's compiled in serialized mode on Android.
A: Just saw this while I was looking for something else.
This problem looks like it would be efficiently solved by using a ContentProvider. That way both the Activity as well as the Service can use the content provider and that will take care of the Db contention issues.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6225374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: AutoLayout - UIImageView that doesn't rotate How can I get a UIImageView to not rotate when the user rotates their phone?
All other views in the view controller should update with auto-layout as normal, but I want the UIImageView to stay constant.
How can I accomplish this? Right now I'm rotating the image in viewWillTransitionToSize, but that looks terrible and doesn't account for LandscapeLeft vs. LandscapeRight
A: There's no magic flag to have a UIView not rotate, but you could rotate it back with the following code:
-(void) viewDidLoad {
[super viewDidLoad];
// Request to turn on accelerometer and begin receiving accelerometer events
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
- (void)orientationChanged:(NSNotification *)notification {
// Respond to changes in device orientation
switch ([UIDevice currentDevice].orientation)
{
case UIDeviceOrientationLandscapeLeft:
self.img.transform = CGAffineTransformMakeRotation(-M_PI/2);
break;
case UIDeviceOrientationLandscapeRight:
self.img.transform = CGAffineTransformMakeRotation(M_PI/2);
break;
case UIDeviceOrientationPortrait:
self.img.transform = CGAffineTransformMakeRotation(0);
break;
case UIDeviceOrientationPortraitUpsideDown:
self.img.transform = CGAffineTransformMakeRotation(0);
break;
case UIDeviceOrientationFaceUp:
break;
case UIDeviceOrientationFaceDown:
break;
case UIDeviceOrientationUnknown:
break;
}
}
-(void) viewDidDisappear {
// Request to stop receiving accelerometer events and turn off accelerometer
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36970404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apply an operation across multiple lists I know in R if I have a list of matrices, I can use the Reduce function to apply an operation across all the matrices. For example:
l <- list(matrix(rnorm(16), 4, 4), matrix(rnorm(16), 4, 4))
Reduce(`*`, l)
But what if I want to apply this operation across multiple lists? I could do a brute-force approach with a for loop but I feel like there should be a better way. I can do two lists with mapply
l2 <- l
mapply(`*`, l, l2, SIMPLIFY = FALSE)
But if I have more that two I'm not sure how to solve that.
The following thoughts all result in errors:
l3 <- l2
mapply(`*`, l, l2, l3, SIMPLIFY = FALSE)
Error in .Primitive("*")(dots[[1L]][[1L]], dots[[2L]][[1L]], dots[[3L]][[1L]]) :
operator needs one or two arguments
Reduce(`*`, list(l, l2, l3))
Error in f(init, x[[i]]) : non-numeric argument to binary operator
The desired output is a list of length 2 with the elementwise products of each matrix within each list. The brute-force loop would look like this:
out <- vector("list", length = 2)
for(i in 1:2){
out[[i]] <- l[[i]] * l2[[i]] * l3[[i]]
}
A: This combination of Reduce and Map will produce the desired result in base R.
# copy the matrix list
l3 <- l2 <- l
out2 <- Reduce(function(x, y) Map(`*`, x, y), list(l, l2, l3))
which returns
out2
[[1]]
[,1] [,2] [,3] [,4]
[1,] -5.614351e-01 -0.06809906 -0.16847839 0.8450600
[2,] -1.201886e-05 0.02008037 5.64656727 -2.4845526
[3,] 5.587296e-02 -0.54793853 0.02254552 0.4608697
[4,] -9.732049e-04 11.73020448 1.83408770 -1.4844601
[[2]]
[,1] [,2] [,3] [,4]
[1,] -4.7372339865 -0.398501528 0.8918474 0.12433983
[2,] 0.0007413892 0.151864126 -0.2138688 -0.10223482
[3,] -0.0790846342 -0.413330364 2.0640126 -0.01549591
[4,] -0.1888032661 -0.003773035 -0.9246891 -2.30731237
We can check that this is the same as the for loop in the OP.
identical(out, out2)
[1] TRUE
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45220975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: AudioRecord object not initializing In the below code my audioRecord object is not initializing. I tried moving it to the onCreate method and made it a global. I've logged the state and that returns a value of 1 which means ready to use. The debugger says that startRecording is being called on an uninitialized object. It is also saying that it could not get the audio source.
Why am I getting these errors?
package com.tecmark;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class recorder extends Activity {
private Thread thread;
private boolean isRecording;
private AudioRecord recorder;
private FileOutputStream os;
private BufferedOutputStream bos;
private DataOutputStream dos;
private TextView text;
private int audioSource = MediaRecorder.AudioSource.MIC;
private int sampleRate = 22050;
private int channel = AudioFormat.CHANNEL_CONFIGURATION_MONO;
private int encoding = AudioFormat.ENCODING_PCM_16BIT;
private int result = 0;
private int bufferSize;
private byte[] buffer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.v("onCreate", "layout set, about to init audiorec obj");
text = (TextView)findViewById(R.id.TextView01);
bufferSize = AudioRecord.getMinBufferSize(sampleRate,channel,encoding);
buffer = new byte[bufferSize];
recorder = new AudioRecord(audioSource, sampleRate,channel,encoding,
AudioRecord.getMinBufferSize(sampleRate, channel,encoding));
Log.i("recorder obj state",""+recorder.getRecordingState());
}
public void onClickPlay(View v){
}
public void record(){
Log.i("inside record method", "******");
File path = Environment.getExternalStorageDirectory();
Log.v("file path", ""+path.getAbsolutePath());
File file = new File(path, "test.wav");
if(file.exists()){
file.delete();
}
path.mkdirs();
Log.v("file path", ""+file.getAbsolutePath());
try {
os = new FileOutputStream(file);
bos = new BufferedOutputStream(os);
dos = new DataOutputStream(bos);
} catch (Exception e1) {
e1.printStackTrace();
}
int bufferSize = AudioRecord.getMinBufferSize(sampleRate,channel,encoding);
byte[] buffer = new byte[bufferSize];
recorder.startRecording();
isRecording = true;
try{
while (isRecording){
result = recorder.read(buffer, 0, bufferSize);
for(int a=0; a<result;a++){
dos.write(buffer[a]);
if(!isRecording){
recorder.stop();
break;
}
}
}
dos.flush();
dos.close();
}catch(Exception e){
e.printStackTrace();
}
}// end of record method
public void onClickStop(View v){
Log.v("onClickStop", "stop clicked");
isRecording=false;
}
public void onClickReverse(View v){
Log.v("onClickReverse", "reverse clicked");
}
public void onClickRecord(View v){
Log.v("onClickRecourd", "record clicked, thread gona start");
text.setText("recording");
thread = new Thread(new Runnable() {
public void run() {
isRecording = true;
record();
}
});
thread.start();
isRecording = false;
}
}//end of class
Logcat
01-30 15:23:16.724: ERROR/AudioRecord(12817): Could not get audio input for record source 1 01-30 15:23:16.729:
ERROR/AudioRecord-JNI(12817): Error creating AudioRecord instance: initialization check failed. 01-30 15:23:16.729:
ERROR/AudioRecord-Java(12817): [ android.media.AudioRecord ] Error code
-20 when initializing native AudioRecord object. 01-30 15:23:16.729: INFO/recorder obj state(12817): 1 01-30 15:23:16.729:
WARN/dalvikvm(12817): threadid=13: thread exiting with uncaught exception (group=0x4001b180) 01-30 15:23:16.729:
ERROR/AndroidRuntime(12817): Uncaught handler: thread Thread-7 exiting due to uncaught exception 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817): java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord. 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817): at android.media.AudioRecord.startRecording(AudioRecord.java:495) 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817): at com.tecmark.recorder.record(recorder.java:114) 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817): at com.tecmark.recorder$1.run(recorder.java:175) 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817): at java.lang.Thread.run(Thread.java:1096)
A: The trick with using AudioRecord is that each device may have different initialization settings, so you will have to create a method that loops over all possible combinations of bit rates, encoding, etc.
private static int[] mSampleRates = new int[] { 8000, 11025, 22050, 44100 };
public AudioRecord findAudioRecord() {
for (int rate : mSampleRates) {
for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT }) {
for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO }) {
try {
Log.d(C.TAG, "Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: "
+ channelConfig);
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize != AudioRecord.ERROR_BAD_VALUE) {
// check if we can instantiate and have a success
AudioRecord recorder = new AudioRecord(AudioSource.DEFAULT, rate, channelConfig, audioFormat, bufferSize);
if (recorder.getState() == AudioRecord.STATE_INITIALIZED)
return recorder;
}
} catch (Exception e) {
Log.e(C.TAG, rate + "Exception, keep trying.",e);
}
}
}
}
return null;
}
AudioRecord recorder = findAudioRecord();
recorder.release();
A: I had the same issue, it was solved by putting
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
into the manifest.
Since Lollipop, you also need to specifically ask the user for each permission. As they may have revoked them. Make sure the permission is granted.
A: Problem with initializing few AudioRecord objects could by fixed by using audioRecord.release(); before creating next object...
More here: Android AudioRecord - Won't Initialize 2nd time
A: Now, with lollipop, you need to specifically ask the user for each permission. Make sure the permission is granted.
A: Even after doing all of the above steps I was getting the same issue, what worked for me was that my os was marshmallow and I had to ask for permissions.
A: Just had the same problem.
The solution was to restart the device. While playing with the code I did not release the AudioRecord Object which obviously caused the audio device to stuck.
To test whether the audio device worked or not I downloaded Audalyzer from Google Play.
A: If your mobile phone system is Android M or above,perhaps you need to apply record audio permission in Android M.http://developer.android.com/guide/topics/security/permissions.html
A: in my case I had to manually allow the permission in android 7 for microphone, as sean zhu commented.
A: According to the javadocs, all devices are guaranteed to support this format (for recording):
44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT.
Change to CHANNEL_OUT_MONO for playback.
A: I noticed that when the SDCard on the avd I am running gets full the AudioRecord constructor returns null. Have you tried clearing the SDCard?
A: I think this has to do with the thread not knowing that you've paused the main activity and still trying to record after you've stopped the recorder.
I solved it by changing my onResume() and onPause() methods to modify the isRecording boolean.
public void onResume() {
...
isRecording = true;
}
public void onPause() {
...
isRecording = false;
}
Then in your thread, surround both your startRecording() and stop() with if-statements checking for isRecording:
if(isRecording)
recorder.startRecording();
...
if(isRecording)
recorder.stop(); // which you've done
A: I rewrote the answer from @DustinB for anyone who is using Xamarin Android AudioRecord with C#.
int[] sampleRates = new int[] { 44100, 22050, 11025, 8000 };
Encoding[] encodings = new Encoding[] { Encoding.Pcm8bit, Encoding.Pcm16bit };
ChannelIn[] channelConfigs = new ChannelIn[]{ ChannelIn.Mono, ChannelIn.Stereo };
//Not all of the formats are supported on each device
foreach (int sampleRate in sampleRates)
{
foreach (Encoding encoding in encodings)
{
foreach (ChannelIn channelConfig in channelConfigs)
{
try
{
Console.WriteLine("Attempting rate " + sampleRate + "Hz, bits: " + encoding + ", channel: " + channelConfig);
int bufferSize = AudioRecord.GetMinBufferSize(sampleRate, channelConfig, encoding);
if (bufferSize > 0)
{
// check if we can instantiate and have a success
AudioRecord recorder = new AudioRecord(AudioSource.Mic, sampleRate, channelConfig, encoding, bufferSize);
if (recorder.State == State.Initialized)
{
mBufferSize = bufferSize;
mSampleRate = sampleRate;
mChannelConfig = channelConfig;
mEncoding = encoding;
recorder.Release();
recorder = null;
return true;
}
}
}
catch (Exception ex)
{
Console.WriteLine(sampleRate + "Exception, keep trying." + ex.Message);
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4843739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "63"
}
|
Q: how to highlight ListView multiple views on click? Well I want to highlight the view so the user can see which item it have selected. I tried like this:
View.setBackground(COLOR.RED);
Inside listView on item click listener and it works, but if the list get scrolled random views start changing backgrounds. How can I highlight them and don't lose what item is highlighted on listView scroll?
Note: I'm using a custom adapter with one imageView and 3 textView per row.
Thanks
EDIT: Sorry forgot to say that I want to be able to select multiple items.
A: Set the background color of the items layout? look here https://github.com/cplain/custom-list the concepts should be the same - just ignore my runnable
A: A quick way to do this is to create a couple custom styles; in the drawable folder you can create styles for normal and hover or pressed states:
So in ../drawable/ you want to make a couple elements:
1) The list_bg.xml file:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#db0000"
android:centerColor="#c50300"
android:endColor="#b30500"
android:angle="270" />
</shape>
2) The list_bg_hover.xml file:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#db0000"
android:centerColor="#c50300"
android:endColor="#b30500"
android:angle="270" />
</shape>
3) The list_selector.xml file:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/list_bg" android:state_pressed="false" android:state_selected="false"/>
<item android:drawable="@drawable/list_bg_hover" android:state_pressed="true"/>
<item android:drawable="@drawable/list_bg_hover" android:state_pressed="false" android:state_selected="true"/>
</selector>
Now, in order to use this all you have to do is attach the style to your layout for the ListView row item like this, android:listSelector="@drawable/list_selector" and that should do the trick.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14371694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error With UICollectionView Sections While Accessing Cells I'm writing a loop that will go through each one of my cells, and make them wiggle. (Like the deletion effect on iOS's home screen). When I do this with just one cell, it works like a charm. When I write a loop to do this, I get an odd error:
Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'request for number of
items before section 2 when there are only 1 sections in the
collection view'
Now, when I researched this error the only information I could find was that this occurred when a user tried deleting a cell. That's not my case. (Well, yet at least. Just want to make them all wiggle first).
Here is my code:
#define RADIANS(degrees) ((degrees * M_PI) / 180.0)
CGAffineTransform leftWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-5.0));
CGAffineTransform rightWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(5.0));
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
int visible = self.gridView.visibleCells.count;
for (int i = 0; i < visible; i++) {
NSIndexPath *path = [NSIndexPath indexPathWithIndex:i];
myCell = [self.gridView cellForItemAtIndexPath:path];
myCell.transform = leftWobble;
[UIView beginAnimations:@"wobble" context:(__bridge void *)(myCell)];
[UIView setAnimationRepeatAutoreverses:YES]; // important
[UIView setAnimationRepeatCount:10];
[UIView setAnimationDuration:1.25];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(wobbleEnded:finished:context:)];
myCell.transform = rightWobble; // end here & auto-reverse
}
[UIView commitAnimations];
}
@end
Like I said, it works fine for one cell, and throws that error when I try to write a loop to do them all. Does anyone know what's wrong here?
Side note, how can I add a small delete buttons inside the upper left of the collection view cells programmatically in this loop? I'm very, very new to collection views.
Also just found out, my entire view wobbles when I side scroll, not just the cells.... Very odd.
A: Try this:
#define RADIANS(degrees) ((degrees * M_PI) / 180.0)
CGAffineTransform leftWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-5.0));
CGAffineTransform rightWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(5.0));
for (UICollectionView *cell in self.gridView.visibleCells) {
cell.transform = leftWobble;
}
[UIView beginAnimations:@"wobble" context:nil];
[UIView setAnimationRepeatAutoreverses:YES]; // important
[UIView setAnimationRepeatCount:10];
[UIView setAnimationDuration:1.25];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(wobbleEnded:finished:context:)];
for (UICollectionViewCell *cell in self.gridView.visibleCells) {
cell.transform = rightWobble;
}
[UIView commitAnimations];
how can I add a small delete buttons inside the upper left of the collection view cells programmatically in this loop?
Add delete button as UIButton to your cell's subviews in you custom UICollectionViewCell subclass, and setHidden:NO when needed.
Also just found out, my entire view wobbles when I side scroll, not
just the cells.... Very odd.
Edited.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31351638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Valgrind's error message I got "Conditional jump or move depends on uninitialised value(s)" , and it is coming from function process_server(). I have tried to figure out where it is coming, but to no avail.
Message from valgrind.
==2468== Conditional jump or move depends on uninitialised value(s)
==2468== at 0x402B3D: process_server (in /home/emeka/Desktop/dump/project/serverd)
==2468== by 0x402DB3: main (in /home/emeka/Desktop/dump/project/serverd)
==2468==
#include "signal.h"
#include "string.h"
#include "sys/types.h"
#include "unistd.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "netdb.h"
#include "stdlib.h"
#include "ctype.h"
#include "stdio.h"
#include "utility.h"
#include "route.c"
#include "tokenize.c"
#include "bridge.c"
#define PORT 1253
#define ADDRESS "127.0.0.1"
#define START "start"
#define STOP "stop"
#define LISTENQ 4
typedef struct sockaddr SA;
//#define INET6_ADDRSTRLEN 3000
requested_data *re_data;
int switch_ch;
struct sockaddr_in serveraddr;
int start_server(int port){
int listenid;
int optval=1;
typedef struct sockaddr SA;
if((listenid = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
error_message("Error in startServer <Failed to create socket>");
}
if (setsockopt(listenid, SOL_SOCKET, SO_REUSEADDR,
(const void *)&optval , sizeof(int)) < 0)
return -1;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)port);
if(bind(listenid, (SA*)&serveraddr, sizeof(serveraddr)) < 0) {
error_message("Error in startServer <Failed to bind socket>");
}
if(listen(listenid, LISTENQ) < 0) {
error_message("Error in startServer <Failed to listen>");
}
return listenid;
}
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
void process_server(int listenid){
char remoteIP[INET6_ADDRSTRLEN];
int fd, read_size;
const int buffer_size = 1000;
char *client_message = malloc(sizeof(char) * buffer_size);
if(!client_message){
printf("Not enough memory");
abort();
}
struct sockaddr_storage remoteaddr; // client address
socklen_t addrlen;
addrlen = sizeof remoteaddr;
char *gen, gen_int = 0, supplied_answer;
while((fd = accept(listenid, (struct sockaddr *)&remoteaddr, &addrlen))) {
while((read_size = recv(fd, client_message, buffer_size, 0)) > 0) {
printf("%s", client_message);
re_data = router(client_message, read_size);
printf("Method %s --url::%s=+++\n", re_data->method, re_data->url);
switch_ch = 1;
free(client_message);
client_message = malloc(sizeof(char) * buffer_size);
if(!client_message){
printf("Not enough memory");
abort();
}
break;
}
printf("DE server: new connection from %s on "
"socket %d\n",
inet_ntop(remoteaddr.ss_family,
get_in_addr((struct sockaddr*)&remoteaddr),
remoteIP, INET6_ADDRSTRLEN),fd);
str_query *rem_data;
str_query *header_meta = re_data->meta_data;
while(header_meta){
if(strncasecmp(re_data->method, "PUT", 3) == 0){
if(strncasecmp(re_data->url, "/answer", 7) == 0){
if(strlen(re_data->url) == 7){
if(strncasecmp(header_meta->req_name, "question", 8) == 0){
int res_int = parse_input(header_meta->req_value);
if(gen_int == res_int && supplied_answer == res_int){
send(fd, "HTTP status 200 OK" , 18, 0);
} else {
send(fd, "400 Bad Request" , 15, 0);
}
printf("\n Resulted from computation of %s result :: %d\n", header_meta->req_name, res_int);
}
}
}
}
if(switch_ch){
if(strncasecmp(re_data->url, "/question" , 9) == 0){
if(strncasecmp(re_data->method, "GET", 3) == 0){
gen = pmain();
send(fd, gen, strlen(gen), 0);
gen_int = parse_input(gen);
switch_ch = 0;
printf("\n Resulted from generated computation of %s result :: %d\n", header_meta->req_name, gen_int);
free(gen);
}
}
}
if(strncasecmp(header_meta->req_name, "answer", 8) == 0){
supplied_answer = atoi(header_meta->req_value);
}
printf("\nname %s value %s\n", header_meta->req_name, header_meta->req_value);
rem_data = header_meta;
header_meta = header_meta->next;
free(rem_data->req_name);
free(rem_data->req_value);
free(rem_data);
}
if(!client_message){
free(client_message);
}
free(re_data);
close(fd);
}
return;
}
int main(int argc, char **argv) {
int port, pid, server_conn = 1;
int internet_address_len = 15;
char serAdd[internet_address_len];
char strAction[7];
if(argc == 1) {
port = PORT;
strcpy(serAdd, ADDRESS);
} else if(argc == 2){
port = atoi(argv[1]);
strcpy(serAdd, ADDRESS);
} else if(argc == 3) {
port = atoi(argv[1]);
int n = strlen(argv[2]);
strncpy(serAdd, argv[2], n);
if(n >= internet_address_len){
error_message("Internet address is incorrect");
}
serAdd[n] = '\0';
}
printf("\n\tDE is a basic server built to carry out simple things\n"
"\t----- -----\n"
"\t| | |\n"
"\t| | -----\n"
"\t| | |\n"
"\t----- -----\n"
"\tMethods implemented [Get & Put]\n"
"\tTo start type start\n"
"\tTo stop type stop\nDE]");
scanf("%s", strAction);
if (strcmp(strAction, START) == 0){
printf("Server %sed\n", START);
int listenid = start_server(port);
printf("listen on port %d & listening is %d\nDE]", port,listenid);
signal(SIGPIPE, SIG_IGN);
while(server_conn) {
pid =fork();
if(pid == 0) {
process_server(listenid);
break;
}
scanf("%s", strAction);
if (strcmp(strAction, STOP) == 0) {
close(listenid);
return 0;
}
}
}
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38861700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: protect folders via htaccess i want to protect some folders from a normal user but i (from localhost or my IP address) m unable to see the folder structure...so i do this
write a .htaccess file in that folder(eg.project/cms/js) and write below code
# no nasty crackers in here!
order deny,allow
deny from all
allow from 192.168.1.7
but by using this prohibit to everyone( including me) to see that folder structure.....
how do i protect that folder from other users except myself?
A: I think you got the allow and deny the wrong way around:
order allow,deny
allow from 192.168.1.7
deny from all
which first processes all the allow statements and next the deny statements.
A: I just checked, your above example works fine for me on my Apache 2.
Make sure your IP really is 192.168.1.7. Note that if it's the local machine you're trying to access, your IP will be 127.0.0.1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2370095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Exposing a DataGridView's Columns Property on the Designer in a composite UserControl Suppose I have a composite UserControl (called 'ListTable'), consisting of a label, two buttons and a DataGridView. The label is the title for the DataGridView, and the two buttons are Add Row and Delete Row, with basic, obvious functionality.
How do I expose the DataGridView's columns in the Designer, so that I can edit the DataGridView's columns through the UserControl in the exact same way I would if editing the DataGridView itself?
WHAT I'VE TRIED:
Various combinations of wrapping the DataGridView's Columns property in the ListTable via a property titled 'TableColumns' of the form 'List', with various attribute values, such as:
[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
[Editor(typeof(TableColumnEditor),
typeof(System.Drawing.Design.UITypeEditor))]
public List<DataGridViewColumn> TableColumns
{
get
{
List<DataGridViewColumn> columns = new List<DataGridViewColumn>();
foreach (DataGridViewColumn col in table.Columns)
{
columns.Add(col);
}
return columns;
}
set
{
this.table.Columns.Clear();
foreach (DataGridViewColumn col in value)
{
this.table.Columns.Add(col);
}
}
}
Where TableColumnEditor is:
class TableColumnEditor : CollectionEditor
{
public TableColumnEditor(Type type) : base(type) { }
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
{
object result = base.EditValue(context, provider, value);
((ListTable)context.Instance).TableColumns = (List<DataGridViewColumn>)result;
return result;
}
}
None of this has seemed to work. Most of this is just prayful patchwork that I don't completely understand.
So, the classic dilemma: I do need to sit down and learn about these innards, but I don't have the (work)time to do an unfocused, leisurely tramp through MSDN's more esoteric WinForms articles. Is the code above salvageable? Is it in the right direction?
A: Does this help:
Put a BindingSource on the Form (BindingSource1).
Set your DataGridView's Datasource to Binding1.
Open the designer for the Form in question, and assuming you want to show the columns for the MyObject class, enter the following:
this.BindingSource1.Datasource = typeof(YourNamespace.MyObject);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13847303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: gwt component to auto-complete text I am using Google Web Toolkit to create a web based XML and Code editor- in this code/xml data will be in a text area... What I want to do is allow code auto-completion- so when user starts typing some text, the possible complete values for the partially typed in text are shown, now user can either select one of the shown values, or type in the entire value.
Is there a GWT component that does this? The only thing that I could think of is using a Tooltip to show possible auto-completion options, and enable the user to select one of the values from the tooltip (this value should then be entered into the text area).
Is this the only approach to solve my problem? Is there a better way of doing this?
A: GWT library has very robust SuggestBox component for that. See description and example here:
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/SuggestBox.html
Plus, I'd recommend to review a video tutorial how to use it:
http://www.rene-pickhardt.de/building-an-autocomplete-service-in-gwt-screencast-part-3-getting-the-server-code-to-send-a-basic-response/
Actually there are set of videos, but suggestion box functionality is described exactly there.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8970171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get current controller in view I have a View - _Edit which lives in News M/V/C.
I reuse the V/M via the CategoryController as:
return PartialView("/Views/News/_Edit.cshtml", model);
How from within the View - _Edit can I alert the controller name?
When I:
alert('@ViewContext. RouteData.Values["controller"].ToString()');
The Value is: News
However, the URL is: /Category/foobar
Is there a way to get the value 'Category' to alert? thanks
A: Just use:
ViewContext.Controller.GetType().Name
This will give you the whole Controller's Name
A: Create base class for all controllers and put here name attribute:
public abstract class MyBaseController : Controller
{
public abstract string Name { get; }
}
In view
@{
var controller = ViewContext.Controller as MyBaseController;
if (controller != null)
{
@controller.Name
}
}
Controller example
public class SampleController: MyBaseController
{
public override string Name { get { return "Sample"; }
}
A: You are still in the context of your CategoryController even though you're loading a PartialView from your Views/News folder.
A: I have put this in my partial view:
@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()
in the same kind of situation you describe, and it shows the controller described in the URL (Category for you, Product for me), instead of the actual location of the partial view.
So use this alert instead:
alert('@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()');
A: Other way to get current Controller name in View
@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
A: I do it like this:
@ViewContext.RouteData.Values["controller"]
A: You can use any of the below code to get the controller name
@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
If you are using MVC 3 you can use
@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
A: For anyone looking for this nowadays (latest versions) of ASP.NET Core MVC, you can use:
@Context.Request.RouteValues["controller"].ToString()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6852979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "131"
}
|
Q: Loading files in a for loop in matlab I am trying to load different file names contained in a matlab vector inside a for loop. I wrote the following:
fileNames = ['fileName1.mat', ..., 'fileName_n.mat'];
for i=1:n
load(fileNames(i))
...
end
However, it doesn't work because fileNames(i) returns the first letter of the filename only.
How can I give the full file name as argument to load (the size of the string of the filename can vary)
A: Use a cell instead of an array.
fileNames = {'fileName1.mat', ..., 'fileName_n.mat'};
Your code is in principle a string cat, giving you just one string (since strings are arrays of characters).
for i=1:n
load(fileNames{i})
...
end
Use { and } instead of parentheses.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27024444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to commit project's changes to git using ant? I need to commit changes in eclipse project. I use the code below to do this:
<project name="my_library_project">
<macrodef name="git">
<attribute name="command" />
<attribute name="dir" default="" />
<element name="args" optional="true" />
<sequential>
<echo message="git @{command}" />
<exec executable="git" dir="@{dir}">
<arg value="@{command}" />
<args/>
</exec>
</sequential>
</macrodef>
<target name="Library">
<echo>Hello Library!</echo>
</target>
<target name="clean">
<delete dir="build"/>
</target>
<target name="compile">
<mkdir dir="build/classes"/>
<javac srcdir="src" destdir="build/classes"/>
</target>
<target name="jar">
<mkdir dir="build/jar"/>
<jar destfile="build/jar/Library.jar" basedir="build/classes">
<manifest>
<attribute name="Main-Class" value="com.library.test.Test"/>
</manifest>
</jar>
</target>
<target name="run">
<java jar="build/jar/Library.jar" fork="true"/>
</target>
<target name="version" description="Commits all changes to version git">
<input message="New version" addproperty="commit-message" />
<echo message="Commiting all changes with message ${commit-message}" />
<input file="Library.jar" addproperty="added-file" />
<git command="add">
<args>
<arg value="${added-file}" />
</args>
</git>
<git command="commit">
<args>
<arg value="-am ${commit-message}" />
</args>
</git>
</target>
Every task have successfully completed except "version" task. Commit doesn't work. What's the problem? How should fix this code?
This is the output:
Buildfile: C:\Users\sersem\git\Library\Library\build.xml
Library:
[echo] Hello Library!
clean:
[delete] Deleting directory C:\Users\sersem\git\Library\Library\build
compile:
[mkdir] Created dir: C:\Users\sersem\git\Library\Library\build\classes
[javac] C:\Users\sersem\git\Library\Library\build.xml:26: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 20 source files to C:\Users\sersem\git\Library\Library\build\classes
[javac] warning: java\lang\Object.class(java\lang:Object.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\Comparable.class(java\lang:Comparable.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\String.class(java\lang:String.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\BufferedOutputStream.class(java\io:BufferedOutputStream.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\FileNotFoundException.class(java\io:FileNotFoundException.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\FileOutputStream.class(java\io:FileOutputStream.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\IOException.class(java\io:IOException.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\InputStream.class(java\io:InputStream.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\OutputStream.class(java\io:OutputStream.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\Closeable.class(java\io:Closeable.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\AutoCloseable.class(java\lang:AutoCloseable.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\Flushable.class(java\io:Flushable.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\Override.class(java\lang:Override.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\annotation\Annotation.class(java\lang\annotation:Annotation.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\annotation\Target.class(java\lang\annotation:Target.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\annotation\ElementType.class(java\lang\annotation:ElementType.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\annotation\Retention.class(java\lang\annotation:Retention.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\annotation\RetentionPolicy.class(java\lang\annotation:RetentionPolicy.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\Double.class(java\lang:Double.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\Number.class(java\lang:Number.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\System.class(java\lang:System.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\PrintStream.class(java\io:PrintStream.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\FilterOutputStream.class(java\io:FilterOutputStream.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\Exception.class(java\lang:Exception.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\Throwable.class(java\lang:Throwable.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\FileDescriptor.class(java\io:FileDescriptor.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\File.class(java\io:File.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\Error.class(java\lang:Error.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\RuntimeException.class(java\lang:RuntimeException.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\StringBuilder.class(java\lang:StringBuilder.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\AbstractStringBuilder.class(java\lang:AbstractStringBuilder.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\CharSequence.class(java\lang:CharSequence.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\StringBuffer.class(java\lang:StringBuffer.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\io\Serializable.class(java\io:Serializable.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] warning: java\lang\Math.class(java\lang:Math.class): major version 51 is newer than 50, the highest major version supported by this compiler.
[javac] It is recommended that the compiler be upgraded.
[javac] Note: C:\Users\sersem\git\Library\Library\src\com\library\tree\RedBlackTree.java uses unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
[javac] 35 warnings
jar:
[mkdir] Created dir: C:\Users\sersem\git\Library\Library\build\jar
[jar] Building jar: C:\Users\sersem\git\Library\Library\build\jar\Library.jar
run:
[java] Hello
[java] Array is full
[java] 2
[java] 3
[java] 4
[java] 5
[java] 6
[java] 7
[java] 8
[java] 9
BUILD SUCCESSFUL
Total time: 1 second
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21674284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can public_dependency contain references to objects not in all_objects? I have the query below:
select * from public_dependency pd
where REFERENCED_OBJECT_ID = 305318
The strange thing is that this returns 26 rows. When I join in the referenced objects, I get three null rows, but a count of 26. And if I use 'join' I get back 23 rows. So there are objects seemingly not in all_objects but in public_dependency.
select * from public_dependency pd
left join all_objects o on o.OBJECT_ID = pd.OBJECT_ID
where REFERENCED_OBJECT_ID = 305318
How is it possible that there are objects in public_dependency that are not in all_objects?
A: all_objects only shows you objects you have permissions on, not all objects in the database. You'd need to query dba_objects to see everything, if you have permissions to do that.
public_dependency appears to include object IDs for objects you don't have permissions on. The objecct IDs on their own don't tell you much, so it isn't revealing anything about objects you can't see (other than that there are some objects you can't see).
So it isn't odd that there is an apparent discrepancy between what the two views reference. Querying all_dependencies might give you a more comsistent picture.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24541307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why does Math.Sign() throws exception when passed a NaN? Many mathematical functions return NaN when a NaN parameter is passed to them. I was wondering why does Math.Sign() throws an exception when passed a NaN?
How is the decision made for which method return NaN and for which method throw exception. Understanding this will help me to follow the correct design in my own methods.
A: int Math.Sign(Double value) returns an integer ... (-1/0/1). Double.Nan doesn't seem like an integer.
Probably that's the main reason why it throws an exception.
It could also be discussed why Int.NaN doesn't exist, we already had that discussion at Why is Nan (not a number) only available for doubles?
The behaviour of Math.Sign(Double) is documented at https://msdn.microsoft.com/en-us/library/ywb0xks3(v=vs.110).aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44826757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: SQL Server 2005 - Good SQL to create a data dictionary I have to create a data dictionary in an existing database for all user tables within that database in SQL Server 2005.
Does anyone have a good piece of sql to use for this purpose. I am intending to add comments in myself after I have the details of the tables and columns.
A: I don't have the exact sql, but you will need to query the systables and syscolumns tables, which have all of the information you need to create the data dictionary.
A: I would use the "information schema" views. Here are 2 of the most useful views:
SELECT * FROM INFORMATION_SCHEMA.Tables
SELECT * FROM INFORMATION_SCHEMA.Columns
A: Instead of doing this yourself, you could take a look at some SQL Server documentation tools/scripts:
http://www.mssqltips.com/tip.asp?tip=1250
http://www.red-gate.com/products/SQL_Doc/index.htm
http://www.mssqltips.com/tip.asp?tip=1499
A: https://www.csvreader.com/posts/data_dictionary.php
SELECT
d.[primary key],
d.[foreign key],
CASE
WHEN LEN(d.[column]) = 0 THEN d.[table]
ELSE ''
END AS [table],
d.[column],
CAST(d.[description] AS VARCHAR(MAX)) AS [description],
d.[data type],
d.nullable,
d.[identity],
d.[default]
FROM
(
SELECT
'' AS [primary key],
'' AS [foreign key],
s.[name] AS [schema],
CASE
WHEN s.[name] = 'dbo' THEN t.[name]
ELSE s.[name] + '.' + t.[name]
END AS [table],
'' AS [column],
ISNULL(RTRIM(CAST(ep.[value] AS NVARCHAR(4000))), '') AS [description],
'' AS [data type],
'' AS nullable,
'' AS [identity],
'' AS [default],
NULL AS column_id
FROM
sys.tables t
INNER JOIN sys.schemas s ON
s.[schema_id] = t.[schema_id]
-- get description of table, if available
LEFT OUTER JOIN sys.extended_properties ep ON
ep.major_id = t.[object_id] AND
ep.minor_id = 0 AND
ep.name = 'MS_Description' AND
ep.class = 1
WHERE
t.is_ms_shipped = 0 AND
NOT EXISTS
(
SELECT *
FROM
sys.extended_properties ms
WHERE
ms.major_id = t.[object_id] AND
ms.minor_id = 0 AND
ms.class = 1 AND
ms.[name] = 'microsoft_database_tools_support'
)
UNION ALL
SELECT
CASE
WHEN pk.column_id IS NOT NULL THEN 'PK'
ELSE ''
END AS [primary key],
CASE
WHEN fk.primary_table IS NOT NULL
THEN fk.primary_table + '.' + fk.primary_column
ELSE ''
END AS [foreign key],
s.[name] AS [schema],
CASE
WHEN s.[name] = 'dbo' THEN t.[name]
ELSE s.[name] + '.' + t.[name]
END AS [table],
c.[name] AS [column],
ISNULL(RTRIM(CAST(ep.[value] AS NVARCHAR(4000))), '') AS [description],
CASE
WHEN uty.[name] IS NOT NULL THEN uty.[name]
ELSE ''
END +
CASE
WHEN uty.[name] IS NOT NULL AND sty.[name] IS NOT NULL THEN '('
ELSE ''
END +
CASE
WHEN sty.[name] IS NOT NULL THEN sty.[name]
ELSE ''
END +
CASE
WHEN sty.[name] IN ('char', 'nchar', 'varchar', 'nvarchar', 'binary', 'varbinary')
THEN '(' +
CASE
WHEN c.max_length = -1 THEN 'max'
ELSE
CASE
WHEN sty.[name] IN ('nchar', 'nvarchar')
THEN CAST(c.max_length / 2 AS VARCHAR(MAX))
ELSE
CAST(c.max_length AS VARCHAR(MAX))
END
END
+ ')'
WHEN sty.[name] IN ('numeric', 'decimal')
THEN '(' +
CAST(c.precision AS VARCHAR(MAX)) + ', ' + CAST(c.scale AS VARCHAR(MAX))
+ ')'
ELSE
''
END +
CASE
WHEN uty.[name] IS NOT NULL AND sty.[name] IS NOT NULL THEN ')'
ELSE ''
END AS [data type],
CASE
WHEN c.is_nullable = 1 THEN 'Y'
ELSE ''
END AS nullable,
CASE
WHEN c.is_identity = 1 THEN 'Y'
ELSE ''
END AS [identity],
ISNULL(dc.[definition], '') AS [default],
c.column_id
FROM
sys.columns c
INNER JOIN sys.tables t ON
t.[object_id] = c.[object_id]
INNER JOIN sys.schemas s ON
s.[schema_id] = t.[schema_id]
-- get name of user data type
LEFT OUTER JOIN sys.types uty ON
uty.system_type_id = c.system_type_id AND
uty.user_type_id = c.user_type_id AND
c.user_type_id <> c.system_type_id
-- get name of system data type
LEFT OUTER JOIN sys.types sty ON
sty.system_type_id = c.system_type_id AND
sty.user_type_id = c.system_type_id
-- get description of column, if available
LEFT OUTER JOIN sys.extended_properties ep ON
ep.major_id = t.[object_id] AND
ep.minor_id = c.column_id AND
ep.[name] = 'MS_Description' AND
ep.[class] = 1
-- get default's code text
LEFT OUTER JOIN sys.default_constraints dc ON
dc.parent_object_id = t.[object_id] AND
dc.parent_column_id = c.column_id
-- check for inclusion in primary key
LEFT OUTER JOIN
(
SELECT
ic.column_id,
i.[object_id]
FROM
sys.indexes i
INNER JOIN sys.index_columns ic ON
ic.index_id = i.index_id AND
ic.[object_id] = i.[object_id]
WHERE
i.is_primary_key = 1
) pk ON
pk.column_id = c.column_id AND
pk.[object_id] = t.[object_id]
-- check for inclusion in foreign key
LEFT OUTER JOIN
(
SELECT
CASE
WHEN s.[name] = 'dbo' THEN pk.[name]
ELSE s.[name] + '.' + pk.[name]
END AS primary_table,
pkc.[name] as primary_column,
fkc.parent_object_id,
fkc.parent_column_id
FROM
sys.foreign_keys fk
INNER JOIN sys.tables pk ON
fk.referenced_object_id = pk.[object_id]
INNER JOIN sys.schemas s ON
s.[schema_id] = pk.[schema_id]
INNER JOIN sys.foreign_key_columns fkc ON
fkc.constraint_object_id = fk.[object_id] AND
fkc.referenced_object_id = pk.[object_id]
INNER JOIN sys.columns pkc ON
pkc.[object_id] = pk.[object_id] AND
pkc.column_id = fkc.referenced_column_id
) fk ON
fk.parent_object_id = t.[object_id] AND
fk.parent_column_id = c.column_id
WHERE
t.is_ms_shipped = 0 AND
NOT EXISTS
(
SELECT *
FROM
sys.extended_properties ms
WHERE
ms.major_id = t.[object_id] AND
ms.minor_id = 0 AND
ms.class = 1 AND
ms.[name] = 'microsoft_database_tools_support'
)
) d
ORDER BY
d.[schema],
d.[table],
d.column_id;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2059516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: @keyframe animation on safari I'm trying to do a very simple rotation animation using keyframes. My animation is not showing up in Safari 6 using retina macbook pro and ipad mini. What's weird is that it does work inside jfiddle iframe window.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<style type='text/css'>
body {padding: 25px; background: black;}
.one {
-webkit-animation: all 6s linear infinite;
background: red;
}
@-webkit-keyframes all
{
0% {-webkit-transform: rotateY(0deg);}
100% {-webkit-transform: rotateY(360deg);}
}
</style>
</head>
<body>
<div class="one">test</div>
</body>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30657398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a better way of structuring a functionality using BLoC? Im wrote a bloc for a functionality that has a home page (that fetches a list of items) and a create/edit page (that creates/updates items).
My bloc is currently in charge of handling both pages since they belong to the same functionality, but my code is getting a little bit harder to read/write then usual because im handling 2 states at once.
class MeusSellersState extends Equatable {
const MeusSellersState({
this.home,
this.form,
});
// Home and Form are my two states.
final Home home;
final Form form;
MeusSellersState copyWith({
Home home,
Form form,
}) {
return MeusSellersState(
home: home ?? this.home,
form: form ?? this.form,
);
}
@override
List<Object> get props => [home, form];
}
I know i could separate this bloc in two, but im worried that more complex functionalities could make me write several blocs and pollute even more my code.
Does anyone know a better solution ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65778584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the parameter passed to the callback function of a promise in this example? I'm following an example online:
const jeffBuysCake3 = cakeType => {
return new Promise((resolve, reject) => {
setTimeout(()=> {
if (cakeType
=== 'black forest') {
resolve('black forest cake!') //Callback function
} else {
reject('No cake ') //Callback function
}
}, 1000)
})
}
console.log(jeffBuysCake3('black forest').then(cake => console.log(cake)).catch(nocake => console.log(nocake)))
This returns black forest cake!
The part I don't understand is cake => console.log(cake)
What is cake in this example?
I understand that passing 'black forest' represents the parameter cakeType.
However It's not clear to me what 'cake' is.
Does cake = resolve?
A: Cake means the result of the successfully called promise, in this example they probably want to mean the cake result, and the cake result is a "black forest".
You could write it like this
jeffBuysCake3('black forest')
.then(result => console.log(result))
.catch(error => console.log(error))
and the result is going to be "black forest cake",
if the promise function was like this
const jeffBuysCake3 = cakeType => {
return new Promise((resolve, reject) => {
setTimeout(()=> {
if (cakeType
=== 'black forest') {
resolve('Strawberry cake !') //Callback function
} else {
reject('No cake for you today') //Callback function
}
}, 1000)
})
}
the result is going to be "Strawberry Cake !", while if there was an error it would print out "No cake for you today".
In case you don't know how promises work, when we supply .then it means if the promise resolved (successfully) then give me back the result. If it couldn't be resolved, then catch the error which then we use .catch.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69616511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the architecture of BlogEngine.net extension manager? I was just wondering that what is the architecture of blogengine.net extension manager ?
How it loads the extension dynamically, how can I use same kind of functionality in my web applications ? so that every time i just create one class and corresponding page then just plug into the website.
Moreover I am interested to know the architecture as I didnt find any article or tutorial on it.
Any help would be appreciable.
A: You can see for yourself the code is on codeplex
A: You can read about what it is and how it works in the wiki docs.
Blogengine uses reflection to find and instantiate types attributed as "extension" and extensions itself use event listeners to communicate with core library. Extension manager is basically API and admin front-end for all extensions running on the blog.
A: Maybe the Plugin Pattern, have a look here how this works..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1319159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to validate the header of token for JSON? I am trying to use token in my search function. How to check the token is correct or not? If token correct then retrieve body to request the server. If wrong then just return the error message.
Request JSON
{
"header": {
"Token": "558fedce-a84e-4a9a-8698-5cd27d5af3ed"
},
"body": {
"WarehouseCode": "W001",
"CompanyCode": "C001"
}
}
For example my token is 558fedce-a84e-4a9a-8698-5cd27d5af3ed so if correct then get the body part and serialize to request the server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60388124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to bind a singleton bean in weld + jersey + javaSE My app needs to register with another app. The registration status needs to be available on a REST resource. How to bind/register a singleton object in weld? The registration process has to happen irrespective of whether the status endpoint is invoked or not.
A: Rather than trying to register a initialized bean, I'm now initializing (registering) after the bean is loaded. Using weld callback I could achive it. Inversion of control after all ;). More Info: http://docs.jboss.org/weld/reference/latest/en-US/html/environments.html#_cdi_se_module
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39075740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Access AD users OneDrive for Businesses through Microsoft Graph in app-mode Is it possible to use the Microsoft Graph API to access a users OneDrive for Business folders and files when running in app-mode?
I've successfully configured the app in Azure AD (with certificate, etc.), I've been able to get bearer token and I've also successfully requested data from certain endpoints. However: I am are not able to work with the users OneDrive for Business folders or files.
In other cases I’ve been using a service account (a user account with full administrative privileges) to perform CRUD operations on folders and files in the users OneDrives, but this requires me to check (and set) permissions on all folders and files before any CRUD operation and also exposes the service account to the users in file and folder permission settings. With the Graph API in app-mode I assume that all these issues goes away?
I have some examples on what works, and more importantly, some that doesen’t:
*
*graph.microsoft.com/v1.0/users
Returns a list of users without issues.
*graph.microsoft.com/v1.0/users/UPN-PLACEHOLDER
Returns information about the specified user without issues.
*graph.microsoft.com/v1.0/users/UPN-PLACEHOLDER/drive
Returns information about the specified users drive without issues.
*graph.microsoft.com/v1.0/users/UPN-PLACEHOLDER/drive/root
Returns information about the specified users drive root without issues.
*graph.microsoft.com/v1.0/users/UPN-PLACEHOLDER/drive/root/children
Does not return information about the specified users drive root children as expected.
*graph.microsoft.com/v1.0/drives/UPN-PLACEHOLDER/root/children
Does not return information about the specified users drive root children as expected.
*graph.microsoft.com/v1.0/drives/DRIVE-ID-PLACEHOLDER/root/children
Does not return information about the specified users drive root children as expected.
Other notes:
*
*All these endpoints work as expected if I log in using a regular user account and the «/me» keyword or if I use a service account (with full administrative privileges) and UPNs to other user accounts, but in app-mode with UPNs all request for information on a deeper level than root (ie. root/children or specific folders) returns empy.
*We’ve tried working with both the SDK abstraction and pure HTTP requests without success.
*We’ve tried a lot of different app priviledge combinations and currently have ALL PERMISSIONS ON
A: The reason you can't do this is that we don't yet expose any app-only permissions to access OneDrive files. This is something we are working on and hope to expose very soon. Please stay tuned to our blog posts where we'll let folks know when this capability is added.
Hope this helps,
A: I am using AAD v2, registered the app in Microsoft App registration portal. Once the admin gives consent to the app via the app consent url that contains tenant id and client id, the app can access to all users drives and files with App Mod permissions. So your scenario is possible now, just wanted to add that information since the accepted answer seems outdated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38185025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I speed up this Where? Let's say I have a class like this:
class ItemLimits
{
public string strAccountNumber = string.Empty;
public string strUserCode = string.Empty;
public long lAccumulatedAmount = 0L;
}
I have an array of these with 50000 elements in it.
I also have a dataset of 50000 items (more or less), and I need to find the element in the ItemLimits array that matches to this dataset.
This is currently being done in a loop through the dataset with this:
ItemLimits ilItemLimit = itemlimits.Where(s => s.strUserCode.Equals(dataset[i].User_UserCode, StringComparison.CurrentCultureIgnoreCase)
&& s.strAccountNumber.Equals(strUnEditedHomingAccountNo, StringComparison.CurrentCultureIgnoreCase)).First();
strUnEditedHomingAccountNo is fetched from the dataset earlier.
Once I've found the ItemLimit I need, I need to add to its lAccumulatedAmount.
What I've seen from my performance benchmarks is that this is very fast as the loop starts, but slows down over time. It's a linear slowdown which you can see in this graph I made:
By the time I reach ~40000 items each item is taking ~40ms to complete. This makes sense in my head because I assume it's just iterating through the items one by one until it finds a match, which is obviously quite slow with large amounts of items.
The number of items in both the array and the dataset can vary greatly.
I've thought about trying to order the array and doing a Array.BinarySearch, but I don't know how to order it most efficiently given that the strUserCode and strAccountNumber can both change, and I can't predict the order of the dataset either.
This is the slowest part of the program which is why I would like to try optimize it (around 70% of the time is spent just doing this, and there's a lot of other stuff going on).
If anyone could give me some pointers on what I can do, it would be MUCH appreciated.
I'm using .NET 3.5 and I can't change that.
A: I've ditched the Where entirely and done it using the Array.BinarySearch using this comparer:
class ItemLimitsComparer : Comparer<ItemLimits>
{
public override int Compare(ItemLimits x, ItemLimits y)
{
if(Convert.ToInt32(x.strUserCode) < Convert.ToInt32(y.strUserCode))
{
return -1;
}
if(Convert.ToInt32(x.strUserCode) > Convert.ToInt32(y.strUserCode))
{
return 1;
}
if(Convert.ToInt32(x.strUserCode) == Convert.ToInt32(y.strUserCode))
{
if(Convert.ToInt64(x.strAccountNumber) < Convert.ToInt64(y.strAccountNumber))
{
return -1;
}
if(Convert.ToInt64(x.strAccountNumber) > Convert.ToInt64(y.strAccountNumber))
{
return 1;
}
if(Convert.ToInt64(x.strAccountNumber) == Convert.ToInt64(y.strAccountNumber))
{
return 0;
}
}
return 0;
}
}
(this is the first time I've used this, I suspect I have a bug lurking somewhere)
The Where has been replaced by this:
int index = Array.BinarySearch(itlaCreditLimits, new ItemLimits { strUserCode = dataset[i].User_UserCode, strAccountNumber = strUnEditedHomingAccountNo }, new ItemLimitsComparer());
if(index < 0)
{
throw new Exception("Didn't find ItemLimit for UserCode = " + dataset.User_UserCode + " and account number " + strUnEditedHomingAccountNo);
}
ItemLimits ilItemLimit = itlaCreditLimits[index];
This has got me down from 15 minutes for all 50k items to 25 seconds.
A: I think that you are correct to what's causing this problem and I suggest you use something with a fast look-up to speed things up. Something like a dictionary, it's very fast. You already know how to compare and see if you have the correct record and you also only look for one match, or the first...
Try something like this, you'll need to change the type of the DataSet (no idea of what you are using) and maybe decide how to handle key-collisions when making the itemLimitDictionary but other than that it should speed things up nicely:
public void DoTheNeedfull(ItemLimit[] itemLimits, DataSet dataSet)
{
var itemLimitDictionary = itemLimits.ToDictionary(i => MakeKey(i.One, i.Two), i => i);
for(var i = 0; i < dataSet.Count; i++)
{
var strUnEditedHomingAccountNo = BlackMagicMethod(dataSet[i]);
var key = MakeKey(dataSet[i].User_UserCode, strUnEditedHomingAccountNo);
if(itemLimitDictionary.ContainsKey(key))
{
// do your thing
}
else
{
// maybe this is an error
}
}
}
private string MakeKey(string keyPartOne, string keyPartTwo)
{
return keyPartOne.ToUpperInvariant() + keyPartTwo.ToUpperInvariant();
}
A: So as far as i understand you like to iterate through your dataset and than increase a counter. That counter is specific to some properties of the dataset entry.
So it sounds to be a job for the GroupJoin() linq statement. With that you would get an ItemLimits object with all matching dataset items as IEnumerable<DataSetItem>. Then you could call Aggregate() on this inner enumeration and write this information into the given ItemLimits object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25995289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting top terms per affinity propagation cluster in scikit-learn I am trying different clustering methods for a bunch of news texts, and am struggling to find any way to find top terms per cluster for sklearns affinity propagation, and am becoming unsure if this is even possible.
For k-means clustering I am using the same approach as here: https://scikit-learn.org/0.19/auto_examples/text/document_clustering.html
I would logically want to use the same X for affinity propagation as for k-means.
Anyone know how producing similar results with affinity propagation would be possible?
A: You can compute the mean, and analyze it the same way as you did for k-means.
For maybe better results, you can weigh each document by the responsibility factor, if these are exposed by the sklearn API.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54346882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Make global variables available in multiple modules I am creating an application consisting of several modules. There is one main.py file which will be the file to run the application. The main.py file will load the configuration file(s) and put them in the 'config'-variable. It will also import the application-module-file (the file which holds the source-code of the application itself, a.k.a. application-class) and start the instance.
I am not very experienced in coding Python, and my biggest question is if I am doing it the right way, by using a main-file to handle all needed stuff (loading configuration-files for example). The problem I am having right now is that I cannot access the 'config'-variable that was defined in the main.py-file from any other module and/or Python-file.
Is it possible to make a global variable for configuration-values exc.? I know in PHP I used to create a singleton object which holds all the specific global arguments. I could also create a global 'ROOT'-variable to hold the full path to the root of the application, which is needed to load/import new files, this is also not possible in Python as far as I know.
I hope someone can help me out of this or send me in the right direction so I can continue working on this project.
A: The answer seems to be by Matthias:
Use from AppName.modules import settings and then access the data in the module with settings.value. According to PEP-8, the style guide for Python code, wildcard imports should be avoided and would in fact lead to undesirable behaviour in this case.
Thanks you all for the help!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26866722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: why should we use native php gettext instead of gettexxt library I'm including gettext library in my application. But, as our team decided to go with native php gettext. The gettext library accepts the string and converts it using the "Translate" function which is defined in the library. Now how can I shift suddenly to native lib? Is it only for performance? Any suggestions on using native lib. Thanks in advance.
A: It is mainly for performance and well as ease of use.
When you use an external library inside PHP using system() for e.g., then the pros are that you will be able to use ALL of its options, which will make you a power user. The cons are that, each time you run it, you have to do like a parsing of the return string and then figure out the results and stuff, which is a hassle and pretty error prone.
When you use a language-binding of the external library, then cons are that you are confined to the API calls that the binding provides. The pros are that the return values, the error status etc will be well defined within the API calls so handling the calls will be easier.
This is usually a tradeoff and it will vary from case to case as to whether one should use native interfaces or just execute the library directly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21485999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using Styled Components to change the color of an SVG's stroke I have an SVG I'm using as an <img> tag. Using Styled Components I am trying to get to a point where I change the stroke color upon hover.
I imported the SVG:
import BurgerOpenSvg from '../../images/burger_open.svg';
I Created a Styled Components for it:
const BurgerImageStyle = styled.img`
&:hover {
.st0 {
stroke: red;
}
}
`;
And I use it:
<BurgerImageStyle alt="my-burger" src={BurgerOpenSvg}/>
The result is, my SVG is displayed correctly, but no color change upon hovering.
Source for the SVG I use:
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 38 28.4" style="enable-background:new 0 0 38 28.4;" xml:space="preserve">
<style type="text/css">
.st0{fill:none;stroke:#221f1f;stroke-width:2;stroke-miterlimit:10;}
</style>
<g>
<g id="XMLID_7_">
<line class="st0" x1="0" y1="1" x2="38" y2="1"/>
</g>
<g id="XMLID_6_">
<line class="st0" x1="0" y1="14.2" x2="38" y2="14.2"/>
</g>
<g id="XMLID_5_">
<line class="st0" x1="0" y1="27.4" x2="38" y2="27.4"/>
</g>
</g>
</svg>
The SVG Renders as follows:
Is it even possible to update the class on an SVG loaded in an <img> tag? or must it be inline <svg> tag?
A: If you are looking to avoid writing separate components or copying your raw SVG file, consider react-inlinesvg;
https://github.com/gilbarbara/react-inlinesvg
import React from "react";
import styled from "styled-components";
import SVG from "react-inlinesvg";
import radio from "./radio.svg";
interface SVGProps {
color: string;
}
const StyledSVG = styled(SVG)<SVGProps>`
width: 24px;
height: 24px;
& path {
fill: ${({ color }) => color};
}
`;
export default function App() {
const color = "#007bff";
return <StyledSVG color={color} src={radio} />;
}
Code Sandbox: https://codesandbox.io/s/stack-56692784-styling-svgs-iz3dc?file=/src/App.tsx:0-414
A: So I looked into this. Turns out you cannot CSS style an SVG image you're loading using the <img> tag.
What I've done is this:
I inlined my SVG like this:
<BurgerImageStyle x="0px" y="0px" viewBox="0 0 38 28.4">
<line x1="0" y1="1" x2="38" y2="1"/>
<line x1="0" y1="14.2" x2="38" y2="14.2"/>
<line x1="0" y1="27.4" x2="38" y2="27.4"/>
</BurgerImageStyle>
Then I used Styled Components to style BurgerImageStyle:
const BurgerImageStyle = styled.svg`
line {
stroke: black;
}
&:hover {
line {
stroke: purple;
}
}
`;
This worked.
A: If you want to have some styling shared across multiple SVGs and you don't want to have an extra dependency on react-inlinesvg you can use this thing instead:
In src prop it accepts SVG React component
import styled from 'styled-components';
import React, { FC, memo } from 'react';
type StyledIconProps = {
checked?: boolean;
};
const StyledIconWrapper = styled.div<StyledIconProps>`
& svg {
color: ${(p) => p.checked ? '#8761DB' : '#A1AAB9'};
transition: 0.1s color ease-out;
}
`;
export const StyledIcon = memo((props: StyledIconProps & { src: FC }) => {
const { src, ...rest } = props;
const Icon = src;
return (
<StyledIconWrapper {...rest}>
<Icon/>
</StyledIconWrapper>
);
});
And then you can use it like:
import { StyledIcon } from 'src/StyledIcon';
import { ReactComponent as Icon } from 'assets/icon.svg';
const A = () => (<StyledIcon src={Icon} checked={false} />)
A: In addition to what JasonGenX I propose the next case when you're using a SVG component (like one generated using SVGR). This is even on the styled-components documentation and in combination with its API it solves it seamlessly.
First import your icon
import React from 'react';
import styled from 'styled-components';
import YourIcon from '../../icons/YourIcon';
In my case I added a styled button like so:
const StyledButton = styled.button`
...
`;
// Provide a styled component from YourIcon
// You can also change the line for path and stroke for fill for instance
const StyledIcon = styled(YourIcon)`
${StyledButton}:hover & line {
stroke: #db632e;
}
`;
const YourButton = () => {
return (
<StyledButton>
<StyledIcon /> Click me
</StyledButton>
);
};
export default YourButton;
After that you'll see your icon changes its color.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56692784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Any Class Based Views or Package for Auth with related model? Currently I have two styles of templates: User + Client, and User + Company. And I want to create a view to create a User + account from either of these two related templates.
Currently I have achieved this, but there is a problem: the code seems to be very bloated, and I also do not know if there is CBV to edit model with related models, then it will result in other views also bloated.
Is there any way to improve this?
models.py: https://pastebin.com/9Fp0F6CG
my views.py:
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.views import generic
from .forms import UserForm, ClientForm, CompanyForm
class ClientFormView(generic.View):
def get(self, request, *args, **kwargs):
template_name = "users/registration/form_client.html"
context = {"form_user": UserForm, "form_client": ClientForm}
return render(request, template_name, context)
def post(self, request, *args, **kwargs):
template_name = "users/registration/form_client.html"
context = {"form_user": UserForm, "form_client": ClientForm}
form_user = UserForm(request.POST)
form_client = ClientForm(request.POST)
if form_user.is_valid() and form_client.is_valid():
# get data for auth and login
email = form_user.cleaned_data["email"]
password_raw = form_user.cleaned_data["password1"]
# add user_type = client
instance_user = form_user.save(commit=False)
instance_user.user_type = "cl"
instance_user.save()
instance_client = form_client.save(commit=False)
user = authenticate(email=email, password=password_raw)
if user is not None:
# add the user in related user field
instance_client.user = user
instance_client.save()
login(request, user)
return redirect("main:home")
return render(request, template_name, context)
class CompanyFormView(generic.View):
def get(self, request, *args, **kwargs):
template_name = "users/registration/form_company.html"
context = {"form_user": UserForm, "form_company": CompanyForm}
return render(request, template_name, context)
def post(self, request, *args, **kwargs):
template_name = "users/registration/form_company.html"
context = {"form_user": UserForm, "form_company": CompanyForm}
form_user = UserForm(request.POST)
form_company = CompanyForm(request.POST)
if form_user.is_valid() and form_company.is_valid():
# get data for auth and login
email = form_user.cleaned_data["email"]
password_raw = form_user.cleaned_data["password1"]
# add user_type = client
instance_user = form_user.save(commit=False)
instance_user.user_type = "comp"
instance_user.save()
instance_company = form_company.save(commit=False)
user = authenticate(email=email, password=password_raw)
if user is not None:
# add the user in related user field
instance_company.user = user
instance_company.save()
login(request, user)
return redirect("main:home")
return render(request, template_name, context)
A: I have only made some improvements in regards to the views, I haven't looked at the models.
*
*First you should change from the generic generic.View to
generic.CreateView since you are creating stuff.
*When deriving from generic.CreateView you can move out the
template_name and context from the functions and put them in the
class instead, since they stay the same for both the GET and
POST operations.
*Then you don't need to user the render functions, you can just call
the super that should handle the render for you.
*And lastly you can create a mixin that handles the logic in the user
creation, as it's largely the same.
With the suggestions above it should look something like this. You might need to tweak it, I haven't been able to test it fully.
from extra_views import CreateWithInlinesView, InlineFormSet
class ClientCompanyMixin(object):
def create_user(self, form_user, form_second, type):
# get data for auth and login
email = form_user.cleaned_data["email"]
password_raw = form_user.cleaned_data["password1"]
# add user_type = client/company
instance_user = form_user.save(commit=False)
instance_user.user_type = type
instance_user.save()
instance = form_second.save(commit=False)
user = authenticate(email=email, password=password_raw)
return instance, user
class UserInline(InlineFormSet):
model = User
class ClientFormView(CreateWithInlinesView, ClientCompanyMixin):
template_name = "users/registration/form_client.html"
model = Client
inlines = [UserInline]
def get_context_data(self, **kwargs):
context = super(ClientFormView, self).get_context_data(**kwargs)
context["form_user"] = UserForm
context["form_client"] = ClientForm
return context
def post(self, request, *args, **kwargs):
form_user = UserForm(request.POST)
form_client = ClientForm(request.POST)
if form_user.is_valid() and form_client.is_valid():
instance_client, user = self.create_user(form_user, form_client, "cl")
if user is not None:
# add the user in related user field
instance_client.user = user
instance_client.save()
login(request, user)
return redirect("main:home")
return super(ClientFormView, self).post(request, *args, **kwargs)
class CompanyFormView(CreateWithInlinesView, ClientCompanyMixin):
template_name = "users/registration/form_company.html"
model = Company
inlines = [UserInline]
def get_context_data(self, **kwargs):
context = super(CompanyFormView, self).get_context_data(**kwargs)
context["form_user"] = UserForm
context["form_company"] = CompanyForm
return context
def post(self, request, *args, **kwargs):
form_user = UserForm(request.POST)
form_company = CompanyForm(request.POST)
if form_user.is_valid() and form_company.is_valid():
instance_company, user = self.create_user(form_user, form_company, "comp")
if user is not None:
# add the user in related user field
instance_company.user = user
instance_company.save()
login(request, user)
return redirect("main:home")
return super(CompanyFormView, self).post(request, *args, **kwargs)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55347588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Coordinate shift when converting from Kivy (origin at bottom left) to MatplotLib pyplot (top left) So I`m making an image annotation tool for images to use them with some tensor flow and OpenCV projects. (yes I know there are already made ones, I do it as part of learning experience) To ensure my script is versatile I first make a json file to store my data easily. Already at this stage I store top left of my rectangle with width and height. Then I use another script to convert my json into xml identical to the one seen in this tutorial: Keras tutorial
The conversion and storage occur in this part of the annotation script:
registration:
def on_touch_up(self, touch):
if abs(self.current_start_point[0] - touch.pos[0]) > 10 and abs(self.current_start_point[1] - touch.pos[1]) > 10:
x = math.trunc(self.current_start_point[0] if self.current_start_point[0] < touch.pos[0] else touch.pos[0])
y = math.trunc(self.current_start_point[1] if self.current_start_point[1] > touch.pos[1] else touch.pos[1])
w = math.trunc(abs(self.current_start_point[0] - touch.pos[0]))
h = math.trunc(abs(self.current_start_point[1] - touch.pos[1]))
debug(CLR=GREEN,MSG=f'Registered rectangle with position {x},{y}.\nIts width is {w} and height {h}')
self.rectangles.append({'x':x,
'y':y,
'w':w,
'h':h})
self.current_drag = False
self.current_start_point = False
and storage:
def do_export(self):
with open(self.save_file,'r') as fl:
cur_state = json.loads(fl.read())
cur_state['root'][self.imname] = self.rectangles
with open(self.save_file,'w') as fl:
strung = json.dumps(cur_state,sort_keys=True,indent=4)
fl.write(strung)
self.rectangles = []
It works fine and displays rectangles accordingly with such function:
def update(self,dt):
self.canvas.clear()
with self.canvas:
Rectangle(pos=(0,0),size=(self.tex_w,self.tex_h),texture=self.tex)
Color(0.9,0,0.2,0.5)
for rect in self.rectangles:
Rectangle(pos=(rect['x'],rect['y']-rect['h']),size=(rect['w'],rect['h']))
if self.current_drag:
dx = self.current_drag[0] if self.current_drag[0] < self.current_start_point[0] else self.current_start_point[0]
dy = self.current_drag[1] if self.current_drag[1] < self.current_start_point[1] else self.current_start_point[1]
dw,dh = abs(self.current_start_point[0]-self.current_drag[0]),abs(self.current_start_point[1]-self.current_drag[1])
Rectangle(pos=(dx,dy),size=(dw,dh))
Then I convert it into xml as such (only the coordinates part):
x_min,y_min,x_max,y_max = item['x'],int(item['y']),item['w'] + item['x'],int(item['y']+item['h'])
obj = ET.SubElement(root,'object')
name,pose,truncated,difficult = ET.SubElement(obj,'name'),ET.SubElement(obj,'pose'),ET.SubElement(obj,'truncated'),ET.SubElement(obj,'difficult')
name.text = 'bob' ; pose.text = 'Unknown' ; truncated.text = str(0) ; difficult.text = str(0)
bndbox = ET.SubElement(obj,'bndbox')
min_x,min_y,max_x,max_y = ET.SubElement(bndbox,'xmin'),ET.SubElement(bndbox,'ymin'),ET.SubElement(bndbox,'xmax'),ET.SubElement(bndbox,'ymax')
min_x.text = str(x_min) ; min_y.text = str(y_min) ; max_x.text = str(x_max) ; max_y.text = str(y_max)
Eventually I load it into the dataset class I copied from same tutorial and use matplotlib to show the mask, which shows something like this:
I clearly see the offset in y but I cant find the origin of it as I clearly pick the top left corner of rectangle in kivy. This is probably something really simple but I just cant find it and I'm stuck on it for couple of days now.
Also JSON for the cat looks like:
{
"root": {
"images\\0.jpg": [
{
"h": 101,
"w": 99,
"x": 1052,
"y": 653
}
]
}
}
and the XML like:
<annotation>
<folder>side</folder>
<filename>0</filename>
<source>Unknown</source>
<size>
<width>1920</width>
<height>1080</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>bob</name>
<pose>Unknown</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>1052</xmin>
<ymin>653</ymin>
<xmax>1151</xmax>
<ymax>754</ymax>
</bndbox>
</object>
Thank you very much in advance, and sorry if it`s something very simple.
A: My apologies to everyone, I'm retarded. For anyone who has same issue just have screen height - the y coordinate to convert, cuz even if u pick different corner the system itself stays.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66868812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding Razorviews/.chtml files non-dynamically in .NET 6.0 I'm learning how to make a website and I want to add new views through a method. Instead of physically clicking add view and then editing it.
The method would take in a Novel object, which is connected to a database. If that novel doesn't already have a view. A new view would be created based off a template view that I make. Some areas in the template would be changed based off the difference in object properties. Ex. Novel Name, Synopsis, Author, Chapters, Rating, Genres, and Tags.
I already have a form that takes in information and makes an update to the sql database adding that object.
There are a lot of guides on how to do this dynamically, but later on I want to add reviews, comments, pageview trackers, and such.
Something similar to what I want.
MVC 4: Create new Razor View from string not from file path
That method doesn't seem to work anymore or I'm just not that familiar with the syntax.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74105063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to accelerate DFT by specifying region of interest in frequency domain Note: This question is originally asked at OpenCV forum a couple of days ago.
I'm building an image processing program which extensively uses 2-dimensional dft, discrete Fourier transform. I'm trying to speed up so as to run in real-time.
In that application I only use a part of dft output specified by a rectangular ROI. My current implementation follows the steps below:
*
*Compute dft of the input image f (typically size of 512x512) and get the entire dft result F
*Crop F into a pre-specified region of interest (ROI, typically size of 32x32, located arbitrary), R
This process basically works well, but involves useless calculation since I only need partial information of F. I'm looking for a way to accelerate this calculation only by computing necessary part of dft.
I found OpenCV with Intel IPP computes dft with Intel IPP functions, which results in an order of magnitude faster than naive OpenCV implementation. I'm wondering if I can even accelerate this computation by only computing pre-specified frequency domain of dft.
Since I'm new to OpenCV, I've lost my way here, so I hope you could provide a way to do this.
Kindly note that I don't mean to do a dft to an ROI of an image, i.e. dft(ROI(f)), but I want to compute ROI(dft(f)).
Thanks in advance.
A: Just a partial idea.
The DFT is separable. It is always computed by first applying the FFT algorithm to rows of the image, then to the columns of the result (or the other way around, the order doesn't matter).
If you want only an ROI of the output, in the second step you only need to process the columns that fall within the ROI.
I don't think you'll find a way to compute only a subset of frequencies along each 1D row/column. That would likely entail hacking your own FFT, which will likely be more computationally expensive than using the one in IPP or FFTW.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50521283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Check if record exists in python. If exists then skip else process I have a function for extracting frames from videos. I have a csv file which has the names of the videos already processed. I want to check if the name of a newly added video file is present in the csv file. If present then exit the code else process the function to extract frames from the new video
def extractFrames(m):
global vid_name
vid_files=glob(m)
for v_f in range(len(vid_files)):
print("path of video========>>>>.",vid_files[v_f])
#latest_file=max(vid_files, key=os.path.getctime)
#print(latest_file)
v1=os.path.basename(vid_files[v_f])
try:
vid_name = os.path.splitext(v1)[0]
vidcap = cv2.VideoCapture(vid_files[v_f])
except cv2.error as e:
print(e)
except:
print('error')
#condition
fsize=os.stat(vid_files[v_f])
print('=============size of video ===================:' , fsize.st_size)
try:
if (fsize.st_size > 1000):
fps = vidcap.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frameCount/fps
minutes = int(duration/60)
print('fps = ' + str(fps))
print('number of frames = ' + str(frameCount))
print('duration (S) = ' + str(duration))
if (duration > 1):
success,image = vidcap.read()
count=0
success=True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count % 10 == 0 or count ==0:
target_non_target(img_name, image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
except:
print("error")
print('finished processing video ', vid_files[v_f])
with open("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv', 'a') as csv_file:
fieldnames = ['Video_Name','Process']
file_is_empty = os.stat("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv').st_size == 0
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
if file_is_empty:
writer.writeheader()
writer.writerow({'Video_Name':vid_name,'Process':'done'})
if __name__ == "__main__":
x="C:\\Python36\\videos\\*.mp4"
extractFrames(x)
Suppose a folder has 2 videos V1 and V2 from which frames have already been extracted and the names V1 and V2 are added in the csv file. Now when i add video V3 the code should check if V3 exists already in the csv. If it exists then the code should be skipped else frames from V3 should be processed and V3 should be added in the csv file after extraction of the frames
A: Without the details you have code like this
def extractFrames(m):
# do stuff
vid_files=glob(m)
for v_f in range(len(vid_files)):
#find vid_name
#do stuff
save_as_done(vid_name)
if __name == '__main__':
x="C:\\Python36\\videos\\*.mp4"
extractFrames(x)
If you pass in a list of things that have been done, something like
done = ['first.mp4', 'second.mp4']
you can check if a filename has been done like this:
>>> 'first.mp4' in done
True
So, if you save the filenames (fully pathed) of what you've done to a file and load them into a list, like this
def load_done_list():
with open('video_info.csv') as f: #or full path, maybe pass in the file name?
return f.readlines()
you can check the list
def extractFrames(m, done):
# do stuff
vid_files=glob(m)
for v_f in range(len(vid_files)):
#find vid_name
if vid_name not in done: #,--- check if done already
#do stuff
save_as_done(vid_name)
if __name == '__main__':
x="C:\\Python36\\videos\\*.mp4"
done = load_done_list() #<--- You need to load this into a list
extractFrames(x, done) #<--- and pass it in to your function
This need something that just saves the filenames as they are done:
def save_as_done(vid_name):
with open('video_info.csv', 'a') as f: #maybe pass in the file name so you only define it once?
f.write(vid_name + '\n')
I haven't filled in all the details, but have shown where you can do loading and saving and checking.
The written file only has the filenames in - there doesn't seem much point in having "done" on the end of each line.
This will keep opening and closing the file as the files are processed. This may slow thing down but might not matter: you could pass in a file handle to write to, to keep it open. You have options.
A: I think you might need a function to get the list completed/done videos from the csv file.
Something like this, might need to tweak a bit for the header row.
def get_completed_videos():
completed_videos = []
with open(".../video_info.csv") as csv_file:
for row in csv.reader(csv_file):
completed_videos.append(row[0])
return completed_videos
Then exclude them in the extracting func
def extractFrames(m):
global vid_name
vid_files=glob(m)
complete_videos = get_completed_videos()
new_vid_files = [x for x in vid_files if x not in complete_videos]
...
A: def extractFrames(m,done):
global vid_name
vid_files=glob(m)
for v_f in range(len(vid_files)):
print("path of video========>>>>.",vid_files[v_f])
v1=os.path.basename(vid_files[v_f])
vid_name = os.path.splitext(v1)[0]
if vid_name not in done:
try:
vidcap = cv2.VideoCapture(vid_files[v_f])
except cv2.error as e:
print(e)
except:
print('error')
#condition
fsize=os.stat(vid_files[v_f])
print('=============size of video ===================:' , fsize.st_size)
try:
if (fsize.st_size > 1000):
fps = vidcap.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frameCount/fps
minutes = int(duration/60)
print('fps = ' + str(fps))
print('number of frames = ' + str(frameCount))
print('duration (S) = ' + str(duration))
if (duration > 1):
success,image = vidcap.read()
count=0
success=True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count % 10 == 0 or count ==0:
target_non_target(img_name, image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
except:
print("error")
print('finished processing video ', vid_files[v_f])
with open("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs\\"+'video_info.csv', 'a') as csv_file:
fieldnames = ['Video_Name','Process']
file_is_empty = os.stat("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs\\"+'video_info.csv').st_size == 0
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
if file_is_empty:
writer.writeheader()
writer.writerow({'Video_Name':vid_name,'Process':'done'})
if __name__ == "__main__":
x="C:\\Python36\\videos\\*.mp4"
y="C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs\\video_info.csv"
done=list(y)
extractFrames(x,done)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56380564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Python3 pika channel.basic_consume() causing MySQL too many connections I had using pika to make a connection to RabbitMQ and consume message, once I start the script on ubuntu prod environment it is working as expected but is opening mysql connection and never closes them and ends up in Too many connection on mysql server.
Will appreciate any recommendation on the code below, as well can not understand what is going wrong. Thanking you in advance.
The flow is the following
*
*Starting pika on Python3
*Subscribe to a channel and waiting for messages
*In callback i do various validation and save or update data inside MySql
*The result that is showing the problem is the at the end of question a screenshot from ubuntu htop, that is showing new connection on MySql and keep adding them on the top
Pika Verion = 0.13.0
For MySql I use pymysql.
Pika Script
def main():
credentials = pika.PlainCredentials(tunnel['queue']['name'], tunnel['queue']['password'])
while True:
try:
cp = pika.ConnectionParameters(
host=tunnel['queue']['host'],
port=tunnel['queue']['port'],
credentials=credentials,
ssl=tunnel['queue']['ssl'],
heartbeat=600,
blocked_connection_timeout=300
)
connection = pika.BlockingConnection(cp)
channel = connection.channel()
def callback(ch, method, properties, body):
if 'messageType' in properties.headers:
message_type = properties.headers['messageType']
if events.get(message_type):
result = Descriptors._reflection.ParseMessage(events[message_type]['decode'], body)
if result:
result = protobuf_to_dict(result)
model.write_response(external_response=result, message_type=message_type)
else:
app_log.warning('Message type not in allowed list = ' + str(message_type))
app_log.warning('continue listening...')
channel.basic_consume(callback, queue=tunnel['queue']['name'], no_ack=True)
try:
channel.start_consuming()
except KeyboardInterrupt:
channel.stop_consuming()
connection.close()
break
except pika.connection.exceptions.ConnectionClosed as e:
app_log.error('ConnectionClosed :: %s' % str(e))
continue
except pika.connection.exceptions.AMQPChannelError as e:
app_log.error('AMQPChannelError :: %s' % str(e))
continue
except Exception as e:
app_log.error('Connection was closed, retrying... %s' % str(e))
continue
if __name__ == '__main__':
main()
Inside the script i have a model that doing inserts or updated in the database, code below
def write_response(self, external_response, message_type):
table_name = events[message_type]['table_name']
original_response = external_response[events[message_type]['response']]
if isinstance(original_response, list):
external_response = []
for o in original_response:
record = self.map_keys(o, message_type, events[message_type].get('values_fix', {}))
external_response.append(self.validate_fields(record))
else:
external_response = self.map_keys(original_response, message_type, events[message_type].get('values_fix', {}))
external_response = self.validate_fields(external_response)
if not self.mysql.open:
self.mysql.ping(reconnect=True)
with self.mysql.cursor() as cursor:
if isinstance(original_response, list):
for e in external_response:
id_name = events[message_type]['id_name']
filters = {id_name: e[id_name]}
self.event(
cursor=cursor,
table_name=table_name,
filters=filters,
external_response=e,
message_type=message_type,
event_id=e[id_name],
original_response=e # not required here
)
else:
id_name = events[message_type]['id_name']
filters = {id_name: external_response[id_name]}
self.event(
cursor=cursor,
table_name=table_name,
filters=filters,
external_response=external_response,
message_type=message_type,
event_id=external_response[id_name],
original_response=original_response
)
cursor.close()
self.mysql.close()
return
On ubuntu i use systemd to run the script and restart in case something goes wrong, below is systemd file
[Unit]
Description=Pika Script
Requires=stunnel4.service
Requires=mysql.service
Requires=mongod.service
[Service]
User=user
Group=group
WorkingDirectory=/home/pika_script
ExecStart=/home/user/venv/bin/python pika_script.py
Restart=always
[Install]
WantedBy=multi-user.target
Image from ubuntu htop, how the MySql keeps adding in the list and never close it
Error
tornado_mysql.err.OperationalError: (1040, 'Too many connections')
A: i have found the issue, posting if will help somebody else.
the problem was that mysqld went into infinite loop trying to create indexing to a specific database, after found to which database was trying to create the indexes and never succeed and was trying again and again.
solution was to remove the database and recreate it, and the mysqld process went back to normal. and the infinite loop to create indexes dissapeared as well.
A: I would say increasing connection may solve your problem temperately.
1st find out why the application is not closing the connection after completion of task.
2nd Any slow queries/calls on the DB and fix them if any.
3rd considering no slow queries/calls on DB and also application is closing the connection/thread after immediately completing the task, then consider playing with "wait_timeout" on mysql side.
A: According to this answer, if you have MySQL 5.7 and 5.8 :
It is worth knowing that if you run out of usable disc space on your
server partition or drive, that this will also cause MySQL to return
this error. If you're sure it's not the actual number of users
connected then the next step is to check that you have free space on
your MySQL server drive/partition.
From the same thread. You can inspect and increase number of MySQL connections.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62714779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I do for my Items inside a ListView start at the right to left? I want make my Items inside a ListView going right to left.
At the moment I have default settings:
As you can see I have a hole in the right and I want to reverse this, put a hole in the left.
Hope you understand the problem.
<telerikDataControls:RadListView ItemsSource="{Binding CatalogSizes, Source={x:Reference ExtendedContentView}}" >
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<listView:ListViewTemplateCell>
<listView:ListViewTemplateCell.View>
<Frame Padding="0" CornerRadius="3.5" BackgroundColor="{Binding IsEnabled, Converter={StaticResource Batata}, ConverterParameter={x:Reference Name=MainColorGrid}}">
<Label Text="{Binding Quantity}" FontAttributes="Bold" HorizontalTextAlignment="Center" VerticalTextAlignment="Center"/>
</Frame>
</listView:ListViewTemplateCell.View>
</listView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
<telerikDataControls:RadListView.LayoutDefinition>
<listView:ListViewGridLayout SpanCount="3" HorizontalItemSpacing="3" />
</telerikDataControls:RadListView.LayoutDefinition>
</telerikDataControls:RadListView>
A: You can change the Direction, to RTL. In CSS is just:
direction: rtl;
You can see a sample here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56508044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ActiveRecord conditional count In my application, I'm trying to sort items by views within the last 10 days. I'm using the Impressionist gem, which creates a model called impression and records every view here.
I've managed to get to this piece of code:
@items = Item.joins("left join impressions on impressions.impressionable_id = items.id and impressions.impressionable_type = 'Item'")
.select("count(distinct(ip_address)) as counter, impressionable_id, items.title, items.id, items.image")
.group('items.id')
.order("counter desc")
.page(params[:page])
.per_page(9)
This sorts the items by total unique views. However, I want to only count the impressions which have been made within the last 10 days. This led me to add a where method as such:
time_range = (Time.now - 10.days)..Time.now
@items = Item.joins("left join impressions on impressions.impressionable_id = items.id and impressions.impressionable_type = 'Item'")
.select("count(distinct(ip_address)) as counter, impressionable_id, items.title, items.id, items.image")
.where('impressions.created_at' => time_range)
.group('items.id')
.order("counter desc")
.page(params[:page])
.per_page(9)
However, this excludes the items which has no views, which is not what I want. These should be represented with 0 view.
Any suggestions how to fix this problem?
A: I had to use CASE, along with some modifications to make it run on heroku's postgres server.
start_date = (Time.now - 10.days)
end_date = Time.now
joins("left join impressions on impressions.impressionable_id = items.id and impressions.impressionable_type = 'Item'")
.select("count(distinct(case when (impressions.created_at BETWEEN '#{start_date}' AND '#{end_date}') then ip_address end)) as counter, impressionable_id, items.gender, items.title, items.id, items.image")
.group('items.id', 'impressions.impressionable_id')
.order("counter desc")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17454467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: not able to click the login button through selenium
please create a selenium code for us where i am not able to hit the Login Button. see my code below and do the correction :
driver.findElement(By.id("Log In")).click();
driver.findElement(By.className("submit")).click();
driver.findElement(By.cssSelector(".sbt-btn-wrap relative .submit")).click();
driver.findElement(By.className("formButton")).click();
A: Try this below xpath.
Explanation: User value attribute of input tag.
driver.findElement(By.xpath("//input[@value='Log In']")).click();
For click on Lock and Edit button use this code.
driver.findElement(By.xpath("//input[@value='Lock & Edit']")).click();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42552755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: In Asp.net, why is the request input stream position sometimes not at position 0 in my controller? Two methods in my ASP.NET MVC3 web service behave differently when I POST to them.
/project
/project/{id}/snapshots
In the first method I can read the POST'ed JSON from the Request.InputStream however in the second method the input stream is not at position 0 and I have to seek to the beginning. Even with nearly identical code in both controllers (except for the parameter of course) the input stream position is still different.
My question is why are the streams in different positions?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7191862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I map two lists to one list in Automapper? I have the following setup:
public class ClassA
{
public int Id { get; set; }
public int JoinId { get; set; }
}
public class ClassB
{
public string Name { get; set; }
public int JoinId { get; set; }
}
public class ClassC
{
public int Id { get; set; }
public string Name { get; set; }
public int JoinId { get; set; }
}
I have a list of ClassA and a list of ClassB
I want a list of ClassC using Automapper. The result should be a Full Outer Join on JoinId.
How can I achieve this?
A: Why not just write the code for it?
var listOfA = new List<A>();
var listOfB = new List<A>();
... // Code for adding values
listOfA.ToC(listOfB);
public static class OuterJoinExtension
{
public static List<C> ToC(this List<A> listOfA, List<B> listOfB)
{
var listOfC = new List<C>();
listOfA.ForEach(a => listOfB.ForEach(b =>
{
if (b.JoinId == a.JoinId)
{
listOfC.Add(new C { Id = a.Id, JoinId = b.JoinId, Name = b.Name });
}
}));
return listOfC;
}
}
A: For simplicity I'll assume these are contained within another class:
class Original
{
List<ClassA> ClassAs { get; set; }
List<ClassB> ClassBs { get; set; }
}
class Result
{
List<ClassC> ClassCs { get; set; }
}
You can map the former to the latter using
Mapper.CreateMap<Original, Result>().ForMember(x => x.ClassCs,
x => x.MapFrom(x.ClassAs.Join(
y.ClassBs,
xEntry => xEntry.JoinId,
yEntry => yEntry.JoinId,
(xEntry, yEntry) => new ClassC {
Id = xEntry.Id,
Name = yEntry.Name,
JoinId = xEntry.JoinId});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29975419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add a PNG-File-Array to an ArrayList - Java I have this method:
private ArrayList<Image> imageArray(File files[]) {
ArrayList<Image> images = null;
for(int x = 0; files.length > x; x++) {
//I want to add each PNG-File to the Image-Array
try {
images.add(x, ImageIO.read(files[x])); //Demo.imageArray(Demo.java:23)
}catch(IOException | ArrayIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
//Now I scale each Image, so it fits the screenSize
int newWidth = (int) screenSize.getWidth(),
newHeight = newWidth * images.get(x).getHeight(null) / images.get(x).getWidth(null);
if(newHeight > screenSize.getHeight()) {
newHeight = (int) screenSize.getHeight();
newWidth = newHeight * images.get(x).getWidth(null) / images.get(x).getHeight(null);
}
images.set(x, images.get(x).getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH));
}
return images;
}
which causes this Exception :
Exception in thread "main" java.lang.NullPointerException
at Demo.imageArray(Demo.java:23) //I've marked the position in the code!
at Demo.main(Demo.java:47) // Just, when I want to use the method anywhere
Why do I get that Error and how can I work around it? I have added a parameter, when I wanted to use the method, which looks like this :
imageArray(new File[] {new File("filePath to PNG-Image"),
new File("filePath to PNG-Image")})
A: A simple solution would be to initialize images.
So instead of just doing this:
ArrayList<Image> images = null;
Do this:
ArrayList<Image> images = new ArrayList<>();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48387712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adding url to mysql row in python I am trying to add a url to a text row in mysql using python and the MySQLdb library, but when I run my code it says there is an error in my sql syntax. Can you tell me what im doing wrong?
Here is my code:
import MySQLdb as mdb
connection = mdb.connect("Localhost", "root", "", "db")
cursor = connection.cursor()
url = mdb.escape_string("http://www.google.com")
cursor.execute("""INSERT INTO index(url) VALUES(%s)""", (url,))
Here is the error:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 551, in __bootstrap_inner
self.run()
File "E:\prospector\webworker.py", line 77, in run
cursor.execute("INSERT INTO index(url) VALUES('%s')", (url_t,))
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index(url) VALUES('http://www.google.com/')' at line 1")
A: I was able to replicate your problem like this:
mysql> create table `index` (url varchar(50));
Query OK, 0 rows affected (0.05 sec)
mysql> insert into index(url) values ('http://www.google.com');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index(url) values ('http://www.google.com')' at line 1
mysql> insert into `index`(url) values ('http://www.google.com');
Query OK, 1 row affected (0.00 sec)
index is a keyword in MySQL. Your life will be easier if you do not use it as a table name.
However, if you really want to, you can use it, but then you have to quote it:
cursor.execute("""INSERT INTO `index`(url) VALUES(%s)""", (url,))
PS: No need to call
url = mdb.escape_string("http://www.google.com")
MySQLdb will do that automatically for you when you call
cursor.execute("""INSERT INTO index(url) VALUES(%s)""", (url,))
In fact, since cursor.execute calls mdb.escape_string for you, doing it yourself could cause undesired values to be inserted into the database depending on the value of url:
In [105]: MySQLdb.escape_string("That's all folks")
Out[105]: "That\\'s all folks"
In [106]: MySQLdb.escape_string(MySQLdb.escape_string("That's all folks"))
Out[106]: "That\\\\\\'s all folks"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13042013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to use output file in another powershell command? I'm using auto-editor first to cut out motionless parts, then Mp4Box to add my intro.
I can't figure out how to automatically use the output from auto-editor into Mp4Box.
This is what I have so far.
Get-ChildItem -Filter *.mp4 | ForEach -Process {mp4box -add c:\intro.mp4 -cat $_ -new $a($_.BaseName + '.mp4') -force-cat && del $_ && auto-editor $a --edit_based_on motion --motion_threshold 0.000001% --no_open}
I tried adding $a to make the output into a variable but that doesn't work. I have the script reversed for testing purposes as Mp4Box is a lot faster than auto-editor.
A: You have to create the variable $a on a separate statement, before calling any of the commands that uses it.
Get-ChildItem -Filter *.mp4 | ForEach {
$a = $_.BaseName + '.mp4'
mp4box -add c:\intro.mp4 -cat $_ -new $a -force-cat &&
del $_ &&
auto-editor $a --edit_based_on motion --motion_threshold 0.000001% --no_open
}
I've also added some line breaks to make the code more readable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66143944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to configure a Daphne server to invite clients to add the Certificate Authority that issued my certificate if they hadn't done it yet? If I make a request to my Daphne/Django server in Postman or the Android app we're developing, Daphne serves the certificate, but it's rejected. If I first make a simple get request to https://letsencrypt.org/ and then make a request to my server, the certificate is accepted.
How can I make sure a client will trust my certificate, even if it's the first time this client is seeing a certificate issued by this CA?
Everything bellow can serve as a history of how I studied the problem.
Original title: SSL Certificate works in browser but can't be verified by Postman
I have an AWS EC2 instance running Ubuntu 18.04, with python 3, Django, a bunch of project dependencies, Daphne running with ASGI, with a certificate by Let's Encrypt. Daphne is using port 8000 for HTTP and por 4430 for HTTPS, iptables is configured to redirect requests from port 80 to 8000 and from port 443 to 4430. Django is configured to enforce secure connections with SECURE_SSL_REDIRECT=True in the settings.py file.
There's a "Site in Construction" temporary page being served, and it's properly accessible from every browser and every device I tested so far. If I explicitly type http, I get redirected to https and the certificate is accepted. Every browser I tested (Firefox, Brave, Chrome, Chrome for Android) says cert is good.
Curl outputs the HTML content returned from the server. I don't know if it accepts the certificate or ignores it.
The Problem
Postman, however, says "Error: unable to verify the first certificate". Only works when I disable "SSL certificate verification", which doesn't answer my question: why Postman is unable to verify my Let's Encrypt certificate?
I'm building an API that runs on the same server, using the same domain, and it's meant to be consumed by a mobile app. Currently, the Android app is throwing a "TypeError: Network request failed", which I suspect could be caused by the same thing Postman is complaining about.
When I spin the server locally and configure 1) the app to use http://localhost:8000 and 2) the server not to enforce SSL, it works in browsers, Postman and in the Android app.
I've being looking for answers in many places for days, so any clue will be very welcome.
EDIT
Interesting clue:
If I make a request to my Daphne/Django server, it servers the certificate, which is rejected. But if I first make a request to https://letsencrypt.org/ and then make a request to my server, it works!
This pattern holds true in both Postman and our Android app.
It also happens when I first make a request to https://alloy.city (instead of letsencrypt.org), which is served by a Node.js app, and uses a certificate also issued by the Let's Encrypt CA.
So maybe the question should be: how to configure my server to politely invite clients to add the CA that issued my certificate if they hadn't done it yet?.
Apparently, that's what my Node.js server does.
A: Yes, in settings, tap ssl verification off
File > Settings > General > SSL Certificate Verification > off
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62070297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Python XML Parser not Returning XML Elemements I am trying to find a way to use Python to parse data from several .xml files that contain part numbers and descriptions for a system my team is working on. Here's what the files look like:
Note: Actual data sanitized for confidentiality reasons.
<DOCUMENT>
<config>
<lruname>NFS</lruname>
<swpn>123-A-456-7890</swpn>
<swname>00 NFS ABC DEFGHI XYZ JKL</swname>
<swver>Appid: abc-defghi-xyz PN: 123-A-456-7890</swver>
</config>
</DOCUMENT>
I'd like to pull the and datatypes from several of these files into .csv format. My initial thought was to try to parse these data types out into a dictionary using the built in xml.etree library, but for some reason it's not finding the elements:
import xml.etree.ElementTree as ET
data = '''
<DOCUMENT>
<config>
<lruname>NFS</lruname>
<swpn>123-A-456-7890</swpn>
<swname>00 NFS ABC DEFGHI XYZ JKL</swname>
<swver>Appid: abc-defghi-xyz PN: 123-A-456-7890</swver>
</config>
</DOCUMENT>
'''
tree = ET.fromstring(data)
PartNo = tree.find('swpn')
Desc = tree.find('swname')
print(PartNo)
The above code returns 'None' for some reason, but I would expect it to return the xml element I'm calling.
A: I think you're missing the config level in your XML hierarchy, you could do:
part_number = tree.find('config').find('swpn').text
part_desc = tree.find('config').find('swname').text
Alternately you can loop through all the elements if you don't want to have to know the structure and use conditionals to find the elements you care about with tree.iter.
for e in tree.iter():
if e.tag == 'sqpn':
part_number = e.text
if e.tag == 'swname':
part_desc = e.text
A: ElementTree and etree's find functionality searchers for direct children.
You can still use it by specifying the entire branch:
tree.find('config').find('swpn')
tree.find('config/swpn')
If you always want to look for swpn, but disregard the structure (e.g. you don't know if it's going to be a child of config), you might find it easier to use the xpath functionality in etree (and not in ElementTree):
tree = etree.fromstring(data)
tree.xpath('//swpn')
In this case, the // basically mean that you are looking for elements in tree, no matter where they are
If the xml files are small, and you don't care about performance, you can use minidom which IMHO is more convenient compared to lxml. In this case, your code could be something like this:
from xml.dom.minidom import parseString
xml = parseString(data)
PartNo = xml.getElementsByTagName('swpn')[0]
Desc = xml.getElementsByTagName('swname')[0]
print(PartNo.firstChild.nodeValue)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57595352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Location of css file in a GWT project I have css file named Sample.css which contain the below contents.
.bandit-report{
margin-left: 20px;
}
.bandit-report1{
margin-left: 50px;
}
I have the ABCD.gwt.xml where I have made the below entry for the css file
<stylesheet src='Sample.css' />
I set the style name using setStyleName(String) method. However the margin-left changes are not getting reflected. I dont know where to place the Sample.css file. I have currently place both ABCD.gwt.xml and Sample.css in the same directory.
Kindly Help.
A: Relative paths in <stylesheet> in a gwt.xml files are relative to the "module base URL" (returned by GWT.getModuleBaseURL() on the client-side code; this is the folder into which GWT will generate the nocache.js file and everything else). Having a file output in this directory is as easy as putting it in your public path, which by default is a public subfolder of your GWT module (next to your client subpackage). It's worth noting that public paths are inherited from modules you <inherit>; this is how GWT's built-in themes work.
If you put your stylesheet in your war folder, then you shouldn't inject it from your gwt.xml, you should rather load it with a <link rel=stylesheet> in your HTML host page.
A: I changed the entry made in ABCD.gwt.xml to as below. Now its working.
<stylesheet src='/Sample.css' />
A: Use your browser developer panel to find out the location of css file.
A: You should create a folder named public in the same place where your client, server and shared folders are and put it in there, that's the default location it will look.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17725542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Compiling .xsl files into .class files I'm currently working on a Java web project (Spring) which involves heavy use of xsl transformations. The stylesheets seldom change, so they are currently cached. I was thinking of improving performance by compiling the xsl-s into class files so they wouldn't have to be interpreted on each request.
I'm new to Java, so I don't really know the ecosystem that well. What's the best way of doing this (libraries, methods etc.)?
Thanks,
Alex
A: You might not have to compile to .class to achieve your goal, you can compile the xsl once per run and re-use the compiled instance for all transformations.
To do so you create a Templates object, like:
TransformerFactory factory = TransformerFactory.newInstance();
factory.setErrorListener(new ErrorListener( ... ));
xslTemplate = factory.newTemplates(new StreamSource( ... ));
and use the template to get a transformer to do the work:
Transformer transformer = xslTemplate.newTransformer();
Depending on the XSL library you use your mileage may vary.
A: You'll need a Template and a stylesheet cache:
http://onjava.com/pub/a/onjava/excerpt/java_xslt_ch5/index.html?page=9
Do be careful about thread safety, because Transformers aren't thread safe. Best to do your transformations in a ThreadLocal for isolation.
A: Consider using Gregor/XSLT compiler
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3052658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: netlink on ClearOS 7.3 issue I am trying following simple program on ClearOS 7.3, 64 bit
#include <sys/socket.h>
#include <linux/netlink.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
int main()
{
int flags =0;
int bus = NETLINK_NETFILTER;
int sock_fd = socket(AF_NETLINK, SOCK_RAW | flags, bus);
if(sock_fd<0)
{
printf("\nsocket failed with error no = %d and error msg = %s\n",
errno, strerror(errno));
return -1;
}
printf("\nOP completed successfully..!\n");
return 0;
}
I am getting following error:
socket failed with error no = 93 and error msg = Protocol not
supported
My OS details are:
*
*ClearOS release 7.3.0 (Final)
*Linux 3.10.0-514.26.2.v7.x86_64 #1 SMP Wed Jul 5 10:37:54 MDT 2017
x86_64 x86_64 x86_64 GNU/Linux
Please help.
A: Works for me.
The NETLINK_NETFILTER protocol is registered by the nfnetlink module.
In my case, the kernel registers the module automatically since this code uses it, but if yours doesn't, try inserting it manually:
$ sudo modprobe nfnetlink
And then try opening the socket again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46341479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Copying a dynamic array of structs to another dynamic array of structs I am trying to copy the contents of a dynamic array of structs to another dynamic array of structs, but I am getting the error, 'invalid array assignment' and was hoping someone could point me in the right direction.
Here is my struct:
struct Agent
{
char name[C_STRING_SIZE];
int idNum;
double years;
char location[C_STRING_SIZE];
};
My function:
Agent *copyEncryptArray(Agent *agentArr, int numOfAgents)
{
Agent *encryptArr = new Agent[numOfAgents];
for (int i = 0; i < numOfAgents; i++)
{
encryptArr[i].name = agentArr[i].name;
encryptArr[i].idNum = agentArr[i].idNum;
encryptArr[i].years = agentArr[i].years;
encryptArr[i].location = agentArr[i].location;
}
return encryptArr;
}
Ultimately, I am trying to encrypt the contents of the agentArr then copy it to encryptArr but I am just trying to figure out how to copy for now. This is for a course and we have not covered memcpy yet so that is not an option.
A: It's easier than you think.
for (int i = 0; i < numOfAgents; i++)
encryptArr[i] = agentArr[i];
Each value in the array is something that meets all requirements of an "object", and can be copied/moved as a whole. No need to bother copying each member of the struct.
A: You should use std::string instead of char arrays. It is assignable and there are more merits including almost unlimited length of string.
struct Agent
{
std::string name;
int idNum;
double years;
std::string location;
};
If you are unfortunately forced to use arrays for some reason, you will have to assign each elements.
If it is guaranteed that the contents of the arrays will always be strings (sequences of characters terminated by null-character), you can use strcpy() to copy them.
(I will show only code for name, but location should also be treated like this)
strcpy(encryptArr[i].name, agentArr[i].name);
If you cannot guarantee this, you should use memmove() (because memcpy() is banned here).
memmove(encryptArr[i].name, agentArr[i].name, sizeof(encryptArr[i].name));
If memmove() is also unfortunately banned, the last option will be assigning the elements one-by-one.
for (int j = 0; j < C_STRING_SIZE; j++)
{
encrypyArr[i].name[j] = agentArr[i].name[j];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66733245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Convert Java loop to Kotlin I'm studying implementation with Kotlin. When I implement Kotlin version by below situation, I can't imagine cool way.
for(i = 0 ; i + 8 <= table.size; i++){
for(j = 0 ; j + 8 <= table[0].size; j++{
whatever
}
}
Above code is Java version
for(i in 0 until table.size){
if(i+8 > table.size)break
for(j in until table[0].size){
if(j+8 > table[0].size)break
whatever
}
}
Above is Kotlin version which I think.
Is this fine way?
A: You can just move the -8 into the upper limit, and since you include (<=) the upper limit you shouldn't be using until, but the regular range expansion with two dots.
So it becomes:
for (i in 0..table.size-8){
for (j in 0..table[i].size-8){}
}
(I imagine you would also want to replace the magical number eight with a variable with a meaningful name)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69535836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Uploading in IE fails while using jQuery to click on the input tags for file and submit in a form So I am trying to get this uploading script to work inside of IE. It works fine in other browsers but when I try it in IE the form doesn't submit. I am using jQuery and CSS to build my own form instead of using what the and tags show, and then i use jQuery to click on those tags. However in IE when I select a file and submit the form, IE says there is nothing in the file input and doesn't run the PHP script specified in the action attribute of the form. Any ideas? I haven't been able to find any help for this just by searching.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8099952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.