_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d12201 | train | Remove the column rental_id from the select list and sort the result by count(*) descending to return the top 1 row:
SELECT cust.customer_id, cust.name, count(*) as Total_Rentals
FROM rental as r
INNER JOIN customer AS cust on r.customer_id = cust.customer_id
GROUP BY cust.customer_id, cust.name
ORDER BY Total_Rentals DESC LIMIT 1
But if you only need the customer's id then there is no need for a join:
SELECT customer_id, count(*) as Total_Rentals
FROM rental
GROUP BY customer_id
ORDER BY Total_Rentals DESC LIMIT 1
A: You need to join customer and rental, group by customer id (without rental id) and count it:
SELECT cust.customer_id, count(*) as Total_Rentals
FROM rental as r
INNER JOIN customer AS cust on r.customer_id = cust.customer_id
GROUP BY cust.customer_id;
So this code should work. If it doesn't work, that probably means that you have duplicates or other nonconventional issues. | unknown | |
d12202 | train | You have to turn on the WORD-WRAP Feature in Visual Studio Code.
There are 2 ways to do this:
*
*By using the View menu (View* → Toggle Word Wrap)
*By using the Keyboard Shortcut
Windows/Linux: ALT + Z
Mac: ⌥ + Z | unknown | |
d12203 | train | Change :
ng-style="{'padding-left': grid.options.treeIndent * row.treeLevel + 'px'}
to :
ng-style="{'padding-left': (grid.options.treeIndent+10) * row.treeLevel + 'px'}
Result | unknown | |
d12204 | train | For protected OAuth requests, the signature is typically generated by using a pair of secrets (often a shared secret and an authorized token secret). As you've probably guessed, an ampersand ("&") is used to separate the two secrets. However, when a single secret is used as the signature (as with imgur) the ampersand is still required, but because there is no second secrete to separate, the ampersand appears at the end of string. Another way to think of it is the ampersand is separating the api_secret and an empty secret. | unknown | |
d12205 | train | The best solution is to downgrade the Flutter . after that update AndroidManifest file | unknown | |
d12206 | train | You could separate the code that was extending the third party DLL into another DLL. Then, in your "extension manager" dll, use a config file to match your extending assemblies with the 3rd party ones.
So, the config file could have an item with two entries like "someClass;inSome3rdPartDll" and then "yourClass;inYourDll".
Go through the config file to see if the listed 3rd party assemblies are present and, if they are, then load you associated assemblies in the app domain.
Now, if you want to extend future 3rd party assemblies, you need only add your dll and add a line to the config file.
Here's a link for help loading assemblies into app domains.
A: You could also look into MEF and leverage composition to accomplish this.
https://mef.codeplex.com | unknown | |
d12207 | train | Stripe Checkout with your live mode keys only works over HTTPS (or security reasons [0]), it works in localhost only in test mode.
You should swap in your live mode keys only when you are ready for production and have your web page/app deployed.
There is a handy checklist that you can reference so that you're meeting all the requirements before going live [1]
[0] https://stripe.com/docs/security#tls
[1] https://stripe.com/docs/payments/checkout/live | unknown | |
d12208 | train | EDIT: I found the correct link, and you can use the browser to translate to english. http://doc.open.youku.com/
The closest thing I can find to help you out this this thread, which contains a link that appears to go to Youku API documentation. I cannot get that link to open however. I hope this helps. | unknown | |
d12209 | train | The question is why the layout worked under 1.0.2 at all. What you see under 1.1.0 is how the layout is really defined. There are a couple of constraints that moved the images and text out of the layout and produced the blank area that you see. I made the corrections to the following XML and all looks OK. (I changed the colors and drawables used since I didn't have ready access to what you used, but you can change them back easily enough.)
<android.support.v7.widget.CardView
android:id="@+id/mCardviewPropertytype"
android:layout_width="160dp"
tools:background="@android:color/darker_gray"
android:layout_height="180dp"
android:layout_margin="8dp"
app:cardCornerRadius="8dp"
app:cardElevation="2dp">
<android.support.constraint.ConstraintLayout
android:layout_width="160dp"
android:layout_height="180dp"
android:layout_gravity="center"
android:layout_margin="8dp">
<android.support.constraint.ConstraintLayout
android:id="@+id/ImgPropertySelect"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@mipmap/ic_launcher"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
tools:visibility="visible"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_centerInParent="true"
app:srcCompat="@mipmap/ic_launcher" />
</android.support.constraint.ConstraintLayout>
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5" />
<ImageView
tools:visibility="visible"
android:id="@+id/imageViewPropertyType"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@mipmap/ic_launcher"
android:layout_marginLeft="16dp"
app:layout_constraintBottom_toTopOf="@+id/guideline"
app:layout_constraintLeft_toLeftOf="parent"
/>
<TextView
tools:text="Near residential area"
android:id="@+id/textViewTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:text="TextView"
android:textColor="@android:color/darker_gray"
android:textSize="20dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/guideline" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
A: Use this
app:cardBackgroundColor="@color/gray_black"
Instead of
tools:background="@color/gray_black"
Also
Use android:text="@string/nearResidentialArea"
instead of tools:text="@string/nearResidentialArea" | unknown | |
d12210 | train | Your loop loops paragraph.length() times (the number of characters in paragraph), but each time you extract a word. See the problem?
Use while (getline(ss, word, ' ')) instead. getline will return the stream it was given, and converting it to bool is equivalent to !ss.fail(). This basically loops until an extraction fails (reached the end of the stream and did not extract anything).
You also never checked if the search for the word in the map fails and therefore have the possibility of trying to dereference tran.end().
Some other minor problems with your code includes using namespace std which can be considered bad practice, and some typos involving the difference between tran and trans.
The fixed code:
#include <iostream>
#include <map>
#include <string>
#include <sstream>
int main()
{
std::map<std::string, std::string> tran;
tran["rearrancar"] = "reboot";
tran["pantalla"] = "screen";
tran["texto"] = "text";
tran["virus"] = "virus";
tran["tinta"] = "ink";
tran["mitad"] = "half";
tran["interno"] = "internal";
tran["memoria"] = "memory";
tran["papel"] = "paper";
tran["energia"] = "power";
tran["fallo"] = "bug";
tran["pelo"] = "hair";
tran["el"] = "the";
tran["dos"] = "two";
tran["todas"] = "all";
tran["en"] = "in";
tran["de"] = "of";
tran["los"] = "the";
tran["comprar"] = "buy";
tran["tarde"] = "afternoon";
tran["quieres"] = "want";
tran["muchachos"] = "boys";
tran["tienen"] = "have";
tran["ordenador"] = "computer";
tran["con"] = "with";
tran["antes"] = "before";
tran["vacio"] = "empty";
tran["tu"] = "you";
tran["hambre"] = "hunger";
tran["contaminado"] = "corrupt";
tran["a"] = "to";
tran["una"] = "a";
tran["la"] = "the";
tran["cafe"] = "brown";
tran["su"] = "your";
tran["es"] = "is";
tran["quiero"] = "want";
tran["vamos"] = "go";
tran["mi"] = "my";
tran["barco"] = "ship";
tran["nosotros"] = "we";
tran["casa"] = "house";
tran["yo"] = "I";
tran["borrar"] = "delete";
tran["necesita"] = "necessary";
tran["despues"] = "after";
std::string paragraph(
"yo quiero una ordenador virusu todas de los muchachos tienen");
std::stringstream ss(paragraph);
std::string word;
while (std::getline(ss, word, ' '))
{
auto findResult = (tran.find(word));
std::cout
<< (findResult != tran.end() ?
findResult->second : "[translation not found]") << " ";
}
} | unknown | |
d12211 | train | You forgot semicolons after your Ext.create() config.
Seems to work just fine here. I made a fiddle
http://jsfiddle.net/WGgR8/1/ | unknown | |
d12212 | train | You need a nested while to go through the days of the week rendering <span />s inside the week container. I'm not a php dev so can't help you with the implementation, sorry.
A: The question is do these events depend on a specific time or are you just trying to throw them in 1 company event per day AM and PM? In which case, you can just do:
$arr = array(0 => "am", 1 => "pm");
echo "<div class='week1'>";
while($Em1WkRow = mysql_fetch_array($Em1Wk1Res))
{
$clientQ = "SELECT * FROM clients WHERE userID='" . $Em1WkRow["userID"] . "'";
$clientRes = mysql_query($clientQ) or die(mysql_error());
$i = 0;
$out .= "<div class='day" . $Em1WkRow["daySlot"] . "'>"; // start day
while($clientRow = mysql_fetch_array($clientRes) && $i < 2)
{
// add current day's event
$out .= "<span class='" . $arr[$i++] . "'>";
$out .= $clientRow["company"];
$out .= "</span";
}
$out .= "</div>" // end day
}
echo $out; // display all week's info
echo "</div>"; // end week
A: This is what I ended up doing...
function emp_schedule($empID) {
$weeks = array(1, 2, 3, 4);
foreach ($weeks as $i => $week) {
$schedQ = "SELECT * FROM seo_schedule WHERE empID=$empID AND weekSlot=$week";
$Em1WkRes = mysql_query($schedQ) or die(mysql_error());
echo "<div class='week'>";
echo "<div class='head'><span class='ts'>Wk ".$week."</span> <span>Monday</span> <span>Tuesday</span> <span>Wednesday</span> <span>Thursday</span> <span>Friday</span></div>";
echo "<div class='ts'><span><strong>AM</strong></span><span><strong>PM</strong></span></div>";
while ($Em1WkRow = mysql_fetch_array($Em1WkRes)) {
$clientQ = "SELECT * FROM clients WHERE userID='".$Em1WkRow["userID"]."'";
$clientRes = mysql_query($clientQ) or die(mysql_error());
while($clientRow = mysql_fetch_array($clientRes)) {
$schd = "<div class='".$Em1WkRow["timeSlot"]."'>";
$schd .= "<span class='client'>".$clientRow["company"]."</span>";
$schd .= "</div>";
$days = array(1, 2, 3, 4, 5);
foreach ($days as $i => $day) {
if ($Em1WkRow["daySlot"] == $day && $Em1WkRow["timeSlot"] == "am" ) {
echo "<div class='day ".$Em1WkRow["daySlot"]."'>";
echo $schd;
}
if ($Em1WkRow["daySlot"] == $day && $Em1WkRow["timeSlot"] == "pm" ) {
echo $schd;
echo "</div>";
}
}
}
}
echo "</div>";
}
}
Mess I Know but it works. | unknown | |
d12213 | train | First things first,
I would like to be able to create several of SomeComponent from within App in the future.
This (at least the way you're doing it) is not something that is possible or should be done at all when using React. You cannot create a component inside another component.
The reason your useEffect is in an infinite loop can be all sorts of things at the moment. It can be that it is not positioned in the highest scope, but my guess is that the following happens:
genId() is called, and state is updated, re-render is initialized (because of state update), and const SomeComponent = () => {...} is initialized again, thus activating useEffect again.
To fix this, first things first remove <SomeComponent /> from being created inside <App /> They should be completely separated. Secondly, pass the genId function as a prop, and add it to useEffect dependency list, since you need it there.
This would be a great start since now the code is semantically and by the rules correct.
const SomeComponent = ({ genId }) => {
const [ componentId, setComponentId ] = React.useState(null);
React.useEffect(() => {
let generatedId = genId();
setComponentId(generatedId);
console.log(`generated '${generatedId}'`)
}, [genId]);
return <div>nothing works</div>
}
const App = () => {
const [ idCounter, setIdCounter ] = React.useState(0);
const genId = () => {
setIdCounter( id => id + 1 );
return `ID-${idCounter}`;
}
return <SomeComponent genId={genId} />
};
A: I wont answer this but just make the point having sub-components have some disadvantages. You sub-componeentn is almost imposible to unit test. Maybe you can move it to top level componennt and accept generatedId as a prop
const SomeComponent = ({generatedId}) => {
const [ componentId, setComponentId ] = React.useState(null);
React.useEffect(() => {
setComponentId( id => generatedId );
console.log(`generated '${generatedId}'`)
}, []);
return <div>nothing works</div>
}
const App = () => {
const [ idCounter, setIdCounter ] = React.useState(0);
const genId = () => {
setIdCounter( id => id + 1 );
return `ID-${idCounter}`;
}
return <SomeComponent generatedId={genId()}/>
}; | unknown | |
d12214 | train | Image Position (Patient) (0020,0032) specifies the origin of the image with respect to the patient-based coordinate system and patient based coordinate system is a right handed system. All three orthogonal planes should share the same Frame of Reference UID (0020,0052) to be spatially related to each other.
A: Yes, the image position (0020,0032) coordinates are absolute coordinates. They are relative to an origin point called the "frame of reference". It doesn't matter where the frame of reference is, but for CT/MRI scanners you can think of it as a fixed point for that particular scanner, relative to the scanner table (the table moves the patient through the scanner, so the frame of reference has to move too - otherwise the z-coodinates wouldn't change!)
What's important when comparing two images is not where the frame of reference is, but whether the same frame of reference is being used. If they are from the same scanner then they probably will be, but the way to check is whether the Frame of Reference UID (0020,0052) is the same.
A few things to note: if you have a stack of 2D slices then the Image Position tag contains the coordinates of the CENTRE of the first voxel of the 2D SLICE (not the whole stack of slices). So it will be different for each slice.
Even if two orthogonal planes line up at an edge, the Image Position coordinates won't necessarily be the same because the voxel dimensions could be different, so the centre of the voxel on one plane isn't necessarily the same as the centre of the voxel on another plane.
Also, it's worth emphasising that the coordinates are relative in some way to the scanner, not to the patient. When your planes are all reconstructed from the same data then everything is consistent. But if two scans were taken at different times then the coordinates of patient features will not necessarily match up as the patient may have moved.
A: Yes, Image position is the absolute values of x, y, and z in the real-world coordinate system.
In MRI we have three different coordinate systems.
1. Real-world coordinate system
2. logical coordinate system
3. anatomical coordinate system.
sometimes they are referred with other names. There are heaps of names on the internet, but conceptually there are three of them.
To uniquely represent the status of the slice in the real world coordinate system we need to pinpoint its position and orientation.
The absolute x, y, and z of the first voxel that is transmitted (the one at the upper left corner of the slice) are considered as the image position. that's straightforward. But that is not enough. what if the slice is rotated?
So we have to determine the orientation as well.
To do that, we consider the first row and column of the image and calculate the cosine of their angles with respect to the main axes of the coordinate system as the image orientation.
Knowing these conventions, by looking at the image position (0020, 0032) and image orientation (0020, 0037) we can precisely pinpoint the slice in the real-world coordinate system. | unknown | |
d12215 | train | use the start.*?end in the re. The question mark means "as few as possible".
A: >>> s = "startabcsdendsffstartsdfsdfendsstartdfsfend."
>>> import re
>>> p = re.compile('start(.*?)end')
>>> p.findall(s)
['abcsd', 'sdfsdf', 'dfsf'] | unknown | |
d12216 | train | Windows Communication Foundation (WCF) was first introduced to the .NET Framework as part of .NET 3.0. It's not available with .NET 2.0.
If the WCF service exposes a SOAP endpoint then you may be able to use it through the Web Service Extensions (WSE) that were published for old versions of Visual Studio. See here: http://www.microsoft.com/download/en/details.aspx?id=10854 for details.
A: If you want to use a service written in .Net 4 with a .Net 2.0 project, you should be able to use basic http binding. That should allow it to interop with a client that knows nothing about WCF. It's similar to using an old school .asmx web service. | unknown | |
d12217 | train | Sample code below
Main trick is unpivot, then using custom column and index to add the current, next, and next+1 row if they are the same Part Number
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Part Number", type text}}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type" , {"Part Number"}, "Attribute", "Value"),
#"Added Index" = Table.AddIndexColumn(#"Unpivoted Other Columns", "Index", 0, 1),
#"Added Custom" = Table.AddColumn(#"Added Index" ,"Sum",(i)=>
List.Sum(Table.SelectRows(#"Added Index" , each [Part Number]=i[Part Number] and [Index]=i[Index]) [Value])+
List.Sum(Table.SelectRows(#"Added Index" , each [Part Number]=i[Part Number] and [Index]=i[Index]+1) [Value])+
List.Sum(Table.SelectRows(#"Added Index" , each [Part Number]=i[Part Number] and [Index]=i[Index]+2) [Value])
, type number),
#"Grouped Rows" = Table.Group(#"Added Custom", {"Part Number"}, {{"Max", each List.Max([Sum]), type number}}),
// Merge the max into the original table
#"Merged Queries" = Table.NestedJoin(#"Changed Type",{"Part Number"}, #"Grouped Rows",{"Part Number"},"Table1",JoinKind.LeftOuter),
#"Expanded Table1" = Table.ExpandTableColumn(#"Merged Queries", "Table1", {"Max"}, {"Max"})
in #"Expanded Table1"
A: Slightly different way:
let
Source = Excel.CurrentWorkbook(){[Name="Table"]}[Content],
i = {"i"}, k = {"Part Number"},
base = Table.UnpivotOtherColumns(Source, k, "Col", "Val"),
f = (n)=>let x = Table.Group(base, k, {"t", each Table.AddIndexColumn(_, "i", n)})
in Table.Combine(x[t]),
a = f(0),
b = f(1),
c = f(2),
join = Table.NestedJoin(Table.NestedJoin(a,i&k,b,i&k,"a"),i&k,c,i&k,"b"),
add = Table.AddColumn(join, "sum", each List.Sum({[Val],[a][Val]{0}?,[b][Val]{0}?})),
group = Table.Group(add, k, {"max", each List.Max([sum])}),
final = Table.Join(Source, k, group, k)
in
final | unknown | |
d12218 | train | If the Path variable in your code sample is user/uid/info, then the rules don't allow access to that location. The rules only allow per-user access to posts/uid. The path in your rules needs to match the path in your code in order for access to be allowed. | unknown | |
d12219 | train | span is not a block element.
padding will not work for inline elements. But margin will work.
*
*either you can use margin: 20px 18px; or
*add display:block; or display:inline-block; to the span.
padding will take effect once you make it a block element.
A: Unlike div, p 1 which are Block Level elements which can take up padding or margin on all sides,span2 cannot as it's an Inline element which takes up padding or margin horizontally only.
From the specification :
Use div instead of span...below code will work
.lead-table .table-head-1 {
background-color: #053449;
text-transform: uppercase;
color: #ffffff;
font-size: 12px;
}
.lead-table .table-head-1 .col-txt{
padding: 20px 18px;
}
<div class="lead-table">
<div class="row table-head-1">
<div class="col-md-9">
<div class='col-txt'><strong>My Leads</strong></div>
</div>
</div>
</div>
A: Just replace that both css with following, it may help you :-
.lead-table .table-head-1 {
background-color: #053449;
text-transform: uppercase;
color: #ffffff;
font-size: 12px;
padding: 20px 18px;
}
A: Your html needs to be wrapped in a "container" class division tag with bootstrap.
HTML:
<div class="container">
<div class="lead-table">
<div class="row table-head-1">
<div class="col-md-9">
<span><strong>My Leads</strong></span>
</div>
</div>
</div>
</div>
Also, your CSS can be reduced for what you have currently as shown below.
CSS:
/* CSS used here will be applied after bootstrap.css */
.lead-table{
background-color: #053449;
text-transform: uppercase;
color: #ffffff;
font-size: 12px;
}
.table-head-1{
padding: 20px 18px;
}
A: By default a span is an inline element. You cannot add padding top or bottom to it unless you add display:block.
.lead-table .table-head-1 span {
padding: 20px 18px;
display:block;
}
Working code example: http://www.bootply.com/kSh1hNCkTb# | unknown | |
d12220 | train | I'm not sure how much this will help, but I have an example here using scala with the ical4j library to read a shared/public google calendar:
http://github.com/kevinwright/lsug-website/tree/master/src/main/scala/org/lsug/ical4scala/ | unknown | |
d12221 | train | The TStringList::Strings[] property getter DOES NOT return a reference to a String object, like you are expecting. It returns a String object by value instead, which means a copy is returned as a temporary object.
Strings[0][1] = ... has no effect because you are modifying that temporary object and not assigning it anywhere afterwards, so it just goes out of scope immediately.
That is why you need to save that temporary object to a local variable first, and then assign that variable back to the Strings[] property after modifying the variable's data. | unknown | |
d12222 | train | var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<CatalogProducts>" +
"<CatalogProduct Name=\"MyName1\" Version=\"1.1.0\"/>" +
"<CatalogProduct Name=\"MyName2\" Version=\"1.1.0\"/>" +
"</CatalogProducts>";
var document = XDocument.Parse(xml);
IEnumerable<CatalogProduct> catalogProducts =
from c in productsXml.Descendants("CatalogProduct")
select new CatalogProduct
{
Name = c.Attribute("Name").Value,
Version = c.Attribute("Version").Value
};
A: Just for your information, here's an example how to really serialize and deserialize an object:
private CatalogProduct Load()
{
var serializer = new XmlSerializer(typeof(CatalogProduct));
using (var xmlReader = new XmlTextReader("CatalogProduct.xml"))
{
if (serializer.CanDeserialize(xmlReader))
{
return serializer.Deserialize(xmlReader) as CatalogProduct;
}
}
}
private void Save(CatalogProduct cp)
{
using (var fileStream = new FileStream("CatalogProduct.xml", FileMode.Create))
{
var serializer = new XmlSerializer(typeof(CatalogProduct));
serializer.Serialize(fileStream, cp);
}
}
A: The canonical method would be to use the xsd.exe tool twice. First, to create a schema from your example XML as so:
xsd.exe file.xml will generate file.xsd.
Then:
xsd.exe /c file.xsd will generate file.cs.
File.cs will be the object(s) you can deserialize your XML from using any one of the techniques that you can easily find here, e.g. this.
A: Without "CatalogProduct" object i think it's very difficult, maybe with the dynamic type of .net 4.0 it's possible, but i'm not sure.
The only way i know, is to utilize the XmlSerializer class with Deserialize method, but you need the object CatalogProduct.
I hope the following link is useful:
Link
A: Assuming your CatalogProduct object looks something like this:
public class CatalogProduct {
public string Name;
public string Version;
}
I think Linq to Xml will be the simplest and fastest way for you
var cps1 = new[] { new CatalogProduct { Name = "Name 1", Version = "Version 1" },
new CatalogProduct { Name = "Name 2", Version = "Version 2" } };
var xml = new XElement("CatalogProducts",
from c in cps1
select new XElement("CatalogProduct",
new XAttribute("Name", c.Name),
new XAttribute("Version", c.Version)));
// Use the following to deserialize you objects
var cps2 = xml.Elements("CatalogProduct").Select(x =>
new CatalogProduct {
Name = (string)x.Attribute("Name"),
Version = (string)x.Attribute("Version") }).ToArray();
Please note that .NET offers true object graph serialization which I have not shown | unknown | |
d12223 | train | Just get the height of the menu bar and subtract it from the offset like for example if the menu is 60px
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#myDiv").offset().top-60
}, 2000);
}); | unknown | |
d12224 | train | Assuming that you have a good reason for doing this in XSLT (like, it's part of a larger task, or XSLT is your only programming language), you should take a look at the EXPath file module. The file:copy() function copies a directory.
http://expath.org/spec/file#fn.copy
It's available in Saxon-PE 9.6 or later/higher.
A: To expand on Xephon's answer: you could generate an Ant script that then does the copying. If you have Oxygen then you also have the D4P net.sourceforge.dita4publishers.common.xslt plugin, which has code for generating an Ant copy script--it's used by the EPUB transform to manage the copying of resources from the source area to the EPUB temp directory from which the EPUB zip is created.
In that same plugin is the relpath_util.xsl module, which provides general XSLT functions for working with URLs and file paths in a Java-like way.
Mike's solution is obviously the easiest but is dependent on extensions.
A: thank you for describing your toolset. If possible, you should simply do this using the Ant Copy Task. The DITA Open Toolkit uses Ant and Oxygen XML ships Ant as well. | unknown | |
d12225 | train | What is value here? UIPicker's value? or it's some other control in your view?
Check out Highlighted state for UIButton in Interface Builder... hope this helps! | unknown | |
d12226 | train | add the below method which generate the previous url in your controller and override the default one add following methods in your controller
in your controller where you have defined $this->validate call define below method and use Request
use Illuminate\Http\Request; // add at the top
protected function getRedirectUrl() {
return route('register');
}
protected function validator(array $data) {
return $this->validate(request(), [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|min:6|confirmed', ]);
}
public function register(Request $request)
{
$this->validator($request->all());
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
} | unknown | |
d12227 | train | Why not try printing out System.getProperty("user.dir"); and finding out what the application thinks?
user.dir User's current working directory
use the following to get the PARENT of where you .jar is loading from, which is what it sounds like you want
import java.io.*;
public class Main
{
public static void main(final String[] args) throws IOException
{
final File file = new File(".");
System.out.println("file = " + file.getAbsoluteFile().getParent());
}
}
The output when I run it from the command line or double clicking from Windows Explorer is:
file = c:\Users\Jarrod Roberson\Projects\SwingJarFinder
A: Looks like a duplicate of:
How to get the path of a running JAR file?
If your jar file is in your file system start here to get the current path:
ClassLoader.getSystemClassLoader().getResource(".").getPath(); | unknown | |
d12228 | train | You can use $reduce to convert an array of strings into single string:
db.collection.aggregate([
{
$addFields: {
notes: {
$reduce: {
input: "$notes.term",
initialValue: "",
in: {
$cond: [ { "$eq": [ "$$value", "" ] }, "$$this", { $concat: [ "$$value", "\n", "$$this" ] } ]
}
}
}
}
}
])
Mongo Playground | unknown | |
d12229 | train | TableFixHeaders project on github has an implementation with both Adapter an Recycling of views, plus handles scrolling wery nicely. And is quite easy to modify to suit your needs.
This is not so uncommon request, so it has been done numerous times. I am sure you can find other implementations if this one is not right for you.
A: I saw a similar question on SO a few months ago, and I was interested to see if I could develop a solution.
My concept was to start with a ListView for vertical scrolling and view recycling. Each list item is a HorizontalScrollView to show a table row with many columns. The trick here is to listen to each HorizontalScrollView for swipe events and then scroll every HorizontalScrollView in sync with the view being swiped.
I have a proof-of-concept project on Github here:
klarson2/android-table-test
Downsides: The project was set up for Eclipse, so you can't open it directly with Android Studio. There is still a small bug with event handling that I haven't got around to fixing. Another limitation is that each cell view in the horizontal LinearLayout must be a fixed size so that the columns will line up correctly.
However, the example uses a 4MB .csv file with 50 columns and over 10,000 rows for a data source proving that it is possible to display an enormous table in an Android app with responsive two-way scrolling. | unknown | |
d12230 | train | ImageSource.Width and ImageSource.Height
A: You actually kind of answered your own question. There are two dependency properties that you can use: ActualWidth and ActualHeight.
This will give you the size that the picture is using on the screen, not what is currently set, which is what Width and Height give you.
Also, these dependency properties are useable by any FrameworkElement I believe.
FrameworkElement.ActualWidth
FrameworkElement.ActualHeight
A: You can set the Stretch property to "None" to have an Image element use the actual source image size:
<Image Source="/Resources/MyImage.png" Stretch="None"/> | unknown | |
d12231 | train | If you use the widget like in the notebook of blois, you can use the following code to call the value:
fruit_picker.value
This will return the value of your chosen fruit.
The code in total will look like this:
import ipywidgets as widgets
fruit_list = ['pomegranate', 'watermelon', 'lychee']
fruit_picker = widgets.Dropdown(options=fruit_list, value='watermelon')
fruit_picker
fruit_picker.value
A: Your original code almost has the solution.
If you look carefully you will find it in the documentation.
Instead of
fruit_list = ['apples', 'bananas', 'mangoes']
fruit_selected = 'apples' #@params fruit_list {input: string}
Use
fruit_selected = 'new' #@param ['apples', 'bananas', 'mangoes'] {allow-input: true}
And you will be able to choose from the list OR enter new elements.
If you want to input the name of an existing variable, you could do this
fruits=['apples', 'bananas', 'mangoes']
other={"a": 1, "b": 2}
fruit_selected = 'b' #@param ['apples', 'bananas', 'mangoes'] {allow-input: true}
#---- Find it in a dictionary
if fruit_selected not in fruits:
if fruit_selected in other:
print(f'{other[fruit_selected]}')
else:
print("Fruit selected NOT in other")
#---- Find it by name
a="x2"
if fruit_selected in globals():
print(f'Got {fruit_selected}')
But for this kind of interactions maybe ipywidgets is a better tool. | unknown | |
d12232 | train | Unless I've misread that error stack it looks to me like that error is coming from HttpLoggingInterceptor trying to allocate a 102Mb buffer to quite literally log the whole of your Image data.
If so I presume you've set the logging level to BODY, in which case setting it to any other level would fix the problem.
A: Add below entities in your manifest file android:hardwareAccelerated="false" , android:largeHeap="true" it will work for some environment's.
<application
android:allowBackup="true"
android:hardwareAccelerated="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
See the StackOverflow answer for details...
A: You can use compress method before sending images to server
public Bitmap compressInputImage(Uri inputImageData){
try {
bitmapInputImage=MediaStore.Images.Media.getBitmap(context.getContentResolver(), inputImageData);
if (bitmapInputImage.getWidth() > 2048 && bitmapInputImage.getHeight() > 2048)
{
dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1024, 1280, true); }
else if (bitmapInputImage.getWidth() > 2048 && bitmapInputImage.getHeight() < 2048)
{
dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1920, 1200, true); }
else if (bitmapInputImage.getWidth() < 2048 && bitmapInputImage.getHeight() > 2048)
{
dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1024, 1280, true); }
else if (bitmapInputImage.getWidth() < 2048 && bitmapInputImage.getHeight() < 2048)
{
dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, bitmapInputImage.getWidth(), bitmapInputImage.getHeight(), true); }
} catch (Exception e)
{
dpBitmap = bitmapInputImage;
}
return dpBitmap;
}
It can minimise the chances of OutOfMemory Exception. Besides this you can handle exception
by adding try - catch . | unknown | |
d12233 | train | You need an index on :Doss(Num) or this won't be able to finish in a reasonable amount of time.
The key is that most Cypher operations execute per row. So the second MATCH is being executed per each result from the first MATCH.
If you don't have an index, then this will likely be doing a NodeByLabelScan for a, and then another NodeByLabelScan per a node and filtering to find matches for b.
Basically, you will be performing a total of 6M + 1 label scans, and filtering across 6M * 6M rows, and that's just not a good idea.
If you add the index, then you will be doing only one NodeByLabelScan, and then 6M index seeks to find, per row, all b nodes with the same num as a.
You should be able to run an EXPLAIN on the query to confirm how the planner wants to execute this. | unknown | |
d12234 | train | Have you tried it with an external manifest and ensured that works? If an external manifest doesn't work, then the manifest information isn't correct.
Once you have a valid external manifest, you might try the Manifest Tool (MT.EXE) from the .Net SDK. It works well with true EXE files. As Terry noted though, the PB generated executable contains additional information that tools that manipulate the EXE need to respect or they will break it.
http://blogs.msdn.com/patricka/archive/2009/12/09/answers-to-several-application-manifest-mysteries-and-questions.aspx
A: This is more a redirection than an answer. One thing you need to be aware of is that PowerBuilder produces executables that do not follow standards for Windows executable files. Essentially they are a bootstrap routine to load the PowerBuilder virtual machine, plus a collection of class definitions (objects). The cases you've brought up are not the first I've heard of where utilities meant to modify executables don't work on PowerBuilder executables.
As for a positive contribution on what other directions to follow, I don't really know enough to give qualified advice. If it were me, I'd try to register the COM object if ConnectToNewObject() fails, but I've got no idea if that possible or if that route is a dead end.
Good luck,
Terry. | unknown | |
d12235 | train | There are a lot of things wrong with what you have. Here is just a simple example that should work for you.
practice.php
<?php
if(isset($_GET['f']))
echo strip_tags($_GET['f']);
?>
index.php
<?php function myFirst() {
echo 'The First ran successfully.';
} ?><html>
<head>
<title>Writing PHP Function</title>
<!-- You need to add the jQuery library -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// You should activate it on an event like click (unless you want it to autoload)
$("#content").click(function() {
$.ajax({
// Your url is funky, and cannot be terminated with a semicolon
// but rather a comma
url : 'localhost/practice.php?f=<?php myFirst(); ?>',
type: "GET",
// You can do an alert, but I just made it populate a div instead
success: function(result) {
$("#place-to-load").html(result);
}
});
});
</script>
</head>
<body>
<!-- Your php function will not work as you intend because one -->
<!-- is a server-side function and the other is a client-side script -->
<!-- The functions are not interchangeable. That being said, you can -->
<!-- populate a javascript with a php variable but it would need to be -->
<!-- echoed like <?php myFirst(); ?> -->
<div id="place-to-load"></div>
<div id="content">Load</div>
</body>
</html>
A: I would try to call the functions based on the params from the URL.
Ajax part,
$.ajax({url:'localhost/practice.php?f=myFirst',type:'GET'}).done(function(response){
alert(response); // or you can write to your document
});
and PHP file
<?php
if(isset($_GET) && $_GET['f'] == 'myFirst'){
myFirst();
}else{
die('No GET params received');
}
function myFirst(){
echo 'The First ran successfully.';
}
?> | unknown | |
d12236 | train | You should be safer with something like this:
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: "GET",
url: "ajax_files/manage_friend_requests.php"
}).done(function(result) {
var $friends_requests = $('#all_friends_requests');
if ($friends_requests.length > 0) {
console.log('Received: '+result);
$friends_requests.html(result);
console.log('UPDATED friends requests');
} else {
console.log('CANNOT access friends requests container');
}
});
}, 9000);
});
Depending on what the console will display, you will probably put the issue in evidence. | unknown | |
d12237 | train | Below code works fine , I have changed the following things
a) axis should be ax b) DF column names were incorrect c) for any one to try this example would also need to install lxml library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from nsepy import get_history
import datetime as dt
start = dt.datetime(2015, 1, 1)
end = dt.datetime.today()
infy = get_history(symbol='INFY', start = start, end = end)
infy.index = pd.to_datetime(infy.index)
hdfc = get_history(symbol='HDFC', start = start, end = end)
hdfc.index = pd.to_datetime(hdfc.index)
reliance = get_history(symbol='RELIANCE', start = start, end = end)
reliance.index = pd.to_datetime(reliance.index)
wipro = get_history(symbol='WIPRO', start = start, end = end)
wipro.index = pd.to_datetime(wipro.index)
open_prices = pd.concat([infy['Open'], hdfc['Open'],reliance['Open'],
wipro['Open']], axis = 1)
open_prices.columns = ['Infy', 'Hdfc', 'Reliance', 'Wipro']
print(open_prices.columns)
ax=[]
f, ax = plt.subplots(2, 2, sharey=True)
ax[0,0].plot(open_prices.index.year,open_prices.Infy)
ax[1,0].plot(open_prices.index.year,open_prices.Hdfc)
ax[0,1].plot(open_prices.index.year,open_prices.Reliance)
ax[1,1].plot(open_prices.index.year,open_prices.Wipro)
plt.show() | unknown | |
d12238 | train | db.products.aggregate([
{
$lookup: {
from: "orders",
localField: "orderId",
foreignField: "orderId",
as: "docs"
}
},
{ $match: { docs: [] },
{ $limit: 10 }
]).pretty() | unknown | |
d12239 | train | In traced = torch.trace(model.forward)(xample_inputs=(x, hidden)) you are passing a method i.e model.forward you should be using something like this
traced = torch.trace(model.forward(x)) if your model is already had an instance with parameters | unknown | |
d12240 | train | It's overkill for your needs but in general to print the yth ,-separated subfield of the xth :-separated field of any input would be:
$ awk -F':' -v s=',' -v x=4 -v y=1 '{split($x,a,s); print a[y]}' file
red
A: Or
awk -F '[:,]' '{print $4}' test
output
red
A: It sounds like you are trying to extract the first field of the fourth field. Top level fields are delimited by ":" and the nested field is delimited by ",".
Combining two cut processes achieves this easily:
<input.txt cut -d: -f4 | cut -d, -f1
If you want all fields until the first comma, extract the first comma-delimited field without first cutting on colon:
cut -d, -f1 input.txt
A: if you want a purely regex approach :
echo 'jon:TX:34:red,green,yellow,black,orange' |
mawk NF=NF FS='.+:|,.+' OFS=
red
if you only want "red" without the trailing newline ("\n"), use RS/ORS instead of FS/OFS — (the % is the command prompt, i.e. no trailing \n):
mawk2 8 RS='.+:|,.+' ORS=
red%
if u wanna hard-code in the $4 :
gawk '$_= $4' FS=,\|: # gawk or nawk
mawk '$!NF=$4' FS=,\|: # any mawk
red
and if you only want the non-numeric text :
nawk NF=NF FS='[!-<]+' OFS='\f\b'
jon
TX
red
green
yellow
black
orange
A: If you have
jon:TX:34:red,green,yellow,black,orange
and desired output is
jon:TX:34:red
then just treat input as comma-separated and get 1st field, which might be expressed in GNU AWK as
echo "jon:TX:34:red,green,yellow,black,orange" | awk 'BEGIN{FS=","}{print $1}'
gives output
jon:TX:34:red
Explanation: I inform GNU AWK that , character is field separator (FS), for each line I print 1st column ($1)
(tested in GNU Awk 5.0.1) | unknown | |
d12241 | train | It's not a matter of "how long" but "at what point". There's enough of a distinction that it's important to study it. :-)
Usually array controllers are automatically updated (re-fetch their contents in this case) on the next run-loop but technically "at some future run loop". If you want them to update immediately after inserting something, send your MOC a -processPendingChanges then ask the array controller to -fetch:.
Among the first things you read in the Core Data documentation is that it's an advanced Cocoa topic whose prerequisite knowledge includes Key Value Binding and Key Value Observing. The missing bit of knowledge that led you to this question is found in understanding of KVC/KVO (and the Cocoa Bindings layer).
A: Just found a fix for this. I use the setSelectedObjects: method of the NSArrayController to select the object. Don't know why I didn't used this method anyway! | unknown | |
d12242 | train | =IF(XLOOKUP(N7,'EDL Filter'!R2:R660,'EDL Filter'!AA2:AA660)="YES","Port Specific",XLOOKUP(N7,'EDL Filter'!R2:R660,'EDL Filter'!AB2:AB660) )
I've tried splitting it up as I have with other Xlookup statements below:
ActiveCell = "=IF(XLookUp(N" & SafetyRow2 & ",'EDL Filter'!R2:R660,'EDL Filter'!AA2:AA660)=""Yes"",""Port Specific"", Xlookup(N" & SafetyRow2 & ",'EDL Filter'!AB2:AB660))"
However, I keep getting Run-time Error '1004': Application-defined or object-defined error.
The variables have been defined and used earlier in my code without issue, but I am still new to VBA so I might be missing something obvious. | unknown | |
d12243 | train | It seems that you can't do it from vs code, it has to be done in android studio...
I have searched for an answer as well as I was stuck with this and ended up doing it in android studio.
If someone has a solution please share.
A: Flutter has its own default icon for every app in its Android and Ios folder so there are few steps that I would like to show to change the app icon.
Head over to https://appicon.co/ and generate your own icon using icon image (the zip file contains two main folders android and Assets.xcassets)
For android: Go inside android\app\src\main\res in your flutter app and there paste the android folder content.
For IOS: Go inside ios\Runner in your flutter app and there paste the Assets.xcassets content
Restart your emulator or rebuild your application | unknown | |
d12244 | train | After some try and error I found the answer and it's pretty obvious now. The thing is, that I was searching for data in the wrong place. The vmobject that I defined like this
vm = new Vue({
template: '<div><account></account></div>',
components: { account }
}).$mount()
Is a Vue instance that only have a component and a template option, the data I was searching for was in the child of that instance. So, I have to use this way to access data
const accountInstance = vm.$children[0]
This works, because to test I defined a single child easy to identify. I also tried before using const accountInstance = new account() but that throws an error because vue components ar not constructors | unknown | |
d12245 | train | Escape the apostrophe with a backslash;
select notes from table1 where notes like '%\'%';
And to update, use REPLACE()
UPDATE table1 SET notes = REPLACE(notes, '\'', '');
A: Did you try:
select notes from table1 where notes like "'%"; | unknown | |
d12246 | train | Add these 2 keys in your Info.plist: LSSupportsOpeningDocumentsInPlace and UIFileSharingEnabled. And set YES as the value for both.
Now you will be able use the Files app to see any file saved by your app in Documents Directory.
A:
Swift 5.0 and iOS13
let documentController = UIDocumentPickerViewController(url: exportToURL, in: .exportToService)
self.present(documentController, animated: true, completion: nil)
exportToURL represent application local URL whichever file want to save into iPhone Files app. | unknown | |
d12247 | train | You can use the following general tree traversal function, taken from How to flatten tree via LINQ?
public static class TreeHelper
{
public static IEnumerable<T> Expand<T>(this IEnumerable<T> source,
Func<T, IEnumerable<T>> elementSelector)
{
var stack = new Stack<IEnumerator<T>>();
var e = source.GetEnumerator();
try
{
while (true)
{
while (e.MoveNext())
{
var item = e.Current;
yield return item;
var elements = elementSelector(item);
if (elements == null) continue;
stack.Push(e);
e = elements.GetEnumerator();
}
if (stack.Count == 0) break;
e.Dispose();
e = stack.Pop();
}
}
finally
{
e.Dispose();
while (stack.Count != 0) stack.Pop().Dispose();
}
}
}
With that function and LINQ, getting all the menu items is simple
var allMenuItems = menuStrip1.Items.OfType<ToolStripMenuItem>()
.Expand(item => item.DropDownItems.OfType<ToolStripMenuItem>());
and producing a text like in your example
textBox1.Text = string.Join(Environment.NewLine, allMenuItems
.Select(item => item.OwnerItem.Text + @"==>" + item.Text));
A: Use recursion .
Write a method that calls itself (but checks for termination as well so it does not call itself when not needed to go deeper).
Here is some code:
static string GetText2(ToolStripMenuItem c)
{
string s = c.OwnerItem.Text + @"==>" + c.Text + Environment.NewLine;
foreach (ToolStripMenuItem c2 in c.DropDownItems)
{
s += GetText2(c2);
}
return s;
} | unknown | |
d12248 | train | In principle, any linux distro will work with the cluster, and also in principle, they can all be different distros. In practice, it'll be a enormously easier with everything the same, and if you get a distribution which already has a lot of your tools set up for you, it'll go much more quickly.
To get started, something like the Bootable Cluster CD should be fairly easy -- I've not used it myself yet, but know some who have. It'll let you boot up a small cluster without overwriting anything on the host computer, which lets you get started very easily. Other distributions of software for clusters include Rocks and Oscar. A technical discussion on building a cluster can be found here.
A: I also liked PelicanHPC when I used it a few years back. I was more successful getting it to work that with Rocks, but it is much less popular.
http://pareto.uab.es/mcreel/PelicanHPC/
Just to get a cluster up and running is actually not very difficult for the situation you're describing. Getting everything installed and configured just how you want it though can be quite challenging. Good luck! | unknown | |
d12249 | train | Regular expressions are not the right choice, when it comes to parsing text.
Parsing for example includes the functionality of counting backslashes, quotes, etc.
Use a parser library (like ANTLR), or live with a semi-robust regular expression solution.
A: if you want to get those strings before and after "=>" you can use this:
String s = "'ab'cd' => 'e\\fg\\'h'";
Pattern p = Pattern.compile("'(.+)'\\s\\=>\\s'(.+)'");
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
}
You will get "ab'cd" and "e\fg\'h" in this concrete case. | unknown | |
d12250 | train | I've fixed this and it had nothing to do with the hosting company.
I published a new version of the site, but in the publish profile I told it to delete all files which deleted the .htaccess file which contained the version of PHP in.
Unfortunately, I needed version 5.4 or above to run my code but since the file was removed it dropped down to 5.2 of PHP.
So I've uploaded a new .htaccess file with the correct version in and everything is working.
Hopefully this may help someone if they're as daft as I am. | unknown | |
d12251 | train | Instead of using an event, I used an observable in one of the fields. The exact solution to the problem I proposed is here.
And I solved it using what I found here (they are basically the same thing, but I included mine for completion). | unknown | |
d12252 | train | Your pattern is working. It is checked onsubmit, not onkeydown nor onkeypress.
However, the pattern is nondeterministic. It should be writen in such a way that every character is matched by at most one subpattern. In this case, deterministic version is: [a-z](([a-z]{1,2})|([\s,]+[a-z])*)
Also maxlength="3" will not work with input a,b,c. | unknown | |
d12253 | train | For me, the project groups appear under:
C:\Users\aedison\AppData\Roaming\NetBeans\8.1\config\Preferences\org\netbeans
\modules\projectui
Replace aedison with your user name and replace 8.1 with your Netbeans version.
Hopefully that gives you a pointer in the right direction.
I would caution you against manually messing with these settings, though.
NetBeans is very very touchy. (Take backups first!)
A: I may be incorrect, but have you tried looking in your NetBeans userdir?
According to this page on their site NetBeans stores some files in ~/.netbeans and ~/.cache/netbeans/7.2/
Maybe try searching there for a database or perhaps XML file describing project locations | unknown | |
d12254 | train | As Glen said here there is no method to directly restore trash mails through Graph API. Please raise a feature request for this in the Microsoft Graph Feedback Forum so that the product team could implement it in the future. | unknown | |
d12255 | train | Method Two is the way Autodesk recommends in the developer's documentation (you can read this section).
In Method One, you use the ObjectId.GetObject() method to open the BlockTable and the model space 'BlockTableRecord'. This method uses the top transaction to open object which means that there's an active transaction you should use to add the newly created entity. You can get it with Database.TransactionManager.TopTransaction. If you don't want to use a transaction at all, you have to use the "for advanced use only" ObjectId.Open() method.
A Method Three should be using some extension methods to be called from within a transaction. Here's a simplified (non error checking) extract of the ones I use.
static class ExtensionMethods
{
public static T GetObject<T>(
this ObjectId id,
OpenMode mode = OpenMode.ForRead,
bool openErased = false,
bool forceOpenOnLockedLayer = false)
where T : DBObject
{
return (T)id.GetObject(mode, openErased, forceOpenOnLockedLayer);
}
public static BlockTableRecord GetModelSpace(this Database db, OpenMode mode = OpenMode.ForRead)
{
return SymbolUtilityServices.GetBlockModelSpaceId(db).GetObject<BlockTableRecord>(mode);
}
public static ObjectId Add (this BlockTableRecord owner, Entity entity)
{
var tr = owner.Database.TransactionManager.TopTransaction;
var id = owner.AppendEntity(entity);
tr.AddNewlyCreatedDBObject(entity, true);
return id;
}
}
Using example:
using (var tr = db.TransactionManager.StartTransaction())
{
var line = new Line(startPt, endPt) { Layer = layerName };
db.GetModelSpace(OpenMode.ForWrite).Add(line);
tr.Commit();
} | unknown | |
d12256 | train | This schema does not allow arbitrary values in the "level" attribute. There is no way to extend the set of valid values. | unknown | |
d12257 | train | Try this:
app.post('/api/character', function(req, res) {
console.log(JSON.stringify(req.body));
res.status(200).send('whatever you want to send back to angular side');
});
app.get('/api/character/:id', function(req, res) {
console.log(req.params.id);
res.status(200).send('whatever you want to send back to angular side'');
}); | unknown | |
d12258 | train | This code seemed to work.
// Declare the futures list
val arrayListNode = ClassHelper.make(ArrayList::class.java)
val variable = "myVariable"
val variableDeclaration = GeneralUtils.varX(variable, arrayListNode)
val asListExpression = GeneralUtils.ctorX(arrayListNode)
// Look for the arraylist constructor in the node
val arrayNodeConstructorMethod = arrayListNode.getDeclaredConstructor(arrayOf())
asListExpression.setNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, arrayNodeConstructorMethod)
val variableStmt = GeneralUtils.declS(variableDeclaration, asListExpression)
codeBlock.addStatement(variableStmt)
//
// Set the codeBlock back to the closure
closure.code = codeBlock | unknown | |
d12259 | train | Bots are now easily detected by Instagram. Your account could be banned for 3 days, 7 days, 30 days or definitively if Instagram detects too many attempts
Usually bots simulate a browser via Sellenium and then create a "browse like a human" bot to create likes, follow, unfollow, etc. | unknown | |
d12260 | train | You're trying to use await within a constructor. You can't do that - constructors are always synchronous.
You can only use await within a method or anonymous function with the async modifier; you can't apply that modifier to constructors.
One approach to fixing this would be to create a static async method to create an instance - that would do all the relevant awaiting, and then pass the results to a simple synchronous constructor. Your callers would then need to handle this appropriately, of course.
public static async Task<MyModel> CreateInstance()
{
string googleSearchText;
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(...))
{
googleSearchText = await response.Content.ReadAsStringAsync();
}
}
// Synchronous constructor to do the rest...
return new MyModel(googleSearchText);
}
A: You can't use await in the constructor of a class.
An async method returns a Task object which can be executed async. A constructor does not have a return type and thus can't return a Task object, and thus can't be awaited.
A simple fix for this problem is create a Init function:
public MyModel()
{
}
public async Task Init()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://api.vkontakte.ru/method/video.get?uid=219171498&access_token=d61b93dfded2a37dfcfa63779efdb149653292636cac442e53dae9ba6a049a75637143e318cc79e826149");
string googleSearchText = await response.Content.ReadAsStringAsync();
JObject googleSearch = JObject.Parse(googleSearchText);
IList<JToken> results = googleSearch["response"].Children().Skip(1).ToList();
IList<MainPage1> searchResults = new List<MainPage1>();
foreach (JToken result in results)
{
MainPage1 searchResult = JsonConvert.DeserializeObject<MainPage1>(result.ToString());
searchResults.Add(searchResult);
}
}
Then when you create your model:
var model = new MyModel();
await model.Init(); | unknown | |
d12261 | train | Your PHP code is producing JSON in an incorrect format for the Google Visualization API. Try this instead:
<?php
$con=mysql_connect("xxxx.xxxx.xxxx.xx","Myuser","Mypass") or die("Failed to connect with database!!!!");
mysql_select_db("data", $con);
$sth = mysql_query("SELECT * FROM data");
$data = array (
'cols' => array(
array('id' => 'date', 'label' => 'Date ', 'type' => 'datetime'),
array('id' => 'temp1', 'label' => 'Temp 1', 'type' => 'number'),
array('id' => 'temp2', 'label' => 'Temp 2', 'type' => 'number')
),
'rows' => array()
);
while ($res = mysql_fetch_assoc($sth))
// array nesting is complex owing to to google charts api
array_push($data['rows'], array('c' => array(
array('v' => $res['date']),
array('v' => $res['temp1']),
array('v' => $res['temp2'])
)));
}
?>
and then in your javascript:
var bar_chart_data = new google.visualization.DataTable(<?php echo json_encode($data); ?>);
A: From the code you've originally posted - change
$task_submissions_arr[][] = $res;
to
$task_submissions_arr[] = $res;
A: Thanks for all your help in the design, I had several mistakes but the crucial mistake was that I used the wrong format for date, datetime from MySQL database, when I changed it from date / datetime to string the code was complete!
$table['cols']=array(
array('label' => 'Date', type=>'string'),
array('label' => 'Temp 1', type=>'number'),
array('label' =>'Temp 2', type=>'number'),
);
Jason result:
new google.visualization.DataTable({"cols":[{"label":"Date","type":"string"},{"label":"Temp 1","type":"number"},{"label":"Temp 2","type":"number"}],"rows":[{"c":[{"v":"2013-10-05 20:41:00"},{"v":10.75},{"v":4}]} | unknown | |
d12262 | train | SELECT c.courseID
s.studentName
FROM course AS c
JOIN asks AS a
ON a.courseID = c.courseID
JOIN student AS s
ON s.studentName = a.studentName
JOIN asks AS a2
ON a2.courseID = c.courseID
JOIN student AS s2
ON s2.studentName = a2.studentName
AND s2.seniority <= s.seniority
GROUP BY c.courseID
, c.ratio
, s.studentName
HAVING c.ratio >= COUNT(*)
ORDER BY c.courseID
, s.seniority | unknown | |
d12263 | train | When you add
LEFT JOIN hintout_thanks AS ht2 ON h.hintout_id = ht2.hintout_id
The number of rows increases, you get duplicate rows for table hc, which get counted double in COUNT(hc.comment_id).
You can replace
COUNT(hc.comment_id) <<-- counts duplicated
/*with*/
COUNT(DISTINCT(hc.comment_id)) <<-- only counts unique ids
To only count unique appearances on an id.
On values that are not unique, like co.county_name the count(distinct will not work because it will only list the distinct countries (if all your results are in the USA, the count will be 1).
Quassnoi
Has solved the whole count problem by putting the counts in a sub-select so that the extra rows caused by all those joins do not influence those counts.
A: SELECT h.*, h.permalink AS hintout_permalink, hi.hinter_name,
hi.permalink, hf.user_id AS followed_hid,
ci.city_id, ci.city_name, co.country_id, co.country_name,
ht.thank_id,
COALESCE(
(
SELECT COUNT(*)
FROM hintout_comments hci
WHERE hc.hintout_id = h.hintout_id
), 0) AS commentsCount,
COALESCE(
(
SELECT COUNT(*)
FROM hintout_comments hti
WHERE hti.hintout_id = h.hintout_id
), 0) AS thanksCount
FROM hintouts AS h
JOIN hinter_follows AS hf
ON hf.hinter_id = h.hinter_id
JOIN hinters AS hi
ON hi.hinter_id = h.hinter_id
LEFT JOIN
cities AS ci
ON ci.city_id = h.city_id
LEFT JOIN
countries as co
ON co.country_id = h.country_id
LEFT JOIN
hintout_thanks AS ht
ON ht.hintout_id = h.hintout_id
AND ht.thanker_user_id=1
WHERE hf.user_id = 1 | unknown | |
d12264 | train | Try to return document itself instead of Object in read method of CommReader.java and then check whether its coming null or not in the writer to stop it. | unknown | |
d12265 | train | That is my prefer ..you can try it
<?php
$link = "http://www.example.com/abc?";
//try with object
// $a = new stdClass();
// $a->a = "a";
// $a->b = "b";
//try with array
$a = ["a","b","c"];
header("location:{$link}param=".json_encode($a));
www.example.com/abc
<?php
$data = json_decode($_GET["param"]);
var_dump($data); | unknown | |
d12266 | train | I recommend two sites: IconArchive and Icon8.
They both have free icon sets that can help you to get you started with your designs!
Cheers
A: Depends on what kind of resources your looking for, if it's mainly icons I suggest: http://iconfinder.com
If your looking for photo resources I would try http://gettyimage.com | unknown | |
d12267 | train | Use a for loop to go from index 0 to yourArray.length - 1 and record the index of the first element with a value greater than 0.
int firstIndex = -1;
for (int i = 0; i < yourArray.length; i++) {
if (yourArray[i] > 0) {
firstIndex = i;
break;
}
}
Alternately, use a method which returns i immediately on finding the index, instead of breaking the loop. In this case, return either -1 (or some other value that can't be a valid index, but -1 is fairly common in the .NET libraries) or an exception, depending on your tastes.
A: How about this?
array.ToList().FindIndex(value => value > 0)
Alternatively, create your own FindIndex extension method for generic arrays:
public static int FindIndex<T>(this T[] array, Predicate<T> predicate) {
for (int index = 0; index < array.length; index++) {
if (predicate(array[index]))
return index;
}
return -1;
}
which would remove the need for LINQ and ToList():
array.FindIndex(value => value > 0)
A: You can use Array.FindIndex to get the index of first element of the array which is greater than 0,
var array = new int[5];
array[0] = 0;
array[1] = 0;
array[2] = 1;
array[3] = 1;
array[4] = 0;
int index = Array.FindIndex(array, x=>x > 0);
Or,you can use Array.IndexOf method of Array,
int index = Array.IndexOf(array, array.First(x=>x > 0));
A: If you want to get its value, you can use LINQ:
array.Where(x=>x>0).First
If you want its index, you can use LINQ but it'll be more complicated than a straight loop - go over all elements and see if one of them is not 0.
A: int count=0;
for(int i=0;i<numbers.Length;i++)
{
if(numbers[i]>0)
{
break;
}
count++;
}
get the value of variable count at last, that is goint to be index.
A: int result;
foreach (int i in array)
if (i > 0)
{
result = i;
break;
}
Since you only want the first, you can break as soon as you find it. | unknown | |
d12268 | train | Attr will return value only for the first item. Read the full docs about it here.
Description: Get the value of an attribute for the first element in the set of matched elements.
So you need to filter the found items with your condition (specific data attribute in your case).
For example, using .is() method
if ($('.item').is('[data-id="' + myId+ '"]')) {
// do stuff
}
A: just check the length. you can use this
if($('.notification-item[data-noti-attr="'+value.id+'"]').length ==0){
....
} | unknown | |
d12269 | train | Maybe consider using the Boost-Python library for interfacing between Python and C++. | unknown | |
d12270 | train | Please check this related issue on github, I think it has the right answer for you:
https://github.com/vuejs/vue-loader/issues/328
Specially look for mister shaun-sweet's answer. | unknown | |
d12271 | train | include courses into student instance
var dbStudents = await _dataContext.Student
.Include(i=>i.Courses)
.ToListAsync();
and fix Course class
public class Course
{
public int Id { get; set; }
public string CourseName { get; set; } = null!;
public virtual List<Student> Students { get; set; }
}
you have to repeat ef migration to database. New table will be created
public class CourseStudent
{
public int CourseId { get; set; }
public virtual Course Course { get; set; }
public int StudentId { get; set; }
public virtual Student Student { get; set; }
} | unknown | |
d12272 | train | Ok here's what I found.
I am using com.objsys.asn1j.runtime library; I need to implement the whole sequence in Java classes, and make each class extend Asn1Seq, Asn1Integer or other super classes from the library.
In each class which extends Asn1Seq (ie. all Sequence-like classes) I need to override the decode method and in the body I have to call decode again on every attribute of the class.
Quick sample (both Type1 and Type2 extend Asn1Integer):
class SeqData extends Asn1Seq {
private static final long serialVersionUID = 55L;
Type1 attribute1;
Type2 attribute2;
@Override
public int getElementCount() {
return 2;
}
@Override
public String getElementName(int arg0) {
switch (arg0) {
case 0:
return "attribute1";
case 1:
return "attribute2";
}
return "";
}
@Override
public Object getElementValue(int arg0) {
switch (arg0) {
case 0:
return attribute1;
case 1:
return attribute2;
}
return null;
}
@Override
public void decode(Asn1PerDecodeBuffer arg0) throws Asn1Exception, IOException {
attribute1 = new Type1();
attribute1.decode(arg0, 1L, 62L);
attribute2 = new Type2();
attribute2.decode(arg0, 1L, 62L);
} | unknown | |
d12273 | train | I had the same issue on El Capitan, after I messed with OpenSSL. This means your Java certificate is screwed up.
In the end, I fixed the problem by reinstalling the JDK.
You can do this by first removing the current JDK under:
/Library/Java/JavaVirtualMachines/jdkmajor.minor.macro[_update].jdk
Then run:
sudo rm -rf jdk1.X.X_XX.jdk
Install your version of JDK again, and everything should be working!
Aside
Other symptoms of this problem includes not being able to run any SSL-related 'fetch' functions. For instance, running the Android package manager will give you errors saying it couldn't fetch xml files from https servers. | unknown | |
d12274 | train | M2_HOME is set as the old maven home directory. Seems maven will pick up the MAVEN from this environment variable. | unknown | |
d12275 | train | Try this:
for dirs in $(ls -F /code | grep '/')
do
eval files=( "$(ls -1 ${dirs})" )
<ShellScript>.sh "${dirs}${files[0]}" "${dirs}${files[1]}" "${dirs%/}" func 50
done | unknown | |
d12276 | train | Ok well, this is under the assumption that you want to specify how many times you want to copy A1 and B2 down the sheet. So your loop is fairly confusing, instead of using MOD, since you know you want it every 6 spaces and you're not doing anything to the other cells, it's easier just to have the number multiplied by 6 for your indexing. This also helps you figure out the dimensions of your transfer arrays more easily since you want to specify how many times you want to copy.
It's also worth noting that you're Application.screenupdating = False is in the wrong place. The real place you would want to speed up is during the loop. So if you were to include it, I would put it near the top of the code, but this isn't very resource intensive so I've just left it out.
Normally it's good to dim Constants if it helps with the legibility of the code, but in this case it doesn't seem to add any clarity. An example where it could help is where you're changing the colour of cells and are using colour indices. Constant Red as long = 3 makes it a lot more understandable, whereas constant Nxt as long = 7 doesn't add much.
Instead of working with a 2-D array dealing with both A and B at once, I chose to use two column vectors because it makes the pasting easier since they are staggered and it simplifies the math since you don't need to have items on staggered rows.
Lastly, I can't advocate this enough, but please, please, please use names that make sense at a glance. Although it may not have made a huge difference in this case, if you get to a more complicated project people might look at it and have to wonder what V is even used for. It also just makes it easier for people to help you since they won't have to sit for a bit wondering what each variable means.
I've also specified the worksheet it looks at, so currently it'll only look at the first sheet as indicated by the index 1. Make sure you change that so it changes the correct sheet.
Hope this helped and welcome to Stack Overflow.
Option Explicit
Sub sequence()
Dim A As Variant
Dim B As Variant
Dim N As Long
Dim ArrA() As Variant
Dim ArrB() As Variant
Dim NumCopies As Long
A = Range("A1").Value
B = Range("B2").Value
NumCopies = 100
ReDim Preserve ArrA(1 To NumCopies * 6, 1 To 1)
ReDim Preserve ArrB(1 To NumCopies * 6, 1 To 1)
For N = 1 To NumCopies
ArrA(N * 6, 1) = A
ArrB(N * 6, 1) = B
Next N
Worksheets(1).Range("A2:A" & 1 + NumCopies * 6).Value = ArrA
Worksheets(1).Range("B3:B" & 2 + NumCopies * 6).Value = ArrB
End Sub | unknown | |
d12277 | train | The syntax for conversion in DW 2 is different. The Code you used is from dw 1. Adding references to type conversions in dw 2 below and fixed your DW script as well.
https://docs.mulesoft.com/dataweave/2.1/dataweave-types
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
"quoteId" : vars.setQuoteOppRecIds.Id,
"productCode" : payload.ServiceTypeCode,
"axSequenceNumber" : vars.counter as Number,
"phaseLevel" : payload.PhaseLevel as Number,
"activeInSOW" : if(payload.PhaseLevelActivateInSOW == "Yes") (toBoolean("true")) else (toBoolean("false")),
"phaseLevelProject" : payload.PhaseLevelProject
} | unknown | |
d12278 | train | y0 and y1 value 0-1 refer the yaxis amplitude.
So you can set y0 and y1 value 0-1 in your layout configuration of the shape and setting the yref as 'paper'. Further documentation can be found here.
{
type: 'rect',
xref: 'x',
yref: 'paper',
x0: 0,
y0: 0, //y0: 0~1 range
x1: 5,
y1: 1,//y1: 0~1 range
// ... visuals
}
Example | unknown | |
d12279 | train | This can be achieved with a module:
#! /usr/bin/env ruby
module Modulino
def modulino_function
return 0
end
end
if ARGV[0] == "-test"
require 'test/unit'
class ModulinoTest < Test::Unit::TestCase
include Modulino
def test_modulino_function
assert_equal(0, modulino_function)
end
end
else
puts "running"
end
or without module, actually:
#! /usr/bin/env ruby
def my_function
return 0
end
if ARGV[0] == "-test"
require 'test/unit'
class MyTest < Test::Unit::TestCase
def test_my_function
assert_equal(0, my_function)
end
end
else
puts "running rc=".my_function()
end | unknown | |
d12280 | train | I had the same issue with version 4.18.0 Facebook SDK. I reverted to an older version 4.17.0 and I no longer get the crash. | unknown | |
d12281 | train | You can achieve that by using the is_home() method.
Here is the reference to the method.
<header class="entry-header">
<?php if ( has_post_thumbnail() && ! post_password_required() ) : ?>
<div class="entry-thumbnail">
<?php the_post_thumbnail(); ?>
</div>
<?php endif;if(!is_home()):?>
<h1 class="entry-title"><?php the_title(); ?></h1></header><!-- .entry-header --><?php endif ?>
A: As I found out function the_title() give you the page title. simply use this and put your html code between if block to customize it.
<?PHP if(the_title() === 'home' /* is_home() */): ?>
... <!-- your html -->
<?PHP endif; ?> | unknown | |
d12282 | train | I'm guessing you have already created the table? And that the table is as per your requirements?
I myself am learning Hibernate, and I find these few problems with your code:
a) @Column(name = "Name") annotation should be there on top of your Name getter setters.
b) Also, I think in your hibernate.cfg.xml, it should say:
<property name="hbm2ddl.auto">update</property>
Because otherwise, its doing nothing. With your current code, it should at least have populated the id. Hibernate docs explain this really well.
c) Besides, you're only saving the user with id 2 if you look close enough.
Hope this helps. | unknown | |
d12283 | train | Let me describe a couple of ways of how you could do this.
ArrayObject with custom code
ArrayObject implements all of the interfaces that you want.
class DomainData extends ArrayObject
{
public $domainId;
public $color;
public function __construct($data = array())
{
parent::__construct($data);
foreach ($data as $key => $value) {
$this->$key = $value;
}
}
}
This isn't very nice, though; it copies the keys and values twice, and changing a property doesn't change the underlying array.
Implement IteratorAggregate on get_object_vars()
If you don't mind giving up on ArrayAccess, you could get away with only implementing an aggregate iterator.
class DomainData implements IteratorAggregate
{
public $domainId;
public $color;
public function __construct($data = [])
{
foreach ($data as $key => $value) {
$this->$key = $value;
}
}
public function getIterator()
{
return new ArrayIterator(get_object_vars($this));
}
}
ArrayObject with property flag and doc blocks
A better way would be to use doc blocks for describing your properties (described here), and then use the ARRAY_AS_PROPS flag to expose the array as properties.
/**
* Magic class
* @property int $domainId
* @property string $color
*/
class DomainData extends ArrayObject
{
function __construct($data = []) {
parent::__construct($data, parent::ARRAY_AS_PROPS);
}
}
When loaded inside PhpStorm, you'd see this:
A: Please try get_object_vars() php function to Gets the accessible non-static properties of the given object according to scope.
The function adds before foreach loop. It's working.
$domainData = get_object_vars($domainData);
foreach($domainData as $k => $v){
var_dump("domainData[$k] = $v");
}
=> Output
string(24) "domainData[domainId] = 1"
string(23) "domainData[color] = red"
A: Implement Iterator interface for ArrayAccess for example
<?php
/**
* Class Collection
* @noinspection PhpUnused
*/
class Collection implements ArrayAccess, IteratorAggregate, JsonSerializable, Countable
{
/**
* @var array $collection
*/
private array $collection;
/**
* @inheritDoc
*/
public function offsetExists($offset): bool
{
return isset($this->collection[$offset]);
}
/**
* @inheritDoc
*/
public function offsetGet($offset)
{
return $this->collection[$offset];
}
/**
* @inheritDoc
*/
public function offsetSet($offset, $value)
{
if (empty($offset)) {
return $this->collection[] = $value;
}
return $this->collection[$offset] = $value;
}
/**
* @inheritDoc
*/
public function offsetUnset($offset): void
{
unset($this->collection[$offset]);
}
/**
* @inheritDoc
*/
public function jsonSerialize()
{
return serialize($this->collection);
}
/**
* @inheritDoc
*/
public function count()
{
return count($this->collection);
}
/**
* @return array
*/
public function __debugInfo()
{
return $this->collection;
}
/**
* @return mixed
*/
public function first()
{
return $this->collection[0];
}
/**
* @inheritDoc
*/
public function getIterator()
{
return new ArrayIterator($this->collection);
}
/** @noinspection MagicMethodsValidityInspection */
public function __toString()
{
return json_encode($this->collection, JSON_THROW_ON_ERROR, 512);
}
/**
* @return mixed
*/
public function last()
{
return $this->collection[$this->count()-1];
}
}
for example using
<?php
$collections = new Collection();
$collections[] =12;
$collections[] = 14;
$collections[] = 145;
$collections[] =4;
print_r($collections);
echo $collections;
echo $collections->last();
echo $collections->first();
foreach ($collections as $collection)
{
echo $collection;
}
count($collections); | unknown | |
d12284 | train | If you know (Line1, City, State) you can determine zip. So,
{Line1, City, State} -> zip
Not the other way around. Because the same zip may contain multiple Line1 values for the same City and State (e.g. different house numbers on the same street).
For 3NF the relations can be
*
*Person {ID, Name, Age, Line1, City, State}
*Address {Line1, City, State, Zip}
From practicality it seems redundent and waste of space in database tables.
A: Assuming {Line1, City, State}->{Zip} and {Zip}->{City, State} then the following decomposition is in 3NF:
Person {ID, Name, Age, Line1, Zip} (key= {ID})
Address {City, State, Zip} (keys = {City, State} and {Zip])
In practice that may not be useful because real address data is often inconsistent or has parts missing. The real question is which dependencies you actually want to enforcein your database. That is why exercises that depend on identifying dependencies only from a list of attribute names are so highly subjective. The only way to give a definitive answer is to start with the set of dependencies which you want the schema to satisfy. | unknown | |
d12285 | train | There are similar questions like this or this other one.
Before JavaFX 11, whenever you were calling something JavaFX related, you had all the javafx modules available within the SDK.
But now you have to include the modules/dependencies you need.
Your error says that you are using FXML but it can't be resolved, but you have just added the javafx.controls module:
--add-modules=javafx.controls
As you can see in the JavaDoc the javafx.controls module depends on javafx.graphics and java.base, but none of those modules includes the FXML classes.
If you need FXML classes like the FXMLLoader, you need to include javafx.fxml module:
--module-path="C:\Program Files\Java\javafx-sdk-11\lib" \
--add-modules=javafx.controls,javafx.fxml
The same will apply if you need media or webkit, those have their own modules. | unknown | |
d12286 | train | Use group_cancat() -
$get_products = Product::select('id','name','mrp','price','status',DB::raw('group_concat(proportion)'))
->groupBy('name')->get(); | unknown | |
d12287 | train | Declare the static variable outside the onKeyDown and increment variable inside the onKeyDown and return if the value is equal to 3 and at the end again equal the static variable equal to 0;
static int i=0;
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
i++;
if(i==3){
//do something
//at the end again i=0;
}
}
return super.onKeyDown(keyCode, event);
}
A: You could listen for every press of the power button, then in your listener you could
*
*measure how many presses you have just made up to this point
*measure the time between your current press and your last press
*if your time interval is right (say 200 ms) then increment your n_presses and do whatever you want after you reach 3 presses (e.g. create a super event and send it to a thread to process it) | unknown | |
d12288 | train | I haven't implemented in Ionic. But you can use the exact same thing in Ionic too:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';
export interface Data {
ITEMS: Array<Item>;
}
export interface Item {
NAME: string;
QUANTITY: Array<string>;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
dbData: Data = {
'ITEMS': [
{
'NAME': 'Farine',
'QUANTITY': ['140', '60']
}]
};
itemsForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.itemsForm = new FormGroup({
'ITEMS': this.formBuilder.array(this.dbData.ITEMS.map(item => this.createItem(item)))
});
}
onFormSubmit() {
console.log('Submit : ', this.itemsForm.value);
}
onAddItems() {
(<FormArray>this.itemsForm.get('ITEMS')).push(this.createItem({ NAME: '', QUANTITY: [] }));
}
addQuantity(i) {
(<FormArray>(<FormArray>this.itemsForm.get('ITEMS')).at(i).get('QUANTITY')).push(this.formBuilder.control(''));
}
private createItem(item: Item) {
return this.formBuilder.group({
NAME: [item.NAME],
QUANTITY: this.formBuilder.array(item.QUANTITY.map(item => this.formBuilder.control(item)))
});
}
}
And in the template:
<pre>{{ itemsForm.value | json }}</pre>
<form [formGroup]="itemsForm" (ngSubmit)="onFormSubmit()">
<button type="button" (click)="onAddItems()">New Item</button>
<div formArrayName="ITEMS">
<div *ngFor="let itemsCtrl of itemsForm.get('ITEMS').controls; let i=index">
<h4>ITEMS</h4>
<div [formGroupName]="i">
<label>Name :
<input type="text" formControlName="NAME">
</label>
<br>
<div formArrayName="QUANTITY">
<div
*ngFor="let item of itemsCtrl.get('QUANTITY').controls; let j = index">
<label>Quantity :
<input type="text" [formControlName]="j">
</label>
<br>
</div>
<button (click)="addQuantity(i)">Add Quantity</button>
</div>
</div>
</div>
</div>
<button type="submit">Submit</button>
</form>
Here's a Working Sample StackBlitz for your ref.
A: There are multiple issues in your code
please see the fixed code here
*
*You need to add controls/form to array, just having any empty form array is not enough
*For loading data into your form, you need to refactor a little bit, because you need to loop through your items and add control/form to your array | unknown | |
d12289 | train | Because the delimiters you want on the string seem to vary according to which part of the string they follow (some have '/', others have ' '), there's probably not a lot you can do there.
If the delimiter were always the same (such as a space), you might use an array and then use join:
var parts = [];
if (level !== '' && level !== 0) parts.push(level);
if (unit !== '' && unit !== 0) parts.push(unit);
if (streetNo.g !== '' && streetNo.g !== 0) parts.push(streetNo.g);
if (streetName !== '' && streetName !== 0) parts.push(streetName);
if (streetType !== '' && streetType !== 0) parts.push(streetType);
if (town !== '' && town !== 0 && town !== '--') parts.push(town);
if (state !== '' && state !== 0) parts.push(state);
string = parts.join(' ' ); | unknown | |
d12290 | train | From this escape sequence reference:
ISO C requires a diagnostic if the backslash is followed by any character not listed here.
So a compiler is required to print a message about it.
After a quick reading of the C11 specification (INCITS+ISO+IEC+9899-2011[2012], following the references in the above linked reference) I find no mention about behavior. While it could be specified somewhere else I doubt it, so the behavior for unspecified escape sequences is, well, unspecified.
A: It is explicit in a (non normative) note of the draft n1570 for C11. The 6.4.4.4 Character constants paragraph defines escape sequences as:
escape-sequence:
*
*simple-escape-sequence
*octal-escape-sequence
*hexadecimal-escape-sequence
*universal-character-name
simple-escape-sequence: one of
*
*\' \" \? \
*\a \b \f \n \r \t \v
octal-escape-sequence:
*
*\ octal-digit
*\ octal-digit octal-digit
*\ octal-digit octal-digit octal-digit
hexadecimal-escape-sequence:
*
*\x hexadecimal-digit
*hexadecimal-escape-sequence hexadecimal-digit
All other sequences of another character following a \ are not defined here, so the behaviour is unspecified (not undefined) by current standard
A note says:
77) ... If any other character follows a backslash,
the result is not a token and a diagnostic is required. See ‘‘future language directions’’ (6.11.4).
And 6.11.4 says:
6.11.4 Character escape sequences
Lowercase letters as escape sequences are reserved for future standardization. Other
characters may be used in extensions.
Commonly, compilers issue the required warning but just ignore the superfluous \. It is fully conformant for non lowercase letters as it can be a local extension, but it could break in a future version of the C language for lower case letters because it is explicitely a reserved feature | unknown | |
d12291 | train | I found the answer, thanks anyway.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CSS3 - Fade between 'background-position' of a sprite image</title>
<style type="text/css">
#button{
float: left;
background-image: url('sprite.jpg');
background-position: 0 -60px;
background-repeat: no-repeat;
width: 120px;
height: 60px;
}
#button a{
background-image: url('sprite.jpg');
background-position: 0 0;
background-repeat: no-repeat;
width: 120px;
height: 60px;
display: block;
text-indent: -9999px;
transition: opacity 0.3s ease-in-out;
-moz-transition: opacity 0.3s ease-in-out;
-webkit-transition: opacity 0.3s ease-in-out;
-o-transition: opacity 0.3s ease-in-out;
}
#button a:hover,
#button a:focus{
opacity: 0;
}
</style>
</head>
<body>
<div id="button"><a href="#"></a></div>
</html>
A: so basically, you need to perform two things upon :hover
*
*background-position change
*fadein effect
CSS3 transition won't be useful in this case.
You can use CSS3 animation property.
animation property accepts name of the animation and duration. Multiple animation names can be provided separated by comma.
you need to define these animation names.They can be any string of your choice, but you need to define them.
so consider this css:
div:hover{
animation: fadein 10s, bp 0.5s;
-moz-animation: fadein 10s, bp 0.5s; /* Firefox */
-webkit-animation: fadein 10s, bp 0.5s; /* Safari and Chrome */
-o-animation: fadein 10s, bp 0.5s;
background-position:0 0;
}
@-webkit-keyframes fadein { /* Safari and Chrome */
from {
opacity:0;
}
to {
opacity:1;
}
}
@-webkit-keyframes bp { /* Safari and Chrome */
from {
background-position:-200px 0;
}
to {
background-position:0 0;
}
}
see this fiddle, for complete browser supported animation
NOTE: it won't work in IE<9 for sure! and it might in IE9(not sure).
A: You can use CSS3 Animation with @keyframes
div:hover{
animation: logo 2s 0 linear;
}
@keyframes logo{
0% { opacity: 1; }
5% { opacity: 0; }
50% { background-position: 0 -60px; opacity: 0; }
100% { background-position: 0 -60px; opacity: 1; }
}
Example: http://jsfiddle.net/Y8W9S/
Of course, now you have to adjust the times and effect you want to implement.
Hope it's helps or point you in right direction.
Good luck.
A: Use like this:
div{
width: 120px;
height: 60px;
background-image: url('sprite.jpg');
background-repeat: no-repeat;
background-position: 0 0;
transition: background-position 1s ease;
}
And don't forget the optional vendor prefixes
Edit:
I've noticed you need fade. You try to similar solution like this:
div{
background: url(foo.jpg) no-repeat 0 0 transparent;
transition: background: 1s ease;
}
div:hover{
background: rgba(0, 0, 0, 1);
}
I can't try this, coz' im from mobile. | unknown | |
d12292 | train | In my opinion the best way might be a join of the two dataframes and then you can model the conditions in the when clause. I think if you create a new column with withColumn it iterates over the values from the current dataframe, but I think you can not access values from another dataframe and expect it also iterates through the rows there.
The following code should fulfill your request:
df_aa = spark.createDataFrame([
(1,1,0,"ab2", "ac3"),
(1,1,1,"dg6", "jf2"),
(2,1,1,"84d", "kf6"),
(2,2,1,"89m", "k34"),
(3,1,0,"5bd", "nc4")
], ("id1", "id2","nr","cell1","cell2"))
df_bb = spark.createDataFrame([
(1, 1, "x","ab2"),
(1, 1, "a","dg6"),
(2, 1, "b","84d"),
(2, 2, "t","89m"),
(3, 1, "d", "5bd")
], ("a", "b","use","cell"))
cond = (df_bb.cell == df_aa.cell1)|(df_bb.cell == df_aa.cell2)
df_bb.join(df_aa, cond, how="full").withColumn("val1", when((col("id1")==col("id2")) & ((col("cell")==col("cell1"))|(col("cell")==col("cell2"))) & (col("nr")==1), 1).otherwise(0)).withColumn("val2", when(~(col("id1")==col("id2")) & ((col("cell")==col("cell1"))|(col("cell")==col("cell2"))) & (col("nr")==1), 1).otherwise(0)).show()
Result looks like:
+---+---+---+----+---+---+---+-----+-----+----+----+
| a| b|use|cell|id1|id2| nr|cell1|cell2|val1|val2|
+---+---+---+----+---+---+---+-----+-----+----+----+
| 1| 1| x| ab2| 1| 1| 0| ab2| ac3| 0| 0|
| 1| 1| a| dg6| 1| 1| 1| dg6| jf2| 1| 0|
| 2| 1| b| 84d| 2| 1| 1| 84d| kf6| 0| 1|
| 2| 2| t| 89m| 2| 2| 1| 89m| k34| 1| 0|
| 3| 1| d| 5bd| 3| 1| 0| 5bd| nc4| 0| 0|
+---+---+---+----+---+---+---+-----+-----+----+----+
It could be that I do not even need to check for the condition cell==cell1|cell==cell2 since that is pretty much the join condition, but to make the when conditions similar to the requirements of you, I put it there | unknown | |
d12293 | train | This pretty much unambiguously says the server says the server has no messages in the INBOX:
A1 SELECT INBOX
* 0 EXISTS
* 0 RECENT
Either they are in another folder, or they are in another account. | unknown | |
d12294 | train | @Effect()
search$: Observable<Action> = this.actions$
.ofType(book.SEARCH)
.debounceTime(300)
.map(toPayload)
.filter(query => query !== '')
.switchMap(query => {
const nextSearch$ = this.actions$.ofType(book.SEARCH).skip(1);
return this.googleBooks.searchBooks(query)
.takeUntil(nextSearch$)
.map(books => data === undefined ? new book.LoadFromWebAPI(query) : new book.SearchCompleteAction(books))
.catch(() => of(new book.SearchCompleteAction([])));
}); | unknown | |
d12295 | train | The reason it flickers is because when you assign the width or height to a canvas element, this action resets the entire context of the canvas, most likely that is causing the blank frame. Try moving all the canvas/context definitions outside the drawCanvas.
Something like:
var elem = document.getElementById('c');
var c = elem.getContext('2d');
var v = $('#v')[0];
// In order to set the canvas width & height, we need to wait for the video to load.
function init() {
if (v.readyState == 4) {
$('#c').attr('width', v.videoWidth);
$('#c').attr('height', v.videoHeight);
} else {
requestAnimationFrame(init);
}
}
init();
$('#v').on('timeupdate', function () {
if ($('#v')[0].currentTime > 2) { //Loop for one second
$('#v')[0].currentTime = 1;
}
var $this = $('#v')[0]; //cache
(function loop() {
if (!$this.paused && !$this.ended) {
drawCanvas();
setTimeout(loop, 1000 / 25); // drawing at 25fps
}
})();
});
function drawCanvas() {
c.drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, v.videoWidth, v.videoHeight);
} | unknown | |
d12296 | train | Please try the following solution based on XML and XQuery.
Notable points:
*
*We are tokenizing input string as XML in the CROSS APPLY clause.
*XQuery's FLWOR expression is checking for numeric integer values with
a particular length, and substitutes then with a replacement string.
*XQuery .value() method outputs back a final result.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, tokens VARCHAR(MAX));
INSERT INTO @tbl (tokens) VALUES
('A12 456 1 65 7944');
-- DDL and sample data population, end
DECLARE @separator CHAR(1) = SPACE(1);
SELECT t.*
, c.query('
for $x in /root/r/text()
return if (xs:int($x) instance of xs:int and string-length($x)=3) then "xxx"
else if (xs:int($x) instance of xs:int and string-length($x)=4) then "zzzz"
else data($x)
').value('.', 'VARCHAR(MAX)') AS Result
FROM @tbl AS t
CROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' +
REPLACE(tokens, @separator, ']]></r><r><![CDATA[') +
']]></r></root>' AS XML)) AS t1(c);
Output
+----+-------------------+-------------------+
| ID | tokens | Result |
+----+-------------------+-------------------+
| 1 | A12 456 1 65 7944 | A12 xxx 1 65 zzzz |
+----+-------------------+-------------------+ | unknown | |
d12297 | train | sample_string.erase(i,j)
Calls the erase method on the sample_string object (assuming that this is an instance of a class that implements this method).
string(sample_string).erase(i,j)
Creates a temporary instance of the string class, calling a string constructor using the sample_string object for initialization of the string, and then calls the erase method on that temporary object.
A: I suppose the type of simple_string is std::string. the code
string(sample_string).erase(i, j)
looked cannot work because string(sample_string) returns a temp obj, and then called erase method on the temporary string object. There is nothing to do with sample_string.
A: The first one, string(sample_string).erase(i,j) creates a temporary string, and erases from that temporary string.
The second erases from the string object sample_string. | unknown | |
d12298 | train | Here was an incorrect solution.
Counterexample for your solution. Suppose, that one in square is the only one important. Your solution will delete one road.
A: If you can prove that the optimal number of cuts is equal to the number of different cycles* that contain an important node, solving the problem is not that hard.
You can do a DFS, keep track of visited nodes, and whenever you reach a node that you already visited you got a cycle. To tell whether the cycle contains an important node or not, keep track of the depth at which each node was visited and remember the depth of the last important node in the current branch of the search. If the cycle's start depth is less (i.e. earlier) than the last important node's depth, the cycle contains an important node.
C++ implementation:
// does not handle multiple test cases
#include <iostream>
#include <vector>
using namespace std;
const int MAX = 10000;
int n, m, k;
vector<int> edges[MAX];
bool seen[MAX];
int seenDepth[MAX]; // the depth at which the DFS visited the node
bool isImportant(int node) { return node < k; }
int findCycles(int node, int depth, int depthOfLastImp)
{
if (seen[node])
{
if (seenDepth[node] <= depthOfLastImp && (depth - seenDepth[node]) > 2)
{
// found a cycle with at least one important node
return 1;
}
else
{
// found a cycle, but it's not valid, so cut this branch
return 0;
}
}
else
{
// mark this node as visited
seen[node] = true;
seenDepth[node] = depth;
// recursively find cycles
if (isImportant(node)) depthOfLastImp = depth;
int cycles = 0;
for (int i = 0; i < edges[node].size(); i++)
{
cycles += findCycles(edges[node][i], depth + 1, depthOfLastImp);
}
return cycles;
}
}
int main()
{
// read data
cin >> n >> m >> k;
for (int i = 0; i < m; i++)
{
int start, stop;
cin >> start >> stop;
edges[start].push_back(stop);
edges[stop].push_back(start);
}
int numCycles = 0;
for (int i = 0; i < m; i++)
{
if (!seen[i])
{
// start at depth 0, and last important was never (-1)
numCycles += findCycles(i, 0, -1);
}
}
cout << numCycles << "\n";
return 0;
}
* By 'different' I mean that a cycle isn't counted if all its edges are already part of different cycles. In the following example, I consider the number of cycles to be 2, not 3:
A–B
| |
C–D
| |
E–F
A: My algorithm is based on the following observation: since we don't care about cycles with unimportant nodes only, unimportant nodes can be collapsed. We are collapsing two neighboring unimportant nodes, by replacing them with a single unimportant node with the sum of edges from the original nodes.
When collapsing two unimportant nodes we need to handle two special cases:
*
*Both nodes were connected to the same unimportant node U. This means there was a cycle of unimportant nodes in the original graph; we can ignore the cycle and the new node will be connected to the same unimportant node U with a single edge.
*Both nodes were connected to the same important node I. This means there was a cycle of unimportant nodes and the single important node I in the original graph; before collapsing the nodes we need to remove one of the edges connecting them to the important node I and thus removing the cycle; The new node will be connected to the important node I with a single edge.
With the above definition of node collapsing, the algorithm is:
*
*Keep collapsing neighboring unimportant nodes, until there are no neighboring unimportant nodes. All removed edges between important and unimportant nodes, as defined in case (2) above, count towards the solution.
*Find the spanning tree of the remaining graph and remove all edges that are not included in the spanning tree. All edges removed in this step count towards the solution.
The algorithm runs in O(M) time. I believe I can prove its correctness, but would like to get your feedback before I spend too much time on it :-) | unknown | |
d12299 | train | use the following line.
sys.path.insert(0, '/some/dir/submodules') | unknown | |
d12300 | train | The FRC will only observe changes to the objects that it is directly interested in, not any of the objects that they are related to.
You should configure your own observation, either directly with KVO or to the context being saved, and use that to trigger a UI refresh. | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.