use DatePipe
> // ts file
import { DatePipe } from '@angular/common';
@Component({
....
providers:[DatePipe]
})
export class FormComponent {
constructor(private datePipe : DatePipe){}
demoUser = new User(0, '', '', '', '', this.datePipe.transform(new Date(), 'yyyy-MM-dd'), '', 0, [], []);
}
Brave browser on iOS behaves differently (buggy?). It changes viewport height dynamically accordingly to showing/hiding address bar. It is kind of annoying because it changes page's layout dependent on vw/vh units.
Chrome and Safari is fine.
Just a side comment, Before adding support for multidex - make sure you are not adding unnecessary dependencies.
For example In the official Facebook analytics guide
They clearly state that you should add the following dependency:
implementation 'com.facebook.android:facebook-android-sdk:[4,5)'
which is actually the entire FacebookSDK - so if you need for example just the Analytics you need to replace it with:
implementation 'com.facebook.android:facebook-core:5.+'
You're not looping over the items. Try this instead:
$.getJSON(url, function(data){
$.each(data.response.venue.tips.groups.items, function (index, value) {
console.log(this.text);
});
});
you should try this
g++-4.4 -std=c++0x or g++-4.7 -std=c++0x
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
I furiously read all of this page, hoping to find a solution for:
"configure: error: C compiler cannot create executables"
In the end nothing worked, because my problem was a "typing" one, and was related to CFLAGS. In my .bash_profile file I had:
export ARM_ARCH="arm64”
export CFLAGS="-arch ${ARM_ARCH}"
As you can observe --- export ARM_ARCH="arm64” --- the last quote sign is not the same with the first quote sign. The first one ( " ) is legal while the second one ( ” ) is not.
This happended because I made the mistake to use TextEdit (I'm working under MacOS), and this is apparently a feature called SmartQuotes: the quote sign CHANGES BY ITSELF TO THE ILLEGAL STYLE whenever you edit something just next to it.
Lesson learned: use a proper text editor...
The Main
method is Static. You can not invoke a non-static method from a static method.
GetRandomBits()
is not a static method. Either you have to create an instance of Program
Program p = new Program();
p.GetRandomBits();
or make
GetRandomBits()
static.
You need to slightly modify your compare
function and use functools.cmp_to_key
to pass it to sorted
. Example code:
import functools
lst = [list(range(i, i+5)) for i in range(5, 1, -1)]
def fitness(item):
return item[0]+item[1]+item[2]+item[3]+item[4]
def compare(item1, item2):
return fitness(item1) - fitness(item2)
sorted(lst, key=functools.cmp_to_key(compare))
Output:
[[2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9]]
Works :)
Another possible cause: You've passed --static to the linker, but you only have a dynamic version of libz (libz.so), but not a version that can be statically linked (libz.a).
You can enable long path names using PowerShell:
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name LongPathsEnabled -Type DWord -Value 1
Another Version is to use a Group Policy in Computer Configuration
/Administrative Templates
/System
/Filesystem
:
First off, Xvfb doesn't read configuration from xorg.conf. Xvfb is a variant of the KDrive X servers and like all members of that family gets its configuration from the command line.
It is true that XRandR and Xinerama are mutually exclusive, but in the case of Xvfb there's no Xinerama in the first place. You can enable the XRandR extension by starting Xvfb using at least the following command line options
Xvfb +extension RANDR [further options]
Using Google APIS:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script>
contry_code = google.loader.ClientLocation.address.country_code
city = google.loader.ClientLocation.address.city
region = google.loader.ClientLocation.address.region
</script>
I know this is an old post but as MisterZimbu stated, the color
property is defining the values of other properties, as the border-color
and, with CSS3, of currentColor
.
currentColor
is very handy if you want to use the font color for other elements (as the background or custom checkboxes and radios of inner elements for example).
Example:
.element {_x000D_
color: green;_x000D_
background: red;_x000D_
display: block;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.innerElement1 {_x000D_
border: solid 10px;_x000D_
display: inline-block;_x000D_
width: 60px;_x000D_
height: 100px;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
.innerElement2 {_x000D_
background: currentColor;_x000D_
display: inline-block;_x000D_
width: 60px;_x000D_
height: 100px;_x000D_
margin: 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
<div class="innerElement1"></div>_x000D_
<div class="innerElement2"></div>_x000D_
</div>
_x000D_
It was changed between 3.1 and 3.2:
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.
So use it without the quotes thus:
i="test"
if [[ $i =~ 200[78] ]] ; then
echo "OK"
else
echo "not OK"
fi
I prefer using HTTP Headers for this kind of contextual information.
For the total number of elements, I use the X-total-count
header.
For links to next, previous page, etc. I use HTTP Link
header:
http://www.w3.org/wiki/LinkHeader
Github does it the same way: https://developer.github.com/v3/#pagination
In my opinion, it's cleaner since it can be used also when you return content that doesn't support hyperlinks (i.e binaries, pictures).
If you want to take advantage of recent Python versions' async features, you can use aioftp (from the same family of libraries and developers as the more popular aiohttp library). Here is a code example taken from their client tutorial:
client = aioftp.Client()
await client.connect("ftp.server.com")
await client.login("user", "pass")
await client.download("tmp/test.py", "foo.py", write_into=True)
If has access to CryptoPP
Readable Hex String to unsigned char
std::string& hexed = "C23412341324AB";
uint8_t buffer[64] = {0};
StringSource ssk(hexed, true,
new HexDecoder(new ArraySink(buffer,sizeof(buffer))));
And back
std::string hexed;
uint8_t val[32] = {0};
StringSource ss(val, sizeof(val), true,new HexEncoder(new StringSink(hexed));
// val == buffer
JavaScript can't send email from a web browser. However, stepping back from the solution you've already tried to implement, you can do something that meets the original requirement:
send an email without refreshing the page
You can use JavaScript to construct the values that the email will need and then make an AJAX request to a server resource that actually sends the email. (I don't know what server-side languages/technologies you're using, so that part is up to you.)
If you're not familiar with AJAX, a quick Google search will give you a lot of information. Generally you can get it up and running quickly with jQuery's $.ajax() function. You just need to have a page on the server that can be called in the request.
does it matter? people are generally smart enough to interpret messages correctly, if they aren't you probably shouldn't let them access your repository anyway!
Never mind, I figured it out - I used the Set()
method on Header()
(doh!)
My handler looks like this now:
func saveHandler(w http.ResponseWriter, r *http.Request) {
// allow cross domain AJAX requests
w.Header().Set("Access-Control-Allow-Origin", "*")
}
Maybe this will help someone as caffeine deprived as myself sometime :)
You can use custom camera with thumbnail image. You can look my project.
You may want to use the ndarray.item
method, as in a.item()
. This is also equivalent to (the now deprecated) np.asscalar(a)
. This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,
>>> a = np.asarray(1).view()
>>> a.item() # correct
1
>>> a[0] # breaks
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array
>>> a = np.asarray([[2]])
>>> a.item() # correct
2
>>> a[0] # bad result
array([2])
This also has the benefit of throwing an exception if the array is not a singleton, while the a[0]
approach will silently proceed (which may lead to bugs sneaking through undetected).
>>> a = np.asarray([1, 2])
>>> a[0] # silently proceeds
1
>>> a.item() # detects incorrect size
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: can only convert an array of size 1 to a Python scalar
Another answer for the first question is to use one for loop and perform linear indexing into the array using the function NUMEL to get the total number of elements:
total = 0;
for i = 1:numel(A)
total = total+A(i);
end
Use apache commons-io, just one line code:
FileUtils.copyURLToFile(URL, File)
I was looking for a way to do this myself and figured out a simple solution.
I'm assuming that you started a default Win32 Project (Windows application) in Visual Studio, which provides a "WinMain" function. By default, Visual Studio sets the entry point to "SUBSYSTEM:WINDOWS". You need to first change this by going to:
Project -> Properties -> Linker -> System -> Subsystem
And select "Console (/SUBSYSTEM:CONSOLE)" from the drop-down list.
Now, the program will not run, since a "main" function is needed instead of the "WinMain" function.
So now you can add a "main" function like you normally would in C++. After this, to start the GUI program, you can call the "WinMain" function from inside the "main" function.
The starting part of your program should now look something like this:
#include <iostream>
using namespace std;
// Main function for the console
int main(){
// Calling the wWinMain function to start the GUI program
// Parameters:
// GetModuleHandle(NULL) - To get a handle to the current instance
// NULL - Previous instance is not needed
// NULL - Command line parameters are not needed
// 1 - To show the window normally
wWinMain(GetModuleHandle(NULL), NULL,NULL, 1);
system("pause");
return 0;
}
// Function for entry into GUI program
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
// This will display "Hello World" in the console as soon as the GUI begins.
cout << "Hello World" << endl;
.
.
.
Now you can use functions to output to the console in any part of your GUI program for debugging or other purposes.
Neither submit()
nor click()
is good enough. However, it works fine if you follow it with an ENTER key:
search_form = driver.find_element_by_id(elem_id)
search_form.send_keys(search_string)
search_form.click()
from selenium.webdriver.common.keys import Keys
search_form.send_keys(Keys.ENTER)
Tested on Mac 10.11, python 2.7.9, Selenium 2.53.5. This runs in parallel, meaning returns after entering the ENTER key, doesn't wait for page to load.
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
If you want to do it via javascript rather than CSS you can use:
var link = document.getElementById('nav-ask');
link.style.display = 'none'; //or
link.style.visibility = 'hidden';
depending on what you want to do.
Here's what I did to fix this:
1) Create a new project
2) open the gradle-wrapper.properties file and copy the distributionUrl to your project e.g.:
distributionUrl=https\://services.gradle.org/distributions/gradle-3.2-all.zip
3) open the build.gradle (Project) and copy the gradle dependency to your project e.g.:
classpath 'com.android.tools.build:gradle:2.3.0-beta1'
4) File --> Invalidate Caches / Restart (I think a re-sync may have sufficed, but didn't try it)
5) Delete that project you made (optional)
Look, this is a silly way to do things, but Android Studio is free so who am I to complain...
You need to include the reference to the assembly System.Web.Mvc in you project.
you may not have the System.Web.Mvc in your C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0
So you need to add it and then to include it as reference to your projrect
There is a new feature on ES6+ that you can check it like below:
if (x?.y)
Actually, the interpretor checks the existence of x
and then call the y
and because of putting inside if
parentheses the coercion happens and x?.y
converted to boolean.
In Python, curly braces are used to define a dictionary.
a={'one':1, 'two':2, 'three':3}
a['one']=1
a['three']=3
In other languages, { } are used as part of the flow control. Python however used indentation as its flow control because of its focus on readable code.
for entry in entries:
code....
There's a little easter egg in Python when it comes to braces. Try running this on the Python Shell and enjoy.
from __future__ import braces
Try this:
function reload(){_x000D_
var container = document.getElementById("yourDiv");_x000D_
var content = container.innerHTML;_x000D_
container.innerHTML= content; _x000D_
_x000D_
//this line is to watch the result in console , you can remove it later _x000D_
console.log("Refreshed"); _x000D_
}
_x000D_
<a href="javascript: reload()">Click to Reload</a>_x000D_
<div id="yourDiv">The content that you want to refresh/reload</div>
_x000D_
Hope it works. Let me know
After trying a lot of methods, I found out, to get the time in millis at GMT you need to create two separate SimpleDateFormat
objects, one for formatting in GMT and another one for parsing.
Here is the code:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date();
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateTime= dateParser.parse(format.format(date));
long gmtMilliSeconds = dateTime.getTime();
This works fine. :)
Go to Start-> All Programs -> Accessories right click on Command Prompt click on Run as administrator
In the command prompt using CD command Go to MySQL bin folder and run the below command
mysqldump --user root --password=root --all-databases>dumps.sql
it will create dumps.sql file in the bin folder itself.
It looks suspicious because there is no apparent function that is being returned from!
It is an anonymous function that has been attached to the click event of the object.
why are you doing this, Steve?
Why on earth are you doi.....Ah nevermind, as you've mentioned, it really is widely adopted bad practice :)
FYI: The 3.0 Google Analytics API will automatically refresh the access token if you have a refresh token when it expires so your script never needs refreshToken
.
(See the Sign
function in auth/apiOAuth2.php
)
Was just working with Nativescript's fetchModule and figured out my own solution using string manipulation. Append the query string bit by bit to the url. Here is an example where query is passed as a json object (query = {order_id: 1}):
function performGetHttpRequest(fetchLink='http://myapi.com/orders', query=null) {
if(query) {
fetchLink += '?';
let count = 0;
const queryLength = Object.keys(query).length;
for(let key in query) {
fetchLink += key+'='+query[key];
fetchLink += (count < queryLength) ? '&' : '';
count++;
}
}
// link becomes: 'http://myapi.com/orders?order_id=1'
// Then, use fetch as in MDN and simply pass this fetchLink as the url.
}
I tested this over a multiple number of query parameters and it worked like a charm :) Hope this helps someone.
Maybe this example listed here can help you out. Statement from the author
about 24 lines of code to encrypt, 23 to decrypt
Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)
/*
Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
#region Usings
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
#endregion
namespace Utilities.Encryption
{
/// <summary>
/// Utility class that handles encryption
/// </summary>
public static class AESEncryption
{
#region Static Functions
/// <summary>
/// Encrypts a string
/// </summary>
/// <param name="PlainText">Text to be encrypted</param>
/// <param name="Password">Password to encrypt with</param>
/// <param name="Salt">Salt to encrypt with</param>
/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="PasswordIterations">Number of iterations to do</param>
/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
/// <param name="KeySize">Can be 128, 192, or 256</param>
/// <returns>An encrypted string</returns>
public static string Encrypt(string PlainText, string Password,
string Salt = "Kosher", string HashAlgorithm = "SHA1",
int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
int KeySize = 256)
{
if (string.IsNullOrEmpty(PlainText))
return "";
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] CipherTextBytes = null;
using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream())
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
{
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
CryptoStream.FlushFinalBlock();
CipherTextBytes = MemStream.ToArray();
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
return Convert.ToBase64String(CipherTextBytes);
}
/// <summary>
/// Decrypts a string
/// </summary>
/// <param name="CipherText">Text to be decrypted</param>
/// <param name="Password">Password to decrypt with</param>
/// <param name="Salt">Salt to decrypt with</param>
/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="PasswordIterations">Number of iterations to do</param>
/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
/// <param name="KeySize">Can be 128, 192, or 256</param>
/// <returns>A decrypted string</returns>
public static string Decrypt(string CipherText, string Password,
string Salt = "Kosher", string HashAlgorithm = "SHA1",
int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
int KeySize = 256)
{
if (string.IsNullOrEmpty(CipherText))
return "";
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
int ByteCount = 0;
using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
{
ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
}
#endregion
}
}
Case study: GitHub API
https://developer.github.com/v3/#client-errors
Maybe copying from well known APIs is a wise idea:
There are three possible types of client errors on API calls that receive request bodies:
Sending invalid JSON will result in a 400 Bad Request response.
HTTP/1.1 400 Bad Request Content-Length: 35 {"message":"Problems parsing JSON"}
Sending the wrong type of JSON values will result in a 400 Bad Request response.
HTTP/1.1 400 Bad Request Content-Length: 40 {"message":"Body should be a JSON object"}
Sending invalid fields will result in a 422 Unprocessable Entity response.
HTTP/1.1 422 Unprocessable Entity Content-Length: 149 { "message": "Validation Failed", "errors": [ { "resource": "Issue", "field": "title", "code": "missing_field" } ] }
I think you have downloaded the .NET Reflector & this FileGenerator plugin http://filegenreflector.codeplex.com/ , If you do,
Open up the Reflector.exe,
Go to View and click Add-Ins,
In the Add-Ins window click Add...,
Then find the dll you have downloaded
FileGenerator.dll (witch came wth the FileGenerator plugin),
Then close the Add-Ins window.
Go to File and click Open and choose the dll that you want to decompile,
After you have opend it, it will appear in the tree view,
Go to Tools and click Generate Files(Crtl+Shift+G),
select the output directory and select appropriate settings as your wish, Click generate files.
OR
You can actually just use the Remove overload that takes one parameter:
str = str.Remove(str.Length - 3);
However, if you're trying to avoid hard coding the length, you can use:
str = str.Remove(str.IndexOf(','));
Yes changing the error_to debug level as Emmanuel Joubaud suggested worked out (edit /etc/nginx/sites-enabled/default ):
error_log /var/log/nginx/error.log debug;
Then after restaring nginx I got in the error log with my Python application using uwsgi:
2017/02/08 22:32:24 [debug] 1322#1322: *1 connect to unix:///run/uwsgi/app/socket, fd:20 #2
2017/02/08 22:32:24 [debug] 1322#1322: *1 connected
2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream connect: 0
2017/02/08 22:32:24 [debug] 1322#1322: *1 posix_memalign: 0000560E1F25A2A0:128 @16
2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request
2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request body
2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer buf fl:0 s:454
2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer in: 0000560E1F2A0928
2017/02/08 22:32:24 [debug] 1322#1322: *1 writev: 454 of 454
2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer out: 0000000000000000
2017/02/08 22:32:24 [debug] 1322#1322: *1 event timer add: 20: 60000:1486593204249
2017/02/08 22:32:24 [debug] 1322#1322: *1 http finalize request: -4, "/?" a:1, c:2
2017/02/08 22:32:24 [debug] 1322#1322: *1 http request count:2 blk:0
2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5DE0
2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5E40
2017/02/08 22:32:24 [debug] 1322#1322: *1 delete posted event 0000560E1F2E5DE0
2017/02/08 22:32:24 [debug] 1322#1322: *1 http run request: "/?"
2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream check client, write event:1, "/"
2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream recv(): -1 (11: Resource temporarily unavailable)
Then I took a look to my uwsgi log and found out that:
Invalid HTTP_HOST header: 'www.mysite.local'. You may need to add u'www.mysite.local' to ALLOWED_HOSTS.
[pid: 10903|app: 0|req: 2/4] 192.168.221.2 () {38 vars in 450 bytes} [Wed Feb 8 22:32:24 2017] GET / => generated 54098 bytes in 55 msecs (HTTP/1.1 400) 4 headers in 135 bytes (1 switches on core 0)
And adding www.mysite.local to the settings.py ALLOWED_HOSTS fixed the issue :)
ALLOWED_HOSTS = ['www.mysite.local']
Try something like gem uninstall rjb --version 1.3.4
.
Try using @Html.DropDownList
instead:
<td>Account: </td>
<td>@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))</td>
@Html.DropDownListFor
expects a lambda as its first argument, not a string
for the ID as you specify.
Other than that, without knowing what getUserAccounts()
consists of, suffice to say it needs to return some sort of collection (IEnumerable
for example) that has at least 1 object in it. If it returns null
the property in the ViewBag won't have anything.
(I don't have enough reputation to comment on toscho's answer.)
I have no experience with screen readers and I'm sure your points are valid.
However as far as using a keyboard to manipulate selects, it is trivial to select any option by using the keyboard:
TAB to the control
SPACE to open the select list
UP or DOWN arrows to scroll to the desired list item
ENTER to select the desired item
Only on ENTER does the onchange or (JQuery .change()) event fire.
While I personally would not use a form control for simple menus, there are many web applications that use form controls to change the presentation of the page (eg., sort order.) These can be implemented either by AJAX to load new content into the page, or, in older implementations, by triggering new page loads, which is essentially a page link.
IMHO these are valid uses of a form control.
As an echo to @Bactisme's response, the way one would go about retrieving the current timestamp (in milliseconds, for example) is:
msec := time.Now().UnixNano() / 1000000
Resource: https://gobyexample.com/epoch
$ for M in `perldoc -t perllocal|grep Module |sed -e 's/^.*" //'`; do V=`perldoc -t perllocal|awk "/$M/{y=1;next}y" |grep VERSION |head -n 1`; printf "%30s %s\n" "$M" "$V"; done |sort
Class::Inspector * "VERSION: 1.28"
Crypt::CBC * "VERSION: 2.33"
Crypt::Rijndael * "VERSION: 1.11"
Data::Dump * "VERSION: 1.22"
DBD::Oracle * "VERSION: 1.68"
DBI * "VERSION: 1.630"
Digest::SHA * "VERSION: 5.92"
ExtUtils::MakeMaker * "VERSION: 6.84"
install * "VERSION: 6.84"
IO::SessionData * "VERSION: 1.03"
IO::Socket::SSL * "VERSION: 2.016"
JSON * "VERSION: 2.90"
MIME::Base64 * "VERSION: 3.14"
MIME::Base64 * "VERSION: 3.14"
Mozilla::CA * "VERSION: 20141217"
Net::SSLeay * "VERSION: 1.68"
parent * "VERSION: 0.228"
REST::Client * "VERSION: 271"
SOAP::Lite * "VERSION: 1.08"
Task::Weaken * "VERSION: 1.04"
Term::ReadKey * "VERSION: 2.31"
Test::Manifest * "VERSION: 1.23"
Test::Simple * "VERSION: 1.001002"
Text::CSV_XS * "VERSION: 1.16"
Try::Tiny * "VERSION: 0.22"
XML::LibXML * "VERSION: 2.0108"
XML::NamespaceSupport * "VERSION: 1.11"
XML::SAX::Base * "VERSION: 1.08"
This is a subjective opinion, but I think a text editor shouldn't do everything and the kitchen sink. I prefer lightweight flexible and powerful (in their specialized fields) editors. Although being mostly a Windows user, I like the Unix philosophy of having lot of specialized tools that you can pipe together (like the UnxUtils) rather than a monster doing everything, but not necessarily as you would like it!
Find in files is on the border of these extra features, but useful when you can double-click on a found line to open the file at the right line. Note that initially, in SciTE it was just a Tools call to grep or equivalent!
FTP is very close to off topic, although it can be seen as an extended open/save dialog.
Replace in files is too much IMO: it is dangerous (you can mess lot of files at once) if you have no preview, etc. I would rather use a specialized tool I chose, perhaps among those in Multi line search and replace tool.
To answer the question, looking at N++, I see a Run menu where you can launch any tool, with assignment of a name and shortcut key. I see also Plugins > NppExec, which seems able to launch stuff like sed (not tried it).
In version 1.28 of Visual Studio Code "files.exclude"
must be placed within a settings
node.
Resulting in a workspace file that looks like:
{
"settings": {
"files.exclude": {
"**/node_modules": true
}
}
}
Your problem might actually be on this line:
<include layout="@layout/content_contact_list" />
Android Studio gets a little confused at time and takes the include layout
for the layout
tag. What's even more frustrating is that this could work the first time, fails to work with a modification on the Java/Kotlin code later, and then work again after a tweak that forces it to rebuild the binding. You may want to replace <include>
tags with something that populates it dynamically.
The underlying connection was closed: An unexpected error occurred on a receive.
This problem occurs when the server or another network device unexpectedly closes an existing Transmission Control Protocol (TCP) connection. This problem may occur when a time-out value on the server or on the network device is set too low. To resolve this problem, see resolutions A, D, E, F, and O. The problem can also occur if the server resets the connection unexpectedly, such as if an unhandled exception crashes the server process. Analyze the server logs to see if this may be the issue.
Resolution
To resolve this problem, make sure that you are using the most recent version of the .NET Framework.
Add a method to the class to override the GetWebRequest
method. This change lets you access the HttpWebRequest object. If you are using Microsoft Visual C#, the new method must be similar to the following.
class MyTestService:TestService.TestService
{
protected override WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);
//Setting KeepAlive to false
webRequest.KeepAlive = false;
return webRequest;
}
}
I think the size of the object matters as well. In one of my projects, we had declared and initialized a large two dimensional array that was making the application throw an out-of-memory exception. We moved the declaration out of the loop instead and cleared the array at the start of every iteration.
/<b>(.*?)<\/b>/g
Add g
(global) flag after:
/<b>(.*?)<\/b>/g.exec(str)
//^-----here it is
However if you want to get all matched elements, then you need something like this:
var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";
var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
return val.replace(/<\/?b>/g,'');
});
//result -> ["Bob", "20", "programming"]
If an element has attributes, regexp will be:
/<b [^>]+>(.*?)<\/b>/g.exec(str)
You can use one of Java template engines. I love this method because you are separating your logic from the view.
Java 8+:
<dependency>
<groupId>com.github.spullara.mustache.java</groupId>
<artifactId>compiler</artifactId>
<version>0.9.6</version>
</dependency>
Java 6/7:
<dependency>
<groupId>com.github.spullara.mustache.java</groupId>
<artifactId>compiler</artifactId>
<version>0.8.18</version>
</dependency>
Example template file:
{{#items}}
Name: {{name}}
Price: {{price}}
{{#features}}
Feature: {{description}}
{{/features}}
{{/items}}
Might be powered by some backing code:
public class Context {
List<Item> items() {
return Arrays.asList(
new Item("Item 1", "$19.99", Arrays.asList(new Feature("New!"), new Feature("Awesome!"))),
new Item("Item 2", "$29.99", Arrays.asList(new Feature("Old."), new Feature("Ugly.")))
);
}
static class Item {
Item(String name, String price, List<Feature> features) {
this.name = name;
this.price = price;
this.features = features;
}
String name, price;
List<Feature> features;
}
static class Feature {
Feature(String description) {
this.description = description;
}
String description;
}
}
And would result in:
Name: Item 1
Price: $19.99
Feature: New!
Feature: Awesome!
Name: Item 2
Price: $29.99
Feature: Old.
Feature: Ugly.
>>> item = set([0,1,2,3,4,5,6,7,8,9])
>>> z = set([2,3,4])
>>> print item - z
set([0, 1, 5, 6, 7, 8, 9])
// dict is Dictionary<string, Foo>
Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);
// or in C# 3.0:
var foos = dict.Values.ToArray();
// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag
---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';
@Directive({
selector: '[resize]',
host: { '(window:resize)': 'onResize()' } // Window resize listener
})
export class AutoResize {
element: ElementRef; // Element that associated to attribute.
$window: any;
constructor(_element: ElementRef) {
this.element = _element;
// Get instance of DOM window.
this.$window = angular.element(window);
this.onResize();
}
// Adjust height of element.
onResize() {
$(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
}
}
Although Chris Baxter's answer helps with original problem, it doesn't work in my case when application is hosted in virtual directory. After investigating the options, I finished with DIY solution.
ProperStyleBundle
class includes code borrowed from original CssRewriteUrlTransform
to properly transform relative paths within virtual directory. It also throws if file doesn't exist and prevents reordering of files in the bundle (code taken from BetterStyleBundle
).
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Optimization;
using System.Linq;
namespace MyNamespace
{
public class ProperStyleBundle : StyleBundle
{
public override IBundleOrderer Orderer
{
get { return new NonOrderingBundleOrderer(); }
set { throw new Exception( "Unable to override Non-Ordered bundler" ); }
}
public ProperStyleBundle( string virtualPath ) : base( virtualPath ) {}
public ProperStyleBundle( string virtualPath, string cdnPath ) : base( virtualPath, cdnPath ) {}
public override Bundle Include( params string[] virtualPaths )
{
foreach ( var virtualPath in virtualPaths ) {
this.Include( virtualPath );
}
return this;
}
public override Bundle Include( string virtualPath, params IItemTransform[] transforms )
{
var realPath = System.Web.Hosting.HostingEnvironment.MapPath( virtualPath );
if( !File.Exists( realPath ) )
{
throw new FileNotFoundException( "Virtual path not found: " + virtualPath );
}
var trans = new List<IItemTransform>( transforms ).Union( new[] { new ProperCssRewriteUrlTransform( virtualPath ) } ).ToArray();
return base.Include( virtualPath, trans );
}
// This provides files in the same order as they have been added.
private class NonOrderingBundleOrderer : IBundleOrderer
{
public IEnumerable<BundleFile> OrderFiles( BundleContext context, IEnumerable<BundleFile> files )
{
return files;
}
}
private class ProperCssRewriteUrlTransform : IItemTransform
{
private readonly string _basePath;
public ProperCssRewriteUrlTransform( string basePath )
{
_basePath = basePath.EndsWith( "/" ) ? basePath : VirtualPathUtility.GetDirectory( basePath );
}
public string Process( string includedVirtualPath, string input )
{
if ( includedVirtualPath == null ) {
throw new ArgumentNullException( "includedVirtualPath" );
}
return ConvertUrlsToAbsolute( _basePath, input );
}
private static string RebaseUrlToAbsolute( string baseUrl, string url )
{
if ( string.IsNullOrWhiteSpace( url )
|| string.IsNullOrWhiteSpace( baseUrl )
|| url.StartsWith( "/", StringComparison.OrdinalIgnoreCase )
|| url.StartsWith( "data:", StringComparison.OrdinalIgnoreCase )
) {
return url;
}
if ( !baseUrl.EndsWith( "/", StringComparison.OrdinalIgnoreCase ) ) {
baseUrl = baseUrl + "/";
}
return VirtualPathUtility.ToAbsolute( baseUrl + url );
}
private static string ConvertUrlsToAbsolute( string baseUrl, string content )
{
if ( string.IsNullOrWhiteSpace( content ) ) {
return content;
}
return new Regex( "url\\(['\"]?(?<url>[^)]+?)['\"]?\\)" )
.Replace( content, ( match =>
"url(" + RebaseUrlToAbsolute( baseUrl, match.Groups["url"].Value ) + ")" ) );
}
}
}
}
Use it like StyleBundle
:
bundles.Add( new ProperStyleBundle( "~/styles/ui" )
.Include( "~/Content/Themes/cm_default/style.css" )
.Include( "~/Content/themes/custom-theme/jquery-ui-1.8.23.custom.css" )
.Include( "~/Content/DataTables-1.9.4/media/css/jquery.dataTables.css" )
.Include( "~/Content/DataTables-1.9.4/extras/TableTools/media/css/TableTools.css" ) );
I have another possible answer for those wondering why event log entries are not showing up in the History tab of Task Scheduler for certain tasks, even though All Task History is enabled, the events for those tasks are viewable in the Event Log, and all other tasks show history just fine. In my case, I had created 13 new tasks. For 5 of them, events showed fine under History, but for the other 8, the History tab was completely blank. I even verified these tasks were enabled for history individually (and logging events) using Mick Wood's post about using the Event Viewer.
Then it hit me. I suddenly realized what all 8 had in common that the other 5 did not. They all had an ampersand (&) character in the event name. I created them by exporting the first task I created, "Sync E to N", renaming the exported file name, editing the XML contents, and then importing the new task. Windows Explorer happily let me rename the task, for example, to "Sync C to N & T", and Task Scheduler happily let me import it. However, with that pesky "&" in the name, it could not retrieve its history from the event log. When I deleted the original event, renamed the xml file to "Sync C to N and T", and imported it, voila, there were all of the log entries in the History tab in Task Scheduler.
It's basic step notation, consider the functionality of:
a[2:4:2]
What happens is the index is sliced between position 2 and 4, what the third variable does is it sets the step size starting from the first value. In this case it would return a[2], since a[4] is an upper bounds only two values are return and no second step takes place. The (-) minus operator simply reverses the step output.
There is a workaround which may help. You may "register" results for each set_fact iteration and then map that results to list:
---
- hosts: localhost
tasks:
- name: set fact
set_fact: foo_item="{{ item }}"
with_items:
- four
- five
- six
register: foo_result
- name: make a list
set_fact: foo="{{ foo_result.results | map(attribute='ansible_facts.foo_item') | list }}"
- debug: var=foo
Output:
< TASK: debug var=foo >
---------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
ok: [localhost] => {
"var": {
"foo": [
"four",
"five",
"six"
]
}
}
You are probably looking for the DATEDIFF function.
DATEDIFF ( datepart , startdate , enddate )
Where you code might look like this:
DATEDIFF ( hh , startdate , enddate )
You need to use <> operator:
while (<>) {
print $_; # or simply "print;"
}
Which can be compacted to:
print while (<>);
Arbitrary file:
open F, "<file.txt" or die $!;
while (<F>) {
print $_;
}
close F;
ldapwhoami -vvv -h <hostname> -p <port> -D <binddn> -x -w <passwd>
, where binddn
is the DN of the person whose credentials you are authenticating.
On success (i.e., valid credentials), you get Result: Success (0)
. On failure, you get ldap_bind: Invalid credentials (49)
.
Inline elements:
Block elements:
Inline-block elements:
From W3Schools:
An inline element has no line break before or after it, and it tolerates HTML elements next to it.
A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.
When you visualize this, it looks like this:
The image is taken from this page, which also talks some more about this subject.
This is because of wrong permission of phpMyAdmin
directory and the file config.inc.php
On *nix like OS set the permission of the directory and the file as follows
chmod -R 755 /path/to/phpMyAdmin
chmod 644 /path/to/phpMyAdmin/config.inc.php
If like me you run a Linux Virtual Machine which mount a Windows folder where phpMyAdmin
sources are located, edit config.inc.php
and add this line
$cfg['CheckConfigurationPermissions'] = false;
run command prompt as administrator and use '--user' flag eg. pip install --user --upgrade pandas
Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue
Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.
<table cellpadding="pixels"cellspacing="pixels"></table>
<td align="position"valign="position"></td>
cellpadding
="length in pixels" ~ The cellpadding attribute, used in the <table>
tag, specifies how much blank space to display in between the content of each table cell and its respective border. The value is defined as a length in pixels. Hence, a cellpadding="10"
attribute-value pair will display 10 pixels of blank space on all four sides of the content of each cell in that table.
cellspacing
="length in pixels" ~ The cellspacing attribute, also used in the <table>
tag, defines how much blank space to display in between adjacent table cells and in between table cells and the table border. The value is defined as a length in pixels. Hence, a cellspacing="10"
attribute-value pair will horizontally and vertically separate all adjacent cells in the respective table by a length of 10 pixels. It will also offset all cells from the table's frame on all four sides by a length of 10 pixels.
In git version 2.14.3,
You can remove upstream using
git branch --unset-upstream
The above command will also remove the tracking stream branch, hence if you want to rebase from repository you have use
git rebase origin master
instead of git pull --rebase
Sku is an int, can't be defaulted to string "sku". Please check Optional URI Parameters and Default Values
You should set a fixed value to your span's line-height
property:
.float, .twoline {
line-height: 100px;
}
Some of the codes are string heavy. Instead of creating substring which creates new object, we can just pass on indexes in recursive calls like below:
private static boolean isPalindrome(String str, int left, int right) {
if(left >= right) {
return true;
}
else {
if(str.charAt(left) == str.charAt(right)) {
return isPalindrome(str, ++left, --right);
}
else {
return false;
}
}
}
public static void main(String []args){
String str = "abcdcbb";
System.out.println(isPalindrome(str, 0, str.length()-1));
}
//This is The easiest I can Imagine .
// You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns
for(int rows=0;rows<array.length;rows++){
for(int columns=0;columns <array[rows].length;columns++){
System.out.print(array[rows][columns] + "\t" );}
System.out.println();}
You should not set ENV variables in package.json
. actionhero uses NODE_ENV
to allow you to change configuration options which are loaded from the files in ./config
. Check out the redis config file, and see how NODE_ENV is uses to change database options in NODE_ENV=test
If you want to use other ENV variables to set things (perhaps the HTTP port), you still don't need to change anything in package.json
. For example, if you set PORT=1234
in ENV and want to use that as the HTTP port in NODE_ENV=production
, just reference that in the relevant config file, IE:
# in config/servers/web.js
exports.production = {
servers: {
web: function(api){
return {
port: process.env.PORT
}
}
}
}
While the rules in C++03 about when you need typename
and template
are largely reasonable, there is one annoying disadvantage of its formulation
template<typename T>
struct A {
typedef int result_type;
void f() {
// error, "this" is dependent, "template" keyword needed
this->g<float>();
// OK
g<float>();
// error, "A<T>" is dependent, "typename" keyword needed
A<T>::result_type n1;
// OK
result_type n2;
}
template<typename U>
void g();
};
As can be seen, we need the disambiguation keyword even if the compiler could perfectly figure out itself that A::result_type
can only be int
(and is hence a type), and this->g
can only be the member template g
declared later (even if A
is explicitly specialized somewhere, that would not affect the code within that template, so its meaning cannot be affected by a later specialization of A
!).
To improve the situation, in C++11 the language tracks when a type refers to the enclosing template. To know that, the type must have been formed by using a certain form of name, which is its own name (in the above, A
, A<T>
, ::A<T>
). A type referenced by such a name is known to be the current instantiation. There may be multiple types that are all the current instantiation if the type from which the name is formed is a member/nested class (then, A::NestedClass
and A
are both current instantiations).
Based on this notion, the language says that CurrentInstantiation::Foo
, Foo
and CurrentInstantiationTyped->Foo
(such as A *a = this; a->Foo
) are all member of the current instantiation if they are found to be members of a class that is the current instantiation or one of its non-dependent base classes (by just doing the name lookup immediately).
The keywords typename
and template
are now not required anymore if the qualifier is a member of the current instantiation. A keypoint here to remember is that A<T>
is still a type-dependent name (after all T
is also type dependent). But A<T>::result_type
is known to be a type - the compiler will "magically" look into this kind of dependent types to figure this out.
struct B {
typedef int result_type;
};
template<typename T>
struct C { }; // could be specialized!
template<typename T>
struct D : B, C<T> {
void f() {
// OK, member of current instantiation!
// A::result_type is not dependent: int
D::result_type r1;
// error, not a member of the current instantiation
D::questionable_type r2;
// OK for now - relying on C<T> to provide it
// But not a member of the current instantiation
typename D::questionable_type r3;
}
};
That's impressive, but can we do better? The language even goes further and requires that an implementation again looks up D::result_type
when instantiating D::f
(even if it found its meaning already at definition time). When now the lookup result differs or results in ambiguity, the program is ill-formed and a diagnostic must be given. Imagine what happens if we defined C
like this
template<>
struct C<int> {
typedef bool result_type;
typedef int questionable_type;
};
A compiler is required to catch the error when instantiating D<int>::f
. So you get the best of the two worlds: "Delayed" lookup protecting you if you could get in trouble with dependent base classes, and also "Immediate" lookup that frees you from typename
and template
.
In the code of D
, the name typename D::questionable_type
is not a member of the current instantiation. Instead the language marks it as a member of an unknown specialization. In particular, this is always the case when you are doing DependentTypeName::Foo
or DependentTypedName->Foo
and either the dependent type is not the current instantiation (in which case the compiler can give up and say "we will look later what Foo
is) or it is the current instantiation and the name was not found in it or its non-dependent base classes and there are also dependent base classes.
Imagine what happens if we had a member function h
within the above defined A
class template
void h() {
typename A<T>::questionable_type x;
}
In C++03, the language allowed to catch this error because there could never be a valid way to instantiate A<T>::h
(whatever argument you give to T
). In C++11, the language now has a further check to give more reason for compilers to implement this rule. Since A
has no dependent base classes, and A
declares no member questionable_type
, the name A<T>::questionable_type
is neither a member of the current instantiation nor a member of an unknown specialization. In that case, there should be no way that that code could validly compile at instantiation time, so the language forbids a name where the qualifier is the current instantiation to be neither a member of an unknown specialization nor a member of the current instantiation (however, this violation is still not required to be diagnosed).
You can try this knowledge on this answer and see whether the above definitions make sense for you on a real-world example (they are repeated slightly less detailed in that answer).
The C++11 rules make the following valid C++03 code ill-formed (which was not intended by the C++ committee, but will probably not be fixed)
struct B { void f(); };
struct A : virtual B { void f(); };
template<typename T>
struct C : virtual B, T {
void g() { this->f(); }
};
int main() {
C<A> c; c.g();
}
This valid C++03 code would bind this->f
to A::f
at instantiation time and everything is fine. C++11 however immediately binds it to B::f
and requires a double-check when instantiating, checking whether the lookup still matches. However when instantiating C<A>::g
, the Dominance Rule applies and lookup will find A::f
instead.
Use strpos()
:
if (strpos($string2, 'http') === 0) {
// It starts with 'http'
}
Remember the three equals signs (===
). It will not work properly if you only use two. This is because strpos()
will return false
if the needle cannot be found in the haystack.
It is strange, but why this topic is not have this answer:
$lastKey = array_keys($array)[count($array)-1];
The other answers here do a good job of explaining the issue, so I won't repeat that here. But there is one solution that can resolve it that isn't listed yet: simply run make clean
, then rerun make
.
Having make remove any already compiled files will prevent make from having any files to compare the timestamps of, resolving the warning.
I started to get the 500 for debug=False in the form of
django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found.
or...
django.urls.exceptions.NoReverseMatch: Reverse for 'about' not found.
when raising django.core.exceptions.ValidationError instead of raising rest_framework.serializers.ValidationError
To be fair, it was already raising a 500 before, but as a ValidationError, with debug=False, this changed into the NoReverseMatch.
Easiest route is probably upgrading or re-installing the Java Runtime Environment (JRE).
Or this:
C:\Program Files\Java\j2re1.4.2_04\bin\javaw.exe" -jar "%1" %
(Note: the part starting with 'javaw' must be exactly like that; the other part of the path name can vary depending on which version of Java you're using) then press the OK buttons until all the dialogs are closed.Which was stolen from here: http://windowstipoftheday.blogspot.com/2005/10/setting-jar-file-association.html
This what worked for me. set HeaderStyle-Width="5%", in the footer set textbox width Width="15",also set the width of your gridview to 100%. following is the one of the column of my gridview.
<asp:TemplateField HeaderText = "sub" HeaderStyle-ForeColor="White" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:Label ID="sub" runat="server" Font-Size="small" Text='<%# Eval("sub")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_sub" runat="server" Text='<%# Eval("sub")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txt_sub" runat="server" Width="15"></asp:TextBox>
</FooterTemplate>
Simple jQuery way:
This is what I use:
DictionaryObj being the JavaScript dictionary object you want to go through. And value, key of course being the names of them in the dictionary.
$.each(DictionaryObj, function (key, value) {
$("#storeDuplicationList")
.append($("<li></li>")
.attr("value", key)
.text(value));
});
iirc :
cat filename.txt | awk '{ print $2 $4 }'
or, as mentioned in the comments :
awk '{ print $2 $4 }' filename.txt
This is how I restore RecyclerView position with GridLayoutManager after rotation when you need to reload data from internet with AsyncTaskLoader.
Make a global variable of Parcelable and GridLayoutManager and a static final string:
private Parcelable savedRecyclerLayoutState;
private GridLayoutManager mGridLayoutManager;
private static final String BUNDLE_RECYCLER_LAYOUT = "recycler_layout";
Save state of gridLayoutManager in onSaveInstance()
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(BUNDLE_RECYCLER_LAYOUT,
mGridLayoutManager.onSaveInstanceState());
}
Restore in onRestoreInstanceState
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//restore recycler view at same position
if (savedInstanceState != null) {
savedRecyclerLayoutState = savedInstanceState.getParcelable(BUNDLE_RECYCLER_LAYOUT);
}
}
Then when loader fetches data from internet you restore recyclerview position in onLoadFinished()
if(savedRecyclerLayoutState!=null){
mGridLayoutManager.onRestoreInstanceState(savedRecyclerLayoutState);
}
..of course you have to instantiate gridLayoutManager inside onCreate. Cheers
select propety
Row Source Type => Value List
Code :
ListbName.ColumnCount=2
ListbName.AddItem "value column1;value column2"
SELECT *
FROM DBA_OBJECTS
WHERE OBJECT_TYPE = 'VIEW'
Creating a dictionary as it has mentioned, but in this case each key has the name of the object name that you want to create. Then the value is set as the class you want to instantiate, see for example:
class MyClass:
def __init__(self, name):
self.name = name
self.checkme = 'awesome {}'.format(self.name)
...
instanceNames = ['red', 'green', 'blue']
# Here you use the dictionary
holder = {name: MyClass(name=name) for name in instanceNames}
Then you just call the holder key and you will have all the properties and methods of your class available for you.
holder['red'].checkme
output:
'awesome red'
I have faced same problem from java heap size.
I have two solutions if you are using java 5(1.5).
just install jdk1.6 and go to the preferences of eclipse and set the jre path of jav1 1.6 as you have installed.
Check your VM argument and let it be whatever it is. just add one line below of all the arguments present in VM arguments as -Xms512m -Xmx512m -XX:MaxPermSize=...m(192m).
I think it will work...
If you are trying to do that in a Portable Class Library PCL (like me), then here is how you can do it :)
public class Foo
{
public string A {get;set;}
[Special]
public string B {get;set;}
}
var type = typeof(Foo);
var specialProperties = type.GetRuntimeProperties()
.Where(pi => pi.PropertyType == typeof (string)
&& pi.GetCustomAttributes<Special>(true).Any());
You can then check on the number of properties that have this special property if you need to.
For Python 3:
bytes(apple,'iso-8859-1').decode('utf-8')
I used this for a text incorrectly encoded as iso-8859-1 (showing words like VeÅ\x99ejné) instead of utf-8. This code produces correct version Verejné.
Note that there are some cases where if you have defined your own custom class and you want to keep the attributes then you should use copy.copy()
or copy.deepcopy()
rather than the alternatives, for example in Python 3:
import copy
class MyList(list):
pass
lst = MyList([1,2,3])
lst.name = 'custom list'
d = {
'original': lst,
'slicecopy' : lst[:],
'lstcopy' : lst.copy(),
'copycopy': copy.copy(lst),
'deepcopy': copy.deepcopy(lst)
}
for k,v in d.items():
print('lst: {}'.format(k), end=', ')
try:
name = v.name
except AttributeError:
name = 'NA'
print('name: {}'.format(name))
Outputs:
lst: original, name: custom list
lst: slicecopy, name: NA
lst: lstcopy, name: NA
lst: copycopy, name: custom list
lst: deepcopy, name: custom list
Polish-> English (VS on MAC) answer: When I started a project and was forced to download Visual Studio, went to their page and saw that Microsoft logo I knew there would be problems... And here it is. It occurred difficult to change the language of VS on Mac. My OS is purely English and only because of the fact I downloaded it using a browser with Polish set as a default language I got the wrong version. I had to reinstall the version to the newest and then Visual Studio Community -> Preferences(in the environment section) -> Visual Style-> User Interface Language.
It translates to polish: Visual Studio Community -> Preferencje -> Styl Wizualny w sekcji Srodowisko -> Jezyk interfejsu uzytkownika -> English.
If you don't see such an option then, as I was, you are forced to upgrade this crappy VS to the newest version.
You can do it with a custom view, like this RoundAppBar and RoundBottomAppBar.
Here a path
is used to clipPath
the canvas.
Only stopped containers can be listed using:
docker ps --filter "status=exited"
or
docker ps -f "status=exited"
WebRequest request = WebRequest.Create("http://www.google.com");
try
{
request.GetResponse();
}
catch //If exception thrown then couldn't get response from address
{
MessageBox.Show("The URL is incorrect");`
}
Instead of:
df2 = df1.filter("Status=2" || "Status =3")
Try:
df2 = df1.filter($"Status" === 2 || $"Status" === 3)
IP Version 4 Only ...
Imports System.Net
Module MainLine
Sub Main()
Dim hostName As String = Dns.GetHostName
Console.WriteLine("Host Name: " & hostName & vbNewLine)
Console.WriteLine("IP Version 4 Address(es):")
For Each address In Dns.GetHostEntry(hostName).AddressList().
Where(Function(p) p.AddressFamily = Sockets.AddressFamily.InterNetwork)
Console.WriteLine(vbTab & address.ToString)
Next
Console.ReadKey()
End Sub
End Module
public function getYear($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("Y");
}
public function getMonth($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("m");
}
public function getDay($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("d");
}
One statement can be written as such:
someValues.forEach(x => console.log(x));
or multiple statements can be enclosed in {}
like this:
someValues.forEach(x => { let a = 2 + x; console.log(a); });
echo $VAR_REMOTEROOTPASS | ssh -tt -i $PATH_TO_KEY/id_mykey $VAR_REMOTEUSER@$varRemoteHost
echo \"$varCommand\" | sudo bash
It seems you need to follow the installation instructions in Daniel DiPaolo's answer to try one of the two approaches below
Hopefully that will resolve your issue!
To get a timestamp
from Date()
, you'll need to divide getTime()
by 1000
, i.e. :
Date currentDate = new Date();
currentDate.getTime() / 1000;
// 1397132691
or simply:
long unixTime = System.currentTimeMillis() / 1000L;
How to create FLUTTER project in android studio in fedora:-
I have installed following:- 1 Android studio 2 Then do following:-
Start Android Studio. Open plugin preferences (Preferences > Plugins on macOS, File > Settings > Plugins on Windows & Linux). Select Marketplace, select the Flutter plugin and click Install. Click Yes when prompted to install the Dart plugin. Click Restart when prompted.
4:- Now create project by clicking new flutter project and do following:- * Choose Flutter Application from the list of configurations * Fill the name and other things * For flutter sdk click and install flutter sdk and specify the location of downloading and after downloading completion, choose that sdk path, this will load your FLutter sdk.
Rest do steps as per your need to create project
The xargs
command takes white space characters (tabs, spaces, new lines) as delimiters.
You can narrow it down only for the new line characters ('\n') with -d
option like this:
ls *.mp3 | xargs -d '\n' mplayer
It works only with GNU xargs.
For BSD systems, use the -0
option like this:
ls *.mp3 | xargs -0 mplayer
This method is simpler and works with the GNU xargs as well.
For MacOS:
ls *.mp3 | tr \\n \\0 | xargs -0 mplayer
I know there are so many examples of this question but what I found I am putting here to share my Idea. there are two ways to chain constructor. In Same class you can use this keyword. in Inheritance, you need to use super keyword.
import java.util.*;
import java.lang.*;
class Test
{
public static void main(String args[])
{
Dog d = new Dog(); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.
Dog cs = new Dog("Bite"); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.
// You need to Explicitly tell the java compiler to use Argument constructor so you need to use "super" key word
System.out.println("------------------------------");
Cat c = new Cat();
Cat caty = new Cat("10");
System.out.println("------------------------------");
// Self s = new Self();
Self ss = new Self("self");
}
}
class Animal
{
String i;
public Animal()
{
i = "10";
System.out.println("Animal Constructor :" +i);
}
public Animal(String h)
{
i = "20";
System.out.println("Animal Constructor Habit :"+ i);
}
}
class Dog extends Animal
{
public Dog()
{
System.out.println("Dog Constructor");
}
public Dog(String h)
{
System.out.println("Dog Constructor with habit");
}
}
class Cat extends Animal
{
public Cat()
{
System.out.println("Cat Constructor");
}
public Cat(String i)
{
super(i); // Calling Super Class Paremetrize Constructor.
System.out.println("Cat Constructor with habit");
}
}
class Self
{
public Self()
{
System.out.println("Self Constructor");
}
public Self(String h)
{
this(); // Explicitly calling 0 args constructor.
System.out.println("Slef Constructor with value");
}
}
const data = [{
realName: 'Sean Bean',
characterName: 'Eddard “Ned” Stark'
}, {
realName: 'Kit Harington',
characterName: 'Jon Snow'
}, {
realName: 'Peter Dinklage',
characterName: 'Tyrion Lannister'
}, {
realName: 'Lena Headey',
characterName: 'Cersei Lannister'
}, {
realName: 'Michelle Fairley',
characterName: 'Catelyn Stark'
}, {
realName: 'Nikolaj Coster-Waldau',
characterName: 'Jaime Lannister'
}, {
realName: 'Maisie Williams',
characterName: 'Arya Stark'
}];
const filterKeys = ['realName', 'characterName'];
const multiFilter = (data = [], filterKeys = [], value = '') => data.filter((item) => filterKeys.some(key => item[key].toString().toLowerCase().includes(value.toLowerCase()) && item[key]));
let filteredData = multiFilter(data, filterKeys, 'stark');
console.info(filteredData);
/* [{
"realName": "Sean Bean",
"characterName": "Eddard “Ned” Stark"
}, {
"realName": "Michelle Fairley",
"characterName": "Catelyn Stark"
}, {
"realName": "Maisie Williams",
"characterName": "Arya Stark"
}]
*/
WARNING! THIS WILL DELETE THE ENTIRE GIT HISTORY FOR YOUR SUBMODULE. ONLY DO THIS IF YOU CREATED THE SUBMODULE BY ACCIDENT. CERTAINLY NOT WHAT YOU WANT TO DO IN MOST CASES.
I think you have to go inside week1 folder and delete the .git folder:
sudo rm -Rf .git
then go back to top level folder and do:
git add .
then do a commit and push the code.
Yes, the new limit is approximately 1 million rows.
Since sync XHR is being deprecated, it's best not to rely on that. If you need to do a sync POST request, you can use the following helpers inside of a service to simulate a form post.
It works by creating a form with hidden inputs which is posted to the specified URL.
//Helper to create a hidden input
function createInput(name, value) {
return angular
.element('<input/>')
.attr('type', 'hidden')
.attr('name', name)
.val(value);
}
//Post data
function post(url, data, params) {
//Ensure data and params are an object
data = data || {};
params = params || {};
//Serialize params
const serialized = $httpParamSerializer(params);
const query = serialized ? `?${serialized}` : '';
//Create form
const $form = angular
.element('<form/>')
.attr('action', `${url}${query}`)
.attr('enctype', 'application/x-www-form-urlencoded')
.attr('method', 'post');
//Create hidden input data
for (const key in data) {
if (data.hasOwnProperty(key)) {
const value = data[key];
if (Array.isArray(value)) {
for (const val of value) {
const $input = createInput(`${key}[]`, val);
$form.append($input);
}
}
else {
const $input = createInput(key, value);
$form.append($input);
}
}
}
//Append form to body and submit
angular.element(document).find('body').append($form);
$form[0].submit();
$form.remove();
}
Modify as required for your needs.
you need to convert to char first because converting to int adds those days to 1900-01-01
select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))
here are some examples
select CONVERT (datetime,5)
1900-01-06 00:00:00.000
select CONVERT (datetime,20100101)
blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit
convert to char first
declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))
If you have 2-Step Verification step up on your Gmail account, you will need to generate an App password. https://support.google.com/accounts/answer/185833?p=app_passwords_sa&hl=en&visit_id=636903322072234863-1319515789&rd=1 Select How to generate an App password option and follow the steps provided. Copy and paste the generated App password somewhere as you will not be able to recover it after you click DONE.
Spring is three things.
The problem is that Spring DI is really well thought out, the wrappers around other things are really well thought out in that the other things thought everything out and Spring just nicely wraps it. The Spring implementations of MVC and REST and all the other stuff is not as well done (YMMV, IMHO) but there are exceptions (Spring Security is da bomb). So I tend to use Spring for DI, and its cool wrappers but prefer other stuff for Web (I like Tapestry a lot), REST (Jersey is really robust), etc.
With second precision, you can print tv_sec
field of timeval
structure that you get from gettimeofday()
function. For example:
#include <sys/time.h>
#include <stdio.h>
int main()
{
struct timeval tv;
gettimeofday(&tv, NULL);
printf("Seconds since Jan. 1, 1970: %ld\n", tv.tv_sec);
return 0;
}
Example of compiling and running:
$ gcc -Wall -o test ./test.c
$ ./test
Seconds since Jan. 1, 1970: 1343845834
Note, however, that its been a while since epoch and so long int
is used to fit a number of seconds these days.
There are also functions to print human-readable times. See this manual page for details. Here goes an example using ctime()
:
#include <time.h>
#include <stdio.h>
int main()
{
time_t clk = time(NULL);
printf("%s", ctime(&clk));
return 0;
}
Example run & output:
$ gcc -Wall -o test ./test.c
$ ./test
Wed Aug 1 14:43:23 2012
$
custom validation step by step
Html template
<form [ngFormModel]="demoForm">
<input
name="NotAllowSpecialCharacters"
type="text"
#demo="ngForm"
[ngFormControl] ="demoForm.controls['spec']"
>
<div class='error' *ngIf="demo.control.touched">
<div *ngIf="demo.control.hasError('required')"> field is required.</div>
<div *ngIf="demo.control.hasError('invalidChar')">Special Characters are not Allowed</div>
</div>
</form>
Component App.ts
import {Control, ControlGroup, FormBuilder, Validators, NgForm, NgClass} from 'angular2/common';
import {CustomValidator} from '../../yourServices/validatorService';
under class define
demoForm: ControlGroup;
constructor( @Inject(FormBuilder) private Fb: FormBuilder ) {
this.demoForm = Fb.group({
spec: new Control('', Validators.compose([Validators.required, CustomValidator.specialCharValidator])),
})
}
under {../../yourServices/validatorService.ts}
export class CustomValidator {
static specialCharValidator(control: Control): { [key: string]: any } {
if (control.value) {
if (!control.value.match(/[-!$%^&*()_+|~=`{}\[\]:";#@'<>?,.\/]/)) {
return null;
}
else {
return { 'invalidChar': true };
}
}
}
}
A Callable is an object that has the __call__
method. This means you can fake callable functions or do neat things like Partial Function Application where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as Currying in functional programming circles).
Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string. This can produce errors where the interpreter attempts to execute a non-callable application. You can see this happening in a python interpreter by doing something like the transcript below.
[nigel@k9 ~]$ python
Python 2.5 (r25:51908, Nov 6 2007, 15:55:44)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'aaa'() # <== Here we attempt to call a string.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>>
Use this.finishAffinity(); on that button instead of finish(); If it does not work then you can also try by adding android:noHistory="true" in your manifest and then finish your activity by uisng finish(); or finishAffinity();
Hope it helps....:)
With these two steps we can check if it LL(1) or not. Both of them have to be satisfied.
1.If we have the production:A->a1|a2|a3|a4|.....|an. Then,First(a(i)) intersection First(a(j)) must be phi(empty set)[a(i)-a subscript i.]
2.For every non terminal 'A',if First(A) contains epsilon Then First(A) intersection Follow(A) must be phi(empty set).
Use overflow-y: auto;
on the div.
Also, you should be setting the width as well.
It should probably be noted that the for
loop is faster than the foreach
. So for the original post, if you are worried about performance on a critical component like a renderer, use a for
loop.
Reference: In .NET, which loop runs faster, 'for' or 'foreach'?
To do this manually, you'd need something like:
List<string> existing;
if (!myDic.TryGetValue(key, out existing)) {
existing = new List<string>();
myDic[key] = existing;
}
// At this point we know that "existing" refers to the relevant list in the
// dictionary, one way or another.
existing.Add(extraValue);
However, in many cases LINQ can make this trivial using ToLookup
. For example, consider a List<Person>
which you want to transform into a dictionary of "surname" to "first names for that surname". You could use:
var namesBySurname = people.ToLookup(person => person.Surname,
person => person.FirstName);
A Task can be seen as a convenient and easy way to execute something asynchronously and in parallel.
Normally a Task is all you need, I cannot remember if I have ever used a thread for something else than experimentation.
You can accomplish the same with a thread (with lots of effort) as you can with a task.
Thread
int result = 0;
Thread thread = new System.Threading.Thread(() => {
result = 1;
});
thread.Start();
thread.Join();
Console.WriteLine(result); //is 1
Task
int result = await Task.Run(() => {
return 1;
});
Console.WriteLine(result); //is 1
A task will by default use the Threadpool, which saves resources as creating threads can be expensive. You can see a Task as a higher level abstraction upon threads.
As this article points out, task provides following powerful features over thread.
Tasks are tuned for leveraging multicores processors.
If system has multiple tasks then it make use of the CLR thread pool internally, and so do not have the overhead associated with creating a dedicated thread using the Thread. Also reduce the context switching time among multiple threads.
Wait on a set of tasks, without a signaling construct.
We can chain tasks together to execute one after the other.
Establish a parent/child relationship when one task is started from another task.
Child task exception can propagate to parent task.
Task support cancellation through the use of cancellation tokens.
Asynchronous implementation is easy in task, using’ async’ and ‘await’ keywords.
You can work it out for yourself given the bucket and the file name you specify in the upload request.
e.g. if your bucket is mybucket
and your file is named myfilename
:
https://mybucket.s3.amazonaws.com/myfilename
The s3
bit will be different depending on which region your bucket is in. For example, I use the south-east asia region so my urls are like:
https://mybucket.s3-ap-southeast-1.amazonaws.com/myfilename
Well, here is my "answer". It uses the fact that String.Split can be told hold many items it should split to (which I found lacking in the other answers):
string theString = "Some Very Large String Here";
var array = theString.Split(new [] { ' ' }, 2); // return at most 2 parts
// note: be sure to check it's not an empty array
string firstElem = array[0];
// note: be sure to check length first
string restOfArray = array[1];
This is very similar to the Substring
method, just by a different means.
you can use skimage.img_as_ubyte(yourdata)
it will make you numpy array ranges from 0->255
from skimage import img_as_ubyte
img = img_as_ubyte(data)
cv2.imshow("Window", img)
While drive allows you to edit plain text and HTML files I don't believe they allow the HTML to actually be displayed. I don't think they want people hosting websites from their drive space.
I ran into a couple of problems when I tried converting Kevin Fairchild's suggestion to work with strings containing spaces and special XML characters (&
, <
, >
) which were encoded.
The final version of my code (which doesn't answer the original question but may be useful to someone) looks like this:
CREATE TABLE #YourTable ([ID] INT, [Name] VARCHAR(MAX), [Value] INT)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'Oranges & Lemons',4)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'1 < 2',8)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)
SELECT [ID],
STUFF((
SELECT ', ' + CAST([Name] AS VARCHAR(MAX))
FROM #YourTable WHERE (ID = Results.ID)
FOR XML PATH(''),TYPE
/* Use .value to uncomment XML entities e.g. > < etc*/
).value('.','VARCHAR(MAX)')
,1,2,'') as NameValues
FROM #YourTable Results
GROUP BY ID
DROP TABLE #YourTable
Rather than using a space as a delimiter and replacing all the spaces with commas, it just pre-pends a comma and space to each value then uses STUFF
to remove the first two characters.
The XML encoding is taken care of automatically by using the TYPE directive.
It is most likely due to a cross-origin request, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Origin
to *
, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
Make sure that you haven't already used header
in another file, or you will get a nasty error. See the docs for more.
I ran into the same issue and figured out the problem. When you initialize a repository there aren't actually any branches. When you start a project run git add .
and then git commit
and the master branch will be created.
Without checking anything in you have no master branch. In that case you need to follow the steps other people here have suggested.
To answer the question:
What is the fastest way to stream live video using JavaScript? Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?
Yes, Websocket can be used to transmit over 30 fps and even 60 fps.
The main issue with Websocket is that it is low-level and you have to deal with may other issues than just transmitting video chunks. All in all it's a great transport for video and also audio.
You can paste the .jar file of the driver in the Java setup instead of adding it to each project that you create. Paste it in C:\Program Files\Java\jre7\lib\ext or wherever you have installed java.
After this you will find that the .jar driver is enlisted in the library folder of your created project(JRE system library) in the IDE. No need to add it repetitively.
!members.find()
I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:
def lst1 = []
assert !lst1.find()
def lst2 = [null]
assert !lst2.find()
def lst3 = [null,2,null]
assert lst3.find()
def lst4 = [null,null,null]
assert !lst4.find()
def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42
def lst6 = null;
assert !lst6.find()
The accepted answer didn't work with my table (thousands of rows, dynamic loading) but the code below works:
- (void)scrollToBottom:(id)sender {
if ([self.sections count] > 0) {
NSInteger idx = [self.sections count] - 1;
CGRect sectionRect = [self.tableView rectForSection:idx];
sectionRect.size.height = self.tableView.frame.size.height;
[self.tableView scrollRectToVisible:sectionRect animated:NO];
}
}
In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified:
Python-2.x
class A(object):
def __init__(self):
print "world"
class B(A):
def __init__(self):
print "hello"
super(B, self).__init__()
Python-3.x
class A(object):
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
super().__init__()
super()
is now equivalent to super(<containing classname>, self)
as per the docs.
If you want to see what is run in the database use dd(DB::getQueryLog())
to see what queries were run.
Try this
BookingDates::where('email', Input::get('email'))
->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();
$str = "
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br />
<br />
Greetings,<br />
Bill";
echo str_replace(array("\n", "\r"), '', $str); // echo $str in a single line
Since awk and perl are closely related...
Perl equivalents of @Dennis's awk solutions:
To print the second line:
perl -ne 'print if $. == 2' file
To print the second field:
perl -lane 'print $F[1]' file
To print the third field of the fifth line:
perl -lane 'print $F[2] if $. == 5' file
Perl equivalent of @Glenn's solution:
Print the j'th field of the i'th line
perl -lanse 'print $F[$j-1] if $. == $i' -- -i=5 -j=3 file
Perl equivalents of @Hai's solutions:
if you are looking for second columns that contains abc:
perl -lane 'print if $F[1] =~ /abc/' foo
... and if you want to print only a particular column:
perl -lane 'print $F[2] if $F[1] =~ /abc/' foo
... and for a particular line number:
perl -lane 'print $F[2] if $F[1] =~ /abc/ && $. == 5' foo
-l
removes newlines, and adds them back in when printing
-a
autosplits the input line into array @F
, using whitespace as the delimiter
-n
loop over each line of the input file
-e
execute the code within quotes
$F[1]
is the second element of the array, since Perl starts at 0
$.
is the line number
In jaxws-rt-2.2.10-ources.jar!\com\sun\xml\ws\transport\http\client\HttpTransportPipe.java
:
public Packet process(Packet request) {
Map<String, List<String>> userHeaders = (Map<String, List<String>>) request.invocationProperties.get(MessageContext.HTTP_REQUEST_HEADERS);
if (userHeaders != null) {
reqHeaders.putAll(userHeaders);
So, Map<String, List<String>>
from requestContext with key MessageContext.HTTP_REQUEST_HEADERS
will be copied to SOAP headers.
Sample of Application Authentication with JAX-WS via headers
BindingProvider.USERNAME_PROPERTY
and BindingProvider.PASSWORD_PROPERTY
keys are processed special way in HttpTransportPipe.addBasicAuth()
, adding standard basic authorization Authorization
header.
See also Message Context in JAX-WS
One great way to prevent reloading the page when submitting using a form is by adding return false
with your onsubmit attribute.
<form action="#" onsubmit="yourJsFunction();return false">
<input type="text"/>
<input type="submit"/>
</form>
I had this problem when having multiple versions of Android Studio, it doesn't look like you have multiple versions. But you do use IntelliJ IDEA Community Edition so are you sure you did install the plugins in Android Studio?.
I would have said this in a comment but I dont have enough rep
The original poster is quoting a GCC compiler error message, but even by reading this thread, it's not clear that the error message is properly addressed - except by @pmg's answer. (+1, btw)
This is a GCC error message that means the return-value of a function is 'void', but that you are trying to assign it to a non-void variable.
Example:
void myFunction()
{
//...stuff...
}
int main()
{
int myInt = myFunction(); //Compile error!
return 0;
}
You aren't allowed to assign void to integers, or any other type.
In the OP's situation:
int a = srand(time(NULL));
...is not allowed. srand()
, according to the documentation, returns void.
This question is a duplicate of:
I am responding, despite it being duplicates, because this is the top result on Google for this error message. Because this thread is the top result, it's important that this thread gives a succinct, clear, and easily findable result.
First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local
.
Another simple way is to use @reboot
in your crontab. Read the cron manpage for details.
However, if you want to do things properly, in addition to adding a script to /etc/init.d
you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d
which creates a symlink from some of the /etc/rc*
directories to your script. So, you'd need to do something like:
update-rc.d yourscriptname start 2
However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README
has some details and further pointers.
In addition to the answers already given you probably want to replace all the occurrences. To do this you will need a regular expression as follows :
str = str.replace(/-/g, ' '); // Replace all '-' with ' '
While not possible using a Literal, maybe a BitConverter can also be a solution?
Yes, s
stands for string. The json.loads
function does not take the file path, but the file contents as a string. Look at the documentation at https://docs.python.org/2/library/json.html!
ok i figure out :
DECLARE @dayName VARCHAR(9), @weekenda VARCHAR(9), @free INT
SET @weekenda =DATENAME(dw,GETDATE())
IF (@weekenda='Saturday' OR @weekenda='Sunday')
SET @free=1
ELSE
SET @free=0
than i use : .......... OR free=1
select t1.user_id,t2.user_id
from t1 left join t2 ON t1.user_id = t2.user_id
and t1.username=t2.username
and t1.first_name=t2.first_name
and t1.last_name=t2.last_name
try this. This will compare your table and find all matching pairs, if any mismatch return NULL on left.
You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:
protected $fillable = ['name', 'created_at'];
Regular Expressions are compiled before being used when using the second version. If you are going to executing it many times it is definatly better to compile it first. If not compiling every time you match for one off's is fine.
As Arnaud suggested in a comment to the original post, you should put this in your html header:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
I don't want any cred for this. I just want to make it more visible for anyone else that come here.
Do you have concurrency, i.e simultaneous users ? If you just run 1000 times the query straight, with just one thread, there will be almost no difference. Too easy for these engines :)
BUT I strongly suggest that you build a true load testing session, which means using an injector such as JMeter with 10, 20 or 50 users AT THE SAME TIME so you can really see a difference (try to embed this code inside a web page JMeter could query).
I just did it today on a single server (and a simple collection / table) and the results are quite interesting and surprising (MongoDb was really faster on writes & reads, compared to MyISAM engine and InnoDb engine).
This really should be part of your test : concurrency & MySQL engine. Then, data/schema design & application needs are of course huge requirements, beyond response times. Let me know when you get results, I'm also in need of inputs about this!
For an example of the css styles have a look at: http://getbootstrap.com/examples/theme/
If you want to see how the example looks without the bootstrap-theme.css file open up your browser developer tools and delete the link from the <head> of the example and then you can compare it.
I know this is an old question but posted it just in case anyone is looking for an example of how it looks like I was.
Update
bootstrap.css
= main css framework (grids, basic styles, etc)
bootstrap-theme.css
= extended styling (3D buttons, gradients etc). This file is optional and does not effect the functionality of bootstrap at all, it only enhances the appearance.
Update 2
With the release of v3.2.0 Bootstrap have added an option to view the theme css on the doc pages. If you go to one of the doc pages (css, components, javascript) you should see a "Preview theme" link at the bottom of the side nav which you can use to turn the theme css on and off.
Functional requirements specifies a function that a system or system component must be able to perform. It can be documented in various ways. The most common ones are written descriptions in documents, and use cases.
Use cases can be textual enumeration lists as well as diagrams, describing user actions. Each use case illustrates behavioural scenarios through one or more functional requirements. Often, though, an analyst will begin by eliciting a set of use cases, from which the analyst can derive the functional requirements that must be implemented to allow a user to perform each use case.
Functional requirements is what a system is supposed to accomplish. It may be
A typical functional requirement will contain a unique name and number, a brief summary, and a rationale. This information is used to help the reader understand why the requirement is needed, and to track the requirement through the development of the system.
LBushkin have already explained more about Non-functional requirements. I will add more.
Non-functional requirements are any other requirement than functional requirements. This are the requirements that specifies criteria that can be used to judge the operation of a system, rather than specific behaviours.
Non-functional requirements are in the form of "system shall be ", an overall property of the system as a whole or of a particular aspect and not a specific function. The system's overall properties commonly mark the difference between whether the development project has succeeded or failed.
Non-functional requirements - can be divided into two main categories:
- Performance requirements
- Interface requirements
- Operational requirements
- Resource requirements
- Verification requirements
- Acceptance requirements
- Documentation requirements
- Security requirements
- Portability requirements
- Quality requirements
- Reliability requirements
- Maintainability requirements
- Safety requirements
Whether or not a requirement is expressed as a functional or a non-functional requirement may depend:
Ex. A system may be required to present the user with a display of the number of records in a database. This is a functional requirement. How up-to-date [update] this number needs to be, is a non-functional requirement. If the number needs to be updated in real time, the system architects must ensure that the system is capable of updating the [displayed] record count within an acceptably short interval of the number of records changing.
References:
You can use the rpad
and lpad
functions to pad numbers to the right or to the left, respectively. Note that this does not work directly on numbers, so you'll have to use ::char
or ::text
to cast them:
SELECT RPAD(numcol::text, 3, '0'), -- Zero-pads to the right up to the length of 3
LPAD(numcol::text, 3, '0'), -- Zero-pads to the left up to the length of 3
FROM my_table
In simple words
$.ajax("info.txt").done(function(data) {
alert(data);
}).fail(function(data){
alert("Try again champ!");
});
if its get the info.text then it will alert and whatever function you add or if any how unable to retrieve info.text from the server then alert or error function.
In my case , I had removed gradlew and gradle folders from project. Reran clean build tasks through "Run Gradle Task" from Gradle Projects window in intellij
This is a variation on hexacyanide's answer above. This middleware also handles the 'data' event but does not wait for the data to be consumed before calling 'next'. This way both this middleware and bodyParser may coexist, consuming the stream in parallel.
app.use(function(req, res, next) {
req.rawBody = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
req.rawBody += chunk;
});
next();
});
app.use(express.bodyParser());
MultiBinding friendly version...
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
BindingOperations.GetBindingExpressionBase((ComboBox)sender, ComboBox.ItemsSourceProperty).UpdateTarget();
}
If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:
var data = context.MyEntities.AsNoTracking().Where(...).ToList();
As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.
I know its an old question but please note for the following differences between Math round and String format round:
decimal d1 = (decimal)1.125;
Math.Round(d1, 2).Dump(); // returns 1.12
d1.ToString("#.##").Dump(); // returns "1.13"
decimal d2 = (decimal)1.1251;
Math.Round(d2, 2).Dump(); // returns 1.13
d2.ToString("#.##").Dump(); // returns "1.13"
Swift 4.2 solution (taking 4.0 answer and updating for new enums to compile)
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
func updateLabel() {
myLabel.fadeTransition(0.4)
myLabel.text = "Hello World"
}
you can use this too
.parent:hover * {
/* ... */
}
_x000D_
As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try
block. Try changing your code to:
try{
Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
throw new MojException("Bledne dane");
}
Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.
The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.
plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) ) )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
}
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))
Kotlin
extension for showing the keyboard on focus.
This is a combination of previous responses, which where either too long or incomplete.
This extension posts a runnable on the message queue which shows the soft keyboard after requesting focus:
fun View.showSoftKeyboard() {
post {
if (this.requestFocus()) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
}
Call it from any view when needed afterwards:
editText.showSoftKeyboard()
What you need is the function strftime:
Time.now.strftime("%Y-%d-%m %H:%M:%S %Z")
If the issue reported from MainActivity.java then replace
import android.support.v7.app.AppCompatActivity;
with
import androidx.appcompat.app.AppCompatActivity;
$('html, body').animate({scrollTop:1200},'50');
You can do this!
Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...
So you can copy as in your first example without any problem :
String s = "hello";
String backup_of_s = s;
s = "bye";
To me, this looks like the simplest/fastest:
$('form input[type=submit]').click(function() { // attach the listener to your button
var yourWantedObjectIsHere = $(this.form); // use the native JS object with `this`
});
Playstore + Google Play Services In Linux(Ubuntu 14.04)
Download Google apps (GoogleLoginService.apk , GoogleServicesFramework.apk )
from here http://www.securitylearn.net/2013/08/31/google-play-store-on-android-emulator/
and Download ( Phonesky.apk) from here https://basketbuild.com/filedl/devs?dev=dankoman&dl=dankoman/Phonesky.apk
GO TO ANDROID SDK LOCATION>>
cd -Android SDK's tools Location-
TO RUN EMULATOR>>
Android/Sdk/tools$ ./emulator64-x86 -avd Kitkat -partition-size 566 -no-audio -no-boot-anim
SET PERMISSIONS>>
cd Android/Sdk/platform-tools platform-tools$ adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system
platform-tools$ adb shell chmod 777 /system/app
platform-tools$ adb push /home/nazmul/Downloads/GoogleLoginService.apk /system/app/.
PUSH PLAY APKS >>
platform-tools$ adb push /home/nazmul/Downloads/GoogleServicesFramework.apk /system/app/. platform-tools$ adb push /home/nazmul/Downloads/Phonesky.apk /system/app/. platform-tools$ adb shell rm /system/app/SdkSetup*
You can simply add this CSS to your header
<link href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet' type='text/css'>
next add this code in place where you want to display a glyph symbol.
<div class="fa fa-search"></div> <!-- smaller -->
<div class="fa fa-search fa-2x"></div> <!-- bigger -->
Have fun.
Driver for Huawei was not found. So I've been using the universal ADB driver:
ADBDriverInstaller
and Run the file. Make sure you have connected your device through USB to your computer.Restart
button. Before doing that read this link:
(The above. in brief, says to press Restart button in the dialog box. Select Troubleshoot. Select Advance Option. Select Startup Setting. Press Restart. After system's been restarted, on the appearing screen press 7)
ADBDriverInstaller
file again. Select your device from the options. Press install. And it's done :)
If using another library is an option, the following may be easier:
package for_so;
import java.io.File;
import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;
public class Q7704827_SimpleRead
{
public static void
main(String[] args)
{
String fileName = args[0];
TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
String recipient = emailNode.nextTextFieldE("recipient");
String sender = emailNode.nextTextFieldE("sender");
String subject = emailNode.nextTextFieldE("subject");
String description = emailNode.nextTextFieldE("description");
emailNode.verifyNoMoreChildren();
System.out.println("recipient = " + recipient);
System.out.println("sender = " + sender);
System.out.println("subject = " + subject);
System.out.println("desciption = " + description);
}
}
The library and its documentation are at rasmustorkel.com
Here is a modern implementation that accounts for Set
and Map
too:
export function deepClone<T extends object>(value: T): T {
if (typeof value !== 'object' || value === null) {
return value;
}
if (value instanceof Set) {
return new Set(Array.from(value, deepClone)) as T;
}
if (value instanceof Map) {
return new Map(Array.from(value, ([k, v]) => [k, deepClone(v)])) as T;
}
if (value instanceof Date) {
return new Date(value) as T;
}
if (value instanceof RegExp) {
return new RegExp(value.source, value.flags) as T;
}
return Object.keys(value).reduce((acc, key) => {
return Object.assign(acc, { [key]: deepClone(value[key]) });
}, (Array.isArray(value) ? [] : {}) as T);
}
Trying it out:
deepClone({
test1: { '1': 1, '2': {}, '3': [1, 2, 3] },
test2: [1, 2, 3],
test3: new Set([1, 2, [1, 2, 3]]),
test4: new Map([['1', 1], ['2', 2], ['3', 3]])
});
test1:
1: 1
2: {}
3: [1, 2, 3]
test2: Array(3)
0: 1
1: 2
2: 3
test3: Set(3)
0: 1
1: 2
2: [1, 2, 3]
test4: Map(3)
0: {"1" => 1}
1: {"2" => 2}
2: {"3" => 3}
This works:
sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"
Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)
Just keep in mind that:
obj= "foo"
is correct; obj="foo"
is not.The easiest and most intuitive solution for me was to combine the column names using get_level_values. This prevents duplicate column names when you do more than one aggregation on the same column:
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
df.columns = level_one + level_two
If you want a separator between columns, you can do this. This will return the same thing as Seiji Armstrong's comment on the accepted answer that only includes underscores for columns with values in both index levels:
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
column_separator = ['_' if x != '' else '' for x in level_two]
df.columns = level_one + column_separator + level_two
I know this does the same thing as Andy Hayden's great answer above, but I think it is a bit more intuitive this way and is easier to remember (so I don't have to keep referring to this thread), especially for novice pandas users.
This method is also more extensible in the case where you may have 3 column levels.
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
level_three = df.columns.get_level_values(2).astype(str)
df.columns = level_one + level_two + level_three
I have also faced same issue when I work with Hibernate and Spring Jpa Data Repository. I forgot to place @Transactional
on spring data repository method.
Its working for me after annotating with @Transactional
.
We can do this by setting access to JsonProperty.Access.WRITE_ONLY
while declaring the property.
@JsonProperty( value = "password", access = JsonProperty.Access.WRITE_ONLY)
@SerializedName("password")
private String password;
request.getSession()
will return a current session. if current session does not exist, then it will create a new one.
request.getSession(true)
will return current session. If current session does not exist, then it will create a new session.
So basically there is not difference between both method.
request.getSession(false)
will return current session if current session exists. If not, it will not create a new session.
To extract STRING
, try:
myString = '123STRINGabc'
startString = '123'
endString = 'abc'
mySubString=myString[myString.find(startString)+len(startString):myString.find(endString)]
I cannot yet comment (getting started on the site) but added a more generic version of Jerry Coffin's fantastic ctype's derived class to his post.
Thanks Jerry for the super idea.
(Because it must be peer-reviewed, adding it here too temporarily)
struct SeparatorReader: std::ctype<char>
{
template<typename T>
SeparatorReader(const T &seps): std::ctype<char>(get_table(seps), true) {}
template<typename T>
std::ctype_base::mask const *get_table(const T &seps) {
auto &&rc = new std::ctype_base::mask[std::ctype<char>::table_size]();
for(auto &&sep: seps)
rc[static_cast<unsigned char>(sep)] = std::ctype_base::space;
return &rc[0];
}
};
No, you have no way to get the "name" from the value in C++ because all the symbols are discarded during compilation.
You may need this way X Macros
To extend Ted Cambron's answer above and something that hasn't been addressed here: If you remove all line breaks indiscriminately from a chunk of entered text, you will end up with paragraphs running into each other without spaces when you output that text later. This is what I use:
sub cleanLines{
my $text = shift;
$text =~ s/\r/ /; #replace \r with space
$text =~ s/\n/ /; #replace \n with space
$text =~ s/ / /g; #replace double-spaces with single space
return $text;
}
The last substitution uses the g 'greedy' modifier so it continues to find double-spaces until it replaces them all. (Effectively substituting anything more that single space)
The comments state the objective is to print to 2 decimal places.
There's a simple answer for Python 3:
>>> num=3.65
>>> "The number is {:.2f}".format(num)
'The number is 3.65'
or equivalently with f-strings (Python 3.6+):
>>> num = 3.65
>>> f"The number is {num:.2f}"
'The number is 3.65'
As always, the float value is an approximation:
>>> "{}".format(num)
'3.65'
>>> "{:.10f}".format(num)
'3.6500000000'
>>> "{:.20f}".format(num)
'3.64999999999999991118'
I think most use cases will want to work with floats and then only print to a specific precision.
Those that want the numbers themselves to be stored to exactly 2 decimal digits of precision, I suggest use the decimal type. More reading on floating point precision for those that are interested.
I use following code, found somewhere in the internet don't remember the source though.
var allText;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
return JSON.parse(allText);
<form onSubmit={(e) => {this.doSomething(); e.preventDefault();}}></form>
it work fine for me
I faced this issue when I had used Open SSL and the solution was to split the cert in 3 files and use all of them doing the call with Curl:
openssl pkcs12 -in mycert.p12 -out ca.pem -cacerts -nokeys
openssl pkcs12 -in mycert.p12 -out client.pem -clcerts -nokeys
openssl pkcs12 -in mycert.p12 -out key.pem -nocerts
curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite
the command to get the effective push remote for the branch, e.g., master, is:
git config branch.master.pushRemote || git config remote.pushDefault || git config branch.master.remote
Here's why (from the "man git config" output):
branch.name.remote [...] tells git fetch and git push which remote to fetch from/push to [...] [for push] may be overridden with remote.pushDefault (for all branches) [and] for the current branch [..] further overridden by branch.name.pushRemote [...]
For some reason, "man git push" only tells about branch.name.remote (even though it has the least precedence of the three) + erroneously states that if it is not set, push defaults to origin - it does not, it's just that when you clone a repo, branch.name.remote is set to origin, but if you remove this setting, git push will fail, even though you still have the origin remote
To handle undefined variables as well as nulls, you can use substitute
with deparse
:
nullSafe <- function(x) {
if (!exists(deparse(substitute(x))) || is.null(x)) {
return(NA)
} else {
return(x)
}
}
nullSafe(my.nonexistent.var)
Check the Build Action of Global.asax.cs. It should be set to Compile.
In Solution Explorer, Right-click Global.asax.cs and go to Properties. In the Properties pane, set the Build Action (while not debugging).
It seems that VS 2008 does not always add the .asax(.cs) files correctly by default.
This problem has been addressed in ASP.Net MVC 3. They now automatically convert underscores in html attribute properties to dashes. They got lucky on this one, as underscores are not legal in html attributes, so MVC can confidently imply that you'd like a dash when you use an underscore.
For example:
@Html.TextBoxFor(vm => vm.City, new { data_bind = "foo" })
will render this in MVC 3:
<input data-bind="foo" id="City" name="City" type="text" value="" />
If you're still using an older version of MVC, you can mimic what MVC 3 is doing by creating this static method that I borrowed from MVC3's source code:
public class Foo {
public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes) {
RouteValueDictionary result = new RouteValueDictionary();
if (htmlAttributes != null) {
foreach (System.ComponentModel.PropertyDescriptor property in System.ComponentModel.TypeDescriptor.GetProperties(htmlAttributes)) {
result.Add(property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
}
}
return result;
}
}
And then you can use it like this:
<%: Html.TextBoxFor(vm => vm.City, Foo.AnonymousObjectToHtmlAttributes(new { data_bind = "foo" })) %>
and this will render the correct data-* attribute:
<input data-bind="foo" id="City" name="City" type="text" value="" />
Looking at the select2 docs you use the below to get/set the value.
$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value
@PanPipes has pointed out that this has changed for 4.x (go toss him an upvote below). val
is now called directly
$("#select").val("CA");
So within the loadComplete
of the jqGrid you can get whatever value you are looking for then set the selectbox value.
Notice from the docs
Notice that in order to use this method you must define the initSelection function in the options so Select2 knows how to transform the id of the object you pass in val() to the full object it needs to render selection. If you are attaching to a select element this function is already provided for you.
A vector is a container class while an array is an allocated memory.
For me I was using expired auth keys. Generated new ones and boom.
We can't disable it directly but we can do the following:
type="button"
.href=""
attribute.disabled
attribute so it shows that it's disabled by changing the cursor and it becomes dimmed.example in PHP:
<?php
if($status=="Approved"){
?>
<a type="button" class="btn btn-primary btn-xs" disabled> EDIT
</a>
<?php
}else{
?>
<a href="index.php" class="btn btn-primary btn-xs"> EDIT
</a>
<?php
}
?>
Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
This happens if you forgot to change your build settings to Simulator
. Unless you want to build to a device, in which case you should see the other answers.
Close PHP Storm in terminal go to the project folder type
git rm -rf .idea; git commit -m "delete .idea"; git push;
Then go to project folder and delete the folder .idea
sudo rm -r .idea/
Start PhpStorm and you are done
In HTML you can specify a mailto:
address in the <form>
element's [action]
attribute.
<form action="mailto:[email protected]" method="GET">
<input name="subject" type="text" />
<textarea name="body"></textarea>
<input type="submit" value="Send" />
</form>
What this will do is allow the user's email client to create an email prepopulated with the fields in the <form>
.
What this will not do is send an email.
My problem similar to this was solved by checking my html code. I was having an onclick
handler in my form submit button to a method. like this : onclick="sendFalconRequestWithHeaders()"
. This method in turn calls ajax just like yours, and does what I want. But not as expected, my browser was returning nothing.
Learned From someone's hardwork, I have returned false in this handler, and solved.
Let me mention that before arriving to this post, I have spent a whole 3-day weekend and a half day in office writing code implementing CORS filters
, jetty config
, other jersey and embedded jetty
related stuff - just to fix this., revolving all my understanding around cross domain ajax requests
and standards stuff. It was ridiculous how simple mistakes in javascript make you dumb.
To be true, I have tried signed.applets.codebase_principal_support = true
and written isLocalHost() **if**
. may be this method needs to be implemented by us, firefox says there is no such
Now I have to clean my code to submit git patch cleanly. Thanks to that someone.
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
please set dataType config property in your ajax call and give it another try!
another point is you are using ajax call setup configuration properties as string and it is wrong as reference site
$.ajax({
url : 'http://voicebunny.comeze.com/index.php',
type : 'GET',
data : {
'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
alert('Data: '+data);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
I hope be helpful!
I almost never use Boolean
because its semantics are vague and obscure. Basically you have 3-state logic: true, false or unknown. Sometimes it is useful to use it when e.g. you gave user a choice between two values and the user didn't answer at all and you really want to know that information (think: NULLable database column).
I see no reason to convert from boolean
to Boolean
as it introduces extra memory overhead, NPE possibility and less typing. Typically I use awkward BooleanUtils.isTrue()
to make my life a little bit easier with Boolean
.
The only reason for the existence of Boolean
is the ability to have collections of Boolean
type (generics do not allow boolean
, as well as all other primitives).
There is a much faster CTE implementation available in this excellent post: http://weblogs.sqlteam.com/mladenp/archive/2009/07/28/SQL-Server-2005-Fast-Running-Totals.aspx
The problem in this thread can be expressed like this:
DECLARE @RT INT
SELECT @RT = 0
;
WITH abcd
AS ( SELECT TOP 100 percent
id
,SomeNumt
,MySum
order by id
)
update abcd
set @RT = MySum = @RT + SomeNumt
output inserted.*
Just like you can password protect workbooks and worksheets, you can password protect a macro in Excel from being viewed (and executed).
Place a command button on your worksheet and add the following code lines:
First, create a simple macro that you want to protect.
Range("A1").Value = "This is secret code"
Next, click Tools, Then VBAProject Properties...
Click Tools, VBAProject Properties...
Enter a Password Twice
Click OK.
Save, close and reopen the Excel file. Try to view the code.
The following dialog box will appear:
Password Protected from being Viewed
You can still execute the code by clicking on the command button but you cannot view or edit the code anymore (unless you know the password). The password for the downloadable Excel file is "easy".
Dim password As Variant password = Application.InputBox("Enter Password", "Password Protected") Select Case password Case Is = False 'do nothing Case Is = "easy" Range("A1").Value = "This is secret code" Case Else MsgBox "Incorrect Password" End Select
Result when you click the command button on the sheet:
Password Protected from being Executed
Explanation: The macro uses the InputBox method of the Application object. If the users clicks Cancel, this method returns False and nothing happens (InputBox disappears). Only when the user knows the password ("easy" again), the secret code will be executed. If the entered password is incorrect, a MsgBox is displayed. Note that the user cannot take a look at the password in the Visual Basic Editor because the project is protected from being viewed