The reasons for this error can be either you did not install Flutter or you are using an older version of Flutter 1.21. So it is advisable to check the above things first of all. If none of the above things are the reasons for your error you can follow the below steps and it might help you.
Flutter SDK path should be empty here. The problem is in here
it is simple but the first time it takes time a few steps to set !!!
you have the latest version on node.
go to the environment variable and set the path "%SystemRoot%\system32"
.
run cmd as administrator mode.
write command npm start.
Use sortedWith
to sort a list with Comparator
.
You can then construct a comparator using several ways:
var request = new HttpRequestMessage {
RequestUri = new Uri("[your request url string]"),
Method = HttpMethod.Post,
Headers = {
{ "X-Version", "1" } // HERE IS HOW TO ADD HEADERS,
{ HttpRequestHeader.Authorization.ToString(), "[your authorization token]" },
{ HttpRequestHeader.ContentType.ToString(), "multipart/mixed" },//use this content type if you want to send more than one content type
},
Content = new MultipartContent { // Just example of request sending multipart request
new ObjectContent<[YOUR JSON OBJECT TYPE]>(
new [YOUR JSON OBJECT TYPE INSTANCE](...){...},
new JsonMediaTypeFormatter(),
"application/json"), // this will add 'Content-Type' header for the first part of request
new ByteArrayContent([BINARY DATA]) {
Headers = { // this will add headers for the second part of request
{ "Content-Type", "application/Executable" },
{ "Content-Disposition", "form-data; filename=\"test.pdf\"" },
},
},
},
};
$("#Id").change(function(){
var selected = $('#Id option:selected').val();
alert(selected);
});
I think this is what you need.
The reason why the sublime documented shortcuts for Mac does not work are they are linked to the shortcuts of other Mac functionalities such as Mission Control, Application Windows, etc. Solution: Go to System Preferences -> Keyboard -> Shortcuts and then un-check the options for Mission Control and Application Windows. Now try "Control + Shift [+ Arrow keys]" for selecting the required text and then move the cursor to the required location without any mouse click, so that the selection can be pasted with the correct indentation at the required location.
There are just two minor things here.
The first is in the following carousel indicator list items:
<li data-target="carousel" data-slide-to="0"></li>
You need to pass the data-target
attribute a selector which means the ID must be prefixed with #
. So change them to the following:
<li data-target="#carousel" data-slide-to="0"></li>
Secondly, you need to give the carousel a starting point so both the carousel indicator items and the carousel inner items must have one active
class. Like this:
<ol class="carousel-indicators">
<li data-target="#carousel" data-slide-to="0" class="active"></li>
<!-- Other Items -->
</ol>
<div class="carousel-inner">
<div class="item active">
<img src="https://picsum.photos/1500/600?image=1" alt="Slide 1" />
</div>
<!-- Other Items -->
</div>
I know this is a rather old question as of now, but I had found the proper solution was that I was not declaring the assembly attribute.
My code is:
using AutoMapper;
...
namespace [...].Controllers
{
public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
{
Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
}
...
}
This was fixed by adding the following line before my namespace declaration:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]
The full code is:
using AutoMapper;
...
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]
namespace [...].Controllers
{
public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
{
Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
}
...
}
You can get the index of the select box by using : .prop() method of JQuery
Check This :
<!doctype html>
<html>
<head>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function check(){
alert($("#NumberSelector").prop('selectedIndex'));
alert(document.getElementById("NumberSelector").value);
}
</script>
</head>
<body bgcolor="yellow">
<div>
<select id="NumberSelector" onchange="check()">
<option value="Its Zero">Zero</option>
<option value="Its One">One</option>
<option value="Its Two">Two</option>
<option value="Its Three">Three</option>
<option value="Its Four">Four</option>
<option value="Its Five">Five</option>
<option value="Its Six">Six</option>
<option value="Its Seven">Seven</option>
</select>
</div>
</body>
</html>
With the command:
sudo apt-get remove --purge mysql\*
you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).
You can list all installed mysql packages with the command:
sudo dpkg -l | grep -i mysql
For more cleanup of the package cache, you can use the command:
sudo apt-get clean
Also, remember to use the command:
sudo updatedb
Otherwise the "locate" command will display old data.
To install mysql again, use the following command:
sudo apt-get install libmysqlclient-dev mysql-client
This will install the mysql client, libmysql and its headers files.
To install the mysql server, use the command:
sudo apt-get install mysql-server
These will also redirect both:
yourcommand &> /dev/null
yourcommand >& /dev/null
though the bash manual says the first is preferred.
You need a delimiter for your pattern. It should be added at the start and end of the pattern like so:
$pattern = "/My name is '(.*)' and im fine/"; // With / as a delimeter
^\+[1-9]{1}[0-9]{7,11}$
The Regular Expression ^\+[1-9]{1}[0-9]{7,11}$
fails for "+290 8000" and similar valid numbers that are shorter than 8 digits.
The longest numbers could be something like 3 digit country code, 3 digit area code, 8 digit subscriber number, making 14 digits.
on Kate
Ctrl + Shift + B also allows you to add more columns by simply clicking anywhere and paste it.
I used this when saving text files I copied from Google Translate as a side-by-side view.
In some projects it really doesn't make sense to have the detailed timezones of Africa, Europe or Pacific. So here is a short version
$timezoneTable = array(
"-12" => "(GMT -12:00) Eniwetok, Kwajalein",
"-11" => "(GMT -11:00) Midway Island, Samoa",
"-10" => "(GMT -10:00) Hawaii",
"-9" => "(GMT -9:00) Alaska",
"-8" => "(GMT -8:00) Pacific Time (US & Canada)",
"-7" => "(GMT -7:00) Mountain Time (US & Canada)",
"-6" => "(GMT -6:00) Central Time (US & Canada), Mexico City",
"-5" => "(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima",
"-4" => "(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz",
"-3.5" => "(GMT -3:30) Newfoundland",
"-3" => "(GMT -3:00) Brazil, Buenos Aires, Georgetown",
"-2" => "(GMT -2:00) Mid-Atlantic",
"-1" => "(GMT -1:00) Azores, Cape Verde Islands",
"0" => "(GMT) Western Europe Time, London, Lisbon, Casablanca",
"1" => "(GMT +1:00) Brussels, Copenhagen, Madrid, Paris",
"2" => "(GMT +2:00) Kaliningrad, South Africa",
"3" => "(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg",
"3.5" => "(GMT +3:30) Tehran",
"4" => "(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi",
"4.5" => "(GMT +4:30) Kabul",
"5" => "(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent",
"5.5" => "(GMT +5:30) Bombay, Calcutta, Madras, New Delhi",
"6" => "(GMT +6:00) Almaty, Dhaka, Colombo",
"7" => "(GMT +7:00) Bangkok, Hanoi, Jakarta",
"8" => "(GMT +8:00) Beijing, Perth, Singapore, Hong Kong",
"9" => "(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk",
"9.5" => "(GMT +9:30) Adelaide, Darwin",
"10" => "(GMT +10:00) Eastern Australia, Guam, Vladivostok",
"11" => "(GMT +11:00) Magadan, Solomon Islands, New Caledonia",
"12" => "(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka"
);
echo "<select>";
foreach ($timezoneTable as $k => $v){
$sel = ($k==-5)?" selected":"";
echo "<option value='".$k."'".$sel.">".$v."</option>";
}
echo "</select>"
this will generate a select as below:
Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.
The finally implemented code started like this:
try
{
// Create a new instance of the AesManaged class. This generates a new key and initialization vector (IV).
AesManaged myAes = new AesManaged();
// Override the cipher mode, key and IV
myAes.Mode = CipherMode.ECB;
myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
myAes.Key = CipherKey; // Byte array representing the key
myAes.Padding = PaddingMode.None;
// Create a encryption object to perform the stream transform.
ICryptoTransform encryptor = myAes.CreateEncryptor();
// TODO: perform the encryption / decryption as required...
}
catch (Exception ex)
{
// TODO: Log the error
throw ex;
}
clearScene: function() {
var objsToRemove = _.rest(scene.children, 1);
_.each(objsToRemove, function( object ) {
scene.remove(object);
});
},
this uses undescore.js to iterrate over all children (except the first) in a scene (it's part of code I use to clear a scene). just make sure you render the scene at least once after deleting, because otherwise the canvas does not change! There is no need for a "special" obj flag or anything like this.
Also you don't delete the object by name, just by the object itself, so calling
scene.remove(object);
instead of scene.remove(object.name);
can be enough
PS: _.each
is a function of underscore.js
Usual way is to go with PHP and ajax. But for your requirement, below will work fine.
<body>
https://www.google.com/controller/Add/2/2<br>
https://www.google.com/controller/Sub/5/2<br>
https://www.google.com/controller/Multi/3/2<br><br>
<input type="text" id="url" placeholder="RESTful URL" />
<input type="button" id="sub" value="Answer" />
<p>
<div id="display"></div>
</body>
<script type="text/javascript">
document.getElementById('sub').onclick = function(){
var url = document.getElementById('url').value;
var controller = null;
var method = null;
var parm = [];
//validating URLs
function URLValidation(url){
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var x = url.split('/');
controller = x[3];
method = x[4];
parm[0] = x[5];
parm[1] = x[6];
}
}
//Calculations
function Add(a,b){
return Number(a)+ Number(b);
}
function Sub(a,b){
return Number(a)/Number(b);
}
function Multi(a,b){
return Number(a)*Number(b);
}
//JSON Response
function ResponseRequest(status,res){
var res = {status: status, response: res};
document.getElementById('display').innerHTML = JSON.stringify(res);
}
//Process
function ProcessRequest(){
if(method=="Add"){
ResponseRequest("200",Add(parm[0],parm[1]));
}else if(method=="Sub"){
ResponseRequest("200",Sub(parm[0],parm[1]));
}else if(method=="Multi"){
ResponseRequest("200",Multi(parm[0],parm[1]));
}else {
ResponseRequest("404","Not Found");
}
}
URLValidation(url);
ProcessRequest();
};
</script>
There is another way. There is a program called PowerRun which allows for elevated cmd to be run. Even with TrustedInstaller rights. It allows for both console and GUI commands.
For example, like this:
const querystring = require('querystring');
const https = require('https');
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'posttestserver.com',
port: 443,
path: '/post.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(postData);
req.end();
You can also watch the output like this:
final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
And don't forget, if you are running a windows command, you need to put cmd /c
in front of your command.
EDIT: And for bonus points, you can also use ProcessBuilder
to pass input to a program:
String[] command = new String[] {
"choice",
"/C",
"YN",
"/M",
"\"Press Y if you're cool\""
};
String inputLine = "Y";
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writer.write(inputLine);
writer.newLine();
writer.close();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
This will run the windows command choice /C YN /M "Press Y if you're cool"
and respond with a Y
. So, the output will be:
Press Y if you're cool [Y,N]?Y
You need to install this
https://pypi.python.org/pypi/six
If you still don't know what pip is , then please also google for pip install
Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/
In Short,
git remote rm origin
git remote add origin [email protected]:username/myapp.git
Worked !
Cheers!
I modified indgar's solution to handle negative numbers and small numbers (including zero).
from math import log10, floor
def round_sig(x, sig=6, small_value=1.0e-9):
return round(x, sig - int(floor(log10(max(abs(x), abs(small_value))))) - 1)
This should do the trick.....
reset($array);
while (list($elementKey, $element) = each($array)) {
while (list($key, $value2) = each($element)) {
if($key == 'id' && $value == 'searched_value') {
unset($array[$elementKey]);
}
}
}
Send a POST request with content type = 'form-data':
import requests
files = {
'username': (None, 'myusername'),
'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)
I used these two to solve my problem after upgrading to android studio 2.3
compile 'com.android.support:animated-vector-drawable:25.0.0'
compile 'com.android.support:mediarouter-v7:25.0.0'
If you want the button to stay static without the "pressed" appearance:
// Swift 2
editButton.userInteractionEnabled = false
// Swift 3
editButton.isUserInteractionEnabled = false
Remember:
1) Your IBOutlet
is --> @IBOutlet weak var editButton: UIButton!
2) Code above goes in viewWillAppear
Don't set the style object itself, set the background color property of the style object that is a property of the element.
And yes, even though you said no, jquery and tablesorter with its zebra stripe plugin can do this all for you in 3 lines of code.
And just setting the class attribute would be better since then you have non-hard-coded control over the styling which is more organized
Sounds like you want to do something like this:
{{> person {another: 'attribute'} }}
Yehuda already gave you a way of doing that:
{{> person this}}
But to clarify:
To give your partial its own data, just give it its own model inside the existing model, like so:
{{> person this.childContext}}
In other words, if this is the model you're giving to your template:
var model = {
some : 'attribute'
}
Then add a new object to be given to the partial:
var model = {
some : 'attribute',
childContext : {
'another' : 'attribute' // this goes to the child partial
}
}
childContext
becomes the context of the partial like Yehuda said -- in that, it only sees the field another
, but it doesn't see (or care about the field some
). If you had id
in the top level model, and repeat id
again in the childContext, that'll work just fine as the partial only sees what's inside childContext
.
You need to tell scp
where to send the file. In your command that is not working:
scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~
You have not mentioned a remote server. scp
uses :
to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c
from the host C
to your local home directory.
The correct upload command, based on your comments, should be something like:
C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:
If you are running the command from your home directory, you can use a relative path:
C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:
You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:
C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/
Adding here my experience that hopefully might help somebody.
I was experiencing the same issue on Android emulator in Linux with hot reload. The code was correct as per accepted answer and the emulator could reach the internet (I needed a domain name).
Refreshing manually the app made it work. So maybe it has something to do with the hot reloading.
Here is how you can accomplish the same using python's general formatting function...
>>>from datetime import datetime
>>>"{:%B %d, %Y}".format(datetime.now())
The formatting characters used here are the same as those used by strftime. Don't miss the leading :
in the format specifier.
Using format() instead of strftime() in most cases can make the code more readable, easier to write and consistent with the way formatted output is generated...
>>>"{} today's date is: {:%B %d, %Y}".format("Andre", datetime.now())
Compare the above with the following strftime() alternative...
>>>"{} today's date is {}".format("Andre", datetime.now().strftime("%B %d, %Y"))
Moreover, the following is not going to work...
>>>datetime.now().strftime("%s %B %d, %Y" % "Andre")
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
datetime.now().strftime("%s %B %d, %Y" % "Andre")
TypeError: not enough arguments for format string
And so on...
STATICFILES_DIRS
is used in development and STATIC_ROOT
in production,
STATICFILES_DIRS
and STATIC_ROOT
should not have same folder name,
If you need to use the exact same static folder in development and production, try this method
include this in settings.py
import socket
HOSTNAME = socket.gethostname()
# if hostname same as production url name use STATIC_ROOT
if HOSTNAME == 'www.example.com':
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
else:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/'),
]
Create a mutex that the running thread and the calling thread both have access to. When the running thread starts it locks the mutex, and when it ends it unlocks the mutex. To check if the thread is still running, the calling thread calls mutex.try_lock(). The return value of that is the status of the thread. (Just make sure to unlock the mutex if the try_lock worked)
One small problem with this, mutex.try_lock() will return false between the time the thread is created, and when it locks the mutex, but this can be avoided using a slightly more complex method.
Swift 4.*
I have created a Xib for UICollectionViewCell which seems to be the good approach.
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return size(indexPath: indexPath)
}
private func size(for indexPath: IndexPath) -> CGSize {
// load cell from Xib
let cell = Bundle.main.loadNibNamed("ACollectionViewCell", owner: self, options: nil)?.first as! ACollectionViewCell
// configure cell with data in it
let data = self.data[indexPath.item]
cell.configure(withData: data)
cell.setNeedsLayout()
cell.layoutIfNeeded()
// width that you want
let width = collectionView.frame.width
let height: CGFloat = 0
let targetSize = CGSize(width: width, height: height)
// get size with width that you want and automatic height
let size = cell.contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .defaultHigh, verticalFittingPriority: .fittingSizeLevel)
// if you want height and width both to be dynamic use below
// let size = cell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
return size
}
}
#note: I don't recommend setting image when configuring data in this size determining case. It gave me the distorted/unwanted result. Configuring texts only gave me below result.
Python doesn't have a feature to access the function or its name within the function itself. It has been proposed but rejected. If you don't want to play with the stack yourself, you should either use "bar"
or bar.__name__
depending on context.
The given rejection notice is:
This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren't enough important use cases given. response has been lukewarm at best.
The best what and easiest way to get nice var_dump is use xDebug (must have for any php dev) Debian way install
In console: apt-get install php-xdebug
after that you should open php.ini (depends on which stack you use) for it's /etc/php/7.0/fpm/php.ini
Search for display_errors
set same -> display_errors = On
Check html_errors
in same file a little bit below, it's also must be On
Save and exit
After open /etc/php/7.0/fpm/conf.d/20-xdebug.ini
And add to the end: ``` xdebug.cli_color=1
``` Save and exit.
A lot other available option and documentation for xdebug can be founded here.
Good luck and Have Fun !!!
The best way to compare 2 objects is by converting them into json strings and compare the strings, its the easiest solution when dealing with complicated nested objects, fields and/or objects that contain arrays.
sample:
import com.google.gson.Gson;
Object a = // ...;
Object b = //...;
String objectString1 = new Gson().toJson(a);
String objectString2 = new Gson().toJson(b);
if(objectString1.equals(objectString2)){
//do this
}
We can try a simpler one as follows:
docker image inspect image_id
This worked in Docker version:
DockerVersion": "18.05.0-ce"
There are no performance implications since the compiler will translate your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language feature that the compiler translates into the exact same code that you are used to working with.
The compiler will convert the code you have to something like this:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//snip
MyButton.Click += new EventHandler(delegate (Object o, EventArgs a)
{
//snip
});
}
}
Maybe there are one or two people coming across this question who need a much stricter check than usual (like I did). In that case, this might be useful:
if(str === String(Number(str))) {
// it's a "perfectly formatted" number
}
Beware! This will reject strings like .1
, 40.000
, 080
, 00.1
. It's very picky - the string must match the "most minimal perfect form" of the number for this test to pass.
It uses the String
and Number
constructor to cast the string to a number and back again and thus checks if the JavaScript engine's "perfect minimal form" (the one it got converted to with the initial Number
constructor) matches the original string.
In my case this error occured when logging in SAP Business One 9.1 application. In Windows events I could find also another error event in addition to the one reported by the OP:
Nome dell'applicazione che ha generato l'errore: SAP Business One.exe, versione: 9.10.160.0, timestamp: 0x551ad316
Nome del modulo che ha generato l'errore: clr.dll, versione: 4.0.30319.34014, timestamp: 0x52e0b784
Codice eccezione: 0xc0000005
Offset errore 0x00029f55
ID processo che ha generato l'errore: 0x1d7c
Ora di avvio dell'applicazione che ha generato l'errore: 0x01d0e6f4fa626e78
Percorso dell'applicazione che ha generato l'errore: C:\Program Files (x86)\SAP\SAP Business One\SAP Business One.exe
Percorso del modulo che ha generato l'errore: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
ID segnalazione: 3fd8e0e7-52e8-11e5-827f-74d435a9d02c
Nome completo pacchetto che ha generato l'errore:
ID applicazione relativo al pacchetto che ha generato l'errore:
The machine run Windows 8.1, with .NET Framework 4.0 installed and without the 4.5 version. As it seemed from the internet that it could be also a bug in .NET 4, I tried installing .NET Framework 4.5.2 and I solved the issue.
Just in case it helps someone:
If the method GetDataThatLooksVerySimilarButNotTheSame()
returns an ExpandoObject
you can also cast to a IDictionary
before checking.
dynamic test = new System.Dynamic.ExpandoObject();
test.foo = "bar";
if (((IDictionary<string, object>)test).ContainsKey("foo"))
{
Console.WriteLine(test.foo);
}
Thanks to a comment by zerkms, I was able to notice my stupid mistake:
I had onItemClick(e, item)
when I should have had onItemClick(item, e)
.
use StickyTableHeaders.js for this.
Header was transparent . so try to add this css .
thead {
border-top: none;
border-bottom: none;
background-color: #FFF;
}
First off, when you call getElementById
, you need to provide an id. o_O
The only item in your dom with an id is the table
element. If you can, you could add ids (make sure they are unique) to your tr
elements.
Alternatively, you can use getElementsByTagName('tr')
to get a list of tr
elements in your document, and then get the number of tds.
You can have it embedded (build action set to Resource
) as well, this is how to retrieve it from there:
private static UnmanagedMemoryStream GetResourceStream(string resName)
{
var assembly = Assembly.GetExecutingAssembly();
var strResources = assembly.GetName().Name + ".g.resources";
var rStream = assembly.GetManifestResourceStream(strResources);
var resourceReader = new ResourceReader(rStream);
var items = resourceReader.OfType<DictionaryEntry>();
var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
return (UnmanagedMemoryStream)stream;
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
string resName = "Test.txt";
var file = GetResourceStream(resName);
using (var reader = new StreamReader(file))
{
var line = reader.ReadLine();
MessageBox.Show(line);
}
}
(Some code taken from this answer by Charles)
In SQLite you should do this:
SELECT *
FROM leftTable lt
LEFT JOIN rightTable rt ON lt.id = rt.lrid
UNION
SELECT lt.*, rl.* -- To match column set
FROM rightTable rt
LEFT JOIN leftTable lt ON lt.id = rt.lrid
Here is how I do it. This way I can actually get a function to simulate returning multiple values;
function foo($array)
{
foreach($array as $_key => $_value)
{
$str .= "{$_key}=".$_value.'&';
}
return $str = substr($str, 0, -1);
}
/* Set the variables to pass to function, in an Array */
$waffles['variable1'] = "value1";
$waffles['variable2'] = "value2";
$waffles['variable3'] = "value3";
/* Call Function */
parse_str( foo( $waffles ));
/* Function returns multiple variable/value pairs */
echo $variable1 ."<br>";
echo $variable2 ."<br>";
echo $variable3 ."<br>";
Especially usefull if you want, for example all fields in a database to be returned as variables, named the same as the database table fields. See 'db_fields( )' function below.
For example, if you have a query
select login, password, email from members_table
where id = $id
Function returns multiple variables:
$login, $password and $email
Here is the function:
function db_fields($field, $filter, $filter_by, $table = 'members_table') {
/*
This function will return as variable names, all fields that you request,
and the field values assigned to the variables as variable values.
$filter_by = TABLE FIELD TO FILTER RESULTS BY
$filter = VALUE TO FILTER BY
$table = TABLE TO RUN QUERY AGAINST
Returns single string value or ARRAY, based on whether user requests single
field or multiple fields.
We return all fields as variable names. If multiple rows
are returned, check is_array($return_field); If > 0, it contains multiple rows.
In that case, simply run parse_str($return_value) for each Array Item.
*/
$field = ($field == "*") ? "*,*" : $field;
$fields = explode(",",$field);
$assoc_array = ( count($fields) > 0 ) ? 1 : 0;
if (!$assoc_array) {
$result = mysql_fetch_assoc(mysql_query("select $field from $table where $filter_by = '$filter'"));
return ${$field} = $result[$field];
}
else
{
$query = mysql_query("select $field from $table where $filter_by = '$filter'");
while ($row = mysql_fetch_assoc($query)) {
foreach($row as $_key => $_value) {
$str .= "{$_key}=".$_value.'&';
}
return $str = substr($str, 0, -1);
}
}
}
Below is a sample call to function. So, If we need to get User Data for say $user_id = 12345, from the members table with fields ID, LOGIN, PASSWORD, EMAIL:
$filter = $user_id;
$filter_by = "ID";
$table_name = "members_table"
parse_str(db_fields('LOGIN, PASSWORD, EMAIL', $filter, $filter_by, $table_name));
/* This will return the following variables: */
echo $LOGIN ."<br>";
echo $PASSWORD ."<br>";
echo $EMAIL ."<br>";
We could also call like this:
parse_str(db_fields('*', $filter, $filter_by, $table_name));
The above call would return all fields as variable names.
If all you want to do is have a checkbox that checks, don't worry about doing it with JQuery. That is default functionality of a checkbox on click. However, if you want to do additional things, you can add them with JQuery. Prior to jQuery 1.9, you can use use $(this).attr('checked');
to get the value instead of $(this).attr('checked', true);
, as the second will set the value.
Here is a fiddle demonstration that shows the default checkbox functionality vs. what you are doing with JQuery.
Note: After JQuery 1.6, you should use $(this).prop;
instead of $(this).attr
in all three places (thanks @Whatevo for pointing this out and see here for further details).
UPDATE:
Sorry, missed the requirement that it had to be a radio button. You still may want to consider the checkbox, but here is the updated code for the radio input version. It works by setting the previousValue
as an attribute on the checkbox, as I don't think prop
is supported in 1.3.2. You could also do this in a scoped variable, as some people don't like setting random attributes on fields. Here is the new example.
UPDATE 2:
As Josh pointed out, the previous solution only worked with one radio button. Here's a function that makes a group of radios deselectable by their name, and a fiddle:
var makeRadiosDeselectableByName = function(name){
$('input[name=' + name + ']').click(function() {
if($(this).attr('previousValue') == 'true'){
$(this).attr('checked', false)
} else {
$('input[name=' + name + ']').attr('previousValue', false);
}
$(this).attr('previousValue', $(this).attr('checked'));
});
};
I faced the same error, in my case I miss-spelled ng-model directive something like "ng-moel"
Wrong one: ng-moel="user.name" Right one: ng-model="user.name"
>>> dt64.tolist()
datetime.datetime(2012, 5, 1, 0, 0)
For DatetimeIndex
, the tolist
returns a list of datetime
objects. For a single datetime64
object it returns a single datetime
object.
Creating new function on your object literal and invoking a constructor seems a radical departure from the original problem, and it's unnecessary.
You cannot reference a sibling property during object literal initialization.
var x = { a: 1, b: 2, c: a + b } // not defined
var y = { a: 1, b: 2, c: y.a + y.b } // not defined
The simplest solution for computed properties follows (no heap, no functions, no constructor):
var x = { a: 1, b: 2 };
x.c = x.a + x.b; // apply computed property
We can also use host machine environment variable using -e flag and $ :
docker run -it -e MG_HOST=$MG_HOST -e MG_USER=$MG_USER -e MG_PASS=$MG_PASS -e MG_AUTH=$MG_AUTH -e MG_DB=$MG_DB -t image_tag_name_and_version
By using this method, you can set the environment variable automatically with your given name. In my case(MG_HOST ,MG_USER)
If you are using python you can access these environment variable inside docker by
import os
host,username,password,auth,database=os.environ.get('MG_HOST'),os.environ.get('MG_USER'),os.environ.get('MG_PASS'),os.environ.get('MG_AUTH'),os.environ.get('MG_DB')
Some times this problem arise when Application is build in one PC and try to run another PC. And also build the application with Visual Studio 2010.I have the following problem
Problem Description
Stop Working
Problem Signature
Problem Event Name: CLR20r3
Problem Signature 01: diagnosticcentermngr.exe
Problem Signature 02: 1.0.0.0
Problem Signature 03: 4f8c1772
Problem Signature 04: System.Drawing
Problem Signature 05: 2.0.0.0
Problem Signature 06: 4a275e83
Problem Signature 07: 7af
Problem Signature 08: 6c
Problem Signature 09: System.ArgumentException
OS Version: 6.1.7600.2.0.0.256.1
Locale ID: 1033
Read our privacy statement online:
http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
If the online privacy statement is not available, please read our privacy statement offline:
C:\Windows\system32\en-US\erofflps.txt
Dont worry, Please check out following link and install .net framework 4.Although my application .net properties was .net framework 2.
http://www.microsoft.com/download/en/details.aspx?id=17718
restart your PC and try again.
install php70w-common.
It provides php-api, php-bz2, php-calendar, php-ctype, php-curl, php-date, php-exif, php-fileinfo, php-filter, php-ftp, php-gettext, php-gmp, php-hash, php-iconv, php-json, php-libxml, php-openssl, php-pcre, php-pecl-Fileinfo, php-pecl-phar, php-pecl-zip, php-reflection, php-session, php-shmop, php-simplexml, php-sockets, php-spl, php-tokenizer, php-zend-abi, php-zip, php-zlib.
Not entirely sure what you want here, but if you want to discount blank cells in the range and pass over zeros then this would do it; if a little contrived:
=MIN(IF(A1:E1=0,MAX(A1:E1),A1:E1))
With Ctrl+Shift+Enter as an array.
What I'm doing here is replacing zeros with the maximum value in the list.
static variables are specific to a class . Constructors initialize attributes ESPECIALY for an instance.
IsNullOrWhiteSpace
is a convenience method that is similar to the following code, except that it offers superior performance:return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
White-space characters are defined by the Unicode standard. The
IsNullOrWhiteSpace
method interprets any character that returns a value of true when it is passed to theChar.IsWhiteSpace
method as a white-space character.
After having read a couple of chapters in the iOS 6 Programming Cookbok and started to learn objective-c and iOS programming, I would just like to add, that if one is going to load resources from a custom bundle and use that in a web view, it can be accomplished like this:
NSString *resourcesBundlePath = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"];
NSBundle *resourcesBundle = [NSBundle bundleWithPath:resourcesBundlePath];
[self.outletWebView loadHTMLString:[html description] baseURL:[resourcesBundle bundleURL]];
Then, in your html you can refer to a resource using the "custom" bundle as your base path:
body {
background-image:url('img/myBg.png');
}
TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.
If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.
As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT
header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/chainedcert.pem; # server certificate
ssl_certificate_key /path/to/key; # server key
ssl_client_certificate /path/to/ca.pem; # client CA
ssl_verify_client on;
proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;
location / {
proxy_pass http://localhost:3000;
}
}
In the manifest file change to this:
android:theme="@style/Theme.AppCompat.Light.NoActionBar" >
I found solution here: https://code.visualstudio.com/docs/customization/colorizer
Go to VS_CODE_FOLDER/resources/app/extensions/
and there update package.json
When you specify position:absolute it positions itself to the next-highest element with position:relative. In this case, that's the .project div.
If you give the image's immediate parent div a style of position:relative, the overlay will key to that instead of the div which includes the text. For example: http://jsfiddle.net/7gYUU/1/
<div class="parent">
<img src="http://placehold.it/500x500" class="img-responsive"/>
<div class="fa fa-plus project-overlay"></div>
</div>
.parent {
position: relative;
}
You can add it programmatically or in the markup, but if you add it programmatically, rather than Add
the item, you should Insert
it as position zero so that it is the first item:
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");
The default item is expected to be the first item in the list. If you just Add
it, it will be on the bottom and will not be selected by default.
You can use the wordwrap()
function then explode on newline and take the first part, if you don't want to split words.
$str = 'Stack Overflow is as frictionless and painless to use as we could make it.';
$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
Source: https://stackoverflow.com/a/1104329/1060423
If you don't care about splitting words, then simply use the php substr function.
echo substr($str, 0, 28) . '...';
In order:
inline
import functools
#: not key(c) in d
d = {"a": "avalue", "b": "bvalue", "d": "dvalue"}
entitiesToREmove = ('a', 'b', 'c')
#: python2
map(lambda x: functools.partial(d.pop, x, None)(), entitiesToREmove)
#: python3
list(map(lambda x: functools.partial(d.pop, x, None)(), entitiesToREmove))
print(d)
# output: {'d': 'dvalue'}
Just use \" instead ", it should resolve the issue.
Azure Data Studio - free and from Microsoft - offers automatic formatting (ctrl + shift + p while editing -> format document). More information about Azure Data Studio here.
While this is not SSMS, it's great for writing queries, free and an official product from Microsoft. It's even cross-platform. Short story: Just switch to Azure Data Studio to write your queries!
Update: Actually Azure Data Studio is in some way the recommended tool for writing queries (source)
Use Azure Data Studio if you: [..] Are mostly editing or executing queries.
The [DisplayFormat] attribute is only used in EditorFor/DisplayFor, and not by the raw HTML APIs like TextBoxFor. I got it working by doing the following,
Model:
[Display(Name = "When was that document issued ?")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime? LiquorLicenceDocumentIssueDate { get; set; }
View:
<div id="IsLiquorLicenceDocumentOnPremisesYes" class="groupLongLabel">
@Html.LabelFor(m => m.LiquorLicenceDocumentIssueDate)
<span class="indicator"></span>
@Html.EditorFor(m => m.LiquorLicenceDocumentIssueDate)
<span id="validEmail"></span>
<br />
@Html.ValidationMessageFor(m => m.LiquorLicenceDocumentIssueDate)
</div>
Output: 30/12/2011
Related link:
I came by this question with exactly the same issue as the asker. The answers here are very informing, and I tried out almost every single one of the suggested answers. None of the answers here worked for me though - there might have been a slight difference in my problem. And that seems to be the case for many. I tried so much before ending up with an answer.
So now I'm adding to the already long list of answers, a solution of my own that solved my kind of encoding problem.
I did just two things. In the database connection script I added:
mysql_set_charset('utf8',$connection);
and apart from that:
The point is that everything must be of the same encoding. And when creating new php-files, for the scripts it is not enough just to change the encoding in the script - the file itself must be correctly encoded.
If you have any field with required attribute which is not visible during the form submission, this error will be thrown. You just remove the required attribute when your try to hide that field. You can add the required attribute in case if you want to show the field again. By this way, your validation will not be compromised and at the same time, the error will not be thrown.
Try using the server IP address rather than the hostname. This worked for me. Hope it will work for you too.
[ ]
defines a character class. So every character you set there, will match. [012]
will match 0
or 1
or 2
and [0-2]
behaves the same.
What you want is groupings to define a or-statement. Use (s|season)
for your issue.
Btw. you have to watch out. Metacharacters in normal regex (or inside a grouping) are different from character class. A character class is like a sub-language. [$A]
will only match $
or A
, nothing else. No escaping here for the dollar.
#ALL THESE REQUIRE THE WHOLE STRING TO BE A NUMBER
#For numbers embedded in sentences, see discussion below
#### NUMBERS AND DECIMALS ONLY ####
#No commas allowed
#Pass: (1000.0), (001), (.001)
#Fail: (1,000.0)
^\d*\.?\d+$
#No commas allowed
#Can't start with "."
#Pass: (0.01)
#Fail: (.01)
^(\d+\.)?\d+$
#### CURRENCY ####
#No commas allowed
#"$" optional
#Can't start with "."
#Either 0 or 2 decimal digits
#Pass: ($1000), (1.00), ($0.11)
#Fail: ($1.0), (1.), ($1.000), ($.11)
^\$?\d+(\.\d{2})?$
#### COMMA-GROUPED ####
#Commas required between powers of 1,000
#Can't start with "."
#Pass: (1,000,000), (0.001)
#Fail: (1000000), (1,00,00,00), (.001)
^\d{1,3}(,\d{3})*(\.\d+)?$
#Commas required
#Cannot be empty
#Pass: (1,000.100), (.001)
#Fail: (1000), ()
^(?=.)(\d{1,3}(,\d{3})*)?(\.\d+)?$
#Commas optional as long as they're consistent
#Can't start with "."
#Pass: (1,000,000), (1000000)
#Fail: (10000,000), (1,00,00)
^(\d+|\d{1,3}(,\d{3})*)(\.\d+)?$
#### LEADING AND TRAILING ZEROES ####
#No commas allowed
#Can't start with "."
#No leading zeroes in integer part
#Pass: (1.00), (0.00)
#Fail: (001)
^([1-9]\d*|0)(\.\d+)?$
#No commas allowed
#Can't start with "."
#No trailing zeroes in decimal part
#Pass: (1), (0.1)
#Fail: (1.00), (0.1000)
^\d+(\.\d*[1-9])?$
Now that that's out of the way, most of the following is meant as commentary on how complex regex can get if you try to be clever with it, and why you should seek alternatives. Read at your own risk.
This is a very common task, but all the answers I see here so far will accept inputs that don't match your number format, such as ,111
, 9,9,9
, or even .,,.
. That's simple enough to fix, even if the numbers are embedded in other text. IMHO anything that fails to pull 1,234.56 and 1234—and only those numbers—out of abc22 1,234.56 9.9.9.9 def 1234
is a wrong answer.
First of all, if you don't need to do this all in one regex, don't. A single regex for two different number formats is hard to maintain even when they aren't embedded in other text. What you should really do is split the whole thing on whitespace, then run two or three smaller regexes on the results. If that's not an option for you, keep reading.
Considering the examples you've given, here's a simple regex that allows pretty much any integer or decimal in 0000
format and blocks everything else:
^\d*\.?\d+$
Here's one that requires 0,000
format:
^\d{1,3}(,\d{3})*(\.\d+)?$
Put them together, and commas become optional as long as they're consistent:
^(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)$
The patterns above require the entire input to be a number. You're looking for numbers embedded in text, so you have to loosen that part. On the other hand, you don't want it to see catch22
and think it's found the number 22. If you're using something with lookbehind support (like .NET), this is pretty easy: replace ^
with (?<!\S)
and $
with (?!\S)
and you're good to go:
(?<!\S)(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)(?!\S)
If you're working with JavaScript or Ruby or something, things start looking more complex:
(?:^|\s)(\d*\.?\d+|\d{1,3}(?:,\d{3})*(?:\.\d+)?)(?!\S)
You'll have to use capture groups; I can't think of an alternative without lookbehind support. The numbers you want will be in Group 1 (assuming the whole match is Group 0).
I think that covers your question, so if that's all you need, stop reading now. If you want to get fancier, things turn very complex very quickly. Depending on your situation, you may want to block any or all of the following:
Just for the hell of it, let's assume you want to block the first 3, but allow the last one. What should you do? I'll tell you what you should do, you should use a different regex for each rule and progressively narrow down your matches. But for the sake of the challenge, here's how you do it all in one giant pattern:
(?<!\S)(?=.)(0|([1-9](\d*|\d{0,2}(,\d{3})*)))?(\.\d*[1-9])?(?!\S)
And here's what it means:
(?<!\S) to (?!\S) #The whole match must be surrounded by either whitespace or line boundaries. So if you see something bogus like :;:9.:, ignore the 9.
(?=.) #The whole thing can't be blank.
( #Rules for the integer part:
0 #1. The integer part could just be 0...
| #
[1-9] # ...otherwise, it can't have leading zeroes.
( #
\d* #2. It could use no commas at all...
| #
\d{0,2}(,\d{3})* # ...or it could be comma-separated groups of 3 digits each.
) #
)? #3. Or there could be no integer part at all.
( #Rules for the decimal part:
\. #1. It must start with a decimal point...
\d* #2. ...followed by a string of numeric digits only.
[1-9] #3. It can't be just the decimal point, and it can't end in 0.
)? #4. The whole decimal part is also optional. Remember, we checked at the beginning to make sure the whole thing wasn't blank.
Tested here: http://rextester.com/YPG96786
This will allow things like:
100,000
999.999
90.0009
1,000,023.999
0.111
.111
0
It will block things like:
1,1,1.111
000,001.111
999.
0.
111.110000
1.1.1.111
9.909,888
There are several ways to make this regex simpler and shorter, but understand that changing the pattern will loosen what it considers a number.
Since many regex engines (e.g. JavaScript and Ruby) don't support the negative lookbehind, the only way to do this correctly is with capture groups:
(:?^|\s)(?=.)((?:0|(?:[1-9](?:\d*|\d{0,2}(?:,\d{3})*)))?(?:\.\d*[1-9])?)(?!\S)
The numbers you're looking for will be in capture group 1.
Tested here: http://rubular.com/r/3HCSkndzhT
Obviously, this is a massive, complicated, nigh-unreadable regex. I enjoyed the challenge, but you should consider whether you really want to use this in a production environment. Instead of trying to do everything in one step, you could do it in two: a regex to catch anything that might be a number, then another one to weed out whatever isn't a number. Or you could do some basic processing, then use your language's built-in number parsing functions. Your choice.
If you want to do rsync and use custom user and custom ssh key, you need to write this key in rsync options.
---
- name: rsync
hosts: serverA,serverB,serverC,serverD,serverE,serverF
gather_facts: no
vars:
ansible_user: oracle
ansible_ssh_private_key_file: ./mykey
src_file: "/path/to/file.txt"
tasks:
- name: Copy Remote-To-Remote from serverA to server{B..F}
synchronize:
src: "{{ src_file }}"
dest: "{{ src_file }}"
rsync_opts:
- "-e ssh -i /remote/path/to/mykey"
delegate_to: serverA
Also just another nice function i like to use when i want to compute i.e. first/last day of the last month or other relative timedeltas etc. ...
The relativedelta function from dateutil function (a powerful extension to the datetime lib)
import datetime as dt
from dateutil.relativedelta import relativedelta
#get first and last day of this and last month)
today = dt.date.today()
first_day_this_month = dt.date(day=1, month=today.month, year=today.year)
last_day_last_month = first_day_this_month - relativedelta(days=1)
print (first_day_this_month, last_day_last_month)
>2015-03-01 2015-02-28
What about: b - delta < a && a < b + delta
What do you mean by ‘hang state’? Typically, a process that is unresponsive and using 100% of a CPU is stuck in an endless loop. But there's no way to determine whether that has happened or whether the process might not eventually reach a loop exit state and carry on.
Desktop hang detectors just work by sending a message to the application's event loop and seeing if there's any response. If there's not for a certain amount of time they decide the app has ‘hung’... but it's entirely possible it was just doing something complicated and will come back to life in a moment once it's done. Anyhow, that's not something you can use for any arbitrary process.
Spring has built-in support for this with an AbstractRequestLoggingFilter
:
@Bean
public Filter loggingFilter(){
final AbstractRequestLoggingFilter filter = new AbstractRequestLoggingFilter() {
@Override
protected void beforeRequest(final HttpServletRequest request, final String message) {
}
@Override
protected void afterRequest(final HttpServletRequest request, final String message) {
}
};
filter.setIncludePayload(true);
filter.setIncludeQueryString(false);
filter.setMaxPayloadLength(1000000);
return filter;
}
Unfortunately you still won't be able to read the payload directly off the request, but the String message parameter will include the payload so you can grab it from there as follows:
String body = message.substring(message.indexOf("{"), message.lastIndexOf("]"));
None of the above worked for me (tomcat 7.0.62)... As Sensei_Shoh notes see the class above the message and add this to logging.properties. My logs were:
Jan 18, 2016 8:44:21 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
so I added
org.apache.catalina.startup.TldConfig.level = FINE
in conf/logging.properties
After that I got so many "offending" files that I did not bother skipping them (and also reverted to normal logging...)
Looking at your output maybe the following query can work, give it a try:
SELECT * FROM tablename
WHERE id IN
(SELECT MIN(id) FROM tablename GROUP BY EmailAddress)
This will select only one row for each distinct email address, the row with the minimum id
which is what your result seems to portray
The %2C
translates to a comma (,
). I saw this while searching for a sentence with a comma in it and on the url, instead of showing a comma, it had %2C
.
As of woocommerce 3.0
$order->id;
will not work, it will generate notice, use getter function:
$order->get_id();
The same applies for other woocommerce objects like procut.
Most likely your sushosin updated, which changed the default of suhosin.memory_limit from disabled to 0 (which won't allow any updates to memory_limit).
On Debian, change /etc/php5/conf.d/suhosin.ini
;suhosin.memory_limit = 0
to
suhosin.memory_limit = 2G
Or whichever value you are comfortable with. You can find the changelog of Sushosin at http://www.hardened-php.net/hphp/changelog.html, which says:
Changed the way the memory_limit protection is implemented
Because JavaScript is such a small language, yet with incredible complexity, you should be able to ask relatively basic questions and find out if they are really that good based on their answers. For instance, my standard first question to gauge the rest of the interview is:
In JavaScript, what is the difference between
var x = 1
andx = 1
? Answer in as much or as little detail as you feel comfortable.
Novice JS programmers might have a basic answer about locals vs globals. Intermediate JS guys should definitely have that answer, and should probably mention function-level scope. Anyone calling themselves an "advanced" JS programmer should be prepared to talk about locals, implied globals, the window
object, function-scope, declaration hoisting, and scope chains. Furthermore, I'd love to hear about [[DontDelete]]
, hoisting precedence (parameters vs var
vs function
), and undefined
.
Another good question is to ask them to write a sum()
function that accepts any number of arguments, and returns their sum. Then, ask them to use that function (without modification) to sum all the values in an array. They should write a function that looks like this:
function sum() {
var i, l, result = 0;
for (i = 0, l = arguments.length; i < l; i++) {
result += arguments[i];
}
return result;
}
sum(1,2,3); // 6
And they should invoke it on your array like this (context for apply
can be whatever, I usually use null
in that case):
var data = [1,2,3];
sum.apply(null, data); // 6
If they've got those answers, they probably know their JavaScript. You should then proceed to asking them about non-JS specific stuff like testing, workflows, version control, etc. to find out if they're a good programmer.
in /usr/bin
type
sudo ln -s -f g++-4.2 g++
sudo ln -s -f gcc-4.2 gcc
That should do it.
You do not need any external command at all, just use Parameter Expansion in bash:
hostname=aaa0.bbb.ccc
echo ${hostname%%.*}
I believe I have a valid use case for using typeid(), the same way it is valid to use sizeof(). For a template function, I need to special case the code based on the template variable, so that I offer maximum functionality and flexibility.
It is much more compact and maintainable than using polymorphism, to create one instance of the function for each type supported. Even in that case I might use this trick to write the body of the function only once:
Note that because the code uses templates, the switch statement below should resolve statically into only one code block, optimizing away all the false cases, AFAIK.
Consider this example, where we may need to handle a conversion if T is one type vs another. I use it for class specialization to access hardware where the hardware will use either myClassA or myClassB type. On a mismatch, I need to spend time converting the data.
switch ((typeid(T)) {
case typeid(myClassA):
// handle that case
break;
case typeid(myClassB):
// handle that case
break;
case typeid(uint32_t):
// handle that case
break;
default:
// handle that case
}
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
Do this:
<video style="display:block; margin: 0 auto;" controls>....</video>
Works perfect! :D
As constraint has unpredictable name, you can write special script(DropConstraint) to remove it without knowing it's name (was tested at EF 6.1.3):
public override void Up()
{
DropConstraint();
AlterColumn("dbo.MyTable", "Rating", c => c.Double(nullable: false));
}
private void DropConstraint()
{
Sql(@"DECLARE @var0 nvarchar(128)
SELECT @var0 = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'dbo.MyTable')
AND col_name(parent_object_id, parent_column_id) = 'Rating';
IF @var0 IS NOT NULL
EXECUTE('ALTER TABLE [dbo].[MyTable] DROP CONSTRAINT [' + @var0 + ']')");
}
public override void Down()
{
AlterColumn("dbo.MyTable", "Rating", c => c.Int(nullable: false));
}
Since this post might be here for a while, lets also point out python 3 syntax:
"{:.2f}".format(5)
There are multiple hit & trial solutions for this error. One of them will surely work for you. Below are the solutions:
1.
Tools -> Android -> Sync Project with Gradle Files (Android Studio 3.0.1)
2.
Go to build.gradle and click sync now
3.
Click this icon to sync gradle enter image description here
or edit any of your module gradle and then sync
4.
File -> Settings -> Android SDK -> Android SDK Location Edit -> Android SDK
5.
Open build.gradle file, just add a space or press enter. Then sync project.
6.
File -> Invalidate Caches / Restart
What about comfortably viewing (and also editing) the content over ODBC & MS-Access, Excel? Softwareversions::
H2 Server:
/*
For JDBC Clients to connect:
jdbc:h2:tcp://localhost:9092/trader;CIPHER=AES;IFEXISTS=TRUE;MVCC=true;LOCK_TIMEOUT=60000;CACHE_SIZE=131072;CACHE_TYPE=TQ
*/
public class DBStarter {
public static final String BASEDIR = "/C:/Trader/db/";
public static final String DB_URL = BASEDIR + "trader;CIPHER=AES;IFEXISTS=TRUE;MVCC=true;LOCK_TIMEOUT=10000;CACHE_SIZE=131072;CACHE_TYPE=TQ";
static void startServer() throws SQLException {
Server tcpServer = Server.createTcpServer(
"-tcpPort", "9092",
"-tcpAllowOthers",
"-ifExists",
// "-trace",
"-baseDir", BASEDIR
);
tcpServer.start();
System.out.println("H2 JDBC Server started: " + tcpServer.getStatus());
Server pgServer = Server.createPgServer(
"-pgPort", "10022",
"-pgAllowOthers",
"-key", "traderdb", DB_URL
);
pgServer.start();
System.out.println("H2 ODBC PGServer started: " + pgServer.getStatus());
}
}
Windows10 ODBC Datasource Configuration which can be used by any ODBC client: In Databse field the name given in '-key' parameter has to be used.
First, grant full control permissions to a local path on your machine (as shown below) with Everyone. (Or alternatively grant permissions specifically to the SQL Server Agent account).
Second, execute the following:
BACKUP DATABASE [dev] TO DISK = N'\\myMachine\c\dev.bak' WITH COPY_ONLY, INIT;
As Internet Explorer doesn't natively support rounded corners. So a better cross-browser way to handle it would be to use rounded-corner images at the corners. Many famous websites use this approach.
You can also find rounded image generators around the web. One such link is http://www.generateit.net/rounded-corner/
Actually in Eclipse Indigo thru Oxygen, you have to go to the Types template Window -> Preferences -> Java -> Code Style -> Code templates -> (in right-hand pane) Comments -> double-click Types
and make sure it has the following, which it should have by default:
/**
* @author ${user}
*
* ${tags}
*/
and as far as I can tell, there is nothing in Eclipse to add the javadoc automatically to existing files in one batch. You could easily do it from the command line with sed
& awk
but that's another question.
If you are prepared to open each file individually, then selected the class / interface declaration line, e.g. public class AdamsClass { and then hit the key combo Shift + Alt + J and that will insert a new javadoc comment above, along with the author tag for your user. To experiment with other settings, go to Windows->Preferences->Java->Editor->Templates
.
Ok, for this first of all you need to use Device Policy Manager, and need to make your device Admin device. After that you have to create one BroadCast receiver and one service. I am posting code here and its working fine.
MainActivity:
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 0;
private DevicePolicyManager mDPM;
private ComponentName mAdminName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Initiate DevicePolicyManager.
mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
mAdminName = new ComponentName(this, DeviceAdminDemo.class);
if (!mDPM.isAdminActive(mAdminName)) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Click on Activate button to secure your application.");
startActivityForResult(intent, REQUEST_CODE);
} else {
// mDPM.lockNow();
// Intent intent = new Intent(MainActivity.this,
// TrackDeviceService.class);
// startService(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_CODE == requestCode) {
Intent intent = new Intent(MainActivity.this, TService.class);
startService(intent);
}
}
}
//DeviceAdminDemo class
public class DeviceAdminDemo extends DeviceAdminReceiver {
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
public void onEnabled(Context context, Intent intent) {
};
public void onDisabled(Context context, Intent intent) {
};
}
//TService Class
public class TService extends Service {
MediaRecorder recorder;
File audiofile;
String name, phonenumber;
String audio_format;
public String Audio_Type;
int audioSource;
Context context;
private Handler handler;
Timer timer;
Boolean offHook = false, ringing = false;
Toast toast;
Boolean isOffHook = false;
private boolean recordstarted = false;
private static final String ACTION_IN = "android.intent.action.PHONE_STATE";
private static final String ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL";
private CallBr br_call;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
Log.d("service", "destroy");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// final String terminate =(String)
// intent.getExtras().get("terminate");//
// intent.getStringExtra("terminate");
// Log.d("TAG", "service started");
//
// TelephonyManager telephony = (TelephonyManager)
// getSystemService(Context.TELEPHONY_SERVICE); // TelephonyManager
// // object
// CustomPhoneStateListener customPhoneListener = new
// CustomPhoneStateListener();
// telephony.listen(customPhoneListener,
// PhoneStateListener.LISTEN_CALL_STATE);
// context = getApplicationContext();
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUT);
filter.addAction(ACTION_IN);
this.br_call = new CallBr();
this.registerReceiver(this.br_call, filter);
// if(terminate != null) {
// stopSelf();
// }
return START_NOT_STICKY;
}
public class CallBr extends BroadcastReceiver {
Bundle bundle;
String state;
String inCall, outCall;
public boolean wasRinging = false;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
wasRinging = true;
Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (wasRinging == true) {
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
recorder = new MediaRecorder();
// recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
recordstarted = true;
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
if (recordstarted) {
recorder.stop();
recordstarted = false;
}
}
}
} else if (intent.getAction().equals(ACTION_OUT)) {
if ((bundle = intent.getExtras()) != null) {
outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
}
//Permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.STORAGE" />
//my_admin.xml
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>
//Declare following thing in manifest:
Declare DeviceAdminDemo class to manifest:
<receiver
android:name="com.example.voicerecorder1.DeviceAdminDemo"
android:description="@string/device_description"
android:label="@string/device_admin_label"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/my_admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
</intent-filter>
</receiver>
<service android:name=".TService" >
</service>
That should work if the dates you saved in the DB are without time (just year, month, day).
Chances are that the dates you saved were new Date()
, which includes the time components. To query those times you need to create a date range that includes all moments in a day.
db.posts.find({ //query today up to tonight
created_on: {
$gte: new Date(2012, 7, 14),
$lt: new Date(2012, 7, 15)
}
})
request.remote_ip
is an interpretation of all the available IP address information and it will make a best-guess. If you access the variables directly you assume responsibility for testing them in the correct precedence order. Proxies introduce a number of headers that create environment variables with different names.
Best Option I could find is Git Windows Just install it and then right click on and click "Git Bash Here" this will open a bash window
This will open a bash window like this:
and the linux commands work...
I've tried 'sh' , 'vi' , 'ssh' , 'curl' ,etc... commands
Just change +
to -
:
str = str.replace(/[^a-z0-9-]/g, "");
You can read it as:
[^ ]
: match NOT from the set[^a-z0-9-]
: match if not a-z
, 0-9
or -
/ /g
: do global matchMore information:
Install the favicon middleware and then do:
var favicon = require('serve-favicon');
app.use(favicon(__dirname + '/public/images/favicon.ico'));
Or better, using the path
module:
app.use(favicon(path.join(__dirname,'public','images','favicon.ico')));
(note that this solution will work in express 3 apps as well)
According to the API, .favicon
accepts a location parameter:
app.use(express.favicon("public/images/favicon.ico"));
Most of the time, you might want this (as vsync suggested):
app.use(express.favicon(__dirname + '/public/images/favicon.ico'));
Or better yet, use the path
module (as Druska suggested):
app.use(express.favicon(path.join(__dirname, 'public','images','favicon.ico')));
According to the package description:
ETag
based on the contents of the icon, rather than file system properties.Content-Type
.Well, you essentially create a JDialog, add your text components and make it visible. It might help if you narrow down which specific bit you're having trouble with.
you need to type it in cmd not in the IDLE. becuse IDLE is not an command prompt if you want to install something from IDLE type this
>>>from pip.__main__ import _main as main
>>>main(#args splitted by space in list example:['install', 'requests'])
this is calling pip like pip <commands>
in terminal. The commands will be seperated by spaces that you are doing there to.
Add following rule to tr and it should work
float: left
Sample (Open it in IE9 offcourse :) ): http://jsfiddle.net/zshmN/
EDIT: This isn't a legal or correct solution as pointed out by many, but if you are left with no option and need something this will work in IE9.
So all those who are giving down votes, please let us know correct solution as well
This is not possible from HTML on. The closest what you can get is the accept-charset
attribute of the <form>
. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type
header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.
To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding
attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).
Update:
Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type
header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.
As of now you still can't animate rotations with jQuery, but you can with CSS3 animations, then simply add and remove the class with jQuery to make the animation occur.
HTML
<img src="http://puu.sh/csDxF/2246d616d8.png" width="30" height="30"/>
CSS3
img {
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
transition-duration:0.4s;
}
.rotate {
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
transition-duration:0.4s;
}
jQuery
$(document).ready(function() {
$("img").mouseenter(function() {
$(this).addClass("rotate");
});
$("img").mouseleave(function() {
$(this).removeClass("rotate");
});
});
using System.Configuration;
/// <summary>
/// For read one setting
/// </summary>
/// <param name="key">Key correspondent a your setting</param>
/// <returns>Return the String contains the value to setting</returns>
public string ReadSetting(string key)
{
var appSettings = ConfigurationManager.AppSettings;
return appSettings[key] ?? string.Empty;
}
/// <summary>
/// Read all settings for output Dictionary<string,string>
/// </summary>
/// <returns>Return the Dictionary<string,string> contains all settings</returns>
public Dictionary<string, string> ReadAllSettings()
{
var result = new Dictionary<string, string>();
foreach (var key in ConfigurationManager.AppSettings.AllKeys)
result.Add(key, ConfigurationManager.AppSettings[key]);
return result;
}
The split() method is used to split a string into an array of substrings, and returns the new array.
var array = string.split(',');
FOR /r %%X IN (*) DO (ECHO %%X & DEL %%X)
I had the same problem on Windows XP just recently. I tried to chmod 700 on my ~/.ssh/id_rsa file but it did not seem to work. When I had a look at the permissions using ls -l on the ~/.ssh/id_rsa I could see that my effective permissions still was 644.
Then I remembered that windows permissions also inherit permissions from the folders, and the folder was still open to everyone. A solution could be to set permissions for the folder as well, but I think a better way would be to tell the system to ignore inheritance for this file. This can be done using the advanced option on the security tab in the properties of the file, and unchecking "inherit from parent permissions..."
This might be helpful for others with the same problem.
If you are having this problem with a homebrew installation of maven 3 on the OSX 10.9.4 then check out this blog post.
When you create a stored routine that has a BEGIN...END
block, statements within the block are terminated by semicolon (;)
. But the CREATE PROCEDURE
statement also needs a terminator. So it becomes ambiguous whether the semicolon within the body of the routine terminates CREATE PROCEDURE
, or terminates one of the statements within the body of the procedure.
The way to resolve the ambiguity is to declare a distinct string (which must not occur within the body of the procedure) that the MySQL client recognizes as the true terminator for the CREATE PROCEDURE
statement.
Make sure that you release all objects related to Excel!
I spent a few hours by trying several ways. All are great ideas but I finally found my mistake: If you don't release all objects, none of the ways above can help you like in my case. Make sure you release all objects including range one!
Excel.Range rng = (Excel.Range)worksheet.Cells[1, 1];
worksheet.Paste(rng, false);
releaseObject(rng);
The options are together here.
SELECT * FROM your_table ORDER BY id ASC LIMIT 0, 1
The ASC
will return resultset in ascending order thereby leaving you with the latest or most recent record. The DESC
counterpart will do the exact opposite. That is, return the oldest record.
As per keras tutorial, you can simply use the same tf.device
scope as in regular tensorflow:
with tf.device('/gpu:0'):
x = tf.placeholder(tf.float32, shape=(None, 20, 64))
y = LSTM(32)(x) # all ops in the LSTM layer will live on GPU:0
with tf.device('/cpu:0'):
x = tf.placeholder(tf.float32, shape=(None, 20, 64))
y = LSTM(32)(x) # all ops in the LSTM layer will live on CPU:0
Another way to suppress the error: Add this line at the top in C/C++ file:
#define _CRT_SECURE_NO_WARNINGS
Also in your storyboard, without single line of code
So the above answers are cute but they all have (imo) a big flaw: they are calculating the height of the image, based on the width of the user's device.
To have a truly responsive (i.e. width: 100%, height: auto
) implementation, what you really want to be doing, is calculating the height of the image, based on the width of the parent container.
Luckily for us, React Native provides us with a way to get the parent container width, thanks to the onLayout View method.
So all we need to do is create a View with width: "100%"
, then use onLayout
to get the width of that view (i.e. the container width), then use that container width to calculate the height of our image appropriately.
The below solution could be improved upon further, by using RN's Image.getSize, to grab the image dimensions within the ResponsiveImage component itself.
JavaScript:
// ResponsiveImage.ts
import React, { useMemo, useState } from "react";
import { Image, StyleSheet, View } from "react-native";
const ResponsiveImage = props => {
const [containerWidth, setContainerWidth] = useState(0);
const _onViewLayoutChange = event => {
const { width } = event.nativeEvent.layout;
setContainerWidth(width);
}
const imageStyles = useMemo(() => {
const ratio = containerWidth / props.srcWidth;
return {
width: containerWidth,
height: props.srcHeight * ratio
};
}, [containerWidth]);
return (
<View style={styles.container} onLayout={_onViewLayoutChange}>
<Image source={props.src} style={imageStyles} />
</View>
);
};
const styles = StyleSheet.create({
container: { width: "100%" }
});
export default ResponsiveImage;
// Example usage...
import ResponsiveImage from "../components/ResponsiveImage";
...
<ResponsiveImage
src={require("./images/your-image.jpg")}
srcWidth={910} // replace with your image width
srcHeight={628} // replace with your image height
/>
TypeScript:
// ResponsiveImage.ts
import React, { useMemo, useState } from "react";
import {
Image,
ImageSourcePropType,
LayoutChangeEvent,
StyleSheet,
View
} from "react-native";
interface ResponsiveImageProps {
src: ImageSourcePropType;
srcWidth: number;
srcHeight: number;
}
const ResponsiveImage: React.FC<ResponsiveImageProps> = props => {
const [containerWidth, setContainerWidth] = useState<number>(0);
const _onViewLayoutChange = (event: LayoutChangeEvent) => {
const { width } = event.nativeEvent.layout;
setContainerWidth(width);
}
const imageStyles = useMemo(() => {
const ratio = containerWidth / props.srcWidth;
return {
width: containerWidth,
height: props.srcHeight * ratio
};
}, [containerWidth]);
return (
<View style={styles.container} onLayout={_onViewLayoutChange}>
<Image source={props.src} style={imageStyles} />
</View>
);
};
const styles = StyleSheet.create({
container: { width: "100%" }
});
export default ResponsiveImage;
// Example usage...
import ResponsiveImage from "../components/ResponsiveImage";
...
<ResponsiveImage
src={require("./images/your-image.jpg")}
srcWidth={910} // replace with your image width
srcHeight={628} // replace with your image height
/>
TelephonyManager
is not the right solution, because in some cases the number is not stored in the SIM. I suggest that you should use the shared preference to store the user's phone number for the first time the application is open and the number will used whenever you need.
You can directly use String.valueOf()
String.valueOf(charSequence)
Though this is same as toString()
it does a null check on the charSequence
before actually calling toString.
This is useful when a method can return either a charSequence
or null
value.
Ciro's solution about an SVG Data URI background containing the text is very clever.
However, it won't work in IE if you just add the plain SVG source to the data URI.
In order to get around this and make it work in IE9 and up, encode the SVG to base64. This is a great tool.
So this:
background:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><text x="5%" y="5%" font-size="30" fill="red">I love SVG!</text></svg>');
Becomes this:
background:url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0ZXh0IHg9IjUlIiB5PSI1JSIgZm9udC1zaXplPSIzMCIgZmlsbD0icmVkIj5JIGxvdmUgU1ZHITwvdGV4dD48L3N2Zz4=');
Tested and it works in IE9-10-11, WebKit (Chrome 37, Opera 23) and Gecko (Firefox 31).
The size of a Java array is fixed when you allocate it, and cannot be changed.
If you want to "grow" or "shrink" an existing array, you have to allocate a new array of the appropriate size and copy the array elements; e.g. using System.arraycopy(...)
or Arrays.copyOf(...)
. A copy loop works as well, though it looks a bit clunky ... IMO.
If you want to "delete" an item or items from an array (in the true sense ... not just replacing them with null
), you need to allocate a new smaller array and copy across the elements you want to retain.
Finally, you can "erase" an element in an array of a reference type by assigning null
to it. But this introduces new problems:
null
elements to mean something, you can't do this.null
element in the appropriate fashion. More complexity and potential for bugs1.There are alternatives in the form of 3rd-party libraries (e.g. Apache Commons ArrayUtils
), but you may want to consider whether it is worth adding a library dependency just for the sake of a method that you could implement yourself with 5-10 lines of code.
It is better (i.e. simpler ... and in many cases, more efficient2) to use a List
class instead of an array. This will take care of (at least) growing the backing storage. And there are operations that take care of inserting and deleting elements anywhere in the list.
For instance, the ArrayList
class uses an array as backing, and automatically grows the array as required. It does not automatically reduce the size of the backing array, but you can tell it to do this using the trimToSize()
method; e.g.
ArrayList l = ...
l.remove(21);
l.trimToSize(); // Only do this if you really have to.
1 - But note that the explicit if (a[e] == null)
checks themselves are likely to be "free", since they can be combined with the implicit null
check that happens when you dereference the value of a[e]
.
2 - I say it is "more efficient in many cases" because ArrayList
uses a simple "double the size" strategy when it needs to grow the backing array. This means that if grow the list by repeatedly appending to it, each element will be copied on average one extra time. By contrast, if you did this with an array you would end up copying each array element close to N/2 times on average.
<script type="text/javascript">
function product(x,y)
{
return x*y;
}
document.getElementById('myvalue').value = product(x,y);
</script>
<input type="hidden" value="THE OUTPUT OF PRODUCT FUNCTION" id="myvalue">
If you are using structured data, this has the added benefit of not invoking an extra shell process to run tr
and/or cut
or something. ...
(Of course, you will want to guard against bad inputs with conditionals and sane alternatives.)
...
while read line ;
do
lineCols=( $line ) ;
echo "${lineCols[0]}"
echo "${lineCols[1]}"
done < $myFQFileToRead ;
...
You should use PDO Prepare
From the link:
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
BOOTSTRAP 3 REFERENCE
Added because I keep getting caught by the solution in this thread and it stuffs me up every time.
Basically the BS dropdown immediately removes the .open
class from the parent, so sliding up does not work.
Use the same bit as other solutions for slideDown();
// ADD SLIDEUP ANIMATION TO DROPDOWN //
$('.dropdown').on('hide.bs.dropdown', function(e){
e.preventDefault();
$(this).find('.dropdown-menu').first().stop(true, true).slideUp(300, function(){
$(this).parent().removeClass('open');
});
});
You can find an easy guide here
The step are 2: - Copy the icon in the correct folder/folders - Change the AndroidManifest.xml
This is not an answer to your question but I believe it is the solution to your problem. The interface org.springframework.data.repository.CrudRepository
does indeed have methods that return java.lang.Iterable
but you should not use this interface. Instead use sub interfaces, in your case org.springframework.data.mongodb.repository.MongoRepository
. This interface has methods that return objects of type java.util.List
.
Here's how we did it:
int DifferenceInMonth(DateTime startDate, DateTime endDate) {
long ToTicks(DateTime date) => new DateTimeOffset(date).Ticks;
var daysPerMonth = 30.4;
return (int)Math.Round((ToTicks(endDate) - ToTicks(startDate)) / TimeSpan.TicksPerDay / daysPerMonth);
}
Just came across this and the short code for transparency is simply #00000000.
In the first case with
set encoding=utf-8
, you'll change the output encoding that is shown in the terminal.In the second case with
set fileencoding=utf-8
, you'll change the output encoding of the file that is written.
As stated by @Dennis, you can set them both in your ~/.vimrc if you always want to work in utf-8
.
From the wiki of VIM about working with unicode
"encoding
sets how vim shall represent characters internally. Utf-8 is necessary for most flavors of Unicode."
"fileencoding
sets the encoding for a particular file (local to buffer); :setglobal sets the default value. An empty value can also be used: it defaults to same as 'encoding'. Or you may want to set one of the ucs encodings, It might make the same disk file bigger or smaller depending on your particular mix of characters. Also, IIUC, utf-8 is always big-endian (high bit first) while ucs can be big-endian or little-endian, so if you use it, you will probably need to set 'bomb" (see below)."
You can define a class constant in php. But your class constant would be accessible from any object instance as well. This is php's functionality.
However, as of php7.1, you can define your class constants with access modifiers (public
, private
or protected
).
A work around would be to define your constant as private
or protected
and then make them readable via a static function
. This function should only return the constant values if called from the static context.
You can also create this static function in your parent class and simply inherit this parent class on all other classes to make it a default functionality.
Credits: http://dwellupper.io/post/48/defining-class-constants-in-php
a = [0,1,2,3,127,200,255]
print str.join("", ("%02x" % i for i in a))
prints
000102037fc8ff
(Also note that your code will fail for integers in the range from 10 to 15.)
Recompile without optimizations (-O0 on gcc).
you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.
or even simpler just use String.charAt()
in the loop to populate array like below:
String ini="Hi there";
char[] array=new char[ini.length()];
for(int count=0;count<array.length;count++){
array[count] = ini.charAt(count);
System.out.print(" "+array[count]);
}
or one liner would be
String ini="Hi there";
char[] array=ini.toCharArray();
Do not use Bitmap.Config.ARGB_8888
Instead use int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_4444; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
ARGB_8888 can land you in OutOfMemory issues when dealing with more bitmaps or large bitmaps. Or better yet, try avoiding usage of ARGB option itself.
> but I don't know how to retrieve the list members from the hash in alphabetical order.
Not really your main question, but for future reference Rod's answer using sorted
can be used for traversing a dict
's keys in sorted order:
for key in sorted(my_dict.keys()):
print key, my_dict[key]
...
and also because tuple
's are ordered by the first member of the tuple, you can do the same with items
:
for key, val in sorted(my_dict.items()):
print key, val
...
could you try doing JSON.stringify(obj);
Like this
var stringify = JSON.stringify(obj);
fs.writeFileSync('./data.json', stringify , 'utf-8');
Go to Project Settings > Artifacts. Select the artifact which has the problem. There is an option "Include in project build". This needs to be checked(enabled). For older versions of IntelliJ this option is "Make on build".
The main()
method is the entry point for a Java application. run()
is typically used for new threads or tasks.
Where have you been writing a run()
method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?
Without having Visual Studio, you can grab Nuget from: http://nuget.org/nuget.exe
For command-line executions using this, check out: http://docs.nuget.org/docs/reference/command-line-reference
With respect to Powershell, just copy the nuget.exe to the machine. No installation required, just execute it using commands from the above documentation.
You can do it inline, but you have to be careful with spaces in the column data. Better to use datalength()
SELECT
ColName,
DATALENGTH(ColName) -
DATALENGTH(REPLACE(Col, 'A', '')) AS NumberOfLetterA
FROM ColName;
-OR- Do the replace with 2 characters
SELECT
ColName,
-LEN(ColName)
+LEN(REPLACE(Col, 'A', '><')) AS NumberOfLetterA
FROM ColName;
sqlitejdbc code can be downloaded using git from https://github.com/crawshaw/sqlitejdbc.
# git clone https://github.com/crawshaw/sqlitejdbc.git sqlitejdbc
...
# cd sqlitejdbc
# make
Note: Makefile requires curl binary to download sqlite libraries/deps.
The point is that the interface represents a contract. A set of public methods any implementing class has to have. Technically, the interface only governs syntax, i.e. what methods are there, what arguments they get and what they return. Usually they encapsulate semantics as well, although that only by documentation.
You can then have different implementations of an interface and swap them out at will. In your example, since every pizza instance is an IPizza
you can use IPizza
wherever you handle an instance of an unknown pizza type. Any instance whose type inherits from IPizza
is guaranteed to be orderable, as it has an Order()
method.
Python is not statically-typed, therefore types are kept and looked up at runtime. So you can try calling an Order()
method on any object. The runtime is happy as long as the object has such a method and probably just shrugs and says »Meh.« if it doesn't. Not so in C#. The compiler is responsible for making the correct calls and if it just has some random object
the compiler doesn't know yet whether the instance during runtime will have that method. From the compiler's point of view it's invalid since it cannot verify it. (You can do such things with reflection or the dynamic
keyword, but that's going a bit far right now, I guess.)
Also note that an interface in the usual sense does not necessarily have to be a C# interface
, it could be an abstract class as well or even a normal class (which can come in handy if all subclasses need to share some common code – in most cases, however, interface
suffices).
Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.
If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.
This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.
Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection.
In the latter case you open the transaction with the TxID and then reconnect using that ID. The DBMS maintains the locks and allows you to pick the session back up through the TxID. This is how distributed transactions using two-phase commit protocols (such as XA or COM+ Transactions) work.
When you write x = 0
, x
is an int...so you can't do x[age1]
because x
is int
Ensure that control Format property is properly set to use a custom format:
DateTimePicker1.Format = DateTimePickerFormat.Custom
Then this is how you can set your desired format:
DateTimePicker1.CustomFormat = "dd-MM-yyyy"
I wanted a more compact output than the great answers above using lapply
, so here's an alternative wrapped as a small function.
# Example data
df <-
data.frame(
w = seq.int(10),
x = LETTERS[seq.int(10)],
y = factor(letters[seq.int(10)]),
z = seq(
as.POSIXct('2020-01-01'),
as.POSIXct('2020-10-01'),
length.out = 10
)
)
# Function returning compact column classes
col_classes <- function(df) {
t(as.data.frame(lapply(df, function(x) paste(class(x), collapse = ','))))
}
# Return example data's column classes
col_classes(df)
[,1]
w "integer"
x "character"
y "factor"
z "POSIXct,POSIXt"
I had a similar problem. I wished to colour a complex drawable background for a view based on a color (int) value. I succeeded by using the code:
ColorStateList csl = new ColorStateList(new int[][]{{}}, new int[]{color});
textView.setBackgroundTintList(csl);
Where color is an int value representing the colour required. This represents the simple xml ColorStateList:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:color="color here"/>
</selector>
Hope this helps.
The best way I found so far is to go to the Oauth playground here: https://developers.google.com/oauthplayground/
In the HTTP header for the REST API request, add: "Authorization: Bearer ". Here, Authorization is the key, and "Bearer ". For example: "Authorization: Bearer za29.KluqA3vRtZChWfJDabcdefghijklmnopqrstuvwxyz6nAZ0y6ElzDT3yH3MT5"
public static IEnumerable<string> LineSplitter(this string line, char
separator, char skip = '"')
{
var fieldStart = 0;
for (var i = 0; i < line.Length; i++)
{
if (line[i] == separator)
{
yield return line.Substring(fieldStart, i - fieldStart);
fieldStart = i + 1;
}
else if (i == line.Length - 1)
{
yield return line.Substring(fieldStart, i - fieldStart + 1);
fieldStart = i + 1;
}
if (line[i] == '"')
for (i++; i < line.Length && line[i] != skip; i++) { }
}
if (line[line.Length - 1] == separator)
{
yield return string.Empty;
}
}
For anyone who looking the most simple solution, here's the one
vowel = ['a', 'e', 'i', 'o', 'u']
Sentence = input("Enter a phrase: ")
count = 0
for letter in Sentence:
if letter in vowel:
count += 1
print(count)
To call the camera you can use:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
The image will be automatically saved in a default directory.
And you need to set the permission for the camera in your AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA"> </uses-permission>
Typically, git commit
brings up an interactive editor (on Linux, and possibly Cygwin, determined by the contents of your $EDITOR
environment variable) for you to edit your commit message in. When you save and exit, the commit completes.
You should make sure that the changes you are trying to commit have been added to the Git index; this determines what is committed. See http://gitref.org/basic/ for details on this.
In my case, I use rails framework and require jQuery twice. I think that is a possible reason.
You can first check app/assets/application.js file. If the jquery and bootstrap-sprockets appears, then there is not need for a second library require. The file should be similar to this:
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
Then check app/views/layouts/application.html.erb, and remove the script for requiring jquery. For example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
I think sometimes when newbies use multiple tutorial code examples will cause this issue.
I guess, a column value in a foreign key table should match with the column value of the primary key table. If we are trying to create a foreign key constraint between two tables where the value inside one column(going to be the foreign key) is different from the column value of the primary key table then it will throw the message.
So it is always recommended to insert only those values in the Foreign key column which are present in the Primary key table column.
For ex. If the Primary table column has values 1, 2, 3 and in Foreign key column the values inserted are different, then the query would not be executed as it expects the values to be between 1 & 3.
By default, the locations of Temporary Internet Files (for Internet Explorer) are:
Windows 95, Windows 98, and Windows ME
c:\WINDOWS\Temporary Internet Files
Windows 2000 and Windows XP
C:\Documents and Settings\\[User]\Local Settings\Temporary Internet Files
Windows Vista and Windows 7
%userprofile%\AppData\Local\Microsoft\Windows\Temporary Internet Files
%userprofile%\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low
Windows 8
%userprofile%\AppData\Local\Microsoft\Windows\INetCache
Windows 10
%localappdata%\Microsoft\Windows\INetCache\IE
Some information came from The Windows Club.
If you just use rm
, you will need to follow it up with git add <fileRemoved>
. git rm
does this in one step.
You can also use git rm --cached
which will remove the file from the index (staging it for deletion on the next commit), but keep your copy in the local file system.
Daniel Imms answer is excellent in regards to applying your CSS rotation to an inner element. However, it is possible to accomplish the end goal in a way that does not require JavaScript and works with longer strings of text.
Typically the whole reason to have vertical text in the first table column is to fit a long line of text in a short horizontal space and to go alongside tall rows of content (as in your example) or multiple rows of content (which I'll use in this example).
By using the ".rotate" class on the parent TD tag, we can not only rotate the inner DIV, but we can also set a few CSS properties on the parent TD tag that will force all of the text to stay on one line and keep the width to 1.5em. Then we can use some negative margins on the inner DIV to make sure that it centers nicely.
td {_x000D_
border: 1px black solid;_x000D_
padding: 5px;_x000D_
}_x000D_
.rotate {_x000D_
text-align: center;_x000D_
white-space: nowrap;_x000D_
vertical-align: middle;_x000D_
width: 1.5em;_x000D_
}_x000D_
.rotate div {_x000D_
-moz-transform: rotate(-90.0deg); /* FF3.5+ */_x000D_
-o-transform: rotate(-90.0deg); /* Opera 10.5 */_x000D_
-webkit-transform: rotate(-90.0deg); /* Saf3.1+, Chrome */_x000D_
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083); /* IE6,IE7 */_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */_x000D_
margin-left: -10em;_x000D_
margin-right: -10em;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
<tr>_x000D_
<td class='rotate' rowspan="4"><div>10 kilograms</div></td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Q</td>_x000D_
<td>R</td>_x000D_
<td>S</td>_x000D_
<td>T</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td class='rotate' rowspan="4"><div>20 kilograms</div></td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Q</td>_x000D_
<td>R</td>_x000D_
<td>S</td>_x000D_
<td>T</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td class='rotate' rowspan="4"><div>30 kilograms</div></td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Q</td>_x000D_
<td>R</td>_x000D_
<td>S</td>_x000D_
<td>T</td>_x000D_
</tr>_x000D_
_x000D_
</table>
_x000D_
One thing to keep in mind with this solution is that it does not work well if the height of the row (or spanned rows) is shorter than the vertical text in the first column. It works best if you're spanning multiple rows or you have a lot of content creating tall rows.
Have fun playing around with this on jsFiddle.
I Also come across these kind of requirements recently.I set the below properties with out writing the code it works.see if this helps you.
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.
SQL databases like Oracle, db2 also support Horizontal scaling through Shared disk cluster. For example Oracle RAC, IBM DB2 purescale or Sybase ASE Cluster edition. New node can be added to Oracle RAC system or DB2 purescale system to achieve horizontal scaling.
But the approach is different from noSQL databases (like mongodb, CouchDB or IBM Cloudant) is that the data sharding is not part of Horizontal scaling. In noSQL databases data is shraded during horizontal scaling.
I think the best way to look at why this doesn't work is that :before and :after insert their content before or after the content within the tag you're applying them to. So it works with divs or spans (or most other tags) because you can put content inside them.
<div>
:before
Content
:after
</div>
However, an img is a self-contained, self-closing tag, and since it has no separate closing tag, you can't put anything inside of it. (That would need to look like <img>Content</img>
, but of course that doesn't work.)
I know this is an old topic, but it pops up first on Google, so hopefully this will help others learn.
You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.
Then the code would be something similar to
string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;
Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.
Python and just about every other computer language use the same principles as (I hope) you would use when finding a word in a printed dictionary:
(1) Depending on the human language involved, you have a notion of character ordering: 'a' < 'b' < 'c' etc
(2) First character has more weight than second character: 'az' < 'za' (whether the language is written left-to-right or right-to-left or boustrophedon is quite irrelevant)
(3) If you run out of characters to test, the shorter string is less than the longer string: 'foo' < 'food'
Typically, in a computer language the "notion of character ordering" is rather primitive: each character has a human-language-independent number ord(character)
and characters are compared and sorted using that number. Often that ordering is not appropriate to the human language of the user, and then you need to get into "collating", a fun topic.
you can use just
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version></version>
</dependency>
=iferror(counta(unique(A1:A100)))
counts number of unique cells from A1 to A100
If you're using a WebView
you'll have to intercept the clicks yourself if you don't want the default Android behaviour.
You can monitor events in a WebView
using a WebViewClient
. The method you want is shouldOverrideUrlLoading()
. This allows you to perform your own action when a particular URL is selected.
You set the WebViewClient
of your WebView
using the setWebViewClient()
method.
If you look at the WebView
sample in the SDK there's an example which does just what you want. It's as simple as:
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
You can add either -DskipTests
or -Dmaven.test.skip=true
to any mvn
command for skipping tests. In your case it would be like below:
mvn package -DskipTests
OR
mvn package -Dmaven.test.skip=true
import os
cwd = os.getcwd()
path = os.path.join(cwd, "my_file")
f = open(path)
You also try to normalize your cwd
using os.path.abspath(os.getcwd())
. More info here.
Since PHP >= 5.2.2 you can use the DateTime
class as such:
if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
# current time is greater than 2010-05-15 16:00:00
# in other words, 2010-05-15 16:00:00 has passed
}
The string passed to the DateTime constructor is parsed according to these rules.
Note that it is also possible to use time
and strtotime
functions. See original answer.
You can follow these tutorials to get started
Tutorials
Hello World Web Server (paid)
Node JS Processing Model – Single Threaded Model with Event Loop Architecture
Developer Sites
Videos
Screencasts
Books
Courses
Blogs
Podcasts
JavaScript resources
Node.js Modules
Other
Update:
Oracle now fully supports the Entity Framework. Oracle Data Provider for .NET Release 11.2.0.3 (ODAC 11.2) Release Notes: http://docs.oracle.com/cd/E20434_01/doc/win.112/e23174/whatsnew.htm#BGGJIEIC
More documentation on Linq to Entities and ADO.NET Entity Framework: http://docs.oracle.com/cd/E20434_01/doc/win.112/e23174/featLINQ.htm#CJACEDJG
Note: ODP.NET also supports Entity SQL.
Ended up using http://videojs.com/ to support all browsers.
But to get the video working in IE9 and Chrome I just added html5 doc type and used mp4:
<!DOCTYPE html>
<html>
<body>
<video src="video.mp4" width="400" height="300" preload controls>
</video>
</body>
</html>
Make sure your first network interface is NAT. The other second network interface can be anything you want when you're building box. Don't forget the Vagrant user, as discussed in the Google thread.
Good luck.
Well, first you need to request the username of the user from the session in your controller action like this:
$username=$this->get('security.context')->getToken()->getUser()->getUserName();
then do a query to the db and get your object with regular dql like
$em = $this->get('doctrine.orm.entity_manager');
"SELECT u FROM Acme\AuctionBundle\Entity\User u where u.username=".$username;
$q=$em->createQuery($query);
$user=$q->getResult();
the $user should now hold the user with this username ( you could also use other fields of course)
...but you will have to first configure your /app/config/security.yml configuration to use the appropriate field for your security provider like so:
security:
provider:
example:
entity: {class Acme\AuctionBundle\Entity\User, property: username}
hope this helps!
Form nesting can be achieved with new HTML5 input element's form attribute. Although we don't nest forms structurally, inputs are evaluated as they are in their own form. In my tests, 3 major browsers support this except IE(IE11). Form nesting limitation was a big obstacle for HTML UI design.
Here is a sample code, when you click Save button you should see "2 3 success" (Original http://www.impressivewebs.com/html5-form-attribute/):
<form id="saveForm" action="/post/dispatch/save" method="post"></form>
<form id="deleteForm" action="/post/dispatch/delete" method="post"></form>
<div id="toolbar">
<input type="text" name="foo" form="saveForm" />
<input type="hidden" value="some_id" form="deleteForm" />
<input type="text" name="foo2" id="foo2" form="saveForm" value="success" />
<input type="submit" name="save" value="Save" form="saveForm" onclick="alert(document.getElementById('deleteForm').elements.length + ' ' + document.getElementById('saveForm').elements.length + ' ' + document.getElementById('saveForm').elements['foo2'].value);return false;" />
<input type="submit" name="delete" value="Delete" form="deleteForm" />
<a href="/home/index">Cancel</a>
</div>
People normally use it to indicate dummy values. I think that it primarily was used before the idea of NULL pointers.
Simply use mysql_fetch_assoc and count the array using count() function
If you don't want to make the button a separate image, you can use the <area>
tag. This is done by using html similar to this:
<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">
<map name="mapname">
<area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>
Note 1: The coords=" "
attribute must be formatted in this way: coords="x1,y1,x2,y2"
where:
x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate
Note 2: The usemap="#mapname"
attribute must include the #
.
EDIT:
I looked at your code and added in the <map>
and <area>
tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.
<div class="flexslider">
<ul class="slides" runat="server" id="Ul">
<li class="flex-active-slide" style="background: url("images/slider-bg-1.jpg") no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
<div class="container">
<div class="sixteen columns contain"></div>
<img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
<map name="imgmap">
<area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
</map>
<!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
</div>
</li>
</ul>
</div>
<!-- <ul class="flex-direction-nav">
<li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
<li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->
Notes:
coord="48,341,294,275"
is in reference to your screenshot you posted.src="./test.png"
is the location and name of the screenshot you posted on my computer.href="http://www.example.com/"
is an example link.Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.
public class Time
{
public static void Timestamps()
{
OutputTimestamp();
Thread.Sleep(1000);
OutputTimestamp();
}
private static void OutputTimestamp()
{
var timestamp = DateTime.UtcNow.Ticks;
var localTicks = DateTime.Now.Ticks;
var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
Console.Out.WriteLine("Timestamp = {0}. Local ticks = {1}. Local time = {2}.", timestamp, localTicks, localTime);
}
}
Output:
Timestamp = 636988286338754530. Local ticks = 636988034338754530. Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736. Local ticks = 636988034348878736. Local time = 2019-07-15 4:03:54 PM.
Looks like your form is submitting which is the default behaviour, you can stop it with this:
<form action="" method="post" onsubmit="completeAndRedirect();return false;">
Same error, solved by updating Google Nuget support packages
Try this one:
#!/bin/bash
find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head
Execute it with the path to the directory where it should start scanning recursively (it supports filenames with spaces).
If there are lots of files it may take a while before it returns anything. Performance can be improved if we use xargs
instead:
#!/bin/bash
find $1 -type f -print0 | xargs -0 stat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head
which is a bit faster.
For some reason I could not get this to work with the proposed answers, but I found another variation, using select, that worked for me:
models.Post.find().sort('-date').limit(10).select('published').exec(function(e, data){
...
});
Has the api perhaps changed? I am using version 3.8.19
I used a combination of the above because my app works in the browser as well as on device. The problem with browser is it won't let you close the window from a script unless your app was opened by a script (like browsersync).
if (typeof cordova !== 'undefined') {
if (navigator.app) {
navigator.app.exitApp();
}
else if (navigator.device) {
navigator.device.exitApp();
}
} else {
window.close();
$timeout(function () {
self.showCloseMessage = true; //since the browser can't be closed (otherwise this line would never run), ask the user to close the window
});
}
code to generate a password with password will be given length (default to 8) and have at least one upper case, one lower, one number and one symbol
(2 functions and one const variable called 'allowed')
const allowed = {
uppers: "QWERTYUIOPASDFGHJKLZXCVBNM",
lowers: "qwertyuiopasdfghjklzxcvbnm",
numbers: "1234567890",
symbols: "!@#$%^&*"
}
const getRandomCharFromString = (str) => str.charAt(Math.floor(Math.random() * str.length))
const generatePassword = (length = 8) => { // password will be @Param-length, default to 8, and have at least one upper, one lower, one number and one symbol
let pwd = "";
pwd += getRandomCharFromString(allowed.uppers); //pwd will have at least one upper
pwd += getRandomCharFromString(allowed.lowers); //pwd will have at least one lower
pwd += getRandomCharFromString(allowed.numbers); //pwd will have at least one number
pwd += getRandomCharFromString(allowed.symbols);//pwd will have at least one symbolo
for (let i = pwd.length; i < length; i++)
pwd += getRandomCharFromString(Object.values(allowed).join('')); //fill the rest of the pwd with random characters
return pwd
}
You can just use
myDict = {
"P1": (lambda x: function1()),
"P2": (lambda x: function2()),
...,
"Pn": (lambda x: functionn())}
myItems = ["P1", "P2", ..., "Pn"]
for item in myItems:
myDict[item]()
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
64/32 bit error? I found this as a problem as my dev machine was 32bit and the production server 64bit. If so, you may need to call the 32bit runtime directly from the command line.
This link says it better (No 64bit JET driver): http://social.msdn.microsoft.com/forums/en-US/sqlintegrationservices/thread/da076e51-8149-4948-add1-6192d8966ead/
On the standard front:
a translation unit is the combination of a source files, included headers and source files less any source lines skipped by conditional inclusion preprocessor directive.
the standard defines 9 phases in the translation. The first four correspond to preprocessing, the next three are the compilation, the next one is the instantiation of templates (producing instantiation units) and the last one is the linking.
In practice the eighth phase (the instantiation of templates) is often done during the compilation process but some compilers delay it to the linking phase and some spread it in the two.
In Angular use 'extends' to define the interface for an 'Array' of objects.
Using an indexer will give you an error as its not an Array interface so doesn't contain the properties and methods.
e.g
error TS2339: Property 'find' does not exist on type 'ISelectOptions2'.
// good
export interface ISelectOptions1 extends Array<ISelectOption> {}
// bad
export interface ISelectOptions2 {
[index: number]: ISelectOption;
}
interface ISelectOption {
prop1: string;
prop2?: boolean;
}
You are missing an include :
#include <stdlib.h>
, so GCC creates an implicit declaration of atof
and atod
, leading to garbage values.
And the format specifier for double is %f
, not %d
(that is for integers).
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *test = "12.11";
double temp = strtod(test,NULL);
float ftemp = atof(test);
printf("price: %f, %f",temp,ftemp);
return 0;
}
/* Output */
price: 12.110000, 12.110000
To perfectly forward without chopping the absoluteURI
of the request and the Host
in the header:
server {
listen 35005;
location / {
rewrite ^(.*)$ "://$http_host$uri$is_args$args";
rewrite ^(.*)$ "http$uri$is_args$args" break;
proxy_set_header Host $host;
proxy_pass https://deploy.org.local:35005;
}
}
Found here: https://opensysnotes.wordpress.com/2016/11/17/nginx-proxy_pass-with-absolute-url/
I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:
// creating locale Locale locale2 = new Locale(loc); Locale.setDefault(locale2); Configuration config2 = new Configuration(); config2.locale = locale2; // updating locale mContext.getResources().updateConfiguration(config2, null);
Why Server.Transfer
? Response.Redirect(Request.RawUrl)
would get you what you need.
Subclassing is a little cumbersome for such a simple case. An alternative is to simply add the UILabel with no background set to a UIView with the background set. Set the label's x to 10 and make the outer view's size 20 pixels wider than the label.
You can also use it in named_scope if You want to put there others conditions
for example include some other model:
named_scope 'get_by_ids', lambda { |ids| { :include => [:comments], :conditions => ["comments.id IN (?)", ids] } }
.bashrc
is not meant to be executed but sourced. Try this instead:
. ~/.bashrc
Cheers!
Apart from the excellent explanation by Mrry, where he suggested to use device_lib.list_local_devices()
I can show you how you can check for GPU related information from the command line.
Because currently only Nvidia's gpus work for NN frameworks, the answer covers only them. Nvidia has a page where they document how you can use the /proc filesystem interface to obtain run-time information about the driver, any installed NVIDIA graphics cards, and the AGP status.
/proc/driver/nvidia/gpus/0..N/information
Provide information about each of the installed NVIDIA graphics adapters (model name, IRQ, BIOS version, Bus Type). Note that the BIOS version is only available while X is running.
So you can run this from command line cat /proc/driver/nvidia/gpus/0/information
and see information about your first GPU. It is easy to run this from python and also you can check second, third, fourth GPU till it will fail.
Definitely Mrry's answer is more robust and I am not sure whether my answer will work on non-linux machine, but that Nvidia's page provide other interesting information, which not many people know about.
Here lies your problem:
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text); // tv is null
}
--> (TextView) findViewById(id); // returns null But from your code, I can't find why this method returns null. Try to track down, what id you give as a parameter and if this view with the specified id exists.
The error message is very clear and even tells you at what method. From the documentation:
public final View findViewById (int id)
Look for a child view with the given id. If this view has the given id, return this view.
Parameters
id The id to search for.
Returns
The view that has the given id in the hierarchy or null
http://developer.android.com/reference/android/view/View.html#findViewById%28int%29
In other words: You have no view with the id you give as a parameter.
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
You can list files in a directory of firebase storage by listAll() method. To use this method, have to implement this version of firebase storage. 'com.google.firebase:firebase-storage:18.1.1'
https://firebase.google.com/docs/storage/android/list-files
Keep in mind that upgrade the Security Rules to version 2.
Did you override equals and hashCode in the Block class?
EDIT:
I assumed you mean it doesn't work at runtime... did you mean that or at compile time? If compile time what is the error message? If it crashes at runtime what is the stack trace? If it compiles and runs but doesn't work right then the equals and hashCode are the likely issue.