_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d11901 | train | After a lot of research and a applying a little brain, I found out the solution. It was a very small but silly mistake. Read the following source code:
public class printnow {
public static void printCard(final String bill ) {
final PrinterJob job = PrinterJob.getPrinterJob();
Printable contentToPrint = new Printable() {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2d.setFont(new Font("Monospaced", Font.BOLD, 7));
if (pageIndex > 0) {
return NO_SUCH_PAGE;
} //Only one page
String Bill [] = bill.split(";");
int y = 0;
for (int i = 0; i < Bill.length; i++) {
g2d.drawString(Bill[i], 0, y);
y = y + 15;
}
return PAGE_EXISTS;
}
};
PageFormat pageFormat = new PageFormat();
pageFormat.setOrientation(PageFormat.PORTRAIT);
Paper pPaper = pageFormat.getPaper();
pPaper.setImageableArea(0, 0, pPaper.getWidth() , pPaper.getHeight() -2);
pageFormat.setPaper(pPaper);
job.setPrintable(contentToPrint, pageFormat);
try {
job.print();
} catch (PrinterException e) {
System.err.println(e.getMessage());
}
}
}
In the previous source code (the wrong one), when the application triggers a print dialog box and the user clicks OK, the default printing preferences are transferred to the Java app and it prints what is required. but when we disable the print dialog box by removing this line:
boolean don = job.printDialog();
an unknow PageFormat is transferred which arises out of nowhere. The problem was not with our defined PageFormat, the problem was that the pageFormat is passed to a printing method which we were not doing initially:
job.setPrintable(contentToPrint, pageFormat);
Notice the second parameter being passed to the above method.
Hope this helps everyone. :) | unknown | |
d11902 | train | Simply by doing request.protocol like
exports.nameOfFunction = function(request, response){
var proto = request.protocol;
console.log(proto);
} | unknown | |
d11903 | train | the onerror does not tell me what failed, so I have to make an XHR just to find it out. That's a minor thing
You could first try the XHR. If it fails, you know what happened, if it succeeds you can display the image from cache (see also here). And of course you also could make it call some globally-defined custom hooks for special status codes - yet you will need to call that manually, there is no pre-defined global event source.
I'd like to have something like a document.onerror handler to avoid using the wrapUrlInErrorHandler function every time I have to put an image in the page
That's impossible. The error event (MDN, MSDN) does not bubble, it fires directly and only on the <img> element. However, you could get around that ugly wrapUrlInErrorHandler if you didn't use inline event attributes, but (traditional) advanced event handling:
function showImageInANiceDiv(imgUrl) {
var img = new Image();
img.src = imgUrl;
img.onerror = errorHandler; // here
$("#imageBox").empty().append(img);
}
// function to handle errors
function errorHandler(event) {
var img = event.srcElement; // or use the "this" keyword
console.log("this guy triggered an "+event.type+": " + img.src);
} | unknown | |
d11904 | train | I find This solution, It is most probably compatible with all browsers.
Note: if anyone finds any error or browser support issues. please update this answer Or comments
CSS Profpery Support reference:
column-count, gap, fill break-inside, page-break-inside
Note: page-break-inside This property has been replaced by the break-inside property.
.container {
-moz-column-count: 1;
column-count: 1;
-moz-column-gap: 20px;
column-gap: 20px;
-moz-column-fill: balance;
column-fill: balance;
margin: 20px auto 0;
padding: 2rem;
}
.container .item {
display: inline-block;
margin: 0 0 20px;
page-break-inside: avoid;
-moz-column-break-inside: avoid;
break-inside: avoid;
width: 100%;
}
.container .item img {
width: 100%;
height: auto;
}
@media (min-width: 600px) {
.container {
-moz-column-count: 2;
column-count: 2;
}
}
@media (min-width: 900px) {
.container {
-moz-column-count: 3;
column-count: 3;
}
}
@media (min-width: 1200px) {
.container {
-moz-column-count: 4;
column-count: 4;
}
}
CSS-Only Masonry Layout
<div class="container">
<div class="item"><img src="https://placeimg.com/600/400/animals" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/600/arch" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/300/nature" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/450/people" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/350/tech" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/800/animals/grayscale" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/650/arch/sepia" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/300/nature/grayscale" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/400/people/sepia" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/600/tech/grayscale" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/200/animals/sepia" alt=""></div>
<div class="item"><img src="https://placeimg.com/600/700/arch/grayscale" alt=""></div>
</div>
A: Finally a CSS-only solution to easily create masonry layout but we need to be patient since there is no support for it for now.
This feature was introduced in the CSS Grid Layout Module Level 3
This module introduces masonry layout as an additional layout mode for CSS Grid containers.
Then
Masonry layout is supported for grid containers by specifying the value masonry for one of its axes. This axis is called the masonry axis, and the other axis is called the grid axis.
A basic example would be:
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-template-rows: masonry; /* this will do the magic */
grid-gap: 10px;
}
img {
width: 100%;
}
<div class="container">
<img src="https://picsum.photos/id/1/200/300">
<img src="https://picsum.photos/id/17/200/400">
<img src="https://picsum.photos/id/18/200/100">
<img src="https://picsum.photos/id/107/200/200">
<img src="https://picsum.photos/id/1069/200/600">
<img src="https://picsum.photos/id/12/200/200">
<img src="https://picsum.photos/id/130/200/100">
<img src="https://picsum.photos/id/203/200/100">
<img src="https://picsum.photos/id/109/200/200">
<img src="https://picsum.photos/id/11/200/100">
</div>
This will produce the following result on Firefox if you enable the feature like explained here: https://caniuse.com/?search=masonry
*
*open Firefox and write about:config in the url bar
*do a search using masonry
*you will get one flag, make it true
If we reduce the screen screen, the reponsive part is perfect!
A: 2021 Update
CSS Grid Layout Level 3 includes a masonry feature.
Code will look like this:
grid-template-rows: masonry
grid-template-columns: masonry
As of March 2021, it's only available in Firefox (after activating the flag).
*
*https://drafts.csswg.org/css-grid-3/#masonry-layout
*https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Masonry_Layout
end update; original answer below
Flexbox
A dynamic masonry layout is not possible with flexbox, at least not in a clean and efficient way.
Flexbox is a one-dimensional layout system. This means it can align items along horizontal OR vertical lines. A flex item is confined to its row or column.
A true grid system is two-dimensional, meaning it can align items along horizontal AND vertical lines. Content items can span across rows and columns simultaneously, which flex items cannot do.
This is why flexbox has a limited capacity for building grids. It's also a reason why the W3C has developed another CSS3 technology, Grid Layout.
row wrap
In a flex container with flex-flow: row wrap, flex items must wrap to new rows.
This means that a flex item cannot wrap under another item in the same row.
Notice above how div #3 wraps below div #1, creating a new row. It cannot wrap beneath div #2.
As a result, when items aren't the tallest in the row, white space remains, creating unsightly gaps.
column wrap
If you switch to flex-flow: column wrap, a grid-like layout is more attainable. However, a column-direction container has four potential problems right off the bat:
*
*Flex items flow vertically, not horizontally (like you need in this case).
*The container expands horizontally, not vertically (like the Pinterest layout).
*It requires the container to have a fixed height, so the items know where to wrap.
*As of this writing, it has a deficiency in all major browsers where the container doesn't expand to accommodate additional columns.
As a result, a column-direction container is not an option in this case, and in many other cases.
CSS Grid with item dimensions undefined
Grid Layout would be a perfect solution to your problem if the various heights of the content items could be pre-determined. All other requirements are well within Grid's capacity.
The width and height of grid items must be known in order to close gaps with surrounding items.
So Grid, which is the best CSS has to offer for building a horizontally-flowing masonry layout, falls short in this case.
In fact, until a CSS technology arrives with the ability to automatically close the gaps, CSS in general has no solution. Something like this would probably require reflowing the document, so I'm not sure how useful or efficient it would be.
You'll need a script.
JavaScript solutions tend to use absolute positioning, which removes content items from the document flow in order to re-arrange them with no gaps. Here are two examples:
*
*Desandro Masonry
Masonry is a JavaScript grid layout library. It
works by placing elements in optimal position based on available
vertical space, sort of like a mason fitting stones in a wall.
source: http://masonry.desandro.com/
*
*How to Build a Site that Works Like Pinterest
[Pinterest] really is a cool site, but what I find interesting is how these pinboards are laid out... So the purpose of this tutorial is to re-create this responsive block effect ourselves...
source: https://benholland.me/javascript/2012/02/20/how-to-build-a-site-that-works-like-pinterest.html
CSS Grid with item dimensions defined
For layouts where the width and height of content items are known, here's a horizontally-flowing masonry layout in pure CSS:
grid-container {
display: grid; /* 1 */
grid-auto-rows: 50px; /* 2 */
grid-gap: 10px; /* 3 */
grid-template-columns: repeat(auto-fill, minmax(30%, 1fr)); /* 4 */
}
[short] {
grid-row: span 1; /* 5 */
background-color: green;
}
[tall] {
grid-row: span 2;
background-color: crimson;
}
[taller] {
grid-row: span 3;
background-color: blue;
}
[tallest] {
grid-row: span 4;
background-color: gray;
}
grid-item {
display: flex;
align-items: center;
justify-content: center;
font-size: 1.3em;
font-weight: bold;
color: white;
}
<grid-container>
<grid-item short>01</grid-item>
<grid-item short>02</grid-item>
<grid-item tall>03</grid-item>
<grid-item tall>04</grid-item>
<grid-item short>05</grid-item>
<grid-item taller>06</grid-item>
<grid-item short>07</grid-item>
<grid-item tallest>08</grid-item>
<grid-item tall>09</grid-item>
<grid-item short>10</grid-item>
<grid-item tallest>etc.</grid-item>
<grid-item tall></grid-item>
<grid-item taller></grid-item>
<grid-item short></grid-item>
<grid-item short></grid-item>
<grid-item short></grid-item>
<grid-item short></grid-item>
<grid-item tall></grid-item>
<grid-item short></grid-item>
<grid-item taller></grid-item>
<grid-item short></grid-item>
<grid-item tall></grid-item>
<grid-item short></grid-item>
<grid-item tall></grid-item>
<grid-item short></grid-item>
<grid-item short></grid-item>
<grid-item tallest></grid-item>
<grid-item taller></grid-item>
<grid-item short></grid-item>
<grid-item tallest></grid-item>
<grid-item tall></grid-item>
<grid-item short></grid-item>
</grid-container>
jsFiddle demo
How it works
*
*Establish a block-level grid container. (inline-grid would be the other option)
*The grid-auto-rows property sets the height of automatically generated rows. In this grid each row is 50px tall.
*The grid-gap property is a shorthand for grid-column-gap and grid-row-gap. This rule sets a 10px gap between grid items. (It doesn't apply to the area between items and the container.)
*The grid-template-columns property sets the width of explicitly defined columns.
The repeat notation defines a pattern of repeating columns (or rows).
The auto-fill function tells the grid to line up as many columns (or rows) as possible without overflowing the container. (This can create a similar behavior to flex layout's flex-wrap: wrap.)
The minmax() function sets a minimum and maximum size range for each column (or row). In the code above, the width of each column will be a minimum of 30% of the container and maximum of whatever free space is available.
The fr unit represents a fraction of the free space in the grid container. It's comparable to flexbox's flex-grow property.
*With grid-row and span we're telling grid items how many rows they should span across.
Browser Support for CSS Grid
*
*Chrome - full support as of March 8, 2017 (version 57)
*Firefox - full support as of March 6, 2017 (version 52)
*Safari - full support as of March 26, 2017 (version 10.1)
*Edge - full support as of October 16, 2017 (version 16)
*IE11 - no support for current spec; supports obsolete version
Here's the complete picture: http://caniuse.com/#search=grid
Cool grid overlay feature in Firefox
In Firefox dev tools, when you inspect the grid container, there is a tiny grid icon in the CSS declaration. On click it displays an outline of your grid on the page.
More details here: https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector/How_to/Examine_grid_layouts
A: This is recently discovered technique involving flexbox: https://tobiasahlin.com/blog/masonry-with-css/.
The article makes sense to me, but I haven't tried to use it, so I don't know if there are any caveats, other than mentioned in Michael's answer.
Here's a sample from the article, making use of the order property, combined with :nth-child.
Stack snippet
.container {
display: flex;
flex-flow: column wrap;
align-content: space-between;
/* Your container needs a fixed height, and it
* needs to be taller than your tallest column. */
height: 960px;
/* Optional */
background-color: #f7f7f7;
border-radius: 3px;
padding: 20px;
width: 60%;
margin: 40px auto;
counter-reset: items;
}
.item {
width: 24%;
/* Optional */
position: relative;
margin-bottom: 2%;
border-radius: 3px;
background-color: #a1cbfa;
border: 1px solid #4290e2;
box-shadow: 0 2px 2px rgba(0,90,250,0.05),
0 4px 4px rgba(0,90,250,0.05),
0 8px 8px rgba(0,90,250,0.05),
0 16px 16px rgba(0,90,250,0.05);
color: #fff;
padding: 15px;
box-sizing: border-box;
}
/* Just to print out numbers */
div.item::before {
counter-increment: items;
content: counter(items);
}
/* Re-order items into 3 rows */
.item:nth-of-type(4n+1) { order: 1; }
.item:nth-of-type(4n+2) { order: 2; }
.item:nth-of-type(4n+3) { order: 3; }
.item:nth-of-type(4n) { order: 4; }
/* Force new columns */
.break {
flex-basis: 100%;
width: 0;
border: 1px solid #ddd;
margin: 0;
content: "";
padding: 0;
}
body { font-family: sans-serif; }
h3 { text-align: center; }
<div class="container">
<div class="item" style="height: 140px"></div>
<div class="item" style="height: 190px"></div>
<div class="item" style="height: 170px"></div>
<div class="item" style="height: 120px"></div>
<div class="item" style="height: 160px"></div>
<div class="item" style="height: 180px"></div>
<div class="item" style="height: 140px"></div>
<div class="item" style="height: 150px"></div>
<div class="item" style="height: 170px"></div>
<div class="item" style="height: 170px"></div>
<div class="item" style="height: 140px"></div>
<div class="item" style="height: 190px"></div>
<div class="item" style="height: 170px"></div>
<div class="item" style="height: 120px"></div>
<div class="item" style="height: 160px"></div>
<div class="item" style="height: 180px"></div>
<div class="item" style="height: 140px"></div>
<div class="item" style="height: 150px"></div>
<div class="item" style="height: 170px"></div>
<div class="item" style="height: 170px"></div>
<span class="item break"></span>
<span class="item break"></span>
<span class="item break"></span>
</div> | unknown | |
d11905 | train | I'm not sure how to fix a row like you're suggesting, but for something that needs to be visible 100% of the time, have you thought about adding a top bar or a bottom bar that displays these values? You can use the displayfield xtype to show text in such a place. I'm doing this in several projects. | unknown | |
d11906 | train | The "keywords" in your input box is stored as a span with class name "tag label label-info". You can simply get the count of that element and verify it to be 5 or not:
JAVA -
List <WebElements> tags_list = driver.findElements(By.xpath("//div[@class = 'bootstrap-tagsinput']/span[@class = 'tag label label-info']"));
if(tags_list.size() >= 5)
{
// do whatever you want
} | unknown | |
d11907 | train | It seems to be a library problem => Github Issue Socket Hangout
Look here if you dont know which library fit more your needs.
A: I quickly realized that felix-couchdb is not compatible with node 8 (I know you're not using version 8, but you will someday), so I switched to nano couchdb and here's the following code:
*
*It will check if the db is created
*It will insert only if the key given is unique
*It will get the user with a key
var couchdb = require('nano')('http://localhost:5984')
, dbName = 'users'
, db = couchdb.use(dbName)
;
var user = {
name: {
first: 'John',
last: 'Doe'
}
}
couchdb.db.create(dbName, function(err, db_body) {
db.insert(user, 'jdoe4', function(err, doc, header) {
if( err) {
console.log('Cannot save user');
} else {
console.log('Saved user.');
}
console.log('Leaving saveDoc');
});
db.get('jdoe', function(err, doc) {
if( err) {
console.log('Cannot get user');
} else {
console.log(JSON.stringify(doc));
}
console.log('Leaving getDoc');
});
});
One thing worth noting is that, while this will get them at the "same time," it's still making 3 requests to the db, 1 to check if it exists, 1 to insert (or not), 1 to get. | unknown | |
d11908 | train | You're looking at a gcc extension that allows you to treat multiple statements as a single expression. The last one needs to be an expression that is used as the result of the entire thing. It's meant for use in macros to allow the presence of temporary variables, but in modern C it's better to use inline functions instead of function like macros in this and many other cases (and not just because this is a non-standard extension and inline functions are standard):
inline int open_listen_fd_or_die(int port) {
int rc = open_listen_fd(port);
assert(rc >= 0); // maybe not the best approach
return rc;
}
More information can be found in the gcc documentation. | unknown | |
d11909 | train | Implementing a pattern is not related to a technical framework you might want to use. It's all about abstraction. So if you really do understand a pattern you can implement it. Well ok, you shouldn't try to implement e.g. the bridge pattern in assembler. ;o)
But if you are going to use a programming language with object oriented concepts like C#, VB, C++ or Java (I know, that there are a lot of other possibilities) you will achieve your goal. | unknown | |
d11910 | train | Install RubyInstaller RC2, version 1.8.7-p249.
http://rubyinstaller.org/download.html
A: You can use pik, a ruby version manager for windows
*
*a simple guide: http://www.dixis.com/?p=117 | unknown | |
d11911 | train | MATLAB has a .Net interface that's well-documented. What you need to do is covered in the Call MATLAB Function from C# Client article.
For a simple MATLAB function, say:
function [x,y] = myfunc(a,b,c)
x = a + b;
y = sprintf('Hello %s',c);
..it boils down to creating an MLApp and invoking the Feval method:
class Program
{
static void Main(string[] args)
{
// Create the MATLAB instance
MLApp.MLApp matlab = new MLApp.MLApp();
// Change to the directory where the function is located
matlab.Execute(@"cd c:\temp\example");
// Define the output
object result = null;
// Call the MATLAB function myfunc
matlab.Feval("myfunc", 2, out result, 3.14, 42.0, "world");
// Display result
object[] res = result as object[];
Console.WriteLine(res[0]);
Console.WriteLine(res[1]);
Console.ReadLine();
}
} | unknown | |
d11912 | train | I had the same problem time ago then i read this tutorial about scopes.
https://github.com/angular/angular.js/wiki/Understanding-Scopes
Anyway the main concept is that when you use ng-model always use a dot notation.
so $scope.user={}
and then $scope.user.name.
Hope it helps.
A: Ok i got it finally. The problem is that the $watch can be only bound to an object and observe it and not to a elementary field like string, int . boolean & co.
The bad thing is when you have a object complex structure you cant only bind it to a property but rather to the whole object that causes performance issues if its a multilevel object. | unknown | |
d11913 | train | I'd start to observe the following:
*
*You have a GenericDao<T> which means that you can have different implementations.
*Currently, you have GenericDaoImpl<T> extends JdbcDaoSupport which means that you cannot use in the other environment you described without any application context unless you prepare all the object in a manual fashion.
So my suggestion is:
*
*Allow GenericDao<T> extends org.springframework.jdbc.core.JdbcOperations
*Develop an AbstractGenericDao<T> implements GenericDao<T> to bring the abstract general functionality you need.
*Develop a MyEnvGenericDao<T> extends AbstractGenericDao<T> that is responsible to provide a data source and underlying implementation of different methods you need; could be using a direct Hibernate/OpenJPA implementation to directly executing the queries.
*Develop a SpringGenericDao<T> extends JdbcDaoSupport implements GenericDao<T> that comes is already with a getJdbcTemplate() to perform the operations you need and is delegated to Spring JDBC template. In this scenario, you need to delegate the operations to JdbcDaoSupport.getJdbcTemplate().
Related to Maven, then you can actually have different modules for MyEnv and Spring implementations but both with one parent to have access to GenericDao<T> interface. | unknown | |
d11914 | train | Fix came from Heroku article https://devcenter.heroku.com/articles/troubleshooting-node-deploys
This part -
Don’t check in generated directories
The app’s node_modules directory is generated at build time from the dependencies listed in package.json and the lockfile. Therefore, node_modules (and other generated directories like bower_components) shouldn’t be included in source control. Check with the following:
git ls-files | grep node_modules
If there are results, then instruct git to stop tracking node_modules:
echo "node_modules" >> .gitignore
git rm -r --cached node_modules
git commit -am 'untracked node_modules'
That did it. I don't really get why that did it when node_modules is in my gitignore AND when I've had this project up for almost a year without having this issue , but it did. | unknown | |
d11915 | train | Try my code link to online demo:
<?php
$data = array(
array(
'id' => 1,
'name' => 'abc',
'link' => 'abcc',
'parent' => 0
),
array(
'id' => 2,
'name' => 'aaa',
'link' => 'bbb',
'parent' => 1
),
array(
'id' => 3,
'name' => 'aas',
'link' => 'bbc',
'parent' => 2
),
array(
'id' => 4,
'name' => 'asdasd',
'link' => 'adsasd',
'parent' => 2
),
array(
'id' => 5,
'name' => 'asdasd',
'link' => 'serae',
'parent' => 4
),
array(
'id' => 6,
'name' => 'rywer',
'link' => 'twet',
'parent' => 0
)
);
function buildMenu($data) {
usort($data, function($a, $b) {
if ($a['parent'] == $b['parent']) {
if ($a['id'] == $b['id']) {
return 0;
}
return ($a['id'] < $b['id']) ? -1 : 1;
}
return ($a['parent'] < $b['parent']) ? -1 : 1;
});
$shortcuts = array();
$menu = array();
foreach($data as &$row) {
if ($row['parent'] <= 0) {
$menu[] = &$row;
$shortcuts[$row['id']] = &$row;
continue;
} else {
$parent = $row['parent'];
if (!isset($shortcuts[$parent])) {
throw new \Exception("Menu cannot be build");
}
$parentItem = &$shortcuts[$parent];
}
if (!isset($parentItem['child'])) {
$parentItem['child'] = array();
}
$parentItem['child'][] = &$row;
$shortcuts[$row['id']] = &$row;
}
return $menu;
}
print_r(buildMenu($data));
It uses references to keep it clean. On the beggining of buildMenu function I have also sorted your sorce array to have data sorted by parent ID, increasingly.
Please also consider using english variable names.
If you would like to generate <ul> menu from this array, use this code:
$menu = '<ul>';
function buildUl($data) {
$menuHtml = '';
foreach ($data as $menuItem) {
$menuHtml .= '<li>';
$menuHtml .= '<a href="'.$menuItem['link'].'">'.$menuItem['name'].'</a>';
if (!empty($menuItem['child'])) {
$menuHtml .= '<ul>';
$menuHtml .= buildUl($menuItem['child']);
$menuHtml .= '</ul>';
}
$menuHtml .= '</li>';
}
return $menuHtml;
}
$menu .= buildUl(buildMenu($data));
$menu .= '</ul>';
echo $menu;
Updated example: http://sandbox.onlinephpfunctions.com/code/27cfa95c066be9b1526b71566e2ec2f2093bdc34
A: Things are way easier when you use objects:
$data = [
['id' => 1, 'nazwa' => 'abc', 'link' => 'abcc', 'parent' => 0],
['id' => 2, 'nazwa' => 'aaa', 'link' => 'bbb', 'parent' => 1],
['id' => 3, 'nazwa' => 'aas', 'link' => 'bbc', 'parent' => 2],
['id' => 4, 'nazwa' => 'asdasd', 'link' => 'adsasd', 'parent' => 2],
['id' => 5, 'nazwa' => 'asdasd', 'link' => 'serae', 'parent' => 4],
['id' => 6, 'nazwa' => 'rywer', 'link' => 'twet', 'parent' => 0],
];
$objectTree = [];
$objects = [];
foreach ($data as $row) {
$obj = (object)$row;
$obj->childs = [];
$objects[$obj->id] = $obj;
}
foreach ($objects as $obj) {
if ($obj->parent == 0) {
$objectTree[] = $obj;
} else {
$objects[$obj->parent]->childs[] = $obj;
}
}
var_export($objectTree);
Demo: http://rextester.com/RZRQLX19028 | unknown | |
d11916 | train | This did the trick for me without changing every line where format is used:
from __future__ import unicode_literals
Basically I had problems whenever "string {}" in "string {}".format("hello") was str object. Writing a simple u"string {}" would have helped, but huge code base remember? "hello" doesn't really matter.
A: # -*- coding: UTF-8 -*-
x = r"ñö"
print isinstance(x,unicode)#prints "True"
y = "Hello {0}".format(x)# "UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)"
print y | unknown | |
d11917 | train | That task is not under logging scope, you should "manually" delete them upon application start. Use os or shutil. | unknown | |
d11918 | train | You can add a new Filter to intercept and authenticate OAuth requests in which it should call the authenticationManager.authenticate method and save the result of the authentication token in the SecurityContextHolder. This way the user is fully authenticated.
Note, that this way you don't "override" or "bypass" the Spring Security. You just use it to perform a different authentication. | unknown | |
d11919 | train | I think one way to do this would be:
for i in range(len(df['code'])):
df['code'].iloc[i] = int(df['code'].iloc[i] )
Instead of using the index itself, it uses the index position. | unknown | |
d11920 | train | I'm on the same problem with my keycloak and Moodle config.
If you aren't an expert in PHP, you can edit the file of (Moodle Installation path) /auth/oidc/classes/oidcclient.php in the 252 line, and edit as follows:
Then retry the login in your Moodle page and the result will be like this:
Here you can view the error detail, in my case is a DNS problem. | unknown | |
d11921 | train | OAuth allows client connection without storing credentials on client ( used widely on mobile devices or to identify tweitte applications ). It also allows to remove access permissions from rogue clients. But I doubt that mysql suzpports this directly,. so you will have to wrap your database with some kind of service layer. One of usable imaplementations of OAuth:
http://code.google.com/p/oauth-signpost/
(IIRC, used by Qipe )
A: Assuming that the database which will be accessed will be on your machines, two things that come to mind:
*
*Set up a small secure REST service (as shown here) which will, upon a certain request with certain credentials, pass the password to your database. This however might be an issue if your application is sitting behind some corporate firewall since you might need to add firewall exceptions, which is something that not all administrators are enthusiastic about.
*You could use a mix of Cryptography and Obfuscation to encrypt the password to the database and then obfuscate all your code.
As a note though, either of these methods can, in time be broken. This is basically the rule about all security related software.
If it where up to me, I would go about this problem using the first approach and make sure that the credentials through which the service is accessed are changed often.
However, databases which are used as part of a client solution contain pretty sensitive data which is in the client's interest not to tamper with, so the client will most likely not mess around with it, he/she will be happy as long as the system works.
If on the other hand, the database is not deployed onto one of your machines then you can't really do much about it. You could recommend that the server will be stored on a remote machine with access only over the intranet, but other than that, I do not think you can do much about it. | unknown | |
d11922 | train | This syntax uses the ocamlyacc rule grammar, which is a DSL for writing parsers. Symbols $N refer to N-th semantic attribute of the defined non-terminal. You can think of them as simple variables, that are bound by the non-terminal pattern expression. So what does (($2 :: fst $1), snd $1) mean?
It is a pair, the first constituent is a list $2 :: fst $1 made from the $2 and the first element of $1, which is itself a pair. And the second part of $1 makes the second constituent of the resulting pair. E.g., suppose that $1 = (5,7) and $2 is 42, you will get, ([42;5],7) as the result of this semantic action. | unknown | |
d11923 | train | In the context of R Markdown documents, I would actually strongly urge you to use figure captions rather than plot titles, like so:
---
title: "Stack Overflow Answer"
author: "duckmayr"
output: pdf_document
---
```{r histogram, fig.cap="Blah Blah $\\mathcal{MATH}$"}
hist(islands, main = "")
```
Update: Multiple histograms
You can use subfigures, which is the normal LaTeX way.
Then you'll use the fig.subcap chunk option rather than fig.cap:
title: "Stack Overflow Answer"
author: "duckmayr"
header-includes:
- \usepackage{subcaption}
output: pdf_document
---
```{r histogram, fig.cap="Histograms", fig.subcap=c("Blah Blah $\\mathcal{MATH}$ (islands)", "Blah Blah $\\mathcal{MATH}$ (linx)"), out.width="45%"}
hist(islands, main = "")
hist(lynx, main = "")
```
A: You can add (limited) latex with latex2exp
install.packages("latex2exp")
You could use it like this:
library("latex2exp")
hist(islands, main =TeX('$\\alpha^5 - \\beta$'))
Which would look like:
Best is you take a look at the documentation page what kind of Latex formatting is possible with the package. | unknown | |
d11924 | train | You seem to display only the first 25 results at any time.
You need to initialize $counter to zero if it's the first page, to 26 if it's the second page, and so on :
$counter = 0;
if(isset($_GET['counter'])){
$counter = intval($_GET['counter']);
}
You need to modify your query to fetch a different set of results for each page :
$sql = 'SELECT id,name,logo FROM mytable ORDER BY name DESC LIMIT ' . mysqli_real_escape_string($db_conx, $counter . ',25');
$query = mysqli_query($db_conx,$sql);
Then I assume you display a link to the other paginated pages, you need to pass it the value of $counter :
<a href="results.php?counter=<?php echo $counter;?>">Next</a> | unknown | |
d11925 | train | Try this:
<?php
$now = new DateTime();
$startdate = new DateTime("2014-11-20");
$enddate = new DateTime("2015-01-20");
if($startdate <= $now && $now <= $enddate) {
echo "Yes";
}else{
echo "No";
}
?> | unknown | |
d11926 | train | Try to reload your project, maybe something wrong with R.java, or verify you are calling the good file with setContentView.
By refreshing/cleaning your project the R.java file will be reloaded and will find the named widgets.
A: I copied your code and made a dummy app. I got these results:
12-27 00:03:48.332: D/First(9165): class android.widget.TextView
12-27 00:03:48.332: D/Second(9165): class android.widget.TextView
12-27 00:03:48.332: D/Third(9165): class android.widget.ImageView
Apparently there is nothing wrong with the code
A: I've tried almost everything here, but nothing worked until I added a new component to the activity and, after running, noticing that the new component didn't show. It suggested my app wasn't updating with the runs. It worked by manually uninstalling the old version of the app an then running again. | unknown | |
d11927 | train | The declaration is required because you need to tell the compiler to reserve a slot in the vtable for that specific method starting from the base class in which it is declared (which is the type you could want to use when calling a method on a derived class)
Just to give you the idea let's make an example (which is not to be considered exactly what happens under the hood). Let's suppose you have three virtual methods in Base, one of which is pure,
class Base {
virtual void pure() = 0;
virtual void nonpure() { }
virtual void nonpure2() { }
};
so the Base vtable will look like
0 [ pure ] -> nothing
1 [ nonpure ] -> address of Base::nonpure
2 [ nonpure2] -> address of Base::nonpure2
now let's derive it with
class Derive : public Base {
virtual pure() override { }
virtual nonpure2() override { }
};
Derived vtable will look like
0 [ pure ] -> address of Derived::pure
1 [ nonpure ] -> address of Base::nonpure
2 [ nonpure2 ] -> address of Derived::nonpure2
When you then try to do
Base* derived = new Derived();
derived->pure();
The method is roughly compiled as
address = derived->vtable[0];
call address
If you don't declare the pure virtual method in the Base class there is no way to know its index in the vtable (0) in this case at compile time since the method is not present at all.
But, if the vtable has 'a hole' in it (an implementation is missing), you can't instantiate that specific class type.
A: You cannot instantiate an object of an abstract class. Which actually makes your question kinda meaningless: since you will never instantiate your abstract class, the virtual table for that class is not needed at all. (In reality it might be needed temporarily during construction/destruction, but this is a different story.)
When you actually instantiate an object, it is an object of some derived class, which is no longer abstract. It does not have any pure virtual functions anymore. The derived class that you actually instantiate has all pure virtual functions overridden by that time. This is why an entry is needed in the virtual method table - to store a pointer to the actual overrider function.
Later in your code, you might call myFunction() through a pointer to that abstract base class
MyAbstractBaseClass *ptr = some_function();
// Pointer actually points to some non-abstract derived object
ptr->myFunction();
The compiler will generate code that will go into the virtual method table associated with *ptr object, extract the pointer entry that corresponds to myFunction() and pass the control trough that pointer. As I said above, that pointer will actually point to an overriding function from some derived class. This is exactly what that entry was reserved for. | unknown | |
d11928 | train | It definitely needs to be Expression<Func<...>>. But instead of using Compile() method (not supported), you can resolve the compile time error using the AsQueryable() method which is perfectly supported (in EF6, the trick doesn't work in current EF Core).
Given the modified definition
private static Expression<Func<Return, ReturnValues>> MapToReturnValues =
r => new ReturnValues { ... };
the sample usage would be
Returns = f.Returns.AsQueryable().Select(MapToReturnValues).FirstOrDefault() | unknown | |
d11929 | train | //in your activity add this for button
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
//set the properties for button
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button");
btnTag.setId(some_random_id);
//add button to the layout
layout.addView(btnTag); | unknown | |
d11930 | train | In Javascript you can use document.querySelector along with href attribute, like this:
var url = document.querySelector('.central-featured-lang.lang1 a[href$=".org/"]').href;
alert(url);
<div class="central-featured-lang lang1" lang="en">
<a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box">
<strong>English</strong>
<br>
<em>The Free Encyclopedia</em>
<br>
<small>5 077 000+ articles</small>
</a>
</div>
A: Use the .attr() Method:
$('.central-featured-lang.lang1 a[href$=".org/"]').attr("href")
var url = $('.central-featured-lang.lang1 a[href$=".org/"]').attr("href");
alert( url );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="central-featured-lang lang1" lang="en">
<a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box">
<strong>English</strong><br>
<em>The Free Encyclopedia</em><br>
<small>5 077 000+ articles</small>
</a>
</div>
A: Use DOM Element getAttribute() Method
getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned
will either be null or "" (the empty string); see Notes for details.
var element = document.querySelector('a.link-box'),
link = element.getAttribute('href');
alert(link)
<div class="central-featured-lang lang1" lang="en">
<a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box">
<strong>English</strong>
<br>
<em>The Free Encyclopedia</em>
<br>
<small>5 077 000+ articles</small>
</a>
</div> | unknown | |
d11931 | train | Here. I made it into an [MCVE] for you. This one compiles.
You declared a type dataArray.
You didn't then go on to declare a signal (or variable or constant) of that type.
Assigning a member of a type (which is something abstract) to a real signal obviously won't work.
Assigning a member of a signal (etc) of that type, however, ...
library ieee;
use ieee.std_logic_1164.all;
entity instructionTranslator is
port(clk :in std_logic;
instructionCode :in std_logic_vector(4 downto 0);
instructionType:out std_logic_vector(1 downto 0) ;
data :out string (1 to 1)--here is data
);
end instructionTranslator;
architecture Translator of instructionTranslator is
type dataArray is array (0 to 13)of string(1 to 1);
signal da : dataArray;
begin
process(clk) is
begin
data<=da(1);
end process;
end Translator; | unknown | |
d11932 | train | easy_install doesn't like use of __file__ and __path__ not so much because they're dangerous, but because packages that use them almost always fail to run out of zipped eggs.
easy_install is warning because it'll install "less efficiently" into an unzipped directory instead of a zipped egg.
In practice, I'm usually glad when the zip_safe check fails, because then if I need to dive into the source of a module it's a ton easier.
A: I wouldn't worry about it. As durin42 notes, this just means that setuptools won't zip the egg when it puts it into site packages. If you don't want to see these messages, I believe you can just use the -Z flag to easy_install. That will make it always unzip the egg.
I recommend using pip. It gives you a lot less unnecessary output to deal with. | unknown | |
d11933 | train | This is probably down to operator precedence; AND has higher precedence than OR. So your condition:
WHERE RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL
is interpreted as
WHERE RJ_SAPID IS NOT NULL OR (RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL)
If you have a source row where OBJECTID is null then it will still pass than condition, and fail on insertion, if RJ_SAPID is anything except 'NA', including if that is null.
I believe you want:
WHERE (RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA') AND OBJECTID IS NOT NULL
so you need to include those parentheses in your statement.
A: i think your where condition should be improved. add '()' around your or condition
WHERE (RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA') AND OBJECTID IS NOT NULL; | unknown | |
d11934 | train | If I had to implement that, my first idea would be:
*
*Get merged file.
*Analyze diff to figure out which regions were changed.
*Generate a new file and inject #pragma directives1 that locally enable/disable warnings around the changed regions.
*Also inject #line directives to make it look like warnings/errors are coming from the original file.
*Compile modified file and save compiler warnings/errors.
*Delete modified file.
*Present compiler diagnostics to the user.
1 E.g. https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas for GCC.
A: Clang supports GCC's #pragma diagnostic.
For example:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
// ... changed code here ...
#pragma GCC diagnostic pop
MSVC also has something similar:
#pragma warning(push, 3)
// ... changed code here ...
#pragma warning(pop) | unknown | |
d11935 | train | In the main process, keep track of your subprocesses (in a list) and loop over them with .join(timeout=50) (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.join).
Then check is he is alive (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.is_alive).
If he is not, replace him with a fresh one.
def start_workers(n):
wks = []
for _ in range(n):
wks.append(WorkerProcess())
wks[-1].start()
while True:
#Remove all terminated process
wks = [p for p in wks if p.is_alive()]
#Start new process
for i in range(n-len(wks)):
wks.append(WorkerProcess())
wks[-1].start()
A: I would not handle the process pool management myself. Instead, I would use the ProcessPoolExecutor from the concurrent.future module.
No need to inherit the WorkerProcess to inherit the Process class. Just write your actual code in the class and then submit it to a process pool executor. The executor would have a pool of processes always ready to execute your tasks.
This way you can keep things simple and less headache for you.
You can read more about in my blog post here: http://masnun.com/2016/03/29/python-a-quick-introduction-to-the-concurrent-futures-module.html
Example Code:
from concurrent.futures import ProcessPoolExecutor
from time import sleep
def return_after_5_secs(message):
sleep(5)
return message
pool = ProcessPoolExecutor(3)
future = pool.submit(return_after_5_secs, ("hello"))
print(future.done())
sleep(5)
print(future.done())
print("Result: " + future.result()) | unknown | |
d11936 | train | This should do the job:
mkdir "$HOME/Documents/subd/vip"
You just had some minor errors in your command. | unknown | |
d11937 | train | You have not included what back end system you are using, which is relevant information. However, with PHP and ASP.NET MVC I've discovered a similar behavior. I believe you are describing disabled/readonly inputs sending null values to the back end controller. In the past, I've found that I had to re-enable inputs with Javascript before submitting them to the controller. The jquery to do this is:
$("input[type='submit']").click(function(e){
e.preventDefault();
$("input").removeProp('readonly');
$("form").submit();
});
However, if the field is always static, you may just want to hard code it on the back end.
I'd also recommend you check out the w3 specification on disabled elements to make sure the readonly attribute is the correct attribute for you. You are currently using the readonly attribute incorrectly, as it is a boolean attribute.
<input readonly="readonly">
should be:
<input readonly> | unknown | |
d11938 | train | You need to understand the difference between private and public data. Public data is data that is not owned by any user and is available publicly.
Methods like Search List for example access public data available on YouTube.
Private data is data that is owned by a user. In order to upload to your YouTube account you need permission to upload to that account.
The Videos.insert method as you can see by the documentation requires that the user have consented to your application accessing their YouTube account. They must have consented to your access with one of the following scopes.
So the answer to your question is that you cant. You need to consent to authorization before your application is going to be allowed to upload to YouTube
upload public videos
Please remember that all videos uploaded via the videos.insert endpoint from unverified API projects created after 28 July 2020 will be restricted to private viewing mode. To lift this restriction, each API project must undergo an audit to verify compliance with the Terms of Service. Please see the API Revision History for more details.
Your application will need to go though application verificatin process before any of the videos you upload will be public | unknown | |
d11939 | train | As d. correctly mentioned the built-in designer does not truly represent your view.
And if we keep in mind that even after 4 years of trying, Microsoft's equivalent for their XAML code still doesn't reach minimum usefulness level, I would strongly recommend to go manual. It's faster, much more difficult but equally rewarding. Once you get a hang of editing the XML files manually the development becomes much easier and WAY faster in my humble opinion.
Regards
A: This answer is very late to the game but each new release of the Eclipse Android plugin improves the layout GUI editor. The one released yesterday (9.0.0) is light years ahead of the original tools which were awful.
A: The form designer is part of the Android Development Tools (ADT) Plugin for Eclipse which comes with the Android SDK.
A: Google has not announced any plans for a wysiwyg designer for Android app development. However, there is a tool available for this. Check out this link http://www.designerandroid.com/?p=165 | unknown | |
d11940 | train | In general, the most popular way to run tasks in Python is using Celery. It is a Python framework that runs on a separate process, continuously checking a queue (like Redis or AMQP) for tasks. When it finds one, it executes it, and logs the result to a "result backend" (like a database or Redis again). Then you have the Flask servers just push the tasks to the queue.
In order to notify the users, you could use polling from the React app, which is just requesting an update every 5 seconds until you see from the result backend that the task has completed successfully. As soon as you see that, stop polling and show the user the notification.
You can easily have multiple worker processes run in parallel, if the app would become large enough to need it. In general, you just need to remember to have every process do what it's needed to do: Flask servers should answer web requests, and Celery servers should process tasks. Not the other way around. | unknown | |
d11941 | train | Unfortunately no! CSV files are basically raw cell data, with no formatting at all.
If you would like to have some styling you would need to learn one of the following formats. But that would be much more complicated.
*
*Office Open XML — for Excel 2007 and above
*Excel 2003 XML — for Excel 2003 and above
*Open Document Format (.ods) — can be read by Excel 2010. | unknown | |
d11942 | train | Adding a dummy read of 1 byte just after calling the init function allowed me to successfully read once without Timeouts. The problem is that after that, the Receive() function starts again to return Timeouts. The only workaround I could find was to re-init the UART just before calling the Receive() function. This allows me to retrieve the full message. It is sloppy, but it works.
I tried to find the registers that change but I was not able to isolate what is causing the problem. | unknown | |
d11943 | train | Following @loremipsum's suggestion, I replaced the mainColor property of the Theme enumeration with
var mainColor: Color {
switch self {
case .bubblegum: return Color(red: 0.933, green: 0.502, blue: 0.820)
case .buttercup: return Color(red: 1.000, green: 0.945, blue: 0.588)
case .indigo: return Color(red: 0.212, green: 0.000, blue: 0.443)
case .lavender: return Color(red: 0.812, green: 0.808, blue: 1.000)
case .magenta: return Color(red: 0.647, green: 0.075, blue: 0.467)
case .navy: return Color(red: 0.000, green: 0.078, blue: 0.255)
case .orange: return Color(red: 1.000, green: 0.545, blue: 0.259)
case .oxblood: return Color(red: 0.290, green: 0.027, blue: 0.043)
case .periwinkle: return Color(red: 0.525, green: 0.510, blue: 1.000)
case .poppy: return Color(red: 1.000, green: 0.369, blue: 0.369)
case .purple: return Color(red: 0.569, green: 0.294, blue: 0.949)
case .seafoam: return Color(red: 0.796, green: 0.918, blue: 0.898)
case .sky: return Color(red: 0.431, green: 0.573, blue: 1.000)
case .tan: return Color(red: 0.761, green: 0.608, blue: 0.494)
case .teal: return Color(red: 0.133, green: 0.561, blue: 0.620)
case .yellow: return Color(red: 1.000, green: 0.875, blue: 0.302)
}
}
copying the RGB values for the themes from the .json asset files. This has fixed the problem and now colors appear as intended.
What I don't understand is why SwiftUI couldn't process Color(rawValue) for the example data used in CardView(), which was DailyScrum(title: "Design", attendees: ["Cathy", "Daisy", "Simon", "Jonathan"], lengthInMinutes: 10, theme: .yellow). Sure, .periwinkle might not be previously defined, but .yellow certainly is. In fact, if I rewrite mainColor from Color(rawValue) to Color(.yellow), I get all cards colored yellow without having to pass any RGB value.
So what's Color(rawValue) getting from the enumeration that it's unable to process .yellow when passed from rawValue? | unknown | |
d11944 | train | The first regex group is greedy (.*) and is matching everything, you can make it non-greedy by adding ?, i.e.:
file = open('tcpdump.txt', 'r');
for line in file:
matchObj = re.match(r"->\s(.*?)\s(\w+)\s(.*?)\s", line, re.M)
The above example is will capture 3 groups containing the remote address 114.113.226.43, protocol TCP and port 54 respectively.
Regex101 Demo
A: Start by look at the regex documentation, for python it is here:
https://docs.python.org/3/library/re.html
There are also many sites that have good tutorials, samples and interactive testers such as:
http://regexr.com/
I don't know the output format of wireshark, but I would imagine it is documented somewhere.
This should get your ip addresses:
\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b
A: As people have already responded, regex is the way to go. A sample code for the purpose
import unittest
import re
from collections import namedtuple
protocol = namedtuple('Protocol', ['source', 'destination', 'protocol'])
def parse_wireshark(input):
pat = re.findall(r"(\d+\.\d+\.\d+\.\d+) -> (\d+\.\d+\.\d+\.\d+) (\w+)", input)[0]
return protocol(source=pat[0], destination=pat[1], protocol=pat[2])
class TestWireShark(unittest.TestCase):
def test_sample(self):
self.assertEqual(parse_wireshark("604 1820.381625 10.200.59.77 -> 114.113.226.43 TCP 54 ssh > 47820 [FIN, ACK] Seq=1848 Ack=522 Win=16616 Len=0"),
protocol(source='10.200.59.77',
destination='114.113.226.43',
protocol='TCP'))
if __name__ == '__main__':
unittest.main() | unknown | |
d11945 | train | You can choose the work item types to make some fields read only.
You will never need to be careful to not mark field read only that are needed for adding items. That would include area and iteration. Use witadmin.exe to export the desired work item and add read only clauses only for those in the stakeholder group.
You would be better with a permissive model. Allow everything and tell them what bout to change. Then have an alert for changes to those fields by stakeholders. | unknown | |
d11946 | train | The same way you get the image from the you can get the PHImageManager, you can get all such images and just attach to mail.
Or if you want to attach ALL images, then you can add all the loaded images to an array and attach those to mail like:
let asset : PHAsset = self.photoAsset[indexPath.item] as! PHAsset
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info)in
if let image = result
{
cell.setThumbnailImage(image)
self.arr.append(image)
}
})
Then add all the images from the arr to mail composer, like
func composeMail() {
let mailComposeVC = MFMailComposeViewController()
for image in arr {
let photoData : NSData = UIImagePNGRepresentation(image)!
mailComposeVC.addAttachmentData(UIImageJPEGRepresentation(photoData, CGFloat(1.0))!, mimeType: "image/jpeg", fileName: "test.jpeg")
}
mailComposeVC.setSubject("Email Subject")
self.presentViewController(mailComposeVC, animated: true, completion: nil)
} | unknown | |
d11947 | train | You need to add a fields or exclude attribute to the form class
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ['name']
Seems like you don't have a model named Category in that case you should inherit from forms.Form
class CategoryForm(forms.Form):
name = forms.CharField(max_length=128, help_text="Please enter the category name.") | unknown | |
d11948 | train | If you just want to skip a commit, do git rebase -i master and select drop for the commit to be skipped. If you just want to remove a single file from it, select edit and amend the commit to remove the file.
A: *
*You can use the squash
*BFG
*Move HEAD back to previous commit (link)
squash
# edit all the commits up to the given sha-1
git rebase -i <sha-1>
but one of the file being very large my push command fails...
How to remove big files from the repository
You can use git filter-branch or BFG.
https://rtyley.github.io/bfg-repo-cleaner/
BFG Repo-Cleaner
an alternative to git-filter-branch.
The BFG is a simpler, faster alternative to git-filter-branch for cleansing bad data out of your Git repository history:
* Removing Crazy Big Files*
* Removing Passwords, Credentials & other Private data
Examples (from the official site)
In all these examples bfg is an alias for java -jar bfg.jar.
# Delete all files named 'id_rsa' or 'id_dsa' :
bfg --delete-files id_{dsa,rsa} my-repo.git
A: If you just want to remove the file then why not just do that by deleting the file and then committing the change?
Now, in your latest commit the file doesn't exist.
You should now be able to push your branch to the remote without any problem.
A: what you can do is you can use git rebase option and squash all the commits. | unknown | |
d11949 | train | These two commands gave me good output. I have no idea why they worked over the commands I put in above. I just kept tinkering with things until it worked.
Xvfb $DISPLAY -screen 0 1920x1080x24 &
ffmpeg -y -probesize 200M -f x11grab -video_size 1920x1080 -i "$DISPLAY" out.webm & | unknown | |
d11950 | train | Simple way !
public static boolean isConnectingToInternet(@NonNull Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null) {
if (info.getType() == ConnectivityManager.TYPE_WIFI || info.getType() == ConnectivityManager.TYPE_MOBILE || info.getType() == ConnectivityManager.TYPE_ETHERNET || info.getType() == ConnectivityManager.TYPE_WIMAX) {
return true;
}
}
}
return false;
}
How to use just check
if (!isConnectingToInternet(getContext())) {
// here no internet connection
}
A: you can use getActiveNetworkInfo() instead of getnetworkinfo , because there were some other factors which weren't considered before ,like network state can vary app to app while using getnetworkinfo hence deprecated docs
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if(activeNetwork!=null && activeNetwork.isConnectedOrConnecting()){
// yeah we are online
}else{
// oops! no network
}
Note : put a nullity check too to confirm it is not null before accessing the network status
A: public class NetworkUtils {
public static boolean isConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
return (activeNetwork != null)
&& activeNetwork.isConnectedOrConnecting();
}
}
Use this class to check network connection as:
if(NetworkUtils.isConnected(getContext())) {
//Call your network related task
} else {
//Show a toast displaying no network connection
}
A: Use ConnectivityManager to get network access. you can use BroadcastReceiver to get constant updates of your network status.
package your_package_name;
import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectivityStatus extends ContextWrapper{
public ConnectivityStatus(Context base) {
super(base);
}
public static boolean isConnected(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo connection = manager.getActiveNetworkInfo();
if (connection != null && connection.isConnectedOrConnecting()){
return true;
}
return false;
}
}
Receive updates from your network class, use this in your main class where to update status.
Register Receiver on class
getContext().registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(!ConnectivityStatus.isConnected(getContext())){
//not connected
}else {
//connected
}
}
}; | unknown | |
d11951 | train | You can change your key to use the newuuid() function. e.g.
a/b/${newuuid()}
This will write the data to a file in the a/b folder with a filename that is a generated UUID.
The key in AWS IoT S3 Actions allow you to use the IoT SQL Reference Functions to form the folder and filename.
The documentation for the key states:
The path to the file where the data is written. For example, if the value of this argument is "${topic()}/${timestamp()}", the topic the message was sent to is "this/is/my/topic,", and the current timestamp is 1460685389, the data is written to a file called "1460685389" in the "this/is/my/topic" folder on Amazon S3.
If you don't want to use a timestamp then you could form the name of the file using other functions such as a random float (rand()), calculate a hash (md5()), a UUID (newuuid()) or the trace id of the message (traceid()). | unknown | |
d11952 | train | You're doing your final echo INSIDE the main while() loop:
while(..) {
while(..) { .. }
echo ..
}
It should be
while(..) {
while(..) { .. }
}
echo ..
Since you're echoing INSIDE the main loop, you'll be running that echo multiple times, spitting out $galeri as it's being built.
A: Try this:
i have added mysq_free_result and echo must be outside the while !
<?php
$cek = mysql_query('select id,isim,aciklama,tarih from galeri where dil = '.$dbDil.' order by id desc');
while($kaynak = mysql_fetch_assoc($cek)){
$cekG = mysql_query('select resim_url from galeriresim where galeriID = '.$kaynak['id'].' order by id desc');
$galeri .= '<h1 class="sayfaBaslik fl"><span>'.$kaynak['tarih'].'</span> '.$kaynak['isim'].'</h1>';
$galeri .= '<h2 class="sayfaAciklama fl">'.$kaynak['aciklama'].'</h2>';
$galeri .= '<div class="sayfaIcerik" style="width:100%">';
$galeri .= '<div class="galeriH fl swiper-container-'.$kaynak['id'].'">';
$galeri .= '<ul class="fl swiper-wrapper-'.$kaynak['id'].'">';
while($kaynakG = mysql_fetch_assoc($cekG)){
$galeri .= '<li class="swiper-slide-'.$kaynak['id'].'"><img src="'.$yol.'images/galeri/'.$kaynak['id'].'/'.$kaynakG['resim_url'].'" /></li>';
}
mysql_free_result($cekG);
$cekG ="";
$galeri .= '</ul></div></div>';
$galeri .='<script>';
$galeri .= 'var mySwiper = new Swiper(\'.swiper-container-'.$kaynak['id'].'\',{';
$galeri .= 'moveStartThreshold : 75,';
$galeri .= 'wrapperClass : "swiper-wrapper-'.$kaynak['id'].'",';
$galeri .= 'slideClass : "swiper-slide-'.$kaynak['id'].'"';
$galeri .= '});';
$galeri .= '</script>';
}
echo $galeri;
?>
A: Use a JOINed query then you wouldn't need a double while loop. you shouldnt be using mysql anyway. Use mysqli or pdo
'select g.id,g.isim,g.aciklama,g.tarih, gr.resim_url
from galeri g
JOIN galeriresim gr on gr.galeriID = g.id
where g.dil = '.$dbDil.' order by id desc' | unknown | |
d11953 | train | I found a perfect solution in this blog. https://medium.com/coinmonks/a-box-detection-algorithm-for-any-image-containing-boxes-756c15d7ed26
Here,We are doing morphological transformations using a vertical kernel to detect vetical lines and horizontal kernel to detect horizontal lines and then combining them to get all the required lines.
Vertical lines
Horizontal lines
required output
A: The problem is and always will be is that you don't have perfect lines.
One solution for this approach can be:
*
*Threshold image to grayscale as you have done.
*Now find the largest contour in the image, which will be your table.
*Now use Floodfill to separate table from the image, by choosing any point on contour to create a flooded mask,
A: The problem might be in HoughLinesTransform()
You can try using: HoughLinesTransformP()
For HoughLinesTranform() to work perfectly, the lines need to be perfect. From the image you have provided, you can see the distortion clearly which is clearly causing the method to fail.
Try dilating your image first. Image Dilation in Python. | unknown | |
d11954 | train | this actually done with JavaScript and all you have to do is add this jquery code in your script
$('.dropdown-toggle').hover(function() {
$(this).parent().addClass("open");
});
$('.dropdown').mouseleave(function() {
$(this).removeClass("open");
});
and you have to remove display: none; from the class .dropdown-menu for the animation to work
see your example here
you can also make it work with CSS only by adding this code:
.dropdown:hover>.dropdown-menu-animated{
visibility: visible;
opacity: 1;
transition: opacity .5s, -webkit-transform .5s;
transition: opacity .5s, transform .5s;
transition-timing-function: cubic-bezier(0.2, 1, 0.3, 1);
-webkit-transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
}
See your example with CSS only
A: The following snippet solves your styling issue for the :hover appearance.
Add your transition effect in the .dropdown .dropdown-menu-animated rules and there you go ;)
.dropdown {
float: left;
cursor: pointer;
}
.dropdown .dropdown-menu-animated {
border: 0 none;
box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
margin-top: 20px;
transform: scale3d(0.95, 0.95, 1) translate3d(0px, -15px, 0px);
transform-origin: 100% 0 0;
transition-delay: 0s, 0s, 0.5s;
transition-duration: 0.5s, 0.5s, 0s;
transition-property: opacity, transform, visibility;
transition-timing-function: cubic-bezier(0.7, 0, 0.3, 1);
visibility: hidden;
}
.dropdown:hover .dropdown-menu-animated {
visibility: visible;
}
<div id="bs-example-navbar-collapse-1" class="collapse navbar-collapse right">
<ul class="nav navbar-nav navbar-left">
<li class="dropdown">
HOVER ME
<ul class="dropdown-menu-animated" role="menu">
<li>
<a href="/points">Sushi Points</a>
</li>
<li><a href="/points">Two</a></li>
</ul>
</li>
</ul>
</div> | unknown | |
d11955 | train | Try inspecting the $_FILES array to see the structure of a single file upload and a mulit-file upload.
Here is a small function you can use to visually inspect an array:
function varDumpToString($var, $type=false){
ob_start();
var_export($var);
$return = ob_get_clean();
return ($type === 'web'
? str_replace("\n", '<br/>', $return)
: $return
);
}
Usage:
echo varDumpToString($_FILES, 'web');
Alternatively:
error_log(varDumpToString($_FILES)); | unknown | |
d11956 | train | migrate is a simply an (undocumented) alias for update:
687 if (this.command.equalsIgnoreCase("migrate")) {
688 this.command = "update";
689 }
liquibase.integration.commandline.Main | unknown | |
d11957 | train | Put this in your Rakefile above require 'rake':
require 'rake/dsl_definition'
OR if the above solution does not work,
write this in your gemfile for rake
gem "rake", "0.8.7"
and go to command prompt and write.
gem uninstall rake
This will uninstall the existing rake gem.
Then type bundle update in your project folder which will install rake 9.8.7 again.
And enjoy rails :). | unknown | |
d11958 | train | Without the details you have code like this
def extractFrames(m):
# do stuff
vid_files=glob(m)
for v_f in range(len(vid_files)):
#find vid_name
#do stuff
save_as_done(vid_name)
if __name == '__main__':
x="C:\\Python36\\videos\\*.mp4"
extractFrames(x)
If you pass in a list of things that have been done, something like
done = ['first.mp4', 'second.mp4']
you can check if a filename has been done like this:
>>> 'first.mp4' in done
True
So, if you save the filenames (fully pathed) of what you've done to a file and load them into a list, like this
def load_done_list():
with open('video_info.csv') as f: #or full path, maybe pass in the file name?
return f.readlines()
you can check the list
def extractFrames(m, done):
# do stuff
vid_files=glob(m)
for v_f in range(len(vid_files)):
#find vid_name
if vid_name not in done: #,--- check if done already
#do stuff
save_as_done(vid_name)
if __name == '__main__':
x="C:\\Python36\\videos\\*.mp4"
done = load_done_list() #<--- You need to load this into a list
extractFrames(x, done) #<--- and pass it in to your function
This need something that just saves the filenames as they are done:
def save_as_done(vid_name):
with open('video_info.csv', 'a') as f: #maybe pass in the file name so you only define it once?
f.write(vid_name + '\n')
I haven't filled in all the details, but have shown where you can do loading and saving and checking.
The written file only has the filenames in - there doesn't seem much point in having "done" on the end of each line.
This will keep opening and closing the file as the files are processed. This may slow thing down but might not matter: you could pass in a file handle to write to, to keep it open. You have options.
A: I think you might need a function to get the list completed/done videos from the csv file.
Something like this, might need to tweak a bit for the header row.
def get_completed_videos():
completed_videos = []
with open(".../video_info.csv") as csv_file:
for row in csv.reader(csv_file):
completed_videos.append(row[0])
return completed_videos
Then exclude them in the extracting func
def extractFrames(m):
global vid_name
vid_files=glob(m)
complete_videos = get_completed_videos()
new_vid_files = [x for x in vid_files if x not in complete_videos]
...
A: def extractFrames(m,done):
global vid_name
vid_files=glob(m)
for v_f in range(len(vid_files)):
print("path of video========>>>>.",vid_files[v_f])
v1=os.path.basename(vid_files[v_f])
vid_name = os.path.splitext(v1)[0]
if vid_name not in done:
try:
vidcap = cv2.VideoCapture(vid_files[v_f])
except cv2.error as e:
print(e)
except:
print('error')
#condition
fsize=os.stat(vid_files[v_f])
print('=============size of video ===================:' , fsize.st_size)
try:
if (fsize.st_size > 1000):
fps = vidcap.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frameCount/fps
minutes = int(duration/60)
print('fps = ' + str(fps))
print('number of frames = ' + str(frameCount))
print('duration (S) = ' + str(duration))
if (duration > 1):
success,image = vidcap.read()
count=0
success=True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count % 10 == 0 or count ==0:
target_non_target(img_name, image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
except:
print("error")
print('finished processing video ', vid_files[v_f])
with open("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs\\"+'video_info.csv', 'a') as csv_file:
fieldnames = ['Video_Name','Process']
file_is_empty = os.stat("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs\\"+'video_info.csv').st_size == 0
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
if file_is_empty:
writer.writeheader()
writer.writerow({'Video_Name':vid_name,'Process':'done'})
if __name__ == "__main__":
x="C:\\Python36\\videos\\*.mp4"
y="C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs\\video_info.csv"
done=list(y)
extractFrames(x,done) | unknown | |
d11959 | train | Try this when you open the dialog :
newNum.ShowDialog()
if (newNum.DialogResult == DialogResult.OK)
{
}
DialogResult.OK cannot be compared to a .showDialog() I guess.
You must compare the DialogResult property of your form, with the value DialogResult.OK, not the .showDialog().
A: I manage to fix it thanks for the help. The error comes from the line
datagridview1.Rows.Add(val[0], 0, val[1], new DataGridViewComboBoxCell(), 4, 0);
I change it to
datagridview1.Rows.Add(val[0], 0, val[1], null, 4, 0);
and it worked. | unknown | |
d11960 | train | There is no out-of-the-box functionality for copying constraints from one model to another in Hibernate Validator, but you could implement it yourself using existing APIs.
More specifically, there is an API for retrieving constraint metadata (standardized by Bean Validation) and an API for dynamically putting constraints to your types at runtime (provided by Hibernate Validator). You could use the former to read the constraints of your domain model and drive the creation of equivalent constraints on your DTO model using the latter. For that you'd of course need a strategy for matching corresponding types and properties of your source and target model. | unknown | |
d11961 | train | You can use pd.cut to categorize the time in df2 into discrete intervals based on the time in df1 then use Series.factorize to obtain a numeric array identifying distinct ordered values.
df2['interval'] = pd.cut(df2['time'], df1['time'], include_lowest=True)\
.factorize(sort=True)[0] + 1
Result:
time value var2 interval
0 1.0 23.0 23.0 1
1 2.0 43.0 43.0 1
2 3.0 76.0 12.0 1
3 4.0 88.0 22.0 1
4 5.0 64.0 45.0 2
5 6.0 98.0 33.0 2
6 7.0 76.0 11.0 2
7 8.0 56.0 44.0 2
8 9.0 23.0 22.0 2
9 10.0 54.0 44.0 3
10 11.0 65.0 22.0 3
11 12.0 25.0 25.0 3 | unknown | |
d11962 | train | After binding you are directly taking the channel from the future, but it probably hasn’t finished at that point.
Try to wait for your bind to complete with bind(port).sync().
See for reference https://www.baeldung.com/netty#6-server-bootstrap and https://netty.io/4.1/api/io/netty/channel/ChannelFuture.html | unknown | |
d11963 | train | You have to use same way as you create one and then update it with whatever you need by using this method:
NotificationManagerCompat.notify()
Read the details here:
https://developer.android.com/training/notify-user/build-notification
You need to use the same Notification id for when creating and when updating. | unknown | |
d11964 | train | Are you using an Eclipse plug-in for your version control system of choice? They seem to take care of everything (at least in my experience with the CVS and Mercurial plugins). If not, you'll need to tell Eclipse to refresh pretty much your whole project whenever you've interacted with version control.
The contents of the Debug and Release directories should all be autogenerated. If they're not, something's wrong.
Rather than what you can delete, turn it around and consider what you need to keep:
*
*.project, .cproject and (if it exists) .settings
*Your source directories
*Your include directories
*Any other human-created files at the top level e.g. Changelog, documentation
It may also be worthwhile looking inside the .metadata directory in your workspace root; for example, any launch configurations you have created are stored by default in .metadata/.plugins/org.eclipse.debug.core/.launches/ . (Although I have seen them inside project directories from time to time.) | unknown | |
d11965 | train | float makes that the element has no height anymore, which causes all kinds of 'funny' stuff. I think you are searching for display: table and display: table-cell. Otherwise you can use clear: left; or clear: both on the element that should be displayed under the left-floating elements.
To get the display: table and display: table-cell working, you'll have to remove one div-wrapper around each column.
<div id="article">
<div>
<div><?php echo $item->fields_by_id[3]->result; ?></div>
</div>
<div>
<div><b>Author:</b></div>
<div><b>Publisher:</b></div>
<div><b>Genre:</b></div>
<!-- etc -->
</div>
</div>
Then use the following CSS:
#article {
display: table;
}
#article > div {
display: table-cell;
} | unknown | |
d11966 | train | Try to check if $('.check') element is not inside of button or other HTML attribute.
For me the problem was:
<button type="button" class="btn btn-default icheck-button">
<input id="check-all" type="checkbox" aria-label="...">
</button>
So i removed button attribute. | unknown | |
d11967 | train | In your controller write a query something like
$cu = current_user_id // you'll have to set this your self from a session variable etc
$q = Doctrine_Query::create()
->select('p.pais')
->from('Model_Pais p')
->leftJoin('p.Model_UsersHasPais s')
->leftJoin('s.Model_Users u')
->where('u.id = ?',$cu);
$result = $q->fetchArray(); | unknown | |
d11968 | train | No, POST responses are never cached:
if request.method not in ('GET', 'HEAD'):
request._cache_update_cache = False
return None # Don't bother checking the cache.
(from FetchFromCacheMiddleware in django.middleware.cache).
You'll have to implement something yourself using the low-level cache API. It's most unusual to cache a response to a POST request, since a POST request is meant to change things in the database and the result is always unique to the particular request. You'll have to think about what exactly you want to cache.
A: I ended up creating a custom decorator which caches responses based on request path, query parameters, and posted data:
# myproject/apps/core/caching.py
import hashlib
import base64
from functools import wraps
from django.core.cache import cache
from django.conf import settings
def make_hash_sha256(o):
hasher = hashlib.sha256()
hasher.update(repr(make_hashable(o)).encode())
return base64.b64encode(hasher.digest()).decode()
def make_hashable(o):
if isinstance(o, (tuple, list)):
return tuple((make_hashable(e) for e in o))
if isinstance(o, dict):
return tuple(sorted((k,make_hashable(v)) for k,v in o.items()))
if isinstance(o, (set, frozenset)):
return tuple(sorted(make_hashable(e) for e in o))
return o
def cache_get_and_post_requests(duration=600):
def view_decorator(view):
@wraps(view)
def view_wrapper(request, *args, **kwargs):
# TODO: make the key also dependable on the user or cookies if necessary
cache_key = "-".join((
settings.CACHE_MIDDLEWARE_KEY_PREFIX,
make_hash_sha256((
request.path,
list(request.GET.items()),
list(request.POST.items()),
request.body,
)),
))
cached_response = cache.get(cache_key)
if cached_response:
return cached_response
response = view(request, *args, **kwargs)
cache.set(cache_key, response, duration)
return response
return view_wrapper
return view_decorator
Then I can use it in the URL configuration like so:
# myproject/urls.py
from django.urls import path
from django.conf.urls.i18n import i18n_patterns
from graphene_django.views import GraphQLView
from myproject.apps.core.caching import cache_get_and_post_requests
urlpatterns = i18n_patterns(
# …
path("graphql/", cache_get_and_post_requests(60*5)(GraphQLView.as_view(graphiql=True))),
) | unknown | |
d11969 | train | if you want to uninstall
you can do rpm -e yum
then
Install it using:
rpm -ivh yum-(version).rpm
If yum is working fine for local installations, but it's not able to access Red Hat Network, verify if the following packages are installed. If not, install them:
rhnsd
yum-rhn-plugin
yum-security
rhn-check
rhn-setup
rhn-setup-gnome
yum-downloadonly
rhn-client-tools
rhn-virtualization-common
rhn-virtualization-host
pirut
yum-updatesd | unknown | |
d11970 | train | I'm going to modernize this a bit. Inline event handlers listeners are not the way to go these days. I'' use addEventListener instead.
Next, I'm going to use one lot of code to handle the actions. One concept to get used to as you learn to program is DRY: Don't Repeat Yourself. To facilitate the state of your playback I'll use a data attribute on the button
/*Get the buttons*/
document.querySelectorAll(".playPause").forEach(function(el) {
/*Add a click event listener*/
el.addEventListener("click", function() {
/*Get the first audio tag in the clicked button*/
var aud = this.querySelector("audio");
/*Check the data attirbute on the button if playing*/
if (this.dataset.isplaying === "true") {
/*Debug line*/
console.log("Pausing " + aud.src)
/*Change the status of the data attribute*/
this.dataset.isplaying = "false";
/*Pause the audio element*/
aud.pause();
} else {
/*Debug line*/
console.log("Playing " + aud.src)
/*Change the status of the data attribute*/
this.dataset.isplaying = "true";
/*PLay the audio element*/
aud.play();
}
})
});
<button id="ASong" class="playPause" data-isplaying="false">
<audio
src="mp3/Persona_5_OST-_Beneath_the_Mask_(getmp3.pro).mp3"
autoplay
loop
></audio>
<img src="img/musica2.png" width="100px" align="left" margin-top="40px">
</button>
<button id="ASong2" class="playPause" data-isplaying="false">
<audio
src="mp3/Persona_5_OST_-_Beneath_the_Mask_r_(getmp3.pro).mp3"
autoplay
loop
></audio>
<img src="img/musica2.png" width="100px" align="left" margin-top="40px">
</button> | unknown | |
d11971 | train | Since you're explicitly passing an UNICODE string, I'd suggest you also explicitly call OutputDebugStringW().
Otherwise, if the UNICODE preprocessor symbol is not defined in your compilation unit, the ANSI version of the function (OutputDebugStringA()) would end up being called with an UNICODE string, which it does not support, and it should result in a compilation error.
EDIT: You cannot use OutputDebugString() to write a string in your application's status bar. OutputDebugString() only sends the string you pass to the debugger.
You have to use the appropriate API to write text to the status bar instead. In your case, wxStatusBar::SetStatusText() should do the trick. | unknown | |
d11972 | train | If your variable is affected after being declared (e.g. anytime you write "b = "123") then it is not effectively final.
In inner class or nested class (such as your class A), you can only reference variable from the outer scope (such as b) that are effectively final.
The same restriction applies to constructs that are derived from nested classes such as lambdas.
Declaring a variable with the "final" keyword is a convenient way to be sure that you variable is effectively final. | unknown | |
d11973 | train | I think this is a valid approach. We are doing something similar with multiple indexes at our location. For example we have 4 different types of items in our database that we are loading into a common schema in the index and we prefix the database table id with the first two unique letters of the type to ensure that it will be unique.
Also IMO, indexing multiple distinct types in one index is really a preference and not a rule of thumb as indicated in the links below
*
*Single schema versus multiple schemas in solr for different document types
*Running Multiple Indexes
A: Typically one POJO will correspond to one schema and one Solr core. I am not sure why you would want to index different POJOs into one Solr core.
But with that said, your class name approach should work fine. Else you can declare a static CLASS_ID field in each one of your classes, keep them different for different classes and form the Solr document ID by concatenating like id:CLASS_ID. | unknown | |
d11974 | train | You can actually use a debugger to see how the numbers progress and why for example the square root of 234 causes an unending loop when epsilon is not multiplied by t.
I have used IntelliJ with a logging breakpoint to see how the numbers progress and why the unending loop happens:
First I have used this expression in the logging breakpoint:
" " + Math.abs(t - c/t) + " " + epsilon
for this code:
private static void calcRoot(String arg) {
// read in the command-line argument
double c = Double.parseDouble(arg);
double epsilon = 1.0e-15; // relative error tolerance
double t = c; // estimate of the square root of c
// repeatedly apply Newton update step until desired precision is achieved
while (Math.abs(t - c/t) > epsilon ) {
t = (c/t + t) / 2.0;
}
// print out the estimate of the square root of c
System.out.println(t);
}
and this is the result proving that actually epsilon is smaller than Math.abs(t - c/t) and this Math.abs(t - c/t) stops in its progression:
233.0 1.0E-15
115.50851063829788 1.0E-15
55.82914775415816 1.0E-15
24.47988606961853 1.0E-15
7.647106514310517 1.0E-15
0.927185521197492 1.0E-15
0.014043197832668497 1.0E-15
3.2230278765865705E-6 1.0E-15
1.723066134218243E-13 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
...
If I then use epsilon * t I and update the logging expression to " " + Math.abs(t - c/t) + " " + epsilon * t I can see a totally different console output:
233.0 2.34E-13
115.50851063829788 1.175E-13
55.82914775415816 5.974574468085106E-14
24.47988606961853 3.1831170803771985E-14
7.647106514310517 1.959122776896272E-14
0.927185521197492 1.5767674511807463E-14
0.014043197832668497 1.5304081751208715E-14
3.2230278765865705E-6 1.529706015229238E-14
1.723066134218243E-13 1.5297058540778443E-14
Update
If you try the same thing with the BigDecimal class, you will be able to calculate the square root of 234 in case you choose enough rounding digits (see the scale variable below):
private static void calcRootBig(String arg) {
// read in the command-line argument
BigDecimal c = new BigDecimal(arg);
BigDecimal epsilon = new BigDecimal(1.0e-15); // relative error tolerance
BigDecimal t = new BigDecimal(c.toString()); // estimate of the square root of c
BigDecimal two = new BigDecimal("2.0");
// repeatedly apply Newton update step until desired precision is achieved
int scale = 10;
while (t.subtract(c.divide(t, scale, RoundingMode.CEILING)).abs().compareTo(epsilon) > 0) {
t = c.divide(t, scale, RoundingMode.CEILING).add(t).divide(two, scale, RoundingMode.CEILING);
}
// print out the estimate of the square root of c
System.out.println(t);
}
Yet if you choose just 3 for the rounding scale, you will be caught up again in an unending loop.
So it seems that it is the precision of the floating point division which is actually causing the unending loop in your case. The multiplication of epsilon * t is just a trick to overcome the lack of rounding precision in the default floating point operations.
A: double has around 15 digits of precision (or 1 to 2^52 or 4.5e15). When you calculate t * epsilon you around requiring an error of 1 to 1e15/234 ratio which is possible with double, when you use epsilon you are requiring a ratio of 1 to 1e15 which is at the limits of the precision of double unless it's an exact value and the error is 0. e.g. try this for 256 and it might work, but anything which is not an exactly value probably doesn't.
A simple solution to an arbitrary end point is to stop once the error doesn't improve from one iteration to the next. This is will give you the most accurate solution using this formula possible. | unknown | |
d11975 | train | The AppBar and TabBar widgets do not allow to set a gradient, just a color.
To achieve what you need you can create a custom widget GradientAppBar or GradientTabBar built with a Stack that integrates a Container with a gradient and an AppBar or TabBar.
You create the GradientAppBar with parameters that would go to the Container and to the AppBar itself.
Here is a working example for Gradient AppBar. Below is a similar example just for the TabBar.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new Policy(),
);
}
}
class Policy extends StatefulWidget {
@override
_PolicyState createState() => _PolicyState();
}
class _PolicyState extends State<Policy> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
appBar: GradientAppBar(
colors: [Colors.white, Colors.black],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
elevation: 4.0,
bottom: TabBar(
indicatorColor: Colors.white,
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
title: Center(child: Text('POLICY')),
),
body: TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
),
),
);
}
}
class GradientAppBar extends StatefulWidget implements PreferredSizeWidget {
// Gradiente properties
final AlignmentGeometry begin;
final AlignmentGeometry end;
final List<Color> colors;
// Material property
final double elevation;
// AppBar properties - Add all you need to change
final Widget title;
final PreferredSizeWidget bottom;
@override
final Size preferredSize;
GradientAppBar({
Key key,
@required this.colors,
this.begin = Alignment.centerLeft,
this.end = Alignment.centerRight,
this.elevation,
this.title,
this.bottom,
}) : preferredSize = new Size.fromHeight(
kToolbarHeight + (bottom?.preferredSize?.height ?? 0.0)),
super(key: key); //appBar.preferredSize;
@override
_GradientAppBarState createState() => _GradientAppBarState();
}
class _GradientAppBarState extends State<GradientAppBar> {
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Material(
elevation: widget.elevation,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: widget.begin,
end: widget.end,
colors: widget.colors,
)),
),
),
AppBar(
backgroundColor: Colors.transparent,
elevation: 0.0,
bottom: widget.bottom,
title: widget.title,
),
],
);
}
}
And here the example for the gradient TabBar.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new Policy(),
);
}
}
class Policy extends StatefulWidget {
@override
_PolicyState createState() => _PolicyState();
}
class _PolicyState extends State<Policy> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: GradientTabBar(
colors: [Theme.of(context).primaryColor, Colors.green],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
tabBar: TabBar(
//indicatorColor: Colors.white,
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
),
title: Center(child: Text('POLICY')),
),
body: TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
),
),
);
}
}
class GradientTabBar extends StatefulWidget implements PreferredSizeWidget {
// Gradiente properties
final AlignmentGeometry begin;
final AlignmentGeometry end;
final List<Color> colors;
final TabBar tabBar;
GradientTabBar({
Key key,
@required this.colors,
this.begin = Alignment.centerLeft,
this.end = Alignment.centerRight,
this.tabBar,
}) : super(key: key);
@override
Size get preferredSize => tabBar.preferredSize;
@override
_GradientTabBarState createState() => _GradientTabBarState();
}
class _GradientTabBarState extends State<GradientTabBar> {
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Container(
height: widget.preferredSize.height,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: widget.begin,
end: widget.end,
colors: widget.colors,
)),
),
widget.tabBar,
],
);
}
}
A: you can try this
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
Colors.red,
Colors.blue
],
),
),
),
In Appbar
appBar: AppBar(
title: Center(child: Text("Add Student",),),
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
darkblue,
darkpurple
],
),
),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.account_circle,color: Colors.white,),),
],
), | unknown | |
d11976 | train | I have done similar implementation with a small change. You can change implementation as follows. The public method ApplicationStarting checks that logging is enabled or not. It has decorated with with [NoEvent] which indicates SLAB not to generate an event when method is invoked. If logging is enabled then the private method will be called to write the event.
[NonEvent]
public void ApplicationStarting()
{
if (this.IsEnabled(EventLevel.Verbose, Keywords.Application))
{
this.ApplicationStartingImplementation();
}
}
[Event(100, Level = EventLevel.Verbose, Keywords = Keywords.Application, Task = Tasks.Initialize, Opcode = Opcodes.Starting, Version = 1)]
private void ApplicationStartingImplementation()
{
this.WriteEvent(100);
}
A: Removing the if statement (which is checking if a particular EventLevel or Keyword IsEnabled) before calling this.WriteEvent accomplished my goal; I now have multiple sinks listening to different EventLevel's.
In my original question above, numbers 1 and 2 would stay the same, and #3 would look like this:
3) The AExpenseEvents (EventSource) method for ApplicationStarting() is:
[Event(100, Level = EventLevel.Verbose, Keywords = Keywords.Application, Task = Tasks.Initialize, Opcode = Opcodes.Starting, Version = 1)]
public void ApplicationStarting()
{
this.WriteEvent(100);
} | unknown | |
d11977 | train | It seems kind of unorganized. Merging version 2 into version 1? Eh? What version are you left with? Still version 1? With the features of version 2? Wha..?
What I like for smallish projects:
Trunk: This is where things get committed when the developer is confident that it's working. Do internal QA testing on the trunk.
Tags: Make a new tag for each release, by copying from the trunk. Name your tags "/tags/v1.0" or "/tags/v1.1" or however you want to do it. If you need an external client to test something, name your tag something like "/tags/v1.0-beta" and give them that to test. Don't let them test with the trunk, because while they're testing you're still going to be developing!
Branches: When you've got a feature that's going to take some time to develop, you can't commit it to the trunk before it's done. Make a branch. Name it after the feature you're implementing, like "/branches/user_logins".
Bugfixes get committed to the trunk and are included in the next tagged release. If there's an emergency bugfix which must be released TODAY, but there's stuff in the trunk which can not yet be released yet, make another tag but copy from the tag of the buggy release instead of from the trunk, call it something like "v1.0.1", fix the bug there, give them a new release, and then merge that bugfix into the trunk.
A: *
*"without trunk bugfixes"
*"it would be even harder to tell new and old bugs apart."
*"I have the feeling that this is more a problem with our development process than an technical one."
Damn straight. Your development process fails to acknowledge failures in V1. How can you hope that V2 will be better than V1 if you don't carry over the corrections in V1 to V2?!
Bug fixes are always more important than new features. If the old features are broken and not worth fixing then remove them.
Get off your lazy ass; if you, or someone, has made the effort to fix a defect in V1, then make sure it doesn't reappear in V2. FIX IT! If your code is so rubbish that this is a daily occurrence then stop working on V2 and focus on getting the bug fixes down to less often. If you can't get V1 features working properly then you'll never make it to V3.
I might also suggest "mercurial" or "git" or "bazaar" rather than svn. They're much better at keeping management types at bay if you find and use the "cherrypicking" and "queue" functionalities: you can add a feature and pull the-ONE-that-management-think-will-save-them into production without pulling all the other half-baked ideas they came up with then abandoned. If politics prevent a move to distributed version control just use it yourself and only push the stuff you deliver (and they want) to svn.
A: For me it seems that you switched the terms branch and trunk. Normally trunk is the active development branch, where releases live on their own bugfix branches. It looks that you use trunk as release1 bugfix branch, while /branches/1 is the real development trunk, and are stuck since you can't create a second trunk for release2.
If I'm right I would recommend to move your current trunk into a /branches/v2 branch, and your /branches/1 branch to /trunk. With this scenario you can have as many release branches as you need (but try to keep them as low as possible), while the main development line is in /trunk.
See http://nvie.com/posts/a-successful-git-branching-model/ for more details. While it is for git, there is a lot of VCS-independent information.
A: I agree to you other fellow posters. c0rnh0li0 You need to rethink your checkin & merge policies.
Look at your repository layout and try to define rules that can easily be repeated by anyone in the team and that help to populate changes consequently from stable to unstable. For me this allows merges mostly in one direction.
Example layout for a maintainance-branch scenario
branches/v1
-approved and shipped/deploy
-Only bugfixes allowed
branches/v2
-is not approved by the client but nearly ready
-Fixes and feature-commits allowed that focus on getting v2 stable & ready
-receive bugfixes commited in v1 (merge down)
branches/v3
-is not approved by the client and far from ready
-Fixes and feature-commits allowed that focus on getting v3 stable & ready
-receive bugfixes commited in v2 (merge down)
trunk
-All syntax-error free commits allowed (mainline)
-receive merges from LATEST stable branch (merge down from v3 in this case)
The top branch is the oldest with the fewest features but the highes stability (well tested, not many featurs been added in the recent past). The trunk on the other hand is pretty unstable and receives bleeding-edge features. v2 and v3 are Somewhet in between.
You could also add featrue branches "below" the trunk which would be even more unstable than the trunk. Merge directions remain the same. I'd like to quote the mantra "merge down, copy up".
The more concurrent releases you prepare/maintain the more merges you will have to do though. But thanks to mergetracking it is not so much of a task IMHO and it ensures no bugfix is left behind and has to be re-discovered and fixed again manually.
I didnt mention tags here. If you can create them and do not release from a branch directly.
Now while this should fix your change-flow management to a great deal and help isolate high-risk development from low-risk, there is the issue left of visualizing to the client what he is testing/previewing.
Visualising application VCS origin to the client
Possibilities:
*
*If it is a web-projekt host, the versions on URLs that contain the branch-name
*For any project: Just check in a logo or text property that contains something like "version 3.x" and display it in your application
*Coolest solution is to use svn keywords and parse the value of $HeadURL$ in your app to dynamically display the branch name this build originates from | unknown | |
d11978 | train | Matplotlib doc says to use ylim(bottom=0) instead of ylim(ymin=0)
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.ylim.html#
you could also just say plt.ylim([0,162772]) | unknown | |
d11979 | train | Check this JS Fiddle
JsFiddle link
There is no need of calling two different methods on two different buttons, a single method to accept the color parameter and change the desired element's color is good enough.
You have to modify your code like this and make sure javascript code comes before your button markup.
<script>
function setColor(color){
document.getElementById("tableCell").style.backgroundColor=color;
};
</script>
<table>
<tr>
<td id="tableCell">test</td>
</tr>
</table>
<input id="button1" type="button" value="I'm red" onclick="setColor('red')">
<input id="button2" type="button" value="I'm green" onclick="setColor('green')"> | unknown | |
d11980 | train | I could be wrong, but I think it could be the || operator. Have you tried a ternary operator?
{results ? results[searchKey].hits : ' // your hardcoded data '}
A: If I understand correctly, you are trying too set list variable as results[searchKey].hits, which have the wrong shape with your this.state.results
What you really want is this:
(results && results.results) || HARDCODED_FALLBACK_DATA | unknown | |
d11981 | train | try adding timeout
const searchIconElement = searchIcon.with({ visibilityCheck: true }).with({ timeout: 10000 });
A: When a selector is passed to a test action as the target element's identifier, the target element should be visible regardless of the visibilityCheck option. If the target element becomes visible too late, you can try to increase the selector timeout. | unknown | |
d11982 | train | How are you connecting? If you are using oci_connect, then that's probably a large part of the problem - switch to oci_pconnect.
Failing that, do make sure that DNS A and PTR records are available for both ends (or make sure you're only using ip addresses rather than names to connect).
C. | unknown | |
d11983 | train | I have an app that checks the flashlight feature and it works fine. Here is the code I used for checking if the user has the light:
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
new AlertDialog.Builder(this)
.setTitle("Sorry")
.setMessage("It appears that your device is incompatible with this app. Sorry for the inconvenience.")
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
}).show();
return;
}
Now to actually make the light work, I made a toggle button and wrote the following code:
private boolean isLightOn = false;
private Camera camera;
private ToggleButton button;
public Vibrator v;
if (camera == null) {
camera = Camera.open();
}
final Parameters p = camera.getParameters();
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (isLightOn) {
Toast.makeText(context, "Light off!", Toast.LENGTH_SHORT).show();
v.vibrate(40);
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLightOn = false;
} else {
Toast.makeText(context, "Light on!", Toast.LENGTH_SHORT).show();
v.vibrate(40);
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLightOn = true;
}
}
});
And finally, here are the only permissions I used:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
Note: All of the above code is in the onCreate method of my activity.
Hope this helps solve your problem!
A: I think you aren't setting your params again:
I used this to check if there is a flashlight:
public static Boolean hasFlashLight(Context context){
return context.getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
and to turn it off and on:
Parameters params = mCamera.getParameters();
if (!isFlashlightOn) {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
} else {
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
}
mCamera.setParameters(params);
Let me know if it works for you too.
A: I had the same problem. Use this
if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
//Flash ok
Parameters params = mCamera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
} else {
//Flash not supported
}
to determinate if your device has flash.
A: Some cameras need surface holder, otherwise they block the flash.
SurfaceView preview = (SurfaceView) findViewById(...);
SurfaceHolder holder = preview.getHolder();
holder.addCallback(this);
Camera camera = Camera.open();
camera.setPreviewDisplay(holder); | unknown | |
d11984 | train | Have you tried runing command with more options? (especially with db name)
mysql -u root -p dundermifflin
also try maybe without defining MYSQL_HOST and then
mysql -u root -p dundermifflin
or
mysql -h localhost -u root -p dundermifflin
https://dev.mysql.com/doc/refman/8.0/en/connecting.html | unknown | |
d11985 | train | In your Program.cs file you need
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().UseSerilog();
the important part is .UseSerilog() | unknown | |
d11986 | train | These are the default list of orderby options available( id, title, relevance, rand, date, price, popularity, rating). The case of the switch case may be what you are looking for.
switch ( $orderby ) {
case 'id':
$args['orderby'] = 'ID';
break;
case 'menu_order':
$args['orderby'] = 'menu_order title';
break;
case 'title':
$args['orderby'] = 'title';
$args['order'] = ( 'DESC' === $order ) ? 'DESC' : 'ASC';
break;
case 'relevance':
$args['orderby'] = 'relevance';
$args['order'] = 'DESC';
break;
case 'rand':
$args['orderby'] = 'rand'; // @codingStandardsIgnoreLine
break;
case 'date':
$args['orderby'] = 'date ID';
$args['order'] = ( 'ASC' === $order ) ? 'ASC' : 'DESC';
break;
case 'price':
$callback = 'DESC' === $order ? 'order_by_price_desc_post_clauses' : 'order_by_price_asc_post_clauses';
add_filter( 'posts_clauses', array( $this, $callback ) );
break;
case 'popularity':
add_filter( 'posts_clauses', array( $this, 'order_by_popularity_post_clauses' ) );
break;
case 'rating':
add_filter( 'posts_clauses', array( $this, 'order_by_rating_post_clauses' ) );
break;
}
The above code is from woocommerce/includes/class-wc-query.php line 586...
A: You need to know what is inside of an product object. You can sort your products by any of this product data.
Here is a list I found where you can access all the data inside of a product object.
(source: https://wpdavies.dev/how-to-get-all-product-info-in-woocommerce/)
<?php
/**
*
* General Product Data
*
*/
$product->get_id(); // Returns the unique ID for this object.
$product->get_description(); // Get product description.
$product->get_formatted_name(); // Get product name with SKU or ID. Used within admin.
$product->get_featured(); // If the product is featured.
$product->get_name(); // Get product name.
$product->get_title(); // Get the product's title. For products this is the product name.
$product->get_type(); // Get internal type. Should return string and *should be overridden* by child classes.
$product->get_virtual(); // Get virtual.
$product->get_total_sales(); // Get number total of sales.
$product->get_short_description(); // Get product short description.
$product->get_sku(); // Get SKU (Stock-keeping unit) - product unique ID.
$product->get_slug(); // Get product slug.
$product->get_status(); // Get product status.
$product->get_permalink(); // Product permalink.
$product->get_catalog_visibility(); // Get catalog visibility.
/**
*
* Pricing Data
*
*/
$product->get_price(); // Returns the product's active price.
$product->get_date_on_sale_from(); // Get date on sale from.
$product->get_date_on_sale_to(); // Get date on sale to.
$product->get_display_price(); // Returns the price including or excluding tax, based on the 'woocommerce_tax_display_shop' setting.
$product->get_price_excluding_tax(); // Returns the price (excluding tax) - ignores tax_class filters since the price may *include* tax and thus needs subtracting.
$product->get_price_html(); // Returns the price in html format.
$product->get_price_html_from_text(); // Functions for getting parts of a price, in html, used by $product->get_price_html.
$product->get_price_html_from_to(); // Functions for getting parts of a price, in html, used by $product->get_price_html.
$product->get_price_including_tax(); // Returns the price (including tax). Uses customer tax rates. Can work for a specific $qty for more accurate taxes.
$product->get_price_suffix(); // Get the suffix to display after prices > 0.
$product->get_sale_price(); // Returns the product's sale price.
$product->get_regular_price(); // Returns the product's regular price.
$product->get_tax_class(); // Returns the tax class.
$product->get_tax_status(); // Returns the tax status.
/**
*
* Image Related Data
*
*/
$product->get_image(); // Returns the main product image.
$product->get_image_id(); // Get main image ID.
$product->get_gallery_attachment_ids(); // Returns the gallery attachment ids.
$product->get_gallery_image_ids(); // Returns the gallery attachment ids.
/**
*
* Stock or Inventory Data
*
*/
$product->get_backorders(); // Get backorders.
$product->get_availability(); // Returns the availability of the product.
$product->get_max_purchase_quantity(); // Get max quantity which can be purchased at once.
$product->get_min_purchase_quantity(); // Get min quantity which can be purchased at once.
$product->get_stock_managed_by_id(); // If the stock level comes from another product ID, this should be modified.
$product->get_stock_quantity(); // Returns number of items available for sale.
$product->get_stock_status(); // Return the stock status.
$product->get_total_stock(); // Get total stock - This is the stock of parent and children combined.
$product->get_sold_individually(); // Return if should be sold individually.
$product->get_low_stock_amount(); // Get low stock amount.
/**
*
* Shipping Data
*
*/
$product->get_height(); // Returns the product height.
$product->get_length(); // Returns the product length.
$product->get_weight(); // Returns the product's weight.
$product->get_width(); // Returns the product width.
$product->get_dimensions(); // Returns formatted dimensions.
$product->get_manage_stock(); // Return if product manage stock.
$product->get_shipping_class(); // Returns the product shipping class SLUG.
$product->get_shipping_class_id(); // Get shipping class ID.
/**
*
* Product Variations / Parent Data
*
*/
$product->get_child(); // Returns the child product.
$product->get_children(); // Returns the children IDs if applicable. Overridden by child classes.
$product->get_formatted_variation_attributes(); // Get formatted variation data with WC < 2.4 back compat and proper formatting of text-based attribute names.
$product->get_matching_variation(); // Match a variation to a given set of attributes using a WP_Query.
$product->get_parent(); // Get the parent of the post.
$product->get_parent_id(); // Get parent ID.
$product->get_variation_default_attributes(); // If set, get the default attributes for a variable product.
$product->get_variation_description(); // Get product variation description.
$product->get_variation_id(); // Get variation ID.
/**
*
* Product Downloads
*
*/
$product->get_download_expiry(); // Get download expiry.
$product->get_download_limit(); // Get download limit.
$product->get_downloadable(); // Get downloadable.
$product->get_downloads(); // Get downloads.
$product->get_file(); // Get a file by $download_id.
$product->get_file_download_path(); // Get file download path identified by $download_id.
$product->get_files(); // Same as $product->get_downloads in CRUD.
/**
*
* Attributes, Tags, Categories & Associated Data Objects
*
*/
$product->get_attribute(); // Returns a single product attribute as a string.
$product->get_attributes(); // Returns product attributes.
$product->get_categories(); // Returns the product categories.
$product->get_category_ids(); // Get category ids.
$product->get_default_attributes(); // Get default attributes.
$product->get_cross_sell_ids(); // Get cross sell IDs.
$product->get_cross_sells(); // Returns the cross sell product ids.
$product->get_related(); // Get and return related products.
$product->get_tag_ids(); // Get tag ids.
$product->get_tags(); // Returns the product tags.
$product->get_upsell_ids(); // Get upsell IDs.
$product->get_upsells(); // Returns the upsell product ids.
$product->get_meta(); // Get Meta Data by Key.
$product->get_meta_data(); // Get All Meta Data.
/**
*
* Ratings and Reviews
*
*/
$product->get_rating_count(); // Get the total amount (COUNT) of ratings, or just the count for one rating e.g. number of 5 star ratings.
$product->get_rating_counts(); // Get rating count.
$product->get_rating_html(); // Returns the product rating in html format.
$product->get_review_count(); // Get review count.
$product->get_reviews_allowed(); // Return if reviews is allowed.
$product->get_average_rating(); // Get average rating.
/**
*
* Other Product Data
*
*/
$product->get_changes(); // Return data changes only.
$product->get_data(); // Returns all data for this object.
$product->get_data_keys(); // Returns array of expected data keys for this object.
$product->get_data_store(); // Get the data store.
$product->get_date_created(); // Get product created date.
$product->get_date_modified(); // Get product modified date.
$product->get_extra_data_keys(); // Returns all "extra" data keys for an object (for sub objects like product types).
$product->get_menu_order(); // Get menu order.
$product->get_meta_cache_key(); // Helper method to compute meta cache key. Different from WP Meta cache key in that meta data cached using this key also contains meta_id column.
$product->get_object_read(); // Get object read property.
$product->get_post_data(); // Get the product's post data.
$product->get_post_password(); // Get post password.
$product->get_purchase_note(); // Get purchase note.
With this you can see under "other product data", that there is a date_modified you can order your products by.
It is not directly a list of all fields you can sort by. But it indirectly shows you which fields are available inside a product and what the fields are called. With the name, you are able to access them.
Custom meta:
Unfortunatelly there is no data saved for "published_date". But you could create a custom field for your product post type and save the date inside product. Via the meta key you can than access the data of the product and sort your products by your custom meta data.
A: If the point of the question is whether there is a list that returns all the fields that can be used for sorting, the short answer is no.
The woocommerce_get_catalog_ordering_args filter allows you to add your own ordering args, but there is no list that would store these fields. This filter is used to overwrite args, not to store it as an array.
Within the get_catalog_ordering_args() function, some orderby defaults are statically specified: id, menu_order, title, relevance, rand, date, price, popularity, rating.
But there is no way to tell what values have been added using a filter by WordPress plugins.
Possible solution:
There is a woocommerce_catalog_orderby filter that stores sorting options as an array.
This is used to display sorting options in the view. So you can assume that WordPress plugins will add options to this as well.
/**
* Add orderby option by plugin
*/
add_filter( 'woocommerce_catalog_orderby', function ( $options ) {
$options['order_by_plugin'] = __( 'Order by plugin setting', 'text-domain' );
return $options;
} );
/**
* Get orderby options
*/
$catalog_orderby_options = apply_filters( 'woocommerce_catalog_orderby', array(
'menu_order' => __( 'Default sorting (custom ordering + name)', 'woocommerce' ),
'popularity' => __( 'Popularity (sales)', 'woocommerce' ),
'rating' => __( 'Average rating', 'woocommerce' ),
'date' => __( 'Sort by most recent', 'woocommerce' ),
'price' => __( 'Sort by price (asc)', 'woocommerce' ),
'price-desc' => __( 'Sort by price (desc)', 'woocommerce' ),
) );
You can use $catalog_orderby_options in which the sorting options are stored, if you only need the orderby fields, use the array_keys() function.
Note: you must specify the default value in apply_filters(), because WooCommerce added these statically, not using add_filter(). So you have to add it statically too. | unknown | |
d11987 | train | You can't return a value through a callback like that. The callback for "success" won't run until the "ajax" call has completed, long after the "submit" handler has already returned.
Instead of that, I'd just do the submit and let it return with an error if there are server-side issues (like "username in use" or whatever). There's no point making two round-trips. If there are no problems, it can just complete the operation and return whatever results page you want.
A: You need to add "async: false" as a parameter to your ajax call in order to force the call to finish before continuing on with the rest of the code.
$("form").submit(function(event) {
$.ajax({
async: false,
url: 'usernamechecker.php?username=' + $("#username").val(),
timeout: 1000,
success: function(resp) {
if (resp.UsernameExists) {
event.preventDefault(); // do not allow form submission
},
error: function() {
//fall back code when there's an error or timeout
},
});
}); | unknown | |
d11988 | train | Code seems fine but I am sure this is not the way to do it,
*
*You should null check your arrayList in your activity itself, then proceed to set adapter.
*For adapter,you should provide activityContext rather than applicationContext, adapters often hold listeners to open activities or to show toasts, it that case it should be activityContext not applicationContext
*For your problem, I will suggest setting layout manager after setting adapter. In this way, you won't need to call notifyDatasetChang.
Updated part
In your xml, you are adding RecyclerView inside horizontal scrollview which is the reason its giving trouble. Take your recyclerview outside the horizontal scrollview because you are setting the LinearLayoutManager with horizontal orientation in your code anyways. Then set both height and width of the recyclerview to match_parent. Also, if you don't want to add anything else in the footer view, you can remove the linearLayout and set your recyclerview as footer with width=match_parent and height=60dp.
Don't forget to delete horizontalscrollview code. | unknown | |
d11989 | train | Would this work for you?
$('#id_emp_name').autocomplete({
source: '/mycompany/employees.json',
minLength: 1,
dataType: 'json',
max: 12,
select: function(event, ui) {
$('#id_emp_id').val(ui.item.id);
}
}).keyup(function(){
$('#id_emp_id').val('');
});
You may need to put some conditions on it of course. | unknown | |
d11990 | train | Have consolidated all of the information from this an other posts along with comments and created a blog post that demonstrates how to use Binder with a real world scenario. Thanks to @mathewc this became possible.
A: Binder is an advanced binding technique that allows you to perform bindings imperatively in your code as opposed to declaratively via the function.json metadata file. You might need to do this in cases where the computation of binding path or other inputs needs to happen at runtime in your function. Note that when using an Binder parameter, you should not include a corresponding entry in function.json for that parameter.
In the below example, we're dynamically binding to a blob output. As you can see, because you're declaring the binding in code, your path info can be computed in any way you wish. Note that you can bind to any of the other raw binding attributes as well (e.g. QueueAttribute/EventHubAttribute/ServiceBusAttribute/etc.) You can also do so iteratively to bind multiple times.
Note that the type parameter passed to BindAsync (in this case TextWriter) must be a type that the target binding supports.
using System;
using System.Net;
using Microsoft.Azure.WebJobs;
public static async Task<HttpResponseMessage> Run(
HttpRequestMessage req, Binder binder, TraceWriter log)
{
log.Verbose($"C# HTTP function processed RequestUri={req.RequestUri}");
// determine the path at runtime in any way you choose
string path = "samples-output/path";
using (var writer = await binder.BindAsync<TextWriter>(new BlobAttribute(path)))
{
writer.Write("Hello World!!");
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
And here is the corresponding metadata:
{
"bindings": [
{
"name": "req",
"type": "httpTrigger",
"direction": "in"
},
{
"name": "res",
"type": "http",
"direction": "out"
}
]
}
There are bind overloads that take an array of attributes. In cases where you need to control the target storage account, you pass in a collection of attributes, starting with the binding type attribute (e.g. BlobAttribute) and inlcuding a StorageAccountAttribute instance pointing to the account to use. For example:
var attributes = new Attribute[]
{
new BlobAttribute(path),
new StorageAccountAttribute("MyStorageAccount")
};
using (var writer = await binder.BindAsync<TextWriter>(attributes))
{
writer.Write("Hello World!");
} | unknown | |
d11991 | train | Perhaps the simplest is send a string parameter that is a delimited list of product IDs, you split this on the server and handle each ID as necessary. So the update might be:
data: {product_ids: "1,2,10,99,500"} | unknown | |
d11992 | train | Not supported, see this FAQ item: https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions#Wpf_designer
You have to edit the small bit of XAML that's needed by hand in Visual Studio.
Apart from the projects MinimalExample repository on GitHub there is also a tutorial taking you through the initial steps at http://www.codeproject.com/Articles/881315/Display-HTML-in-WPF-and-CefSharp-Tutorial-Part | unknown | |
d11993 | train | The collections framework was designed to meet several goals, such as −
*
*The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hashtables) were to be highly efficient.
*The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability.
*The framework had to extend and/or adapt a collection easily.
A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following −
Interfaces − These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
Implementations, i.e., Classes − These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.
Algorithms − These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface.
For More Details you can find documents on ORACLE's Collection Documents | unknown | |
d11994 | train | Does gridSize represent number of slave threads which will be spawned?
Not necessarily. The grid size is the number of partitions that will be created by the partitioner. Note that this is just a hint to the partitioner, some partitioners do not use it (like the MultiResourcePartitioner).
This is different from the number of workers. You can have more partitions than workers and vice versa.
If yes, I want to make it dynamic using Runtime.getRuntime().availableProcessors()+1.
You can use Runtime.getRuntime().availableProcessors() to dynamically spawn as much workers as available cores (even though I don't see the value of adding 1 to that, unless I'm missing something).
is that right approach for I/O Job?
It depends on how you are processing each record. But I think this is a good start since each worker will handle a different partition and all workers can be executed in parallel. | unknown | |
d11995 | train | Your installation is corrupted, please reinstall.
A: Below are the steps which i have tried
*
*Clearing cache as per the intellij Website instructions --didn't worked
*Clearing Temp files -- didn't worked
*Use window system cleaner to remove...temp files..temp internet files..etc --- Worked. | unknown | |
d11996 | train | It is server code that is executed. The expression is replaced by the value of lbltotalmsg.ClientID.
The result that is sent to the client is therefor something like this:
','some-client-id')" rows="10" style="width: 477px; height: 111px">
A:
After some time or when i open the project next time then i find the below code
That doesn't seem to be possible unless you don't save, or unless you look at the code-view from a browser (i.e., after the page is rendered). Another thought might be that you're inside a version control system connected to an auto-build environment, which may rollback your changes if they contain compile errors (but I doubt that any build environment does so automatically).
Regardless, your issue has nothing to do with the <%= > itself, which simply interprets the expression on server side and outputs its value.
Update: perhaps your issue is the following: if the controls lbltotalmsg or lblcharcount are invisible (server-side Visible="False"), they are not rendered to the client side and hence will have an empty ClientId.
A: It runs a C# or VB.NET expression. Like DateTime.Now | unknown | |
d11997 | train | Well, the answer isn't that simple, and it actually depends on many factors, amongst them the number of items you wish to process, and the relative speed of your storage system and CPUs.
But the question is why to use multithreading at all here. Data too big to be held in memory? So many items that even a qsort algorithm can't sort fast enough? Take advantage of multiple processors or cores? Don't know.
I would suggest that you first write some test routines to measure the time needed to read and write the input file and the output files, as well as the CPU time needed for sorting. Please note that I/O is generally A LOT slower than CPU execution (actually they aren't even comparable), and I/O may not be efficient if you read data in parallel (there is one disk head which has to move in and out, so reads are in effect serialized - even if it's a digital drive it's still a device, with input and output channels). That is, the additional overhead of reading/writing temporary files may more than eliminate any benefit from multithreading. So I would say, first try making an algorithm that reads the whole file in memory, sorts it and writes it, and put in some time counters to check their relative speed. If I/O is some 30% of the total time (yes, that little!), it's definitely not worth, because with all that reading/merging/writing of temporary files, this will rise a lot more, so a solution processing the whole data at once would rather be preferable.
Concluding, don't see why use multithreading here, the only reason imo would be if data are actually delivered in blocks, but then again take into account my considerations above, about relative I/O-CPU speeds and the additional overhead of reading/writing the temporary files. And a hint, your file accessing must be very efficient, eg reading/writing in larger blocks using application buffers, not one by one (saves on system calls), otherwise this may have a detrimental effect if the file(s) are stored on a machine other than yours (eg a server).
Hope you find my suggestions useful. | unknown | |
d11998 | train | It is AceJump plugin - the easiest way to get it - go to Settings-Plugins click on Browse Repository and search for AceJump. Once you install it - the hardest thing for me was to force myself to use it after 2 months - I even type documents in webstorm and then copy it to Word.
Repository is here
https://plugins.jetbrains.com/plugin/7086
Github is here
https://github.com/johnlindquist/AceJump
Good luck :-) | unknown | |
d11999 | train | int checkRecord(int n) {
int dp[n + 1][2][3];
The size of an array variable must be compile time constant in C++. n + 1 is not compile time constant and as such the program is ill-formed.
If you want to create an array with runtime size, then you must create an array with dynamic storage duration. simplest way to do that is to use std::vector.
int helper(int idx, int A, int startL, int N, int M, int K, int dp[N][M][K]) {
Same applies to parameters which are also variables. Though there is slight difference since the array parameter will be adjusted to be a pointer to the first element of the array and the outermost dimension of the array i.e. N is ignored. The type of dp would be int(*)[M][K] if M and K were compile time constant.
Yeah, but 3d vector is too much to type vector<vector<..
In order to write long class template instances, you should pace yourself so that you don't get exhausted before the end. In case you are overcome by fatigue, take a short break to recover and continue later. I believe that you can do it.
That said, the inner dimensions of your array seem to be constant, so you don't need to use vectors inside vectors.
if(idx == N) return;
This is an ill-formed return statement in a non-void function.
A: Seems like you are trying to solve a competitive programming problem. So my answer is going to focus on that. I think others pointed out why it is not valid C++.
In C++, I don't see any easy way to achieve what you want.
In practice, when it comes to competitive programming problems, you may just define a big global array(As problems have fixed input sizes usually. In this case, there would be the max number of N, M, and K) and you don't have to struggle with passing it. Reuse the array for each case, but make sure you initialize it every time. Yeah, this is not a good practice in general but pretty handy for competitive programming.
If you think about 3D vectors are overkill, you may consider this. | unknown | |
d12000 | train | I discovered the issue! I was adding the classes in the visual studio so the Unreal couldn't find them. I just had to move the classes from the file "Intermediate" and put it in the "source" and generate the visual studio project files again and then build and it showed up! | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.