_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d7201 | train | Our IT department spoke with Trend technical support and they were able to fix this issue by excluding several folders (source code, VS installation path and others) from the real-time scan.
A: I found a blog post about this: http://blog.aabech.no/archive/debugging-happily-alongside-trend-micro/
Pretty much it is saying that you can use the Trend Micro Performance Tuning Tool to inspect the slowness of your debugging.
For me an the author of the blog post it was the msvsmon.exe which is used for remote debugging and was causing a lot of events which slowed down the whole thing. | unknown | |
d7202 | train | You can use onlyIf() on task prepareTranslationSetup and make test depend on it. onlyIf() is defined as follows:
You can use the onlyIf() method to attach a predicate to a task. The task’s actions are only executed if the predicate evaluates to true.
(From: Authoring Tasks)
Example
Let's say you've got the following tasks:
task doBeforeTest {
onlyIf {
project.hasProperty("runit")
}
doLast {
println "doBeforeTest()"
}
}
task runTest {
dependsOn = [ doBeforeTest ]
doLast {
println "runTest()"
}
}
doBeforeTest's actions are only executed if the project has the specified property. runTest is configured to depend on doBeforeTest. Now, when you do
gradlew runTest --info
the output is similar to
> Task :doBeforeTest SKIPPED
Skipping task ':doBeforeTest' as task onlyIf is false.
> Task :runTest
runTest()
As you can see doBeforeTest is skipped as the precondition is not fulfilled. On the other hand, running
gradlew runTest -Prunit
executes doBeforeTest as expected
> Task :doBeforeTest
doBeforeTest()
> Task :runTest
runTest() | unknown | |
d7203 | train | Answering an old post for posterity... and next time I ask Google and get sent here.
Renaming used to be a pain in Maven, this plugin does what is says on the tin:
copy-rename-maven-plugin
(available in Maven central)
Easy to use:
<plugin>
<groupId>com.coderplus.maven.plugins</groupId>
<artifactId>copy-rename-maven-plugin</artifactId>
<version>1.0.1</version>
<executions>
<execution>
<id>copy-properties-file</id>
<phase>prepare-package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<sourceFile>source.props</sourceFile>
<destinationFile>destination.properties</destinationFile>
</configuration>
</execution>
</executions>
</plugin>
Note: the rename goal will move file(s) in target/
A: I faced with same problem, I need to use unpack with renaming some files and as solution we can use two executions of maven-assembly-plugin.
During first execution we will use format dir instead of one of archive formats and will prepare files content and as result will have folder with all needed files.
During second execution we will use folder from previous execution as source in fileSets with files and we will have ability to rename any file using files.file.destName, and as format for second execution we can use archive format like zip to create final archive.
A: You can use
<outputFileNameMapping>...</outputFileNameMapping>
which sets the mapping pattern for all dependencies included in this assembly uses
default value:
${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}.
A: You just need to add it in assembly plugin executions like below;
<executions>
<execution>
<configuration>
<finalName> you can give any name you want <finalName>
<configuration>
</execution>
</executions> | unknown | |
d7204 | train | Then, in addition to remove it from the AD group, try to deny permissions on the schema:
DENY SELECT,VIEW DEFINITION On SCHEMA::Schema_Name To [user_name] | unknown | |
d7205 | train | That is the command format I use from my bash terminal and it works for me.
I just tried to login with a user other than Ubuntu on the server and it gave me permission denied also even though the user was su status. I changed it back to the user ubuntu and it worked fine.
A: What is the error you get? You can add '-v' flag to the ssh command to get complete verbose log.
If you're using same key for both Putty and through gitbash client, it might not work. Putty uses one form of private key and gitbash needs OpenSSH format of the private key.
You can convert the key between the types using PuttyGen utility. | unknown | |
d7206 | train | Why not return promise of angularjs $http and use then in your code like this?
function validityCheck(userid, serviceid, system) {
let params = {
userid: userid,
serviceid: serviceid,
system: system
};
let request = {
url: "https:*******userValidation",
method: "GET",
headers: {"Content-Type": "application/x-www-form-urlencoded"},
params: params
};
return $http(request).then((response) => {
return response.data[0] ? response.data[0] : '';
});
}
Usage:
validityCheck($scope.userid, serviceid, 'abc').then((validity) => {
if (validity === "VALID") {
//do something
} else {
//do something
}
});
P.S. Don't forget to inject angularjs $http
UPDATE: Register library.js in angular
(function () {
"use strict";
angular
.module("yourAngularModuleName")
.factory("LibraryFactory", LibraryFactory);
function LibraryFactory($http) {
// Add your functions here...
}
})();
UPDATE: Plain JavaScript Using The Existing Code
function validityCheck(userid, serviceid, system) {
return new Promise((resolve, reject) => {
$.get("https:*******userValidation?serviceid=" + serviceid + "&userid=" + userid + "&system=" + system, function (data, status) {
console.log(data);
resolve(data[0]);
});
});
}
Use the same code in the USAGE that I have provided. | unknown | |
d7207 | train | Define the delegates of UITableView & UICollectionView in same controller, set there delegates to the same class as
self.mytableview.delegate = self;
self.mycollectionview.delegate = self;
You can follow this tutorial, Putting a UICollectionView in a UITableViewCell | unknown | |
d7208 | train | The easy way is to add the table with a 'hide' class, like:
<button id='toggleTable'>
show/hide table
</button>
<table class='hide' id='tableTarget'>
...
</table>
The js:
document.addEventListener('DOMContentLoaded', () => {
document
.querySelector('#toggleTable')
.addEventListener(
'click',
() => {
document
.querySelector('#tableTarget')
.classList
.toggle('hide')
},
false
)
},
false
)
the css:
.hide {
display: none !important;
}
if you use any frontend framework should be easier. But this is with plain html/js/css. And IE9 is not supported with this solution. If you need it, you have to change a little bit the js code.
Good Luck! | unknown | |
d7209 | train | The widget framework is geared towards minimal HTML. Building a rich application using Ext JS is much more like building a desktop application than building a web page. It just happens to be written in JavaScript and runs in a browser.
Start with the boilerplate HTML file, then build your application purely in .js files. Communicate to your web service for data using REST and JSON.
A: You can do either, although Ext is really more geared toward building UI's in code. You can use Ext Core much as you would jQuery to have a "little bit here and there" but once you get into serious widget/UI development you'll inevitably spend a lot more time in your .js files. Some of the widgets do support instantiation from markup, but not all of them (and it was never built from the ground up to be markup-based like Dojo and maybe some others). | unknown | |
d7210 | train | using axios
await axios.post(process.env.NEXT_PUBLIC_DR_HOST, body)
.then((res) =>
{
window.location = res.request.responseURL;
}) | unknown | |
d7211 | train | The solution is enabling LogTimestamp in the worldserver.conf, which will make the core save every Server.log file with a different datetime in the file name, so you can check what happened.
https://github.com/azerothcore/azerothcore-wotlk/blob/master/src/server/worldserver/worldserver.conf.dist#L451 | unknown | |
d7212 | train | Through the use of callbacks, and based on the design of express, you can send a response and continue to perform actions in that same function. You can, therefore, restructure it to look something like this:
const Pool = require('pg').Pool
const pool = new Pool({
user: 'xxx',
host: 'xx.xxx.xx.xxx',
database: 'xxxxxxxx',
password: 'xxxxxxxx',
port: xxxx,
})
const getReport = (request, response) => {
const { business_group_id, initial_date, final_date } = request.body
pool.query(` SELECT GIANT QUERY`, [business_group_id, initial_date, final_date], (error, results) => {
if (error) {
// TODO: Do something to handle error, or send an email that the query was unsucessfull
throw error
}
// Send the email here.
})
response.status(200).json({message: 'Process Began'});
}
module.exports = {
getReport
}
=============================================================================
Another approach could be to implement a queuing system that would push these requests to a queue, and have another process listening and sending the emails. That would be a bit more complicated though. | unknown | |
d7213 | train | Try the following (PSv3+ syntax):
$res = (Get-ChildItem -Path C:\Downloads\Customers\*.csv).Name |
Select-String -CaseSensitive '\b[A-Z]{4}-\d{3}\b' |
ForEach-Object { $_.Matches[0].Value }
*
*(Get-ChildItem -Path C:\Downloads\Customers\*.csv).Name outputs the file names of all CSV files in dir. C:\Downloads\Customers
*Select-String -CaseSensitive '\b[A-Z]{4}-\d{3}\b' uses case-sensitive regex (regular-expression) matching to only select file names that contain 4 ({4}) uppercase chars. [A-Z], followed by -, followed by 3 digits (\d), on word boundaries (\b)
*The ForEach-Object script block then outputs the part of each matching file name that matched the regex ($_.Matches[0].Value), so that only the relevant portions of matching file names are collected in $res, as an array.
A: This would be a good time to use regex.
See https://regex101.com/r/AH00n6/1
and understand the following regex:
.*\s[#]*([A-Z]{4}-[0-9]{3}).*.csv
This is a little extra to capture just the names, but gives more insight into how to control the regex. | unknown | |
d7214 | train | This will get you all customer who purchased item 'B' in the last 90 Days:
Customers Who Bought Product B 90 Days Ago :=
CALCULATE (
DISTINCTCOUNT ( 'FSale'[CustomerKey] ),
ALL ( 'DimDate'[Date] ),
KEEPFILTERS (
DATESINPERIOD ( 'DimDate'[Date], MAX ( 'DimDate'[Date] ), -90, DAY )
),
KEEPFILTERS ( DimProduct[Product] = "B" )
)
Your question is a little hard to read, so maybe update it and we can go from there. | unknown | |
d7215 | train | As per the response you have posted, it is a JSONArray of JSONObjects. Each JSONObject contains the values with the keys like data1, data2...etch. But every JSONObject doesn't contain the keys data25, data26, data27. If you don't want to throw exception even the response does n't contain the data25,data26, data27 keys in every JSONObject then you need to modify the code like below:
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
// getJSONObject() will throw exception if the key is not found in the jsonObject. Instead of it use optJSONObject() to get the values from JSONObject. It returns the value if contains otherwise returns the empty jsonObject.
// JSONObject json_data = jArray.getJSONObject(i);
JSONObject json_data = jArray.optJSONObject(i);
//map.put("data25", "date25:" + json_data.getString("data25"));
map.put("data25", "date25:" + json_data.optString("data25")); // returns empty string on not finding the key in JSONObject.
//map.put("data26", "data26:" + json_data.getString("data26"));
//map.put("data27", "data27:" + json_data.getString("data27"));
mylist.add(map);
} | unknown | |
d7216 | train | *
*I am extremely surprised to see a measurable impact after enabling a single probe; does even
dtrace -n syscall::posix_spawn:return
cause a problem? If so, are you running short of memory? DTrace does require a (by default) modest amount and its initialisation may be pushing you over the edge. Do you see the problem with anything besides Fusion? It appears to suffer from performance problems of its own on Yosemite.
*Probes are shared between consumers. If there is only one running consumer (e.g. dtrace) then all DTrace probes will be removed when it exits. If two consumers have enabled the same probe then it will remain active until the last consumer exits.
*Maybe. Someone with access to the OS X source code could modify this script. | unknown | |
d7217 | train | You will need to push the string argument on the stack before the invokestatic. This is done with the LDC opcode. Something like:
il.insert( new LDC(cpg.addString("MyString")));
The outline looks like this:
JavaClass clazz = Repository.lookupClass( class_name );
ClassGen c_gen = new ClassGen( clazz );
ConstantPoolGen cpg = new ConstantPoolGen( clazz.getConstantPool() );
InstructionFactory factory = new InstructionFactory( c_gen, cpg );
Methods [] methods = clazz.getMethods();
for ( int i = 0; i < methods.length; i ++ )
{
if ( m.isAbstract() || m.isNative() || .... )
continue;
MethodGen m_gen = new MethodGen( methods[i], class_name, cpg );
InstructionList il = m_gen.getInstructionList();
il.insert( factory.createInvoke("ClassName", "printSomething",
Type.VOID, new Type[]{Type.STRING}, INVOKESTATIC) );
il.insert( factory.createPush( "StringToPrint" ) );
methods[i] = m_gen.getMethod();
}
clazz.setConstantPool( cpg.getFinalConstantPool() );
clazz.setMethods( methods ); // might be redundant
clazz.dump( new File( .... ) );
A few notes:
*
*Since we're inserting, every insert will prepend to the method. This is why we first insert the instruction opcode, and then the arguments (in reverse), so that the actual sequence will be ldc #stringref; invokestatic #methodref.
*We need to replace the ConstantPool and the Methods with our modified versions of them. | unknown | |
d7218 | train | I think it'll end up being a bit tedious but one thing you might try is to have both dialogs parented by a minimalist container using a window mask. So something like...
class minimalist_container: public QWidget {
using super = QWidget;
public:
explicit minimalist_container (QWidget *parent = nullptr)
: super(parent)
{}
protected:
virtual void resizeEvent (QResizeEvent *event) override
{
/*
* Start with an empty mask.
*/
QRegion mask;
/*
* Now loop though the children and add a region to
* the mask for each child based on its geometry.
*/
for (const auto *obj: children()) {
if (const auto *child = dynamic_cast<const QWidget *>(obj)) {
mask += child->geometry();
}
}
setMask(mask);
super::resizeEvent(event);
}
};
Then you can add a layout and children to this in the usual way but the parent itself should be essentially invisible...
minimalist_container minimalist_container;
auto *minimalist_container_layout = new QHBoxLayout;
minimalist_container_layout->addWidget(new QColorDialog);
minimalist_container_layout->addStretch(1);
minimalist_container_layout->addWidget(new QFontDialog);
minimalist_container.setLayout(minimalist_container_layout);
minimalist_container.show();
The code above links all children within the masked parent widget so that they appear visually distinct but move together when the parent is moved.
There are a few niggles however. The title bar of the parent is, by default, the only one visible whereas what I think you really want is for the parent title bar to be the only one that isn't visible. It can certainly be hidden by setting the window flags and/or configuring your window manager but you'll probably then have to write code to handle the usual move, resize functions etc.
So, as I say... tedious, but it could certainly work.
A: You can install an event filter to monitor the moving/resizing of the source window and propagate changes to the target window. On OS X, you also need to monitor the non-client area button press, since the window move events are not sent while the window is moving, but only after it has stopped for a short time.
I leave the propagation in opposite direction as an exercise to the reader :)
// https://github.com/KubaO/stackoverflown/tree/master/questions/win-move-track-42019943
#include <QtWidgets>
class WindowOffset : public QObject {
Q_OBJECT
QPoint m_offset, m_ref;
QPointer<QWidget> m_src, m_dst;
void adjust(QEvent * event, const QPoint & delta = QPoint{}) {
qDebug() << "ADJUST" << delta << event;
m_dst->move(m_src->geometry().topRight() + m_offset + delta);
}
protected:
bool eventFilter(QObject *watched, QEvent *event) override {
#ifdef Q_OS_OSX
if (watched == m_src.data()) {
if (event->type() == QEvent::NonClientAreaMouseButtonPress) {
m_ref = QCursor::pos();
qDebug() << "ACQ" << m_ref << event;
}
else if (event->type() == QEvent::NonClientAreaMouseMove &&
static_cast<QMouseEvent*>(event)->buttons() == Qt::LeftButton) {
auto delta = QCursor::pos() - m_ref;
adjust(event, delta);
}
}
#endif
if ((watched == m_src.data() &&
(event->type() == QEvent::Move || event->type() == QEvent::Resize)) ||
(watched == m_dst.data() && event->type() == QEvent::Show)) {
if (event->type() == QEvent::Move)
m_ref = QCursor::pos();
adjust(event);
}
return false;
}
public:
WindowOffset(const QPoint & offset, QObject * parent = nullptr) :
QObject{parent},
m_offset{offset}
{}
WindowOffset(QWidget * src, QWidget * dst, const QPoint & offset, QObject * parent = nullptr) :
WindowOffset{offset, parent}
{
src->installEventFilter(this);
dst->installEventFilter(this);
m_src = src;
m_dst = dst;
}
};
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QLabel d1{"Source"}, d2{"Target"};
WindowOffset offset{&d1, &d2, {200, 50}};
for (auto d : {&d1, &d2}) {
d->setMinimumSize(300,100);
d->show();
}
return app.exec();
}
#include "main.moc" | unknown | |
d7219 | train | The method you are using requires 2 parameters:
getIntExtra(String name, int defaultValue)
So, just add a second int parameter, specifying the default value, in case the name is not found, something like this:
int defaultValue = -1;
count = data.getIntExtra(HelloActivity.EXTRA_REPLY, defaultValue); | unknown | |
d7220 | train | You can use BeautifulSoup it's great for parse HTML content, see this example
A: If your requirement is to create an application using Python and users will access via browser and update some data into a table?
Use Django or any web framework, basically, you are trying to build a web app!!
or
if you are looking for something else do mention your requirement thoroughly.
A: The slick grid datatable used in bokeh can be edited directly by users:
http://docs.bokeh.org/en/latest/docs/reference/models/widgets.tables.html.
Since the data for each column of a datatable can correspond to a field of a ColumnDataSource, one could create python or javascript callbacks, to detect any changes to the datavalues in the table. You can then access the updated data for your desired use case.
Here is an example using javascript callback when the data is edited. When the data is edited the updated column is printed to the browser console. Note it only detects the data as changed after you edit the value then click out of the cell.
You can do exactly the same with a python callback if you want to run outside python functions based off user input. That does require running a bokeh server to work though.
from datetime import date
from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn, StringEditor
output_file("data_table.html")
data = dict(
dates=[date(2014, 3, i+1) for i in range(10)],
strings=['edit_this' for i in range(10)],
)
source = ColumnDataSource(data)
columns = [
TableColumn(field="dates", title="Date", formatter=DateFormatter()),
TableColumn(field="strings", title="Downloads", editor=StringEditor()),
]
data_table = DataTable(source=source, columns=columns, width=400, height=280,
editable=True)
# callback code to detect user edit of table
code = """
data = source.data
console.log('data has been updated!')
console.log(data['strings'])
"""
callback = CustomJS(code=code,args={'source':source})
source.js_on_change('data', callback)
show(widgetbox(data_table))
edit:
Here is a similar example using a python callback. When you edit the cell all of the cells are replaced in this example. Obviously you could do what ever you wanted this is just an illustration.
You need to set a callback on source that responds to a change in the data. Hence source.on_change('data', update). Read more
https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html
from datetime import date
from bokeh.io import curdoc
from bokeh.layouts import widgetbox
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn, StringEditor
data = dict(
dates=[date(2014, 3, i+1) for i in range(10)],
strings=['edit_this' for i in range(10)],
)
source = ColumnDataSource(data)
columns = [
TableColumn(field="dates", title="Date", formatter=DateFormatter()),
TableColumn(field="strings", title="Downloads", editor=StringEditor()),
]
data_table = DataTable(source=source, columns=columns, width=400, height=280,
editable=True)
# callback code to detect user edit of table
def update(attrname, old, new):
data = source.data
data['strings'] = ['you just edited the table.']*10
source.data = data
source.on_change('data', update)
curdoc().add_root(widgetbox(data_table)) | unknown | |
d7221 | train | You may use a POSIX ERE regex with grep like this:
grep -E '([[:space:]]|^)A1BG([[:space:]]|$)' file
To return matches (not matching lines) only:
grep -Eo '([[:space:]]|^)A1BG([[:space:]]|$)' file
Details
*
*([[:space:]]|^) - Group 1: a whitespace or start of line
*A1BG - a substring
*([[:space:]]|$) - Group 2: a whitespace or end of line
A: If I got clarifications in comments right, the objective is to find the average of values (second column) for unique names in the first column. Then there is no need for external tools.
Read the file line by line and add up values for each name. The name uniqueness is granted by using a hash, with names being keys. Along with this also track their counts
use warnings;
use strict;
use feature 'say';
my $file = shift // die "Usage: $0 filename\n";
open my $fh, '<', $file or die "Can't open $file: $!";
my %results;
while (<$fh>) {
#my ($name, $value) = split /\t/;
my ($name, $value) = split /\s+/; # used for easier testing
$results{$name}{value} += $value;
++$results{$name}{count};
}
foreach my $name (sort keys %results) {
$results{$name}{value} /= $results{$name}{count}
if $results{$name}{count} > 1;
say "$name => $results{$name}{value}";
}
After the file is processed each accumulated value is divided by its count and overwritten by that, so by its average (/= divides and assigns), if count > 1 (as a small measure of efficiency).
If there is any use in knowing all values that were found for each name, then store them in an arrayref for each key instead of adding them
while (<$fh>) {
#my ($name, $value) = split /\t/;
my ($name, $value) = split /\s+/; # used for easier testing
push @{$results{$name}}, $value;
}
where now we don't need the count as it is given by the number of elements in the array(ref)
use List::Util qw(sum);
foreach my $name (sort keys %results) {
say "$name => ", sum(@{$results{$name}}) / @{$results{$name}};
}
Note that a hash built this way needs memory comparable to the file size (or may even exceed it), since all values are stored.
This was tested using the shown two lines of sample data, repeated and changed in a file. The code does not test the input in any way, but expects the second field to always be a number.
Notice that there is no reason to ever step out of our program and use external commands. | unknown | |
d7222 | train | It doesn't change because in case of list you changed value of int which is immutable in python, so changing item won't affect it's original value in list, while in second case you modified dict object which is mutable, so your change was applied to original object. For example, following code with list will work:
list = [{}, {}]
for item in list:
item['Age'] = 1
print(list)
Output:
[{'Age': 1}, {'Age': 1}] | unknown | |
d7223 | train | Check this:
//create a session namespace
$session = new Zend_Session_Namespace('myapp');
$session->somevar = 'somevalue';
echo $session->somevar; //somevalue
Zend_Session_Namespace has magic getter and setter.
So, if a attribute of the session object is not set, it will be NULL by default.
http://framework.zend.com/manual/1.12/en/zend.session.basic_usage.html | unknown | |
d7224 | train | According to api-ref List Servers doc, maybe you should add the project scope in the request.
By default the servers are filtered using the project ID associated with the authenticated request.
In my opinion, you could use openstacksdk to execute the operation, simply with the Connection object and list_servers method.
import openstack
conn = openstack.connect(
region_name='example-region',
auth_url='http://x.x.x.x:5000/v3/',
username='amazing-user',
password='super-secret-password',
project_id='33...b5',
domain_id='05...03'
)
servers = conn.list_servers() | unknown | |
d7225 | train | Yes, Cloudant boost factor should work correctly. Setting boost to a field of a specific doc, will modify the score of this doc: Score = OriginalScore * boost while searching on this field.
Do you search on the same field you boost? How does your query look like? Does the field my_field consists of multiple tokens? This may also influence scoring (e.g. longer fields get scored less).
You can observe scores of docs in the order fields in the results, and then by modifying boost observe how the scores are changing. | unknown | |
d7226 | train | It's a known issue in Python.
Default parameter values are always evaluated when, and only when, the
“def” statement they belong to is executed
Ref: http://effbot.org/zone/default-values.htm
In your code example, the temp_list's default value is evaluated when the def statement is executed. And thus it's set to an empty list. On subsequent calls, the list just keeps growing because the temp_list's default values are no longer evaluated and it keeps using the list instance it created the first time.
This could be a work around:
def flat_list(array, temp_list=None):
if not temp_list:
temp_list = []
for item in array:
if str(item).isdigit():
temp_list.append(item)
else:
temp_list = flat_list(item, temp_list)
return temp_list
Here, we have passed None instead of the empty list. And then inside the function body we check the value and initialize an empty list as we need. | unknown | |
d7227 | train | I just run into this.
The scrolling part is the angular-smooth-scroll's job (angular-ui-tour uses it properly).
The minified version is the problematic, also it shows no error :/
So I switched to the source version (/dist/angular-smooth-scroll.min.js -> /lib/angular-smooth-scroll.js) and it's working just fine. | unknown | |
d7228 | train | I would suggest restructuring the project so that it has a package.json in the root folder. A simple way to make it work is by letting the Express app serve the NextJS app.
I was having the same issue as you. I realized that deploying a NextJS app isn't as straight-forward as deploying a Create-React-App app. I ended up following the official recommendation of the NextJS team for deployment, which is to let Vercel serve it.
It was actually incredibly easy. I managed to deploy the NextJS app in a matter of minutes. Create a Vercel account, add a new app and deploy it.
The downside of this is that you will use Heroku for deploying your backend, and Vercel for deploying your frontend. But if you are using GitHub for example, Vercel will automatically re-deploy your NextJS app everytime you push to your main branch. So, in actuality you won't even have to do much in Vercel after deploying it the first time.
There are probably other ways and workarounds, but according to Vercel (who by the way are the creators of NextJS), deploying it with Vercel is the easiest way. | unknown | |
d7229 | train | Multiple Observables
PyMC3 supports multiple observables, that is, you can add multiple RandomVariable objects to the graph with the observed argument set.
Single Trial
In your first case, this would lend some clarity to the model:
counts=[countforPattime0, countforPattime1, ...]
with pm.Model() as single_trial:
# priors
k = pm.Uniform('k', 0, 20)
B = pm.Uniform('B', 0, 1000)
P = pm.Uniform('P', 0, 1000)
# transformed RVs
rate = pm.Deterministic('exprate', k*B)
mu = P*pm.math.exp(-rate*ts)
# observations
B_obs = pm.Poisson('B_obs', mu=B, observed=countforB)
Y_obs = pm.Poisson('Y_obs', mu=mu, observed=counts)
Multiple Trials
With this additional flexibility, hopefully it makes the transition to multiple trials more obvious. It should go something like:
B_cts = np.array(...) # shape (N, 1)
Y_cts = np.array(...) # shape (N, M)
ts = np.array(...) # shape (1, M)
with pm.Model() as multi_trial:
# priors
k = pm.Uniform('k', 0, 20)
B = pm.Uniform('B', 0, 1000, shape=B_cts.shape)
P = pm.Uniform('P', 0, 1000, shape=B_cts.shape)
# transformed RVs
rate = pm.Deterministic('exprate', k*B)
mu = P*pm.math.exp(-rate*ts)
# observations
B_obs = pm.Poisson('B_obs', mu=B, observed=B_cts)
Y_obs = pm.Poisson('Y_obs', mu=mu, observed=Y_cts)
There might be some extra syntax stuff to get the matrices multiplying correctly, but this at least includes the correct shapes.
Priors
Once you get that setup working, it would be in your interest to reconsider the priors. I suspect you have more information about the typical values for those than is currently included, especially since this seems like a chemical or physical model.
For instance, right now the model says,
We believe the true value of B remains fixed for the duration of a trial, but across trials is a completely arbitrary value between 0 and 1000, and measuring it repeatedly within a trial would be Poisson distributed.
Typically, one should avoid truncations unless they are excluding meaningless values. Hence, a lower bound of 0 is fine, but the upper bounds are arbitrary. I'd recommend having a look at the Stan Wiki on choosing priors. | unknown | |
d7230 | train | This line NSMutableDictionary *dictValues =[NSMutableDictionary dictionary]; should be inside for loop.
While finding the break time you must consider the date as well. Otherwise you will get wrong values.
NSMutableDictionary *thirdEntry = [NSMutableDictionary dictionary];
[thirdEntry setObject:@"02:00:00" forKey:@"end_time"];
[thirdEntry setObject:@"PUL" forKey:@"function_code"];
[thirdEntry setObject:@"01:25:00" forKey:@"start_time"];
[thirdEntry setObject:@"45" forKey:@"total_units"];
[thirdEntry setObject:@"20" forKey:@"total_time"];
[arrData addObject:thirdEntry];
NSLog(@"%@",arrData);
//dictionary
NSMutableDictionary *dictData =[NSMutableDictionary dictionary];
NSMutableDictionary *dictData1=[NSMutableDictionary dictionary];
NSMutableArray *arrayProgressDate =[NSMutableArray array];
for (int i =0; i<arrData.count; i++) {
dictData =arrData[i];
[arrayProgressDate addObject:dictData];
NSString *strendTime1 =[dictData objectForKey:@"end_time"];
NSLog(@"%@",strendTime1);
//storing the breaktime values
NSMutableDictionary *dictValues =[NSMutableDictionary dictionary];
[dictValues setObject:strendTime1 forKey:@"end_time_value"];
if ((i + 1) < arrData.count) {
dictData1=arrData[i+1];
NSString *strStartTimeNext = [dictData1 objectForKey:@"start_time"];
NSLog(@"%@",strStartTimeNext
);
//[arrayProgressDate addObject:strStartTimeNext];
[dictValues setObject:strStartTimeNext forKey:@"start_time_value"];
//calculating break time
NSDate *endTimeDate = [[DateHelper sharedHelper ] dateFromString:strendTime1 withFormat:@"HH:mm:ss"];
NSDate *startTimeDate = [[DateHelper sharedHelper]dateFromString:strStartTimeNext withFormat:@"HH:mm:ss"];
NSTimeInterval timeElapsedInSeconds = [endTimeDate timeIntervalSinceDate:startTimeDate];
double hours = timeElapsedInSeconds / 3600.0;
NSLog(@"%f",hours);
int breakTimeInMinutes = timeElapsedInSeconds/60;
breakTimeInMinutes =ABS(breakTimeInMinutes);
NSString *newStr =[NSString stringWithFormat:@"%i",breakTimeInMinutes];
NSLog(@"%@",newStr);
[dictValues setObject:newStr forKey:@"break_time"];
[arrayProgressDate addObject:dictValues];
}
NSLog(@"%@",dictData);
}
NSLog(@"%@",arrayProgressDate); | unknown | |
d7231 | train | Is there some sort of hex code I can use?
The ASCII code for Space is 32 or 0x20. If you want to use SPACEBAR like a constant, you can #define it to be:
#define SPACEBAR 32
or
#define SPACEBAR 0x20
Caveat
The above encoding will work for systems that use ASCII and UTF-8 encoding. For systems that use EBCDIC encoding, the decimal value to encode Space is 64 (Thanks are due to @BasileStarynkevitch for pointing that out).
A: #define SPACEBAR 32
OR
char ch = 0x20
Hope it helps
A: Depending of what you exactly want to do, you may be able to use:
#define SPACEBAR \040
It is the octal value of the space char, like it may appear in a string. | unknown | |
d7232 | train | Include another pipeline in $facet.
{"$facet":{
"UUID":[{"$group":{"_id":{"id":"$_id","UUID":"$UUID"}}},{"$count":"UUID_Count"}],
"COUNT":[
{"$group":{"_id":null,"subjects_list":{"$addToSet":"$SUBJECT"},"UUID_distinct_list":{"$addToSet":"$UUID"}}},
{"$addFields":{"subject_count":{"$size":"$subjects_list"},"UUID_distinct_count":{"$size":"$UUID_distinct_list"}}},
{"$project":{"_id":0}}
],
"SUB":[
{"$group":{"_id":"$SUBJECT","count":{"$sum":1}," UUID_list":{"$push":"$UUID"}}},
{"$group":{"_id":null,"each_sub_count":{"$push":{"sub":"$_id", "count":"$count"}},"UUID-assocaited_sub":{"$push":{"sub":"$_id", uuids:"$UUID_list"}}}},
{"$project":{"_id":0}}
]
}},
{"$replaceRoot":{"newRoot":{"$mergeObjects":[{"$arrayElemAt":["$UUID",0]},{"$arrayElemAt":["$COUNT",0]}, {"$arrayElemAt":["$SUB",0]}]}}} | unknown | |
d7233 | train | In your [:args :func] spec:
(spec/fspec :args (spec/cat :maps (spec/* map?)) :ret map?)
You're saying that the function must accept as arguments any number of maps and return a map. But the function you pass to deep-merge-with does not conform to that spec:
(fn [f s] s)
This function takes exactly two arguments, not an arbitrary number of maps. | unknown | |
d7234 | train | You could check the date on a shared file on the file system. Every time the configuration data changes, simply touch the file to change the modification date. Compare the date your program last loaded the data with the file's date. If the file has a newer date, reload the data, and update your LastLoaded date.
It is light weight, and it allows you to easily trigger data reloads. So long as the file hasn't changed in a while, the OS should have most of the file metadata in ram anyway.
While I haven't done performance comparisons, I've always found this way to be the a robust and easy to implement way to pass the "Reload your cache" message around to all clients.
DateTime cacheDate = DateTime.Now.AddHours(-1);
DateTime fileDate = System.IO.File.GetLastWriteTime(@"C:\cachefile.txt");
if(fileDate > cacheDate)
{
//Reload cache
cacheDate = DateTime.Now;
}
//Get Cached Data
You could also use the HttpContext cache.
Context.Cache.Add(key, val,
new System.Web.Caching.CacheDependency(@"C:\cachefile.txt"),
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Default,
null/* or your Callback for loading the cache.*/);
I haven't used this before in this way, so I don't know much about how it works. | unknown | |
d7235 | train | This is best way where I have taken the source from here
Selecet XML Nodes by similar names in Powershell
$XMLA = "D:\employee.xml"
$SqlDataBase = [xml](Get-Content $XMLA)
$data = $SqlDataBase.SelectNodes("Batch/Alter/ObjectDefinition/DataSources/DataSource/ConnectionString")
#$data
$DataSource = "localhost"
$SqlDataBase.Batch.Alter.ObjectDefinition.DataSources.DataSource.ChildNodes | Where-Object Name -Match 'ConnectionString' | ForEach-Object {
$DataBase = $_.'#text'.Split(";").Split("=")
$DataBase = $DataBase[$DataBase.Length - 1]
$ConnectionString = "Provider=SQLNCLI11.1;Data Source=$DataSource;Integrated Security=SSPI;Initial Catalog =$Database"
$_.'#text' = "$ConnectionString"
}
$SqlDataBase.Save($XMLA) | unknown | |
d7236 | train | From the docs:
identifier: "{{item.identifier|default(omit)}}" | unknown | |
d7237 | train | Enter the data rate (Kbps) for each connection: 1
Okay, so dataRate = 1.
Enter number of bit(s): 1
And bitMultiplexed = 1.
System.out.println(1 / (1000 * 1)); // 0
Need to cast to a float/double somehow, for example.
System.out.println(1 / (1000.0 * 1)) // 0.001
A: As you program/answer suggests.
inputSlot = 1 / 10000 = 0;
output = (1/3)*0 = 0;
frameDuration = 3 * 0 = 0;
Since these are int. It will strip the decimal part. Use BigDecimal or double for this purpose
A: The variables have to be floats instead of Integers. Integers can only store integers as the name sais. Floats can store point nubers like 0.0002. If u divide the int 20 by 11 and store this as a int Java will put 1 as the result. So if your result is 1.9 it is 1.0 as int. That is the Problem here. It looks like this
float inputSlot = (bitMultiplexed / (dataRate * 1000));
float outputSlot = ((1 / connectionsNum) * inputSlot);
int frameDuration = (connectionsNum * outputSlot);
System.out.println(inputSlot);
System.out.println(outputSlot);
System.out.println(frameDuration);
If you have a question ask me :)
A: The problem arises due to these 3 fields being initialized as ints. If you make them double your problem will be solved because when you declare them as ints, it will take just the integer part. So for example if you have 0.588 it will take just the 0 which is what is happening as of now.
int inputSlot = (bitMultiplexed / (dataRate * 1000));
int outputSlot = ((1 / connectionsNum) * inputSlot);
int frameDuration = (connectionsNum * outputSlot);
In order to solve this, you need to change the int to double. | unknown | |
d7238 | train | You would need to put the closing backtick after the end of the awk command, but it's preferable to use $() instead:
result=$( grep 'packet loss' dummy |
awk '{ first=match($0,"[0-9]+%")
last=match($0," packet loss")
s=substr($0,first,last-first)
print s}' )
echo $result
but you could just do:
result=$( grep 'packet loss' | grep -o "[0-9]\+%" )
A: Try
awk '{print $3}'
instead.
A: the solution below can be used when you don't know where the percentage numbers are( and there's no need to use awk with greps)
$ results=$(awk '/packet loss/{for(i=1;i<=NF;i++)if($i~/[0-9]+%$/)print $i}' file)
$ echo $results
100%
A: You could do this with bash alone using expr.
i=`expr "There is 98.76% packet loss at node 1" : '[^0-9.]*\([0-9.]*%\)[^0-9.]*'`; echo $i;
This extracts the substring matching the regex within \( \).
A: Here I'm assuming that the output lines you're interested in adhere strictly to your example, with the percentage value being the only variation.
With that assumption, you really don't need anything more complicated than:
awk '/packet loss/ { print $3 }' dummy
This quite literally means "print the 3rd field of any lines containing 'packet loss' in them". By default awk treats whitespace as field delimiters, which is perfect for you.
If you are doing more than simply printing the percentage, you could save the results to a shell variable using backticks, or redirect the output to a file. But your sample code simply echoes the percentages to stdout, and then exits. The one-liner does the exact same thing. No need for backticks or $() or any other shell machinations whatsoever.
NB: In my experience, piping the output of grep to awk is usually doing something that awk can do all by itself. | unknown | |
d7239 | train | For FlatList the data property requires an array, as highlighted in the docs. Since FlatList works by taking a list of items and rendering a seperate row for each, the data property needs to be an array.
Once you receive your JSON data, I would recommend only passing the required array to the FlatList, e.g.:
<FlatList
data={myResponse.listOfItems}
...
/>
Where myResponse is your JSON object and listOfItems is your array of items.
Also, according to the docs, there is no dataSource property, the correct property is simply data. | unknown | |
d7240 | train | It looks like there is an bug:
the setTitle method, does not set the title but the titleValue!
I would guess the correct implementation is:
public void setTitle(String title) {
this.title = title;
System.out.println(" Form set"+title);
}
A: Try using this. I suspect a mistake in your getter and setter implementation
public class LoginForm extends XFormBase {
private String title;
public void setTitle(String titleValue ) {
this.title= titleValue;
System.out.println(" Form set"+this.title);
}
public String getTitle() {
System.out.println(" Form get"+this.title);
return this.title;
}
} | unknown | |
d7241 | train | Your issue is here, that you did not create a StateObject in main View, and every time you pressed the key on keyboard you created a new model which it was empty as default!
import SwiftUI
struct ContentView: View {
@State var showNew = false
@StateObject var viewModel: CreateNewCardViewModel = CreateNewCardViewModel() // <<: Here
var body: some View {
Button(action: { showNew = true }, label: { Text("Create") })
.sheet(isPresented: $showNew, content: {
CreateNewCard(viewModel: viewModel)
})
}
}
struct CreateNewCard: View {
@ObservedObject var viewModel: CreateNewCardViewModel
var body: some View {
TextField("placeholder...", text: $viewModel.definition)
.foregroundColor(.black)
}
}
class CreateNewCardViewModel: ObservableObject {
@Published var definition: String = ""
} | unknown | |
d7242 | train | onActivityCreated() is deprecated in API level 28.
There is no error shown because no error exists. Deprecated means that a newer or better method exists to handle stuff. So you need to change onActivityCreated() to onCreate(). But as I see you don't need to call this a second time if you already have a Fragment with onCreateView(). Keep your project clear and make a new .java file instead. Don't code everything in one single file.
*
*onCreate() is for Activity
*onCreateView() is for Fragment | unknown | |
d7243 | train | >>> song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
>>> count = 0
>>> while count < (len(song)):
if song[count] == "look" :
print song[count]
count += 4
song[count] = 'a' + song[count]
continue
print song[count]
count += 1
Output:
always
look
aside
of
life
A: for uses iter(song) to loop; you can do this in your own code and then advance the iterator inside the loop; calling iter() on the iterable again will only return the same iterable object so you can advance the iterable inside the loop with for following right along in the next iteration.
Advance the iterator with the next() function; it works correctly in both Python 2 and 3 without having to adjust syntax:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
print sing
if sing == 'look':
next(song_iter)
next(song_iter)
next(song_iter)
print 'a' + next(song_iter)
By moving the print sing line up we can avoid repeating ourselves too.
Using next() this way can raise a StopIteration exception, if the iterable is out of values.
You could catch that exception, but it'd be easier to give next() a second argument, a default value to ignore the exception and return the default instead:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
print sing
if sing == 'look':
next(song_iter, None)
next(song_iter, None)
next(song_iter, None)
print 'a' + next(song_iter, '')
I'd use itertools.islice() to skip 3 elements instead; saves repeated next() calls:
from itertools import islice
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
print sing
if sing == 'look':
print 'a' + next(islice(song_iter, 3, 4), '')
The islice(song_iter, 3, 4) iterable will skip 3 elements, then return the 4th, then be done. Calling next() on that object thus retrieves the 4th element from song_iter().
Demo:
>>> from itertools import islice
>>> song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
>>> song_iter = iter(song)
>>> for sing in song_iter:
... print sing
... if sing == 'look':
... print 'a' + next(islice(song_iter, 3, 4), '')
...
always
look
aside
of
life
A: I think, it's just fine to use iterators and next here:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
it = iter(song)
while True:
word = next(it, None)
if not word:
break
print word
if word == 'look':
for _ in range(4): # skip 3 and take 4th
word = next(it, None)
if word:
print 'a' + word
or, with exception handling (which is shorter as well as more robust as @Steinar noticed):
it = iter(song)
while True:
try:
word = next(it)
print word
if word == 'look':
for _ in range(4):
word = next(it)
print 'a' + word
except StopIteration:
break
A: You can do this without an iter() as well simply using an extra variable:
skipcount = -1
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
for sing in song:
if sing == 'look' and skipcount <= 0:
print sing
skipcount = 3
elif skipcount > 0:
skipcount = skipcount - 1
continue
elif skipcount == 0:
print 'a' + sing
skipcount = skipcount - 1
else:
print sing
skipcount = skipcount - 1
A: Actually, using .next() three times is not nonsense. When you want to skip n values, call next() n+1 times (don't forget to assign the value of the last call to something) and then "call" continue.
To get an exact replica of the code you posted:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
songiter = iter(song)
for sing in songiter:
if sing == 'look':
print sing
songiter.next()
songiter.next()
songiter.next()
sing = songiter.next()
print 'a' + sing
continue
print sing
A: Of course you can use three time next (here I actually do it four time)
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
it = iter(song)
for sing in it:
if sing == 'look':
print sing
try:
sing = it.next(); sing = it.next(); sing = it.next(); sing=it.next()
except StopIteration:
break
print 'a'+sing
else:
print sing
Then
always
look
aside
of
life
A: I believe the following code is the simplest for me.
# data list
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
# this is one possible way
for sing in song:
if sing != 'look'\
and sing != 'always' \
and sing != 'side' \
and sing != 'of'\
and sing != 'life':
continue
if sing == 'side':
sing = f'a{sing}' # or sing = 'aside'
print(sing)
# this is another possible way
songs_to_keep = ['always', 'look', 'of', 'side', 'of', 'life']
songs_to_change = ['side']
for sing in song:
if sing not in songs_to_keep:
continue
if sing in songs_to_change:
sing = f'a{sing}'
print(sing)
This produces the results you are looking for.
always
look
aside
of
life | unknown | |
d7244 | train | I may be wrong but I think that when you set your header Content-type to image/jpeg, you should just return the image data (assuming it is stored as a blob in your database)
<?php
header('Content-type: image/jpeg');
echo $contentIMG;
?>
Your code should look like this:
<?php
include 'connections/conn.php';
error_reporting(E_ALL);
// some basic sanity checks
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
$contentIMG = $row_Recordset1['content'];
header('Content-type: image/jpeg');
echo $row_Recordset1['content'];
// close the db link
mysql_close($result);
}
else {
echo 'Please use a real id number';
}
?> | unknown | |
d7245 | train | The html will be held in memory for as long as the object that references it exists.
If your for loop does not assign the B object to any other variable, then each time you re-assign page the previously created B object will become eligible for garbage collection, and the html will be removed from memory at the same time.
If you are retaining references to each of your B objects you will slowly fill up your memory, but if you allow them to be garbage collected you should be fine.
A: You can use del page or page = None, both statements release the content for garbage collection. This makes sense if your for-loop kernel is memory critical or you are using object that bring their own memory management (like numpy.ndarray).
Also note that variables "bleed" out of the scope of for-loops. That means that the page from the last iteration will be present until the current scope is terminated (usually at the end of the function/method). | unknown | |
d7246 | train | ...coming from the comments, I leave an answer here:
With version 6.0.0, Cypress introduced a new command: .intercept().
.intercept() allows you to manage the behavior of network requests. It supports fetch, it can intercept both request and response of your app API calls and so much more, official docs here.
Related to your case, make sure you declare your intercept command before the proper fetch action, let's say on the top of the test. Then, simply call it below in the body of the test by its alias:
cy.intercept('GET', '/project/*').as('myObject')
// ...
cy.wait('@myObject').its('response.body.data.id').then(objUUID => {
// here is your uuid
cy.log(objUUID)
})
Note, that any other action related to this uuid should be done inside above callback: .then(objUUID => {}). In case you need it shared between different tests, then intercept your request inside .beforeEach() hook and assign the uuid in a context shared variable, however, this is a bad practice (more about aliases and variables, here) | unknown | |
d7247 | train | Up to java 8 you check the bundled xerces version with:
java com.sun.org.apache.xerces.internal.impl.Version
After java 8 (i.e from java 9 upwards) you can extract the jmods/java.xml.jmod with:
jmod extract java.xml.jmod
And then look in the just extracted legal/xerces.md. Usually the version is on the first line stated as a commented text. | unknown | |
d7248 | train | The problem is that you're creating a style for each cell, while you should create just ONE style for each type of cell.
var baseStyle = workBook.CreateCellStyle();
...
var priceStyle = workBook.CreateCellStyle();
priceStyle.CloneStyleFrom(numberStyle);
priceStyle.DataFormat = workBook.CreateDataFormat().GetFormat("€ #,##0.00");
private static void SetCellValuePrice(IRow row, ICellStyle cellStyle, int colIndex, decimal value)
{
var xlCell = row.CreateCell(colIndex);
xlCell.SetCellValue(Convert.ToDouble(value));
xlCell.CellStyle = cellStyle;
}
Usage:
SetCellValue(row, priceStyle, colIndex++, data.Description); | unknown | |
d7249 | train | Assuming createCORSRequest returns an xhr or xhr-like object (which seems to be the typical boilerplate for createCORSRequest from places like the HTML5 Rocks website), you need to include geocode.send(); at the end of your code. Otherwise the request never fires and therefore the onload handler never gets called.
A: Look like you're following HTML5Rocks site Using CORS article.
Once you create the xhr request. You must invoke send() method to trigger the ajax call.
var geocode = new XMLHttpRequest();
geocode = createCORSRequest('GET', 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=');
geocode.onload = function() {
var geoData = JSON.parse(geocode.responseText); // parse the JSON from geocode response
var results = geoData["results"]; // create variable for results
var userLong = results["geometry"]["location"]["lng"]; // parse the latitude
var userLat = results["geometry"]["location"]["lat"]; // parse the longitude
console.log(userLong);
console.log(userLat);
}
geocode.send();
Unless you call geocode.send(), the value will be undefined as no request has been fired. | unknown | |
d7250 | train | I think this could be an alternative, instead of overwriting perform_create, overwrite create
class showcaseCreateViewSet(generics.CreateAPIView):
queryset = Showcase.objects.all()
serializer_class = ShowcaseSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
def create(self, request):
serializer = self.serializer_class(
data=request.data
)
if serializer.is_valid():
showcase = serializer.save(user=request.user)
if showcase:
showcase.administrator.add(request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Another possibility is passing in the view the request (or just the user) to the context of the serializer by implementing get_serializer_context,
def get_serializer_context(self):
return {
'request': self.request
}
and then, implement the create method of the serializer,
def create(self, validated_data):
showcase = Showcase(**validated_data)
showcase.administrator.add(self.context['request'].user)
showcase.save()
return showcase | unknown | |
d7251 | train | I do not clearly get what you requirement is. However you can create a distributed deployment of WSO2 APIM as in [1].
There is no specific distributed deployment scenario of wso2 IS. However IS can be used in clustering as in previous answer.
Other than that, WSO2 products can be deployed by clustering. Refer this [2] such clustering patterns.
[1] https://docs.wso2.com/display/AM210/Distributed+Deployment+of+API+Manager
[2] https://docs.wso2.com/display/AM210/Distributed+Deployment+of+API+Manager
A: You can find the clustering documentation for WSO2 IS 5.4.0 in https://docs.wso2.com/display/IS540/Setting+Up+Deployment+Pattern+1 | unknown | |
d7252 | train | Like this:
SET/P upper_bound=<input.txt | unknown | |
d7253 | train | The solution is the !important tag, it overrides the existing style values. Use the following css code to avoid eye cancer when using xdebug:
.xdebug-error {
font-size: 12px !important;
width: 95% !important;
margin: 0 auto 10px auto !important;
border-color: #666 !important;
background: #ddd !important;
}
.xdebug-error th, .xdebug-error td {
padding: 2px !important;
}
.xdebug-error th {
background: #ccc !important;
}
.xdebug-error span {
display: none !important;
}
.xdebug-error_description th {
font-size: 1.2em !important;
padding: 20px 4px 20px 100px !important;
background: #ccc no-repeat left top !important;
}
.xdebug-error_callStack th {
background: #666 !important;
color: #ddd !important;
}
A: Have a nice xdebug!
Yes you can. Try this css below.
table.xdebug-error {
width: auto;
background: white;
border: none;
border-spacing: none;
border-collapse: collapse;
box-shadow: 0px 3px 10px 0px black;
position: fixed;
top: 0px;
right: 0px;
z-index: 8888;
font: 14px verdana;
transform-origin: top right;
transform: scaleX(0.4);
opacity: 0.3;
transition: all 200ms ease;
}
table.xdebug-error caption,
table.xdebug-error th,
table.xdebug-error td {
text-align: left;
vertical-align: middle;
}
table.xdebug-error a img {
border: 0;
}
table.xdebug-error :focus {
outline: 0;
}
table.xdebug-error pre {
margin: 0;
}
table.xdebug-error tbody tr td,
table.xdebug-error tbody tr th {
border: none;
border-bottom: 1px solid rgba(0,0,0,0.2);
font-weight: normal;
}
table.xdebug-error tbody tr td {
padding: 3px !important;
vertical-align: top;
}
table.xdebug-error tbody tr th {
padding: 13px !important;
}
table.xdebug-error tbody tr td:nth-of-type(1) {
width: 5% !important;
}
table.xdebug-error tbody tr th[bgcolor='#f57900'] {
font-weight: normal;
background: steelblue;
color: white;
}
table.xdebug-error tbody tr th[bgcolor='#f57900'] span {
display: none;
}
table.xdebug-error tbody tr font[color='#00bb00'] {
color: #005e00;
}
table.xdebug-error tbody tr td small {
display: none;
}
table.xdebug-error tbody tr td i {
padding-left: 12px;
}
table.xdebug-error:hover {
transform: none;
opacity: 1;
}
CONS:
*
*Depending on your other css defs, you may have to fiddle a bit until it looks as promised.
*It's not as beautiful as a Laravel/Symfony error
PROS:
*
*You can see the actual page, despite the error. (Message will be dimmed and pushed on the right side, appearing on mouse hover.)
*It's nothing more than CSS
*You can even add it to your page via CSS Live Editor Plugin or something similar; therefore, no need to add to your own code
*It won't break your styling, won't stuff a whole lot of text into a tiny container where the error happened, etc. - because it's position:fixed.
*Pleasant to the eye - you'll end up throwing errors just to see it again :)
A: Another option is to disable xdebug from overloading var_dump.
In the php.ini [XDebug] section add xdebug.overload_var_dump=0
Formatting the output is then up to you; one such way could be wrapping var_dump in your own debug function that prints <pre> tags.
A:
// notice the line height, the padding(cellspacing), monospace font, font size, making readability better at least for me.
//
// A FILENAME : xdebug_stack_trace.css
//
// This is how the xdebug_stack_trace.css is called from the index.php page
//
// <style><?php require_once("./resources/css/xdebug_stack_trace.css");?></ style>
//
// notice that on the line above there is a space between the slash
// and the 'style', on the ending 'style' tag, otherwise the display
// get all messed up when this page gets loaded.
//
// make sure that when you copy the 'style' line from here to the
// index page, that you remove the extra space at the ending 'style'
// tag of the index page.
// +---------+---------+---------+---------+---------+---------+---------+
// orange/black td header line
// +---------+---------+---------+---------+---------+---------+---------+
.xdebug-error th
{
font-family:monospace;
font-weight:normal;
font-size:15px;
padding: 6px 6px 6px 6px;
border:1px solid black;
background: #FFCC99; // orange
color:#000000; // black
}
// +---------+---------+---------+---------+---------+---------+---------+
// black/white th header line
// +---------+---------+---------+---------+---------+---------+---------+
.xdebug-error > tr:first-child > th:first-child,
.xdebug-error > tbody > tr:first-child > th:first-child
{
line-height:1.6em;
padding: 10px 10px 10px 10px;
border:1px solid #000000;
background: #000000; // black
color:#FFFFFF;
}
// +---------+---------+---------+---------+---------+---------+---------+
// green/black td content one or more lines
// +---------+---------+---------+---------+---------+---------+---------+
.xdebug-error td
{
font-size:14px;
padding: 6px 6px 6px 6px;
border:1px solid green;
background: #D1FFE8; // light green
}
// +---------+---------+---------+---------+---------+---------+---------+ | unknown | |
d7254 | train | You are concatenating on dim=1, well that means you need to join the tensors one after the othe ralong dim=1. The value that you get after concatenation along dim=1 is value=256+512+1024+2048+256, provided shapes of the tensors match in other dimensions too. The size of tensor x should be x=(5,256,32,32).
A: Inputs (values of l1, l2, l3, l4) are not provided, so I just guessed it and tried to mimic your code. Below snippet works fine.
import torch
import torch.nn as nn
import torch.nn.functional as F
class Pyramid_Pooling(nn.Module):
def __init__(self, levels, inChans, outChans):
super(Pyramid_Pooling, self).__init__()
self.inChans = inChans
self.outChans = outChans
assert len(levels) == 4
self.pool_4 = nn.AvgPool2d((levels[3], levels[3]))
self.pool_3 = nn.AvgPool2d((levels[2], levels[2]))
self.pool_2 = nn.AvgPool2d((levels[1], levels[1]))
self.pool_1 = nn.AvgPool2d((levels[0], levels[0]))
# lower the number of channels to desired size
self.bottleneck_pyramid = nn.Conv2d(
self.inChans, self.outChans, kernel_size=1
)
def forward(self, en1, en2, en3, en4):
pooled_out_1 = self.pool_1(en1)
print(pooled_out_1.shape)
pooled_out_2 = self.pool_2(en2)
print(pooled_out_2.shape)
pooled_out_3 = self.pool_3(en3)
print(pooled_out_3.shape)
pooled_out_4 = self.pool_4(en4)
print(pooled_out_4.shape)
cat = torch.cat((pooled_out_1, pooled_out_2, pooled_out_3, pooled_out_4), 1)
out = self.bottleneck_pyramid(cat)
return out
I tried to guess your inputs and issue might be somehwere in input dimensions. You want to output 32 x 32 then input should be like below. Also added a 1x1 conv to lower the channels to desired output.
x_train_0 = torch.randn((3, 256, 32, 32), device = torch.device('cuda'))
x_train_1 = torch.randn((3, 512, 64, 64), device = torch.device('cuda'))
x_train_2 = torch.randn((3, 1024, 128, 128), device = torch.device('cuda'))
x_train_3 = torch.randn((3, 2048, 256, 256), device = torch.device('cuda'))
inChans = x_train_0.shape[1] + x_train_1.shape[1] + x_train_2.shape[1] + x_train_3.shape[1]
outChans = 512
# kernel_size = [1,2,4,8]
pyramid_pooling = Pyramid_Pooling([1, 2, 4, 8], inChans, outChans)
pyramid_pooling.to(torch.device('cuda'))
out = pyramid_pooling(x_train_0, x_train_1, x_train_2, x_train_3)
print(f"Output shape: {out.shape}")
Output will look like this:
torch.Size([3, 256, 32, 32])
torch.Size([3, 512, 32, 32])
torch.Size([3, 1024, 32, 32])
torch.Size([3, 2048, 32, 32])
Output shape: torch.Size([3, 512, 32, 32]) | unknown | |
d7255 | train | Hi Your fixed code here:
<html>
<head><title>Sheet</title></head>
<body>
<h2 align="center">SKU Selection</h2>
<?php
$conn = mysqli_connect('localhost', 'root', '');
$db = "sample";
mysqli_select_db($conn, $db);
$sql = "SELECT DISTINCT(Site) FROM `bom`";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn)); // add error show info
echo "Site Name :";
echo "<select name='Site'>";
echo "<option value='0'>Select Site</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['Site'] . "'>" . $row['Site'] . "</option>";
}
echo "</select>";
$sql1 = "SELECT BOM Desc FROM `bom` where Site IS NULL "; // change the for null site
$result1 = mysqli_query($conn, $sql1) or die(mysqli_error($conn)); // add error show info
echo "<br>";
echo "SKU :";
echo "<select name='SKU'>";
while ($row1 = mysqli_fetch_array($result1)) {
echo "<option value='" . $row1['BOM Desc'] . "'>" . $row1['BOM Desc'] . "</option>";
}
echo "</select>";
?>
</body>
</html>
And if you need load on second select php only cant handle this because you must give time to user for check first select.
I think the better way is using Ajax request for second:
Auto Load Second Dropdown using AJAX
A: I suggest to use in both <select> the clause selected to show the selected <option>.
Then, in the first <select> add the on change event to launch a page refresh so that:
*
*The selected entry is recognised as selected
*The SQL for the second drop-down can be filtered on the selected entry in first dropdown
The first select should appear then like this:
<select onChange='if(options[selectedIndex].value) { location=options[selectedIndex].value;}' size='1'>
<option value='?site=Plant1'>Plant ONE</option>
<option value='?site=Plant2' selected>Plant 2</option>
</select>
When Plant 2 is selected, the page will be refreshed with the URL containing the parameter &site=Plant2 which you can read in the variable $_REQUEST['site'] to be used in the 2nd SQL query | unknown | |
d7256 | train | There is a chance that the model doesn't exist. You can add a check for this in your controller as follows:
public function update(Request $r, $post_id) {
$post = Post::find($post_id);
if (!$post) {
// You can add code to handle the case when the model isn't found like displaying an error message
return back();
}
$post->post_title = $r->post_title;
$post->post_image = $r->post_image;
$post->post_details = $r->post_details;
$post->post_rating = $r->post_rating;
$post->id = $r->id;
$post->save();
return back();
} | unknown | |
d7257 | train | I have an update. The issue turned out to be simple in hindsight. I added both the RobotUIKit and RobotKit frameworks to the "Embedded Binaries" section of the General tab for my target app in Xcode. They should ONLY be added to the "Linked Frameworks and Libraries" section. The Sphero framework is a pre-iOS 8 framework and thus appears to be statically linked. | unknown | |
d7258 | train | In an ultra-basic way, that website (that you have removed from your question) would have the container measure the height of your window and attach the height of the window to the header(container) and then absolute position the menu to the bottom of this container (see code for a very rough example)
.container {
background:red;
position:relative;
height:100vh;
}
li {
list-style:none;
float:left;
}
.menu {
position:absolute;
bottom:0;
width:100%;
background:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div class="container">
<div class="menu">
<ul>
<li>Link</li>
<li>Link</li>
<li>Link</li>
<li>Link</li>
</ul>
</div>
</div>
<h1>This is more content</h1>
If you need anything further explaining, let me know.
--- UPDATE ---
Instead of using JavaScript to work out the height of your browser window, simply add height:100vh to the container height. This will match the container height to the browser height, give you the same outcome (just through CSS rather than JavaScript - with the added positive of that this you won't have to assign this to an on resize in case the user resizes their screen). I have updated the code above.
--- FURTHER UPDATE ---
Thanks, by moving .slider-btm out of .slider-outer-wrapper container, this should resolve your issue so that .slider-btm can sit at the bottom of your container which is 100vh.
A: You want to have the bar fixed at the bottom of the screen, also while scrolling?
Use position: fixed
.slider-btm {
position: fixed;
width: 100%;
bottom: 0;
height: 60px;
z-index: 10;
}
A: i think the issue is the the different screen resolution of the devices , add this line to the "slider-outer-wrapper" class
.slider-outer-wrapper{
position: relative;
height: 100%;
}
you have added max-height property , please remove it
after removing | unknown | |
d7259 | train | I found a solution.
It's necessary to use XmlAttributeOverrides.
Because I have two projects I had to use reflection to retrieve classes which derive from GuiConfigurationBase. (I don't know anything about project where is my toolkit project referenced)
Then add new XmlElementAttribute for each class (in my case it should be enough to use Linq First() method) - This should be same as XmlIncludeAttribute(Type)
And finaly add XmlAttributeOverrides for ConfigurationBase class's property GuiConfiguration
Here is my deserialize method:
public T Deserialize<T>(string input) where T : class
{
//Init attrbibutee overrides
XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
//Load all types which derive from GuiConfiguration base
var guiConfTypes = (from lAssembly in AppDomain.CurrentDomain.GetAssemblies()
from lType in lAssembly.GetTypes()
where typeof(GuiConfigurationBase).IsAssignableFrom(lType) && lType != typeof(GuiConfigurationBase)
select lType).ToArray();
//All classes which derive from GuiConfigurationBase
foreach (var guiConf in guiConfTypes)
{
XmlElementAttribute attr = new XmlElementAttribute
{
ElementName = guiConf.Name,
Type = guiConf
};
attrs.XmlElements.Add(attr);
}
//Add Attribute overrides for ConfigurationBase class's property GuiConfiguration
attrOverrides.Add(typeof(ConfigurationBase), nameof(ConfigurationBase.GuiConfiguration), attrs);
XmlSerializer ser = new XmlSerializer(typeof(T), attrOverrides);
using (StringReader sr = new StringReader(input))
{
return (T)ser.Deserialize(sr);
}
}
I hope it will help someone else :-) | unknown | |
d7260 | train | The scroll works if you add background-attachment: local :
body {
background: #369;
color: #fff;
}
.wrap {
height: 50vh;
overflow: auto;
font: 26px / 1.5 sans-serif;
background-image: linear-gradient(180deg, transparent 0, currentColor 30%, currentColor 70%, transparent 100%);
background-color: transparent;
background-clip: text;
background-attachment: local;
-webkit-background-clip: text;
-moz-text-fill-color: transparent;
-webkit-text-fill-color: transparent;
}
<div class="wrap">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!
</div>
A:
body {
background: #369;/*bg color*/
color: #fff;
}
.wrap {
overflow: auto;
width: 100%;
height: 50vh;
display: inline-block;
margin: 10px;/*x*/
position: relative;
font: 26px / 1.5 sans-serif;
-ms-overflow-style: none; /* IE and Edge ,hide scroll bar*/
scrollbar-width: none; /* Firefox ,hide scroll bar*/
}
.wrap::-webkit-scrollbar {
display: none;/*hide scroll bar*/
}
.dwn{
height: 15vh;/*y*/
width: 100%;
bottom: 15vh;/*y*/
position: relative;
background: linear-gradient( transparent 0%,#369/*use same color as bg*/ 100%);
background: -webkit-linear-gradient( transparent 0%,#369/*use same color as bg*/ 100%);
}
.upn{
height: 15vh;/*y*/
width: 100%;
top: 10px;/*x*/
position: absolute;
z-index: 100;
background: linear-gradient( #369/*use same color as bg*/ 0%, transparent 100%);
background: -webkit-linear-gradient( #369/*use same color as bg*/ 0%, transparent 100%);
}
<div class="tl">
<div class="upn">
</div>
<div class="wrap" id="prisonerResponse">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus,
ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt
aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi
blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing
elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at
distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum
delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima
nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus
dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima
nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus
dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima
nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus
dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima
nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus
dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima
nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus
dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima
nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus
dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima
nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus
dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima
nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus
dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima
nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus
dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci,
aspernatur minima nobis at distinctio eveniet sunt aliquid, iure
laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis
veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio
eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus
ipsa, sequi blanditiis veritatis!
</div>
<div class="dwn">
</div>
</div>
(Run it IN FULL PAGE)
Here we
*
*do some stuff to it by using position&display which makes it scrollable as well as dynamically fades in top and bottom
*hide scrollbar(it works even without hiding scrollbar!)
*since we hide scrollbar hover your mouse over text and scroll
*we have made it work in firefox by .dwn,.upn div classes thus hover your mouse over the center of text and scroll down
StackBlitz Code-https://stackblitz.com/edit/web-platform-1cfdsj?file=index.html
Demo-https://web-platform-1cfdsj.stackblitz.io
A: Try using:
.wrap {
height: 50vh;
overflow: auto;
font: 26px / 1.5 sans-serif;
mask-image: linear-gradient(180deg, transparent 0, currentColor 30%, currentColor 70%, transparent 100%);
-webkit-mask-image: linear-gradient(180deg, transparent 0, currentColor 30%, currentColor 70%, transparent 100%);
}
A: The problem was that background was not fixed relative to the "element's contents". Using: background-attachment: local;
will help make the background fixed relative to the element's contents.
Add background-attachment: local; to the wrap class. | unknown | |
d7261 | train | While specifying operands for expr command, to validate against a boolean value, we should use only string is command.
% expr {0==false}
0
% expr {[string is false 0]}
1
Simply validating against boolean equal == will treat them as if like literal string/list.
Reference : expr | unknown | |
d7262 | train | Demo FIDDLE
Jquery
var d=new Date();
d.setDate(d.getDate()+2);
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
alert(weekday[d.getDay()]);
A: Simply add +2 because getDay() returns the day.
var n = weekday[d.getDay()+2];
Here is the example Fiddle
A: In the following sample +d gives the same result as d.getTime() :
// 3600000ms (=1h) x 48 = 2 days
var n = weekday[new Date(+d + 3600000 * 48).getDay()]
I also really like ling.s's approach, but it needs a little fix :
// friday.getDay() -> 5
// weekday[5 + 2] -> undefined
// weekday[(5 + 2) % 7] -> "Sunday"
var n = weekday[(d.getDay() + 2) % 7];
Here is one way to display it :
<span id="twoDaysLater"></span>
var weekday = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
var now = new Date();
var twoDaysLater = new Date(+now + 3600000 * 48);
var dayName = weekday[twoDaysLater.getDay()];
jQuery(function ($) {
// DOM is now ready
$('#twoDaysLater').text(dayName);
});
Here is a demo : http://jsfiddle.net/wared/346L8/.
Based on ling.s's solution : http://jsfiddle.net/wared/346L8/2/. | unknown | |
d7263 | train | Get the value of the function when the user click on the button and alert inside clickListener.
As per your code snippet you are getting the value of the startBtn function outside of the click listener and alerting it also give 5, but you need to get the value and alert that value only after the user click on the button not when JS is compiled.
function startBtn() {
var a = 5;
return a;
}
document.getElementsByName("submit-button")[0].addEventListener("click", () => {
var test = startBtn();
alert(test);
});
var test = startBtn();
alert(test);
<input class="submit-btn" type="submit" name="submit-button" value="Start">
A: if you want to alert a from js function just insert the alert function on your startBtn function like this
function startBtn() {
var a = 5;
alert(a);
}
document.getElementsByName("submit-button")[0].addEventListener("click", startBtn);
// var test = startBtn(); //Does not work as I want
// alert(test); //Does not work as I want
<input class="submit-btn" type="submit" name="submit-button" value="Start"> | unknown | |
d7264 | train | One way to control individual process scripts is with signals. If you combine SIGINT (ctrl-c) to resume with SIGQUIT (ctrl-) to kill then the child process looks like this:
#!/bin/sh
trap 'echo you hit ctrl-c, waking up...' SIGINT
trap 'echo you hit ctrl-\, stoppng...; exit' SIGQUIT
while (true)
do
echo "do the work..."
# pause for a very long time...
sleep 600000
done
If you run this script, and hit ctrl-c, the work continues. If you hit ctrl-\, the script stops.
You would want to run this in the background then send kill -2 $pid to resume and kill -3 $pid to stop (or kill -9 would work) where $pid is the child process's process id.
Here is a good bash signals reference: http://www.ibm.com/developerworks/aix/library/au-usingtraps/
-- here is the parent script...
#!/bin/sh
./child.sh &
pid=$!
echo "child running at $pid"
sleep 2
echo "interrupt the child at $pid"
kill -INT $pid # you could also use SIGCONT
sleep 2
echo "kill the child at $pid"
kill -QUIT $pid
A: One way is to create a named pipe per child:
mkfifo pipe0
Then redirect stdin of the child to read from the pipe:
child < pipe0
to stop the child:
read _
(the odd _ is just there for read to have a place to store the empty line it will read).
to resume the child:
echo > pipe0
A more simple approach would be to save the stdin which gets passed to the child in form a pure file descriptor but I don't know the exact syntax anymore and can't google a good example ATM. | unknown | |
d7265 | train | The first two are equivalent. Whether you use an inner join or cross join is really a matter of preference in this case. I think I would typically use the cross join, because there is no real join condition between the tables.
Note: You should never use cross join when the intention is a "real" inner join that has matching conditions between the tables.
The cross apply is not doing the same thing. It is only choosing one row. If your intention is to get at most one matching row, then use cross apply. If the intention is to get exactly one matching row, then use outer apply.
A: We use Cross join (or just the keyword Join) only when we don't have any column in common among the tables (not the best structure design!) or we need all the possible cases. I don't know your table structure but I'm assuming table SecRole has no foreign or common key to Staff and InsStaff. In this case I would use a Right join (outer joins) here to get all the result from the first inner join between Staff and InsStaff and then put them next to SecRole desired records.
Here is the concept of a Right join
http://www.dofactory.com/sql/right-outer-join | unknown | |
d7266 | train | Google actually has an article in their Webmaster guidelines on this subject. You may want to take a look, as they specifically address the issues you have raised: http://www.google.com/support/webmasters/bin/answer.py?answer=182192
A: I'd use subdomains:
eng.mysite.com/whatever
it.mysite.com/whatever
Then have a sitemap which points to the home page of each of those language subdomains, and they should all be crawled just fine.
A: You can use the following approach:
*
*Scan the Accept-Language header ($_SERVER['HTTP_ACCEPT_LANGUAGE']) for languages that the user agent prefers. This is usually more reliable than checking the IP address for their country.
*Check the User-Agent header ($_SERVER['HTTP_USER_AGENT']) to see if the request comes from a search engine, such as "Googlebot" and "Yahoo! Slurp". | unknown | |
d7267 | train | So if you look through the source for mechanize in form.rb - form submitting is calling a function called build_query which sorts the fields on the form. Since sort uses the <=> operator, and it's undefined on Hpricot elements, you are getting an exception.
It seems as if mechanize was built to use Nokogiri - it may have unfixed bugs with other parsing implementations. I did not get too deep into mechanize's source and don't want to blame anyone, but you may want to try switching to Nokogiri for this project (if possible). It doesn't seem from this snippet as if you're relying heavily on Hpricot. It seems strange to me that mechanize is throwing an exception on a hidden form field from Hpricot, but the stack trace is pretty clear in this regard.
Your other major option is to hop into the mechanize source and see if you can fix it yourself (or file a bug on the mechanize github and hope somebody gets to it).
Good luck. | unknown | |
d7268 | train | Yes, via the Full Packaged Scan: https://www.zaproxy.org/docs/docker/full-scan/
Setting up authentication is also possible - we've just published a video walking through this process: https://www.youtube.com/watch?v=BOlalxfdLbU | unknown | |
d7269 | train | Jiang Bo, I was also getting the same problem with the latest Strawberry Perl version (5.24.0.1). I downgraded to 5.20.3.3 / 64bit and cpan installations work fine there. | unknown | |
d7270 | train | I finally resolved this issue by setting the property in a new thread like below:
Task.Factory.StartNew(() =>
{
InvokeOnMainThread(() =>
{
_searchController.SearchBar.BecomeFirstResponder();
});
}); | unknown | |
d7271 | train | It seems you are looking more for auditing features. Oracle and several other DBMS have full auditing features. But many DBAs still end up implementing trigger based row auditing. It all depends on your needs.
Oracle supports several granularities of auditing that are easy to configure from the command line.
I see you tagged as MySQL, but asked about any storage engine. Anyway, other answers are saying the same thing, so I'm going delete this post as originally it was about the flashback features.
A: Obviously you are really after a MySQL solution, so this probably won't help you much, but Oracle has a feature called Total Recall (more formally Flashback Archive) which automates the process you are currently hand-rolling. The Archive is a set of compressed tables which are populated with changes automatically, and queryable with a simple AS OF syntax.
Naturally being Oracle they charge for it: it needs an additional license on top of the Enterprise Edition, alas. Find out more (PDF).
A: You can achieve similar behavior with triggers (search for "triggers to catch all database changes") - particularly if they implement SQL92 INFORMATION_SCHEMA.
Otherwise I'd agree with mrjoltcola
Edit: The only gotcha I'd mention with MySQL and triggers is that (as of the latest community version I downloaded) it requires the user account have the SUPER privilege, which can make things a little ugly
A: Oracle and Sql Server both call this feature Change Data Capture. There is no equivalent for MySql at this time.
A: I think Big table, the Google DB engine, does something like that : it associate a timestamp with every update of a row.
Maybe you can try Google App Engine.
There is a Google paper explaining how Big Table works.
A: CouchDB has full versioning for every change made, but it is part of the NOSQL world, so would probably be a pretty crazy shift from what you are currently doing.
A: The wikipedia article on google's bigtable mentions that it allows versioning by adding a time dimension to the tables:
Each table has multiple dimensions
(one of which is a field for time,
allowing versioning).
There are also links there to several non-google implementations of a bigtable-type dbms.
A: The book Refactoring Databases has some insights on the matter.
But it also points out there is no real solution currently, other then carefully making changes and managing them manually.
A: One approximation to this is a temporal database - which allows you to see the status of the whole database at different times in the past. I'm not sure that wholly answers your question though; it would not allow you to see the contents of Row 1 at time t1 while simultaneously letting you look at the contents of Row 2 at a separate time t2.
A: "It's kind of an esoteric thing, but it would beat having to keep writing these separate history tables and functions every time a change is made..."
I wouldn't call audit trails (which is obviously what you're talking of) an "esoteric thing" ...
And : there is still a difference between the history of database updates, and the history of reality. Historical database tables should really be used to reflect the history of reality, NOT the history of database updates.
The history of database updates is already kept by the DBMS in its logs and journals. If someone needs to inquire the history of database upates, then he/she should really resort to the logs and journals, not to any kind of application-level construct that can NEVER provide sufficient guarantee that it reflects ALL updates. | unknown | |
d7272 | train | Something like this will help:
With Selection.Find
.ClearFormatting
.Text = "If you no longer wish to receive emails from Self Service Terminal, please click on the 'Unsubscribe' link below: Unsubscribe"
.Replacement.ClearFormatting
.Replacement.Text = ""
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
See Om3rs link in the comment for more information on this. | unknown | |
d7273 | train | You should be able to use set_source_files_properties along with the LANGUAGE property to mark the file(s) as C++ sources:
set_source_files_properties(${TheFiles} PROPERTIES LANGUAGE CXX)
As @steveire pointed out in his own answer, this bug will require something like the following workaround:
set_source_files_properties(${TheFiles} PROPERTIES LANGUAGE CXX)
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
add_definitions("-x c++")
endif()
A: Normally you should be able to just extend CMAKE_CXX_SOURCE_FILE_EXTENSIONS. This would help, if you have a lot of files with unknown file extensions.
But this variable is not cached - as e.g. CMAKE_CXX_FLAGS is - so the following code in CMakeCXXCompiler.cmake.in will always overwrite/hide whatever you will set:
set(CMAKE_CXX_IGNORE_EXTENSIONS inl;h;hpp;HPP;H;o;O;obj;OBJ;def;DEF;rc;RC)
set(CMAKE_CXX_SOURCE_FILE_EXTENSIONS C;M;c++;cc;cpp;cxx;mm;CPP)
I consider this non-caching being a bug in CMake, but until this is going to be changed I searched for a workaround considering the following:
*
*You normally don't want to change files in your CMake's installation
*It won't have any effect if you change CMAKE_CXX_SOURCE_FILE_EXTENSIONS after project()/enable_language() (as discussed here).
I have successfully tested the following using one of the "hooks"/configuration variables inside CMakeCXXCompiler.cmake.in:
cmake_minimum_required(VERSION 2.8)
set(CMAKE_CXX_SYSROOT_FLAG_CODE "list(APPEND CMAKE_CXX_SOURCE_FILE_EXTENSIONS pde)")
project(RPiCopter CXX)
message("CMAKE_CXX_SOURCE_FILE_EXTENSIONS ${CMAKE_CXX_SOURCE_FILE_EXTENSIONS}")
add_executable(RPiCopter tinycopter.pde)
A: I decided to use this approach. I just remove the file ending by cmake in the temporary build directory.
So GCC is not confused anymore because of the strange Arduino *.pde file extension.
# Exchange the file ending of the Arduino project file
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/tinycopter.pde ${CMAKE_CURRENT_BINARY_DIR}/tinycopter.cpp)
A: CMake doesn't do this for you:
http://public.kitware.com/Bug/view.php?id=14516 | unknown | |
d7274 | train | You can use automapper to transfer data from first to second entity.After that your code will be:
...
db.sample_table1.Add(sample_table1);
db.SaveChanges();
//insert data to 2nd Entities
var sample_table2 = Mapper.Map<sample_table2>(sample_table1);
db2.sample_table_2.Add(sample_table2);
db2.SaveChanges();
... | unknown | |
d7275 | train | It's really designed as a standard for describing in a cross-platform cross-language manner an interface that a developer can use to develop a SOAP based way to exchange information with a web service.
Another alternative would be providing a library that provides a local interface to a blackbox communcation scheme, which is fraught with compatability/security issues.
Or providing documentation, which may be difficult to find, have compatibility issues, be out of date, or incomplete.
In short, it's very useful. | unknown | |
d7276 | train | You have a mistake in your code of Categories Called
Corrected Code
function getLatestProducts() {
$args = array(
'post_status' => 'publish',
'post_type' => 'products',
'posts_per_page' => 12,
'meta_key' => '_cus_sort_order',
'orderby' => 'meta_value_num, name',
'order' => 'ASC'
);
$terms = get_terms('product_categories', $args);
foreach($terms as $term) {
$prod_meta = get_option("taxonomy_term_".$term->term_id);
?>
<a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
<?php
echo '<img src="'.$prod_meta['img'].'" title="" alt=""></a>'; ?>
</div>
<div class="product-name">
<h5>
<a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
<?php echo $term->name;?>
</a>
</h5>
I have removed an array of argument which is called after main arguments array. As the below mentioned argument array is overriding the above mentioned arguments array.
Removed Arguments Array
$args = array(
'orderby' => 'name',
);
Hope this helps!
A: Extending on Mehul's answer, your saving function has also some mistakes.
Have you checked previously saved sort orders of your categories ?
"taxonomy_term_$t_id" should be "taxonomy_term_" . $t_id . Otherwise you are saving everything as taxonomy_term_$t_id option and not with a dynamic term id.
function save_product_categories_custom_fields($term_id)
{
if (isset($_POST['term_meta'])) {
$t_id = $term_id;
$term_meta = get_option("taxonomy_term_" . $t_id);
$cat_keys = array_keys($_POST['term_meta']);
foreach ($cat_keys as $key) {
if (isset($_POST['term_meta'][$key])) {
$term_meta[$key] = $_POST['term_meta'][$key];
}
}
//save the option array
update_option("taxonomy_term_" . $t_id, $term_meta);
}
} | unknown | |
d7277 | train | Regarding ClearCase, as mentioned in this IBM technote:
The SCC API is an interface specification, defined by Microsoft® that defines hooks for a number of common source control operations.
An application (typically an "integrated" development environment (IDE) of any kind) can provide source control functions without implementing the functions itself.
If an SCC compliant code control system is installed, the application dispatches code control operations to the source control tool (e.g. Visual Studio > ClearCase).
That being said:
*
*if you are new to version control, try and stay away from ClearCase: it isn't the more practical one by far ;)
*IBM Jazz protocol is a much more recent standard, that other SCM tools can use to integrate into other environments.
So while the concept of tool integration is important, the SCC concept is quite old, and limited to version control.
As opposed to Application Hub communication protocol, for integrating any two applications together, like Jazz. | unknown | |
d7278 | train | It's obvious that you have to authenticate server-side. Assuming that you've already had one, so the remaining is not very difficult.
The most simple way is just send an Ext.Ajax.request:
Ext.Ajax.request({
url: your_API_url,
params: {
username: your_username_from_formpanel,
password: your_password_from_formpanel
},
timeout: 10000, // time out for your request
success: function(result) {
// here, base on your response, provide suitable messages
// and further processes for your users
},
failure: function(){
Ext.Msg.alert("Could not connect to server.");
}
});
Note: for security reasons, you should encrypt your user's password before sending it to server. | unknown | |
d7279 | train | Although scenarios can be written in that way, it is not best practice. I for one, have made that mistake and it can cause problems in reports and maintenance.
One reason would be that When declares an action and Then verifies the result of that action. Having When - Then twice goes against the individual behavior of a scenario.
Can also get confusing for someone who reads the scenario :)
Here's a little post regarding this
A: There is alot of really bad Gherkin on the web. Also there is a range of opinions about what good Gherkin is.
My opinion is that When Then When Then is an anti-pattern. Its likely that one of the following is required
*
*You need a better Given to incorporate the first When Then
or
*You need to split the scenario in two.
In general most When's in scenario's become Given's in later scenario's, as you build on existing behaviour to define and create new behaviour.
A: Syntactically Interchangeable; Linguistically Different
The Gherkin syntax currently includes six keywords for describing feature steps:
*
*Given
*When
*Then
*And
*But
**
The keywords are there for human consumption and the ease of conveying business logic. However, the Gherkin language itself treats the keywords as interchangeable symbols, so you could just as grammatically (from a Gherkin point of view) write tortured English like:
But for a dollar held
Then another dollar more
Given ownership of two dollars am I.
This is perfectly valid Gherkin, but a terrible representation of counting money. So, if all the words are interchangeable, why have so many of them?
The wiki is quite clear that they provide a set of conventions to facilitate communication in a more natural style, and the wiki even gives a few examples of how the words are meant to be differentiated. The wiki also specifically says:
Cucumber doesn’t technically distinguish between these...[kinds] of steps. However, we strongly recommend that you do! These words have been carefully selected for their purpose, and you should know what the purpose is to get into the BDD mindset.
In other words, use the Gherkin terms to communicate in (relatively) natural language about your feature, and bury the arcana in step definitions. Use whatever keyword fits most naturally in the linguistic flow, and don't sweat a well-written scenario that doesn't rigidly adhere to a convention that may not apply in all cases. | unknown | |
d7280 | train | Yes, it is possible to work offline by installing locally:
*
*Apache / Nginx
*PHP
*MySQL
That can be done...:
*
*with WampServer (Windows)
*with XAMPP (ALL)
*with MAMP (OSX)
*manually by installing all apps.
You will have to edit your host file to map the domain.com to your localhost (127.0.0.1). The reason is that, by default, WordPress is not domain agnostic, which means absolute links (including the domain) are stored in the database. Otherwise, you will need to edit the data to map it to localhost.
As you are new with WordPress, I will remind you to backup the website BEFORE doing any change. A free tool like BackWPup can do the job to backup all files and the database.
The changes you made on the website were made directly in production (meaning on the live site). That is a really bad practice, as you probably know why now, because your visitors see and incomplete and buggy website.
That is why you need a dev environment where you can build and test everything. If you did not do any backup and feel screwed, you can install a maintenance plugin like Ultimate Coming Soon Page and configure it to tell your visitors that the site is having a make over and come back later.
As for tutorials, I would start with How to install WordPress with WampServer. First, you will understand how to install WordPress... in general. Once you understand this part, you are ready to export an existing website and import it locally. I would suggest to read more about How move a WordPress website locally.
This is a start! Use Google as you go... it will help a lot! :-)
A: You can install XAMPP packages that ships with Apache, Mysql (MariaDB actually) and PHP environments. All already configured so you can just Next > Next > Install.
https://www.apachefriends.org/pt_br/index.html
A: I've always preferred working directly on the remote server using Aptana with built-in FTP client. I've known others that prefer working locally using WAMP.
https://sourceforge.net/projects/wampserver/ | unknown | |
d7281 | train | the thing is that image is not UIImage, it's NSURL.
Change code to this one:
imageView.image = UIImage(data: NSData(contentsOfURL: image as NSURL)!)!
A: U need to do like this
if let strongImageView = weakImageView {
if let imageURL = image as? NSURL{
strongImageView.image = UIImage(data:NSData(contentsOfURL: imageURL)!)
}else{
strongImageView.image = image as? UIImage
}
}
For Clarification I added Full Code Please refer, It worked for me
override func viewDidLoad() {
super.viewDidLoad()
// Get the item[s] we're handling from the extension context.
// For example, look for an image and place it into an image view.
// Replace this with something appropriate for the type[s] your extension supports.
var imageFound = false
for item: AnyObject in self.extensionContext!.inputItems {
let inputItem = item as! NSExtensionItem
for provider: AnyObject in inputItem.attachments! {
let itemProvider = provider as! NSItemProvider
if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeImage as String) {
// This is an image. We'll load it, then place it in our image view.
weak var weakImageView = self.imageView
itemProvider.loadItemForTypeIdentifier(kUTTypeImage as String, options: nil, completionHandler: { (image, error) in
NSOperationQueue.mainQueue().addOperationWithBlock {
if let strongImageView = weakImageView {
if let imageURL = image as? NSURL{
strongImageView.image = UIImage(data:NSData(contentsOfURL: imageURL)!)
}else{
strongImageView.image = image as? UIImage
}
}
}
})
imageFound = true
break
}
}
if (imageFound) {
// We only handle one image, so stop looking for more.
break
}
}
}
A: Getting image as
<UIImage: 0x16ecb410>, {100, 100}
It cannot be casted as NSURL and getting nil in the following expression.
imageView.image = UIImage(data: NSData(contentsOfURL: image as NSURL)!)! | unknown | |
d7282 | train | The problem is that you need to change the CSS. I will try to explain.
In your CSS, you have set the canvas to display: none. In your jQuery, you try to use the fadeOut animation. This won't work because the element is not displayed, it is basically removed from the document, so jQuery can't change it.
What you need to do is set the canvas to display: block. So that the 'preloader' is visible when the user accesses the website. Then the 'preloader' will fade out.
Here is the updated CSS.
canvas {
display: block;
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
background-color: #000000;
z-index: 99;
}
JavaScript
if (sessionStorage.getItem('dontLoad') == null)
{
jQuery("#c").delay(1000).fadeOut('slow', function()
{
jQuery( "body" ).animate({
visibility: visible
})
}, 1000);
}
if (sessionStorage.getItem('dontLoad') == true)
{
$('#c').css('display', 'none');
} | unknown | |
d7283 | train | This is a quirk in the way Ruby handles trailing if/unless conditions and how variables come into existence and get "defined".
In the first case the constant is not "defined" until it's assigned a value. The only way to create a constant is to say:
CONSTANT = :value
Variables behave differently and some would argue a lot more strangely. They come into existence if they're used anywhere in a scope, even in blocks of code that get skipped by logical conditions.
In the case of your line of the form:
variable = :value unless defined?(variable)
The variable gets "defined" since it exists on the very line that's being executed, it's going to be conditionally assigned to. For that to happen it must be a local variable.
If you rework it like this:
unless defined?(variable)
variable = :value
end
Then the behaviour goes away, the assignment proceeds because the variable was not defined prior to that line.
What's strange is this:
if defined?(variable)
variable = :value
end
Now obviously it's not defined, it doesn't get assigned, but then this happens:
defined?(variable)
# => "local-variable"
Now it's defined anyway because Ruby's certain it's a variable. It doesn't have a value yet, it's nil, but it's "defined" as far as Ruby's concerned.
It gets even stranger:
defined?(variable)
# => false
if (false)
variable = :value
end
defined?(variable)
# => "local-variable"
Where that block of code didn't even run, it can't even run, and yet, behold, variable is now defined. From that assignment line on forward that variable exists as far as Ruby is concerned.
Since you're doing an attempted assignment and defined? on the same line the variable exists and your assignment won't happen. It's like a tiny paradox. | unknown | |
d7284 | train | Here is a data.table approach. Probably not the fastest, but it will get the job done.
library(data.table)
# Make it a data.table
setDT(df1)
# Create an id-column
df1[, rowid := .I]
# Set id column as key
setkey(df1, rowid)
# Create temp data.table with all succesfull shots
dt.shot.success <- df1[type_name == "shot" & result_name == "success", ]
# perform join on all fouls
df1[df1[type_name == "foul", ], foul_to_goal_within_120 := {
temp <- dt.shot.success[!home_team == i.home_team &
game_id == i.game_id &
period_id == i.period_id &
time_seconds %between% c(i.time_seconds, i.time_seconds + 120), ]
list(nrow(temp) > 0)
}, by = .EACHI][]
#fouls on row 15, 36 and 37 lead to a successfull shot for the other team within 120 seconds | unknown | |
d7285 | train | Looking at this package, you should import pyupnp.upnp, not pyupnp. The contents of __all__ are irrelevant here. | unknown | |
d7286 | train | You just need to convert your array to a hash:
@data[:duration] = per_hour.collect do |val|
[val[0], val[1]]
end.to_h
For Ruby 1.9:
@data[:duration] = Hash[*per_hour.collect { |val| [val[0], val[1]] }]
A: I would write this as follows:
def duration
@data[:duration] ||= build_duration
end
This is a short way to say: return @data[:duration] if not nil, otherwise, assign build_duration to it.
And then you define build_duration
def build_duration
result = {}
per_hour.each do |val|
result[val[0]] = val[1]
end
result
end
You can write the build_duration more compact, but for me this is very readable: it will build a hash and fill it up as you wish.
A: @data[:duration] ||= per_hour.collect { | val | [val[0], val[1]] }.to_h
Try this. | unknown | |
d7287 | train | If I understand correctly, you want to use simulation to approximate the probability of obtaining a sum of k when roll m dice. What I recommend is creating a function that will take k and m as arguments and repeat the simulation a large number of times. The following might help you get started:
function Simulate(m,k,Nsim=10^4)
#Initialize the counter
cnt=0
#Repeat the experiment Nsim times
for sim in 1:Nsim
#Simulate roll of m dice
s = sum(rand(1:6,m))
#Increment counter if sum matches k
if s == k
cnt += 1
end
end
#Return the estimated probability
return cnt/Nsim
end
prob = Simulate(3,4)
The estimate is approximately .0131.
A: You can also perform your simulation in a vectorized style as shown below. Its less efficient in terms of memory allocation because it creates a vector s of length Nsim, whereas the loop code uses a single integer to count, cnt. Sometimes unnecessary memory allocation can cause performance issues. In this case, it turns out that the vectorized code is about twice as fast. Usually, loops are a bit faster. Someone more familiar with the internals of Julia might be able to offer an explanation.
function Simulate1(m,k,Nsim=10^4)
#Simulate roll of m dice Nsim times
s = sum(rand(1:6,Nsim,m),2)
#Relative frequency of matches
prob = mean(s .== k)
return prob
end | unknown | |
d7288 | train | you can try like this with create nested array.
interface Teacher {
name: string;
sex: string;
age: number;
student: Student[{
name: string;
sex: string;
address: string;
}];
}
{Teacher.map(({name,sex,address,student}) => (
<View>
{student.map(student => (
<Text>{student.name}</Text>
<Text>{student.sex}</Text>
<Text>{student.address}</Text>
))}
</View>
)} | unknown | |
d7289 | train | With Git 2.16 or more, do at least once:
git add --renormalize .
git commit -m "normalize eol files"
git push
Then try and clone your repo elsewhere, and check that git status behaves as expected.
Make sure you don't have core.autocrlf set to true.
git config core.autocrlf
And you can test for your files eol style. | unknown | |
d7290 | train | As there is no registry singleton like in ZF1 creating a service and injecting it where needed is appropriate. You can then place it according to your autoloader configuration in the filesystem. As well inside that class you could do anything you like to build the array, e.g. using a database for it.
Nevertheless you can as well use your config for it if it is static information - e.g. like this:
Module.php
class Module
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
}
module.config.php
return [
'deptList' => [
'01' => 'Human Resources',
'02' => 'Sales',
'03' => 'Marketing',
'04' => 'Accounting',
// ...
],
];
MyController.php
class MyController extends \Zend\Mvc\Controller\AbstractActionController
{
public function myAction()
{
$config = $this->getServiceLocator()->get('config');
$deptList = $config['deptList'];
}
} | unknown | |
d7291 | train | For this you can use the directions API inside of the Unity SDK. Check out the traffic and directions example. You'll see how the response is being drawn as a line and rendered on a map. The DirectionsFactory.cs script draws a line along the route with the assigned material. | unknown | |
d7292 | train | This is a C# 6.0 feature called expression bodied property
public ICommand ChangeLangCommand => new DelegateCommand(this.ChangeLangClick);
You can either upgrade your compiler (install latest release version of VS2015) or don't use it, as it's equal to getter-only property:
public ICommand ChangeLangCommand
{
get
{
return new DelegateCommand(this.ChangeLangClick);
}
}
I have feeling, what creating new instance of the command every time property is accessed is wrong, correct code may/would be
public ICommand ChangeLangCommand { get; }
// in constructor
ChangeLangCommand = new DelegateCommand(this.ChangeLangClick);
I think this is also a new feature (to initialize getter-only property from constructor), if this is true, then you can use older syntax:
ICommand _changeLangCommand;
public ICommand ChangeLangCommand
{
get
{
return _changeLangCommand;
}
}
// in constructor
_changeLangCommand = new DelegateCommand(this.ChangeLangClick); | unknown | |
d7293 | train | I found the problem. I am adding the subdirectory I want to install with EXCLUDE_FROM_ALL such that it doesn't build everything in the subdirectory, only the library I need. That flag seems to prevent the subdirectory install() from happening. Perhaps ExternalProject_Add is indeed the best way to go here...
Also, RE overriding custom targets, this worked for me: http://public.kitware.com/pipermail/cmake/2011-July/045269.html | unknown | |
d7294 | train | var proxyUrl = 'https://cors-anywhere.herokuapp.com/'
var url="https://www.bitbns.com/order/getTicker";
let x = proxyUrl + url
fetch(x, {mode: "cors",
}).then(function(response) {
return response.json();
}).then(function(j) {
console.log(JSON.stringify(j));
}).catch(function(error) {
console.log('Request failed', error)
});
This will get things rolling, but it is better not to use this for production due to lack of security.
https://cors-anywhere.herokuapp.com/ is a link that add cors header.
A: Here is what i found on https://www.sencha.com/forum/showthread.php?299915-How-to-make-an-ajax-request-cross-origin-CORS
$.ajax({
url: 'http:ww.abc.com?callback=?',
dataType: 'JSONP',
jsonpCallback: 'callbackFnc',
type: 'GET',
async: false,
crossDomain: true,
success: function () { },
failure: function () { },
complete: function (data) {
if (data.readyState == '4' && data.status == '200') {
errorLog.push({ IP: Host, Status: 'SUCCESS' })
}
else {
errorLog.push({ IP: Host, Status: 'FAIL' })
}
}
}); | unknown | |
d7295 | train | After some trial and error, the sequence of setting the tv.setMovementMethod(LinkMovementMethod.getInstance()); does matter.
Here's my full code
String stringTerms = getString(R.string.sign_up_terms);
Spannable spannable = new SpannableString(stringTerms);
int indexTermsStart = stringTerms.indexOf("Terms");
int indexTermsEnd = indexTermsStart + 18;
spannable.setSpan(new UnderlineSpan(), indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(getColor(R.color.theme)), indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Log.d(TAG, "TODO onClick.. Terms and Condition");
}
}, indexTermsStart, indexTermsEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
int indexPolicyStart = stringTerms.indexOf("Privacy");
int indexPolicyEnd = indexPolicyStart + 14;
spannable.setSpan(new UnderlineSpan(), indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(getColor(R.color.theme)), indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Log.d(TAG, "TODO onClick.. Privacy Policy");
}
}, indexPolicyStart, indexPolicyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView textViewTerms = (TextView) findViewById(R.id.sign_up_terms_text);
textViewTerms.setText(spannable);
textViewTerms.setClickable(true);
textViewTerms.setMovementMethod(LinkMovementMethod.getInstance());
A: Direct Approach in Kotlin
val textHeadingSpannable = SpannableString(resources.getString(R.string.travel_agent))
val clickSpan = object : ClickableSpan(){
override fun onClick(widget: View) {
// Handel your click
}
}
textHeadingSpannable.setSpan(clickSpan,104,136,Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
tv_contact_us_inquire_travel_agent.movementMethod = LinkMovementMethod.getInstance()
tv_contact_us_inquire_travel_agent.text = textHeadingSpannable
A: Have you tried setting the MovementMethod on the TextView that contains the span? You need to do that to make the clicking work...
tv.setMovementMethod(LinkMovementMethod.getInstance());
A: Kotlin util function:
fun setClickable(textView: TextView, subString: String, handler: () -> Unit, drawUnderline: Boolean = false) {
val text = textView.text
val start = text.indexOf(subString)
val end = start + subString.length
val span = SpannableString(text)
span.setSpan(ClickHandler(handler, drawUnderline), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
textView.linksClickable = true
textView.isClickable = true
textView.movementMethod = LinkMovementMethod.getInstance()
textView.text = span
}
class ClickHandler(
private val handler: () -> Unit,
private val drawUnderline: Boolean
) : ClickableSpan() {
override fun onClick(widget: View?) {
handler()
}
override fun updateDrawState(ds: TextPaint?) {
if (drawUnderline) {
super.updateDrawState(ds)
} else {
ds?.isUnderlineText = false
}
}
}
Usage:
Utils.setClickable(textView, subString, {handleClick()}) | unknown | |
d7296 | train | int sorted[] = {}
OK... so sorted is an array with no elements. Some compilers will warn about this:
test.cpp(217) : error C2466: cannot allocate an array of constant size 0
But let's assume it works for your compiler and creates an array of constant size 0... Then what? Your code does this:
sorted[indx] = symbols[i];
Hey! What's going on here... sorted doesn't have space to store anything. That write results in undefined behavior - it may crash, it may overwrite memory or it may cause your computer to add... one... hundred... billion... dollars to your bank account.
A: int sorted[] = {}
This creates an array with 0 elements.
A: It is always a good idea to run your compiler in a more... restrictive mode than it runs by default, just to disable the most thoughtless compiler extensions. This applies to virtually all compilers out there.
In your case
int sorted[] = {};
is completely ill-formed C++ code, which is required to trigger diagnostic message. An there's a very good reason for that diagnostic message to be an error message specifically, not a mere warning.
Strictly speaking, even though there are quite a few weird extensions compilers implement, I'm still surprised that there's one that allowed this declaration to slip through. What compiler is that?
Just tried it myself and discovered that GCC actually accepts this. What were they thinking this time? What is it for? To support local declarations for "struct hack"-ed objects with a trailing array of zero size? Something else? | unknown | |
d7297 | train | After looking at network requests, I saw a request going to Google Payments Services which end to a 500 error. At this moment, I just remember that I've conflict with my Google Payments account. When I solved it, I was totally able to be both member of a Developer Console and owner of my own Developer Console. On the Developer Console UI, I'm able to switch between the 2 accounts thanks to the menu on top right corner. | unknown | |
d7298 | train | This may help you http://forum.developers.facebook.net/viewtopic.php?id=37430 | unknown | |
d7299 | train | setAllBoughts({
...allBoughts,
[boughtDate]: [
...(allBoughts.boughtDate || []),
{
product,
quantityBought,
},
],
});
allBoughts is the state that existed when this effect ran. Ie, it's the empty state, with no results in it yet. So every time a result comes back, you are copying the empty state, and adding one entry to it. This erases any results you have.
Instead, you need to use the most recent version of the state, which you can do with the function version of set state:
setAllBoughts(prevState => {
return {
...prevState,
[boughtDate]: [
...(prevState.boughtDate || []),
{
product,
quantityBought,
},
],
};
})
A: From what you're saying, it seems to me that you're erasing the previous stored result in the state (You get result for id 123, store it, then result of 345, store it and erase the previous value). Or you're just not looping through the array.
Here is an example of how to GET multiple times in a useEffect and assign all the results in the state.
Fully working example at Codesandbox
export default function App() {
const ids = useRef([1, 3, 5]);
const [items, setItems] = useState([]);
useEffect(() => {
const promises = ids.current.map((id) => fetchData(id));
Promise.all(promises).then((responses) => {
setItems(responses);
});
}, []);
async function fetchData(id) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${id}`
);
return response.json();
}
return (
<div className="App">
{items.map((item) => (
<div key={item.id}>
{item.id} - {item.title}
</div>
))}
</div>
);
} | unknown | |
d7300 | train | You should add ^ (start of line) to your regex:
/(?<=^[MA]\s).+/
If you don't do that, (?<=[MA]\s) will lookabehind the M part and .+ will catch db.
A: As of Mercurial 3.5, you can use templates (still an experimental feature, you can see it with hg help status -v). Namely:
hg status --change <rev> --template '{path}\n'
A: Why not use log with template?
hg log -r CSET -T "{files % '{file}\n'}"
will produce clean output
lang/UTF-8/serendipity_lang_ru.inc.php
plugins/serendipity_event_bbcode/UTF-8/lang_ru.inc.php
plugins/serendipity_event_emoticate/UTF-8/lang_ru.inc.php
plugins/serendipity_event_karma/UTF-8/lang_ru.inc.php
plugins/serendipity_event_s9ymarkup/UTF-8/lang_ru.inc.php
plugins/serendipity_plugin_shoutbox/UTF-8/lang_ru.inc.php
contrary to templated status
'lang\UTF-8\serendipity_lang_ru.inc.php
''plugins\serendipity_event_bbcode\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_emoticate\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_karma\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_s9ymarkup\UTF-8\lang_ru.inc.php
''plugins\serendipity_plugin_shoutbox\UTF-8\lang_ru.inc.php
' | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.