$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['iUserId'=>SORT_ASC]]
]);
The problem in the jsfiddle is that your dummy text is all one word. If you use your lorem ipsum given in the question, then the text wraps fine.
If you want large words to be broken mid-word and wrap around, add this to your .title css:
word-wrap: break-word;
$(document).ready(function(){
$('#txtInput').live("cut copy paste",function(e) {
e.preventDefault();
});
});
On textbox live event cut, copy, paste event is prevented and it works well.
In Swift 3 and later you can:
let url = URL(string: "http://www.thisismylink.com/postName.php")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let parameters: [String: Any] = [
"id": 13,
"name": "Jack & Jill"
]
request.httpBody = parameters.percentEncoded()
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else { // check for fundamental networking error
print("error", error ?? "Unknown error")
return
}
guard (200 ... 299) ~= response.statusCode else { // check for http errors
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
Where:
extension Dictionary {
func percentEncoded() -> Data? {
return map { key, value in
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
.data(using: .utf8)
}
}
extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}
This checks for both fundamental networking errors as well as high-level HTTP errors. This also properly percent escapes the parameters of the query.
Note, I used a name
of Jack & Jill
, to illustrate the proper x-www-form-urlencoded
result of name=Jack%20%26%20Jill
, which is “percent encoded” (i.e. the space is replaced with %20
and the &
in the value is replaced with %26
).
See previous revision of this answer for Swift 2 rendition.
An update for Windows 10 Ubuntu Application via Subsystem (also works on standard Ubuntu):
You might have problems finding the package. If you do, never fear! PPA is here!
sudo add-apt-repository ppa:boost-latest/ppa
sudo apt-get update
Then run:
sudo apt-get install libboost-all-dev
Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:
<input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />
Then you just get the value in your ajax call:
var path = $("#GetIndexDataPath").val();
$.ajax({
type: "GET",
url: path,
data: { id = e.value},
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.
There is a possibility to improve Nathan Long's approach. You can replace the logic for detection of already submitted form with this one:
var lastTime = $(this).data("lastSubmitTime");
if (lastTime && typeof lastTime === "object") {
var now = new Date();
if ((now - lastTime) > 2000) // 2000ms
return true;
else
return false;
}
$(this).data("lastSubmitTime", new Date());
return true; // or do an ajax call or smth else
D = {}
is a dictionary not set.
>>> d = {}
>>> type(d)
<type 'dict'>
Use D = set()
:
>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])
From the documentation:
$this->db->insert_id()
The insert ID number when performing database inserts.
Therefore, you could use something like this:
$lastid = $this->db->insert_id();
React Native has updated the WebView component to allow for direct html rendering. Here's an example that works for me
var htmlCode = "<b>I am rendered in a <i>WebView</i></b>";
<WebView
ref={'webview'}
automaticallyAdjustContentInsets={false}
style={styles.webView}
html={htmlCode} />
If you don't want to output a Python script every time you save, or you don't want to restart the IPython kernel:
On the command line, you can use nbconvert
:
$ jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb
As a bit of a hack, you can even call the above command in an IPython notebook by pre-pending !
(used for any command line argument). Inside a notebook:
!jupyter nbconvert --to script config_template.ipynb
Before --to script
was added, the option was --to python
or --to=python
, but it was renamed in the move toward a language-agnostic notebook system.
The \
on it's own is used to escape special characters, such as \n
(new line), \t
(tabulation), \"
(quotes) when typing these specific values in a System.out.println()
statement.
Thus, if you want to print a backslash, \
, you can't have it on it's own since the compiler will be expecting a special character (such as the ones above). Thus, to print a backslash you need to escape it, since itself is also one of these special characters, thus, \\
yields \
.
may need to change the SCHEMA not only table
ALTER SCHEMA `<database name>` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);
(mariaDB 10)
Just adding to Jason's answer, the .
selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.
e.g.
$('element[attr=val]')
Add the --force
option:
mysql -u username -p database_name --force < file.sql
Follow this:
Automator.app
Application
Show library
in the toolbar (if hidden)Run shell script
(from the Actions/Utilities
)save somewhere (for example you can make an Applications
folder in your HOME, you will get an your_name.app
)
go to System Preferences
-> Accounts
-> Login items
EDIT:
I've recently earned a "Good answer" badge for this answer. While my solution is simple and working, the cleanest way to run any program or shell script at login time is described in @trisweb's answer, unless, you want interactivity.
With automator solution you can do things like next:
so, asking to run a script or quit the app, asking passwords, running other automator workflows at login time, conditionally run applications at login time and so on...
Here is how I would write a validator for MaxValue
public class MaxValueAttribute : ValidationAttribute
{
private readonly int _maxValue;
public MaxValueAttribute(int maxValue)
{
_maxValue = maxValue;
}
public override bool IsValid(object value)
{
return (int) value <= _maxValue;
}
}
The MinValue Attribute should be fairly the same
You just rebuilt your project
compile fileTree(dir: 'libs', include: ['*.jar'])
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
you could do something like (below)
var query = from p in context.T1
join q in context.T2
on
new { p.Col1, p.Col2 }
equals
new { q.Col1, q.Col2 }
select new {p...., q......};
Yes it is.
In Python a function doesn't always have to return a variable of the same type (although your code will be more readable if your functions do always return the same type). That means that you can't specify a single return type for the function.
In the same way, the parameters don't always have to be the same type too.
I think you change
compile 'com.google.firebase:firebase-messaging:11.0.4'
You have to realize that server-side sessions are an artificial add-on to HTTP. Since HTTP is stateless, the server needs to somehow recognize that a request belongs to a particular user it knows and has a session for. There are 2 ways to do this:
What are you trying to do anyway? Why would you want tabs to have separate sessions? Maybe there's a way to achieve your goal without using sessions at all?
Edit: For testing, other solutions can be found (such as running several browser instances on separate VMs). If one user needs to act in different roles at the same time, then the "role" concept should be handled in the app so that one login can have several roles. You'll have to decide whether this, using URL rewriting, or just living with the current situation is more acceptable, because it's simply not possible to handle browser tabs separately with cookie-based sessions.
Based on luttken's answer. Thought I'd add my twist :)
function dateIsInBetween(\DateTime $from, \DateTime $to, \DateTime $subject)
{
return $subject->getTimestamp() > $from->getTimestamp() && $subject->getTimestamp() < $to->getTimestamp() ? true : false;
}
$paymentDate = new \DateTime('now');
$contractDateBegin = new \DateTime('01/01/2001');
$contractDateEnd = new \DateTime('01/01/2016');
echo dateIsInBetween($contractDateBegin, $contractDateEnd, $paymentDate) ? "is between" : "NO GO!";
Rewrite the query into this
SELECT st1.*, st2.relevant_field FROM sometable st1
INNER JOIN sometable st2 ON (st1.relevant_field = st2.relevant_field)
GROUP BY st1.id /* list a unique sometable field here*/
HAVING COUNT(*) > 1
I think st2.relevant_field
must be in the select, because otherwise the having
clause will give an error, but I'm not 100% sure
Never use IN
with a subquery; this is notoriously slow.
Only ever use IN
with a fixed list of values.
More tips
SELECT *
only select
the fields that you really need.relevant_field
to speed up the equi-join.group by
on the primary key. General solution for 90% of your IN (select
queries
Use this code
SELECT * FROM sometable a WHERE EXISTS (
SELECT 1 FROM sometable b
WHERE a.relevant_field = b.relevant_field
GROUP BY b.relevant_field
HAVING count(*) > 1)
I got the error because of a clumsy typo:
This errors:
knitr::opts_chunk$seet(echo = FALSE)
Error: attempt to apply non-function
After correcting the typo, it works:
knitr::opts_chunk$set(echo = FALSE)
One of my options didn't have a value: <option>-----</option>
. I was trying to use if (!$(this).val()) { .. }
but I was getting strange results. Turns out if you don't have a value
attribute on your <option>
element, it returns the text inside of it instead of an empty string. If you don't want val()
to return anything for your option, make sure to add value=""
.
With library fpp
, you can easily create time series with date format:
time_ser=ts(data,frequency=4,start=c(1954,2))
here we start at the 2nd quarter of 1954 with quarter fequency.
If you are using bootstrap then use this class in the holding div
radio-inline
Example:
<label for="active" class="col-md-4 control-label">Active</label>
<div class="col-md-6 radio-inline">
<input type="checkbox" name="active" value="1">
<div>
Here the label Active and the checkbox will appear to be aligned.
Use the Find method if item_manuf_id
is a primary key:
var result = dtPs.Rows.Find("some value");
If you only want to know if the value is in there then use the Contains method.
if (dtPs.Rows.Contains("some value"))
{
...
}
Primary key restriction applies to Contains
aswell.
This operator allows you to determine the type of an object.
It returns a boolean
value.
For example
package test;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
public class instanceoftest
{
public static void main(String args[])
{
Map m=new HashMap();
System.out.println("Returns a boolean value "+(m instanceof Map));
System.out.println("Returns a boolean value "+(m instanceof HashMap));
System.out.println("Returns a boolean value "+(m instanceof Object));
System.out.println("Returns a boolean value "+(m instanceof Date));
}
}
the output is:
Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false
Content types are included in HTTP responses because the same, byte for byte sequence of values in the content could be interpreted in more than one way.(*)
Remember that http can transport more than just HTML (js, css and images are obvious examples), and in some cases, the receiver will not know what type of object it's going to receive.
(*) the obvious one here is XHTML - which is XML. If it's served with a content type of application/xml
, the receiver ought to just treat it as XML. If it's served up as application/xhtml+xml
, then it ought to be treated as XHTML.
EDIT: the name "lock" is a tricky one, its NPM trying to catch up with Yarn. It isn't a locked file whatsoever. package.json
is a user-fixed file, that once "installed" will generate node_modules folder tree and that tree will then be written in package-lock.json
. So you see, its the other way around - dependency versions will be pulled from package.json
as always, and package-lock.json
should be called package-tree.json
(hope this made my answer clearer, after so many downvotes)
A simplistic answer: package.json
have your dependencies as usual, while package-lock.json
is "an exact, and more importantly reproducible node_modules tree" (taken from npm docs itself).
As for the tricky name, its NPM trying to catch up with Yarn.
Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:
SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a
If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
I was having this problem when running from c#, on Windows 7, the "Interactive Services Detection" service was popping up when running a hidden powershell window as the SYSTEM account.
Using the "CreateNoWindow" parameter prevented the ISD service popping up it's warning.
process.StartInfo = new ProcessStartInfo("powershell.exe",
String.Format(@" -NoProfile -ExecutionPolicy unrestricted -encodedCommand ""{0}""",encodedCommand))
{
WorkingDirectory = executablePath,
UseShellExecute = false,
CreateNoWindow = true
};
Robin Kanters' answer is right, but it does check for installed apps regardless of their enabled or disabled state.
We all know an app can be installed but disabled by the user, therefore unusable.
This checks for installed AND enabled apps:
public static boolean isPackageInstalled(String packageName, PackageManager packageManager) {
try {
return packageManager.getApplicationInfo(packageName, 0).enabled;
}
catch (PackageManager.NameNotFoundException e) {
return false;
}
}
You can put this method in a class like Utils
and call it everywhere using:
boolean isInstalled = Utils.isPackageInstalled("com.package.name", context.getPackageManager())
None of the above solutions worked for me. It's possible that there were some other styles conflicting.
For myself, the following worked, hopefully it may help someone else. I'm using bootstrap 4.
.carousel-inner img {
display:block;
height: auto;
max-width: 100%;
}
To make logic clear is very important. This problem appear, because the reference become a dead loop.
If you don't want to change the logic, you can put the some import statement which caused ImportError to the other position of file, for example the end.
from test.b import b2
def a1():
print('a1')
b2()
from test.a import a1
def b1():
print('b1')
a1()
def b2():
print('b2')
if __name__ == '__main__':
b1()
You will get Import Error:
ImportError: cannot import name 'a1'
But if we change the position of from test.b import b2 in A like below:
def a1():
print('a1')
b2()
from test.b import b2
And the we can get what we want:
b1
a1
b2
The most efficient (using over()).
select Grade, count(*) * 100.0 / sum(count(*)) over()
from MyTable
group by Grade
Universal (any SQL version).
select Grade, count(*) * 100.0 / (select count(*) from MyTable)
from MyTable
group by Grade;
With CTE, the least efficient.
with t(Grade, GradeCount)
as
(
select Grade, count(*)
from MyTable
group by Grade
)
select Grade, GradeCount * 100.0/(select sum(GradeCount) from t)
from t;
The above answers may help you but you may also want to know how to use array of function pointers.
void fun1()
{
}
void fun2()
{
}
void fun3()
{
}
void (*func_ptr[3])() = {fun1, fun2, fun3};
main()
{
int option;
printf("\nEnter function number you want");
printf("\nYou should not enter other than 0 , 1, 2"); /* because we have only 3 functions */
scanf("%d",&option);
if((option>=0)&&(option<=2))
{
(*func_ptr[option])();
}
return 0;
}
You can only assign the addresses of functions with the same return type and same argument types and no of arguments to a single function pointer array.
You can also pass arguments like below if all the above functions are having the same number of arguments of same type.
(*func_ptr[option])(argu1);
Note: here in the array the numbering of the function pointers will be starting from 0 same as in general arrays. So in above example fun1
can be called if option=0, fun2
can be called if option=1 and fun3
can be called if option=2.
You can use this snippet :-D
using System;
using System.Reflection;
public static class EnumUtils
{
public static T GetDefaultValue<T>()
where T : struct, Enum
{
return (T)GetDefaultValue(typeof(T));
}
public static object GetDefaultValue(Type enumType)
{
var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
if (attribute != null)
return attribute.Value;
var innerType = enumType.GetEnumUnderlyingType();
var zero = Activator.CreateInstance(innerType);
if (enumType.IsEnumDefined(zero))
return zero;
var values = enumType.GetEnumValues();
return values.GetValue(0);
}
}
Example:
using System;
public enum Enum1
{
Foo,
Bar,
Baz,
Quux
}
public enum Enum2
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 0
}
public enum Enum3
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 4
}
public static class Program
{
public static void Main()
{
var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
Console.WriteLine(defaultValue1); // Foo
var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
Console.WriteLine(defaultValue2); // Quux
var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
Console.WriteLine(defaultValue3); // Foo
var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
Console.WriteLine(defaultValue4); // Bar
}
}
for(File f : files) {
f.delete();
}
files.delete(); // will work
Use this:
$(document).ready(function () {
$('#workPatternDataTable').dataTable({
//"aaSorting": [],
ajax: null,
columnDefs: [
{
targets: 0,
sortable: false,
autoWidth: false,
}
]
});
});
As a quick and very scoped solution:
Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.
When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.
There's an easy, old-fashioned way to store user credentials in an HTTPS URL:
https://user:[email protected]/...
You can change the URL with git remote set-url <remote-repo> <URL>
The obvious downside to that approach is that you have to store the password in plain text. You can still just enter the user name (https://[email protected]/...
) which will at least save you half the hassle.
You might prefer to switch to SSH or to use the GitHub client software.
Using Guava:
if (CharMatcher.anyOf("ABC...").matches(symbol)) { ... }
Or if many of those characters are a range, such as "A" to "U" but some aren't:
CharMatcher.inRange('A', 'U').or(CharMatcher.anyOf("1379"))
You can also declare this as a static final
field so the matcher doesn't have to be created each time.
private static final CharMatcher MATCHER = CharMatcher.anyOf("ABC...");
I have done this before, I think you need to remove the ActionResult. Make it a void and remove the return View(MyView). this is the solution
You can also affect differente DOM elements using :target pseudo class. If an element is the destination of an anchor target it will get the :target pseudo element.
<style>
p { color:black; }
p:target { color:red; }
</style>
<a href="#elem">Click me</a>
<p id="elem">And I will change</p>
Here is a fiddle : https://jsfiddle.net/k86b81jv/
Or also you can do something like this.
<div style="background=#aeaeae; float: right">
</div>
We can add any CSS inside the style attribute of HTML tags.
Have you tried this?
$("#notification").fadeOut(300, function(){
$(this).remove();
});
That is, using the current this context to target the element in the inner function and not the id. I use this pattern all the time - it should work.
Try using Environment.NewLine
:
Gets the newline string defined for this environment.
Something like this ought to work:
textBox.AppendText("your new text" & Environment.NewLine)
You are using str
methods on an open file object.
You can read the file as a list of lines by simply calling list()
on the file object:
with open('goodlines.txt') as f:
mylist = list(f)
This does include the newline characters. You can strip those in a list comprehension:
with open('goodlines.txt') as f:
mylist = [line.rstrip('\n') for line in f]
My problem was that I had the Server service stopped and this gave exactly this same issue. So started the Server service and the installation worked.
Same issue with ambiguous (matches "iPhone Developer: [me] " and /// tweetdeck's library privatedata file. Fixed it by moving file to the trash and re-logging into Tweetdeck, setting up passwords again. What a pain.
You could use the Redis Keyspace Notifications by using psubscribe
and "__keyevent@<DB-INDEX>__:expired"
.
With that, each time that a key will expire, you will get a message published on your redis connection.
Regarding your question basically you create a temporary "normal" key using set
with an expiration time in s/ms. It should match the name of the key that you wish to delete in your set.
As your temporary key will be published to your redis connection holding the "__keyevent@0__:expired"
when it expired, you can easily delete your key from your original set as the message will have the name of the key.
A simple example in practice on that page : https://medium.com/@micah1powell/using-redis-keyspace-notifications-for-a-reminder-service-with-node-c05047befec3
doc : https://redis.io/topics/notifications ( look for the flag xE)
Assuming you want to replace the newlines with something so that something like this:
the quick brown fox\r\n
jumped over the lazy dog\r\n
doesn't end up like this:
the quick brown foxjumped over the lazy dog
I'd do something like this:
string[] SplitIntoChunks(string text, int size)
{
string[] chunk = new string[(text.Length / size) + 1];
int chunkIdx = 0;
for (int offset = 0; offset < text.Length; offset += size)
{
chunk[chunkIdx++] = text.Substring(offset, size);
}
return chunk;
}
string[] GetComments()
{
var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox;
if (cmtTb == null)
{
return new string[] {};
}
// I assume you don't want to run the text of the two lines together?
var text = cmtTb.Text.Replace(Environment.Newline, " ");
return SplitIntoChunks(text, 50);
}
I apologize if the syntax isn't perfect; I'm not on a machine with C# available right now.
@Test
public void google_Search()
{
WebDriver driver;
driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("Cheese!\n");
element.submit();
//Wait until the google page shows the result
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));
//Get the url of third link and navigate to it
String third_link = findElements.get(2).getAttribute("href");
driver.navigate().to(third_link);
}
The other method that's not mentioned in the other comments is to bind to the service from the activity using bindService() and get an instance of the service in the ServiceConnection callback. As described here http://developer.android.com/guide/components/bound-services.html
You could throw the enum value and string into an STL map. Then you could use it like so.
return myStringMap[Enum::Apple];
$array = explode("\n", $text);
for($i=0; $i < count($array); $i++)
{
echo $line;
if($i < count($array)-1)
{
echo '<br />';
}
}
Here is a simple context manager that prints to the console and writes the same output to an file. It also writes any exceptions to the file.
import traceback
import sys
# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
def __init__(self, filename):
self.file = open(filename, 'w')
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = self.stdout
if exc_type is not None:
self.file.write(traceback.format_exc())
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
To use the context manager:
print("Print")
with Tee('test.txt'):
print("Print+Write")
raise Exception("Test")
print("Print")
It's not that your file is partially downloaded. It fails authentication and hence downloads e.g "index.html" but it names it myfile.zip (since this is what you want to download).
I followed the link suggested by @thomasbabuj and figured it out eventually.
You should try adding --auth-no-challenge
and as @thomasbabuj suggested replace your password entry
I.e
wget --auth-no-challenge --user=myusername --ask-password https://test.mydomain.com/files/myfile.zip
There is no such thing as "SOAP protocol". SOAP is an XML schema.
It usually runs over HTTP (port 80), however.
The alert box is a system object, and not subject to CSS. To do this style of thing you would need to create an HTML element and mimic the alert()
functionality. The jQuery UI Dialogue does a lot of the work for you, working basically as I have described: Link.
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<title>jQuery UI Dialog - Default functionality</title>_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">_x000D_
<link rel="stylesheet" href="/resources/demos/style.css">_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<script>_x000D_
$( function() {_x000D_
$( "#dialog" ).dialog();_x000D_
} );_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div id="dialog" title="Basic dialog">_x000D_
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
The problem is with line
imageWidth = 1 * Convert.ToInt32(Label1.Text);
Label1.Text
may or may not be int. Check.
Use Int32.TryParse(value, out number)
instead. That will solve your problem.
int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
Image1.Width= imageWidth;
}
On Button
click event write this:
Uri uri = Uri.parse("http://www.google.com"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
that open the your URL.
I have problem running the py files in my java code using eclipse/STS, getting PyException due to insufficient jvm heap memory. I have done the changes as mentioned below and I'm able to resolve this issue. Below is my System configuration.
And these are the changes I did in my workspace and voila it runs perfect now.
What about this expect script?
#!/usr/bin/expect -f
spawn ssh root@myhost
expect -exact "root@myhost's password: "
send -- "mypassword\r"
interact
AnyObject
is the official way to use a weak reference in Swift.
class MyClass {
weak var delegate: MyClassDelegate?
}
protocol MyClassDelegate: AnyObject {
}
From Apple:
To prevent strong reference cycles, delegates should be declared as weak references. For more information about weak references, see Strong Reference Cycles Between Class Instances. Marking the protocol as class-only will later allow you to declare that the delegate must use a weak reference. You mark a protocol as being class-only by inheriting from AnyObject, as discussed in Class-Only Protocols.
I know this is an old thread but I thought I would chime in.
Chrome currently has a solution built in.
CTRL+SHIFT+I
(or navigate to Current Page Control > Developer > Developer Tools
. In the newer versions of Chrome, click the Wrench icon > Tools > Developer Tools.) to enable the Developer Tools. Network
button. If it isn't already, enable it for the session or always. "XHR"
sub-button.AJAX call
. "Resources"
. I have written a script that does this myself:
#!/bin/bash
LANG=C
if [ -z "$1" ]; then
if [ "$(tty)" = "not a tty" ]; then
p=`cat`;
else
echo "No timestamp given."
exit
fi
else
p=$1
fi
echo $p | gawk '{ print strftime("%c", $0); }'
I just removed android:lines="1"
and added android:maxLines="2"
, this got the text to wrap automatically. The problem was the android:lines
attribute. That causes the text wrapping to not happen.
I didnt have to use maxEms
or singleLine="false"
(deprecated API) to fix this.
?#:
var a = Double.Parse("10.0", CultureInfo.InvariantCulture); // returns 10
var b = Double.Parse("10,0", CultureInfo.InvariantCulture); // returns 100
In invariant culture comma is not decimal point symbol, but group separator.
As I know, it's common mistake for novice programmers from some locales.
Realise this is an old thread, but after seeing lots of scripts like this I noticed that you can do this just using conditional formatting.
Assuming the "Status" was Column D:
Highlight cells > right click > conditional formatting. Select "Custom Formula Is" and set the formula as
=RegExMatch($D2,"Complete")
or
=OR(RegExMatch($D2,"Complete"),RegExMatch($D2,"complete"))
Edit (thanks to Frederik Schøning)
=RegExMatch($D2,"(?i)Complete")
then set the range to cover all the rows e.g. A2:Z10
. This is case insensitive, so will match complete, Complete or CoMpLeTe.
You could then add other rules for "Not Started" etc. The $ is very important. It denotes an absolute reference. Without it cell A2 would look at D2, but B2 would look at E2, so you'd get inconsistent formatting on any given row.
$("#SelectedCountryId_option_selected")[0].textContent
this worked for me, here instead of [0]
, pass the selected index of your drop down list.
If you're finding by Contains then it'll be like this
$("input[id*='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you're finding by Starts With then it'll be like this
$("input[id^='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you're finding by Ends With then it'll be like this
$("input[id$='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which id is not a given string
$("input[id!='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which name contains a given word, delimited by spaces
$("input[name~='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen
$("input[id|='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
There is no portable way to read raw characters from a Java console.
Some platform-dependent workarounds have been presented above. But to be really portable, you'd have to abandon console mode and use a windowing mode, e.g. AWT or Swing.
In my case I was using jackson-databind-2.8.8.jar
that is not compatible with JDK 1.6
I need to use so Spring wasn't loading this converter. I downgraded the version and it works now.
There was a bug, but it was fixed in the meantime. :host { }
works fine now.
Also supported are
:host(selector) { ... }
for selector
to match attributes, classes, ... on the host element:host-context(selector) { ... }
for selector
to match elements, classes, ...on parent components
selector /deep/ selector
(alias selector >>> selector
doesn't work with SASS) for styles to match across element boundaries
UPDATE: SASS is deprecating /deep/
.
Angular (TS and Dart) added ::ng-deep
as a replacement that's also compatible with SASS.
UPDATE2: ::slotted
::slotted
is now supported by all new browsers and can be used with `ViewEncapsulation.ShadowDom
https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted
See also Load external css style into Angular 2 Component
/deep/
and >>>
are not affected by the same selector combinators that in Chrome which are deprecated.
Angular emulates (rewrites) them, and therefore doesn't depend on browsers supporting them.
This is also why /deep/
and >>>
don't work with ViewEncapsulation.Native
which enables native shadow DOM and depends on browser support.
I would use a list:
string = []
for i in range(0, 9):
string.append("Hello")
This way, you would have 9 "Hello" and you could get them individually like this:
string[x]
Where x
would identify which "Hello" you want.
So, print(string[1])
would print Hello
.
Use "\\"
to escape the \ character.
Building upon Anthony and Anton's answers I incorporated the ability to rotate the generated circle without affecting it's overall appearance. This is useful if you're using the path for an animation and you need to control where it begins.
function(cx, cy, r, deg){
var theta = deg*Math.PI/180,
dx = r*Math.cos(theta),
dy = -r*Math.sin(theta);
return "M "+cx+" "+cy+"m "+dx+","+dy+"a "+r+","+r+" 0 1,0 "+-2*dx+","+-2*dy+"a "+r+","+r+" 0 1,0 "+2*dx+","+2*dy;
}
Below code will help you to find out iframe data.
let iframe = document.getElementById('frameId');
let innerDoc = iframe.contentDocument || iframe.contentWindow.document;
As long as your vector remains in global scope you can return:
&(*iterator)
I'll caution you that this is pretty dangerous in general. If your vector is ever moved out of global scope and is destructed, any pointers to myObject become invalid. If you're writing these functions as part of a larger project, returning a non-const pointer could lead someone to delete the return value. This will have undefined, and catastrophic, effects on the application.
I'd rewrite this as:
myObject myFunction(const vector<myObject>& objects)
{
// find the object in question and return a copy
return *iterator;
}
If you need to modify the returned myObject, store your values as pointers and allocate them on the heap:
myObject* myFunction(const vector<myObject*>& objects)
{
return *iterator;
}
That way you have control over when they're destructed.
Something like this will break your app:
g_vector<tmpClass> myVector;
tmpClass t;
t.i = 30;
myVector.push_back(t);
// my function returns a pointer to a value in myVector
std::auto_ptr<tmpClass> t2(myFunction());
echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts
the >>
appends the output of echo
to the file.
Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.
First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.
Second, it requires you to add an entry for every host name on a domain; just adding websitename.com
will not block www.websitename.com
, for example.
Its Worked for me on Windows
First i installed and started XAMPP Control Panel
Clicked for Start under Actions for MySQL. And below is my Configuration for MySQL (MySQL Workbench 8.0 CE) Connections And it got connected with Test DataBase
If you want just the time in a shell variable then this works:
var=`{ time <command> ; } 2>&1 1>/dev/null`
Code to add audio to video using ffmpeg.
If audio length is greater than video length it will cut the audio to video length. If you want full audio in video remove -shortest from the cmd.
String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy", ,outputFile.getPath()};
private void execFFmpegBinaryShortest(final String[] command) {
final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");
String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};
try {
ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
@Override
public void onFailure(String s) {
System.out.println("on failure----"+s);
}
@Override
public void onSuccess(String s) {
System.out.println("on success-----"+s);
}
@Override
public void onProgress(String s) {
//Log.d(TAG, "Started command : ffmpeg "+command);
System.out.println("Started---"+s);
}
@Override
public void onStart() {
//Log.d(TAG, "Started command : ffmpeg " + command);
System.out.println("Start----");
}
@Override
public void onFinish() {
System.out.println("Finish-----");
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// do nothing for now
System.out.println("exceptio :::"+e.getMessage());
}
}
The difference lies in the fact that ./gradlew
indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle
and then invoke gradle using the gradle
command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.
Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.
Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable
Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html
Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk
You want to use the live()
function. See the docs.
For example:
$("#anchor1").live("click", function() {
$("#anchor1").append('<a class="myclass" href="#">test4</a>');
});
Based on my practice, before accessing the $_SESSION[]
you need to call session_start
every time to use the script. See the link below for manual.
http://php.net/manual/en/function.session-start.php
For me at least session_start
is confusing as a name. A session_load
can be more clear.
For reference I was looking at the same problem, I wanted to join the string value of stream elements in the reverse order.
itemList = { last, middle, first } => first,middle,last
I started to use an intermediate collection with collectingAndThen
from comonad or the ArrayDeque
collector of Stuart Marks, although I wasn't happy with intermediate collection, and streaming again
itemList.stream()
.map(TheObject::toString)
.collect(Collectors.collectingAndThen(Collectors.toList(),
strings -> {
Collections.reverse(strings);
return strings;
}))
.stream()
.collect(Collector.joining());
So I iterated over Stuart Marks answer that was using the Collector.of
factory, that has the interesting finisher lambda.
itemList.stream()
.collect(Collector.of(StringBuilder::new,
(sb, o) -> sb.insert(0, o),
(r1, r2) -> { r1.insert(0, r2); return r1; },
StringBuilder::toString));
Since in this case the stream is not parallel, the combiner is not relevant that much, I'm using insert
anyway for the sake of code consistency but it does not matter as it would depend of which stringbuilder is built first.
I looked at the StringJoiner, however it does not have an insert
method.
I was going out of my mind when a rule was being ignored while others weren't. Run your CSS through a validator and look for parsing errors.
I accidentally used // for a comment instead of /* */ causing odd behavior. My IDE said nothing about it. I hope it helps someone.
You should set the $RANDFILE environment variable and/or create $HOME/.rnd file. (OpenSSL FAQ). (Of course, you should have rights to that file. Others answers here are about that. But first you should have the file and a reference to it.)
Up to version 0.9.6 OpenSSL wrote the seeding file in the current directory in the file ".rnd". At version 0.9.6a you have no default seeding file. OpenSSL 0.9.6b and later will behave similarly to 0.9.6a, but will use a default of "C:\" for HOME on Windows systems if the environment variable has not been set.
If the default seeding file does not exist or is too short, the "PRNG not seeded" error message may occur.
The $RANDFILE environment variable and $HOME/.rnd are only used by the OpenSSL command line tools. Applications using the OpenSSL library provide their own configuration options to specify the entropy source, please check out the documentation coming the with application.
Based in this implementation with Node.js of JWT with refresh token:
1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.
2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.
3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.
There is no need to add if{}else{} control flow. Initialise the button texts for different states at the View or ViewController constructor:
[btnCheckButton setTitle:@"Normal" forState:UIControlStateNormal]; [btnCheckButton setTitle:@"Selected" forState:UIControlStateSelected];
Then switch the button state to Selected:
[btnCheckButton setSelected:YES];
Then switch the button state to Normal:
[btnCheckButton setSelected:NO];
oops! just found myself: just add this line on any element you need
-webkit-appearance: none;
we have 3 choices to get the first row in Oracle DB table.
1) select * from table_name where rownum= 1
is the best way
2) select * from table_name where id = ( select min(id) from table_name)
3)
select * from
(select * from table_name order by id)
where rownum = 1
You can just write
System.Diagnostics.Process.Start("http://google.com");
EDIT: The WebBrowser
control is an embedded copy of IE.
Therefore, any links inside of it will open in IE.
To change this behavior, you can handle the Navigating
event.
http://www.lfd.uci.edu/~gohlke/pythonlibs/
press contrl F type Pillow-2.4.0.win-amd64-py3.3.exe
then click and downloadd the 64 bit version
Pillow is a replacement for PIL, the Python Image Library, which provides image processing functionality and supports many file formats.
Note: use from PIL import Image
instead of import Image
.
PIL-1.1.7.win-amd64-py2.5.exe
PIL-1.1.7.win32-py2.5.exe
Pillow-2.4.0.win-amd64-py2.6.exe
Pillow-2.4.0.win-amd64-py2.7.exe
Pillow-2.4.0.win-amd64-py3.2.exe
Pillow-2.4.0.win-amd64-py3.3.exe
Pillow-2.4.0.win-amd64-py3.4.exe
Pillow-2.4.0.win32-py2.6.exe
Pillow-2.4.0.win32-py2.7.exe
Pillow-2.4.0.win32-py3.2.exe
Pillow-2.4.0.win32-py3.3.exe
Pillow-2.4.0.win32-py3.4.exe
The installation of CuDNN is just copying some files. Hence to check if CuDNN is installed (and which version you have), you only need to check those files.
Step 1: Register an nvidia developer account and download cudnn here (about 80 MB). You might need nvcc --version
to get your cuda version.
Step 2: Check where your cuda installation is. For most people, it will be /usr/local/cuda/
. You can check it with which nvcc
.
Step 3: Copy the files:
$ cd folder/extracted/contents
$ sudo cp include/cudnn.h /usr/local/cuda/include
$ sudo cp lib64/libcudnn* /usr/local/cuda/lib64
$ sudo chmod a+r /usr/local/cuda/lib64/libcudnn*
You might have to adjust the path. See step 2 of the installation.
$ cat /usr/local/cuda/include/cudnn.h | grep CUDNN_MAJOR -A 2
When you get an error like
F tensorflow/stream_executor/cuda/cuda_dnn.cc:427] could not set cudnn filter descriptor: CUDNN_STATUS_BAD_PARAM
with TensorFlow, you might consider using CuDNN v4 instead of v5.
Ubuntu users who installed it via apt
: https://askubuntu.com/a/767270/10425
The problem is in the network layer. Here are the status codes explained:
Connection refused
: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.
Connection timed out
: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.
That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.
Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.
It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.
As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.
To rule out network congestion as a problem you could use a tool like mtr
or traceroute
or even ping
to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.
Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).
If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp
is definetly recommended then.
Try below block of code, its working for me.
char *p = "0x820";
uint16_t intVal;
sscanf(p, "%x", &intVal);
printf("value x: %x - %d", intVal, intVal);
Output is:
value x: 820 - 2080
This may sound silly and seems obvious from the name SessionGUID, but is the column a uniqueidentifier on Report_Opener? If not, you may want to try casting it to the correct type and give it a shot or declare your variable to the correct type.
The plan created as part of the sproc may work unintuitively and do an internal cast on a large table.
Instead of adding "ws." before every Range, as suggested above, you can add "ws.activate" before Call instead.
This will get you into the worksheet you want to work on.
Get Screen Width and Height in terms of DP with some good decoration:
Step 1: Create interface
public interface ScreenInterface {
float getWidth();
float getHeight();
}
Step 2: Create implementer class
public class Screen implements ScreenInterface {
private Activity activity;
public Screen(Activity activity) {
this.activity = activity;
}
private DisplayMetrics getScreenDimension(Activity activity) {
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics;
}
private float getScreenDensity(Activity activity) {
return activity.getResources().getDisplayMetrics().density;
}
@Override
public float getWidth() {
DisplayMetrics displayMetrics = getScreenDimension(activity);
return displayMetrics.widthPixels / getScreenDensity(activity);
}
@Override
public float getHeight() {
DisplayMetrics displayMetrics = getScreenDimension(activity);
return displayMetrics.heightPixels / getScreenDensity(activity);
}
}
Step 3: Get width and height in activity:
Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();
Here is simple steps add this gradle:
dependencies {
compile "com.google.firebase:firebase-messaging:9.0.0"
}
No extra permission are needed in manifest like GCM.
No receiver is needed to manifest like GCM. With FCM, com.google.android.gms.gcm.GcmReceiver
is added automatically.
Migrate your listener service
A service extending InstanceIDListenerService
is now required only if you want to access the FCM token.
This is needed if you want to
Add Service in manifest
<service
android:name=".MyInstanceIDListenerService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
Change MyInstanceIDListenerService
to extend FirebaseInstanceIdService
, and update code to listen for token updates and get the token whenever a new token is generated.
public class MyInstanceIDListenerService extends FirebaseInstanceIdService {
...
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is also called
* when the InstanceID token is initially generated, so this is where
* you retrieve the token.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
}
For more information visit
Here is an implementation in Kotlin
try {
val inputStream: InputStream = this.getResources().openRawResource(R.raw.**)
val inputStreamReader = InputStreamReader(inputStream)
val sb = StringBuilder()
var line: String?
val br = BufferedReader(inputStreamReader)
line = br.readLine()
while (line != null) {
sb.append(line)
line = br.readLine()
}
br.close()
var content : String = sb.toString()
Log.d(TAG, content)
} catch (e:Exception){
Log.d(TAG, e.toString())
}
Simple workaround is to open the file and simply press save button in Excel (no need to change the format). once saved in excel it will start to work and you should be able to see its sheets in the DFT.
You can do something like this:
$('.notice')
.fadeIn()
.animate({opacity: '+=0'}, 2000) // Does nothing for 2000ms
.fadeOut('fast');
Sadly, you can't just do .animate({}, 2000) -- I think this is a bug, and will report it.
An absolute URI specifies a scheme; a URI that is not absolute is said to be relative.
http://docs.oracle.com/javase/8/docs/api/java/net/URI.html
So, perhaps your URLEncoder isn't working as you're expecting (the https bit)?
URLEncoder.encode(uri)
You can avoid the loop and cut etc by using:
awk -F ':' '{system("ping " $1);}' config.txt
However it would be better if you post a snippet of your config.txt
You can't manipulate :after
, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after
specified.
CSS:
.pageMenu .active.changed:after {
/* this selector is more specific, so it takes precedence over the other :after */
border-top-width: 22px;
border-left-width: 22px;
border-right-width: 22px;
}
JS:
$('.pageMenu .active').toggleClass('changed');
UPDATE: while it's impossible to directly modify the :after
content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.
If you have a variable containing f.e. 1 minute(in seconds), you can add it to the systimestamp then use to_char to select the different time parts from it.
select to_char(systimestamp+60/(24*60*60), 'yyyy.mm.dd HH24:mi:ss') from dual
I have included JS (for OG's) and TS versions below.
.html
<a [routerLink]="['/search', { tag: 'fish' } ]">A link</a>
In the above I am using the link parameter array see sources below for more information.
routing.js
(function(app) {
app.routing = ng.router.RouterModule.forRoot([
{ path: '', component: indexComponent },
{ path: 'search', component: searchComponent }
]);
})(window.app || (window.app = {}));
searchComponent.js
(function(app) {
app.searchComponent =
ng.core.Component({
selector: 'search',
templateUrl: 'view/search.html'
})
.Class({
constructor: [ ng.router.Router, ng.router.ActivatedRoute, function(router, activatedRoute) {
// Pull out the params with activatedRoute...
console.log(' params', activatedRoute.snapshot.params);
// Object {tag: "fish"}
}]
}
});
})(window.app || (window.app = {}));
routing.ts (excerpt)
const appRoutes: Routes = [
{ path: '', component: IndexComponent },
{ path: 'search', component: SearchComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
// other imports here
],
...
})
export class AppModule { }
searchComponent.ts
import 'rxjs/add/operator/switchMap';
import { OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
export class SearchComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.route.params
.switchMap((params: Params) => doSomething(params['tag']))
}
More infos:
"Link Parameter Array" https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array
"Activated Route - the one stop shop for route info" https://angular.io/docs/ts/latest/guide/router.html#!#activated-route
I would normally go for .loc/.iloc
as suggested by Ted, but one may also select a row by tranposing the DataFrame. To stay in the example above, df.T[2]
gives you row 2 of df
.
using
is for namespaces only - if both classes are in the same namespace just drop the using
.
You have to reference the assembly created in the first step when you compile the .exe:
csc /t:library /out:MyClass.dll MyClass.cs
csc /reference:MyClass.dll /t:exe /out:MyProgram.exe MyMainClass.cs
You can make things simpler if you just compile the files together:
csc /t:exe /out:MyProgram.exe MyMainClass.cs MyClass.cs
or
csc /t:exe /out:MyProgram.exe *.cs
EDIT: Here's how the files should look like:
MyClass.cs:
namespace MyNamespace {
public class MyClass {
void stuff() {
}
}
}
MyMainClass.cs:
using System;
namespace MyNamespace {
public class MyMainClass {
static void Main() {
MyClass test = new MyClass();
}
}
}
os.path.getsize(path)
Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<newBooks>
<xsl:for-each select="books/book">
<newBook>
<countNo><xsl:value-of select="position()"/></countNo>
<title>
<xsl:value-of select="title"/>
</title>
</newBook>
</xsl:for-each>
</newBooks>
</xsl:template>
</xsl:stylesheet>
Select the text of all items under produce:
//produce/item/text()
Select all the manager nodes in all departments:
//department/*
I managed to fix this by changing settings for new projects:
File -> New Projects Settings -> Settings for New Projects -> Java Compiler -> Set the version
File -> New Projects Settings -> Structure for New Projects -> Project -> Set Project SDK + set language level
Remove the projects
Import the projects
Typically you must set java.library.path
on the JVM's command line:
java -Djava.library.path=/path/to/my/dll -cp /my/classpath/goes/here MainClass
I also followed Josh Frankel's advice and created a Sublime Macro + added key binding. The difference is that this script ensures that spacing is first set to tabs and set to a tab size of 2. The macro won't work if that's not the starting point.
Here's a gist of the macro: https://gist.github.com/drivelous/aa8dc907de34efa3e462c65a96e05f09
In Mac, to use the macro + key binding:
spaces2to4.sublime-macro
and copy/paste the code from the gist. For me this is located at:
/Library/Application\ Support/Sublime\ Text\ 3/Packages/User/spaces2to4.sublime-macro
Sublime Text
> Preferences
> Key Bindings
{
"keys": ["super+shift+o"],
"command": "run_macro_file",
"args": {
"file":"Packages/User/spaces2to4.sublime-macro"
}
}
Now ? + shift + o
now automatically converts each file from 2 space indentation to 4 (but will keep indenting if you run it further)
Yes, the first means "match all strings that start with a letter", the second means "match all strings that contain a non-letter". The caret ("^") is used in two different ways, one to signal the start of the text, one to negate a character match inside square brackets.
file
-> Project Structure
-> Modules
, find the module with problems, click it and choose the Dependencies
tab in the right side. Click the green plus sign, try to add the jar or libraries that cause the problem. That works for me.
I had the same issue and realized that removing the parentheses worked. Sometimes having someone else read your code can be useful if you have been the only one working on it for some time.
E.g.
cmd.CommandType = CommandType.Text();
Replace: cmd.CommandType = CommandType.Text;
If you have updated your android studio, then go to FILE, Project Structure, Project, then check gradle version. Before that check your gradle version in C:\Program Files\Android\Android Studio\gradle and check the version if it matches then sync again else change the gradle version in android studio and sync again.
You just need to rename ib_logfile0 and ib_logfile1 as ib_logfile_0 and ib_logfile_1. Then your problem would be solved.
Check if the text you're trying to append to the node is not escaped like this:
var prop = {
match: {
description: '<h1>Hi there!</h1>'
}
};
Instead of this:
var prop = {
match: {
description: '<h1>Hi there!</h1>'
}
};
if is escaped you should convert it from your server-side.
The node is text because is escaped
The node is a dom node because isn't escaped
This answer is more meant to explain why, not how. The '=='
operator in R is vectorized in a same way as the '+'
operator. It matches the elements of whatever is on the left side to the elements of whatever is on the right side, per element. For example:
> 1:3 == 1:3
[1] TRUE TRUE TRUE
Here the first test is 1==1
which is TRUE, the second 2==2
and the third 3==3
. Notice that this returns a FALSE in the first and second element because the order is wrong:
> 3:1 == 1:3
[1] FALSE TRUE FALSE
Now if one object is smaller then the other object then the smaller object is repeated as much as it takes to match the larger object. If the size of the larger object is not a multiplication of the size of the smaller object you get a warning that not all elements are repeated. For example:
> 1:2 == 1:3
[1] TRUE TRUE FALSE
Warning message:
In 1:2 == 1:3 :
longer object length is not a multiple of shorter object length
Here the first match is 1==1
, then 2==2
, and finally 1==3
(FALSE) because the left side is smaller. If one of the sides is only one element then that is repeated:
> 1:3 == 1
[1] TRUE FALSE FALSE
The correct operator to test if an element is in a vector is indeed '%in%'
which is vectorized only to the left element (for each element in the left vector it is tested if it is part of any object in the right element).
Alternatively, you can use '&'
to combine two logical statements. '&'
takes two elements and checks elementwise if both are TRUE:
> 1:3 == 1 & 1:3 != 2
[1] TRUE FALSE FALSE
How about catching the exception that gets generated from the assertion failure? In your catch block you could output the data however you wanted to wherever. Then when you were done you could re-throw the exception. The test runner probably wouldn't know the difference.
Disclaimer: I haven't tried this with python's unit test framework but have with other unit test frameworks.
I have used mpdf in my project. In Codeigniter-3, putted mpdf files under application/third_party and then used in this way:
/**
* This function is used to display data in PDF file.
* function is using mpdf api to generate pdf.
* @param number $id : This is unique id of table.
*/
function generatePDF($id){
require APPPATH . '/third_party/mpdf/vendor/autoload.php';
//$mpdf=new mPDF();
$mpdf = new mPDF('utf-8', 'Letter', 0, '', 0, 0, 7, 0, 0, 0);
$checkRecords = $this->user_model->getCheckInfo($id);
foreach ($checkRecords as $key => $value) {
$data['info'] = $value;
$filename = $this->load->view(CHEQUE_VIEWS.'index',$data,TRUE);
$mpdf->WriteHTML($filename);
}
$mpdf->Output(); //output pdf document.
//$content = $mpdf->Output('', 'S'); //get pdf document content's as variable.
}
Have you tried using the 'static' storage class similar to?:
public static class employee
{
static NameValueCollection appSetting = ConfigurationManager.AppSettings;
}
function foo() { ... }
Because of function hoisting, the function declared this way can be called both after and before the definition.
Named Function Expression
var foo = function bar() { ... }
Anonymous Function Expression
var foo = function() { ... }
foo()
can be called only after creation.
(function() { ... }());
Crockford recommends to use function expression because it makes it clear that foo
is a variable containing a function value. Well, personally, I prefer to use Declaration unless there is a reason for Expression.
Once installed in windows Followed the instructions starting from Run SQL Command Line (command prompt)
then... v. SQL> connect /as sysdba
Connected. [SQL prompt response]
vi. SQL> alter user SYS identified by "newpassword";
User altered. [SQL prompt response]
Thank you. This minimized a headache
you can use scrollto(x,y) function to handle the position of scrollbar right to the point that you need to be showed after zooming.for finding the position of mouse use event.clientX and event.clientY. this will help you
I used just "save in zoom", in example:
.my_checkbox {
width:5vw;
height:5vh;
}
Angular 2, 4 and Angular 5 compatible!
You have provided so few details, so I'll try to answer your question without them.
You can use Interpolation:
<img src={{imagePath}} />
Or you can use a template expression:
<img [src]="imagePath" />
In a ngFor loop it might look like this:
<div *ngFor="let student of students">
<img src={{student.ImagePath}} />
</div>
This is one that I like to ask at parties (which is probably why I don't get invited anymore):
Can you make the following piece of code compile?
public void Foo()
{
this = new Teaser();
}
An easy cheat could be:
string cheat = @"
public void Foo()
{
this = new Teaser();
}
";
But the real solution is this:
public struct Teaser
{
public void Foo()
{
this = new Teaser();
}
}
So it's a little know fact that value types (structs) can reassign their this
variable.
And you can use HTML5's autofocus attribute (works in all current browsers except IE9 and below). Only call your script if it's IE9 or earlier, or an older version of other browsers.
<input type="text" name="fname" autofocus>
Please also see this Microsoft Connect report on essentially, how blummin' difficult it is to use PowerShell to run shell commands (oh, the irony).
http://connect.microsoft.com/PowerShell/feedback/details/376207/
They suggest using --%
as a way to force PowerShell to stop trying to interpret the text to the right.
For example:
MSBuild /t:Publish --% /p:TargetDatabaseName="MyDatabase";TargetConnectionString="Data Source=.\;Integrated Security=True" /p:SqlPublishProfilePath="Deploy.publish.xml" Database.sqlproj
I adopted the @Jotne solution and works perfectly! For example for mongodb server in my NAS
#! /bin/bash
case "$(pidof mongod | wc -w)" in
0) echo "Restarting mongod:"
mongod --config mongodb.conf
;;
1) echo "mongod already running"
;;
esac
Use the \
character to escape a character that has special meaning inside a regular expression.
To automate it, you could use this:
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape
Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.
If this is a Magento related problem, you should turn off automatic re-indexing as this could be causing the socket to timeout (or expire). You can turn it back on once the script has finished its tasks. Increasing the default socket timeout in php.ini is also a good idea.
RESULT
HTML
<ul class="list">
<li>This is the text</li>
<li>This is another text</li>
<li>This is another another text</li>
</ul>
Use align-items
instead of align-self
and I also added flex-direction
to column
.
CSS
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
html,
body {
height: 100%;
}
.list {
display: flex;
justify-content: center;
flex-direction: column; /* <--- I added this */
align-items: center; /* <--- Change here */
height: 100px;
width: 100%;
background: silver;
}
.list li {
background: gold;
height: 20%;
}
There are two different ways of generating a UUID.
If you just need a unique ID, you want a version 1 or version 4.
Version 1: This generates a unique ID based on a network card MAC address and a timer. These IDs are easy to predict (given one, I might be able to guess another one) and can be traced back to your network card. It's not recommended to create these.
Version 4: These are generated from random (or pseudo-random) numbers. If you just need to generate a UUID, this is probably what you want.
If you need to always generate the same UUID from a given name, you want a version 3 or version 5.
Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.
Version 5: This generates a unique ID from an SHA-1 hash of a namespace and name. This is the preferred version.
You can create the same behavior creating a simple custom editor called DateTime.cshtml, saving it in Views/Shared/EditorTemplates
@model DateTime
@{
var css = ViewData["class"] ?? "";
@Html.TextBox("", (Model != DateTime.MinValue? Model.ToString("dd/MM/yyyy") : string.Empty), new { @class = "calendar medium " + css});
}
and in your views
@Html.EditorFor(model => model.StartDate, new { @class = "required" })
Note that in my example I'm hard-coding two css classes and the date format. You can, of course, change that. You also can do the same with others html attributes, like readonly, disabled, etc.
For simplicity's sake: newList = list(set(oldList))
But there are better options out there if you'd like to get speed/ordering/optimization instead: http://www.peterbe.com/plog/uniqifiers-benchmark
In one of your dataframes the year is a string and the other it is an int64
you can convert it first and then join (e.g. df['year']=df['year'].astype(int)
or as RafaelC suggested df.year.astype(int)
)
Edit: Also note the comment by Anderson Zhu: Just in case you have None
or missing values in one of your dataframes, you need to use Int64
instead of int
. See the reference here.
Use xpath more directly for both performance and clarity.
time_path <- "//start-valid-time"
temp_path <- "//temperature[@type='hourly']/value"
df <- data.frame(
latitude=data[["number(//point/@latitude)"]],
longitude=data[["number(//point/@longitude)"]],
start_valid_time=sapply(data[time_path], xmlValue),
hourly_temperature=as.integer(sapply(data[temp_path], as, "integer"))
leading to
> head(df, 2)
latitude longitude start_valid_time hourly_temperature
1 29.81 -82.42 2014-02-14T18:00:00-05:00 60
2 29.81 -82.42 2014-02-14T19:00:00-05:00 55
I use FLTK because Qt is not free. I don't choose wxWidgets, because my first test with a simple Hello, World! program produced an executable of 24 MB, FLTK 0.8 MB...
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s
instead:
.replace(/\s/g,'')
You can also use .replaceAll
if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll
, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
error_reporting(E_ALL ^ E_WARNING);
:)
You should change subject to "How to fix warning from date() in PHP"...
This helps me, https://pip.pypa.io/en/stable/installing/
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
If you are using python3 and not set it default. do this,
python3 get-pip.py
It works for me.
I had same issue. One of the reasons was, my application was cached and I was performing local build.
I would prefer deleting the css file and re-adding it again with changes if none of the above comments work.
See InnerFade.
<script type="text/javascript">
$(document).ready(
function() {
$('#portfolio').innerfade({
speed: 'slow',
timeout: 10000,
type: 'sequence',
containerheight: '220px'
});
});
</script>
<ul id="portfolio">
<li>
<a href="http://medienfreunde.com/deutsch/referenzen/kreation/good_guy__bad_guy.html">
<img src="images/ggbg.gif" alt="Good Guy bad Guy" />
</a>
</li>
<li>
<a href="http://medienfreunde.com/deutsch/referenzen/kreation/whizzkids.html">
<img src="images/whizzkids.gif" alt="Whizzkids" />
</a>
</li>
<li>
<a href="http://medienfreunde.com/deutsch/referenzen/printdesign/koenigin_mutter.html">
<img src="images/km.jpg" alt="Königin Mutter" />
</a>
</li>
<li>
<a href="http://medienfreunde.com/deutsch/referenzen/webdesign/rt_reprotechnik_-_hybride_archivierung.html">
<img src="images/rt_arch.jpg" alt="RT Hybride Archivierung" />
</a>
</li>
<li>
<a href="http://medienfreunde.com/deutsch/referenzen/kommunikation/tuev_sued_gruppe.html">
<img src="images/tuev.jpg" alt="TÜV SÜD Gruppe" />
</a>
</li>
</ul>
Try to use:
easy_install lxml
That works for me, win10, python 2.7.
You can use array_column for that.
$search_value = '5465';
$search_key = 'uid';
$user = array_search($search_value, array_column($userdb, $search_key));
print_r($userdb[$user]);
5465 is the user ID you want to search, uid is the key that contains user ID and $userdb is the array that is defined in the question.
The solutions provided will actually return the current region of the device - not the currently selected language. These are often one and the same. However, if I am in North America and I set my language to Japanese, my region will still be English (United States). In order to retrieve the currently selected language, you can do:
NSString * language = [[NSLocale preferredLanguages] firstObject];
This will return a two letter code for the currently selected language. "en" for English, "es" for Spanish, "de" for German, etc. For more examples, please see this Wikipedia entry (in particular, the 639-1 column):
Then it's a simple matter of converting the two letter codes to the string you would like to display. So if it's "en", display "English".
Hope this helps someone that's looking to differentiate between region and currently selected language.
EDIT
Worth to quote the header information from NSLocale.h:
+ (NSArray *)preferredLanguages NS_AVAILABLE(10_5, 2_0); // note that this list does not indicate what language the app is actually running in; the [NSBundle mainBundle] object determines that at launch and knows that information
People interested in app language take a look at @mindvision's answer
All of the above methods didn't work for me. Using Left Ctrl + <Windows Key> + F11 worked on Linux Mint 17.
With Pandas,
wit column names
dataframe[['column1','column2']]
to select by iloc and specific columns with index number:
dataframe.iloc[:,[1,2]]
with loc column names can be used like
dataframe.loc[:,['column1','column2']]
WKWebView: I find this question to be the best place to let people know that they should start using WKWebview as UIWebView is now deprecated.
Objective C
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame];
webView.navigationDelegate = self;
NSURL *nsurl=[NSURL URLWithString:@"https://www.example.com/document.pdf"];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webView loadRequest:nsrequest];
[self.view addSubview:webView];
Swift
let myURLString = "https://www.example.com/document.pdf"
let url = NSURL(string: myURLString)
let request = NSURLRequest(URL: url!)
let webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.loadRequest(request)
view.addSubview(webView)
I haven't copied this code directly from Xcode, so it might, it might contain some syntax error. Please check while using it.
cp -Rvn /source/path/* /destination/path/
cp: /destination/path/any.zip: No such file or directory
It will create no existing paths in destination, if path have a source file inside. This dont create empty directories.
A moment ago i've seen xxxxxxxx: No such file or directory, because i run out of free space. without error message.
with ditto:
ditto -V /source/path/* /destination/path
ditto: /destination/path/any.zip: No space left on device
once freed space cp -Rvn /source/path/* /destination/path/
works as expected
To identify which x86/x64 version of VC is needed:
Go to IIS Manager > Handler Mappings > right click then Edit *.php path. In the "Executable (optional)" field note in which version of Program Files is the php-cgi.exe installed.
To clarify, the syntax is as follows for MongoDB version 4.0.x:
db.collection.update({},{$set: {"new_field*":1}},false,true)
Here is a working example adding a published field to the articles collection and setting the field's value to true:
db.articles.update({},{$set: {"published":true}},false,true)
In Mgmt Studio, when you are editing the top 200, you can view the SQL pane - either by right clicking in the grid and choosing Pane->SQL or by the button in the upper left. This will allow you to write a custom query to drill down to the row(s) you want to edit.
But ultimately mgmt studio isn't a data entry/update tool which is why this is a little cumbersome.
The syntax you have there for your function doesn't make sense (why would the return value have a member called arr
?).
To find the index, use std::distance
and std::find
from the <algorithm>
header.
int x = std::distance(arr, std::find(arr, arr + 5, 3));
Or you can make it into a more generic function:
template <typename Iter>
size_t index_of(Iter first, Iter last, typename const std::iterator_traits<Iter>::value_type& x)
{
size_t i = 0;
while (first != last && *first != x)
++first, ++i;
return i;
}
Here, I'm returning the length of the sequence if the value is not found (which is consistent with the way the STL algorithms return the last iterator). Depending on your taste, you may wish to use some other form of failure reporting.
In your case, you would use it like so:
size_t x = index_of(arr, arr + 5, 3);
Joey mentioned that Format-*
is for human consumption. If you're writing to a file for machine consumption, maybe you want to use Export-*
? Some good ones are
Export-Csv
- Comma separated value. Great for when you know what the columns are going to beExport-Clixml
- You can export whole objects and collections. This is great for serialization.If you want to read back in, you can use Import-Csv
and Import-Clixml
. I find that I like this better than inventing my own data formats (also it's pretty easy to whip up an Import-Ini
if that's your preference).
For those who are using python 2.7, python2.7 don't support django 2 so you can't install django.urls. If you are already using python 3.6 so you need to upgrade django to latest version which is greater than 2.
On PowerShell
pip install -U django
Verification
>
PS C:\Users\xyz> python
Python 3.6.6 |Anaconda, Inc.| (default, Jul 25 2018, 15:27:00) [MSC v.1910 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.urls import path
>>>
As next prompt came, it means it is installed now and ready to use.
If your aim is to redirect all pages to a single maintenance page (as the title could suggest also this), then use:
RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.php$
RewriteCond %{REMOTE_HOST} !^000\.000\.000\.000
RewriteRule $ /maintenance.php [R=302,L]
Where 000 000 000 000 should be replaced by your ip adress.
Source:
http://www.techiecorner.com/97/redirect-to-maintenance-page-during-upgrade-using-htaccess/
Starting from Rob's answer, I am currently using the following syntax.Since the question has received a lot of attention,I decided to share it with you :
var requrl = '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)';
$.ajax({
type: "POST",
url: requrl,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
}
});
Another way is to use box-shadow
:
#mybox {
box-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
-moz-box-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
-webkit-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
}
<div id="mybox">ABC</div>
See example here.
I added a reference to the .dll file, for System.Data.Linq, the above was not sufficient. You can find .dll in the various directories for the following versions.
System.Data.Linq C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll 3.5.0.0
System.Data.Linq C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.Data.Linq.dll 4.0.0.0
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
Best option is multiple updates.
Alternatively you can do the following but is NOT recommended:
UPDATE table
SET ID = CASE WHEN ID = 2555 THEN 111111259
WHEN ID = 2724 THEN 111111261
WHEN ID = 2021 THEN 111111263
WHEN ID = 2017 THEN 111111264
END
WHERE ID IN (2555,2724,2021,2017)
A server-side solution is more compatible, until the "download" attribute is implemented in all the browsers.
One Python example could be a custom HTTP request handler for a filestore. The links that point to the filestore are generated like this:
http://www.myfilestore.com/filestore/13/130787e71/download_as/desiredName.pdf
Here is the code:
class HTTPFilestoreHandler(SimpleHTTPRequestHandler):
def __init__(self, fs_path, *args):
self.fs_path = fs_path # Filestore path
SimpleHTTPRequestHandler.__init__(self, *args)
def send_head(self):
# Overwrite SimpleHTTPRequestHandler.send_head to force download name
path = self.path
get_index = (path == '/')
self.log_message("path: %s" % path)
if '/download_as/' in path:
p_parts = path.split('/download_as/')
assert len(p_parts) == 2, 'Bad download link:' + path
path, download_as = p_parts
path = self.translate_path(path )
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# Redirect browser - doing basically what Apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Expires", '0')
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.send_header("Cache-Control", 'must-revalidate, post-check=0, pre-check=0')
self.send_header("Content-Transfer-Encoding", 'binary')
if download_as:
self.send_header("Content-Disposition", 'attachment; filename="%s"' % download_as)
self.send_header("Content-Length", str(fs[6]))
self.send_header("Connection", 'close')
self.end_headers()
return f
class HTTPFilestoreServer:
def __init__(self, fs_path, server_address):
def handler(*args):
newHandler = HTTPFilestoreHandler(fs_path, *args)
newHandler.protocol_version = "HTTP/1.0"
self.server = BaseHTTPServer.HTTPServer(server_address, handler)
def serve_forever(self, *args):
self.server.serve_forever(*args)
def start_server(fs_path, ip_address, port):
server_address = (ip_address, port)
httpd = HTTPFilestoreServer(fs_path, server_address)
sa = httpd.server.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
I've seen the short-circuiting behaviour of the &&
operator used to achieve this, although people who are not accustomed to this may find it hard to read or even call it an anti-pattern:
lemons && document.write("foo gave me a bar");
Personally, I'll often use single-line if
without brackets, like this:
if (lemons) document.write("foo gave me a bar");
If I need to add more statements in, I'll put the statements on the next line and add brackets. Since my IDE does automatic indentation, the maintainability objections to this practice are moot.
moving element top: -12px or positioning it absolutely doesn't solve the problem but only masks it
I had the same problem - check if you have in one wrapping element mixed: floating elements with non-floating ones - my non-floating element caused this strange offset to the floating one
run-sequence is the most clear way (at least until Gulp 4.0 is released)
With run-sequence, your task will look like this:
var sequence = require('run-sequence');
/* ... */
gulp.task('develop', function (done) {
sequence('clean', 'coffee', done);
});
But if you (for some reason) prefer not using it, gulp.start
method will help:
gulp.task('develop', ['clean'], function (done) {
gulp.on('task_stop', function (event) {
if (event.task === 'coffee') {
done();
}
});
gulp.start('coffee');
});
Note: If you only start task without listening to result, develop
task will finish earlier than coffee
, and that may be confusing.
You may also remove event listener when not needed
gulp.task('develop', ['clean'], function (done) {
function onFinish(event) {
if (event.task === 'coffee') {
gulp.removeListener('task_stop', onFinish);
done();
}
}
gulp.on('task_stop', onFinish);
gulp.start('coffee');
});
Consider there is also task_err
event you may want to listen to.
task_stop
is triggered on successful finish, while task_err
appears when there is some error.
You may also wonder why there is no official documentation for gulp.start()
. This answer from gulp member explains the things:
gulp.start
is undocumented on purpose because it can lead to complicated build files and we don't want people using it
(source: https://github.com/gulpjs/gulp/issues/426#issuecomment-41208007)
Here's something I've just knocked up. It inspects the environment of the last-launched "gnome-session" process (DISPLAY is set correctly when VNC launches a session/window manager). Replace "gnome-session" with the name of whatever process your VNC server launches on startup.
PID=`pgrep -n -u $USER gnome-session`
if [ -n "$PID" ]; then
export DISPLAY=`awk 'BEGIN{FS="="; RS="\0"} $1=="DISPLAY" {print $2; exit}' /proc/$PID/environ`
echo "DISPLAY set to $DISPLAY"
else
echo "Could not set DISPLAY"
fi
unset PID
You should just be able to drop that in your .bashrc file.
I have another method for finding the last element in a vector.
Say the vector is a
.
> a<-c(1:100,555)
> end(a) #Gives indices of last and first positions
[1] 101 1
> a[end(a)[1]] #Gives last element in a vector
[1] 555
There you go!
This will be compiled into:
React.createElement(Modal, { ...this.props, title: "Modal heading", animation: false }, child0, child1, child2, ...)
where it gives more two properties title
& animation
beyond the props
the host element has.
...
is the ES6 operator called Spread.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:
SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName
I believe the best way to view revisions is to use a program/app that makes it easy for you. I like to use trac : http://trac.edgewall.org/wiki/TracSubversion
It provides a great svn browser and makes it really easy to go back through your revisions.
It may be a little overkill to set this up for one specific revision you want to check, but it could be useful if you're going to do this a lot in the future.
This is an old post and the links are no longer valid but because it came up early in a search I was doing I thought I should comment to help others understand the problem better.
By using float you are asking the browser to arrange your controls automatically. It responds by wrapping when the controls don't fit the width for their specified float arrangement. float:left, float:right or clear:left,clear:right,clear:both.
So if you want to force a bunch of float:left items to float uniformly into one left column then you need to make the browser decide to wrap/unwrap them at the same width. Because you don't want to do any scripting you can wrap all of the controls you want to float together in a single div. You would want to add a new wrapping div with a class like:
.LeftImages{
float:left;
}
html
<div class="LeftImages">
<img...>
<img...>
</div>
This div will automatically adjust to the width of the largest image and all the images will be floated left with the div all the time (no wrapping).
If you still want them to wrap you can give the div a width like width:30% and each of the images the float:left; style. Rather than adjust to the largest image it will vary in size and allow the contained images to wrap.
The unresponsive script dialog box shows when some javascript thread takes too long too complete. Editing the registry could work, but you would have to do it on all client machines. You could use a "recursive closure" as follows to alleviate the problem. It's just a coding structure in which allows you to take a long running for loop and change it into something that does some work, and keeps track where it left off, yielding to the browser, then continuing where it left off until we are done.
Figure 1, Add this Utility Class RepeatingOperation to your javascript file. You will not need to change this code:
RepeatingOperation = function(op, yieldEveryIteration) {
//keeps count of how many times we have run heavytask()
//before we need to temporally check back with the browser.
var count = 0;
this.step = function() {
//Each time we run heavytask(), increment the count. When count
//is bigger than the yieldEveryIteration limit, pass control back
//to browser and instruct the browser to immediately call op() so
//we can pick up where we left off. Repeat until we are done.
if (++count >= yieldEveryIteration) {
count = 0;
//pass control back to the browser, and in 1 millisecond,
//have the browser call the op() function.
setTimeout(function() { op(); }, 1, [])
//The following return statement halts this thread, it gives
//the browser a sigh of relief, your long-running javascript
//loop has ended (even though technically we havn't yet).
//The browser decides there is no need to alarm the user of
//an unresponsive javascript process.
return;
}
op();
};
};
Figure 2, The following code represents your code that is causing the 'stop running this script' dialog because it takes so long to complete:
process10000HeavyTasks = function() {
var len = 10000;
for (var i = len - 1; i >= 0; i--) {
heavytask(); //heavytask() can be run about 20 times before
//an 'unresponsive script' dialog appears.
//If heavytask() is run more than 20 times in one
//javascript thread, the browser informs the user that
//an unresponsive script needs to be dealt with.
//This is where we need to terminate this long running
//thread, instruct the browser not to panic on an unresponsive
//script, and tell it to call us right back to pick up
//where we left off.
}
}
Figure 3. The following code is the fix for the problematic code in Figure 2. Notice the for loop is replaced with a recursive closure which passes control back to the browser every 10 iterations of heavytask()
process10000HeavyTasks = function() {
var global_i = 10000; //initialize your 'for loop stepper' (i) here.
var repeater = new this.RepeatingOperation(function() {
heavytask();
if (--global_i >= 0){ //Your for loop conditional goes here.
repeater.step(); //while we still have items to process,
//run the next iteration of the loop.
}
else {
alert("we are done"); //when this line runs, the for loop is complete.
}
}, 10); //10 means process 10 heavytask(), then
//yield back to the browser, and have the
//browser call us right back.
repeater.step(); //this command kicks off the recursive closure.
};
Adapted from this source:
You get the error because you imported wrong package.You should import android.widget.CompoundButton.OnCheckedChangeListener;
So the callback should be :
box.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
}
});
Make sure that your WebAPI service is expecting a strongly typed object with a structure that matches the JSON that you are passing. And make sure that you stringify the JSON that you are POSTing.
Here is my JavaScript (using AngluarJS):
$scope.updateUserActivity = function (_objuserActivity) {
$http
({
method: 'post',
url: 'your url here',
headers: { 'Content-Type': 'application/json'},
data: JSON.stringify(_objuserActivity)
})
.then(function (response)
{
alert("success");
})
.catch(function (response)
{
alert("failure");
})
.finally(function ()
{
});
And here is my WebAPI Controller:
[HttpPost]
[AcceptVerbs("POST")]
public string POSTMe([FromBody]Models.UserActivity _activity)
{
return "hello";
}
UseParNewGC usually knowns as "parallel young generation collector" is same in all ways as the parallel garbage collector (-XX:+UseParallelGC), except that its more sophiscated and effiecient. Also it can be used with a "concurrent low pause collector".
See Java GC FAQ, question 22 for more information.
Note that there are some known bugs with UseParNewGC
In my case, I had to create local.properties file with sdk.dir=PATH_TO_ANDROID_SDK in my machine. It seems that, it's regarding the android sdk path setup. Hence, it could also be set in ANDROID_HOME env. variable too.
For version 2.4.3 (current version as of posting date), create a config file and then execute the following:
C:\MongoDB\bin\mongod.exe --config C:\MongoDB\mongod.cfg --service
This is the best way, because if user not back more than two seconds then reset backpressed value.
declare one global variable.
private boolean backPressToExit = false;
Override
onBackPressed
Method.
@Override
public void onBackPressed() {
if (backPressToExit) {
super.onBackPressed();
return;
}
this.backPressToExit = true;
Snackbar.make(findViewById(R.id.yourview), getString(R.string.exit_msg), Snackbar.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
backPressToExit = false;
}
}, 2000);
}
You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc
I create sample here, just change ImageView into ClickableImageView from your layout. Hope it help.
I would like to share my experience with \n
I came to notice that "\n" works as-
puts "\n\n" // to provide 2 new lines
but not
p "\n\n"
also
puts '\n\n'
Doesn't works.
Hope will work for you!!