Login to your WHM panel if you have access to
Then go to Software -> MultiPHP INI Editor
Then select the php version from the dropdown, then scroll down for the upload_max_filesize which will be 2M by default, now increase it according to your need.
Also enable the file_uploads for HTTP file uploads for convenience.
If you don't have access to WHM, then follow the .htaccess method.
you can write multiple lines in case of different minutes, for example you want to run at 10:01 AM and 2:30 PM
1 10 * * * php -f /var/www/package/index.php controller function
30 14 * * * php -f /var/www/package/index.php controller function
but the following is the best solution for running cron multiple times in a day as minutes are same, you can mention hours like 10,30
.
30 10,14 * * * php -f /var/www/package/index.php controller function
I've had problems using /usr/bin/php on CPanel as it is compiled as a "cgi-fcgi" binary and not "cli". Try using /usr/local/bin/php or, as it is first in the path anyway, just use 'php' instead:
php /path/to/script.php
If you want to run the script as an executable, give it +x perms and use the following as the first line of the script:
#!/usr/bin/env php
I had the same issue as all of our servers run older versions of MySQL. This can be solved by running a PHP script. Save this code to a file and run it entering the database name, user and password and it'll change the collation from utf8mb4/utf8mb4_unicode_ci
to utf8/utf8_general_ci
<!DOCTYPE html>
<html>
<head>
<title>DB-Convert</title>
<style>
body { font-family:"Courier New", Courier, monospace; }
</style>
</head>
<body>
<h1>Convert your Database to utf8_general_ci!</h1>
<form action="db-convert.php" method="post">
dbname: <input type="text" name="dbname"><br>
dbuser: <input type="text" name="dbuser"><br>
dbpass: <input type="text" name="dbpassword"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_POST) {
$dbname = $_POST['dbname'];
$dbuser = $_POST['dbuser'];
$dbpassword = $_POST['dbpassword'];
$con = mysql_connect('localhost',$dbuser,$dbpassword);
if(!$con) { echo "Cannot connect to the database ";die();}
mysql_select_db($dbname);
$result=mysql_query('show tables');
while($tables = mysql_fetch_array($result)) {
foreach ($tables as $key => $value) {
mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}}
echo "<script>alert('The collation of your database has been successfully changed!');</script>";
}
?>
You cant do it on shared hosting , Add ticket to support of hosting for same ( otherwise you can look for dedicated server where you can manage anything )
You can use curl
as is in this thread
For the lazy:
*/5 * * * * curl --request GET 'http://exemple.com/path/check.php?param1=1'
This will be executed every 5 minutes.
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
The unix setup should be like the following:
0 */3 * * * sh cron/update_old_citations.sh
good reference for how to set various settings in cron at: http://www.thegeekstuff.com/2011/07/cron-every-5-minutes/
in your HTML : <input type="file" id="yourFile">
don't forget to reference your js file or put the following script between <script></script>
in your script :
var fileToRead = document.getElementById("yourFile");
fileToRead.addEventListener("change", function(event) {
var files = fileToRead.files;
if (files.length) {
console.log("Filename: " + files[0].name);
console.log("Type: " + files[0].type);
console.log("Size: " + files[0].size + " bytes");
}
}, false);
In case you are uploading an sql file on cpanel, then try and replace root with your cpanel username in your sql file.
in the case above you could write
CREATE DEFINER = control_panel_username
@localhost
FUNCTION fnc_calcWalkedDistance
then upload the file. Hope it helps
There are 5 cases for using the underscore in Python.
For storing the value of last expression in interpreter.
For ignoring the specific values. (so-called “I don’t care”)
To give special meanings and functions to name of variables or functions.
To use as ‘internationalization (i18n)’ or ‘localization (l10n)’ functions.
To separate the digits of number literal value.
Here is a nice article with examples by mingrammer.
As far as I know, it's not possible in IE because it uses the OS component.
Here is a link where the control is replaced, but I don't know if thats what you want to do.
<select>
Something New, Part 1So you've built a beautiful, standards-compliant site utilizing the latest and
greatest CSS techniques. You've mastered control of styling every element, but
in the back of your mind, a little voice is nagging you about how ugly your
<select>
s are. Well, today we're going to explore a way to silence that
little voice and truly complete our designs. With a little DOM scripting and
some creative CSS, you too can make your <select>
s beautiful… and you won't
have to sacrifice accessibility, usability or graceful degradation.
We all know the <select>
is just plain ugly. In fact, many try to limit its
use to avoid its classic web circa 1994 inset borders. We should not avoid
using the <select>
though--it is an important part of the current form
toolset; we should embrace it. That said, some creative thinking can improve
it.
<select>
We'll use a simple for our example:
<select id="something" name="something">
<option value="1">This is option 1</option>
<option value="2">This is option 2</option>
<option value="3">This is option 3</option>
<option value="4">This is option 4</option>
<option value="5">This is option 5</option>
</select>
[Note: It is implied that this <select>
is in the context of a complete
form.]
So we have five <option>
s within a <select>
. This <select>
has a
uniquely assigned id
of "something." Depending on the browser/platform
you're viewing it on, your <select>
likely looks roughly like this:
(source: easy-designs.net)
or this
(source: easy-designs.net)
Let's say we want to make it look a little more modern, perhaps like this:
(source: easy-designs.net)
So how do we do it? Keeping the basic <select>
is not an option. Apart from
basic background color, font and color adjustments, you don't really have a
lot of control over the .
However, we can mimic the superb functionality of a <select>
in a new form
control without sacrificing semantics, usability or accessibility. In order to
do that, we need to examine the nature of a <select>
.
A <select>
is, essentially, an unordered list of choices in which you can
choose a single value to submit along with the rest of a form. So, in essence,
it's a <ul>
on steroids. Continuing with that line of thinking, we can
replace the <select>
with an unordered list, as long as we give it some
enhanced functionality. As <ul>
s can be styled in a myriad of different
ways, we're almost home free. Now the questions becomes "how to ensure that we
maintain the functionality of the <select>
when using a <ul>
?" In other
words, how do we submit the correct value along with the form, if we
are no longer using a form control?
Enter the DOM. The final step in the process is making the <ul>
function/feel like a <select>
, and we can accomplish that with
JavaScript/ECMA Script and a little clever CSS. Here is the basic list of
requirements we need to have a functional faux <select>
:
With this plan, we can begin to tackle each part in succession.
So first we need to collect all of the attributes and s out of the and rebuild it as a . We accomplish this by running the following JS:
function selectReplacement(obj) {
var ul = document.createElement('ul');
ul.className = 'selectReplacement';
// collect our object's options
var opts = obj.options;
// iterate through them, creating <li>s
for (var i=0; i<opts.length; i++) {
var li = document.createElement('li');
var txt = document.createTextNode(opts[i].text);
li.appendChild(txt);
ul.appendChild(li);
}
// add the ul to the form
obj.parentNode.appendChild(ul);
}
You might be thinking "now what happens if there is a selected <option>
already?" We can account for this by adding another loop before we create the
<li>
s to look for the selected <option>
, and then store that value in
order to class
our selected <li>
as "selected":
…
var opts = obj.options;
// check for the selected option (default to the first option)
for (var i=0; i<opts.length; i++) {
var selectedOpt;
if (opts[i].selected) {
selectedOpt = i;
break; // we found the selected option, leave the loop
} else {
selectedOpt = 0;
}
}
for (var i=0; i<opts.length; i++) {
var li = document.createElement('li');
var txt = document.createTextNode(opts[i].text);
li.appendChild(txt);
if (i == selectedOpt) {
li.className = 'selected';
}
ul.appendChild(li);
…
[Note: From here on out, option 5 will be selected, to demonstrate this functionality.]
Now, we can run this function on every <select>
on the page (in our case,
one) with the following:
function setForm() {
var s = document.getElementsByTagName('select');
for (var i=0; i<s.length; i++) {
selectReplacement(s[i]);
}
}
window.onload = function() {
setForm();
}
We are nearly there; let's add some style.
I don't know about you, but I am a huge fan of CSS dropdowns (especially the
Suckerfish variety). I've been
working with them for some time now and it finally dawned on me that a
<select>
is pretty much like a dropdown menu, albeit with a little more
going on under the hood. Why not apply the same stylistic theory to our
faux-<select>
? The basic style goes something like this:
ul.selectReplacement {
margin: 0;
padding: 0;
height: 1.65em;
width: 300px;
}
ul.selectReplacement li {
background: #cf5a5a;
color: #fff;
cursor: pointer;
display: none;
font-size: 11px;
line-height: 1.7em;
list-style: none;
margin: 0;
padding: 1px 12px;
width: 276px;
}
ul.selectOpen li {
display: block;
}
ul.selectOpen li:hover {
background: #9e0000;
color: #fff;
}
Now, to handle the "selected" list item, we need to get a little craftier:
ul.selectOpen li {
display: block;
}
ul.selectReplacement li.selected {
color: #fff;
display: block;
}
ul.selectOpen li.selected {
background: #9e0000;
display: block;
}
ul.selectOpen li:hover,
ul.selectOpen li.selected:hover {
background: #9e0000;
color: #fff;
}
Notice that we are not using the :hover pseudo-class for the <ul>
to make it
open, instead we are class
-ing it as "selectOpen". The reason for this is
two-fold:
<select>
behave like a real <select>
, we need the list to open in an onclick
event and not on a simple mouse-over.To implement this, we can take what we learned from Suckerfish and apply it to
our own JavaScript by dynamically assigning and removing this class
in
``onclickevents for the list items. To do this right, we will need the
ability to change the
onclick` events for each list item on the fly to switch
between the following two actions:
<select>
when clicking the selected/default option when the list is collapsed; and<select>
.We will create a function called selectMe()
to handle the reassignment of
the "selected" class
, reassignment of the onclick
events for the list
items, and the collapsing of the faux-<select>
:
As the original Suckerfish taught us, IE will not recognize a hover state on
anything apart from an <a>
, so we need to account for that by augmenting
some of our code with what we learned from them. We can attach onmouseover and
onmouseout events to the "selectReplacement" class
-ed <ul>
and its
<li>
s:
function selectReplacement(obj) {
…
// create list for styling
var ul = document.createElement('ul');
ul.className = 'selectReplacement';
if (window.attachEvent) {
ul.onmouseover = function() {
ul.className += ' selHover';
}
ul.onmouseout = function() {
ul.className =
ul.className.replace(new RegExp(" selHover\\b"), '');
}
}
…
for (var i=0; i<opts.length; i++) {
…
if (i == selectedOpt) {
li.className = 'selected';
}
if (window.attachEvent) {
li.onmouseover = function() {
this.className += ' selHover';
}
li.onmouseout = function() {
this.className =
this.className.replace(new RegExp(" selHover\\b"), '');
}
}
ul.appendChild(li);
}
Then, we can modify a few selectors in the CSS, to handle the hover for IE:
ul.selectReplacement:hover li,
ul.selectOpen li {
display: block;
}
ul.selectReplacement li.selected {
color: #fff;
display: block;
}
ul.selectReplacement:hover li.selected**,
ul.selectOpen li.selected** {
background: #9e0000;
display: block;
}
ul.selectReplacement li:hover,
ul.selectReplacement li.selectOpen,
ul.selectReplacement li.selected:hover {
background: #9e0000;
color: #fff;
cursor: pointer;
}
Now we have a list behaving like a <select>
; but we still
need a means of changing the selected list item and updating the value of the
associated form element.
We already have a "selected" class
we can apply to our selected list item,
but we need a way to go about applying it to a <li>
when it is clicked on
and removing it from any of its previously "selected" siblings. Here's the JS
to accomplish this:
function selectMe(obj) {
// get the <li>'s siblings
var lis = obj.parentNode.getElementsByTagName('li');
// loop through
for (var i=0; i<lis.length; i++) {
// not the selected <li>, remove selected class
if (lis[i] != obj) {
lis[i].className='';
} else { // our selected <li>, add selected class
lis[i].className='selected';
}
}
}
[Note: we can use simple className
assignment and emptying because we are in
complete control of the <li>
s. If you (for some reason) needed to assign
additional classes to your list items, I recommend modifying the code to
append and remove the "selected" class to your className
property.]
Finally, we add a little function to set the value of the original <select>
(which will be submitted along with the form) when an <li>
is clicked:
function setVal(objID, selIndex) {
var obj = document.getElementById(objID);
obj.selectedIndex = selIndex;
}
We can then add these functions to the onclick
event of our <li>
s:
…
for (var i=0; i<opts.length; i++) {
var li = document.createElement('li');
var txt = document.createTextNode(opts[i].text);
li.appendChild(txt);
li.selIndex = opts[i].index;
li.selectID = obj.id;
li.onclick = function() {
setVal(this.selectID, this.selIndex);
selectMe(this);
}
if (i == selectedOpt) {
li.className = 'selected';
}
ul.appendChild(li);
}
…
There you have it. We have created our functional faux-. As we have
not hidden the original
yet, we can [watch how it
behaves](files/4.html) as we choose different options from our
faux-
. Of course, in the final version, we don't want the original
to show, so we can hide it by
class`-ing it as "replaced," adding
that to the JS here:
function selectReplacement(obj) {
// append a class to the select
obj.className += ' replaced';
// create list for styling
var ul = document.createElement('ul');
…
Then, add a new CSS rule to hide the
select.replaced {
display: none;
}
With the application of a few images to finalize the design (link not available) , we are good to go!
And here is another link to someone that says it can't be done.
tr ' ' ',' <input >output
Substitutes each space with a comma, if you need you can make a pass with the -s flag (squeeze repeats), that replaces each input sequence of a repeated character that is listed in SET1 (the blank space) with a single occurrence of that character.
Use of squeeze repeats used to after substitute tabs:
tr -s '\t' <input | tr '\t' ',' >output
A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.
If you want to control the width of your data, then you could use the width
sub-specifiers in the printf
format string. Eg. :
printf("%5d", 2);
It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.
If you want complete control, you'll probably have to implement it yourself.
for my script of python, I use...
To START python script :
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --exec $DAEMON
To STOP python script :
PID=$(cat $PIDFILE)
kill -9 $PID
rm -f $PIDFILE
P.S.: sorry for poor English, I'm from CHILE :D
This does not want to be a "just-use-a-library" answer but just in case you're using Lodash you can use .clamp
:
_.clamp(yourInput, lowerBound, upperBound);
So that:
_.clamp(22, -10, 10); // => 10
Here is its implementation, taken from Lodash source:
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
Also, it's worth noting that Lodash makes single methods available as standalone modules, so in case you need only this method, you can install it without the rest of the library:
npm i --save lodash.clamp
SELECT substring(convert (varchar(23),Dateadd(s,10000,LEFT(getdate(),11)),121),12,8)
10000 is your value in sec
Here's how I ended up doing this:
<div id="divform">
<form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div><input type="button" value="Upload" onclick="closeSelf();"/></div>
</form>
</div>
<div id="closelink" style="display:none">
<a href="javascript:window.close()">Click Here to Close this Page</a>
</div>
function closeSelf(){
document.forms['certform'].submit();
hide(document.getElementById('divform'));
unHide(document.getElementById('closelink'));
}
Where hide()
and unhide()
set the style.display
to 'none'
and 'block'
respectively.
Not exactly what I had in mind, but this will have to do for the time being. Works on IE, Safari, FF and Chrome.
Find the .PCH file inside the project. and then add #import "YourProjectName-Swift.h"
This will import the class headers. So that you don't have to import into specific file.
#ifndef __IPHONE_3_0
#warning "This project uses features only available in iPhone SDK 3.0 and later."
#endif
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "YourProjectName-Swift.h"
#endif
As stated from David Cournapeau, use figure().
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.figure()
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")
plt.figure()
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
Or subplot(121) / subplot(122) for the same plot, different position.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(121)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.subplot(122)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
In case of gray image, I am using this function and it works fine! however you must take care about the function features ;)
CvMat * src= cvCreateMat(300,300,CV_32FC1);
IplImage *dist= cvCreateImage(cvGetSize(dist),IPL_DEPTH_32F,3);
cvConvertScale(src, dist, 1, 0);
Without content, the height has no value to calculate the percentage of. The width, however, will take the percentage from the DOM, if no parent is specified. (Using your example) Placing the second div inside the first div, would have rendered a result...example below...
<div id="working">
<div id="not-working"></div>
</div>
The second div would be 30% of the first div's height.
There are a number of libraries available for generating graphs.
More are listed above and here.
This works for me on all browsers and Jquery <= v1.10
$('#kat').on('keyup', function () {
alert("Hello");
});
or as it seems you want
$('#kat').on('click', function () {
alert("Hello");
});
Textbox input field change event fires as you would expect it to, the jQuery .Change event only works correctly on html5 supported browsers
Create Table as select (CTAS) is possible in Hive.
You can try out below command:
CREATE TABLE new_test
row format delimited
fields terminated by '|'
STORED AS RCFile
AS select * from source where col=1
Create table like is also possible in Hive.
Friends I had the same problem because of the different bit version Make sure following point * Your jdk bit 64 or 32 * Your Path for sqljdbc_4.0\enu\auth\x64 or x86 this directory depend on your jdk bit * sqljdbc_auth.dll select this file based on your bit x64 or x86 and put this in system32 folder and it will works for me
Quickest solution-
See this URL for a easy example http://ajithmanmadhan.wordpress.com/2009/12/16/customizing-ckeditor-and-adding-a-new-toolbar-button/
There are a couple of steps:
1) create a plugin folder
2) register your plugin (the URL above says to edit the ckeditor.js file DO NOT do this, as it will break next time a new version is relased. Instead edit the config.js and add a line like so
config.extraPlugins = 'pluginX,pluginY,yourPluginNameHere';
3) make a JS file called plugin.js inside your plugin folder Here is my code
(function() {
//Section 1 : Code to execute when the toolbar button is pressed
var a = {
exec: function(editor) {
var theSelectedText = editor.getSelection().getNative();
alert(theSelectedText);
}
},
//Section 2 : Create the button and add the functionality to it
b='addTags';
CKEDITOR.plugins.add(b, {
init: function(editor) {
editor.addCommand(b, a);
editor.ui.addButton("addTags", {
label: 'Add Tag',
icon: this.path+"addTag.gif",
command: b
});
}
});
})();
In MS SQL, you can write the below line to check the column names of a particular table:
sp_help your_tablename
Or, you can first select your table name in the query windows (highlight the schema and table name) and then press key combination below:
Alt + F1
I think the confusion is that on my server I had to right click the Task Scheduler Library on left hand side and right click to get the option to enable or disable all tasks history.
Hope this helps
Dim distinctValues As List(Of Double) = (From r In _
DirectCast(DataTable.AsEnumerable(),IEnumerable(Of DataRow)) Where (Not r.IsNull("ColName")) _
Select r.Field(Of Double)("ColName")).Distinct().ToList()
If you have multiple databases for testing and development this might help
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
test:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
production:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
From the answer here, spark.sql.shuffle.partitions
configures the number of partitions that are used when shuffling data for joins or aggregations.
spark.default.parallelism
is the default number of partitions in RDD
s returned by transformations like join
, reduceByKey
, and parallelize
when not set explicitly by the user. Note that spark.default.parallelism
seems to only be working for raw RDD
and is ignored when working with dataframes.
If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions)
(don't forget to assign it to a new val
) in your code.
To change the settings in your code you can simply do:
sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")
Alternatively, you can make the change when submitting the job to a cluster with spark-submit
:
./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300
int j = num * -1;
if (j - num == j)
{
// Num is equal to zero
}
else if (j < i)
{
// Num is positive
}
else if (j > i)
{
// Num is negative
}
If you're using AForge.NET:
using(var croppedBitmap = new Crop(new Rectangle(10, 10, 10, 10)).Apply(bitmap))
{
// ...
}
For a similar post a long time ago there seems to be issues with making table visibility hidden.
You have two options, one is to use the display:none
attribute.
Or two wrap the table in a div and make the div hidden.
<div id="wrapper" style="visibility:hidden">
<table>
<tr>
<td>
Content
</td>
</tr>
</table>
</div>
If you have to write code for Internet Explorer make sure you chose an implementation, which uses array joins. Concatenating strings with the +
or +=
operator are extremely slow on IE. This is especially true for IE6. On modern browsers +=
is usually just as fast as array joins.
When I have to do lots of string concatenations I usually fill an array and don't use a string builder class:
var html = [];
html.push(
"<html>",
"<body>",
"bla bla bla",
"</body>",
"</html>"
);
return html.join("");
Note that the push
methods accepts multiple arguments.
I also found the apache commons IOUtils
class , so :
InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));
Check count of modals and add the value to backdrop as z-index
var zIndex = 1500 + ($('.modal').length*2) + 1;
this.popsr.css({'z-index': zIndex});
this.popsr.on('shown.bs.modal', function () {
$(this).next('.modal-backdrop').css('z-index', zIndex - 1);
});
this.popsr.modal('show');
I've written some code that provides "LINQ to HTML" functionality. I thought I would share it here. It is based on Majestic 12. It takes the Majestic-12 results and produces LINQ XML elements. At that point you can use all your LINQ to XML tools against the HTML. As an example:
IEnumerable<XNode> auctionNodes = Majestic12ToXml.Majestic12ToXml.ConvertNodesToXml(byteArrayOfAuctionHtml);
foreach (XElement anchorTag in auctionNodes.OfType<XElement>().DescendantsAndSelf("a")) {
if (anchorTag.Attribute("href") == null)
continue;
Console.WriteLine(anchorTag.Attribute("href").Value);
}
I wanted to use Majestic-12 because I know it has a lot of built-in knowledge with regards to HTML that is found in the wild. What I've found though is that to map the Majestic-12 results to something that LINQ will accept as XML requires additional work. The code I'm including does a lot of this cleansing, but as you use this you will find pages that are rejected. You'll need to fix up the code to address that. When an exception is thrown, check exception.Data["source"] as it is likely set to the HTML tag that caused the exception. Handling the HTML in a nice manner is at times not trivial...
So now that expectations are realistically low, here's the code :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Majestic12;
using System.IO;
using System.Xml.Linq;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace Majestic12ToXml {
public class Majestic12ToXml {
static public IEnumerable<XNode> ConvertNodesToXml(byte[] htmlAsBytes) {
HTMLparser parser = OpenParser();
parser.Init(htmlAsBytes);
XElement currentNode = new XElement("document");
HTMLchunk m12chunk = null;
int xmlnsAttributeIndex = 0;
string originalHtml = "";
while ((m12chunk = parser.ParseNext()) != null) {
try {
Debug.Assert(!m12chunk.bHashMode); // popular default for Majestic-12 setting
XNode newNode = null;
XElement newNodesParent = null;
switch (m12chunk.oType) {
case HTMLchunkType.OpenTag:
// Tags are added as a child to the current tag,
// except when the new tag implies the closure of
// some number of ancestor tags.
newNode = ParseTagNode(m12chunk, originalHtml, ref xmlnsAttributeIndex);
if (newNode != null) {
currentNode = FindParentOfNewNode(m12chunk, originalHtml, currentNode);
newNodesParent = currentNode;
newNodesParent.Add(newNode);
currentNode = newNode as XElement;
}
break;
case HTMLchunkType.CloseTag:
if (m12chunk.bEndClosure) {
newNode = ParseTagNode(m12chunk, originalHtml, ref xmlnsAttributeIndex);
if (newNode != null) {
currentNode = FindParentOfNewNode(m12chunk, originalHtml, currentNode);
newNodesParent = currentNode;
newNodesParent.Add(newNode);
}
}
else {
XElement nodeToClose = currentNode;
string m12chunkCleanedTag = CleanupTagName(m12chunk.sTag, originalHtml);
while (nodeToClose != null && nodeToClose.Name.LocalName != m12chunkCleanedTag)
nodeToClose = nodeToClose.Parent;
if (nodeToClose != null)
currentNode = nodeToClose.Parent;
Debug.Assert(currentNode != null);
}
break;
case HTMLchunkType.Script:
newNode = new XElement("script", "REMOVED");
newNodesParent = currentNode;
newNodesParent.Add(newNode);
break;
case HTMLchunkType.Comment:
newNodesParent = currentNode;
if (m12chunk.sTag == "!--")
newNode = new XComment(m12chunk.oHTML);
else if (m12chunk.sTag == "![CDATA[")
newNode = new XCData(m12chunk.oHTML);
else
throw new Exception("Unrecognized comment sTag");
newNodesParent.Add(newNode);
break;
case HTMLchunkType.Text:
currentNode.Add(m12chunk.oHTML);
break;
default:
break;
}
}
catch (Exception e) {
var wrappedE = new Exception("Error using Majestic12.HTMLChunk, reason: " + e.Message, e);
// the original html is copied for tracing/debugging purposes
originalHtml = new string(htmlAsBytes.Skip(m12chunk.iChunkOffset)
.Take(m12chunk.iChunkLength)
.Select(B => (char)B).ToArray());
wrappedE.Data.Add("source", originalHtml);
throw wrappedE;
}
}
while (currentNode.Parent != null)
currentNode = currentNode.Parent;
return currentNode.Nodes();
}
static XElement FindParentOfNewNode(Majestic12.HTMLchunk m12chunk, string originalHtml, XElement nextPotentialParent) {
string m12chunkCleanedTag = CleanupTagName(m12chunk.sTag, originalHtml);
XElement discoveredParent = null;
// Get a list of all ancestors
List<XElement> ancestors = new List<XElement>();
XElement ancestor = nextPotentialParent;
while (ancestor != null) {
ancestors.Add(ancestor);
ancestor = ancestor.Parent;
}
// Check if the new tag implies a previous tag was closed.
if ("form" == m12chunkCleanedTag) {
discoveredParent = ancestors
.Where(XE => m12chunkCleanedTag == XE.Name)
.Take(1)
.Select(XE => XE.Parent)
.FirstOrDefault();
}
else if ("td" == m12chunkCleanedTag) {
discoveredParent = ancestors
.TakeWhile(XE => "tr" != XE.Name)
.Where(XE => m12chunkCleanedTag == XE.Name)
.Take(1)
.Select(XE => XE.Parent)
.FirstOrDefault();
}
else if ("tr" == m12chunkCleanedTag) {
discoveredParent = ancestors
.TakeWhile(XE => !("table" == XE.Name
|| "thead" == XE.Name
|| "tbody" == XE.Name
|| "tfoot" == XE.Name))
.Where(XE => m12chunkCleanedTag == XE.Name)
.Take(1)
.Select(XE => XE.Parent)
.FirstOrDefault();
}
else if ("thead" == m12chunkCleanedTag
|| "tbody" == m12chunkCleanedTag
|| "tfoot" == m12chunkCleanedTag) {
discoveredParent = ancestors
.TakeWhile(XE => "table" != XE.Name)
.Where(XE => m12chunkCleanedTag == XE.Name)
.Take(1)
.Select(XE => XE.Parent)
.FirstOrDefault();
}
return discoveredParent ?? nextPotentialParent;
}
static string CleanupTagName(string originalName, string originalHtml) {
string tagName = originalName;
tagName = tagName.TrimStart(new char[] { '?' }); // for nodes <?xml >
if (tagName.Contains(':'))
tagName = tagName.Substring(tagName.LastIndexOf(':') + 1);
return tagName;
}
static readonly Regex _startsAsNumeric = new Regex(@"^[0-9]", RegexOptions.Compiled);
static bool TryCleanupAttributeName(string originalName, ref int xmlnsIndex, out string result) {
result = null;
string attributeName = originalName;
if (string.IsNullOrEmpty(originalName))
return false;
if (_startsAsNumeric.IsMatch(originalName))
return false;
//
// transform xmlns attributes so they don't actually create any XML namespaces
//
if (attributeName.ToLower().Equals("xmlns")) {
attributeName = "xmlns_" + xmlnsIndex.ToString(); ;
xmlnsIndex++;
}
else {
if (attributeName.ToLower().StartsWith("xmlns:")) {
attributeName = "xmlns_" + attributeName.Substring("xmlns:".Length);
}
//
// trim trailing \"
//
attributeName = attributeName.TrimEnd(new char[] { '\"' });
attributeName = attributeName.Replace(":", "_");
}
result = attributeName;
return true;
}
static Regex _weirdTag = new Regex(@"^<!\[.*\]>$"); // matches "<![if !supportEmptyParas]>"
static Regex _aspnetPrecompiled = new Regex(@"^<%.*%>$"); // matches "<%@ ... %>"
static Regex _shortHtmlComment = new Regex(@"^<!-.*->$"); // matches "<!-Extra_Images->"
static XElement ParseTagNode(Majestic12.HTMLchunk m12chunk, string originalHtml, ref int xmlnsIndex) {
if (string.IsNullOrEmpty(m12chunk.sTag)) {
if (m12chunk.sParams.Length > 0 && m12chunk.sParams[0].ToLower().Equals("doctype"))
return new XElement("doctype");
if (_weirdTag.IsMatch(originalHtml))
return new XElement("REMOVED_weirdBlockParenthesisTag");
if (_aspnetPrecompiled.IsMatch(originalHtml))
return new XElement("REMOVED_ASPNET_PrecompiledDirective");
if (_shortHtmlComment.IsMatch(originalHtml))
return new XElement("REMOVED_ShortHtmlComment");
// Nodes like "<br <br>" will end up with a m12chunk.sTag==""... We discard these nodes.
return null;
}
string tagName = CleanupTagName(m12chunk.sTag, originalHtml);
XElement result = new XElement(tagName);
List<XAttribute> attributes = new List<XAttribute>();
for (int i = 0; i < m12chunk.iParams; i++) {
if (m12chunk.sParams[i] == "<!--") {
// an HTML comment was embedded within a tag. This comment and its contents
// will be interpreted as attributes by Majestic-12... skip this attributes
for (; i < m12chunk.iParams; i++) {
if (m12chunk.sTag == "--" || m12chunk.sTag == "-->")
break;
}
continue;
}
if (m12chunk.sParams[i] == "?" && string.IsNullOrEmpty(m12chunk.sValues[i]))
continue;
string attributeName = m12chunk.sParams[i];
if (!TryCleanupAttributeName(attributeName, ref xmlnsIndex, out attributeName))
continue;
attributes.Add(new XAttribute(attributeName, m12chunk.sValues[i]));
}
// If attributes are duplicated with different values, we complain.
// If attributes are duplicated with the same value, we remove all but 1.
var duplicatedAttributes = attributes.GroupBy(A => A.Name).Where(G => G.Count() > 1);
foreach (var duplicatedAttribute in duplicatedAttributes) {
if (duplicatedAttribute.GroupBy(DA => DA.Value).Count() > 1)
throw new Exception("Attribute value was given different values");
attributes.RemoveAll(A => A.Name == duplicatedAttribute.Key);
attributes.Add(duplicatedAttribute.First());
}
result.Add(attributes);
return result;
}
static HTMLparser OpenParser() {
HTMLparser oP = new HTMLparser();
// The code+comments in this function are from the Majestic-12 sample documentation.
// ...
// This is optional, but if you want high performance then you may
// want to set chunk hash mode to FALSE. This would result in tag params
// being added to string arrays in HTMLchunk object called sParams and sValues, with number
// of actual params being in iParams. See code below for details.
//
// When TRUE (and its default) tag params will be added to hashtable HTMLchunk (object).oParams
oP.SetChunkHashMode(false);
// if you set this to true then original parsed HTML for given chunk will be kept -
// this will reduce performance somewhat, but may be desireable in some cases where
// reconstruction of HTML may be necessary
oP.bKeepRawHTML = false;
// if set to true (it is false by default), then entities will be decoded: this is essential
// if you want to get strings that contain final representation of the data in HTML, however
// you should be aware that if you want to use such strings into output HTML string then you will
// need to do Entity encoding or same string may fail later
oP.bDecodeEntities = true;
// we have option to keep most entities as is - only replace stuff like
// this is called Mini Entities mode - it is handy when HTML will need
// to be re-created after it was parsed, though in this case really
// entities should not be parsed at all
oP.bDecodeMiniEntities = true;
if (!oP.bDecodeEntities && oP.bDecodeMiniEntities)
oP.InitMiniEntities();
// if set to true, then in case of Comments and SCRIPT tags the data set to oHTML will be
// extracted BETWEEN those tags, rather than include complete RAW HTML that includes tags too
// this only works if auto extraction is enabled
oP.bAutoExtractBetweenTagsOnly = true;
// if true then comments will be extracted automatically
oP.bAutoKeepComments = true;
// if true then scripts will be extracted automatically:
oP.bAutoKeepScripts = true;
// if this option is true then whitespace before start of tag will be compressed to single
// space character in string: " ", if false then full whitespace before tag will be returned (slower)
// you may only want to set it to false if you want exact whitespace between tags, otherwise it is just
// a waste of CPU cycles
oP.bCompressWhiteSpaceBeforeTag = true;
// if true (default) then tags with attributes marked as CLOSED (/ at the end) will be automatically
// forced to be considered as open tags - this is no good for XML parsing, but I keep it for backwards
// compatibility for my stuff as it makes it easier to avoid checking for same tag which is both closed
// or open
oP.bAutoMarkClosedTagsWithParamsAsOpen = false;
return oP;
}
}
}
You want to apply the fixed property to the position style of the element.
position: fixed;
What browser are you working with? Not all browsers support the fixed property. Read more about who supports it, who doesn't and some work around here
http://webreflection.blogspot.com/2009/09/css-position-fixed-solution.html
<uses-permission android:name="android.permission.INTERNET"/>
add this tag above into AndroidManifest.xml of your Android project
,and it will be ok.
Agreed. The basic philosophy of REST is to use the web infrastructure. The HTTP Status codes are the messaging framework that allows parties to communicate with each other without increasing the HTTP payload. They are already established universal codes conveying the status of response, and therefore, to be truly RESTful, the applications must use this framework to communicate the response status.
Sending an error response in a HTTP 200 envelope is misleading, and forces the client (api consumer) to parse the message, most likely in a non-standard, or proprietary way. This is also not efficient - you will force your clients to parse the HTTP payload every single time to understand the "real" response status. This increases processing, adds latency, and creates an environment for the client to make mistakes.
Technically possible. You would probably reference employees_ce in deductions and employees_sn. But why don't you merge employees_sn and employees_ce? I see no reason why you have two table. No one to many relationship. And (not in this example) many columns.
If you do two references for one column, an employee must have an entry in both tables.
Put the data into a Pivot Table and do a top n filter on it
process.terminate() doesn't work when using shell=True
. This answer will help you.
You should use something similar to this for adding TextView to LinearLayout dynamically:
LinearLayout linearLayout = getActivity().findViewById(R.id.infoLayout);
TextView valueTV = new TextView(context);
valueTV.setText("hallo hallo");
valueTV.setId(Integer.parseInt("5"));
valueTV.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(valueTV);
getActivity() is used for inside Fragments, you can use context or anything similar per each instance you are inside.
Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.
So, abstract methods have no actual code in them, and subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override
modifier and provide a custom implementation.
public abstract class E
{
public abstract void AbstractMethod(int i);
public virtual void VirtualMethod(int i)
{
// Default implementation which can be overridden by subclasses.
}
}
public class D : E
{
public override void AbstractMethod(int i)
{
// You HAVE to override this method
}
public override void VirtualMethod(int i)
{
// You are allowed to override this method.
}
}
A method is a function that takes a class instance as its first parameter. Methods are members of classes.
class C:
def method(self, possibly, other, arguments):
pass # do something here
As you wanted to know what it specifically means in Python, one can distinguish between bound and unbound methods. In Python, all functions (and as such also methods) are objects which can be passed around and "played with". So the difference between unbound and bound methods is:
1) Bound methods
# Create an instance of C and call method()
instance = C()
print instance.method # prints '<bound method C.method of <__main__.C instance at 0x00FC50F8>>'
instance.method(1, 2, 3) # normal method call
f = instance.method
f(1, 2, 3) # method call without using the variable 'instance' explicitly
Bound methods are methods that belong to instances of a class. In this example, instance.method
is bound to the instance called instance
. Everytime that bound method is called, the instance is passed as first parameter automagically - which is called self
by convention.
2) Unbound methods
print C.method # prints '<unbound method C.method>'
instance = C()
C.method(instance, 1, 2, 3) # this call is the same as...
f = C.method
f(instance, 1, 2, 3) # ..this one...
instance.method(1, 2, 3) # and the same as calling the bound method as you would usually do
When you access C.method
(the method inside a class instead of inside an instance), you get an unbound method. If you want to call it, you have to pass the instance as first parameter because the method is not bound to any instance.
Knowing that difference, you can make use of functions/methods as objects, like passing methods around. As an example use case, imagine an API that lets you define a callback function, but you want to provide a method as callback function. No problem, just pass self.myCallbackMethod
as the callback and it will automatically be called with the instance as first argument. This wouldn't be possible in static languages like C++ (or only with trickery).
Hope you got the point ;) I think that is all you should know about method basics. You could also read more about the classmethod
and staticmethod
decorators, but that's another topic.
While the syntax is certainly different between Razor (.cshtml
/.vbhtml
) and WebForms (.aspx
/.ascx
), (Razor's being the more concise and modern of the two), nobody has mentioned that while both can be used as View Engines / Templating Engines, traditional ASP.NET Web Forms controls can be used on any .aspx or .ascx files, (even in cohesion with an MVC architecture).
This is relevant in situations where long standing solutions to a problem have been established and packaged into a pluggable component (e.g. a large-file uploading control) and you want to use it in an MVC site. With Razor, you can't do this. However, you can execute all of the same backend-processing that you would use with a traditional ASP.NET architecture with a Web Form view.
Furthermore, ASP.NET web forms views can have Code-Behind files, which allows embedding logic into a separate file that is compiled together with the view. While the software development community is growing to be see tightly coupled architectures and the Smart Client pattern as bad practice, it used to be the main way of doing things and is still very much possible with .aspx/.ascx files. Razor, intentionally, has no such quality.
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
Here is another way to run multi line commands.
apiVersion: batch/v1 kind: Job metadata: name: multiline spec: template: spec: containers: - command: - /bin/bash - -exc - | set +x echo "running below scripts" if [[ -f "if-condition.sh" ]]; then echo "Running if success" else echo "Running if failed" fi name: ubuntu image: ubuntu restartPolicy: Never backoffLimit: 1
Note that if you want to comment out a single line of printing erb you should do like this
<%#= ["Buck", "Papandreou"].join(" you ") %>
Here's a one-liner using sschober
's tool.
$ while true; do kqwait ./file-to-watch.js; script-to-execute.sh; done
Try this. I purposely broke out various parts so you can move things around.
library(sfsmisc)
#Generate the data
x <- 1:100000
y <- 1:100000
#Setup the plot area
par(pty="m", plt=c(0.1, 1, 0.1, 1), omd=c(0.1,0.9,0.1,0.9))
#Plot a blank graph without completing the x or y axis
plot(x, y, type = "n", xaxt = "n", yaxt="n", xlab="", ylab="", log = "x", col="blue")
mtext(side=3, text="Test Plot", line=1.2, cex=1.5)
#Complete the x axis
eaxis(1, padj=-0.5, cex.axis=0.8)
mtext(side=1, text="x", line=2.5)
#Complete the y axis and add the grid
aty <- seq(par("yaxp")[1], par("yaxp")[2], (par("yaxp")[2] - par("yaxp")[1])/par("yaxp")[3])
axis(2, at=aty, labels=format(aty, scientific=FALSE), hadj=0.9, cex.axis=0.8, las=2)
mtext(side=2, text="y", line=4.5)
grid()
#Add the line last so it will be on top of the grid
lines(x, y, col="blue")
The use
operator is for giving aliases to names of classes, interfaces or other namespaces. Most use
statements refer to a namespace or class that you'd like to shorten:
use My\Full\Namespace;
is equivalent to:
use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo
If the use
operator is used with a class or interface name, it has the following uses:
// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;
// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;
The use
operator is not to be confused with autoloading. A class is autoloaded (negating the need for include
) by registering an autoloader (e.g. with spl_autoload_register
). You might want to read PSR-4 to see a suitable autoloader implementation.
With the commit introduced today (Nov 25), you can now specify a port number right after the run
or start
sbt commands.
For instance
play run 8080
or play start 8080
Play defaults to port 9000
I encountered this once my system crashed. What I did is this:
(Please note your corrupt commits are lost, but changes are retained. You might have to recreate those commits at the end of this procedure)
.git
folder..git
folder in it.Only thing that comes even close is the :contains
pseudo class in CSS3, but that only selects textual content, not tags or elements, so you're out of luck.
A simpler way to select a parent with specific children in jQuery can be written as (with :has()
):
$('#parent:has(#child)');
l = [1,2,3]
print id(l)
l.append(4)
print id(l) #object l is the same
a = "dog"
print id(a)
a = "cat"
print id(a) #object a is a new object, previous one is deleted
== is an operator. equals is a method defined in the Object class
== checks if two objects have the same address in the memory and for primitive it checks if they have the same value.equals method on the other hand checks if the two objects which are being compared have an equal value(depending on how ofcourse the equals method has been implemented for the objects. equals method cannot be applied on primitives(which means that if a is a primitive a.equals(someobject) is not allowed, however someobject.equals(a) is allowed).
First, we are going to create a Windows Service that runs under the System account. This service will be responsible for spawning an interactive process within the currently active User’s Session. This newly created process will display a UI and run with full admin rights. When the first User logs on to the computer, this service will be started and will be running in Session0; however the process that this service spawns will be running on the desktop of the currently logged on User. We will refer to this service as the LoaderService.
Next, the winlogon.exe process is responsible for managing User login and logout procedures. We know that every User who logs on to the computer will have a unique Session ID and a corresponding winlogon.exe process associated with their Session. Now, we mentioned above, the LoaderService runs under the System account. We also confirmed that each winlogon.exe process on the computer runs under the System account. Because the System account is the owner of both the LoaderService and the winlogon.exe processes, our LoaderService can copy the access token (and Session ID) of the winlogon.exe process and then call the Win32 API function CreateProcessAsUser to launch a process into the currently active Session of the logged on User. Since the Session ID located within the access token of the copied winlogon.exe process is greater than 0, we can launch an interactive process using that token.
Try this one. Subverting Vista UAC in Both 32 and 64 bit Architectures
If you use Cristian's solution, you'll need to inject the EntityManager
into your FormType class. Here is a simplified example:
class EntityType extends AbstractType{
public function __construct($em) {
$this->em = $em;
}
public function buildForm(FormBuilderInterface $builder, array $options){
$builder
->add('MyEntity', 'entity', array(
'class' => 'AcmeDemoBundle:Entity',
'property' => 'name',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('e')
->orderBy('e.name', 'ASC');
},
'data' => $this->em->getReference("AcmeDemoBundle:Entity", 3)
));
}
}
And your controller:
// ...
$form = $this->createForm(new EntityType($this->getDoctrine()->getManager()), $entity);
// ...
From Doctrine Docs:
The method EntityManager#getReference($entityName, $identifier) lets you obtain a reference to an entity for which the identifier is known, without loading that entity from the database. This is useful, for example, as a performance enhancement, when you want to establish an association to an entity for which you have the identifier.
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
No, unless in that file format the line lengths are pre-determined (e.g. all lines with a fixed length), you'll have to iterate line by line to count them.
While using the disk utility graphically, it shows disk space used by all filesystem and it uses commands in the terminal such as df -H
. In other words, it uses powers of 1000, not 1024. (Note: there is difference between -h
and -H
.)
While also finding the unallocated space in a hard disk using command line
# fdisk /dev/sda
will display the total space and total cylinder value.
Now check the last cylinder value and subtract it from the total cylinder value. Hence the final value * 1000 gives you the unallocated disk space.
Note: the cylinder value shows up in df -H
as a power of 1000 or it might also show up using df -h
, a power of 1024.
Throwing my version into the pile here:
import argparse
parser = argparse.ArgumentParser()
args = parser.parse_args()
if not vars(args):
parser.print_help()
parser.exit(1)
You may notice the parser.exit
- I mainly do it like that because it saves an import line if that was the only reason for sys
in the file...
You can do using a simple notepad and save as FILENAME.json
That's all.
If you are reading this in 2019, credentials: "same-origin"
is the default value.
fetch(url).then
Its a new operator for combined comparison. Similar to strcmp()
or version_compare() in behavior, but it can be used on all generic PHP values with the same semantics as <
, <=
, ==
, >=
, >
. It returns 0
if both operands are equal, 1
if the left is greater, and -1
if the right is greater. It uses exactly the same comparison rules as used by our existing comparison operators: <
, <=
, ==
, >=
and >
.
I have been working on to write a custom module in Drupal 7 and got the same error:
Notice: Trying to get property of non-object
My code is something like this:
function example_node_access($node, $op, $account) {
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes to it.','error');
return NODE_ACCESS_DENY;
}
}
Solution:
I just added a condition if (is_object($sqlResult))
, and everything went fine.
Here is my final code:
function mediaten_node_access($node, $op, $account) {
if (is_object($node)){
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes.','error');
return NODE_ACCESS_DENY;
}
}
}
You can install unix2dos with Homebrew
brew install unix2dos
Then you can do this:
unix2dos file-to-convert
You can also convert dos files to unix:
dos2unix file-to-convert
When I want access some value from GridView
before GridView
was appears.
BoundField
and bind DataField
nomally.RowDataBound
event, I do some process in that event.Before GridView
was appears I write this:
protected void GridviewLecturer_PreRender(object sender, EventArgs e)
{
GridviewLecturer.Columns[0].Visible = false;
}
Remove "track by index" from the ng-repeat and it would refresh the DOM
In Bash, you should get what you need like this:
#!/usr/bin/env bash
BASEDIR=$(dirname "$0")
echo "$BASEDIR"
Mac OSX only
An easier way to get going (assuming you already have homebrew installed, which you should, if not, go do that first and let homebrew make your life better) is to just run the following command:
brew install chromedriver
That should put the chromedriver in your path and you should be all set.
Browsers control a lot of this functionality but
<a href="http://www.yahoo.com" target="_blank">Go to Yahoo</a>
will attempt to open yahoo.com in a new window.
Easy way
((25[0-5]|2[0-4][0-9]|[1][0-9][0-9]|[1-9][0-9]{0,1})\.){3}(25[0-5]|2[0-4][0-9]|[1][0-9][0-9]|[1-9][0-9]{0,1})
Create a file named "overrideBashCdForWindowsPaths" in your HOME folder. Paste the following lines into that file and save it:
#!/bin/bash
function cd() {
CD_PATH="$(history | tail -1 | sed -e "s,.*${FUNCNAME[0]}\s*,,g")"
if [ -z "${CD_PATH}" -o "${CD_PATH}" = "~" ]; then
CD_PATH="${HOME}"
fi
builtin cd "$(cygpath "$CD_PATH")"
}
Next, type the following command in a terminal, while you are in your HOME folder:
echo ". overrideBashCdForWindowsPaths" >> .bashrc
Close your terminal and open a new one. You can now easily change into that Windows folder by simply typing
cd C:\Python31\sip
The script reads the last command, extracts the path and passes it to Cygwin's path-conversion tool. By naming the function "cd" we sort of 'override' Bash's builtin "cd" and delegate the actual call to it in the very last line.
Material UI have implemented their own Flexbox layout via the Grid component.
It appears they initially wanted to keep themselves as purely a 'components' library. But one of the core developers decided it was too important not to have their own. It has now been merged into the core code and was released with v1.0.0.
You can install it via:
npm install @material-ui/core
It is now in the official documentation with code examples.
iOS 10,11 (Swift 3.1,Swift 4.0)
According to UIViewController
in UIKit
developers,
1. loadView()
This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly.
2. loadViewIfNeeded()
Loads the view controller's view if it has not already been set.
3. viewDidLoad()
Called after the view has been loaded. For view controllers created in code, this is after -loadView. For view controllers unarchived from a nib, this is after the view is set.
4. viewWillAppear(_ animated: Bool)
Called when the view is about to made visible. Default does nothing
5. viewWillLayoutSubviews()
Called just before the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. Default does nothing.
6. viewDidLayoutSubviews()
Called just after the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. Default does nothing.
7. viewDidAppear(_ animated: Bool)
Called when the view has been fully transitioned onto the screen. Default does nothing
8. viewWillDisappear(_ animated: Bool)
Called when the view is dismissed, covered or otherwise hidden. Default does nothing
9. viewDidDisappear(_ animated: Bool)
Called after the view was dismissed, covered or otherwise hidden. Default does nothing
10. viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
Called when the view is Transitioning.
11. willMove(toParentViewController parent: UIViewController?)
12. didMove(toParentViewController parent: UIViewController?)
These two methods are public for container subclasses to call when transitioning between child controllers. If they are overridden, the overrides should ensure to call the super.
The parent argument in both of these methods is nil when a child is being removed from its parent; otherwise it is equal to the new parent view controller.
13. didReceiveMemoryWarning()
Called when the parent application receives a memory warning. On iOS 6.0 it will no longer clear the view by default.
You have it, but you should only catch NumberFormatException
.
So I think I found a method that works cleaner than the ones above because it doesn't require any global variables. I got it from here: http://nshipster.com/swift-objc-runtime/
The gist is that you use a struct like so:
extension UIViewController {
private struct AssociatedKeys {
static var DescriptiveName = "nsh_DescriptiveName"
}
var descriptiveName: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.DescriptiveName,
newValue as NSString?,
UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)
)
}
}
}
}
UPDATE for Swift 2
private struct AssociatedKeys {
static var displayed = "displayed"
}
//this lets us check to see if the item is supposed to be displayed or not
var displayed : Bool {
get {
guard let number = objc_getAssociatedObject(self, &AssociatedKeys.displayed) as? NSNumber else {
return true
}
return number.boolValue
}
set(value) {
objc_setAssociatedObject(self,&AssociatedKeys.displayed,NSNumber(bool: value),objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
For http/https proxy with or without authentication:
Run one of the following commands in cmd.exe
set http_proxy=http://your_proxy:your_port
set http_proxy=http://username:password@your_proxy:your_port
set https_proxy=https://your_proxy:your_port
set https_proxy=https://username:password@your_proxy:your_port
what you have is fine - however to save some typing, you can simply use for your data
data: $('#formId').serialize()
see http://www.ryancoughlin.com/2009/05/04/how-to-use-jquery-to-serialize-ajax-forms/ for details, the syntax is pretty basic.
Good day
for some guys the order by in the sub-query is questionable. the order by in sub-query is a must to use if you need to delete some records based on some sorting. like
delete from someTable Where ID in (select top(1) from sometable where condition order by insertionstamp desc)
so that you can delete the last insertion form table. there are three way to do this deletion actually.
however, the order by in the sub-query can be used in many cases.
for the deletion methods that uses order by in sub-query review below link
i hope it helps. thanks you all
if you want to embedded Google drive images in your blogger or any sites then just follow the instructions : -
Blogger
<img src='https://drive.google.com/uc?export=view&id=1OCx6mUEMbWcwCQbDePA5PeeOh'/>
I resolved it by selecting http
as the protocol and giving my GitHub username and password.
You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME
Another way to achieve this is using old printf()
function of C language
You can use this like
int dd = 1, mm = 9, yy = 1;
printf("%02d - %02d - %04d", mm, dd, yy);
This will print 09 - 01 - 0001
on the console.
You can also use another function sprintf()
to write formatted output to a string like below:
int dd = 1, mm = 9, yy = 1;
char s[25];
sprintf(s, "%02d - %02d - %04d", mm, dd, yy);
cout << s;
Don't forget to include stdio.h
header file in your program for both of these functions
You can fill blank space either by 0 or by another char (not number).
If you do write something like %24d
format specifier than this will not fill 2
in blank spaces. This will set pad to 24
and will fill blank spaces.
I know this question is specific to sql server, but I'm using postgresql and came across this question, so for anybody else in a similar situation, there is the split_part(string text, delimiter text, field int)
function.
Here is all way to add your program to startup for Windows Vista, 7, 8, 10
- File path
C:\Users\Bureau Briffault\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
(Visible from task manager, Running on current user login success, No admin privileges required)
C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
(Visible from task manager, Running on all user login success, Admin privileges required)
- Registry path
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
(Visible from task manager, Running on current user login success, No admin privileges required)
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
(Not visible from task manager, Running on current user login success, Running for one login time, No admin privileges required)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
(Visible from task manager, Running on all user login success, Admin privileges required)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
(Not visible from task manager, Running on all user login success, Running for one login time, Admin privileges required)
- Task scheduler
Microsoft.Win32.Taskscheduler.dll
(Not visible from task manager, Running on windows boot, Running as admin, Admin privileges required)
I would use this in HTML 5... Just sayin
#footer {
position: absolute;
bottom: 0;
width: 100%;
height: 60px;
background-color: #f5f5f5;
}
If you want a "capture/streamer in a box" component, there are several out there as others have mentioned.
If you want to get down to the low-level control over it all, you'll need to use DirectShow as thealliedhacker points out. The best way to use DirectShow in C# is through the DirectShow.Net library - it wraps all of the DirectShow COM APIs and includes many useful shortcut functions for you.
In addition to capturing and streaming, you can also do recording, audio and video format conversions, audio and video live filters, and a whole lot of stuff.
Microsoft claims DirectShow is going away, but they have yet to release a new library or API that does everything that DirectShow provides. I suspect many of the latest things they have released are still DirectShow under the hood. Because of its status at Microsoft, there aren't a whole lot of books or references on it other than MSDN and what you can find on forums. Last year when we started a project using it, the best book on the subject - Programming Microsoft DirectShow - was out of print and going for around $350 for a used copy!
Just use a normal Javascript expression, no {}
or anything necessary:
@click="addToCount(item.contactID)"
if you also need the event object:
@click="addToCount(item.contactID, $event)"
If you have Java 5, use char c = ...; String s = String.format ("\\u%04x", (int)c);
If your source isn't a Unicode character (char
) but a String, you must use charAt(index)
to get the Unicode character at position index
.
Don't use codePointAt(index)
because that will return 24bit values (full Unicode) which can't be represented with just 4 hex digits (it needs 6). See the docs for an explanation.
[EDIT] To make it clear: This answer doesn't use Unicode but the method which Java uses to represent Unicode characters (i.e. surrogate pairs) since char is 16bit and Unicode is 24bit. The question should be: "How can I convert char
to a 4-digit hex number", since it's not (really) about Unicode.
$.event.special.rightclick = {
bindType: "contextmenu",
delegateType: "contextmenu"
};
$(document).on("rightclick", "div", function() {
console.log("hello");
return false;
});
I put the \let\cleardoublepage\clearpage
before \makeindex
. Else, your content page will display page number based on the page number before you clear the blank page.
echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts
the >>
appends the output of echo
to the file.
Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.
First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.
Second, it requires you to add an entry for every host name on a domain; just adding websitename.com
will not block www.websitename.com
, for example.
This works too and you dont have to use join or anything:
DROP VIEW IF EXISTS yourview;
CREATE VIEW yourview AS
SELECT table1.column1,
table2.column2
FROM
table1, table2
WHERE table1.column1 = table2.column1;
You might need to do some checking. You cannot safely convert factors directly to numeric. as.character
must be applied first. Otherwise, the factors will be converted to their numeric storage values. I would check each column with is.factor
then coerce to numeric as necessary.
df1[] <- lapply(df1, function(x) {
if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(df1, class)
# a b
# "numeric" "numeric"
This is probably because an empty line at the end of your input file.
Try this:
for x in f:
try:
print int(x.strip(),16)
except ValueError:
print "Invalid input:", x
You can get the protocol, host, and port using this:
window.location.origin
Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
(Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | 11 | ? | 7 (possibly earlier, see webkit bug 46558) |
Android | Edge | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
(Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | ? | ? | 7 (possibly earlier, see webkit bug 46558) |
All browser compatibility is from Mozilla Developer Network
We can also solve this utilizing vectors.
Let's define the segments as [start, end]
. Given two such segments [A, B]
and [C, D]
that both have non-zero length, we can choose one of the endpoints to be used as a reference point so that we get three vectors:
x = 0
y = 1
p = A-C = [C[x]-A[x], C[y]-A[y]]
q = B-A = [B[x]-A[x], B[y]-A[y]]
r = D-C = [D[x]-C[x], D[y]-C[y]]
From there, we can look for an intersection by calculating t and u in p + t*r = u*q
. After playing around with the equation a little, we get:
t = (q[y]*p[x] - q[x]*p[y])/(q[x]*r[y] - q[y]*r[x])
u = (p[x] + t*r[x])/q[x]
Thus, the function is:
def intersects(a, b):
p = [b[0][0]-a[0][0], b[0][1]-a[0][1]]
q = [a[1][0]-a[0][0], a[1][1]-a[0][1]]
r = [b[1][0]-b[0][0], b[1][1]-b[0][1]]
t = (q[1]*p[0] - q[0]*p[1])/(q[0]*r[1] - q[1]*r[0]) \
if (q[0]*r[1] - q[1]*r[0]) != 0 \
else (q[1]*p[0] - q[0]*p[1])
u = (p[0] + t*r[0])/q[0] \
if q[0] != 0 \
else (p[1] + t*r[1])/q[1]
return t >= 0 and t <= 1 and u >= 0 and u <= 1
in addition to @emil-vikström's answer, checking for variable!=null
would be true for variable!==null
as well as for variable!==undefined
(or typeof(variable)!="undefined"
).
_ [$%-4009] * #,##0_ ;_ [$%-4009] * -#,##0_ ;_ [$%-4009] * "-"??_ ;_ @_
I like prettyPhoto
prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox
This is a very interesting bug. (In my opinion, it is a bug anyway) Nice find!
Regarding how to set it, I would recommend Camilo Martin's answer. But as to why, I'd like to explain this a bit if you guys don't mind.
In the CSS specs I found:
'padding'
Percentages: refer to width of containing block
… which is weird, but okay.
So, with a parent width: 210px
and a child padding-top: 50%
, I get a calculated/computed value of padding-top: 96.5px
– which is not the expected 105px
.
That is because in Windows (I'm not sure about other OSs), the size of common scrollbars is per default 17px × 100%
(or 100% × 17px
for horizontal bars). Those 17px
are substracted before calculating the 50%
, hence 50% of 193px = 96.5px
.
Try this :
$('select[name^="salesrep"] option[value="Bruce Jones"]').attr("selected","selected");
Just replace option[value="Bruce Jones"]
by option[value=result[0]]
And before selecting a new option, you might want to "unselect" the previous :
$('select[name^="salesrep"] option:selected').attr("selected",null);
You may want to read this too : jQuery get specific option tag text
Edit: Using jQuery Mobile, this link may provide a good solution : jquery mobile - set select/option values
I have tested this code working file:
var timeout = null;
var timee = '4000'; // default time for session time out.
$(document).bind('click keyup mousemove', function(event) {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
timeout = null;
console.log('Document Idle since '+timee+' ms');
alert("idle window");
}, timee);
});
Baud rate is mostly used in telecommunication and electronics, representing symbol per second or pulses per second, whereas bit rate is simply bit per second. To be simple, the major difference is that symbol may contain more than 1 bit, say n bits, which makes baud rate n times smaller than bit rate.
Suppose a situation where we need to represent a serial-communication signal, we will use 8-bit as one symbol to represent the info. If the symbol rate is 4800 baud, then that translates into an overall bit rate of 38400 bits/s. This could also be true for wireless communication area where you will need multiple bits for purpose of modulation to achieve broadband transmission, instead of simple baseline transmission.
Hope this helps.
The minimum width that your screen can display is 1 pixel. So its impossible to display less then 1px. 1 pixels can only have 1 color and cannot be split up.
The problem you encounter comes from the lack of call to super.prepareForReuse()
.
Some other solutions above, suggesting to update the UI of the cell from the delegate's functions, are leading to a flawed design where the logic of the cell's behaviour is outside of its class. Furthermore, it's extra code that can be simply fixed by calling super.prepareForReuse()
. For example :
class myCell: UICollectionViewCell {
// defined in interface builder
@IBOutlet weak var viewSelection : UIView!
override var isSelected: Bool {
didSet {
self.viewSelection.alpha = isSelected ? 1 : 0
}
}
override func prepareForReuse() {
// Do whatever you want here, but don't forget this :
super.prepareForReuse()
// You don't need to do `self.viewSelection.alpha = 0` here
// because `super.prepareForReuse()` will update the property `isSelected`
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.viewSelection.alpha = 0
}
}
With such design, you can even leave the delegate's functions collectionView:didSelectItemAt:
/collectionView:didDeselectItemAt:
all empty, and the selection process will be totally handled, and behave properly with the cells recycling.
take look at this sample code from my project
public static IList<Letter> GetDepartmentLettersLinq(int departmentId)
{
IEnumerable<Letter> allDepartmentLetters =
from allLetter in LetterService.GetAllLetters()
join allUser in UserService.GetAllUsers() on allLetter.EmployeeID equals allUser.ID into usersGroup
from user in usersGroup.DefaultIfEmpty()// here is the tricky part
join allDepartment in DepartmentService.GetAllDepartments() on user.DepartmentID equals allDepartment.ID
where allDepartment.ID == departmentId
select allLetter;
return allDepartmentLetters.ToArray();
}
in this code I joined 3 tables and I spited join condition from where clause
note: the Services classes are just warped(encapsulate) the database operations
I might be a little late, but after spending hours and researching on this issue.
I found out that in the latest version IntelliJ 2020 @AutoWired is optional and constructor based depedency injection is preferable.
I sloved the problem by simply removing the @AutoWired Annotation from Service and Controller class and using constructor based dependency injection.
This link might help.
Happy Coding!
int total = 0;
protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotal");
lblamount.Text = total.ToString();
}
}
You can use the -B
option.
-B, --block-size=SIZE use SIZE-byte blocks
All together,
df -BG
Fastest way for Android Studio 3.x.x and Android Studio 4.x.x
1.Go to the design tab of the activity layout
2.At the top you should press on the orientation for preview button, there is a option to create a landscape layout (check image), a new folder will be created as your xml layout file for that particular orientation
Put [] around any field names that had spaces (as Dreden says) and save your query, close it and reopen it.
Using Access 2016, I still had the error message on new queries after I added [] around any field names... until the Query was saved.
Once the Query is saved (and visible in the Objects' List), closed and reopened, the error message disappears. This seems to be a bug from Access.
:not
selector:
input:not([type]), input[type='text'], input[type='password'] {
/* style here */
}
Support: in Internet Explorer 9 and higher
$session_start();
extract($_POST);
//extract data from submit post
if(isset($submit))
{
if($user=="user" && $pass=="pass")
{
$_SESSION['user']= $user;
//if correct password and name store in session
}
else {
echo "Invalid user and password";
header("Locatin:form.php");
}
if(isset($_SESSION['user']))
{
//your home page code here
exit;
}
There are two ways to resize an image. The new size can be specified:
Manually;
height, width = src.shape[:2]
dst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)
By a scaling factor.
dst = cv2.resize(src, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC)
,
where fx is the scaling factor along the horizontal axis and fy along the vertical axis.
To shrink an image, it will generally look best with INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with INTER_CUBIC (slow) or INTER_LINEAR (faster but still looks OK).
import cv2
img = cv2.imread('YOUR_PATH_TO_IMG')
height, width = img.shape[:2]
max_height = 300
max_width = 300
# only shrink if img is bigger than required
if max_height < height or max_width < width:
# get scaling factor
scaling_factor = max_height / float(height)
if max_width/float(width) < scaling_factor:
scaling_factor = max_width / float(width)
# resize image
img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
cv2.imshow("Shrinked image", img)
key = cv2.waitKey()
import cv2 as cv
im = cv.imread(path)
height, width = im.shape[:2]
thumbnail = cv.resize(im, (round(width / 10), round(height / 10)), interpolation=cv.INTER_AREA)
cv.imshow('exampleshq', thumbnail)
cv.waitKey(0)
cv.destroyAllWindows()
Checkout And Run The Following Code. It will help you...
$( function() {_x000D_
$.widget( "custom.iconselectmenu", $.ui.selectmenu, {_x000D_
_renderItem: function( ul, item ) {_x000D_
var li = $( "<li>" ),_x000D_
wrapper = $( "<div>", { text: item.label } );_x000D_
_x000D_
if ( item.disabled ) {_x000D_
li.addClass( "ui-state-disabled" );_x000D_
}_x000D_
_x000D_
$( "<span>", {_x000D_
style: item.element.attr( "data-style" ),_x000D_
"class": "ui-icon " + item.element.attr( "data-class" )_x000D_
})_x000D_
.appendTo( wrapper );_x000D_
_x000D_
return li.append( wrapper ).appendTo( ul );_x000D_
}_x000D_
});_x000D_
_x000D_
$( "#filesA" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget" )_x000D_
.addClass( "ui-menu-icons" );_x000D_
_x000D_
$( "#filesB" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget" )_x000D_
.addClass( "ui-menu-icons customicons" );_x000D_
_x000D_
$( "#people" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget")_x000D_
.addClass( "ui-menu-icons avatar" );_x000D_
} );_x000D_
</script>_x000D_
<style>_x000D_
h2 {_x000D_
margin: 30px 0 0 0;_x000D_
}_x000D_
fieldset {_x000D_
border: 0;_x000D_
}_x000D_
label
_x000D_
{_x000D_
display: block;_x000D_
}_x000D_
_x000D_
/* select with custom icons */_x000D_
.ui-selectmenu-menu .ui-menu.customicons .ui-menu-item-wrapper {_x000D_
padding: 0.5em 0 0.5em 3em;_x000D_
}_x000D_
.ui-selectmenu-menu .ui-menu.customicons .ui-menu-item .ui-icon {_x000D_
height: 24px;_x000D_
width: 24px;_x000D_
top: 0.1em;_x000D_
}_x000D_
.ui-icon.video {_x000D_
background: url("images/24-video-square.png") 0 0 no-repeat;_x000D_
}_x000D_
.ui-icon.podcast {_x000D_
background: url("images/24-podcast-square.png") 0 0 no-repeat;_x000D_
}_x000D_
.ui-icon.rss {_x000D_
background: url("images/24-rss-square.png") 0 0 no-repeat;_x000D_
}_x000D_
_x000D_
/* select with CSS avatar icons */_x000D_
option.avatar {_x000D_
background-repeat: no-repeat !important;_x000D_
padding-left: 20px;_x000D_
}_x000D_
.avatar .ui-icon {_x000D_
background-position: left top;_x000D_
}
_x000D_
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<title>jQuery UI Selectmenu - Custom Rendering</title>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="demo">_x000D_
_x000D_
<form action="#">_x000D_
<h2>Selectmenu with framework icons</h2>_x000D_
<fieldset>_x000D_
<label for="filesA">Select a File:</label>_x000D_
<select name="filesA" id="filesA">_x000D_
<option value="jquery" data-class="ui-icon-script">jQuery.js</option>_x000D_
<option value="jquerylogo" data-class="ui-icon-image">jQuery Logo</option>_x000D_
<option value="jqueryui" data-class="ui-icon-script">ui.jQuery.js</option>_x000D_
<option value="jqueryuilogo" selected="selected" data-class="ui-icon-image">jQuery UI Logo</option>_x000D_
<option value="somefile" disabled="disabled" data-class="ui-icon-help">Some unknown file</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
_x000D_
<h2>Selectmenu with custom icon images</h2>_x000D_
<fieldset>_x000D_
<label for="filesB">Select a podcast:</label>_x000D_
<select name="filesB" id="filesB">_x000D_
<option value="mypodcast" data-class="podcast">John Resig Podcast</option>_x000D_
<option value="myvideo" data-class="video">Scott González Video</option>_x000D_
<option value="myrss" data-class="rss">jQuery RSS XML</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
_x000D_
<h2>Selectmenu with custom avatar 16x16 images as CSS background</h2>_x000D_
<fieldset>_x000D_
<label for="people">Select a Person:</label>_x000D_
<select name="people" id="people">_x000D_
<option value="1" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/b3e04a46e85ad3e165d66f5d927eb609?d=monsterid&r=g&s=16');">John Resig</option>_x000D_
<option value="2" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/e42b1e5c7cfd2be0933e696e292a4d5f?d=monsterid&r=g&s=16');">Tauren Mills</option>_x000D_
<option value="3" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/bdeaec11dd663f26fa58ced0eb7facc8?d=monsterid&r=g&s=16');">Jane Doe</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
</form>_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Normally, if there's no guarantee that your input is in the '0'..'9' range, you'd have to perform a check like this:
if (c >= '0' && c <= '9') {
int v = c - '0';
// safely use v
}
An alternative is to use a lookup table. You get simple range checking and conversion with less (and possibly faster) code:
// one-time setup of an array of 256 integers;
// all slots set to -1 except for ones corresponding
// to the numeric characters
static const int CHAR_TO_NUMBER[] = {
-1, -1, -1, ...,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // '0'..'9'
-1, -1, -1, ...
};
// Now, all you need is:
int v = CHAR_TO_NUMBER[c];
if (v != -1) {
// safely use v
}
P.S. I know that this is an overkill. I just wanted to present it as an alternative solution that may not be immediately evident.
You have 2 options
1) Use javascript to confirm deletion (use onsubmit event handler), however if the client has JS disabled, you're in trouble.
2) Use PHP to echo out a confirmation message, along with the contents of the form (hidden if you like) as well as a submit button called "confirmation", in PHP check if $_POST["confirmation"]
is set.
int index = std::distance(std::begin(myArray), std::find(begin(myArray), end(std::myArray), VALUE));
Returns an invalid index (length of the array) if not found.
Suppose User has_many Posts:
u = User.first
u.posts.methods
u.posts.methods - Object.methods
Simply add these code before setting Adapter
it's working for me:
listView.destroyDrawingCache();
listView.setVisibility(ListView.INVISIBLE);
listView.setVisibility(ListView.VISIBLE);
Or Directly you can use below method after change Data resource.
adapter.notifyDataSetChanged()
The comparison of interface vs. abstract class is wrong. There should be two other comparisons instead: 1) interface vs. class and 2) abstract vs. final class.
Interface is a contract between two objects. E.g., I'm a Postman and you're a Package to deliver. I expect you to know your delivery address. When someone gives me a Package, it has to know its delivery address:
interface Package {
String address();
}
Class is a group of objects that obey the contract. E.g., I'm a box from "Box" group and I obey the contract required by the Postman. At the same time I obey other contracts:
class Box implements Package, Property {
@Override
String address() {
return "5th Street, New York, NY";
}
@Override
Human owner() {
// this method is part of another contract
}
}
Abstract class is a group of incomplete objects. They can't be used, because they miss some parts. E.g., I'm an abstract GPS-aware box - I know how to check my position on the map:
abstract class GpsBox implements Package {
@Override
public abstract String address();
protected Coordinates whereAmI() {
// connect to GPS and return my current position
}
}
This class, if inherited/extended by another class, can be very useful. But by itself - it is useless, since it can't have objects. Abstract classes can be building elements of final classes.
Final class is a group of complete objects, which can be used, but can't be modified. They know exactly how to work and what to do. E.g., I'm a Box that always goes to the address specified during its construction:
final class DirectBox implements Package {
private final String to;
public DirectBox(String addr) {
this.to = addr;
}
@Override
public String address() {
return this.to;
}
}
In most languages, like Java or C++, it is possible to have just a class, neither abstract nor final. Such a class can be inherited and can be instantiated. I don't think this is strictly in line with object-oriented paradigm, though.
Again, comparing interfaces with abstract classes is not correct.
I found a solution, which at least helps in my situation, it probably is not suitable for other situations:
I give all my green child divs a complete margin:
margin: 10px;
And for the surrounding yellow parent div i set a negative margin:
margin: -10px;
I also had to remove any explicit width or height setting for the yellow parent div, otherwise it did not work.
This way, in absolute terms, the child divs are correctly aligned, although the parent yellow div obviously is set off, which in my case is OK, because it will not be visible.
I found that the simplest way to achieve this is by adding the file.json under folder: assets.
No need to edit: .angular-cli.json
Service
@Injectable()
export class DataService {
getJsonData(): Promise<any[]>{
return this.http.get<any[]>('http://localhost:4200/assets/data.json').toPromise();
}
}
Component
private data: any[];
constructor(private dataService: DataService) {}
ngOnInit() {
data = [];
this.dataService.getJsonData()
.then( result => {
console.log('ALL Data: ', result);
data = result;
})
.catch( error => {
console.log('Error Getting Data: ', error);
});
}
Ideally, you only want to have this in a dev environment so to be bulletproof. create a variable on your environment.ts
export const environment = {
production: false,
baseAPIUrl: 'http://localhost:4200/assets/data.json'
};
Then replace the URL on the http.get for ${environment.baseAPIUrl}
And the environment.prod.ts
can have the production API URL.
Hope this helps!
fopen vs open in C
1) fopen
is a library function while open
is a system call.
2) fopen
provides buffered IO which is faster compare to open
which is non buffered.
3) fopen
is portable while open
not portable (open is environment specific).
4) fopen
returns a pointer to a FILE structure(FILE *); open
returns an integer that identifies the file.
5) A FILE *
gives you the ability to use fscanf and other stdio functions.
By default, most of distribution uses Ctrl+F12.
Some OS distribution (in my case Xubuntu) which uses Xcfe, overrides Ctrl+F12 to "Workspace 12" switch.
From oracle documentation page about ReentrantLock:
A reentrant mutual exclusion Lock with the same basic behaviour and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.
The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order.
ReentrantLock key features as per this article
You can use ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock to further acquire control on granular locking on read and write operations.
Have a look at this article by Benjamen on usage of different type of ReentrantLocks
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
To encode the characters, you can use CGI.escapeHTML
:
string = CGI.escapeHTML('test "escaping" <characters>')
To decode them, there is CGI.unescapeHTML
:
CGI.unescapeHTML("test "unescaping" <characters>")
Of course, before that you need to include the CGI library:
require 'cgi'
And if you're in Rails, you don't need to use CGI to encode the string. There's the h
method.
<%= h 'escaping <html>' %>
from bower help, save option has a capital S
-S, --save Save installed packages into the project's bower.json dependencies
JAXB is part of JDK standard edition version 1.6+. So it is FREE
and no extra libraries to download and manage.
A simple example can be found here
XStream seems to be dead. Last update was on Dec 6 2008.
Simple
seems as easy and simpler as JAXB but I could not find any licensing information to evaluate it for enterprise use.
Using the accepted answer and knowing that Object.values() is proposed in ECMAScript 2017 Draft you can extend Object with method:
if(Object.values == null) {
Object.values = function(obj) {
var arr, o;
arr = new Array();
for(o in obj) { arr.push(obj[o]); }
return arr;
}
}
Having the following blog
database table storing the blogs hosted by our platform:
And, we have two blogs currently hosted:
id | created_on | title | url |
---|---|---|---|
1 | 2013-09-30 | Vlad Mihalcea's Blog | https://vladmihalcea.com |
2 | 2017-01-22 | Hypersistence | https://hypersistence.io |
We need to build a report that extracts the following data from the blog
table:
If you're using PostgreSQL, then you have to execute the following SQL query:
SELECT
b.id as blog_id,
extract(
YEAR FROM age(now(), b.created_on)
) AS age_in_years,
date(
created_on + (
extract(YEAR FROM age(now(), b.created_on)) + 1
) * interval '1 year'
) AS next_anniversary,
date(
created_on + (
extract(YEAR FROM age(now(), b.created_on)) + 1
) * interval '1 year'
) - date(now()) AS days_to_next_anniversary
FROM blog b
ORDER BY blog_id
As you can see, the age_in_years
has to be defined three times because you need it when calculating the next_anniversary
and days_to_next_anniversary
values.
And, that's exactly where LATERAL JOIN can help us.
The following relational database systems support the LATERAL JOIN
syntax:
SQL Server can emulate the LATERAL JOIN
using CROSS APPLY
and OUTER APPLY
.
LATERAL JOIN allows us to reuse the age_in_years
value and just pass it further when calculating the next_anniversary
and days_to_next_anniversary
values.
The previous query can be rewritten to use the LATERAL JOIN, as follows:
SELECT
b.id as blog_id,
age_in_years,
date(
created_on + (age_in_years + 1) * interval '1 year'
) AS next_anniversary,
date(
created_on + (age_in_years + 1) * interval '1 year'
) - date(now()) AS days_to_next_anniversary
FROM blog b
CROSS JOIN LATERAL (
SELECT
cast(
extract(YEAR FROM age(now(), b.created_on)) AS int
) AS age_in_years
) AS t
ORDER BY blog_id
And, the age_in_years
value can be calculated one and reused for the next_anniversary
and days_to_next_anniversary
computations:
blog_id | age_in_years | next_anniversary | days_to_next_anniversary |
---|---|---|---|
1 | 7 | 2021-09-30 | 295 |
2 | 3 | 2021-01-22 | 44 |
Much better, right?
The age_in_years
is calculated for every record of the blog
table. So, it works like a correlated subquery, but the subquery records are joined with the primary table and, for this reason, we can reference the columns produced by the subquery.
A handy tool Convert SQL to Excel converts SQL table or SQL query result to Excel file without programming.
Main Features - Convert/export a SQL Table to Excel file - Convert/export multiple tables (multiple query results) to multiple Excel worksheets. - Allow flexible TSQL query which can have multiple SELECT statements or other complex query statements.
B. Regards, Alex
You can have return
in a void method, you just can't return any value (as in return 5;
), that's why they call it a void method. Some people always explicitly end void methods with a return statement, but it's not mandatory. It can be used to leave a function early, though:
void someFunct(int arg)
{
if (arg == 0)
{
//Leave because this is a bad value
return;
}
//Otherwise, do something
}
window.parent.caches.delete("call")
close and open the browser after executing the code in console.
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
To filter an array irrespective of the property type (i.e. for all property types), we can create a custom filter pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: "filter" })
export class ManualFilterPipe implements PipeTransform {
transform(itemList: any, searchKeyword: string) {
if (!itemList)
return [];
if (!searchKeyword)
return itemList;
let filteredList = [];
if (itemList.length > 0) {
searchKeyword = searchKeyword.toLowerCase();
itemList.forEach(item => {
//Object.values(item) => gives the list of all the property values of the 'item' object
let propValueList = Object.values(item);
for(let i=0;i<propValueList.length;i++)
{
if (propValueList[i]) {
if (propValueList[i].toString().toLowerCase().indexOf(searchKeyword) > -1)
{
filteredList.push(item);
break;
}
}
}
});
}
return filteredList;
}
}
//Usage
//<tr *ngFor="let company of companyList | filter: searchKeyword"></tr>
Don't forget to import the pipe in the app module
We might need to customize the logic to filer with dates.
In my case I only need to add to project's build.gradle file:
android {
packagingOptions {
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
}
...
}
Deleting a lot of rows can be very slow. Try to delete a few at a time, like:
delete top (10) YourTable where col in ('1','2','3','4')
while @@rowcount > 0
begin
delete top (10) YourTable where col in ('1','2','3','4')
end
You can use outline with outline offset
<div class="double-border"></div>
.double-border{
background-color:#ccc;
outline: 1px solid #f00;
outline-offset: 3px;
}
This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.
On the other hand, SQL Server would let you do what you are trying to achieve.
There are 2 workarounds here:
Both are, of course, stupid workarounds :)
I would also recommend the Tao Framework. But one additional note:
Take a look at these tutorials: http://www.taumuon.co.uk/jabuka/
The show method does what you're looking for.
For example, given the following dataframe of 3 rows, I can print just the first two rows like this:
df = sqlContext.createDataFrame([("foo", 1), ("bar", 2), ("baz", 3)], ('k', 'v'))
df.show(n=2)
which yields:
+---+---+
| k| v|
+---+---+
|foo| 1|
|bar| 2|
+---+---+
only showing top 2 rows
Adding screen shots(examples) and some more context for the answer of @Thomas G.
import pandas as pd
is ran properly before checking below shortcut.Place the cursor in middle of parenthesis ()
before you use shortcut.
shift + tab
Display short document and few params
shift + tab + tab
Expands document with scroll bar
shift + tab + tab + tab
Provides document with a Tooltip: "will linger for 10secs while you type". which means it allows you write params and waits for 10secs.
shift + tab + tab + tab + tab
It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.
Try below code to get currently loaded product id:
$product_id = $this->getProduct()->getId();
When you don’t have access to $this, you can use Magento registry:
$product_id = Mage::registry('current_product')->getId();
Also for product type i think
$product = Mage::getModel('catalog/product')->load($product_id);
$productType = $product->getTypeId();
Opening the debug console in Chrome, or even looking at the html source file (after it is loaded in the browser), make sure that all the paths there are valid (i.e. when you follow a link you get to it's content, and not an error). When something is not valid, fix the path (e.g. get rid of the server specific part and make sure you only refer to files that are part of your extension through paths like /js/jquery-123-min.js
).
Check this out.
http://jsfiddle.net/LD55x/
Code:
var myobj = {};
myobj.name="javascriptisawesome";
myobj.age=25;
myobj.mobile=123456789;
debugger;
var str = JSON.stringify(myobj);
alert(str);
var obj = JSON.parse(str);
alert(obj);
Try this to detect the Enter
key pressed in a textbox.
$(function(){
$(".input1").keyup(function (e) {
if (e.which == 13) {
// Enter key pressed
}
});
});
You can use np.logaddexp
(which implements the idea in @gg349's answer):
In [33]: d = np.array([[1089, 1093]])
In [34]: e = np.array([[1000, 4443]])
In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])
In [36]: log_res
Out[36]: -266.99999385580668
In [37]: res = exp(log_res)
In [38]: res
Out[38]: 1.1050349147204485e-116
Or you can use scipy.special.logsumexp
:
In [52]: from scipy.special import logsumexp
In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))
In [54]: res
Out[54]: 1.1050349147204485e-116
I was looking for a different problem and came across this, so I will add my solution to a related problem: comparing two Maps.
// make a copy of the data
Map<String,String> a = new HashMap<String,String>(actual);
Map<String,String> e = new HashMap<String,String>(expected);
// check *every* expected value
for(Map.Entry<String, String> val : e.entrySet()){
// check for presence
if(!a.containsKey(val.getKey())){
System.out.println(String.format("Did not find expected value: %s", val.getKey()));
}
// check for equality
else{
if(0 != a.get(val.getKey()).compareTo(val.getValue())){
System.out.println(String.format("Value does not match expected: %s", val.getValue()));
}
// we have found the item, so remove it
// from future consideration. While it
// doesn't affect Java Maps, other types of sets
// may contain duplicates, this will flag those
// duplicates.
a.remove(val.getKey());
}
}
// check to see that we did not receive extra values
for(Map.Entry<String,String> val : a.entrySet()){
System.out.println(String.format("Found unexpected value: %s", val.getKey()));
}
It works on the same principle as the other solutions but also compares not only that values are present, but that they contain the same value. Mostly I've used this in accounting software when comparing data from two sources (Employee and Manager entered values match; Customer and Corporate transactions match; ... etc)
Have you tried the following expression ..?
0 19 * * 1,3,5
Phonegap can be a little tricky for freshers. I spent much time trying to find the optimum way for creating a robust android application which can access the phone's native features.
This link provides a step wise method for creating a Phonegap android application using windows, html and javascript.
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeDon't customize your bootstrap CSS by directly editing bootstrap CSS file.Instead, I suggest to copy paste bootstrap CSS and save them in a different CSS folder and there you can customize or edit stylings suitable to your needs.
Look at this pandas three-way joining multiple dataframes on columns
filenames = ['fn1', 'fn2', 'fn3', 'fn4',....]
dfs = [pd.read_csv(filename, index_col=index_col) for filename in filenames)]
dfs[0].join(dfs[1:])
They are right. IMG is a content element and CSS is about design. But, how about when you use some content elements or properties for design purposes? I have IMG across my web pages that must change if i change the style (the CSS).
Well this is a solution for defining IMG presentation (no really the image) in CSS style.
It works like a charm :)
You have to put the entire path as a parameter to os.path.split. See The docs. It doesn't work like string split.
You have to use:
abs() for int
fabs() for double
fabsf() for float
Above function will also work but you can also try something like this.
if(a<0)
{
a=-a;
}
You can use
sessionStorage.SessionName = "SessionData"
,
sessionStorage.getItem("SessionName")
and
sessionStorage.setItem("SessionName","SessionData");
See the supported browsers on http://caniuse.com/namevalue-storage
slaveOk does not work anymore. One needs to use readPreference https://docs.mongodb.com/v3.0/reference/read-preference/#primaryPreferred
e.g.
const client = new MongoClient(mongoURL + "?readPreference=primaryPreferred", { useUnifiedTopology: true, useNewUrlParser: true });
For changing visibility:
predictbtn.setVisibility(View.INVISIBLE);
For removing:
predictbtn.setVisibility(View.GONE);
You can get it with .outerHeight()
.
Sometimes, it will return 0
. For the best results, you can call it in your div
's ready event.
To be safe, you should not set the height of the div
to x
. You can keep its height auto
to get content populated properly with the correct height.
$('#x').ready( function(){
// alerts the height in pixels
alert($('#x').outerHeight());
})
You can find a detailed post here.
I tried all the above and it did not work.
I found that in spite of uninstalling the app a new version of the app still gives the same error.
This is what solved it: go to Settings -> General -> application Manager -> choose your app -> click on the three dots on the top -> uninstall for all users
Once you do this, now it is actually uninstalled and will now allow your new version to install.
Hope this helps.
Found the solution:
It should be:
"{'Id1':'2','Id2':'2'}"
and not
"{'Id1':'2'},{'Id2':'2'}"
It's called a favicon. It is inserted like this:
<link rel="shortcut icon" href="favicon.ico" />
window.onclick = e => {
console.dir(e.target); // use this in chrome
console.log(e.target); // use this in firefox - click on tag name to view
}
take advantage of using filter propeties
e.target.tagName
e.target.className
e.target.style.height // its not the value applied from the css style sheet, to get that values use `getComputedStyle()`
Open up your git bash and type
echo $HOME
This shall be the same folder as you get when you open your command window (cmd) and type
echo %USERPROFILE%
And – of course – the .ssh
folder shall be present on THAT directory.
Use strlen
to get the length of a null-terminated string.
sizeof
returns the length of the array not the string. If it's a pointer (char *s
), not an array (char s[]
), it won't work, since it will return the size of the pointer (usually 4 bytes on 32-bit systems). I believe an array will be passed or returned as a pointer, so you'd lose the ability to use sizeof
to check the size of the array.
So, only if the string spans the entire array (e.g. char s[] = "stuff"
), would using sizeof
for a statically defined array return what you want (and be faster as it wouldn't need to loop through to find the null-terminator) (if the last character is a null-terminator, you will need to subtract 1). If it doesn't span the entire array, it won't return what you want.
An alternative to all this is actually storing the size of the string.
Just finished a 2 hour wild goose chase trying to solve this. None of the posted answers worked for me. Im on a Mac (Mojave Version 10.14.6, Xcode Version 11.3).
It turns out the ruby file headers were missing so i had to run open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
That didnt work for me at first because the version of CommandLineTools i had installed did not have the "Packages" folder. So i uninstalled and reinstalled like this:
rm -rf /Library/Developer/CommandLineTools
xcode-select --install
Then i ran the previous command again:
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
After install the error was fixed!
While I tried the approach above, it becomes a complete disaster with mvc. Your controller passing a model and your view using a strongly typed model become too difficult to work with.
Get your Dataset into a List ..... I have a repository pattern and here is an example of getting a dataset from an old school asmx web service private readonly CISOnlineSRVDEV.ServiceSoapClient _ServiceSoapClient;
public Get_Client_Repository()
: this(new CISOnlineSRVDEV.ServiceSoapClient())
{
}
public Get_Client_Repository(CISOnlineSRVDEV.ServiceSoapClient serviceSoapClient)
{
_ServiceSoapClient = serviceSoapClient;
}
public IEnumerable<IClient> GetClient(IClient client)
{
// **** Calling teh web service with passing in the clientId and returning a dataset
DataSet dataSet = _ServiceSoapClient.get_clients(client.RbhaId,
client.ClientId,
client.AhcccsId,
client.LastName,
client.FirstName,
"");//client.BirthDate.ToString()); //TODO: NEED TO FIX
// USE LINQ to go through the dataset to make it easily available for the Model to display on the View page
List<IClient> clients = (from c in dataSet.Tables[0].AsEnumerable()
select new Client()
{
RbhaId = c[5].ToString(),
ClientId = c[2].ToString(),
AhcccsId = c[6].ToString(),
LastName = c[0].ToString(), // Add another field called Sex M/F c[4]
FirstName = c[1].ToString(),
BirthDate = c[3].ToDateTime() //extension helper ToDateTime()
}).ToList<IClient>();
return clients;
}
Then in the Controller I'm doing this
IClient client = (IClient)TempData["Client"];
// Instantiate and instance of the repository
var repository = new Get_Client_Repository();
// Set a model object to return the dynamic list from repository method call passing in the parameter data
var model = repository.GetClient(client);
// Call the View up passing in the data from the list
return View(model);
Then in the View it is easy :
@model IEnumerable<CISOnlineMVC.DAL.IClient>
@{
ViewBag.Title = "CLIENT ALL INFORMATION";
}
<h2>CLIENT ALL INFORMATION</h2>
<table>
<tr>
<th></th>
<th>Last Name</th>
<th>First Name</th>
<th>Client ID</th>
<th>DOB</th>
<th>Gender</th>
<th>RBHA ID</th>
<th>AHCCCS ID</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Select", "ClientDetails", "Cis", new { id = item.ClientId }, null) |
</td>
<td>
@item.LastName
</td>
<td>
@item.FirstName
</td>
<td>
@item.ClientId
</td>
<td>
@item.BirthDate
</td>
<td>
Gender @* ADD in*@
</td>
<td>
@item.RbhaId
</td>
<td>
@item.AhcccsId
</td>
</tr>
}
</table>
I used mkdir -p /root/.android && touch /root/.android/repositories.cfg to make it works
I've found this page on their github repo, I'll just paste the content here.
There are two main approaches for serializing and restoring a model.
The first (recommended) saves and loads only the model parameters:
torch.save(the_model.state_dict(), PATH)
Then later:
the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))
The second saves and loads the entire model:
torch.save(the_model, PATH)
Then later:
the_model = torch.load(PATH)
However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.
There is definitly a problem with the destination folder path.
Your above error message says, it wants to put the contents to a file in the directory /files/grantapps/
, which would be beyond your vhost
, but somewhere in the system (see the leading absolute slash )
You should double check:
/home/username/public_html/files/grantapps/
really present./home/username/public_html/files/grantapps/
Here's a nice function that allows this:
public static void animateBetweenColors(final @NonNull View viewToAnimateItsBackground, final int colorFrom,
final int colorTo, final int durationInMs) {
final ColorDrawable colorDrawable = new ColorDrawable(durationInMs > 0 ? colorFrom : colorTo);
ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable);
if (durationInMs > 0) {
final ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.addUpdateListener(animator -> {
colorDrawable.setColor((Integer) animator.getAnimatedValue());
ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable);
});
colorAnimation.setDuration(durationInMs);
colorAnimation.start();
}
}
And in Kotlin:
@JvmStatic
fun animateBetweenColors(viewToAnimateItsBackground: View, colorFrom: Int, colorTo: Int, durationInMs: Int) {
val colorDrawable = ColorDrawable(if (durationInMs > 0) colorFrom else colorTo)
ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable)
if (durationInMs > 0) {
val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo)
colorAnimation.addUpdateListener { animator: ValueAnimator ->
colorDrawable.color = (animator.animatedValue as Int)
ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable)
}
colorAnimation.duration = durationInMs.toLong()
colorAnimation.start()
}
}
Are you calling the web service from client script or on the server side?
You may find sending a content type header to the server will help, e.g.
'application/json; charset=utf-8'
On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.
push
does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:
import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {
arr:[]
}
export default function userState(state = initialUserState, action){
console.log(arr);
switch (action.type){
case ADD_ITEM :
return {
...state,
arr:[...state.arr, action.newItem]
}
default:return state
}
}
Sydius outlined the types fairly well:
How about when you should use them? You will either make heavy use of scoped pointers or shared pointers. How many threads are running in your application? If the answer is "potentially a lot", shared pointers can turn out to be a performance bottleneck if used everywhere. The reason being that creating/copying/destructing a shared pointer needs to be an atomic operation, and this can hinder performance if you have many threads running. However, it won't always be the case - only testing will tell you for sure.
There is an argument (that I like) against shared pointers - by using them, you are allowing programmers to ignore who owns a pointer. This can lead to tricky situations with circular references (Java will detect these, but shared pointers cannot) or general programmer laziness in a large code base.
There are two reasons to use scoped pointers. The first is for simple exception safety and cleanup operations - if you want to guarantee that an object is cleaned up no matter what in the face of exceptions, and you don't want to stack allocate that object, put it in a scoped pointer. If the operation is a success, you can feel free to transfer it over to a shared pointer, but in the meantime save the overhead with a scoped pointer.
The other case is when you want clear object ownership. Some teams prefer this, some do not. For instance, a data structure may return pointers to internal objects. Under a scoped pointer, it would return a raw pointer or reference that should be treated as a weak reference - it is an error to access that pointer after the data structure that owns it is destructed, and it is an error to delete it. Under a shared pointer, the owning object can't destruct the internal data it returned if someone still holds a handle on it - this could leave resources open for much longer than necessary, or much worse depending on the code.
i have a simple solution without lot of changes. the initial statement is
I want to break the if statement above and stop executing echo "yes"; or such codes which are no longer necessary to be executed, there may be or may not be an additional condition, is there way to do this?
so, it seem simple. try code like this.
$a="test";
if("test"==$a)
{
if (1==0){
echo "yes"; // this line while never be executed.
// and can be reexecuted simply by changing if (1==0) to if (1==1)
}
}
echo "finish";
if you want to try without this code, it's simple. and you can back when you want. another solution is comment blocks. or simply thinking and try in another separated code and copy paste only the result in your final code. and if a code is no longer nescessary, in your case, the result can be
$a="test";
echo "finish";
with this code, the original statement is completely respected.. :) and more readable!
If need to copy from another table then need to copy structure first:
DataTable copyDt = existentDt.Clone();
copyDt.ImportRow(existentDt.Rows[0]);
this worked for me inside a directive and works without refreshing the baseurl (just adds the endpoint).Good for Single Page Apps with routing mechanism.
$(location).attr('href', 'http://localhost:10005/#/endpoint')
PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:
Using this will save you extra coding on cross platform developments.
IE.
$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);
If you looped through this twice you would see in 'somefile':
some data
some data
Just create the variables in a class. And then inherit from that class to access its variables. But before accessing them, the parent class has to be called to initiate the variables.
class a:
def func1(self):
a.var1 = "Stack "
class b:
def func2(self):
b.var2 = "Overflow"
class c(a,b):
def func3(self):
c.var3 = a.var1 + b.var2
print(c.var3)
a().func1()
b().func2()
c().func3()
Try closing your text editor (maybe VS Code) and File Explorer and run the command again in terminal with admin permissions.
Very simple example, similar to the one found here:
http://docs.python.org/tutorial/errors.html#defining-clean-up-actions
If you're attempting to catch ALL exceptions, then put all your code within the "try:" statement, in place of 'print "Performing an action which may throw an exception."'.
try:
print "Performing an action which may throw an exception."
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
In the above example, you'd see output in this order:
1) Performing an action which may throw an exception.
2) Finally is called directly after executing the try statement whether an exception is thrown or not.
3) "An exception was thrown!" or "Everything looks great!" depending on whether an exception was thrown.
Hope this helps!
You can use:
public YourClass[] AllProducts()
{
try
{
using (UserDataDataContext db = new UserDataDataContext())
{
return db.mrobProducts.Where(x => x.Status == 1)
.OrderBy(x => x.ID)
.Select(x => new YourClass { ID = x.ID, Name = x.Name, Price = x.Price})
.ToArray();
}
}
catch
{
return null;
}
}
And here is YourClass
implementation:
public class YourClass
{
public string Name {get; set;}
public int ID {get; set;}
public int Price {get; set;}
}
And your AllProducts
method's return type must be YourClass[]
.
In 2020 using r115 it works very good with this:
const renderer = new THREE.WebGLRenderer({ alpha: true });
const scene = new THREE.Scene();
scene.background = null;
I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
If you want to redirect the output to a log file to look for errors or something. You can do something like this.
sqlplus -s <<EOF>> LOG_FILE_NAME user/passwd@host/db
#Your SQL code
EOF
Look in JavaScript split() Method
Usage:
"something -- something_else".split(" -- ")
In iOS 7 you must use the -barTintColor property:
navController.navigationBar.barTintColor = [UIColor barColor];
document.getElementById("my").className = 'myclass';
var result = from cx in CustomerList
group cx by cx.GroupID into cxGroup
orderby cxGroup.Key
select cxGroup;
foreach (var cxGroup in result) {
Console.WriteLine(String.Format("GroupID = {0}", cxGroup.Key));
foreach (var cx in cxGroup) {
Console.WriteLine(String.Format("\tUserID = {0}, UserName = {1}, GroupID = {2}",
new object[] { cx.ID, cx.Name, cx.GroupID }));
}
}
nc or 'netcat' also has a scan mode which may be of use.
I suspect you're only reporting the last error in a stack like this:
ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "schema.package" has been invalidated
ORA-04065: not executed, altered or dropped package body "schema.package"
ORA-06508: PL/SQL: could not find program unit being called: "schema.package"
If so, that's because your package is stateful:
The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state. If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.
When you recompile the state is lost:
If the body of an instantiated, stateful package is recompiled (either explicitly, with the "ALTER PACKAGE Statement", or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.
After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it...
You can't avoid this if your package has state. I think it's fairly rare to really need a package to be stateful though, so you should revisit anything you have declared in the package, but outside a function or procedure, to see if it's really needed at that level. Since you're on 10g though, that includes constants, not just variables and cursors.
But the last paragraph from the quoted documentation means that the next time you reference the package in the same session, you won't get the error and it will work as normal (until you recompile again).
it's a pure PHP setting. The alternative is to increase the execution time limit only for specific php scripts, by inserting on top of that php file, the following:
ini_set('max_execution_time', 180); //3 minutes
To get public static void main(String[] args) line in eclipse without typing the whole line type "main" and press Ctrl + space then, you will get the option for the main method select it.
dlocate -s apache2 | grep '^Version:'
In my case (after renaming application namespace manually) I had to reselect the Startup object in Project properties.
I've had a similar requirement: I needed to inject a Spring-managed repository bean into my Person
entity class ("entity" as in "something with an identity", for example an JPA entity). A Person
instance has friends, and for this Person
instance to return its friends, it shall delegate to its repository and query for friends there.
@Entity
public class Person {
private static PersonRepository personRepository;
@Id
@GeneratedValue
private long id;
public static void setPersonRepository(PersonRepository personRepository){
this.personRepository = personRepository;
}
public Set<Person> getFriends(){
return personRepository.getFriends(id);
}
...
}
.
@Repository
public class PersonRepository {
public Person get Person(long id) {
// do database-related stuff
}
public Set<Person> getFriends(long id) {
// do database-related stuff
}
...
}
So how did I inject that PersonRepository
singleton into the static field of the Person
class?
I created a @Configuration
, which gets picked up at Spring ApplicationContext construction time. This @Configuration
gets injected with all those beans that I need to inject as static fields into other classes. Then with a @PostConstruct
annotation, I catch a hook to do all static field injection logic.
@Configuration
public class StaticFieldInjectionConfiguration {
@Inject
private PersonRepository personRepository;
@PostConstruct
private void init() {
Person.setPersonRepository(personRepository);
}
}