If if
is not working you use:
:switch case %n%=1
statements;
goto :switch case end
etc..
You have to change max_connections
to increase total permitted connections.
And set max_user_connections
back to default 0 => no limit unless you need to limit this per user connections.
You can use ::after
to create a 0px
-height block after the <h4>
, which effectively moves anything after the <h4>
to the next line:
h4 {_x000D_
display: inline;_x000D_
}_x000D_
h4::after {_x000D_
content: "";_x000D_
display: block;_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
Text, text, text, text, text. <h4>Sub header</h4>_x000D_
Text, text, text, text, text._x000D_
</li>_x000D_
</ul>
_x000D_
It would be a lot more simple just to do this;
name = input("What's your name? ")
age = int(input("How old are you? "))
print ("Hi,{0} you will be 21 in {1} years.".format(name, 21 - age))`
There is a project on CodeProject that makes it simple to convert an XML file to SQL Script. It uses XSLT. You could probably modify it to generate the DDL too.
And See this question too : Generating SQL using XML and XSLT
This command did it for me:
zip -r Target.zip Source -x "*.DS_Store"
Target.zip
is the zip file to create. Source
is the source file/folder to zip up. And the _x
parameter specifies the file/folder to not include. If the above doesn't work for whatever reason, try this instead:
zip -r Target.zip Source -x "*.DS_Store" -x "__MACOSX"
If you want to view readme.txt in your repository without checking it out:
$ svn cat http://svn.red-bean.com/repos/test/readme.txt
This is a README file. You should read this.Tip: If your working copy is out of date (or you have local modifications) and you want to see the HEAD revision of a file in your working copy, svn cat will automatically fetch the HEAD revision when you give it a path:
$ cat foo.c
This file is in my local working copy and has changes that I've made.$ svn cat foo.c
Latest revision fresh from the repository!
What is REST
REST stands for representational state transfer, it's actually an architectural style for creating Web API which treats everything(data or functionality) as recourse. It expects; exposing resources through URI and responding in multiple formats and representational transfer of state of the resources in stateless manner. Here I am talking about two things:
REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP.SOAP uses services interfaces to expose the business logic. REST uses URI to expose business logic.
REST is not REST without HATEOAS. This means that a client only knows the entry point URI and the resources are supposed to return links the client should follow. Those fancy documentation generators that give URI patterns for everything you can do in a REST API miss the point completely. They are not only documenting something that's supposed to be following the standard, but when you do that, you're coupling the client to one particular moment in the evolution of the API, and any changes on the API have to be documented and applied, or it will break.
HATEOAS, an abbreviation for Hypermedia As The Engine Of Application State, is a constraint of the REST application architecture that distinguishes it from most other network application architectures. The principle is that a client interacts with a network application entirely through hypermedia provided dynamically by application servers. A REST client needs no prior knowledge about how to interact with any particular application or server beyond a generic understanding of hypermedia. By contrast, in some service-oriented architectures (SOA), clients and servers interact through a fixed interface shared through documentation or an interface description language (IDL).
The answer with screenshots (put the checkbox as in the second pic, then press OK):
The solution that worked for me when I had huge legend was to use extra empty image layout. In following example I made 4 rows and at the bottom I plot image with offset for legend (bbox_to_anchor) at the top it does not get cut.
f = plt.figure()
ax = f.add_subplot(414)
lgd = ax.legend(loc='upper left', bbox_to_anchor=(0, 4), mode="expand", borderaxespad=0.3)
ax.autoscale_view()
plt.savefig(fig_name, format='svg', dpi=1200, bbox_extra_artists=(lgd,), bbox_inches='tight')
For those just stumbling across this, there is now a much better alternative as per research by Percona.
It consists of reorganising the UUID chunks for optimal indexing, then converting into binary for reduced storage.
Read the full article here
Something worth noting is that INSERT IGNORE will still increment the primary key whether the statement was a success or not just like a normal INSERT would.
This will cause gaps in your primary keys that might make a programmer mentally unstable. Or if your application is poorly designed and depends on perfect incremental primary keys, it might become a headache.
Look into innodb_autoinc_lock_mode = 0
(server setting, and comes with a slight performance hit), or use a SELECT first to make sure your query will not fail (which also comes with a performance hit and extra code).
Came across this some time ago
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
# Thanks to Steven D'Aprano, http://www.velocityreviews.com/forums
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print('\n' * numlines)
Then just use clearscreen()
As already said, the easiest way is to use querystring.
But if you cannot, because of security reason, you should consider using cookies.
Okay here some more complex sample for the use of For /F
:: Main
@prompt -$G
call :REGQUERY "Software\Classes\CLSID\{3E6AE265-3382-A429-56D1-BB2B4D1D}"
@goto :EOF
:REGQUERY
:: Checks HKEY_LOCAL_MACHINE\ and HKEY_CURRENT_USER\
:: for the key and lists its content
@call :EXEC "REG QUERY HKCU\%~1"
@call :EXEC "REG QUERY "HKLM\%~1""
@goto :EOF
:EXEC
@set output=
@for /F "delims=" %%i in ('%~1 2^>nul') do @(
set output=%%i
)
@if not "%output%"=="" (
echo %1 -^> %output%
)
@goto :EOF
I packed it into the sub function :EXEC so all of its nasty details of implementation doesn't litters the main script. So it got some kinda some batch tutorial. Notes 'bout the code:
echo %1 -^>...
so there ^ makes it possible the output a '>' via echo what else wouldn't have been possible.@if not "%output%"==""
looks like in most common programming languages - it's maybe different that you expected (if you're not used to MS-batch). Well remove the '@' at the beginning. Study the output. Change it tonot %output%==""
-rerun and consider why this doesn't work. ;)See this Link
HTML
<div id="products"></div>
JS
var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
};
var name = $("<div/>",{"text":someone.name,"class":"name"
});
var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);
You can explore the json tree with gson.
Try something like this :
gson.toJsonTree(student).getAsJsonObject()
.get("country").getAsJsonObject().remove("name");
You can add some properties also :
gson.toJsonTree(student).getAsJsonObject().addProperty("isGoodStudent", false);
Tested with gson 2.2.4.
The problems is that dropboxes don't work the same as listboxes, at least the way ASP.NET MVC2 design expects: A dropbox allows only zero or one values, as listboxes can have a multiple value selection. So, being strict with HTML, that value shouldn't be in the option list as "selected" flag, but in the input itself.
See the following example:
<select id="combo" name="combo" value="id2">
<option value="id1">This is option 1</option>
<option value="id2" selected="selected">This is option 2</option>
<option value="id3">This is option 3</option>
</select>
<select id="listbox" name="listbox" multiple>
<option value="id1">This is option 1</option>
<option value="id2" selected="selected">This is option 2</option>
<option value="id3">This is option 3</option>
</select>
The combo has the option selected, but also has its value attribute set. So, if you want ASP.NET MVC2 to render a dropbox and also have a specific value selected (i.e., default values, etc.), you should give it a value in the rendering, like this:
// in my view
<%=Html.DropDownList("UserId", selectListItems /* (SelectList)ViewData["UserId"]*/, new { @Value = selectedUser.Id } /* Your selected value as an additional HTML attribute */)%>
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
An easy way to deal with refs:
class UserInfo extends React.Component {_x000D_
_x000D_
constructor(props) {_x000D_
super(props);_x000D_
this.handleSubmit = this.handleSubmit.bind(this);_x000D_
}_x000D_
_x000D_
handleSubmit(e) {_x000D_
e.preventDefault();_x000D_
_x000D_
const formData = {};_x000D_
for (const field in this.refs) {_x000D_
formData[field] = this.refs[field].value;_x000D_
}_x000D_
console.log('-->', formData);_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
<form onSubmit={this.handleSubmit}>_x000D_
<input ref="phone" className="phone" type='tel' name="phone"/>_x000D_
<input ref="email" className="email" type='tel' name="email"/>_x000D_
<input type="submit" value="Submit"/>_x000D_
</form>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
export default UserInfo;
_x000D_
const Discord = require("discord.js");
const superagent = require("superagent");
module.exports = {
name: "hug",
category: "action",
description: "hug a user!",
usage: "hug <user>",
run: async (client, message, args) => {
let hugUser = message.mentions.users.first()
if(!hugUser) return message.channel.send("You forgot to mention somebody.");
let hugEmbed2 = new Discord.MessageEmbed()
.setColor("#36393F")
.setDescription(`**${message.author.username}** hugged **himself**`)
.setImage("https://i.kym-cdn.com/photos/images/original/000/859/605/3e7.gif")
.setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
if (hugUser.id === message.author.id) return message.channel.send(hugEmbed2);
const {body} = await superagent
.get(`https://nekos.life/api/v2/img/hug`);
let hugEmbed = new Discord.MessageEmbed()
.setDescription(`**${message.author.username}** hugged **${message.mentions.users.first().username}**`)
.setImage(body.url)
.setColor("#36393F")
.setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
message.channel.send(hugEmbed)
}
}
Eclipse TCF team has just release terminal (SSH, Telnet, local)
originally named TCF Terminal, then renamed to TM Terminal
http://marketplace.eclipse.org/content/tcf-terminals
Finally Windows and Linux all supported
Support for Git Bash on Windows is resolved Bug 435014.
This plugin is included into Enide Studio 2014 and Enide 2015.
To access the terminal go to Window -> Show View -> Terminal or Ctrl+Alt+T
Easy. Use .shape
.
>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.
It might be considered a bit 'hacky' but depending the size and contents of the slice, you can join the slice together and do a string search.
For example you have a slice containing single word values (e.g. "yes", "no", "maybe"). These results are appended to a slice. If you want to check if this slice contains any "maybe" results, you may use
exSlice := ["yes", "no", "yes", "maybe"]
if strings.Contains(strings.Join(exSlice, ","), "maybe") {
fmt.Println("We have a maybe!")
}
How suitable this is really depends on the size of the slice and length of its members. There may be performance or suitability issues for large slices or long values, but for smaller slices of finite size and simple values it is a valid one-liner to achieve the desired result.
To fix the issues with the canOpenURL failing. This is because of the new App Transport Security feature in iOS9
Read this post to fix that issue http://discoverpioneer.com/blog/2015/09/18/updating-facebook-integration-for-ios-9/
The easiest way to check is:
if(!variable) {
// If the variable is null or undefined then execution of code will enter here.
}
To improve James' excellent answer:
It's better to put BINARY
in front of the constant instead:
SELECT * FROM `table` WHERE `column` = BINARY 'value'
Putting BINARY
in front of column
will prevent the use of any index on that column.
Use Device Detector open source library, it offers a isBot() function: https://github.com/piwik/device-detector
java.util.Date date= new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
use this
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Default"]];
Skip the first section if you have already installed Miniconda successfully.
Installation of Miniconda on Raspberry Pi
wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
sudo md5sum Miniconda3-latest-Linux-armv7l.sh
sudo /bin/bash Miniconda3-latest-Linux-armv7l.sh
Accept the license agreement with yes
When asked, change the install location: /home/pi/miniconda3
Do you wish the installer to prepend the Miniconda3 install location
to PATH in your /root/.bashrc ? yes
Now add the install path to the PATH variable:
sudo nano /home/pi/.bashrc
Go to the end of the file .bashrc and add the following line:
export PATH="/home/pi/miniconda3/bin:$PATH"
Save the file and exit.
To test if the installation was successful, open a new terminal and enter
conda
If you see a list with commands you are ready to go.
But how can you use Python versions greater than 3.4 ?
Adding Python 3.5 / 3.6 to Miniconda on Raspberry Pi
After the installation of Miniconda I could not yet install Python versions higher than Python 3.4, but i needed Python 3.5. Here is the solution which worked for me on my Raspberry Pi 4:
First i added the Berryconda package manager by jjhelmus (kind of an up-to-date version of the armv7l version of Miniconda):
conda config --add channels rpi
Only now I was able to install Python 3.5 or 3.6 without the need for compiling it myself:
conda install python=3.5
conda install python=3.6
Afterwards I was able to create environments with the added Python version, e.g. with Python 3.5:
conda create --name py35 python=3.5
The new environment "py35" can now be activated:
source activate py35
Using Python 3.7 on Raspberry Pi
Currently Jonathan Helmus, who is the developer of berryconda, is working on adding Python 3.7 support, if you want to see if there is an update or if you want to support him, have a look at this pull request. (update 20200623) berryconda is now inactive, This project is no longer active, no recipe will be updated and no packages will be added to the rpi channel.
If you need to run Python 3.7 on your Pi right now, you can do so without Miniconda. Check if you are running the latest version of Raspbian OS called Buster. Buster ships with Python 3.7 preinstalled (source), so simply run your program with the following command:
Python3.7 app-that-needs-python37.py
I hope this solution will work for you too!
Personally I'd go with AJAX.
If you cannot switch to @Ajax...
helpers, I suggest you to add a couple of properties in your model
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
Change your view to a strongly typed Model via
@using MyModel
Before returning the View, in case of successfull creation do something like
MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);
then in your view, add this
@{
if (model.TriggerOnLoad) {
<text>
<script type="text/javascript">
alert('@Model.TriggerOnLoadMessage');
</script>
</text>
}
}
Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:
$(document).ready(function () {
alert('@Model.TriggerOnLoadMessage');
});
Please remember to reset the Model properties upon successfully alert emission.
Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:
@Html.EditorFor (m => m.TriggerOnLoadMessage)
But in case you want to build up such a thing, maybe it's better to define your own C# class:
class ClientMessageNotification {
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
}
and add a ClientMessageNotification
property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification
class and you're done. Nice, clean, and reusable.
The programmatically trigger to call the autocomplete.change event is via a namespaced trigger on the source select element.
$("#CompanyList").trigger("blur.autocomplete");
Within version 1.8 of jquery UI..
.bind( "blur.autocomplete", function( event ) {
if ( self.options.disabled ) {
return;
}
clearTimeout( self.searching );
// clicks on the menu (or a button to trigger a search) will cause a blur event
self.closing = setTimeout(function() {
self.close( event );
self._change( event );
}, 150 );
});
Jay Gilford's answer will work, but I think really the easiest way is to just slap a display: none;
on a submit button in the form.
You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.
You can get the Java EE Edition of eclipse with has it pre-installed.
To create and run your first servlet:
doGet()
method.That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.
In C++20 we'll finally get std::set::contains
method.
#include <iostream>
#include <string>
#include <set>
int main()
{
std::set<std::string> example = {"Do", "not", "panic", "!!!"};
if(example.contains("panic")) {
std::cout << "Found\n";
} else {
std::cout << "Not found\n";
}
}
You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)
usually the log file is in
/var/log/apache2/error.log
or
/var/log/httpd/error.log
Though technically this doesn't directly answer question posed, it does answer the question of how to do what the original poster wanted to do: combine files. If anything, this is a post to help newbies understand what Instance Hunter and Konstantin are talking about.
This is the method I use to combine files (in this case a jpg and a zip). Note that I create a buffer that gets filled with the content of the zip file (in small chunks rather than in one big read operation), and then the buffer gets written to the back of the jpg file until the end of the zip file is reached:
private void CombineFiles(string jpgFileName, string zipFileName)
{
using (Stream original = new FileStream(jpgFileName, FileMode.Append))
{
using (Stream extra = new FileStream(zipFileName, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[32 * 1024];
int blockSize;
while ((blockSize = extra.Read(buffer, 0, buffer.Length)) > 0)
{
original.Write(buffer, 0, blockSize);
}
}
}
}
for anyone who's using react-moment
:
simply use format
prop to your needed format:
const now = new Date()
<Moment format="DD/MM/YYYY">{now}</Moment>
wait until the process is over ...
while(webview.getProgress()< 100){}
progressBar.setVisibility(View.GONE);
tolist()
works fine even if encountered a nested array, say a pandas DataFrame
;
my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]
print(type(my_list),type(my_dt),type(new_list))
You can use the instanceof
operator for this. From MDN:
The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:
class Animal {_x000D_
name;_x000D_
_x000D_
constructor(name) {_x000D_
this.name = name;_x000D_
}_x000D_
}_x000D_
_x000D_
const animal = new Animal('fluffy');_x000D_
_x000D_
// true because Animal in on the prototype chain of animal_x000D_
console.log(animal instanceof Animal); // true_x000D_
// Proof that Animal is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
_x000D_
// true because Object in on the prototype chain of animal_x000D_
console.log(animal instanceof Object); _x000D_
// Proof that Object is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
_x000D_
console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
_x000D_
_x000D_
The prototype chain in this example is:
animal > Animal.prototype > Object.prototype
Since there is no accepted answer I will try to answer this one:
[s] - seconds
you said:
my id coloumn is auto increment i have to get the id and convert it to another base.So i need to get the next id before insert cause converted code will be inserted too.
what you're asking for is very dangerous and will lead to a race condition. if your code is run twice at the same time by different users, they will both get 6 and their updates or inserts will step all over each other.
i suggest that you instead INSERT
in to the table, get the auto_increment value using LAST_INSERT_ID()
, and then UPDATE
the row to set whatever value you have that depends on the auto_increment value.
Just another helpful hint in addition to the above comment would be when you have a string value contained in some variable such as a request parameter. In this case, passing this in will also result in JSTL keying the value of say "1" as a sting and as such no match being found in a Map hashmap.
One way to get around this is to do something like this.
<c:set var="longKey" value="${param.selectedIndex + 0}"/>
This will now be treated as a Long object and then has a chance to match an object when it is contained withing the map Map or whatever.
Then, continue as usual with something like
${map[longKey]}
You can transfer array from javascript to PHP...
Javascript... ArraySender.html
<script language="javascript">
//its your javascript, your array can be multidimensional or associative
plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info';
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3';
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4';
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5';
function convertJsArr2Php(JsArr){
var Php = '';
if (Array.isArray(JsArr)){
Php += 'array(';
for (var i in JsArr){
Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
Php += ', ';
}
}
Php += ')';
return Php;
}
else{
return '\'' + JsArr + '\'';
}
}
function ajaxPost(str, plArrayC){
var xmlhttp;
if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("POST",str,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('Array=' + plArrayC);
}
ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>
and PHP Code... ArrayReader.php
<?php
eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);
?>
I had the same problem, and I used the UTF-8 coding for both of my files as follows:
add @charset "UTF-8";
in CSS file and <meta charset="UTF-8">
under <head>
tag in HTML file.
and it worked for me.
it makes the same encoding for both the files i.e HTML and CSS.
You can also do the same for "UTF-16" encoding.
If it is still not working check for the <link type="text/css" rel="stylesheet" href="style.css"/>
under <head>
tag in HTML File where you should mention type="text/css"
Wrap your div with
<a name="sushi">
<div id="sushi">
</div>
</a>
and link to it by
<a href="#sushi">Sushi</a>
"Empty": only works on variables. Empty can mean different things for different variable types (check manual: http://php.net/manual/en/function.empty.php).
"isset": checks if the variable exists and checks for a true NULL or false value. Can be unset by calling "unset". Once again, check the manual.
Use of either one depends of the variable type you are using.
I would say, it's safer to check for both, because you are checking first of all if the variable exists, and if it isn't really NULL or empty.
The code you have is a white with low opacity.
If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.
Here is a simple demo.
If you want it to look 'more white', make it less opaque:
background:rgba(255,255,255, 0.9);
just found an advance and most currently used method to set string in textView
textView.setText(String.valueOf(YourIntegerNumber));
A couple things
(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.
(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:
.button:after {
content: "";
width: 30px;
height: 30px;
background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
top: 10px;
right: 5px;
position: absolute;
display: inline-block;
}
I updated your jsFiddle to this and it showed the image.
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
You can check Visual Studio Downloads for available Visual Studio Community
, Visual Studio Professional
, Visual Studio Enterprise
and Visual Studio Code
download links.
Update!
There is no direct links of Visual Studio 2015
at Visual Studio Downloads anymore. but the below links still works.
OR simply click on direct links below (for .iso/.exe file):
VSCode area:
As Mr. Taylor pointed out this is usually set in php.ini. Usually they are stored as files in a specific directory.
Yes: TIME_CREATED contains a date and a time. Use TRUNC
to strip the time:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')
UPDATE:
As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED
if it exists. An alternative approach without this problem is this:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy')
AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1
None of the answers so far gets at the problem of filenames with spaces.
Additionally, all that use xargs
are subject to fail if the total length of paths in the tree exceeds the shell environment size limit (defaults to a few megabytes in Linux).
Here is one that fixes these problems in a pretty direct manner. The subshell takes care of files with spaces. The awk
totals the stream of individual file wc
outputs, so it ought never to run out of space. It also restricts the exec
to files only (skipping directories):
find . -type f -name '*.php' -exec bash -c 'wc -l "$0"' {} \; | awk '{s+=$1} END {print s}'
I thought all of them were great but I had troubles actually getting them to work with javascript and c#. Here is what I did. Hope it helps someone else.
//put this at the top of the page
<script src="https://www.google.com/recaptcha/api.js"></script>
//put this under the script tag
<script>
var isCaptchaValid = false;
function doCaptchaValidate(source, args) {
args.IsValid = isCaptchaValid;
}
var verifyCallback = function (response) {
isCaptchaValid = true;
};
</script>
//retrieved from google and added callback
<div class="g-recaptcha" data-sitekey="sitekey" data-callback="verifyCallback">
//created a custom validator and added error message and ClientValidationFucntion
<asp:CustomValidator runat="server" ID="CustomValidator1" ValidationGroup="Initial" ErrorMessage="Captcha Required" ClientValidationFunction="doCaptchaValidate"/>
Set the name in the form to check_list[]
and you will be able to access all the checkboxes as an array($_POST['check_list'][]
).
Here's a little sample as requested:
<form action="test.php" method="post">
<input type="checkbox" name="check_list[]" value="value 1">
<input type="checkbox" name="check_list[]" value="value 2">
<input type="checkbox" name="check_list[]" value="value 3">
<input type="checkbox" name="check_list[]" value="value 4">
<input type="checkbox" name="check_list[]" value="value 5">
<input type="submit" />
</form>
<?php
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
?>
XCode 12 update:
If you run xcodebuild
without -arch
param, XCode 12 will build simulator library with architecture "arm64 x86_64" as default.
Then run xcrun -sdk iphoneos lipo -create -output
will conflict, because arm64
architecture exist in simulator and also device library.
I fork script from Adam git and fix it.
Try to put all your <script ...></script>
tags before the </body>
tag. Perhaps the js is trying to access an object of the DOM before it's built up.
This is just extra information, but if you really want the string in a header file, try something like:
class foo
{
public:
static const std::string& RECTANGLE(void)
{
static const std::string str = "rectangle";
return str;
}
};
Though I doubt that's recommended.
bash
does not abort the running execution in case something detects an error state (unless you set the -e
flag). Programming languages which offer try/catch
do this in order to inhibit a "bailing out" because of this special situation (hence typically called "exception").
In the bash
, instead, only the command in question will exit with an exit code greater than 0, indicating that error state. You can check for that of course, but since there is no automatic bailing out of anything, a try/catch does not make sense. It is just lacking that context.
You can, however, simulate a bailing out by using sub shells which can terminate at a point you decide:
(
echo "Do one thing"
echo "Do another thing"
if some_condition
then
exit 3 # <-- this is our simulated bailing out
fi
echo "Do yet another thing"
echo "And do a last thing"
) # <-- here we arrive after the simulated bailing out, and $? will be 3 (exit code)
if [ $? = 3 ]
then
echo "Bail out detected"
fi
Instead of that some_condition
with an if
you also can just try a command, and in case it fails (has an exit code greater than 0), bail out:
(
echo "Do one thing"
echo "Do another thing"
some_command || exit 3
echo "Do yet another thing"
echo "And do a last thing"
)
...
Unfortunately, using this technique you are restricted to 255 different exit codes (1..255) and no decent exception objects can be used.
If you need more information to pass along with your simulated exception, you can use the stdout of the subshells, but that is a bit complicated and maybe another question ;-)
Using the above mentioned -e
flag to the shell you can even strip that explicit exit
statement:
(
set -e
echo "Do one thing"
echo "Do another thing"
some_command
echo "Do yet another thing"
echo "And do a last thing"
)
...
std::iterator
with random_access_iterator_tag
.These base classes define all type definitions required by STL and do other work.To avoid code duplication iterator class should be a template class and be parametrized by "value type", "pointer type", "reference type" or all of them (depends on implementation). For example:
// iterator class is parametrized by pointer type
template <typename PointerType> class MyIterator {
// iterator class definition goes here
};
typedef MyIterator<int*> iterator_type;
typedef MyIterator<const int*> const_iterator_type;
Notice iterator_type
and const_iterator_type
type definitions: they are types for your non-const and const iterators.
See Also: standard library reference
EDIT: std::iterator
is deprecated since C++17. See a relating discussion here.
Most of the time, it is the same.
But, path can exist physically whereas path.exists()
returns False. This is the case if os.stat() returns False for this file.
If path exists physically, then path.isdir()
will always return True. This does not depend on platform.
A simple trick:
import java.util.Scanner;
/* Add these codes at the end of your method ...*/
Scanner input = new Scanner(System.in);
System.out.print("Press Enter to quit...");
input.nextLine();
I found the best solution for me, after reading all your answers:
set t=%date%_%time%
set d=%t:~10,4%%t:~7,2%%t:~4,2%_%t:~15,2%%t:~18,2%%t:~21,2%
echo hello>"Archive_%d%"
If AM I get 20160915_ 150101
(with a leading space and time).
If PM I get 20160915_2150101
.
Be aware that if you want to have values in the reverse order, you can easily do so:
> example = matrix(c(1,1,1,4,3,3,2,349,393,392,459,49,32,94), ncol = 2)
> example[order(example[,1], decreasing = TRUE),]
[,1] [,2]
[1,] 4 459
[2,] 3 49
[3,] 3 32
[4,] 2 94
[5,] 1 349
[6,] 1 393
[7,] 1 392
You want to use %d
or %i
for integers. %@
is used for objects.
It's worth noting, though, that the following code will accomplish the same task and is much clearer.
label.intValue = count;
An excellent answer given by msigman. I just want to add that in windows 10 you can find IIS Express System Tray (32 bit)
process under Visual Studio
process:
try this package, works wonders, and was made for date/time...
library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)
Building on the answer from @Brian-Fisher and answering the comments of some of the people on this post, I have a bunch of huge (and unnecessary) tables in my database so I wanted to skip their contents when copying, but keep the structure:
mysqldump -h <host> -u <username> -p <schema> --no-data > db-structure.sql
mysqldump -h <host> -u <username> -p <schema> --no-create-info --ignore-table=schema.table1 --ignore-table=schema.table2 > db-data.sql
The resulting two files are structurally sound but the dumped data is now ~500MB rather than 9GB, much better for me. I can now import these two files into another database for testing purposes without having to worry about manipulating 9GB of data or running out of disk space.
Also useful is the coalesce operator ??:
VB:
Return Iif( s IsNot Nothing, s, "My Default Value" )
C#:
return s ?? "My Default Value";
Use immediate children selector >
:
$('#tblOne > tbody > tr')
Description: Selects all direct child elements specified by "child" of elements specified by "parent".
.print:last-child{
page-break-after: avoid;
page-break-inside: avoid;
margin-bottom: 0px;
}
This worked for me.
In the Table Designer on SQL Server Management Studio you can set the where the auto increment will start. Right-click on the table in Object Explorer and choose Design, then go to the Column Properties for the relevant column:
Angular 2 Beta
This answer is for those who use Javascript for angularJS v.2.0 Beta.
To use ngModel
in your view you should tell the angular's compiler that you are using a directive called ngModel
.
How?
To use ngModel
there are two libraries in angular2 Beta, and they are ng.common.FORM_DIRECTIVES
and ng.common.NgModel
.
Actually ng.common.FORM_DIRECTIVES
is nothing but group of directives which are useful when you are creating a form. It includes NgModel
directive also.
app.myApp = ng.core.Component({
selector: 'my-app',
templateUrl: 'App/Pages/myApp.html',
directives: [ng.common.NgModel] // specify all your directives here
}).Class({
constructor: function () {
this.myVar = {};
this.myVar.text = "Testing";
},
});
returning true or false indicates that whether execution should continue or stop right there. So just an example
<input type="button" onclick="return func();" />
Now if func() is defined like this
function func()
{
// do something
return false;
}
the click event will never get executed. On the contrary if return true is written then the click event will always be executed.
Check out Pathname and in particular Pathname#exist?
.
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
With:
Calendar cal = Calendar.getInstance();
Then cal
have the current date and time.
You also could get the current Date and Time for timezone with:
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT-2"));
You could ask cal.get(Calendar.DATE);
or other Calendar constant about others details.
Date and Timestamp are deprecated in Java. Calendar class it isn't.
I just stumbled upon a combination of Mixin and Extend:
.block1 { box-shadow: 0 5px 10px #000; }
.block2 { box-shadow: 5px 0 10px #000; }
.block3 { box-shadow: 0 0 1px #000; }
@mixin customExtend($class){ @extend .#{$class}; }
like: @include customExtend(block1);
h1 {color: fff; @include customExtend(block2);}
Sass will compile only the mixins content to the extended blocks, which makes it able to combine blocks without generating duplicate code. The Extend logic only puts the classname of the Mixin import location in the block1, ..., ... {box-shadow: 0 5px 10px #000;}
Because constructors are an implementation detail - they're not something that a user of an interface/superclass can actually invoke at all. By the time they get an instance, it's already been constructed; and vice-versa, at the time you construct an object there's by definition no variable it's currently assigned to.
Think about what it would mean to force all subclasses to have an inherited constructor. I argue it's clearer to pass the variables in directly than for the class to "magically" have a constructor with a certain number of arguments just because it's parent does.
This may be helpful whenever you need a very very random token
<?php
echo mb_strtoupper(strval(bin2hex(openssl_random_pseudo_bytes(16))));
?>
GNU awk 4.1
awk -i inplace NF--
This will remove the last field of each line.
Easy CSS properties can do the trick. The following is for a three-line ellipsis.
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
Here is one that I have been using: -
[<1000000]0.00," KB";[<1000000000]0.00,," MB";0.00,,," GB"
Seems to work fine.
<textarea cols='60' rows='8'>This is my statement one.
This is my statement2</textarea>
Fiddle showing that it works: http://jsfiddle.net/trott/5vu28/.
If you really want this to be on a single line in the source file, you could insert the HTML character references for a line feed and a carriage return as shown in the answer from @Bakudan:
<textarea cols='60' rows='8'>This is my statement one. This is my statement2</textarea>
_x000D_
You can't use String.isEmpty()
if it is null. Best is to have your own method to check null or empty.
public static boolean isBlankOrNull(String str) {
return (str == null || "".equals(str.trim()));
}
You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:
import seaborn as sns
tips = sns.load_dataset("tips")
b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()
, which results in this:
To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.
NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.
I am working with a Python code for a REST API, so this is for those who are working on similar projects.
I extract data from an URL using a POST request and the raw output is JSON. For some reason the output is already a dictionary, not a list, and I'm able to refer to the nested dictionary keys right away, like this:
datapoint_1 = json1_data['datapoints']['datapoint_1']
where datapoint_1 is inside the datapoints dictionary.
A simple solution is to set the spring bean in the Job Data Map and then retrieve the bean in the job class, for instance
// the class sets the configures the MyJob class
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
Date startTime = DateBuilder.nextGivenSecondDate(null, 15);
JobDetail job = newJob(MyJob.class).withIdentity("job1", "group1").build();
job.getJobDataMap().put("processDataDAO", processDataDAO);
`
// this is MyJob Class
ProcessDataDAO processDataDAO = (ProcessDataDAO) jec.getMergedJobDataMap().get("processDataDAO");
use your Model class to get row values selected from datagrid like,
XDocument xmlDoc = XDocument.Load(filepath);
if (tablet_DG.SelectedValue == null)
{
MessageBox.Show("select any record from list..!", "select atleast one record", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
}
else
{
try
{
string tabletID = "";
/*here i have used my model class named as TabletMode*/
var row_list = (TabletModel)tablet_DG.SelectedItem;
tabletID= row_list.TabletID;
var items = from item in xmlDoc.Descendants("Tablet")
where item.Element("TabletID").Value == tabletID
select item;
foreach (var item in items)
{
item.SetElementValue("Instance",row_list.Instance);
item.SetElementValue("Database",row_list.Database);
}
xmlDoc.Save(filepath);
MessageBox.Show("Details Updated..!"
+ Environment.NewLine + "TabletId: " +row_list.TabletID + Environment.NewLine
+ "Instance:" + row_list.Instance + Environment.NewLine + "Database:" + row_list.Database, "", MessageBoxButton.YesNoCancel, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
}
This is due a conflict of versions, to solve it, just force an update of your support-annotations version, adding this line on your module: app gradle
implementation ('com.android.support:support-annotations:27.1.1')
Hope this solves your issue ;)
Edit
Almost forgot, you can declare a single extra property (https://docs.gradle.org/current/userguide/writing_build_scripts.html#sec:extra_properties) for the version, go to your project (or your top) gradle file, and declare your support, or just for this example, annotation version var
ext.annotation_version = "27.1.1"
Then in your module gradle replace it with:
implementation ("com.android.support:support-annotations:$annotation_version")
This is very similar to the @emadabel solution, which is a good alternative for doing it, but without the block, or the rootproject
prefix.
You can use "await" in an "async function".
app.controller('MainCtrl', async function($scope, $q, $timeout) {
...
var all = await $q.all([one.promise, two.promise, three.promise]);
...
}
NOTE: I'm not 100% sure you can call an async function from a non-async function and have the right results.
That said this wouldn't ever be used on a website. But for load-testing/integration test...maybe.
Example code:
async function waitForIt(printMe) {_x000D_
console.log(printMe);_x000D_
console.log("..."+await req());_x000D_
console.log("Legendary!")_x000D_
}_x000D_
_x000D_
function req() {_x000D_
_x000D_
var promise = new Promise(resolve => {_x000D_
setTimeout(() => {_x000D_
resolve("DARY!");_x000D_
}, 2000);_x000D_
_x000D_
});_x000D_
_x000D_
return promise;_x000D_
}_x000D_
_x000D_
waitForIt("Legen-Wait For It");
_x000D_
{{ }}
tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %}
template tag and then assign the value the same way you would in normal python code.
{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}
Result:
it worked
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
This code blocks for the specified duration. This is CPU hogging code. This is different from a thread blocking itself and releasing CPU cycles to be utilized by another thread. No such thing is going on here. Do not use this code, it's a very bad idea.
With me this problem occurred because the proxy configuration. I added the ip git server in the proxy exception. The git server was local, but the no_proxy environment variable was not set correctly.
I used this command to identify the problem:
#Linux:
export GIT_TRACE_PACKET=1
export GIT_TRACE=1
export GIT_CURL_VERBOSE=1
#Windows
set GIT_TRACE_PACKET=1
set GIT_TRACE=1
set GIT_CURL_VERBOSE=1
In return there was the "Proxy-Authorization" as the git server was spot should not go through the proxy. But the real problem was the size of the files defined by the proxy rules
From version 1.9 Easier and official way of getting json
from django.http import JsonResponse
from django.forms.models import model_to_dict
return JsonResponse( model_to_dict(modelinstance) )
No one has explained that you can dynamically define classes. So you can have a decorator that defines (and returns) a subclass:
def addId(cls):
class AddId(cls):
def __init__(self, id, *args, **kargs):
super(AddId, self).__init__(*args, **kargs)
self.__id = id
def getId(self):
return self.__id
return AddId
Which can be used in Python 2 (the comment from Blckknght which explains why you should continue to do this in 2.6+) like this:
class Foo:
pass
FooId = addId(Foo)
And in Python 3 like this (but be careful to use super()
in your classes):
@addId
class Foo:
pass
So you can have your cake and eat it - inheritance and decorators!
Add a header to your request to set content type to application/json
curl -H 'Content-Type: application/json' -s -XPOST http://your.domain.com/ -d YOUR_JSON_BODY
this way spring knows how to parse the content.
Calendar c = new GregorianCalendar();
c.set(Calendar.HOUR_OF_DAY, 0); //anything 0 - 23
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Date d1 = c.getTime(); //the midnight, that's the first second of the day.
should be Fri Mar 09 00:00:00 IST 2012
I use mysql -u root -ppassword databasename < filename.sql
in batch process. For an individual file, I like to use source
more because it shows the progress and any errors like
Query OK, 6717 rows affected (0.18 sec)
Records: 6717 Duplicates: 0 Warnings: 0
mysql -u root -ppassword
In MySQL, change the database you want to import in: mysql>use databasename;
Import the SQL file using source command: mysql>source path\to\the\file\filename.sql;
Go to the folder in which you have Node and NPM (such as C:\Program Files (x86)\nodejs\
) and type the following:
> set path=%PATH%;%CD%
> setx path "%PATH%"
From http://www.hacksparrow.com/install-node-js-and-npm-on-windows.html
Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api
fetch("https://worldtimeapi.org/api/ip")
.then(response => response.json())
.then(data => console.log(data.dst,data.datetime));
_x000D_
I was in the same place as you, finally I found a neat answer :
<form action="xx/xx" method="POST">
<input type="hidden" name="what you want" value="what you want">
<input type="image" src="xx.xx">
</form>
This is probably how you should do it:
void push(std::string&& filename)
{
{
std::lock_guard<std::mutex> lock(qMutex);
q.push(std::move(filename));
}
populatedNotifier.notify_one();
}
bool try_pop(std::string& filename, std::chrono::milliseconds timeout)
{
std::unique_lock<std::mutex> lock(qMutex);
if(!populatedNotifier.wait_for(lock, timeout, [this] { return !q.empty(); }))
return false;
filename = std::move(q.front());
q.pop();
return true;
}
See this question: JADE + EXPRESS: Iterating over object in inline JS code (client-side)?
I'm having the same problem. Jade does not pass local variables in (or do any templating at all) to javascript scripts, it simply passes the entire block in as literal text. If you use the local variables 'address' and 'port' in your Jade file above the script tag they should show up.
Possible solutions are listed in the question I linked to above, but you can either: - pass every line in as unescaped text (!= at the beginning of every line), and simply put "-" before every line of javascript that uses a local variable, or: - Pass variables in through a dom element and access through JQuery (ugly)
Is there no better way? It seems the creators of Jade do not want multiline javascript support, as shown by this thread in GitHub: https://github.com/visionmedia/jade/pull/405
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
print data['fruits']
# the print displays:
# [u'apple', u'banana', u'orange']
You had everything you needed. data
will be a dict, and data['fruits']
will be a list
Yes. It will work: FileInfo.CopyTo Method
Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.
All other responses are correct, but since you asked for FileInfo
, here's a sample:
FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten
Also you can use HRTime package. It has a class StopWatch.
When you're analyzing code, you have to analyse it line by line, counting every operation/recognizing time complexity, in the end, you have to sum it to get whole picture.
For example, you can have one simple loop with linear complexity, but later in that same program you can have a triple loop that has cubic complexity, so your program will have cubic complexity. Function order of growth comes into play right here.
Let's look at what are possibilities for time complexity of an algorithm, you can see order of growth I mentioned above:
Constant time has an order of growth 1
, for example: a = b + c
.
Logarithmic time has an order of growth LogN
, it usually occurs
when you're dividing something in half (binary search, trees, even loops), or multiplying something in same way.
Linear, order of growth is N
, for example
int p = 0;
for (int i = 1; i < N; i++)
p = p + 2;
Linearithmic, order of growth is n*logN
, usually occurs in divide and conquer algorithms.
Cubic, order of growth N^3
, classic example is a triple loop where you check all triplets:
int x = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
x = x + 2
Exponential, order of growth 2^N
, usually occurs when you do exhaustive search, for example check subsets of some set.
alert(document.documentElement.outerHTML);
An unsigned 1 byte number can contain the range [0-255] inclusive. So when you see 255, it is mostly because programmers think in base 10
(get the joke?) :)
Actually, for a while, 255 was the largest size you could give a VARCHAR in MySQL, and there are advantages to using VARCHAR over TEXT with indexing and other issues.
If you're on a Unix-like system, use gettimeofday
and convert the result from microseconds to milliseconds.
Consider using the Nullable(T) structure available. It'll let you only set values if you have them, and your SQL Command objects will recognize the nullable value and process accordingly with no hassle on your end.
I tried this and it works:
stage.getIcons().add(new Image(getClass().getResourceAsStream("../images/icon.png")));
Easiest Solution... Drumm Roll... git version 2.10.1 (Apple Git-78)
1) git checkout -b localBranchNameThatDoesNotExistInRemote
2) Do your changes, and do a git commit
3) git push origin localBranchNameThatDoesNotExistInRemote --force
N.B. - The branch you just created in your local environment, and the remote non-existing branch where you are trying to push, must have the same name.
Array has a GetValue(Int32) method which you can use to retrieve the value at a specified index.
Other answers mention site.USER_SITE
as where Python packages get placed. If you're looking for binaries, these go in {site.USER_BASE}/bin
.
If you want to add this directory to your shell's search path, use:
export PATH="${PATH}:$(python3 -c 'import site; print(site.USER_BASE)')/bin"
Use a public static class and access it from anywhere.
public static class MyGlobals {
public const string Prefix = "ID_"; // cannot change
public static int Total = 5; // can change because not const
}
used like so, from master page or anywhere:
string strStuff = MyGlobals.Prefix + "something";
textBox1.Text = "total of " + MyGlobals.Total.ToString();
You don't need to make an instance of the class; in fact you can't because it's static. Just use it directly. All members inside a static class must also be static. The string Prefix isn't marked static because new
const
is implicitly static by nature.
The static class can be anywhere in your project. It doesn't have to be part of Global.asax or any particular page because it's "global" (or at least as close as we can get to that concept in object-oriented terms.)
You can make as many static classes as you like and name them whatever you want.
Sometimes programmers like to group their constants by using nested static classes. For example,
public static class Globals {
public static class DbProcedures {
public const string Sp_Get_Addresses = "dbo.[Get_Addresses]";
public const string Sp_Get_Names = "dbo.[Get_First_Names]";
}
public static class Commands {
public const string Go = "go";
public const string SubmitPage = "submit_now";
}
}
and access them like so:
MyDbCommand proc = new MyDbCommand( Globals.DbProcedures.Sp_Get_Addresses );
proc.Execute();
//or
string strCommand = Globals.Commands.Go;
Is it too late to answer. I would say, its better to go by Libraries like ClassPathScanningCandidateComponentProvider or like Scannotations
But even after somebody wants to try some hands on it with classLoader, I have written some on my own to print the annotations from classes in a package:
public class ElementScanner {
public void scanElements(){
try {
//Get the package name from configuration file
String packageName = readConfig();
//Load the classLoader which loads this class.
ClassLoader classLoader = getClass().getClassLoader();
//Change the package structure to directory structure
String packagePath = packageName.replace('.', '/');
URL urls = classLoader.getResource(packagePath);
//Get all the class files in the specified URL Path.
File folder = new File(urls.getPath());
File[] classes = folder.listFiles();
int size = classes.length;
List<Class<?>> classList = new ArrayList<Class<?>>();
for(int i=0;i<size;i++){
int index = classes[i].getName().indexOf(".");
String className = classes[i].getName().substring(0, index);
String classNamePath = packageName+"."+className;
Class<?> repoClass;
repoClass = Class.forName(classNamePath);
Annotation[] annotations = repoClass.getAnnotations();
for(int j =0;j<annotations.length;j++){
System.out.println("Annotation in class "+repoClass.getName()+ " is "+annotations[j].annotationType().getName());
}
classList.add(repoClass);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* Unmarshall the configuration file
* @return
*/
public String readConfig(){
try{
URL url = getClass().getClassLoader().getResource("WEB-INF/config.xml");
JAXBContext jContext = JAXBContext.newInstance(RepositoryConfig.class);
Unmarshaller um = jContext.createUnmarshaller();
RepositoryConfig rc = (RepositoryConfig) um.unmarshal(new File(url.getFile()));
return rc.getRepository().getPackageName();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
And in config File, you put the package name and unmarshall it to a class .
Try this type of link , it will run in also IE . hope this helps .
<link href='//fonts.googleapis.com/css?family=Josefin+Sans:300,400,600,700,300italic' rel='stylesheet' type='text/css'>
Please refer below Ajax overview:
I'm not entirely sure of the general purpose of the function, but you could always do this:
function getMachine(color, qty) {
var retval;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
retval = thisArray[3];
return false;
}
});
return retval;
}
var retval = getMachine(color, qty);
If you need only change url but prevent change state:
Change location with (add .replace if you want to replace in history):
this.$location.path([Your path]).replace();
Prevent redirect to your state:
$transitions.onBefore({}, function($transition$) {
if ($transition$.$to().name === '[state name]') {
return false;
}
});
Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():
PS > $a.GetType().fullname
System.DayOfWeek
PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject
One obvious solution would be to use javascript (which is not JSF). To implement this by JSF you should use AJAX. In this example, I use a radio button group to show and hide two set of components. In the back bean, I define a boolean switch.
private boolean switchComponents;
public boolean isSwitchComponents() {
return switchComponents;
}
public void setSwitchComponents(boolean switchComponents) {
this.switchComponents = switchComponents;
}
When the switch is true, one set of components will be shown and when it is false the other set will be shown.
<h:selectOneRadio value="#{backbean.switchValue}">
<f:selectItem itemLabel="showComponentSetOne" itemValue='true'/>
<f:selectItem itemLabel="showComponentSetTwo" itemValue='false'/>
<f:ajax event="change" execute="@this" render="componentsRoot"/>
</h:selectOneRadio>
<H:panelGroup id="componentsRoot">
<h:panelGroup rendered="#{backbean.switchValue}">
<!--switchValue to be shown on switch value == true-->
</h:panelGroup>
<h:panelGroup rendered="#{!backbean.switchValue}">
<!--switchValue to be shown on switch value == false-->
</h:panelGroup>
</H:panelGroup>
Note: on the ajax event we render components root. because components which are not rendered in the first place can't be re-rendered on the ajax event.
Also, note that if the "componentsRoot" and radio buttons are under different component hierarchy. you should reference it from the root (form root).
Just create a data.frame
with 0 length variables
eg
nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)
## 'data.frame': 0 obs. of 3 variables:
## $ x: num
## $ y: int
## $ z: Factor w/ 0 levels:
or to create a data.frame with 5 columns named a,b,c,d,e
nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))
i had the same problem, my solution was apply the required attribute to all elements
<input type="checkbox" name="checkin_days[]" required="required" value="0" /><span class="w">S</span>
<input type="checkbox" name="checkin_days[]" required="required" value="1" /><span class="w">M</span>
<input type="checkbox" name="checkin_days[]" required="required" value="2" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="3" /><span class="w">W</span>
<input type="checkbox" name="checkin_days[]" required="required" value="4" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="5" /><span class="w">F</span>
<input type="checkbox" name="checkin_days[]" required="required" value="6" /><span class="w">S</span>
when the user check one of the elements i remove the required attribute from all elements:
var $checkedCheckboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]:checked'),
$checkboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]');
$checkboxes.click(function() {
if($checkedCheckboxes.length) {
$checkboxes.removeAttr('required');
} else {
$checkboxes.attr('required', 'required');
}
});
SELECT * FROM table
where Date(col) = 'date'
-Xmx1024m -XX:MaxPermSize=512m -Xms512m
Add this parameter as argument in your server params
CREATE VIEW [dbo].[ret_vwSalariedForReport]
AS
WITH temp1 AS (SELECT
salaried.*,
operationalUnits.Title as OperationalUnitTitle
FROM
ret_vwSalaried salaried LEFT JOIN
prs_operationalUnitFeatures operationalUnitFeatures on salaried.[Guid] = operationalUnitFeatures.[FeatureGuid] LEFT JOIN
prs_operationalUnits operationalUnits ON operationalUnits.id = operationalUnitFeatures.OperationalUnitID
),
temp2 AS (SELECT
t2.*,
STUFF ((SELECT ' - ' + t1.OperationalUnitTitle
FROM
temp1 t1
WHERE t1.[ID] = t2.[ID]
For XML PATH('')), 2, 2, '') OperationalUnitTitles from temp1 t2)
SELECT
[Guid],
ID,
Title,
PersonnelNo,
FirstName,
LastName,
FullName,
Active,
SSN,
DeathDate,
SalariedType,
OperationalUnitTitles
FROM
temp2
GROUP BY
[Guid],
ID,
Title,
PersonnelNo,
FirstName,
LastName,
FullName,
Active,
SSN,
DeathDate,
SalariedType,
OperationalUnitTitles
Update 2018-07-23
As was just pointed out in the comments, this question was about getting a screenshot from the command line. Sorry, I just read over that. So here is the correct answer:
As of Firefox 57 you can create a screenshot in headless mode like this:
firefox -screenshot https://developer.mozilla.com
Read more in the documentation.
Update 2017-06-15
As of Firefox 55 there is Firefox Screenshots as a more flexible alternative. As of Firefox 57 Screenshots can capture a full page, too.
Original answer
Since Firefox 32 there is also a full page screenshot button in the developer tools (F12). If it is not enabled go to the developer tools settings (gear button) and choose "Take a fullpage screenshot" at the "Available Toolbox Buttons" section.
source: developer.mozilla.org
By default the screenshots are saved in the download directory. This works similar to screenshot --fullpage
in the toolbar.
I'm probably a bit late to the party, but I wrote the junitcategorizer for my thesis project at TOPdesk. Earlier versions indeed used a company internal Parent POM. So your problems are caused by the Parent POM not being resolvable, since it is not available to the outside world.
You can either:
<parent>
block, but then have to configure the Surefire, Compiler and other plugins yourself<parent>
<groupId>com.topdesk</groupId>
<artifactId>open-source-parent</artifactId>
<version>1.2.0</version>
</parent>
The function I use currently:
/**
* Serializes form or any other element with jQuery.serialize
* @param el
*/
serialize: function(el) {
var serialized = $(el).serialize();
if (!serialized) // not a form
serialized = $(el).
find('input[name],select[name],textarea[name]').serialize();
return serialized;
}
select{
*zoom: 1.6;
*font-size: 9px;
}
If you change properties, size of select
will change also in IE7.
Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.
DateTime#minusMonths
method would help you get previous month.
DateTime month = new DateTime().minusMonths (1);
You had it nearly right in the last line. You want
str(bytes_string, 'utf-8')
because the type of bytes_string
is bytes
, the same as the type of b'abc'
.
It might help to "How to write the code for countdown watch in AngularJS"
Step 1 : HTML Code-sample
<div ng-app ng-controller="ExampleCtrl">
<div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
<div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
<div ng-show="countDown_text == 0">Your password is expired!.</div>
</div>
Step 2 : The AngulaJs code-sample
function ExampleCtrl($scope, $timeout) {
var countDowner, countDown = 10;
countDowner = function() {
if (countDown < 0) {
$("#warning").fadeOut(2000);
countDown = 0;
return; // quit
} else {
$scope.countDown_text = countDown; // update scope
countDown--; // -1
$timeout(countDowner, 1000); // loop it again
}
};
$scope.countDown_text = countDown;
countDowner()
}
The full example over countdown watch in AngularJs as given below.
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Example - Single Timer Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>
function ExampleCtrl($scope, $timeout) {
var countDowner, countDown = 10;
countDowner = function() {
if (countDown < 0) {
$("#warning").fadeOut(2000);
countDown = 0;
return; // quit
} else {
$scope.countDown_text = countDown; // update scope
countDown--; // -1
$timeout(countDowner, 1000); // loop it again
}
};
$scope.countDown_text = countDown;
countDowner()
}
</script>
</head>
<body>
<div ng-app ng-controller="ExampleCtrl">
<div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
<div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
<div ng-show="countDown_text == 0">Your password is expired!.</div>
</div>
</body>
</html>
What's wrong with
func (e *Easy)SetStringOption(option Option, param string)
func (e *Easy)SetLongOption(option Option, param long)
and so on?
#testDiv{
/* set green border independently on each side */
border-left: solid green 2px;
border-right: solid green 2px;
border-bottom: solid green 2px;
border-top: solid green 2px;
}
Yes: implements Runnable
is the preferred way to do it, IMO. You're not really specialising the thread's behaviour. You're just giving it something to run. That means composition is the philosophically "purer" way to go.
In practical terms, it means you can implement Runnable
and extend from another class as well... and you can also implement Runnable
via a lambda expression as of Java 8.
With closure:
class TextFieldWithClosure: UITextField {
var targetAction: (() -> Void)? {
didSet {
self.addTarget(self, action: #selector(self.targetSelector), for: .editingChanged)
}
}
func targetSelector() {
self.targetAction?()
}
}
and using
textField.targetAction? = {
// will fire on text changed
}
CURL request by default is GET, you don't have to set any options to make a GET CURL request.
I don't believe this is possible - there is no ability to set the timezone on a Date object after it is created.
And in a way this makes sense - conceptually (if perhaps not in implementation); per http://en.wikipedia.org/wiki/Unix_timestamp (emphasis mine):
Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970.
Once you've constructed one it will represent a certain point in "real" time. The time zone is only relevant when you want to convert that abstract time point into a human-readable string.
Thus it makes sense you would only be able to change the actual time the Date represents in the constructor. Sadly it seems that there is no way to pass in an explicit timezone - and the constructor you are calling (arguably correctly) translates your "local" time variables into GMT when it stores them canonically - so there is no way to use the int, int, int
constructor for GMT times.
On the plus side, it's trivial to just use the constructor that takes a String instead. You don't even have to convert the numeric month into a String (on Firefox at least), so I was hoping a naive implementation would work. However, after trying it out it works successfully in Firefox, Chrome, and Opera but fails in Konqueror ("Invalid Date") , Safari ("Invalid Date") and IE ("NaN"). I suppose you'd just have a lookup array to convert the month to a string, like so:
var months = [ '', 'January', 'February', ..., 'December'];
function createGMTDate(xiYear, xiMonth, xiDate) {
return new Date(months[xiMonth] + ' ' + xiDate + ', ' + xiYear + ' 00:00:00 GMT');
}
Show file and track error
systemctl status nginx.service
Our aim is basically to check whether 2 arrays are equal sets. set is the mathematically defined set. Fastest sorting asymptotically takes O(nlog(n)) time. So If you sort an array, it would take at least O(nlog(n)) time. But you can do this task faster, which asymptotically takes O(n) time (average case not worst case) with a dictionary data structure. In JS, a dictionary is simply an object with keys and values.
/** assumes array elements are primitive types
* check whether 2 arrays are equal sets.
* @param {} a1 is an array
* @param {} a2 is an array
*/
function areArraysEqualSets(a1, a2) {
const superSet = {};
for (const i of a1) {
const e = i + typeof i;
superSet[e] = 1;
}
for (const i of a2) {
const e = i + typeof i;
if (!superSet[e]) {
return false;
}
superSet[e] = 2;
}
for (let e in superSet) {
if (superSet[e] === 1) {
return false;
}
}
return true;
}
Note that this function works with arrays of primitive types and assumes a1
and a2
are arrays.
Array.sort()
to sort an array…
) to make the function pureupdated_at
)Array.sort()
works by subtracting two properties from current and next item if it is a number / object on which you can perform arrhythmic operationsconst input = [
{
updated_at: '2012-01-01T06:25:24Z',
foo: 'bar',
},
{
updated_at: '2012-01-09T11:25:13Z',
foo: 'bar',
},
{
updated_at: '2012-01-05T04:13:24Z',
foo: 'bar',
}
];
const sortByUpdatedAt = (items) => [...items].sort((itemA, itemB) => new Date(itemA.updated_at) - new Date(itemB.updated_at));
const output = sortByUpdatedAt(input);
console.log(input);
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' },
{ updated_at: '2012-01-09T11:25:13Z', foo: 'bar' },
{ updated_at: '2012-01-05T04:13:24Z', foo: 'bar' } ]
*/
console.log(output)
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' },
{ updated_at: '2012-01-05T04:13:24Z', foo: 'bar' },
{ updated_at: '2012-01-09T11:25:13Z', foo: 'bar' } ]
*/
But the thing is that the .chapter class is not dynamic you're declaring a height:1200px
so it's better to use background:cover and set with media queries specific height's for popular resolutions.
You don't need to have static
in function definition
Here's an upstart solution I've been using for my personal projects:
Place it in /etc/init/node_app_daemon.conf
:
description "Node.js Daemon"
author "Adam Eberlin"
stop on shutdown
respawn
respawn limit 3 15
script
export APP_HOME="/srv/www/MyUserAccount/server"
cd $APP_HOME
exec sudo -u user /usr/bin/node server.js
end script
This will also handle respawning your application in the event that it crashes. It will give up attempts to respawn your application if it crashes 3 or more times in less than 15 seconds.
The accepted answer only renamed the user but the privileges were left behind.
I'd recommend using:
RENAME USER 'foo'@'1.2.3.4' TO 'foo'@'1.2.3.5';
According to MySQL documentation:
RENAME USER causes the privileges held by the old user to be those held by the new user.
You are expecting an id
parameter in your URL but you aren't supplying one. Such as:
http://yoursite.com/controller/edit/12
^^ missing
Using the function above, you would do:
var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);
Of course, the following would also work:
var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];
since all objects in JavaScript are hash tables! It would, however, be harder to iterate over since using foreach(var item in object)
would also get you all its functions, etc., but that might be enough depending on your needs.
If the .project
and .classpath
are already committed, then they need to be removed from the index (but not the disk)
git rm --cached .project
git rm --cached .classpath
Then the .gitignore
would work (and that file can be added and shared through clones).
For instance, this gitignore.io/api/eclipse
file will then work, which does include:
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath
Note that you could use a "Template Directory" when cloning (make sure your users have an environment variable $GIT_TEMPLATE_DIR
set to a shared folder accessible by all).
That template folder can contain an info/exclude
file, with ignore rules that you want enforced for all repos, including the new ones (git init
) that any user would use.
When you change the index, you need to commit the change and push it.
Then the file is removed from the repository. So the newbies cannot checkout the files.classpath
and.project
from the repo.
It's 2020 and stuffs had greatly evolved with php 7.4 and opcache.
Here is the OP^ benchmark, ran as unix CLI, without the echo and html parts.
Test ran locally on a regular computer.
php -v
PHP 7.4.6 (cli) (built: May 14 2020 10:02:44) ( NTS )
Modified benchmark script:
<?php
## preperations; just a simple environment state
$test_iterations = 100;
$test_arr_size = 1000;
// a shared function that makes use of the loop; this should
// ensure no funny business is happening to fool the test
function test($input)
{
//echo '<!-- '.trim($input).' -->';
}
// for each test we create a array this should avoid any of the
// arrays internal representation or optimizations from getting
// in the way.
// normal array
$test_arr1 = array();
$test_arr2 = array();
$test_arr3 = array();
// hash tables
$test_arr4 = array();
$test_arr5 = array();
for ($i = 0; $i < $test_arr_size; ++$i)
{
mt_srand();
$hash = md5(mt_rand());
$key = substr($hash, 0, 5).$i;
$test_arr1[$i] = $test_arr2[$i] = $test_arr3[$i] = $test_arr4[$key] = $test_arr5[$key]
= $hash;
}
## foreach
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr1 as $k => $v)
{
test($v);
}
}
echo 'foreach '.(microtime(true) - $start)."\n";
## foreach (using reference)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr2 as &$value)
{
test($value);
}
}
echo 'foreach (using reference) '.(microtime(true) - $start)."\n";
## for
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
$size = count($test_arr3);
for ($i = 0; $i < $size; ++$i)
{
test($test_arr3[$i]);
}
}
echo 'for '.(microtime(true) - $start)."\n";
## foreach (hash table)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr4 as $k => $v)
{
test($v);
}
}
echo 'foreach (hash table) '.(microtime(true) - $start)."\n";
## for (hash table)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
$keys = array_keys($test_arr5);
$size = sizeOf($test_arr5);
for ($i = 0; $i < $size; ++$i)
{
test($test_arr5[$keys[$i]]);
}
}
echo 'for (hash table) '.(microtime(true) - $start)."\n";
Output:
foreach 0.0032877922058105
foreach (using reference) 0.0029420852661133
for 0.0025191307067871
foreach (hash table) 0.0035080909729004
for (hash table) 0.0061779022216797
As you can see the evolution is insane, about 560 time faster than reported in 2012.
On my machines and servers, following my numerous experiments, basics for loops are the fastest. This is even clearer using nested loops ($i $j $k..)
It is also the most flexible in usage, and has a better readability from my view.
This happened to me. I checked the SDK Manager and it told me the one I was using had a update. I updated it and the problem went away.
In case you don't need to catch the error and you want to immediately stop the application you can use a fatalError:
fatalError ("Custom message here")
I meet this error when integrate modal bootstrap in angular.
This is my solution to solve this issue.
I share for whom concern.
First step you need install jquery
and bootstrap
by npm
command.
Second you need add declare var $ : any;
in component
And use can use $('#myModal').modal('hide');
on onSave() method
Demo https://stackblitz.com/edit/angular-model-bootstrap-close?file=src/app/app.component.ts
See this snippet: (C#)
private Microsoft.Office.Interop.Excel.Application xla;
Workbook wb;
Worksheet ws;
Range rg;
..........
xla = new Microsoft.Office.Interop.Excel.Application();
wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
ws = (Worksheet)xla.ActiveSheet;
rg = (Range)ws.Cells[1, 2];
rg.ColumnWidth = 10;
rg.Value2 = "Frequency";
rg = (Range)ws.Cells[1, 3];
rg.ColumnWidth = 15;
rg.Value2 = "Impudence";
rg = (Range)ws.Cells[1, 4];
rg.ColumnWidth = 8;
rg.Value2 = "Phase";
If you are running cmake
to generate SomeLib
yourself (say as part of a superbuild), consider using the User Package Registry. This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the CONFIG
mode of the find_packages() command, you'll see that the User Package Registry is one of elements.
Brief how-to
Associate the targets of SomeLib
that you need outside of that external project by adding them to an export set in the CMakeLists.txt
files where they are created:
add_library(thingInSomeLib ...)
install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib)
Create a XXXConfig.cmake
file for SomeLib
in its ${CMAKE_CURRENT_BUILD_DIR}
and store this location in the User Package Registry by adding two calls to export() to the CMakeLists.txt
associated with SomeLib
:
export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake
export(PACKAGE SomeLib) # Store location of SomeLibConfig.cmake
Issue your find_package(SomeLib REQUIRED)
commmand in the CMakeLists.txt
file of the project that depends on SomeLib
without the "non-cross-platform hard coded paths" tinkering with the CMAKE_MODULE_PATH
.
When it might be the right approach
This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary.
But if you're never actually installing SomeLib
in your workflow, calling EXPORT(PACKAGE <name>)
allows you to avoid the hard-coded path. And, of course, if you are installing SomeLib
, you probably know your platform, CMAKE_MODULE_PATH
, etc, so @user2288008's excellent answer will have you covered.
On OSX 10.8 and on, the control for MySQL is available from the System Configs. Open System Preferences, click on Mysql (usually on the very bottom) and start/stop the service from that pane. https://dev.mysql.com/doc/refman/5.6/en/osx-installation-launchd.html
The plist file is now under /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist
For:
2 mod 4
We can use this little formula I came up with after thinking a bit, maybe it's already defined somewhere I don't know but works for me, and its really useful.
A mod B = C
where C is the answer
K * B - A = |C|
where K is how many times B fits in A
2 mod 4
would be:
0 * 4 - 2 = |C|
C = |-2| => 2
Hope it works for you :)
It might be worth mentioning that the bisect docs now provide searching examples: http://docs.python.org/library/bisect.html#searching-sorted-lists
(Raising ValueError instead of returning -1 or None is more pythonic – list.index() does it, for example. But of course you can adapt the examples to your needs.)
I have a different take on this. I could do a docker ps
and see that there is a docker container running, I even tried to restart it, but as soon as I tried to get a session for it with New-PSSession -ContainerId $containerId -RunAsAdministrator
It would error out, saying:
##[error]New-PSSession : The input ContainerId xxx does not exist, ##[error]or the corresponding container is not running.
My problem was I was running with network service and it did not have enough permissions to see the container, even though I had given it permissions to run docker commands (with docker security group configuration)
I didn't know how to enable working with containers, so I had to revert to running it as an admin user instead
For a long time I have used the alternative:
('netscape' in window) && / rv:/.test(navigator.userAgent)
because I don't trust user agent strings. Some bugs are not detectable using feature detection, so detecting the browser is required for some workarounds.
Also if you are working around a bug in Gecko, then the bug is probably also in derivatives of Firefox, and this code should work with derivatives too (Do Waterfox and Pale Moon have 'Firefox' in the user agent string?).
By using regular expression :
String s = "test string (67)";
Pattern p = Pattern.compile("\\(.*?\\)");
Matcher m = p.matcher(s);
if(m.find())
System.out.println(m.group().subSequence(1, m.group().length()-1));
Try using TRUNC
and TO_DATE
instead
WHERE
TRUNC(start_ts) = TO_DATE('2016-05-13', 'YYYY-MM-DD')
Alternatively, you can use >=
and <
instead to avoid use of function in the start_ts
column:
WHERE
start_ts >= TO_DATE('2016-05-13', 'YYYY-MM-DD')
AND start_ts < TO_DATE('2016-05-14', 'YYYY-MM-DD')
In Android studio, Edit -- > Find --> Replace in path, this will check in whole project including comments and code.
Okay, so I have just spent several hours looking for a viable method for posting multiple parameters to an MVC 4 WEB API, but most of what I found was either for a 'GET' action or just flat out did not work. However, I finally got this working and I thought I'd share my solution.
Use NuGet packages to download JSON-js json2
and Json.NET
. Steps to install NuGet packages:
(1) In Visual Studio, go to Website > Manage NuGet Packages...
(2) Type json (or something to that effect) into the search bar and find JSON-js json2
and Json.NET
. Double-clicking them will install the packages into the current project.
(3) NuGet will automatically place the json file in ~/Scripts/json2.min.js
in your project directory. Find the json2.min.js file and drag/drop it into the head of your website. Note: for instructions on installing .js (javascript) files, read this solution.
Create a class object containing the desired parameters. You will use this to access the parameters in the API controller. Example code:
Public Class PostMessageObj
Private _body As String
Public Property body As String
Get
Return _body
End Get
Set(value As String)
_body = value
End Set
End Property
Private _id As String
Public Property id As String
Get
Return _id
End Get
Set(value As String)
_id = value
End Set
End Property
End Class
Then we setup the actual MVC 4 Web API controller that we will be using for the POST action. In it, we will use Json.NET to deserialize the string object when it is posted. Remember to use the appropriate namespaces. Continuing with the previous example, here is my code:
Public Sub PostMessage(<FromBody()> ByVal newmessage As String)
Dim t As PostMessageObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of PostMessageObj)(newmessage)
Dim body As String = t.body
Dim i As String = t.id
End Sub
Now that we have our API controller set up to receive our stringified JSON object, we can call the POST action freely from the client-side using $.ajax; Continuing with the previous example, here is my code (replace localhost+rootpath appropriately):
var url = 'http://<localhost+rootpath>/api/Offers/PostMessage';
var dataType = 'json'
var data = 'nothn'
var tempdata = { body: 'this is a new message...Ip sum lorem.',
id: '1234'
}
var jsondata = JSON.stringify(tempdata)
$.ajax({
type: "POST",
url: url,
data: { '': jsondata},
success: success(data),
dataType: 'text'
});
As you can see we are basically building the JSON object, converting it into a string, passing it as a single parameter, and then rebuilding it via the JSON.NET framework. I did not include a return value in our API controller so I just placed an arbitrary string value in the success()
function.
This was done in Visual Studio 2010 using ASP.NET 4.0, WebForms, VB.NET, and MVC 4 Web API Controller. For anyone having trouble integrating MVC 4 Web API with VS2010, you can download the patch to make it possible. You can download it from Microsoft's Download Center.
Here are some additional references which helped (mostly in C#):
If you're just needing the path of the MDB currently open in the Access UI, I'd suggest writing a function that parses CurrentDB.Name and then stores the result in a Static variable inside the function. Something like this:
Public Function CurrentPath() As String
Dim strCurrentDBName As String
Static strPath As String
Dim i As Integer
If Len(strPath) = 0 Then
strCurrentDBName = CurrentDb.Name
For i = Len(strCurrentDBName) To 1 Step -1
If Mid(strCurrentDBName, i, 1) = "\" Then
strPath = Left(strCurrentDBName, i)
Exit For
End If
Next
End If
CurrentPath = strPath
End Function
This has the advantage that it only loops through the name one time.
Of course, it only works with the file that's open in the user interface.
Another way to write this would be to use the functions provided at the link inside the function above, thus:
Public Function CurrentPath() As String
Static strPath As String
If Len(strPath) = 0 Then
strPath = FolderFromPath(CurrentDB.Name)
End If
CurrentPath = strPath
End Function
This makes retrieving the current path very efficient while utilizing code that can be used for finding the path for any filename/path.
System.getProperty("user.dir")
fetches the directory or path of the workspace for the current project
Statement
DEFINER=
username
@`%
is an issue in your backup dump.
The solution that you can work around is to remove all the entry from sql dump file and import data from GCP console.
cat DUMP_FILE_NAME.sql | sed -e 's/DEFINER=
<username>
@%
//g' > NEW-CLEANED-DUMP.sql
Try importing new file(NEW-CLEANED-DUMP.sql).
Select * from (Select orgName,id,
ROW_NUMBER() OVER(Partition By OrgName ORDER by id DESC) Rownum
From organizations )tbl Where Rownum>1
So the records with rowum> 1 will be the duplicate records in your table. ‘Partition by’ first group by the records and then serialize them by giving them serial nos. So rownum> 1 will be the duplicate records which could be deleted as such.
My answer:
set_headless(headless=True) is deprecated.
options.headless = True
works for me
This is because your <h1>
is the width of the centercol. Specify a width on the <h1>
and use margin: 0 auto;
if you want it centered.
Or, alternatively, you could float the <h1>
, which would make it only exactly as wide as the text.
I know this is very old and possibly talking about an older version of Visual studio and so this might not have been an option before but anyway, my way would be when at a breakpoint use the locals window to see all current variable values ( Debug >> Windows >> Locals )
I'm using this, and it works well for me:
textBox1.Text = ConfigurationManager.AppSettings["Name"];
Did you change any thing on the virtual-host before it stop working ?
Add this line to xampp/apache/conf/extra/httpd-vhosts.conf
<VirtualHost localhost:80>
DocumentRoot "C:/xampp/htdocs"
ServerAdmin localhost
<Directory "C:/xampp/htdocs">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
MySQL 5.7 now provides a JSON data type. This new datatype provides a convenient new way to store complex data: lists, dictionaries, etc.
That said, arrays don't map well databases which is why object-relational maps can be quite complex. Historically people have stored lists/arrays in MySQL by creating a table that describes them and adding each value as its own record. The table may have only 2 or 3 columns, or it may contain many more. How you store this type of data really depends on characteristics of the data.
For example, does the list contain a static or dynamic number of entries? Will the list stay small, or is it expected to grow to millions of records? Will there be lots of reads on this table? Lots of writes? Lots of updates? These are all factors that need to be considered when deciding how to store collections of data.
Also, Key/Value data stores, Document stores such as Cassandra, MongoDB, Redis etc provide a good solution as well. Just be aware of where the data is actually being stored (if its being stored on disk or in memory). Not all of your data needs to be in the same database. Some data does not map well to a relational database and you may have reasons for storing it elsewhere, or you may want to use an in-memory key:value database as a hot-cache for data stored on disk somewhere or as an ephemeral storage for things like sessions.
For me, the fix was to upgrade the version of System.Web.Optimization to 1.1.0.0 When I was at version 1.0.0.0 it would never resolve a .map file in a subdirectory (i.e. correctly minify and bundle scripts in a subdirectory)
Work out the solution according to what you want...
There are two things that getResource
/getResourceAsStream()
will get from the class it is called on...
So if you do
this.getClass().getResource("foo.txt");
it will attempt to load foo.txt from the same package as the "this" class and with the class loader of the "this" class. If you put a "/" in front then you are absolutely referencing the resource.
this.getClass().getResource("/x/y/z/foo.txt")
will load the resource from the class loader of "this" and from the x.y.z package (it will need to be in the same directory as classes in that package).
Thread.currentThread().getContextClassLoader().getResource(name)
will load with the context class loader but will not resolve the name according to any package (it must be absolutely referenced)
System.class.getResource(name)
Will load the resource with the system class loader (it would have to be absolutely referenced as well, as you won't be able to put anything into the java.lang package (the package of System).
Just take a look at the source. Also indicates that getResourceAsStream just calls "openStream" on the URL returned from getResource and returns that.
Just simply
var tar = (TargetFrameworkAttribute)Assembly
.LoadFrom("yoursAssembly.dll")
.GetCustomAttributes(typeof(TargetFrameworkAttribute)).First();
LocalDate date = new Date(); date.lengthOfMonth()
or
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd");
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM");
String stringDate = formatter.format(date);
String month = monthFormatter.format(date);
It's not a direct answer to the question but you could just use the OR-operator
( grep "#SystemMaxUse=" journald.conf > /dev/null && sed -i 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf ) || echo "This file has been edited. You'll need to do it manually."
There is an Ini Parser available in CommonLibrary.NET
This has various very convenient overloads for getting sections/values and is very light weight.
The Rob Evans anwser works correctly for me but when I use request.abort(), it occurs to throw a socket hang up error which stays unhandled.
I had to add an error handler for the request object :
var options = { ... }
var req = http.request(options, function(res) {
// Usual stuff: on(data), on(end), chunks, etc...
}
req.on('socket', function (socket) {
socket.setTimeout(myTimeout);
socket.on('timeout', function() {
req.abort();
});
}
req.on('error', function(err) {
if (err.code === "ECONNRESET") {
console.log("Timeout occurs");
//specific error treatment
}
//other error treatment
});
req.write('something');
req.end();
find /home/test -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' -mtime +3
-name
uses globular expressions,
aka wildcards. What you want is
-regex
find
to use Extended
Regular Expressions via the
-regextype posix-extended
flag\.
+
as
in -mtime +3
.$ find . -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip'
./test.log.1234-12-12.zip
For Interface Builder version with Swift
@IBOutlet weak var tvValue: UITextView! {
didSet {
tvValue.tintColor = .black
}
}
Random number from the range [min..max] inclusive:
int randomFromMinToMaxInclusive = ThreadLocalRandom.current()
.nextInt(min, max + 1);
Sadly, straight from google, which is where you will want to download if your company firewall blocks other sources, Release 1.6 r1 September 2009 is the latest SDK they have.
You can create constants in many different ways:
const myString = "hello"
const pi = 3.14 // untyped constant
const life int = 42 // typed constant (can use only with ints)
You can also create a enum constant:
const (
First = 1
Second = 2
Third = 4
)
You can not create constants of maps, arrays and it is written in effective go:
Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.
A tag is used to mark a version, more specifically it references a point in time on a branch. A branch is typically used to add features to a project.
You can start with a google sheet set up with a main page and drop down source page like shown below.
You can set up the first column drop down through the normal Data > Validations menu prompts.
Main Page
Drop Down Source Page
After that, you need to set up a script with the name onEdit
. (If you don't use that name, the getActiveRange() will do nothing but return cell A1)
And use the code provided here:
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var myRange = SpreadsheetApp.getActiveRange();
var dvSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Categories");
var option = new Array();
var startCol = 0;
if(sheet.getName() == "Front Page" && myRange.getColumn() == 1 && myRange.getRow() > 1){
if(myRange.getValue() == "Category 1"){
startCol = 1;
} else if(myRange.getValue() == "Category 2"){
startCol = 2;
} else if(myRange.getValue() == "Category 3"){
startCol = 3;
} else if(myRange.getValue() == "Category 4"){
startCol = 4;
} else {
startCol = 10
}
if(startCol > 0 && startCol < 10){
option = dvSheet.getSheetValues(3,startCol,10,1);
var dv = SpreadsheetApp.newDataValidation();
dv.setAllowInvalid(false);
//dv.setHelpText("Some help text here");
dv.requireValueInList(option, true);
sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).setDataValidation(dv.build());
}
if(startCol == 10){
sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).clearDataValidations();
}
}
}
After that, set up a trigger in the script editor screen by going to Edit > Current Project Triggers. This will bring up a window to have you select various drop downs to eventually end up at this:
You should be good to go after that!
There is a condition, when all of the values that you are checking are the same, where @jerryjvl's code would return NaN.
if (OldMin != OldMax && NewMin != NewMax):
return (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
else:
return (NewMax + NewMin) / 2
Here's a good way using :after on the image div, instead of the extra overlay div: http://jsfiddle.net/Zf5am/576/
<div class="image">
<img src="http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg" alt="" />
</div>
.image {position:relative; border:1px solid black; width:200px; height:200px;}
.image img {max-width:100%; max-height:100%;}
.image:hover:after {content:""; position:absolute; top:0; left:0; bottom:0; right:0; background-color: rgba(0,0,0,0.3);}