You can also increase it via the VM arguments in your IDE. In my case, I am using Tomcat v7.0 which is running on Eclipse. To do this, double click on your server (Tomcat v7.0). Click the 'Open launch configuration' link. Go to the 'Arguments' tab. Add -XX:MaxPermSize=512m to the VM arguments list. Click 'Apply' and then 'OK'. Restart your server.
select replace(ImagePath, '~/', '../') as NewImagePath from tblMyTable
where "ImagePath" is my column Name.
"NewImagePath" is temporery column Name insted of "ImagePath"
"~/" is my current string.(old string)
"../" is my requried string.(new string)
"tblMyTable" is my table in database.
I have used pdf2image. A simple python library that works like charm.
First install poppler on non linux machine. You can just download the zip. Unzip in Program Files and add bin to Machine Path.
After that you can use pdf2image in python class like this:
from pdf2image import convert_from_path, convert_from_bytes
images_from_path = convert_from_path(
inputfile,
output_folder=outputpath,
grayscale=True, fmt='jpeg')
I am not good with python but was able to make exe of it. Later you may use the exe with file input and output parameter. I have used it in C# and things are working fine.
Image quality is good. OCR works fine.
I made a small investigation because I am also interested in the solution.
According to http://books.sonatype.com/mvnref-book/reference/running-sect-options.html#running-sect-verbose-option
Currently maven 3.1.x uses SLF4J to log to the System.out . You can modify the logging settings at the file:
${MAVEN_HOME}/conf/logging/simplelogger.properties
According to the page : http://maven.apache.org/maven-logging.html
I think you should be able to setup the default Log level of the simple logger via a command line parameter, like this:
$ mvn clean package -Dorg.slf4j.simpleLogger.defaultLogLevel=debug
But I could not get it to work. I guess the only problem with this is, maven picks up the default level from the config file on the classpath. I also tried a couple of other settings via System.properties, but all of them were unsuccessful.
You can find the source of slf4j on github here : slf4j github
The source of the simplelogger here : slf4j/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SimpleLog.java
The plexus loader loads the simplelogger.properties
.
To provide a bit more clarity, let's look at a DataFrame with two levels in its index (a MultiIndex).
index = pd.MultiIndex.from_product([['TX', 'FL', 'CA'],
['North', 'South']],
names=['State', 'Direction'])
df = pd.DataFrame(index=index,
data=np.random.randint(0, 10, (6,4)),
columns=list('abcd'))
The reset_index
method, called with the default parameters, converts all index levels to columns and uses a simple RangeIndex
as new index.
df.reset_index()
Use the level
parameter to control which index levels are converted into columns. If possible, use the level name, which is more explicit. If there are no level names, you can refer to each level by its integer location, which begin at 0 from the outside. You can use a scalar value here or a list of all the indexes you would like to reset.
df.reset_index(level='State') # same as df.reset_index(level=0)
In the rare event that you want to preserve the index and turn the index into a column, you can do the following:
# for a single level
df.assign(State=df.index.get_level_values('State'))
# for all levels
df.assign(**df.index.to_frame())
Seems like Firebug or whatever Debugger you are using, is not initialized properly. Are you sure Firebug is fully initialized when you try to access the console.log()-method? Check the Console-Tab (if it's set to activated).
Another possibility could be, that you overwrite the console-Object yourself anywhere in the code.
I followed these instructions but then found that the menu hover color was wrong.
I am using the Spacegray theme in Sublime 3 beta 3074. So to accomplish the sidebar font color change and also hover color change, on OSX, I created a new file ~/Library/"Application Support"/"Sublime Text 3"/Packages/User/Spacegray.sublime-theme
then added this code to it:
[
{
"class": "sidebar_label",
"color": [192,197,203],
"font.bold": false,
"font.size": 15
},
{
"class": "sidebar_label",
"parents": [{"class": "tree_row","attributes": ["hover"]}],
"color": [255,255,255]
},
]
It is possible to tweak many other settings for your theme if you can see the original default:
https://gist.github.com/nateflink/0355eee823b89fe7681e
I extracted this file from the sublime package zip file by installing the PackageResourceViewer following MattDMo's instructions (https://stackoverflow.com/users/1426065/mattdmo) here:
For .nupkg files I like to use:
Install-Package C:\Path\To\Some\File.nupkg
If you using roles you could check for ROLE_USER
that is the solution i use:
if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
// user is logged in
}
If you haven't install mysql_client
yet and using Docker
container instead:
sudo docker exec MySQL_CONTAINER_NAME /usr/bin/mysqldump --host=192.168.1.1 -u username --password=password db_name > dump.sql
This is due because of the items id being the same. On change fires only if a different item id is detected on select.
So you have 2 options: First is to make sure that each items have a unique id when retrieving datas from ajax.
Second is to trigger a rand number at formatSelection for the selected item.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
.
formatSelection: function(item) {item.id =getRandomInt(1,200)}
You can write like this:
img{
width:100%;
max-width:600px;
}
Check this http://jsfiddle.net/ErNeT/
There is an even simpler way
LocalDateTime.now(Clock.systemUTC())
try this one, user json to serialize and deserialize:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
object newobj = new object();
for (int i = 0; i < 10; i++)
{
List<int> temp = new List<int>();
temp.Add(i);
temp.Add(i + 1);
newobj = newobj.AddNewField("item_" + i.ToString(), temp.ToArray());
}
}
}
public static class DynamicExtention
{
public static object AddNewField(this object obj, string key, object value)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string data = js.Serialize(obj);
string newPrametr = "\"" + key + "\":" + js.Serialize(value);
if (data.Length == 2)
{
data = data.Insert(1, newPrametr);
}
else
{
data = data.Insert(data.Length-1, ","+newPrametr);
}
return js.DeserializeObject(data);
}
}
}
Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.
In my case this amounted to defining my column as:
`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''
This is in my opinion preferential to adjusting your queries.
Here my answer :
<form onsubmit="event.preventDefault();searchOrder(event);">
...
</form>
<script>
const searchOrder = e => {
e.preventDefault();
const name = e.target.name.value;
renderSearching();
return false;
}
</script>
I add event.preventDefault();
on onsubmit
and it works.
After more than five years I answer my question. I think that the problem with a negative duration can be solved by a simple correction:
LocalDateTime fromDateTime = LocalDateTime.of(2014, 9, 9, 7, 46, 45);
LocalDateTime toDateTime = LocalDateTime.of(2014, 9, 10, 6, 46, 45);
Period period = Period.between(fromDateTime.toLocalDate(), toDateTime.toLocalDate());
Duration duration = Duration.between(fromDateTime.toLocalTime(), toDateTime.toLocalTime());
if (duration.isNegative()) {
period = period.minusDays(1);
duration = duration.plusDays(1);
}
long seconds = duration.getSeconds();
long hours = seconds / SECONDS_PER_HOUR;
long minutes = ((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
long secs = (seconds % SECONDS_PER_MINUTE);
long time[] = {hours, minutes, secs};
System.out.println(period.getYears() + " years "
+ period.getMonths() + " months "
+ period.getDays() + " days "
+ time[0] + " hours "
+ time[1] + " minutes "
+ time[2] + " seconds.");
Note: The site https://www.epochconverter.com/date-difference now correctly calculates the time difference.
Thank you all for your discussion and suggestions.
This doesn't use jQuery UI, but does use jQuery, and may be useful for those who aren't using jQuery UI for whatever reason. Do it like so:
function showDialog(){
$('#dialog').show();
$('*').on('click',function(e){
$('#zoomer').hide();
});
}
$(document).ready(function(){
showDialog();
});
So, once I've shown a dialog, I add a click handler that only looks for the first click on anything.
Now, it would be nicer if I could get it to ignore clicks on anything on #dialog and its contents, but when I tried switching $('*') with $(':not("#dialog,#dialog *")'), it still detected #dialog clicks.
Anyway, I was using this purely for a photo lightbox, so it worked okay for that purpose.
I had the same problem. Try this.
<nav>
<ul>
<li><a href="#">AnaSayfa</a></li>
<li><a href="#">Hakkimizda</a></li>
<li><a href="#">Iletisim</a></li>
</ul>
</nav>
@charset "utf-8";
nav {
background-color: #9900CC;
height: 80px;
width: 400px;
}
ul {
list-style: none;
float: right;
margin: 0;
}
li {
float: left;
width: 100px;
line-height: 80px;
vertical-align: middle;
text-align: center;
margin: 0;
}
nav li a {
width: 100px;
text-decoration: none;
color: #FFFFFF;
}
Yes;
git commit FILE
will commit just FILE. Then you can use
git reset --hard
to undo local changes in other files.
There may be other ways too that I don't know about...
edit: or, as NicDumZ said, git-checkout just the files you want to undo the changes on (the best solution depends on wether there are more files to commit or more files to undo :-)
I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:
div.hardware-accelarate {
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
I've made a plunkr setup for ya'll to test and tweak...
Since no one* has mentioned it: concurrency. Static variables can surprise you if you have multiple threads reading and writing to the static variable. This is common in web applications (e.g., ASP.NET) and it can cause some rather maddening bugs. For example, if you have a static variable that is updated by a page, and the page is requested by two people at "nearly the same time", one user may get the result expected by the other user, or worse.
statics reduce the inter-dependencies on the other parts of the code. They can act as perfect state holders
I hope you're prepared to use locks and deal with contention.
*Actually, Preet Sangha mentioned it.
As a workaround, go to sdk installation directory and perform the following steps:
system-images/android-19/default
system-images/android-19/
The directory structure should look like this:
And it should work!
You can't unless you're using some kind of extended CSS such as SASS. However it is very reasonable to apply those two extra classes to .someDiv
.
If .someDiv
is unique I would also choose to give it an id and referencing it in css using the id.
this looks like PHP to me. I'll delete if it's some other language.
Simply unset($arr[1]);
I found the solution go to
settings>build,execute,deployment>instant run>Enable instant run to hot swap code /resource change on deploy(unchecked this option)
`
Easiest way is to use +strVal or Number(strVal)
Examples:
let strVal1 = "123.5"
let strVal2 = "One"
let val1a = +strVal1
let val1b = Number(strVal1)
let val1c = parseFloat(strVal1)
let val1d = parseInt(strVal1)
let val1e = +strVal1 - parseInt(strVal1)
let val2a = +strVal2
console.log("val1a->", val1a) // 123.5
console.log("val1b->", val1b) // 123.5
console.log("val1c->", val1c) // 123.5
console.log("val1d->", val1d) // 123
console.log("val1e->", val1e) // 0.5
console.log("val2a->", val2a) // NaN
It's fairly easy using the New-SelfSignedCertificate command in Powershell. Open powershell and run these 3 commands.
1) Create certificate:
$cert = New-SelfSignedCertificate -DnsName www.yourwebsite.com -Type CodeSigning -CertStoreLocation Cert:\CurrentUser\My2) set the password for it:
$CertPassword = ConvertTo-SecureString -String "my_passowrd" -Force –AsPlainText3) Export it:
Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath "d:\selfsigncert.pfx" -Password $CertPassword
Your certificate selfsigncert.pfx will be located @ D:/
Optional step: You would also require to add certificate password to system environment variables. do so by entering below in cmd: setx CSC_KEY_PASSWORD "my_password"
You can set it as a no title bar theme in the activity's xml in the AndroidManifest
<activity
android:name=".AnActivity"
android:label="@string/a_string"
android:theme="@android:style/Theme.NoTitleBar">
</activity>
I did a little research and was able to write this code:
strbody = "<BODY style=font-size:11pt;font-family:Calibri>Good Morning;<p>We have completed our main aliasing process for today. All assigned firms are complete. Please feel free to respond with any questions.<p>Thank you.</BODY>"
apparently by setting the "font-size=11pt"
instead of setting the font size <font size=5>
,
It allows you to select a specific font size like you normally would in a text editor, as opposed to selecting a value from 1-7 like my code was originally.
This link from simpLE MAn gave me some good info.
The method System.Web.UI.Page.RegisterClientScriptBlock has been deprecated for some time (along with the other Page.Register* methods), ever since .NET 2.0 as shown by MSDN.
Instead use the .NET 2.0 Page.ClientScript.Register* methods. - (The ClientScript property expresses an instance of the ClientScriptManager class )
Guessing the problem
If you are saying your JavaScript alert box occurs before the page's content is visibly rendered, and therefore the page remains white (or still unrendered) when the alert box is dismissed by the user, then try using the Page.ClientScript.RegisterStartupScript(..) method instead because it runs the given client-side code when the page finishes loading - and its arguments are similar to what you're using already.
Also check for general JavaScript errors in the page - this is often seen by an error icon in the browser's status bar. Sometimes a JavaScript error will hold up or disturb unrelated elements on the page.
In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.
In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".
You could prepare the query for inserting one row using the mysqli_stmt class, and then iterate over the array of data. Something like:
$stmt = $db->stmt_init();
$stmt->prepare("INSERT INTO mytbl (fld1, fld2, fld3, fld4) VALUES(?, ?, ?, ?)");
foreach($myarray as $row)
{
$stmt->bind_param('idsb', $row['fld1'], $row['fld2'], $row['fld3'], $row['fld4']);
$stmt->execute();
}
$stmt->close();
Where 'idsb' are the types of the data you're binding (int, double, string, blob).
TL&DR: When you typically get data from a server, it is sent in bytes. The rationale is that these bytes will need to be 'decoded' by the recipient, who should know how to use the data. You should decode the binary upon arrival to not get 'b' (bytes) but instead a string.
Use case:
import requests
def get_data_from_url(url):
response = requests.get(url_to_visit)
response_data_split_by_line = response.content.decode('utf-8').splitlines()
return response_data_split_by_line
In this example, I decode the content that I received into UTF-8. For my purposes, I then split it by line, so I can loop through each line with a for loop.
<?php
//create table
/*
--
-- Database: `mydb`
--
-- --------------------------------------------------------
--
-- Table structure for table `tbl_user_data`
--
CREATE TABLE `tbl_user_data` (
`attachment_id` int(11) NOT NULL,
`attachment` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tbl_user_data`
--
ALTER TABLE `tbl_user_data`
ADD PRIMARY KEY (`attachment_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_user_data`
--
ALTER TABLE `tbl_user_data`
MODIFY `attachment_id` int(11) NOT NULL AUTO_INCREMENT;
*/
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$fileName=$_FILES["resume"]["name"];
$fileSize=$_FILES["resume"]["size"]/1024;
$fileType=$_FILES["resume"]["type"];
$fileTmpName=$_FILES["resume"]["tmp_name"];
$statusMsg = '';
$random=rand(1111,9999);
$newFileName=$random.$fileName;
//file upload path
$targetDir = "resumeUpload/";
$fileName = basename($_FILES["resume"]["name"]);
$targetFilePath = $targetDir . $newFileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(!empty($_FILES["resume"]["name"])) {
//allow certain file formats
//$allowTypes = array('jpg','png','jpeg','gif','pdf','docx','doc');
$allowTypes = array('pdf','docx','doc');
if(in_array($fileType, $allowTypes)){
//upload file to server
if(move_uploaded_file($_FILES["resume"]["tmp_name"], $targetFilePath)){
$statusMsg = "The file ".$fileName. " has been uploaded.";
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only DOC,DOCX, & PDF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
//display status message
echo $statusMsg;
$sql="INSERT INTO `tbl_user_data` (`attachment_id`, `attachment`) VALUES
('NULL', '$newFileName')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "upload success";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
<form id="frm_upload" action="" method="post" enctype="multipart/form-data">
Upload Resume:<input type="file" name="resume" id="resume">
<button type="submit" name="submit">Apply Now</button>
</form>
//output sample[![check here for sample output][1]][1]
With pivot_data as
(
select
action, -- grouping column
view_edit -- spreading column
from tbl
)
select action, [view], [edit]
from pivot_data
pivot ( max(view_edit) for view_edit in ([view], [edit]) ) as p;
OPTION 1 worked for me, in PHP 7, and for sure it does in PHP 5 too. And the global scope declaration is not necessary for the included file for variables access, the included - or "required" - files are part of the script, only be sure you make the "include" AFTER the variable declaration. Maybe you have some misconfiguration with variables global scope in your PHP.ini?
Try in first file:
<?php
$myvariable="from first file";
include ("./mysecondfile.php"); // in same folder as first file LOLL
?>
mysecondfile.php
<?php
echo "this is my variable ". $myvariable;
?>
It should work... if it doesn't just try to reinstall PHP.
I resolved this by adding following code to the HTML page, since we are using the third party API which is not controlled by us.
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
Hope this would help, and for a record as well.
Disclaimer: While the top answer is probably a better solution, as a beginner it's a lot to take in when all you want is something very simple. This is intended as a more direct answer to your original question "How can I select certain elements in React"
I think the confusion in your question is because you have React components which you are being passed the id "Progress1", "Progress2" etc. I believe this is not setting the html attribute 'id', but the React component property. e.g.
class ProgressBar extends React.Component {
constructor(props) {
super(props)
this.state = {
id: this.props.id <--- ID set from <ProgressBar id="Progress1"/>
}
}
}
As mentioned in some of the answers above you absolutely can use document.querySelector
inside of your React app, but you have to be clear that it is selecting the html output of your components' render methods. So assuming your render output looks like this:
render () {
const id = this.state.id
return (<div id={"progress-bar-" + id}></div>)
}
Then you can elsewhere do a normal javascript querySelector call like this:
let element = document.querySelector('#progress-bar-Progress1')
The number in parentheses specifies the precision of fractional seconds to be stored. So, (0)
would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.
So an unspecified value would store a date like:
TIMESTAMP 24-JAN-2012 08.00.05.993847 AM
And specifying (0)
stores only:
TIMESTAMP(0) 24-JAN-2012 08.00.05 AM
I was googling about how to convert an int to char, that got me here. But my question was to convert for example int of 6 to char of '6'. For those who came here like me, this is how to do it:
int num = 6;
num.ToString().ToCharArray()[0];
In Spring or Spring boot application.properties file here is the way to escape the special characters;
table.whereclause=where id'\='100
In my personal opinion trailing slashes are misused.
Basically the URL format came from the same UNIX format of files and folders, later on, on DOS systems, and finally, adapted for the web.
A typical URL for this book on a Unix-like operating system would be a file path such as file:///home/username/RomeoAndJuliet.pdf, identifying the electronic book saved in a file on a local hard disk.
Source: Wikipedia: Uniform Resource Identifier
Another good source to read: Wikipedia: URI Scheme
According to RFC 1738, which defined URLs in 1994, when resources contain references to other resources, they can use relative links to define the location of the second resource as if to say, "in the same place as this one except with the following relative path". It went on to say that such relative URLs are dependent on the original URL containing a hierarchical structure against which the relative link is based, and that the ftp, http, and file URL schemes are examples of some that can be considered hierarchical, with the components of the hierarchy being separated by "/".
Source: Wikipedia Uniform Resource Locator (URL)
Also:
That is the question we hear often. Onward to the answers! Historically, it’s common for URLs with a trailing slash to indicate a directory, and those without a trailing slash to denote a file:
http://example.com/foo/ (with trailing slash, conventionally a directory)
http://example.com/foo (without trailing slash, conventionally a file)
Source: Google WebMaster Central Blog - To slash or not to slash
Finally:
A slash at the end of the URL makes the address look "pretty".
A URL without a slash at the end and without an extension looks somewhat "weird".
You will never name your CSS file (for example) http://www.sample.com/stylesheet/ would you?
BUT I'm being a proponent of web best practices regardless of the environment. It can be wonky and unclear, just as you said about the URL with no ext.
I believe this technically answers the question, but don't do this at home. At the moment, all answers involve creating a new tuple, but you can use ctypes
to modify a tuple in-memory. Relying on various implementation details of CPython on a 64-bit system, one way to do this is as follows:
def modify_tuple(t, idx, new_value):
# `id` happens to give the memory address in CPython; you may
# want to use `ctypes.addressof` instead.
element_ptr = (ctypes.c_longlong).from_address(id(t) + (3 + idx)*8)
element_ptr.value = id(new_value)
# Manually increment the reference count to `new_value` to pretend that
# this is not a terrible idea.
ref_count = (ctypes.c_longlong).from_address(id(new_value))
ref_count.value += 1
t = (10, 20, 30)
modify_tuple(t, 1, 50) # t is now (10, 50, 30)
modify_tuple(t, -1, 50) # Will probably crash your Python runtime
It’s because you tried to update a table without a WHERE that uses a KEY column.
The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :
SET SQL_SAFE_UPDATES=0;
Or
close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .
BTW you can use TRUNCATE TABLE tablename;
to delete all the records .
private static int SecondBiggest(int[] vector)
{
if (vector == null)
{
throw new ArgumentNullException("vector");
}
if (vector.Length < 2)
{
return int.MinValue;
}
int max1 = vector[0];
int max2 = vector[1];
for (int i = 2; i < vector.Length; ++i)
{
if (max1 > max2 && max1 != vector[i])
{
max2 = Math.Max(max2, vector[i]);
}
else if (max2 != vector[i])
{
max1 = Math.Max(max1, vector[i]);
}
}
return Math.Min(max1, max2);
}
This treats duplicates as the same number. You can change the condition checks if you want to all the biggest and the second biggest to be duplicates.
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
Here is how I do it:
var hashTagActive = "";
$(".scroll").on("click touchstart" , function (event) {
if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
event.preventDefault();
//calculate destination place
var dest = 0;
if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
dest = $(document).height() - $(window).height();
} else {
dest = $(this.hash).offset().top;
}
//go to destination
$('html,body').animate({
scrollTop: dest
}, 2000, 'swing');
hashTagActive = this.hash;
}
});
Then you just need to create your anchor like this:
<a class="scroll" href="#destination1">Destination 1</a>
You can see it on my website.
A demo is also available here: http://jsfiddle.net/YtJcL/
You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.
Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.
import csv
inf = csv.reader(open('yourfile.csv','r'))
for row in inf:
print row[1]
In the DOM, a tr
element is (implicitly or explicitly) a child of tbody
, thead
, or tfoot
, not a child of table
(hence the 0 you got). So a general answer is:
var count = $('#gvPerformanceResult > * > tr').length;
This includes the rows of the table but excludes rows of any inner table.
You may have imported,
project/controllers/base
inside the
project/controllers/routes
You have already imported before. That's not supported.
Try setting 'clientCredentialType' to 'Windows' instead of 'Ntlm'.
I think that this is what the server is expecting - i.e. when it says the server expects "Negotiate,NTLM", that actually means Windows Auth, where it will try to use Kerberos if available, or fall back to NTLM if not (hence the 'negotiate')
I'm basing this on somewhat reading between the lines of: Selecting a Credential Type
Swift 5 Solution
Follow these four steps:
Set the height constraint for the tableview from the storyboard.
Drag the height constraint from the storyboard and create @IBOutlet
for it in the view controller file.
@IBOutlet var tableViewHeightConstraint: NSLayoutConstraint!
Add an observer for the contentSize property on the override func viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
}
Then you can change the height for the table dynamicaly using this code:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if(keyPath == "contentSize"){
if let newvalue = change?[.newKey]
{
DispatchQueue.main.async {
let newsize = newvalue as! CGSize
self.tableViewHeightConstraint.constant = newsize.height
}
}
}
}
You don't have to manipulate $PATH
anymore!
From [email protected], npm ships with npx
package which lets you run commands from a local node_modules/.bin
or from a central cache.
Simply run:
$ npx [options] <command>[@version] [command-arg]...
By default, npx
will check whether <command>
exists in $PATH
, or in the local project binaries, and execute that.
Calling npx <command>
when <command>
isn't already in your $PATH
will automatically install a package with that name from the NPM registry for you, and invoke it. When it's done, the installed package won’t be anywhere in your globals, so you won’t have to worry about pollution in the long-term. You can prevent this behaviour by providing --no-install
option.
For npm < 5.2.0
, you can install npx
package manually by running the following command:
$ npm install -g npx
$(".class").click(function(){
alert($(this).attr('id'));
});
only on jquery button click we can do this class should be written there
Without using external tools, if you are connecting to the server view SSH, this is a relatively easy command:
From a Windows 7+ command prompt:
ssh user@server cat /etc/passwd | clip
This will put the content of the remote file to your local clipboard.
(The command requires running Pageant for the key, or it will ask you for a password.)
I use something like this (you should add code to deal with the various fails):
var response = RunTaskWithTimeout<ReturnType>(
(Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);
/// <summary>
/// Generic method to run a task on a background thread with a specific timeout, if the task fails,
/// notifies a user
/// </summary>
/// <typeparam name="T">Return type of function</typeparam>
/// <param name="TaskAction">Function delegate for task to perform</param>
/// <param name="TimeoutSeconds">Time to allow before task times out</param>
/// <returns></returns>
private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
{
Task<T> backgroundTask;
try
{
backgroundTask = Task.Factory.StartNew(TaskAction);
backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
}
catch (AggregateException ex)
{
// task failed
var failMessage = ex.Flatten().InnerException.Message);
return default(T);
}
catch (Exception ex)
{
// task failed
var failMessage = ex.Message;
return default(T);
}
if (!backgroundTask.IsCompleted)
{
// task timed out
return default(T);
}
// task succeeded
return backgroundTask.Result;
}
I think there is a lot of confusion about which weights are used for what. I am not sure I know precisely what bothers you so I am going to cover different topics, bear with me ;).
The weights from the class_weight
parameter are used to train the classifier.
They are not used in the calculation of any of the metrics you are using: with different class weights, the numbers will be different simply because the classifier is different.
Basically in every scikit-learn classifier, the class weights are used to tell your model how important a class is. That means that during the training, the classifier will make extra efforts to classify properly the classes with high weights.
How they do that is algorithm-specific. If you want details about how it works for SVC and the doc does not make sense to you, feel free to mention it.
Once you have a classifier, you want to know how well it is performing.
Here you can use the metrics you mentioned: accuracy
, recall_score
, f1_score
...
Usually when the class distribution is unbalanced, accuracy is considered a poor choice as it gives high scores to models which just predict the most frequent class.
I will not detail all these metrics but note that, with the exception of accuracy
, they are naturally applied at the class level: as you can see in this print
of a classification report they are defined for each class. They rely on concepts such as true positives
or false negative
that require defining which class is the positive one.
precision recall f1-score support
0 0.65 1.00 0.79 17
1 0.57 0.75 0.65 16
2 0.33 0.06 0.10 17
avg / total 0.52 0.60 0.51 50
F1 score:/usr/local/lib/python2.7/site-packages/sklearn/metrics/classification.py:676: DeprecationWarning: The
default `weighted` averaging is deprecated, and from version 0.18,
use of precision, recall or F-score with multiclass or multilabel data
or pos_label=None will result in an exception. Please set an explicit
value for `average`, one of (None, 'micro', 'macro', 'weighted',
'samples'). In cross validation use, for instance,
scoring="f1_weighted" instead of scoring="f1".
You get this warning because you are using the f1-score, recall and precision without defining how they should be computed! The question could be rephrased: from the above classification report, how do you output one global number for the f1-score? You could:
avg / total
result above. It's also called macro averaging.'weighted'
in scikit-learn will weigh the f1-score by the support of the class: the more elements a class has, the more important the f1-score for this class in the computation.These are 3 of the options in scikit-learn, the warning is there to say you have to pick one. So you have to specify an average
argument for the score method.
Which one you choose is up to how you want to measure the performance of the classifier: for instance macro-averaging does not take class imbalance into account and the f1-score of class 1 will be just as important as the f1-score of class 5. If you use weighted averaging however you'll get more importance for the class 5.
The whole argument specification in these metrics is not super-clear in scikit-learn right now, it will get better in version 0.18 according to the docs. They are removing some non-obvious standard behavior and they are issuing warnings so that developers notice it.
Last thing I want to mention (feel free to skip it if you're aware of it) is that scores are only meaningful if they are computed on data that the classifier has never seen. This is extremely important as any score you get on data that was used in fitting the classifier is completely irrelevant.
Here's a way to do it using StratifiedShuffleSplit
, which gives you a random splits of your data (after shuffling) that preserve the label distribution.
from sklearn.datasets import make_classification
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix
# We use a utility to generate artificial classification data.
X, y = make_classification(n_samples=100, n_informative=10, n_classes=3)
sss = StratifiedShuffleSplit(y, n_iter=1, test_size=0.5, random_state=0)
for train_idx, test_idx in sss:
X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
svc.fit(X_train, y_train)
y_pred = svc.predict(X_test)
print(f1_score(y_test, y_pred, average="macro"))
print(precision_score(y_test, y_pred, average="macro"))
print(recall_score(y_test, y_pred, average="macro"))
Hope this helps.
Is there any particular reason that you need to use find
? You can just use ls
to find files that match a pattern in a directory.
ls /dev/abc-*
If you do need to use find
, you can use the -maxdepth 1
switch to only apply to the specified directory.
I found that using the Common Event described above works well and you could have the common event set up like this:
private void checkChanged(object sender, EventArgs e)
{
foreach (RadioButton r in yourPanel.Controls)
{
if (r.Checked)
textBox.Text = r.Text;
}
}
Of course, then you can't have other controls in your panel that you use, but it's useful if you just have a separate panel for all your radio buttons (such as using a sub panel inside a group box or however you prefer to organize your controls)
your line raising the error is here:
comment = Comment.objects.get(pk=comment_id)
you try to access a non-existing comment.
from django.shortcuts import get_object_or_404
comment = get_object_or_404(Comment, pk=comment_id)
Instead of having an error on your server, your user will get a 404 meaning that he tries to access a non existing resource.
Ok up to here I suppose you are aware of this.
Some users (and I'm part of them) let tabs running for long time, if users are authorized to delete data, it may happens. A 404 error may be a better error to handle a deleted resource error than sending an email to the admin.
Other users go to addresses from their history, (same if data have been deleted since it may happens).
>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
In some cases we could have a couple of tables, and then we need to detect click just for particular table. My solution is this:
<table id="elitable" border="1" cellspacing="0" width="100%">
<tr>
<td>100</td><td>AAA</td><td>aaa</td>
</tr>
<tr>
<td>200</td><td>BBB</td><td>bbb</td>
</tr>
<tr>
<td>300</td><td>CCC</td><td>ccc</td>
</tr>
</table>
<script>
$(function(){
$("#elitable tr").click(function(){
alert (this.rowIndex);
});
});
</script>
For those who created rating bar programmatically and want set small rating bar instead of default big rating bar
private LinearLayout generateRatingView(float value){ LinearLayout linearLayoutRating=new LinearLayout(getContext()); linearLayoutRating.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); linearLayoutRating.setGravity(Gravity.CENTER); RatingBar ratingBar = new RatingBar(getContext(),null, android.R.attr.ratingBarStyleSmall); ratingBar.setEnabled(false); ratingBar.setStepSize(Float.parseFloat("0.5"));//for enabling half star ratingBar.setNumStars(5); ratingBar.setRating(value); linearLayoutRating.addView(ratingBar); return linearLayoutRating; }
Using java.time
framework built into Java 8 and later.
The DayOfWeek
enum can generate a String of the day’s name automatically localized to the human language and cultural norms of a Locale
. Specify a TextStyle
to indicate you want long form or abbreviated name.
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.TextStyle
import java.util.Locale
import java.time.DayOfWeek;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy");
LocalDate date = LocalDate.parse("23/2/2010", formatter); // LocalDate = 2010-02-23
DayOfWeek dow = date.getDayOfWeek(); // Extracts a `DayOfWeek` enum object.
String output = dow.getDisplayName(TextStyle.SHORT, Locale.US); // String = Tue
A functional requirement describes what a software system should do, while non-functional requirements place constraints on how the system will do so.
Let me elaborate.
An example of a functional requirement would be:
A related non-functional requirement for the system may be:
The functional requirement is describing the behavior of the system as it relates to the system's functionality. The non-functional requirement elaborates a performance characteristic of the system.
Typically non-functional requirements fall into areas such as:
A more complete list is available at Wikipedia's entry for non-functional requirements.
Non-functional requirements are sometimes defined in terms of metrics (i.e. something that can be measured about the system) to make them more tangible. Non-functional requirements may also describe aspects of the system that don't relate to its execution, but rather to its evolution over time (e.g. maintainability, extensibility, documentation, etc.).
If you are interested in the indexes, the best choice is np.argsort(a)
a = np.random.randint(0, 100, 10)
sorted_idx = np.argsort(a)
In your XML set the Background
attribute to any colour, White(#FFFFFF)
shade or Black(#000000)
shade. If you want transparency, just put 80 before the actual hash code:
#80000000
This will change any colour you want to a transparent one.. :)
I found the answer today. Maybe its too late but still I think its a much better one. Check this one https://jsfiddle.net/Amar_newDev/khb2oyru/5/
Try to change the CSS code : <ul> max-width:1%; margin:auto; text-align:left; </ul>
max-width:80% or something like that.
Try experimenting you might find something new.
Use atoi() from <stdlib.h>
http://linux.die.net/man/3/atoi
Or, write your own atoi()
function which will convert char*
to int
int a2i(const char *s)
{
int sign=1;
if(*s == '-'){
sign = -1;
s++;
}
int num=0;
while(*s){
num=((*s)-'0')+num*10;
s++;
}
return num*sign;
}
Skip reading the html and use curl
to POST whatever form data you want to submit to the server.
I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular expressions even if they aren't needed.
For example:
LIGHT_MESSAGES = {
'English': "There are %(number_of_lights)s lights.",
'Pirate': "Arr! Thar be %(number_of_lights)s lights."
}
def lights_message(language, number_of_lights):
"""Return a language-appropriate string reporting the light count."""
return LIGHT_MESSAGES[language] % locals()
def is_pirate(message):
"""Return True if the given message sounds piratical."""
return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None
Apply CSS table-layout:fixed;
(and sometimes width:<any px or %>
) to the TABLE and white-space: nowrap; overflow: hidden;
style on TD. Then set CSS widths on the correct cell or column elements.
Significantly, fixed-layout table column widths are determined by the cell widths in the first row of the table. If there are TH elements in the first row, and widths are applied to TD (and not TH), then the width only applies to the contents of the TD (white-space and overflow may be ignored); the table columns will distribute evenly regardless of the set TD width (because there are no widths specified [on TH in the first row]) and the columns will have [calculated] equal widths; the table will not recalculate the column width based on TD width in subsequent rows. Set the width on the first cell elements the table will encounter.
Alternatively, and the safest way to set column widths is to use <COLGROUP>
and <COL>
tags in the table with the CSS width set on each fixed width COL. Cell width related CSS plays nicer when the table knows the column widths in advance.
That's a great way to do it. Might want to make sure its output is back an array again. Now you're only showing the last unique value.
Try this:
$arrDuplicate = array ("","",1,3,"",5);
foreach (array_unique($arrDuplicate) as $v){
if($v != "") { $arrRemoved[] = $v; }
}
print_r ($arrRemoved);
To differentiate or compare these 2, you should know what REST is.
REST (REpresentational State Transfer) is basically an architectural style of development having some principles:
It should be stateless
It should access all the resources from the server using only URI
It does not have inbuilt encryption
It does not have session
It uses one and only one protocol - HTTP
For performing CRUD operations, it should use HTTP verbs such as get
, post
, put
and delete
It should return the result only in the form of JSON or XML, atom, OData etc. (lightweight data )
REST based services
follow some of the above principles and not all
RESTFUL services
means it follows all the above principles.
It is similar to the concept of:
Object oriented languages
support all the OOP concepts, examples: C++, C#
Object-based languages
support some of the OOP features, examples: JavaScript, VB
Example:
ASP Dot NET MVC 4 is REST-Based
while Microsoft WEB API is RESTFul
.
MVC supports only some of the above REST principles whereas WEB API supports all the above REST Principles.
MVC only supports the following from the REST API
We can access the resource using URI
It supports the HTTP verb to access the resource from server
It can return the results in the form of JSON, XML, that is the HTTPResponse.
However, at the same time in MVC
We can use the session
We can make it stateful
We can return video or image from the controller action method which basically violates the REST principles
That is why MVC is REST-Based
whereas WEB API supports all the above principles and is RESTFul
.
I faced the same error when displaying YouTube links.
For example: https://www.youtube.com/watch?v=8WkuChVeL0s
I replaced watch?v=
with embed/
so the valid link will be:
https://www.youtube.com/embed/8WkuChVeL0s
It works well.
Try to apply the same rule on your case.
Image by default is displayed as inline-block, you need to display it as block in order to center it with .mx-auto
. This can be done with built-in .d-block
:
<div class="container">
<div class="row">
<div class="col-4">
<img class="mx-auto d-block" src="...">
</div>
</div>
</div>
Or leave it as inline-block and wrapped it in a div with .text-center
:
<div class="container">
<div class="row">
<div class="col-4">
<div class="text-center">
<img src="...">
</div>
</div>
</div>
</div>
I made a fiddle showing both ways. They are documented here as well.
A useful application for : is if you're only interested in using parameter expansions for their side-effects rather than actually passing their result to a command. In that case you use the PE as an argument to either : or false depending upon whether you want an exit status of 0 or 1. An example might be : "${var:=$1}"
. Since :
is a builtin it should be pretty fast.
Use vscode-solution-explorer
extension:
This extension adds a Visual Studio Solution File explorer panel in Visual Studio Code. Now you can navigate into your solution following the original Visual Studio structure.
https://github.com/fernandoescolar/vscode-solution-explorer
Thanks @fernandoescolar
Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
alert("Hello!");
}
</script>
</body>
</html>
Copy Paste this in an HTML file and run in any browser , this should show an alert using javascript.
You Can approach this way:
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>
or this way:
<option *ngFor="let workout of workouts" [attr.value]="workout.name" [attr.selected]="workout.name == 'leg' ? true : null">{{workout.name}}</option>
or you can set default value this way:
<option [value]="null">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>
or
<option [value]="0">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>
You can do the following :-
$(document).ready(function(){
$("#id").trigger("click");
});
I had the same problem, running X64 Java (1.7.0_03-b05)
. Even though I had both C:\Program Files\Java\jre7\bin
and C:\Program Files\Java\jdk1.7.0_03\bin
listed in my path, it wouldn't start - just flashed a command prompt.
The tools\lib\find_java.bat
file was reporting that it was attempting to run C:\Windows\system32\java.exe
but failed. Huh? I checked, and found outdated copies of java.exe
, javaw.exe
and javaws.exe
in my C:\Windows\system32
. How did those get there, I didn't put them there!
I deleted those three files from C:\Windows\system32
and the problem was fixed.
Thinking about it, the problem likely would have been fixed by making sure thatC:\Program Files\Java\jre7\bin
and C:\Program Files\Java\jdk1.7.0_03\bin
were at the START of my PATH variable instead of tacked onto the end.
If you are using Multidex on Android 4.4 and prior, your issue might be that your activity class is located in the second dex file and therefore not found by the android system.
To keep your activity class in the main dex file, see this page:
https://developer.android.com/studio/build/multidex.html#keep
To find which classes are located in a dex file use Android Studio.
Simply drag n drop your apk into Android Studio. You should be able to see your dex files in the apk explorer.
Then select the dex file to see what classes are inside.
another alternative is dexdump:
You can check the content of your dex files contained in your apk by using the command dexdump which can be found in
android-sdk/build-tools/27.0.3/dexdump
For windows users see this tool I made to ease the process
I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader
's fault. Try measuring this:
InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing
I think you'll find it's almost exactly the same time as when you're parsing the text.
Note that you should also give InputStreamReader
an appropriate encoding - the platform default encoding is almost certainly not what you should be using.
Passing variables between the windows (if your windows are on the same domain) can be easily done via:
In my case git push
was trying to push more that just the current branch, therefore, I got this error since the other branches were not in sync.
To fix that you could use: git config --global push.default simple
That will make git to only push the current branch.
This will only work on more recent versions of git. i.e.: won't work on 1.7.9.5
In bash, we use
declare -A name_of_dictonary_variable
so that Bash understands it is a dictionary.
For e.g. you want to create sounds
dictionary then,
declare -A sounds
sounds[dog]="Bark"
sounds[wolf]="Howl"
where dog
and wolf
are "keys"
, and Bark
and Howl
are "values"
.
You can access all values using : echo ${sounds[@]}
OR echo ${sounds[*]}
You can access all keys only using: echo ${!sounds[@]}
And if you want any value for a particular key, you can use:
${sounds[dog]}
this will give you value (Bark
) for key (Dog
).
You must put all columns of the SELECT
in the GROUP BY
or use functions on them which compress the results to a single value (like MIN
, MAX
or SUM
).
A simple example to understand why this happens: Imagine you have a database like this:
FOO BAR
0 A
0 B
and you run SELECT * FROM table GROUP BY foo
. This means the database must return a single row as result with the first column 0
to fulfill the GROUP BY
but there are now two values of bar
to chose from. Which result would you expect - A
or B
? Or should the database return more than one row, violating the contract of GROUP BY
?
To rotate the x-axis label to 90 degrees
for tick in ax.get_xticklabels():
tick.set_rotation(45)
The bootstrap 3 documentation lists this under helper classes:
Muted
, Primary
, Success
, Info
, Warning
, Danger
.
The bootstrap 4 documentation lists this under utilities -> color, and has more options:
primary
, secondary
, success
, danger
, warning
, info
, light
, dark
, muted
, white
.
To access them one uses the class
text-[class-name]
So, if I want the primary text color for example I would do something like this:
<p class="text-primary">This text is the primary color.</p>
This is not a huge number of choices, but it's some.
None of the above answers worked for me, here is my solution which updates a disabled input with the filename:
<script type="text/javascript">
document.getElementById('img_name').onchange = function () {
var filePath = this.value;
if (filePath) {
var fileName = filePath.replace(/^.*?([^\\\/]*)$/, '$1');
document.getElementById('img_name_input').value = fileName;
}
};
</script>
Building off of Vaali's solution:
def sparse_cosine_similarity(sparse_matrix):
out = (sparse_matrix.copy() if type(sparse_matrix) is csr_matrix else
sparse_matrix.tocsr())
squared = out.multiply(out)
sqrt_sum_squared_rows = np.array(np.sqrt(squared.sum(axis=1)))[:, 0]
row_indices, col_indices = out.nonzero()
out.data /= sqrt_sum_squared_rows[row_indices]
return out.dot(out.T)
This takes a sparse matrix (preferably a csr_matrix) and returns a csr_matrix. It should do the more intensive parts using sparse calculations with pretty minimal memory overhead. I haven't tested it extensively though, so caveat emptor (Update: I feel confident in this solution now that I've tested and benchmarked it)
Also, here is the sparse version of Waylon's solution in case it helps anyone, not sure which solution is actually better.
def sparse_cosine_similarity_b(sparse_matrix):
input_csr_matrix = sparse_matrix.tocsr()
similarity = input_csr_matrix * input_csr_matrix.T
square_mag = similarity.diagonal()
inv_square_mag = 1 / square_mag
inv_square_mag[np.isinf(inv_square_mag)] = 0
inv_mag = np.sqrt(inv_square_mag)
return similarity.multiply(inv_mag).T.multiply(inv_mag)
Both solutions seem to have parity with sklearn.metrics.pairwise.cosine_similarity
:-D
Update:
Now I have tested both solutions against my existing Cython implementation: https://github.com/davidmashburn/sparse_dot/blob/master/test/benchmarks_v3_output_table.txt and it looks like the first algorithm performs the best of the three most of the time.
You can set the Hadoop home directory by sending a -Dhadoop.home.dir to the VM. To send this parameters to all your application that you execute inside eclipse, you can set them in Window->Preferences->Java->Installed JREs-> (select your JRE installation) -> Edit.. -> (set the value in the "Default VM arguments:" textbox). You can replace ${HADOOP_HOME} with the path to your Hadoop installation.
This is an easy way to present the message if any data is input into the form, and not to show the message if the form is submitted:
$(function () {
$("input, textarea, select").on("input change", function() {
window.onbeforeunload = window.onbeforeunload || function (e) {
return "You have unsaved changes. Do you want to leave this page and lose your changes?";
};
});
$("form").on("submit", function() {
window.onbeforeunload = null;
});
})
Since you want the trailing string from the input, you can use %n
(number of characters consumed thus far) to get the position at which the trailing string starts. This avoids memory copies and buffer sizing issues, but comes at the cost that you may need to do them explicitly if you wanted a copy.
const char *input = "19 cool kid";
int age;
int nameStart = 0;
sscanf(input, "%d %n", &age, &nameStart);
printf("%s is %d years old\n", input + nameStart, age);
outputs:
cool kid is 19 years old
For those who came here looking for "how to get All input of POST" only
class Illuminate\Http\Request
extends from Symfony\Component\HttpFoundation\Request
which has two class variables that store request parameters.
public $query
- for GET parameters
public $request
- for POST parameters
Usage: To get a post data only
$request = Request::instance();
$request->request->all(); //Get all post requests
$request->request->get('my_param'); //Get a post parameter
Source here
EDIT
For Laravel >= 5.5, you can simply call $request->post()
or $request->post('my_param')
which internally calls $request->request->all()
or $request->request->get('my_param')
respectively.
You have to reimplement it using <xsl:choose>
tag:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2> mooooooooooooo </h2>
</xsl:when>
<xsl:otherwise>
<h2> dooooooooooooo </h2>
</xsl:otherwise>
</xsl:choose>
In your component i.e angular js code:
function getthefile (){
window.location.href='http://localhost:1036/CourseRegConfirm/getfile';
};
This was my solution for evaluating file sizes without using VB/perl/etc. and sticking with native windows shell commands:
FOR /F "tokens=4 delims= " %%i in ('dir /-C %temp% ^| find /i "filename.txt"') do (
IF %%i GTR 1000000 (
echo filename.txt filesize is greater than 1000000
) ELSE (
echo filename.txt filesize is less than 1000000
)
)
Not the cleanest solution, but it gets the job done.
If you are happy with "blah" in somestring
but want it to be a function/method call, you can probably do this
import operator
if not operator.contains(somestring, "blah"):
continue
All operators in Python can be more or less found in the operator module including in
.
Using C# it's very easy to start a batch command without having a window open. Have a look at the following code example:
Process process = new Process();
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "doSomeBatch.bat";
process.Start();
For me on Windows 8, I simply found openssl.cnf file and copied it on the C drive. then:
openssl req -new -key server.key -out server.csr -config C:\openssl.cnf
Worked perfectly.
Update Feb. 2021, as noted by Abhishek Singh in the comments, and Nat Friedman on Twitter:
You can now – finally! – drop images and videos (mp4, gif) onto the Markdown file editor on GitHub.
Paste works too, if you're into that kind of thing.
It's worked in issues and PRs for a while; what's new here is support in markdown files.GitHub Enterprise Server tends to lag http://github.com by a couple of months, but it will get there in a future release.
Kyle Daigle (Senior Director of Special Projects at GitHub) adds:
Currently, the file is stored as an asset outside the repository (sort of like an image uploaded to an image).
(Uploads to githubusercontent and stores it there. Then makes a link in the markdown to that uploaded image.)The team is interested in exploring adding the image to the repo too... would you want something like that?
Sven-Michael Stübe comments:
I usually add the images to my repo. Especially if you host your blog as github page w/ a custom domain.
But I think this feature would also add a lot of complexity. It's not a big pain to add the image manually. For PRs+Comments the drag&drop is more essential
Kyle answers:
For the blog case (which is what made us think about image upload to the repo) you're totally right.
This type of drag and drop is helpful when adding an image to aREADME
or other in-repo documentation though (when you don't want to upload to the repo).
That feature has come a long way since its initial proposal... back in 2012(!)
Update Dec. 2020: see "Video upload public beta ", which embeds video (embedding only, not link/reference)
2010: The "Github Flavored Markdown" doesn't support this kind of feature for any page:
An old support thread "Embed YouTube videos in markdown files" stated:
With
pages.github.io
, yes, everywhere else, no.
(Note: as detailed in "Github Top-Level Project Page", github.io is the new domain for user and organization pages since April 2013.
The page GitHub publication is presented here)
This could be a feature request like the syntax highlighting was.
For instance: "HTML5 video in markdown" (August 2010):
Is there any way to implement a HTML5 video into the
README.markdown
file?Not currently but we might be expanding what you can do with the READMEs in the future.
In the meantime, you can do this with GitHub Pages and our Wikis.
Benjamin Oakes confirms in the comments (May 2012):
I sent in a support request. The response was that embedding videos is not supported.
Surround it with a div and give it a border and remove the border from the table
<div style="border: 1px solid black">
<table border="0">
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>one</td>
<td>two</td>
</tr>
</table>
</div>
You can check the working fiddle here
As per your updated question .... where you want to add or remove borders. You should remove borders from the html table first and then do the following
<td style="border-top: 1px solid black">
Assuming like you only want the top border. Similarly you have to do for others. Better way create four css class...
.topBorderOnly {
border-top: 1px solid black;
}
.bottomBorderOnly {
border-bottom: 1px solid black;
}
Then add the css to your code depending on the requirements.
<td class="topBorderOnly bottomBorderOnly">
This will add both top and bottom border, similarly do for the rest.
First you should ask yourself the following question: Do you really need an int?
The purpose of enums is to have a collection of items (constants), that have a meaning in the code without relying on an external value (like an int). Enums in Java can be used as an argument on switch statments and they can safely be compared using "==" equality operator (among others).
Proposal 1 (no int needed) :
Often there is no need for an integer behind it, then simply use this:
private enum DownloadType{
AUDIO, VIDEO, AUDIO_AND_VIDEO
}
Usage:
DownloadType downloadType = MyObj.getDownloadType();
if (downloadType == DownloadType.AUDIO) {
//...
}
//or
switch (downloadType) {
case AUDIO: //...
break;
case VIDEO: //...
break;
case AUDIO_AND_VIDEO: //...
break;
}
Proposal 2 (int needed) :
Nevertheless, sometimes it may be useful to convert an enum to an int (for instance if an external API expects int values). In this case I would advise to mark the methods as conversion methods using the toXxx()
-Style. For printing override toString()
.
private enum DownloadType {
AUDIO(2), VIDEO(5), AUDIO_AND_VIDEO(11);
private final int code;
private DownloadType(int code) {
this.code = code;
}
public int toInt() {
return code;
}
public String toString() {
//only override toString, if the returned value has a meaning for the
//human viewing this value
return String.valueOf(code);
}
}
System.out.println(DownloadType.AUDIO.toInt()); //returns 2
System.out.println(DownloadType.AUDIO); //returns 2 via `toString/code`
System.out.println(DownloadType.AUDIO.ordinal()); //returns 0
System.out.println(DownloadType.AUDIO.name()); //returns AUDIO
System.out.println(DownloadType.VIDEO.toInt()); //returns 5
System.out.println(DownloadType.VIDEO.ordinal()); //returns 1
System.out.println(DownloadType.AUDIO_AND_VIDEO.toInt()); //returns 11
Summary
ordinal()
for getting an integer of an enum, because this value may change, if you change the order (for example by inserting a value). If you are considering to use ordinal()
it might be better to use proposal 1.UglifyJS2, used by the jQuery project.
^(0|[1-9][0-9]*)$
At https://github.com/golang/go/issues/44196 randall77 suggested
time.Now().Sub(time.Unix(0,0)).Milliseconds()
which exploits the fact that Go's time.Duration
already have Milliseconds
method.
Thanks Alex your second point helped me fix this.
It appears that unless you run visual studio as an administrator in Windows 7 it stores your temp files locally rather than C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files.
See following blog post: http://www.dotnetscraps.com/dotnetscraps/post/Location-of-Temporary-ASPNET-files-in-Vista-or-Windows-7.aspx
I did all of the suggested stuff here and my code still did not work because I was using curl
If you are using curl
in the php file, curl seems to reject all ssl traffic by default. A quick-fix that worked for me was to add:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
before calling:
curl_exec():
in the php file.
I believe that this disables all verification of SSL certificates.
You can do something like this:
SELECT id,name, REPLACE(REPLACE(hide,0,"false"),1,"true") AS hide FROM your-table
Hope this can help you.
If you removed the make all
line from your "fresh" target:
fresh :
rm -f *.o $(EXEC)
clear
You could simply run the command make fresh all
, which will execute as make fresh; make all
.
Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.
My .env file configuration is like this for laravel 5.1
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=****************
MAIL_ENCRYPTION=tls
here most important thing is that I created gmail application specific password(16 digit).
I need to reveal one more thing since no luck for any of configuration. That is, whenever I changed .env file need to run this command
php artisan config:cache
And this is most most most important because without this command laravel executes previous settings from it's cache. It's required me more than 10 hours to figure out.
You can do date arithmetic by using NSDateComponents
. For example:
import Foundation
let comps = NSDateComponents()
comps.minute = 5
let cal = NSCalendar.currentCalendar()
let r = cal.dateByAddingComponents(comps, toDate: NSDate(), options: nil)
It is what you see when you try it in playground
Its easy to do using Google's Guava library.
e.g. Objects.equal(name, name2) && Objects.equal(age, age2) && ...
More examples:
I found it to be pretty nice to do it like this (usage in the view):
@Html.HiddenJsonFor(m => m.TrackingTypes)
Here is the according helper method Extension class:
public static class DataHelpers
{
public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return HiddenJsonFor(htmlHelper, expression, (IDictionary<string, object>) null);
}
public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
return HiddenJsonFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
var name = ExpressionHelper.GetExpressionText(expression);
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("name", name);
tagBuilder.MergeAttribute("type", "hidden");
var json = JsonConvert.SerializeObject(metadata.Model);
tagBuilder.MergeAttribute("value", json);
return MvcHtmlString.Create(tagBuilder.ToString());
}
}
It is not super-sofisticated, but it solves the problem of where to put it (in Controller or in view?) The answer is obviously: neither ;)
One point not yet mentioned is that there are a few different types of assembly code. In the most basic form, all numbers used in instructions must be specified as constants. For example:
$1902: BD 37 14 : LDA $1437,X $1905: 85 03 : STA $03 $1907: 85 09 : STA $09 $1909: CA : DEX $190A: 10 : BPL $1902
The above bit of code, if stored at address $1900 in an Atari 2600 cartridge, will display a number of lines in different colors fetched from a table which starts at address $1437. On some tools, typing in an address, along with the rightmost part of the line above, would store to memory the values shown in the middle column, and start the next line with the following address. Typing code in that form was much more convenient than typing in hex, but one had to know the precise addresses of everything.
Most assemblers allow one to use symbolic addresses. The above code would be written more like:
rainbow_lp: lda ColorTbl,x sta WSYNC sta COLUBK dex bpl rainbow_lp
The assembler would automatically adjust the LDA instruction so it would refer to whatever address was mapped to the label ColorTbl. Using this style of assembler makes it much easier to write and edit code than would be possible if one had to hand-key and hand-maintain all addresses.
Do this:
function changeHeight() { document.getElementById('chartdiv').style.height = "200px" } <button type="button" onClick="changeHeight();"> Click Me!</button>
How can I undo every change made to my directory after the last commit, including deleting added files, resetting modified files, and adding back deleted files?
You can undo changes to tracked files with:
git reset HEAD --hard
You can remove untracked files with:
git clean -f
You can remove untracked files and directories with:
git clean -fd
but you can't undo change to untracked files.
You can remove ignored and untracked files and directories
git clean -fdx
but you can't undo change to ignored files.
You can also set clean.requireForce
to false
:
git config --global --add clean.requireForce false
to avoid using -f
(--force
) when you use git clean
.
All scripts should be loaded last
In just about every case, it's best to place all your script references at the end of the page, just before </body>
.
If you are unable to do so due to templating issues and whatnot, decorate your script tags with the defer
attribute so that the browser knows to download your scripts after the HTML has been downloaded:
<script src="my.js" type="text/javascript" defer="defer"></script>
Edge cases
There are some edge cases, however, where you may experience page flickering or other artifacts during page load which can usually be solved by simply placing your jQuery script references in the <head>
tag without the defer
attribute. These cases include jQuery UI and other addons such as jCarousel or Treeview which modify the DOM as part of their functionality.
Further caveats
There are some libraries that must be loaded before the DOM or CSS, such as polyfills. Modernizr is one such library that must be placed in the head tag.
I use ui-grid - v3.0.0-rc.20
because a scrolling issue is fixed when you go full height of container. Use the ui.grid.autoResize
module will dynamically auto resize the grid to fit your data. To calculate the height of your grid use the function below. The ui-if
is optional to wait until your data is set before rendering.
angular.module('app',['ui.grid','ui.grid.autoResize']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {_x000D_
..._x000D_
_x000D_
$scope.gridData = {_x000D_
rowHeight: 30, // set row height, this is default size_x000D_
..._x000D_
};_x000D_
_x000D_
..._x000D_
_x000D_
$scope.getTableHeight = function() {_x000D_
var rowHeight = 30; // your row height_x000D_
var headerHeight = 30; // your header height_x000D_
return {_x000D_
height: ($scope.gridData.data.length * rowHeight + headerHeight) + "px"_x000D_
};_x000D_
};_x000D_
_x000D_
...
_x000D_
<div ui-if="gridData.data.length>0" id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize ng-style="getTableHeight()"></div>
_x000D_
Just use the rows below:
spring.security.user.name=XXX
spring.security.user.password=XXX
to set the default security user name and password
at your application.properties
(name might differ) within the context of the Spring Application.
To avoid default configuration (as a part of autoconfiguration of the SpringBoot) at all - use the approach mentioned in Answers earlier:
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
or
@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class })
@LukeTaylor: I currently have the same task at hand (creating a popup/dialog that contains an EditText)..
Personally, I find the fully-dynamic route to be somewhat limiting in terms of creativity.
FULLY CUSTOM DIALOG LAYOUT :
Rather than relying entirely upon Code to create the Dialog, you can fully customize it like so :
1) - Create a new Layout Resource
file.. This will act as your Dialog, allowing for full creative freedom!
NOTE: Refer to the Material Design guidelines to help keep things clean and on point.
2) - Give ID's to all of your View
elements.. In my example code below, I have 1 EditText
, and 2 Buttons
.
3) - Create an Activity
with a Button
, for testing purposes.. We'll have it inflate and launch your Dialog!
public void buttonClick_DialogTest(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
// Inflate the Layout Resource file you created in Step 1
View mView = getLayoutInflater().inflate(R.layout.timer_dialog_layout, null);
// Get View elements from Layout file. Be sure to include inflated view name (mView)
final EditText mTimerMinutes = (EditText) mView.findViewById(R.id.etTimerValue);
Button mTimerOk = (Button) mView.findViewById(R.id.btnTimerOk);
Button mTimerCancel = (Button) mView.findViewById(R.id.btnTimerCancel);
// Create the AlertDialog using everything we needed from above
mBuilder.setView(mView);
final AlertDialog timerDialog = mBuilder.create();
// Set Listener for the OK Button
mTimerOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View view) {
if (!mTimerMinutes.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "You entered a Value!,", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
}
}
});
// Set Listener for the CANCEL Button
mTimerCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View view) {
timerDialog.dismiss();
}
});
// Finally, SHOW your Dialog!
timerDialog.show();
// END OF buttonClick_DialogTest
}
Piece of cake! Full creative freedom! Just be sure to follow Material Guidelines ;)
I hope this helps someone! Let me know what you guys think!
Meteor is a framework built ontop of node.js. It uses node.js to deploy but has several differences.
The key being it uses its own packaging system instead of node's module based system. It makes it easy to make web applications using Node. Node can be used for a variety of things and on its own is terrible at serving up dynamic web content. Meteor's libraries make all of this easy.
If there is no vertical scrolling then you can use position:absolute
and height:100%
declared on html and body elements.
Another option is to use viewport height units, see Make div 100% height of browser window
Absolute position Example:
html, body {_x000D_
height:100%;_x000D_
position: absolute;_x000D_
background-color:red;_x000D_
}_x000D_
.button{_x000D_
height:50%;_x000D_
background-color:white;_x000D_
}
_x000D_
<div class="button">BUTTON</div>
_x000D_
html, body {min-height:100vh;background:gray;_x000D_
}_x000D_
.col-100vh {_x000D_
height:100vh;_x000D_
}_x000D_
.col-50vh {_x000D_
height:50vh;_x000D_
}_x000D_
#mmenu_screen--information{_x000D_
background:teal;_x000D_
}_x000D_
#mmenu_screen--book{_x000D_
background:blue;_x000D_
}_x000D_
.mmenu_screen--direktaction{_x000D_
background:red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div id="mmenu_screen" class="col-100vh container-fluid main_container">_x000D_
_x000D_
<div class="row col-100vh">_x000D_
<div class="col-xs-6 col-100vh">_x000D_
_x000D_
<div class="col-50vh col-xs-12" id="mmenu_screen--book">_x000D_
BOOKING BUTTON_x000D_
</div>_x000D_
_x000D_
<div class="col-50vh col-xs-12" id="mmenu_screen--information">_x000D_
INFO BUTTON_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
<div class="col-100vh col-xs-6 mmenu_screen--direktaction">_x000D_
DIRECT ACTION BUTTON_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
i tried to train unet on voc data set but because of huge image size, memory finishes. i tried all the above tips, even tried with batch size==1, yet to no improvement. sometimes TensorFlow version also causes the memory issues. try by using
pip install tensorflow-gpu==1.8.0
I use jQuery prop
$('#yourCheckbox').change(function(){
if($(this).prop("checked")) {
$('#showDiv').show();
} else {
$('#hideDiv').hide();
}
});
You want something like the cex=1.5
argument to scale fonts 150 percent. But do see help(par)
as there are also cex.lab
, cex.axis
, ...
Example 1:
0 means ignore
1 means show
User.find({}, { createdAt: 0, updatedAt: 0, isActive: 0, _id : 1 }).then(...)
Example 2:
User.findById(id).select("_id, isActive").then(...)
int add(int a, int b)
{
return (a+b);
}
int minus(int a, int b)
{
return (a-b);
}
typedef int (*math_func)(int, int); //declaration of function pointer
int main()
{
math_func addition = add; //typedef assigns a new variable i.e. "addition" to original function "add"
math_func substract = minus; //typedef assigns a new variable i.e. "substract" to original function "minus"
int c = addition(11, 11); //calling function via new variable
printf("%d\n",c);
c = substract(11, 5); //calling function via new variable
printf("%d",c);
return 0;
}
Output of this is :
22
6
Note that, same math_func definer has been used for the declaring both the function.
Same approach of typedef may be used for extern struct.(using sturuct in other file.)
The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.
NP-Complete is a class of problems.
The class P
consists of those problems that are solvable in polynomial time. For example, they could be solved in O(nk) for some constant k, where n is the size of the input. Simply put, you can write a program that will run in reasonable time.
The class NP
consists of those problems that are verifiable in polynomial time. That is, if we are given a potential solution, then we could check if the given solution is correct in polynomial time.
Some examples are the Boolean Satisfiability (or SAT) problem, or the Hamiltonian-cycle problem. There are many problems that are known to be in the class NP.
NP-Complete
means the problem is at least as hard as any problem in NP.
It is important to computer science because it has been proven that any problem in NP can be transformed into another problem in NP-complete. That means that a solution to any one NP-complete problem is a solution to all NP problems.
Many algorithms in security depends on the fact that no known solutions exist for NP hard problems. It would definitely have a significant impact on computing if a solution were found.
It's far from pretty, but you could create a script or an alias that does something like this:
for c in $(git for-each-ref refs/tags/ --format='%(refname)'); do echo $c; git show --quiet "$c"; echo; done
$('#link').prop('value', 'new value');
Explanation: Attr will work on jQuery 1.6 but as of jQuery 1.6.1 things have changed. In the majority of cases, prop() does what attr() used to do. Replacing calls to attr() with prop() in your code will generally work. Attr will give you the value of element as it was defined in the html on page load and prop gives the updated values of elements which are modified via jQuery.
You might also try
Application.CalculateFull
or
Application.CalculateFullRebuild
if you don't mind rebuilding all open workbooks, rather than just the active worksheet. (CalculateFullRebuild
rebuilds dependencies as well.)
You can also do this in phpMyAdmin without writing SQL.
Note: You'll see that phpMyAdmin is issuing the same SQL that is mentioned in the other answers.
Heredoc sounds more convenient for this purpose. It is used to send multiple commands to a command interpreter program like ex or cat
cat << EndOfMessage
This is line 1.
This is line 2.
Line 3.
EndOfMessage
The string after <<
indicates where to stop.
To send these lines to a file, use:
cat > $FILE <<- EOM
Line 1.
Line 2.
EOM
You could also store these lines to a variable:
read -r -d '' VAR << EOM
This is line 1.
This is line 2.
Line 3.
EOM
This stores the lines to the variable named VAR
.
When printing, remember the quotes around the variable otherwise you won't see the newline characters.
echo "$VAR"
Even better, you can use indentation to make it stand out more in your code. This time just add a -
after <<
to stop the tabs from appearing.
read -r -d '' VAR <<- EOM
This is line 1.
This is line 2.
Line 3.
EOM
But then you must use tabs, not spaces, for indentation in your code.
You probably want to check the length of the string first and do something like this:
if (!myStr.empty())
{
char lastChar = *myStr.rbegin();
}
What regex engine are you using? Most of them will support the following expression:
\{\d+:\d+\}
The \d
is actually shorthand for [0-9]
, but the important part is the addition of +
which means "one or more".
You save some bytes by avoiding the .attr
altogether by passing the properties to the jQuery constructor:
var img = $('<img />',
{ id: 'Myid',
src: 'MySrc.gif',
width: 300
})
.appendTo($('#YourDiv'));
You can even go one further and restrict on this coalesced field such as, for example:-
SELECT CAST(coalesce(<column>, '0') AS integer) as new_field
from <table>
where CAST(coalesce(<column>, '0') AS integer) >= 10;
module.exports = function isset () {
// discuss at: http://locutus.io/php/isset/
// original by: Kevin van Zonneveld (http://kvz.io)
// improved by: FremyCompany
// improved by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: Rafal Kukawski (http://blog.kukawski.pl)
// example 1: isset( undefined, true)
// returns 1: false
// example 2: isset( 'Kevin van Zonneveld' )
// returns 2: true
var a = arguments
var l = a.length
var i = 0
var undef
if (l === 0) {
throw new Error('Empty isset')
}
while (i !== l) {
if (a[i] === undef || a[i] === null) {
return false
}
i++
}
return true
}
phpjs.org is mostly retired in favor of locutus Here is the new link http://locutus.io/php/var/isset
i prefer the most readable and extensible way using jquery.
Also, you can build fully dynamic content on the fly.
Since jquery version 1.4 you can pass attributes to elements which is,
imho, a killer feature.
Also the code can be kept cleaner.
$(function(){
var tablerows = new Array();
$.each(['result1', 'result2', 'result3'], function( index, value ) {
tablerows.push('<tr><td>' + value + '</td></tr>');
});
var table = $('<table/>', {
html: tablerows
});
var div = $('<div/>', {
id: 'here_table',
html: table
});
$('body').append(div);
});
Addon: passing more than one "html" tag you've to use array notation like: e.g.
var div = $('<div/>', {
id: 'here_table',
html: [ div1, div2, table ]
});
best Rgds.
Franz
Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.
Alt + Right Arrow and Alt + Numpad 6 (if Num Lock is disabled) are also possibilities.
In my .bashrc
file the following lines were there by default:
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
Hence, in my platform .bash_aliases
is the file used for aliases by default (and the one I use). I'm not an OS X user, but I guess that if you open your .bashrc
file, you'll be able to identify what's the file commonly used for aliases in your platform.
To make the images flexible, simply add
max-width:100%
andheight:auto
. Imagemax-width:100%
andheight:auto
works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to addwidth:auto\9
for IE8.source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries
for example :
img {
max-width: 100%;
height: auto;
width: auto\9; /* ie8 */
}
and then any images you add simply using the img tag will be flexible
JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).
Your update syntax is incorrect. Please check Update Syntax for the correct syntax.
$sql = "UPDATE `access_users` set `contact_first_name` = :firstname, `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";
Using some ES6:
Get the options first, filter the value based on the option and set the selected attribute to true.
window.onload = () => {_x000D_
_x000D_
Array.from(document.querySelector(`#Mobility`).options)_x000D_
.filter(x => x.value === "12")[0]_x000D_
.setAttribute('selected', true);_x000D_
_x000D_
};
_x000D_
<select style="width: 280px" id="Mobility" name="Mobility">_x000D_
<option selected disabled>Please Select</option>_x000D_
<option>K</option>_x000D_
<option>1</option>_x000D_
<option>2</option>_x000D_
<option>3</option>_x000D_
<option>4</option>_x000D_
<option>5</option>_x000D_
<option>6</option>_x000D_
<option>7</option>_x000D_
<option>8</option>_x000D_
<option>9</option>_x000D_
<option>10</option>_x000D_
<option>11</option>_x000D_
<option>12</option>_x000D_
</select>
_x000D_
Using print
and JSON.stringify
you can simply produce a valid JSON
result.
Use --quiet
flag to filter shell noise from the output.
Use --norc
flag to avoid .mongorc.js
evaluation. (I had to do it because of a pretty-formatter that I use, which produces invalid JSON output)
Use DBQuery.shellBatchSize = ?
replacing ?
with the limit of the actual result to avoid paging.
And finally, use tee
to pipe the terminal output to a file:
// Shell:
mongo --quiet --norc ./query.js | tee ~/my_output.json
// query.js:
DBQuery.shellBatchSize = 2000;
function toPrint(data) {
print(JSON.stringify(data, null, 2));
}
toPrint(
db.getCollection('myCollection').find().toArray()
);
Hope this helps!
I would suggest you just write a function to do what you're saying probably using drop
(to delete columns) and insert
to insert columns at a position. There isn't an existing API function to do what you're describing.
JSLT is very close to a JSON equivalent of XSLT. It's a transform language where you write the fixed part of the output in JSON syntax, then insert expressions to compute the values you want to insert in the template.
An example:
{
"time": round(parse-time(.published, "yyyy-MM-dd'T'HH:mm:ssX") * 1000),
"device_manufacturer": .device.manufacturer,
"device_model": .device.model,
"language": .device.acceptLanguage
}
It's implemented in Java on top of Jackson.
I think the following is the easiest way to do it.
<asp:TextBox ID="DateControl" runat="server" Visible="False"></asp:TextBox>
<asp:RangeValidator ID ="rvDate" runat ="server" ControlToValidate="DateControl" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic"></asp:RangeValidator>
In Powershell 7 you can use ForEach-Object -Parallel
$Message = "Output:"
Get-ChildItem $dir | ForEach-Object -Parallel {
"$using:Message $_"
} -ThrottleLimit 4
Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php
,
$result = mysql_query("SELECT field_name, field_value
FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />
. You can reference that field with this jQuery: $("#field1").val()
.
Here's a complete example with the HTML. If we're assuming your fields are called field1
and field2
, then
<!DOCTYPE html>
<html>
<head>
<title>That's about it</title>
</head>
<body>
<form>
<input type="text" id="field1" />
<input type="text" id="field2" />
</form>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$.getJSON('data.php', function(data) {
$.each(data, function(fieldName, fieldValue) {
$("#" + fieldName).val(fieldValue);
});
});
</script>
</html>
That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value
attribute.
Here are a couple of complete working examples that build on the @bendewey & @dommer examples. I needed to tweak each one a bit to get it to work, but in case another LINQ noob is looking for working examples, here you go:
//bendewey's example using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ1
{
static void Main( )
{
//Load xml
XDocument xdoc = XDocument.Load(@"c:\\data.xml"); //you'll have to edit your path
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new
{
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
StringBuilder result = new StringBuilder(); //had to add this to make the result work
//Loop through results
foreach (var lv1 in lv1s)
{
result.AppendLine(" " + lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result.ToString()); //added this so you could see the output on the console
}
}
And next:
//Dommer's example, using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ
{
static void Main( )
{
XElement rootElement = XElement.Load(@"c:\\data.xml"); //you'll have to edit your path
Console.WriteLine(GetOutline(0, rootElement));
}
static private string GetOutline(int indentLevel, XElement element)
{
StringBuilder result = new StringBuilder();
if (element.Attribute("name") != null)
{
result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
}
foreach (XElement childElement in element.Elements())
{
result.Append(GetOutline(indentLevel + 1, childElement));
}
return result.ToString();
}
}
These both compile & work in VS2010 using csc.exe version 4.0.30319.1 and give the exact same output. Hopefully these help someone else who's looking for working examples of code.
EDIT: added @eglasius' example as well since it became useful to me:
//@eglasius example, still using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ2
{
static void Main( )
{
StringBuilder result = new StringBuilder(); //needed for result below
XDocument xdoc = XDocument.Load(@"c:\\deg\\data.xml"); //you'll have to edit your path
var lv1s = xdoc.Root.Descendants("level1");
var lvs = lv1s.SelectMany(l=>
new string[]{ l.Attribute("name").Value }
.Union(
l.Descendants("level2")
.Select(l2=>" " + l2.Attribute("name").Value)
)
);
foreach (var lv in lvs)
{
result.AppendLine(lv);
}
Console.WriteLine(result);//added this so you could see the result
}
}
You want to check if an object is NULL/empty. Being NULL and empty are not the same. Like Justin and Brian have already mentioned, in C++ NULL is an assignment you'd typically associate with pointers. You can overload operator= perhaps, but think it through real well if you actually want to do this. Couple of other things:
bool IsEmpty()
method that returns true if an object's variables are reset to some default state? Guess that might bypass the NULL usage.A* p = new A; ... p = NULL;
is bad (no delete p) unless you can ensure your code will be garbage collected. If anything, this'd lead to memory leaks and with several such leaks there's good chance you'd have slow code. class Null {}; Null _NULL;
and then overload operator= and operator!= of other classes depending on your situation. Perhaps you should post us some details about the context to help you better with option 4.
Arpan
I have the same problem. I ran docker system prune -a --volumes
, docker network prune
, but neither helped me.
I use a VPN, I turned off the VPN and, after it docker started normal and was able to create a network. After that, you can enable VPN again.
You can get your result by simply use substr():
Syntax substr(string,start,length)
Example
<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>
Output :
Hello
You might want to consider refactoring that query instead of adding an arbitrarily long list of ids... You could use a range if the ids indeed follow the pattern in your example:
SELECT * FROM user WHERE id >= minValue AND id <= maxValue;
Another option is to add an inner select:
SELECT *
FROM user
WHERE id IN (
SELECT userId
FROM ForumThreads ft
WHERE ft.id = X
);
It is possibly to use the flag -o,--offline "Work offline"
to prevent that.
Like this:
maven compile -o
If you want to check if file exists using javascript then no, as far as I know, javascript has no access to file system due to security reasons.. But as for me it is not clear enough what are you trying to do..
I had to deal with this same issue and was able to solve it without stopping any of my running containers. This is a solution up-to-date as of February 2016, using Docker 1.9.1. Anyway, this answer is a detailed version of @ricardo-branco's answer, but in more depth for new users.
In my scenario, I wanted to temporarily connect to MySQL running in a container, and since other application containers are linked to it, stopping, reconfiguring, and re-running the database container was a non-starter.
Since I'd like to access the MySQL database externally (from Sequel Pro via SSH tunneling), I'm going to use port 33306
on the host machine. (Not 3306
, just in case there is an outer MySQL instance running.)
About an hour of tweaking iptables proved fruitless, even though:
Step by step, here's what I did:
mkdir db-expose-33306
cd db-expose-33306
vim Dockerfile
Edit dockerfile
, placing this inside:
# Exposes port 3306 on linked "db" container, to be accessible at host:33306
FROM ubuntu:latest # (Recommended to use the same base as the DB container)
RUN apt-get update && \
apt-get -y install socat && \
apt-get clean
USER nobody
EXPOSE 33306
CMD socat -dddd TCP-LISTEN:33306,reuseaddr,fork TCP:db:3306
Then build the image:
docker build -t your-namespace/db-expose-33306 .
Then run it, linking to your running container. (Use -d
instead of -rm
to keep it in the background until explicitly stopped and removed. I only want it running temporarily in this case.)
docker run -it --rm --name=db-33306 --link the_live_db_container:db -p 33306:33306 your-namespace/db-expose-33306
I had a same problem because I installed both of python2.7 and python3. when I run program with python3 I received same error. I install scipy with this command and problem has been solved:
sudo apt-get install python3-scipy
a bit example when playing video
let v = document.getElementById('video-plan');
v.onplay = function() {
console.log('Start video')
};
In addition, if you wish to parse your object in case of http error (400-5** codes), You can use the following code: (just replace 'getInputStream' with 'getErrorStream':
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getErrorStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
return sb.toString();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myfun(){
$(document).ready(function(){
$("#select").click(
function(){
var data=$("#select").val();
$("#disp").val(data);
});
});
}
</script>
</head>
<body>
<p>id <input type="text" name="user" id="disp"></p>
<select id="select" onclick="myfun()">
<option name="1"value="one">1</option>
<option name="2"value="two">2</option>
<option name="3"value="three"></option>
</select>
</body>
</html>
In case you want to work with the original MNIST files, here is how you can deserialize them.
If you haven't downloaded the files yet, do that first by running the following in the terminal:
wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
Then save the following as deserialize.py
and run it.
import numpy as np
import gzip
IMG_DIM = 28
def decode_image_file(fname):
result = []
n_bytes_per_img = IMG_DIM*IMG_DIM
with gzip.open(fname, 'rb') as f:
bytes_ = f.read()
data = bytes_[16:]
if len(data) % n_bytes_per_img != 0:
raise Exception('Something wrong with the file')
result = np.frombuffer(data, dtype=np.uint8).reshape(
len(bytes_)//n_bytes_per_img, n_bytes_per_img)
return result
def decode_label_file(fname):
result = []
with gzip.open(fname, 'rb') as f:
bytes_ = f.read()
data = bytes_[8:]
result = np.frombuffer(data, dtype=np.uint8)
return result
train_images = decode_image_file('train-images-idx3-ubyte.gz')
train_labels = decode_label_file('train-labels-idx1-ubyte.gz')
test_images = decode_image_file('t10k-images-idx3-ubyte.gz')
test_labels = decode_label_file('t10k-labels-idx1-ubyte.gz')
The script doesn't normalize the pixel values like in the pickled file. To do that, all you have to do is
train_images = train_images/255
test_images = test_images/255
The bottom statement is equivalent to:
.half {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 50%;
}
Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.
Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.
I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)
Would you want the same form with different parts, showing each part accordingly with a button?
Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters «
and »
just print respectively « and » which might be interesting for the previous and next button characters.
shows_form_part(1)_x000D_
_x000D_
/* this function shows form part [n] and hides the remaining form parts */_x000D_
function shows_form_part(n){_x000D_
var i = 1, p = document.getElementById("form_part"+1);_x000D_
while (p !== null){_x000D_
if (i === n){_x000D_
p.style.display = "";_x000D_
}_x000D_
else{_x000D_
p.style.display = "none";_x000D_
}_x000D_
i++;_x000D_
p = document.getElementById("form_part"+i);_x000D_
}_x000D_
}_x000D_
_x000D_
/* this is called at the last step using info filled during the previous steps*/_x000D_
function calc_sum() {_x000D_
var sum =_x000D_
parseInt(document.getElementById("num1").value) +_x000D_
parseInt(document.getElementById("num2").value) +_x000D_
parseInt(document.getElementById("num3").value);_x000D_
_x000D_
alert("The sum is: " + sum);_x000D_
}
_x000D_
<div id="form_part1">_x000D_
Part 1<br>_x000D_
<input type="number" value="1" id="num1"><br>_x000D_
<button type="button" onclick="shows_form_part(2)">»</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part2">_x000D_
Part 2<br>_x000D_
<input type="number" value="2" id="num2"><br>_x000D_
<button type="button" onclick="shows_form_part(1)">«</button>_x000D_
<button type="button" onclick="shows_form_part(3)">»</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part3">_x000D_
Part 3<br>_x000D_
<input type="number" value="3" id="num3"><br>_x000D_
<button type="button" onclick="shows_form_part(2)">«</button>_x000D_
<button type="button" onclick="calc_sum()">Sum</button>_x000D_
</div>
_x000D_
Use pyfancy. It is a simple way to do color in the terminal!
Example:
print(pyfancy.RED + "Hello Red" + pyfancy.END)
.yaml
is apparently the official extension, because some applications fail when using .yml
. On the other hand I am not familiar with any applications which use YAML code, but fail with a .yaml
extension.
I just stumbled across this, as I was used to writing .yml
in Ansible and Docker Compose. Out of habit I used .yml
when writing Netplan files which failed silently. I finally figured out my mistake. The author of a popular Ansible Galaxy role for Netplan makes the same assumption in his code:
- name: Capturing Existing Configurations
find:
paths: /etc/netplan
patterns: "*.yml,*.yaml"
register: _netplan_configs
Yet any files with a .yml
extension get ignored by Netplan in the same way as files with a .bak
extension. As Netplan is very quiet, and gives no feedback whatsoever on success, even with netplan apply --debug
, a config such as 01-netcfg.yml
will fail silently without any meaningful feedback.
Please refer to the official documentation:
https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration
Below code changes would hide the gridLines:
gridLines: {
display:false
}
This also works on MAC OS:
Prev tab: Shift + Cmd + [
Next Tab: Shift + Cmd + ]
Ditto on the getApplicationContext thing.
The documents on the android site says to use it, but it doesn't work...grrrrr :-P
Just do:
dialog = new Dialog(this);
"this" is usually your Activity from which you start the dialog.
ItemDecoration
Static headers can easily be added with an ItemDecoration
and without any further changes.
// add the decoration. done.
HeaderDecoration headerDecoration = new HeaderDecoration(/* init */);
recyclerView.addItemDecoration(headerDecoration);
The decoration is also reusable since there is no need to modify the adapter or the RecyclerView
at all.
The sample code provided below will require a view to add to the top which can just be inflated like everything else. It can look like this:
If you just have to display text and images this solution is for you—there is no possibility for user interaction like buttons or view pagers, since it will just be drawn to top of your list.
If there is no view to decorate, the decoration will not be drawn. You will still have to handle an empty list yourself. (One possible workaround would be to add a dummy item to the adapter.)
You can find the full source code here on GitHub including a Builder
to help with the initialization of the decorator, or just use the code below and supply your own values to the constructor.
Please be sure to set a correct layout_height
for your view. e.g. match_parent
might not work properly.
public class HeaderDecoration extends RecyclerView.ItemDecoration {
private final View mView;
private final boolean mHorizontal;
private final float mParallax;
private final float mShadowSize;
private final int mColumns;
private final Paint mShadowPaint;
public HeaderDecoration(View view, boolean scrollsHorizontally, float parallax, float shadowSize, int columns) {
mView = view;
mHorizontal = scrollsHorizontally;
mParallax = parallax;
mShadowSize = shadowSize;
mColumns = columns;
if (mShadowSize > 0) {
mShadowPaint = new Paint();
mShadowPaint.setShader(mHorizontal ?
new LinearGradient(mShadowSize, 0, 0, 0,
new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
new float[]{0f, .5f, 1f},
Shader.TileMode.CLAMP) :
new LinearGradient(0, mShadowSize, 0, 0,
new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
new float[]{0f, .5f, 1f},
Shader.TileMode.CLAMP));
} else {
mShadowPaint = null;
}
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
// layout basically just gets drawn on the reserved space on top of the first view
mView.layout(parent.getLeft(), 0, parent.getRight(), mView.getMeasuredHeight());
for (int i = 0; i < parent.getChildCount(); i++) {
View view = parent.getChildAt(i);
if (parent.getChildAdapterPosition(view) == 0) {
c.save();
if (mHorizontal) {
c.clipRect(parent.getLeft(), parent.getTop(), view.getLeft(), parent.getBottom());
final int width = mView.getMeasuredWidth();
final float left = (view.getLeft() - width) * mParallax;
c.translate(left, 0);
mView.draw(c);
if (mShadowSize > 0) {
c.translate(view.getLeft() - left - mShadowSize, 0);
c.drawRect(parent.getLeft(), parent.getTop(), mShadowSize, parent.getBottom(), mShadowPaint);
}
} else {
c.clipRect(parent.getLeft(), parent.getTop(), parent.getRight(), view.getTop());
final int height = mView.getMeasuredHeight();
final float top = (view.getTop() - height) * mParallax;
c.translate(0, top);
mView.draw(c);
if (mShadowSize > 0) {
c.translate(0, view.getTop() - top - mShadowSize);
c.drawRect(parent.getLeft(), parent.getTop(), parent.getRight(), mShadowSize, mShadowPaint);
}
}
c.restore();
break;
}
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) < mColumns) {
if (mHorizontal) {
if (mView.getMeasuredWidth() <= 0) {
mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
}
outRect.set(mView.getMeasuredWidth(), 0, 0, 0);
} else {
if (mView.getMeasuredHeight() <= 0) {
mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
}
outRect.set(0, mView.getMeasuredHeight(), 0, 0);
}
} else {
outRect.setEmpty();
}
}
}
Please note: The GitHub project is my personal playground. It is not thorougly tested, which is why there is no library yet.
An ItemDecoration
is additional drawing to an item of a list. In this case, a decoration is drawn to the top of the first item.
The view gets measured and laid out, then it is drawn to the top of the first item. If a parallax effect is added it will also be clipped to the correct bounds.
std::atomic
exists because many ISAs have direct hardware support for it
What the C++ standard says about std::atomic
has been analyzed in other answers.
So now let's see what std::atomic
compiles to to get a different kind of insight.
The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic
basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.
This support allows for faster alternatives to more general methods such as std::mutex
, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic
because std::mutex
it makes futex
system calls in Linux, which is way slower than the userland instructions emitted by std::atomic
, see also: Does std::mutex create a fence?
Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.
main.cpp
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
size_t niters;
#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif
void threadMain() {
for (size_t i = 0; i < niters; ++i) {
#if LOCK
__asm__ __volatile__ (
"lock incq %0;"
: "+m" (global),
"+g" (i) // to prevent loop unrolling
:
:
);
#else
__asm__ __volatile__ (
""
: "+g" (i) // to prevent he loop from being optimized to a single add
: "g" (global)
:
);
global++;
#endif
}
}
int main(int argc, char **argv) {
size_t nthreads;
if (argc > 1) {
nthreads = std::stoull(argv[1], NULL, 0);
} else {
nthreads = 2;
}
if (argc > 2) {
niters = std::stoull(argv[2], NULL, 0);
} else {
niters = 10;
}
std::vector<std::thread> threads(nthreads);
for (size_t i = 0; i < nthreads; ++i)
threads[i] = std::thread(threadMain);
for (size_t i = 0; i < nthreads; ++i)
threads[i].join();
uint64_t expect = nthreads * niters;
std::cout << "expect " << expect << std::endl;
std::cout << "global " << global << std::endl;
}
Compile, run and disassemble:
comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out -DLOCK $common
./main_fail.out 4 100000
./main_std_atomic.out 4 100000
./main_lock.out 4 100000
gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out
Extremely likely "wrong" race condition output for main_fail.out
:
expect 400000
global 100000
and deterministic "right" output of the others:
expect 400000
global 400000
Disassembly of main_fail.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: mov 0x29b5(%rip),%rcx # 0x5140 <niters>
0x000000000000278b <+11>: test %rcx,%rcx
0x000000000000278e <+14>: je 0x27b4 <threadMain()+52>
0x0000000000002790 <+16>: mov 0x29a1(%rip),%rdx # 0x5138 <global>
0x0000000000002797 <+23>: xor %eax,%eax
0x0000000000002799 <+25>: nopl 0x0(%rax)
0x00000000000027a0 <+32>: add $0x1,%rax
0x00000000000027a4 <+36>: add $0x1,%rdx
0x00000000000027a8 <+40>: cmp %rcx,%rax
0x00000000000027ab <+43>: jb 0x27a0 <threadMain()+32>
0x00000000000027ad <+45>: mov %rdx,0x2984(%rip) # 0x5138 <global>
0x00000000000027b4 <+52>: retq
Disassembly of main_std_atomic.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a6 <threadMain()+38>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock addq $0x1,0x299f(%rip) # 0x5138 <global>
0x0000000000002799 <+25>: add $0x1,%rax
0x000000000000279d <+29>: cmp %rax,0x299c(%rip) # 0x5140 <niters>
0x00000000000027a4 <+36>: ja 0x2790 <threadMain()+16>
0x00000000000027a6 <+38>: retq
Disassembly of main_lock.out
:
Dump of assembler code for function threadMain():
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a5 <threadMain()+37>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock incq 0x29a0(%rip) # 0x5138 <global>
0x0000000000002798 <+24>: add $0x1,%rax
0x000000000000279c <+28>: cmp %rax,0x299d(%rip) # 0x5140 <niters>
0x00000000000027a3 <+35>: ja 0x2790 <threadMain()+16>
0x00000000000027a5 <+37>: retq
Conclusions:
the non-atomic version saves the global to a register, and increments the register.
Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000
.
std::atomic
compiles to lock addq
. The LOCK prefix makes the following inc
fetch, modify and update memory atomically.
our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic
, except that our inc
is used instead of add
. Not sure why GCC chose add
, considering that our INC generated a decoding 1 byte smaller.
ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?
Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.
Dashes don't need to be removed from HTTP request as you can see in URL of this thread. But if you want to prepare well-formed URL without dependency on data you should use URLEncoder.encode( String data, String encoding ) instead of changing standard form of you data. For UUID string representation dashes is normal.
You can get and set environment variables via os.environ
:
import os
user_home = os.environ["HOME"]
os.environ["PYTHONPATH"] = "..."
But since your interpreter is already running, this will have no effect. You're better off using
import sys
sys.path.append("...")
which is the array that your PYTHONPATH
will be transformed into on interpreter startup.
Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).
apt-get install -d -o=dir::cache=/tmp whateveryouwant
By default, IDLE has it on Shift-Left Bracket. However, if you want, you can customise it to be Shift-Tab by clicking Options --> Configure IDLE --> Keys --> Use a Custom Key Set --> dedent-region --> Get New Keys for Selection
Then you can choose whatever combination you want. (Don't forget to click apply otherwise all the settings would not get affected.)
A Classical Object Oriented Solution
First I must genuflect to the awesomeness of LINQ.... Now that we've got that out of the way
A variation on JimmyHoffa answer. With generics the CompareTo
parameter becomes type safe.
public class Order : IComparable<Order> {
public int CompareTo( Order that ) {
if ( that == null ) return 1;
if ( this.OrderDate > that.OrderDate) return 1;
if ( this.OrderDate < that.OrderDate) return -1;
return 0;
}
}
// in the client code
// assume myOrders is a populated List<Order>
myOrders.Sort();
This default sortability is re-usable of course. That is each client does not have to redundantly re-write the sorting logic. Swapping the "1" and "-1" (or the logic operators, your choice) reverses the sort order.
You can do it this way:
Declare interface:
public interface MyInterface{
public void foo();
}
Let your Activity imlement it:
public class MyActivity extends Activity implements MyInterface{
public void foo(){
//do stuff
}
public onCreate(){
//your code
MyAdapter adapter = new MyAdapter(this); //this will work as your
//MyInterface listener
}
}
Then pass your activity to ListAdater:
public MyAdapter extends BaseAdater{
private MyInterface listener;
public MyAdapter(MyInterface listener){
this.listener = listener;
}
}
And somewhere in adapter, when you need to call that Activity method:
listener.foo();
You don't need to use Regex.
phone = new String(phone.Where(c => char.IsDigit(c)).ToArray())
It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.
var x = '';
var y = 'bob';
var z = x || y;
alert(z);
Will output 'bob';
You can just delete .git. Typically:
rm -rf .git
Then, recreate as the right user.
//file1.php
<?php
class ClassA
{
private $name = 'John';
function getName()
{
return $this->name;
}
}
?>
//file2.php
<?php
include ("file1.php");
class ClassB
{
function __construct()
{
}
function callA()
{
$classA = new ClassA();
$name = $classA->getName();
echo $name; //Prints John
}
}
$classb = new ClassB();
$classb->callA();
?>
The reject
actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject()
the exception value is undefined
, hence the "undefined" part in the error that you get.
You do not show the code that uses the promise, but I reckon it is something like this:
var promise = doSth();
promise.then(function() { doSthHere(); });
Try adding an empty failure call, like this:
promise.then(function() { doSthHere(); }, function() {});
This will prevent the error to appear.
However, I would consider calling reject
only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.
this could be a possible code solution:
from skimage import io
import numpy as np
data=np.random.randn(5,2)
io.imshow(data)
Swift 4. If your array contains elements of type [String: AnyObject]. So to find the index of element use the below code
var array = [[String: AnyObject]]()// Save your data in array
let objectAtZero = array[0] // get first object
let index = (self.array as NSArray).index(of: objectAtZero)
Or If you want to found index on the basis of key from Dictionary. Here array contains Objects of Model class and I am matching id property.
let userId = 20
if let index = array.index(where: { (dict) -> Bool in
return dict.id == userId // Will found index of matched id
}) {
print("Index found")
}
OR
let storeId = Int(surveyCurrent.store_id) // Accessing model key value
indexArrUpTo = self.arrEarnUpTo.index { Int($0.store_id) == storeId }! // Array contains models and finding specific one
It is worth adding that if you want to search for a method of a class, you can use a .
(dot) between the class and method name inside of either the search everywhere or search symbols dialog. This even works with IDEAs usual search benefits. For example, you can search for LDT.now
and LocalDateTime::now
will pop up as a result. (As long as you are searching All Files and not just Project Files).
To add to @Craig Schwarze answer,
Here are some related MSDN links:
Loading and Running a Local Package Programmatically:
Loading and Running a Remote Package Programmatically
Capturing Events from a Running Package:
using System;
using Microsoft.SqlServer.Dts.Runtime;
namespace RunFromClientAppWithEventsCS
{
class MyEventListener : DefaultEvents
{
public override bool OnError(DtsObject source, int errorCode, string subComponent,
string description, string helpFile, int helpContext, string idofInterfaceWithError)
{
// Add application-specific diagnostics here.
Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
return false;
}
}
class Program
{
static void Main(string[] args)
{
string pkgLocation;
Package pkg;
Application app;
DTSExecResult pkgResults;
MyEventListener eventListener = new MyEventListener();
pkgLocation =
@"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" +
@"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";
app = new Application();
pkg = app.LoadPackage(pkgLocation, eventListener);
pkgResults = pkg.Execute(null, null, eventListener, null, null);
Console.WriteLine(pkgResults.ToString());
Console.ReadKey();
}
}
}
you can simply do like that in the html part:
<span>Heading Text</span>
and in the css you can make it as an h1 block using display:
span{
display:block;
font-size:20px;
}
you will get it as a h1 without bold ,
if you want it bold just add this to the css:
font-weight:bold;
Lets do some experimentation, to see how we could get/interpret the length of different dict/array values in a dict.
create our test dict, see list and dict comprehensions:
>>> my_dict = {x:[i for i in range(x)] for x in range(4)}
>>> my_dict
{0: [], 1: [0], 2: [0, 1], 3: [0, 1, 2]}
Get the length of the value of a specific key:
>>> my_dict[3]
[0, 1, 2]
>>> len(my_dict[3])
3
Get a dict of the lengths of the values of each key:
>>> key_to_value_lengths = {k:len(v) for k, v in my_dict.items()}
{0: 0, 1: 1, 2: 2, 3: 3}
>>> key_to_value_lengths[2]
2
Get the sum of the lengths of all values in the dict:
>>> [len(x) for x in my_dict.values()]
[0, 1, 2, 3]
>>> sum([len(x) for x in my_dict.values()])
6
For the sake of others having this issue - I landed here because I tried to get cute with how I set up a new github repository, but per the setup page credential helper doesn't work unless you clone a repository.
"Tip: The credential helper only works when you clone an HTTPS repository URL. If you use the SSH repository URL instead, SSH keys are used for authentication. This guide offers help generating and using an SSH key pair."
If your goal is to have
str = "Hello\nWorld";
and output what it contains in string literal form, you can use JSON.stringify
:
console.log(JSON.stringify(str)); // ""Hello\nWorld""
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
}
_x000D_
console.log
adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).
JSON.stringify
takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("
), the word Hello
, a backslash (\
), the letter n
, the word World
, and the closing quote ("
). The linefeed in the string is escaped in the output as a \
and an n
because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.