Well!! I found this way convenient , check for the height attribute of image to be 0, then you can overwrite the src attribute with default image: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
image.setAttribute('src','../icons/<some_image>.png');
//check the height attribute.. if image is available then by default it will
//be 100 else 0
if(image.height == 0){
image.setAttribute('src','../icons/default.png');
}
In plt.colorbar(z1_plot,cax=ax1)
, use ax=
instead of cax=
, i.e. plt.colorbar(z1_plot,ax=ax1)
In my case i had a findViewById reference to a view i had deleted in xml
if you are running AS 3.1 and above:
you should see the full stacktrace in the expanded view and the specific error.
You can change the value of a static readonly string
only in the static
constructor of the class or a variable initializer, whereas you cannot change the value of a const
string anywhere.
I would like to re-structure the statement that you mentioned which is:
This means that the state as consumed by your target component can have a wildly different structure from the state as it is stored on your store
You can say that the state consumed by your target component has a small portion of the state that is stored on the redux store. In other words, the state consumed by your component would be the sub-set of the state of the redux store.
As far as understanding the connect() method is concerned, it's fairly simple! connect() method has the power to add new props to your component and even override existing props. It is through this connect method that we can access the state of the redux store as well which is thrown to us by the Provider. A combination of which works in your favor and you get to add the state of your redux store to the props of your component.
Above is some theory and I would suggest you look at this video once to understand the syntax better.
Code Snippet:
div{height: calc(100vh - 10vmax)}
Ok, this is a very interesting problem I researched a lot and came to a conclusion that private members of a superclass are indeed available (but not accessible) in the subclass's objects. To prove this, here is a sample code with a parent class and a child class and I am writing child class object to a txt file and reading a private member named 'bhavesh' in the file, hence proving it is indeed available in the child class but not accessible due to the access modifier.
import java.io.Serializable;
public class ParentClass implements Serializable {
public ParentClass() {
}
public int a=32131,b,c;
private int bhavesh=5555,rr,weq,refw;
}
import java.io.*;
import java.io.Serializable;
public class ChildClass extends ParentClass{
public ChildClass() {
super();
}
public static void main(String[] args) {
ChildClass childObj = new ChildClass();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(new FileOutputStream("C:\\MyData1.txt"));
oos.writeObject(childObj); //Writing child class object and not parent class object
System.out.println("Writing complete !");
} catch (IOException e) {
}
}
}
Open MyData1.txt and search for the private member named 'bhavesh'. Please let me know what you guys think.
@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.
movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
var url:String = "http://site";
var request:URLRequest = new URLRequest(url);
try {
navigateToURL(request, '_blank');
} catch (e:Error) {
trace("Error occurred!");
}
}
source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/
You need a loop over the lines of a file, you need to learn about string methods
with open(filename,'r') as f:
for line in f.readlines():
# python can do regexes, but this is for s fixed string only
if "something" in line:
idx1 = line.find('"')
idx2 = line.find('"', idx1+1)
field = line[idx1+1:idx2-1]
print(field)
and you need a method to pass the filename to your python program and while you are at it, maybe also the string to search for...
For the future, try to ask more focused questions if you can,
Since no one* has mentioned it: concurrency. Static variables can surprise you if you have multiple threads reading and writing to the static variable. This is common in web applications (e.g., ASP.NET) and it can cause some rather maddening bugs. For example, if you have a static variable that is updated by a page, and the page is requested by two people at "nearly the same time", one user may get the result expected by the other user, or worse.
statics reduce the inter-dependencies on the other parts of the code. They can act as perfect state holders
I hope you're prepared to use locks and deal with contention.
*Actually, Preet Sangha mentioned it.
As JoshC said, the class .sr-only
is used to visually hide the information used for screen readers only. But not only to hide labels. You might consider hiding various other elements such as "skip to main content" link, icons which have an alternative texts etc.
BTW. you can also use .sr-only sr-only-focusable
if you need the element to become visible when focused e.g. "skip to main content"
If you want make your website even more accessible I recommend to start here:
Why?
According to the World Health Organization, 285 million people have vision impairments. So making a website accessible is important.
IMPORTANT: Avoid treating disabled users differently. Generally speaking try to avoid developing a different content for different groups of users. Instead try to make accessible the existing content so that it simply works out-of-the-box and for all not specifically targeting e.g. screen readers. In other words don't try to reinvent the wheel. Otherwise the resulting accessibility will often be worse than if there was nothing developed at all. We developers should not assume how those users will use our website. So be very careful when you need to develop such solutions. Obviously a "skip link" is a good example of such content if it's made visible when focused. But there many bad examples too. Such would be hiding from a screen reader a "zoom" button on the map assuming that it has no relevance to blind users. But surprisingly, a zoom function indeed is used among blind users! They like to download images like many other users do (even in high resolution), for sending them to somebody else or for using them in some other context. Source - Read more @ADG: Bad ARIA practices
The option that I tend to use, mostly because it's simple and I don't have to think, is using Write-Output as below. Write-Output will put an EOL marker in the string for you and you can simply output the finished string.
Write-Output $stringThatNeedsEOLMarker | Out-File -FilePath PathToFile -Append
Alternatively, you could also just build the entire string using Write-Output and then push the finished string into Out-File.
every minute:
* * * * * /path/to/php /var/www/html/a.php
every 24hours (every midnight):
0 0 * * * /path/to/php /var/www/html/reset.php
See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml
json.dumps()
converts a dictionary to str
object, not a json(dict)
object! So you have to load your str
into a dict
to use it by using json.loads()
method
See json.dumps()
as a save method and json.loads()
as a retrieve method.
This is the code sample which might help you understand it more:
import json
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict
You may also set {{ant.build.javac.target=1.5}}
ant property to update default target version of task.
See http://ant.apache.org/manual/javacprops.html#target
It depends exactly what you're defining as "ASCII", but I would suggest trying a variant of a query like this:
SELECT * FROM tableName WHERE columnToCheck NOT REGEXP '[A-Za-z0-9]';
That query will return all rows where columnToCheck contains any non-alphanumeric characters. If you have other characters that are acceptable, add them to the character class in the regular expression. For example, if periods, commas, and hyphens are OK, change the query to:
SELECT * FROM tableName WHERE columnToCheck NOT REGEXP '[A-Za-z0-9.,-]';
The most relevant page of the MySQL documentation is probably 12.5.2 Regular Expressions.
The answer that won the bounty is correct, but it doesn't work if the first row of the table has a merged/joined cell (all the cells get equal width).
In this case you should use the colgroup
and col
tags to display it properly:
<table style="table-layout: fixed; width: 200px">
<colgroup>
<col style="width: 30%;">
<col style="width: 70%;">
</colgroup>
<tr>
<td colspan="2">Merged cell</td>
</tr>
<tr>
<td style="word-wrap: break-word">VeryLongWordInThisCell</td>
<td style="word-wrap: break-word">Cell 2</td>
</tr>
</table>
These are all good answers but if you want an aggregate function to do this to grab the last row in the result set generated by an arbitrary query, there's a standard way to do this (taken from the Postgres wiki, but should work in anything conforming reasonably to the SQL standard as of a decade or more ago):
-- Create a function that always returns the last non-NULL item
CREATE OR REPLACE FUNCTION public.last_agg ( anyelement, anyelement )
RETURNS anyelement LANGUAGE SQL IMMUTABLE STRICT AS $$
SELECT $2;
$$;
-- And then wrap an aggregate around it
CREATE AGGREGATE public.LAST (
sfunc = public.last_agg,
basetype = anyelement,
stype = anyelement
);
It's usually preferable to do select ... limit 1
if you have a reasonable ordering, but this is useful if you need to do this within an aggregate and would prefer to avoid a subquery.
See also this question for a case where this is the natural answer.
use MM
(months) instead of mm
(minutes) :
DateTime.Now.ToString("dd/MM/yyyy");
check here for more format options.
One thing that should be considered is licensing.
Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.
To quote the Sublime Text 2 website:
..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.
The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.
Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.
This licensing requirement is still correct as of Dec 2019.
i use this
<style>
html, body{height:100%;margin:0;padding:0 0}
.container-fluid{height:100%;display:table;width:100%;padding-right:0;padding-left: 0}
.row-fluid{height:100%;display:table-cell;vertical-align:middle;width:100%}
.centering{float:none;margin:0 auto}
</style>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="offset3 span6 centering">
content here
</div>
</div>
</div>
</body>
cleaned solution :
$.fn.donetyping = function(callback, delay){
delay || (delay = 1000);
var timeoutReference;
var doneTyping = function(elt){
if (!timeoutReference) return;
timeoutReference = null;
callback(elt);
};
this.each(function(){
var self = $(this);
self.on('keyup',function(){
if(timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function(){
doneTyping(self);
}, delay);
}).on('blur',function(){
doneTyping(self);
});
});
return this;
};
The forward declaration is an "incomplete type", the only thing you can do with such a type is instantiate a pointer to it, or reference it in a function declaration (i.e. and argument or return type in a function prototype). In line 52 in your code, you are attempting to instantiate an object.
At that point the compiler has no knowledge of the object's size nor its constructor, so cannot instantiate an object.
In mongodb 3.4 we can use below logic, i am not sure about previous versions
select roll from student ==> db.student.find(!{}, {roll:1})
the above logic helps to define some columns (if they are less)
It's between the Z and the C on your keyboard.
Not taking anything away from Nikos' awesome answer, perhaps you can do this more simply:
<form name="telForm">
<input name="cb" type='checkbox' data-ng-modal='requireTel'>
<input name="tel" type="text" ng-model="..." ng-if='requireTel' ng-pattern="phoneNumberPattern" required/>
<button type="submit" ng-disabled="telForm.$invalid || telForm.$pristine">Submit</button>
</form>
Pay attention to the second input: We can use an ng-if
to control rendering and validation in forms.
If the requireTel
variable is unset, the second input would not only be hidden, but not rendered at all, thus the form will pass validation and the button will become enabled, and you'll get what you need.
You can use quotemeta (\Q \E)
if your Perl is version 5.16 or later, but if below you can simply avoid using a regular expression at all.
For example, by using the index
command:
if (index($text_to_search, $search_string) > -1) {
print "wee";
}
This is not an answer to the question but as I found this page while looking to an answer to a problem that I had, I want to mention the solution that I found as it cost me a lot of time. In the hope this will be useful to others:
The problem was that text in a <p> tag would not fold in the div. Eventually, I opened the inspector and noticed a 'no breaking space entity' between all the words. My editor, vi, was just showing normal blank spaces (some invisible chr, I don't know what) but I had copied pasted the text from a PDF document. The solution was to copy a blank space from within vi and replace it with a blank space. ie. :%s/ / /g where the blank to be replaced was copied from the offending text. Problem solved.
For Xamarin Developers, you can use:
intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
Generate a Ruby on Rails migration:
$:> rails g migration Fixcolumnname
Insert code in the migration file (XXXXXfixcolumnname.rb):
class Fixcolumnname < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
Try deleting the meta data and rebuild project.
There are updated now and then, just keep checking for the latest version.
To provide some timing figures behind the different approaches, consider the following code. The get() is my custom addition to Python's setobject.c, being just a pop() without removing the element.
from timeit import *
stats = ["for i in xrange(1000): iter(s).next() ",
"for i in xrange(1000): \n\tfor x in s: \n\t\tbreak",
"for i in xrange(1000): s.add(s.pop()) ",
"for i in xrange(1000): s.get() "]
for stat in stats:
t = Timer(stat, setup="s=set(range(100))")
try:
print "Time for %s:\t %f"%(stat, t.timeit(number=1000))
except:
t.print_exc()
The output is:
$ ./test_get.py
Time for for i in xrange(1000): iter(s).next() : 0.433080
Time for for i in xrange(1000):
for x in s:
break: 0.148695
Time for for i in xrange(1000): s.add(s.pop()) : 0.317418
Time for for i in xrange(1000): s.get() : 0.146673
This means that the for/break solution is the fastest (sometimes faster than the custom get() solution).
First backup the old database called HRMS and edit the script file with replace the word HRMS to SUNHRM. After this step import the database file to the mysql
I like to use the following to get a nicely sorted listing of the current dir:
> dir . /s /b sortorder:N
There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).
You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:
Company: Vodafone
------------------
LSE symbol: VOD
in Google: LON:VOD
in Yahoo: VOD.L
NASDAQ symbol: VOD
in Google: NASDAQ:VOD
in Yahoo: VOD
@Autowired
to autowire(or search) by-type
@Qualifier
to autowire(or search) by-name
Other alternate option for @Qualifier
is @Primary
@Component
@Qualifier("beanname")
public class A{}
public class B{
//Constructor
@Autowired
public B(@Qualifier("beanname")A a){...} // you need to add @autowire also
//property
@Autowired
@Qualifier("beanname")
private A a;
}
//If you don't want to add the two annotations, we can use @Resource
public class B{
//property
@Resource(name="beanname")
private A a;
//Importing properties is very similar
@Value("${property.name}") //@Value know how to interpret ${}
private String name;
}
more about @value
These are the shift operators
x << y Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
Better way, with solution to tab and chrome problem and new jquery way
$("#element").on("focus keyup", function(e){
var keycode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
if(keycode === 9 || !keycode){
// Hacemos select
var $this = $(this);
$this.select();
// Para Chrome's que da problema
$this.on("mouseup", function() {
// Unbindeamos el mouseup
$this.off("mouseup");
return false;
});
}
});
Please see this.
Text inside a CDATA section will be ignored by the parser.
http://www.w3schools.com/xml/dom_cdatasection.asp
This is will help you to understand the basics about XML
You need to escape your backslash by preceding it with, yes, another backslash:
print("\\")
And for versions prior to Python 3:
print "\\"
The \
character is called an escape character, which interprets the character following it differently. For example, n
by itself is simply a letter, but when you precede it with a backslash, it becomes \n
, which is the newline character.
As you can probably guess, \
also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.
Make sure your
AutowiringSpringBeanJobFactory extends SpringBeanJobFactory
dependency is pulled from
"org.springframework:spring-context-support:4..."
and NOT from
"org.springframework:spring-support:2..."
It wanted me to use
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler)
instead of
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle)
so was failing to autowire job instance.
$.browser
has been removed from JQuery 1.9. You can to use Modernizr project instead
http://jquery.com/upgrade-guide/1.9/#jquery-browser-removed
UPDATE TO SUPPORT IE 10 AND IE 11 (TRIDENT version)
To complete the @daniel.moura answer, here is a version which support IE 11 and +
var matched, browser;
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie)[\s?]([\w.]+)/.exec( ua ) ||
/(trident)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
//IE 11+ fix (Trident)
matched.browser = matched.browser == 'trident' ? 'msie' : matched.browser;
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
// log removed - adds an extra dependency
//log(jQuery.browser)
Terminal opens a login shell. This means, ~/.bash_profile
will get executed, ~/.bashrc
not.
The solution on most systems is to "require" the ~/.bashrc
in the ~/.bash_profile
: just put this snippet in your ~/.bash_profile
:
[[ -s ~/.bashrc ]] && source ~/.bashrc
here are few differences between Comparator and Comparable I found on web :
If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.
Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.
If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Array.sort() method and object will be sorted based on there natural order defined by CompareTo method.
Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.
site:How to use Comparator and Comparable in Java? With example
Read more: How to use Comparator and Comparable in Java? With example
You can use :
composer self-update --2
To update to 2.0.8 version (Latest stable version)
Starting with 1.6.4, Arduino IDE can be used to program and upload the NodeMCU board by installing the ESP8266 third-party platform package (refer https://github.com/esp8266/Arduino):
To install additional ESP8266WiFi library:
After above steps, you should compile the sketch normally.
var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
console.log(key + ': ' + value);
});
yields the attributes of obj
with their respective values:
name: Krishna
gender: male
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
Took me a while to find this but note that if you have a spacing error you will also get the same error:
[: =: unary operator expected
Correct:
if [ "$APP_ENV" = "staging" ]
vs
if ["$APP_ENV" = "staging" ]
As always setting -x
debug variable helps to find these:
set -x
Open a command prompt window. If you have a default instance of SQL Server already running, run the following command on the command prompt to stop the SQL Server service:
net stop mssqlserver
Now go to the directory where SQL server is installed. The directory can for instance be one of these:
C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn
C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Binn
Figure out your MSSQL directory and CD
into it as such:
CD C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn
Now run the following command to start SQL Server in single user mode. As
SQLCMD
is being specified, only one SQLCMD
connection can be made (from another command prompt window).
sqlservr -m"SQLCMD"
Now, open another command prompt window as the same user as the one that started SQL Server in single user mode above, and in it, run:
sqlcmd
And press enter. Now you can execute SQL statements against the SQL Server instance running in single user mode:
create login [<<DOMAIN\USERNAME>>] from windows;
-- For older versions of SQL Server:
EXEC sys.sp_addsrvrolemember @loginame = N'<<DOMAIN\USERNAME>>', @rolename = N'sysadmin';
-- For newer versions of SQL Server:
ALTER SERVER ROLE [sysadmin] ADD MEMBER [<<DOMAIN\USERNAME>>];
GO
UPDATED
Do not forget a semicolon after ALTER SERVER ROLE [sysadmin] ADD MEMBER [<<DOMAIN\USERNAME>>];
and do not add extra semicolon after GO
or the command never executes.
This is what I used. Link button is
<div class="link-button"><a href="/">Example</a></div>
CSS
/* body is sans-serif */
.link-button {
margin-top:15px;
max-width:90px;
background-color:#eee;
border-color:#888888;
color:#333;
display:inline-block;
vertical-align:middle;
text-align:center;
text-decoration:none;
align-items:flex-start;
cursor:default;
-webkit-appearence: push-button;
border-style: solid;
border-width: 1px;
border-radius: 5px;
font-size: 1em;
font-family: inherit;
border-color: #000;
padding-left: 5px;
padding-right: 5px;
width: 100%;
min-height: 30px;
}
.link-button a {
margin-top:4px;
display:inline-block;
text-decoration:none;
color:#333;
}
.link-button:hover {
background-color:#888;
}
.link-button:active {
background-color:#333;
}
.link-button:hover a, .link-button:active a {
color:#fff;
}
its because you probaly installed wamp server and uninstall it but wampmysql.exe still running and using the default mysql port go to msconfig under services tab uncheck wampmysqld to deactivate it reboot the computer should work
I believe its in /tmp/. Check your phpinfo function though, it should say session.save_path in there somewhere.
keep using the id
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserVerification extends Model
{
protected $table = 'user_verification';
protected $fillable = [
'id',
'email',
'verification_token'
];
//$timestamps = false;
protected $primaryKey = 'verification_token';
}
and get the email :
$usr = User::find($id);
$token = $usr->verification_token;
$email = UserVerification::find($token);
Use a raw string:
>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
Note that although it looks wrong, it's actually right. There is only one backslash in the string foo
.
This happens because when you just type foo
at the prompt, python displays the result of __repr__()
on the string. This leads to the following (notice only one backslash and no quotes around the print
ed string):
>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"
And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:
>>> foo = r'baz \'
File "<stdin>", line 1
foo = r'baz \'
^
SyntaxError: EOL while scanning single-quoted string
Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:
>>> foo = 'baz \\'
>>> print(foo)
baz \
However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath()
function:
myfile = os.path.normpath('c:/folder/subfolder/file.txt')
open(myfile)
This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.
When you call for i in a:
, you are getting the actual elements, not the indexes. When we reach the last element, that is 3
, b.append(a[i+1]-a[i])
looks for a[4]
, doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like
for i in range(0, len(a)-1): Do something
Your current code won't work yet for the do something part though ;)
I had the same problem. The only solution that worked for me was adding <property = "defaultEncoding" value = "UTF-8"> to multipartResoler in spring configurations file.
You can use the IGNORE
keyword too, example:
update IGNORE table set primary_field = 'value'...............
To set the position relative to the parent you need to set the position:relative
of parent and position:absolute
of the element
$("#mydiv").parent().css({position: 'relative'});
$("#mydiv").css({top: 200, left: 200, position:'absolute'});
This works because position: absolute;
positions relatively to the closest positioned parent (i.e., the closest parent with any position property other than the default static
).
I like to use a combination of the singleton pattern with the module pattern, and init-time branching with a Global NS check, wrapped within a closure.
In a case where the environment isn't going to change after the initialization of the singleton, the use of an immediately invoked object-literal to return a module full of utilities that will persist for some duration should be fine.
I'm not passing any dependencies, just invoking the singletons within their own little world - the only goal being to: create a utilities module for event binding / unbinding (device orientation / orientation changes could also work in this case).
window.onload = ( function( _w ) {
console.log.apply( console, ['it', 'is', 'on'] );
( {
globalNS : function() {
var nameSpaces = ["utils", "eventUtils"],
nsLength = nameSpaces.length,
possibleNS = null;
outerLoop:
for ( var i = 0; i < nsLength; i++ ) {
if ( !window[nameSpaces[i]] ) {
window[nameSpaces[i]] = this.utils;
break outerLoop;
};
};
},
utils : {
addListener : null,
removeListener : null
},
listenerTypes : {
addEvent : function( el, type, fn ) {
el.addEventListener( type, fn, false );
},
removeEvent : function( el, type, fn ) {
el.removeEventListener( type, fn, false );
},
attachEvent : function( el, type, fn ) {
el.attachEvent( 'on'+type, fn );
},
detatchEvent : function( el, type, fn ) {
el.detachEvent( 'on'+type, fn );
}
},
buildUtils : function() {
if ( typeof window.addEventListener === 'function' ) {
this.utils.addListener = this.listenerTypes.addEvent;
this.utils.removeListener = this.listenerTypes.removeEvent;
} else {
this.utils.attachEvent = this.listenerTypes.attachEvent;
this.utils.removeListener = this.listenerTypes.detatchEvent;
};
this.globalNS();
},
init : function() {
this.buildUtils();
}
} ).init();
} ( window ) );
There is now also the class org.apache.http.entity.ContentType
from package org.apache.httpcomponents.httpcore
, starting from 4.2 up.
I know this post is really old but, to get the contents of an element in reference to its ID, this is what I would do:
window.onclick = e => {
console.log(e.target);
console.log(e.target.id, ' -->', e.target.innerHTML);
}
Does anything, easy like that, exists?? THANKS :))
C++ does not store class member names in compiled code, and there's no way to discover (at runtime) which members (variables/methods) class contains. In other words, you cannot iterate through members of a struct. Because there's no such mechanism, you won't be able to automatically create "JSONserialize" for every object.
You can, however, use any json library to serialize objects, BUT you'll have to write serialization/deserialization code yourself for every class. Either that, or you'll have to create serializeable class similar to QVariantMap that'll be used instead of structs for all serializeable objects.
In other words, if you're okay with using specific type for all serializeable objects (or writing serialization routines yourself for every class), it can be done. However, if you want to automatically serialize every possible class, you should forget about it. If this feature is important to you, try another language.
I met similar problem. the log is like below
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: still could not bind()
2018/10/31 12:54:23 [alert] 127997#127997: unlink() "/run/nginx.pid" failed (2: No such file or directory)
2018/10/31 22:40:48 [info] 36948#36948: Using 32768KiB of shared memory for push module in /etc/nginx/nginx.conf:68
2018/10/31 22:50:40 [emerg] 37638#37638: duplicate listen options for [::]:80 in /etc/nginx/sites-enabled/default:18
2018/10/31 22:51:33 [info] 37787#37787: Using 32768KiB of shared memory for push module in /etc/nginx/nginx.conf:68
The last [emerg]
shows that duplicate listen options for [::]:80
which means that there are more than one nginx block file containing [::]:80
.
My solution is to remove one of the [::]:80
setting
P.S. you probably have default block file. My advice is to keep this file as default server for port 80. and remove [::]:80
from other block files
Found a likely answer in /jstillwell's posts here: https://github.com/stefanocudini/leaflet-gps/issues/15 basically this feature will not be supported (in Chrome only?) in the future, but only for HTTP sites. HTTPS will still be ok, and there are no plans to create an equivalent replacement for HTTP use.
A quick algorithm that simulates the way that it work is the following:
public int toByte(int number) {
int tmp = number & 0xff
return (tmp & 0x80) == 0 ? tmp : tmp - 256;
}
How this work ? Look to daixtr answer. A implementation of exact algorithm discribed in his answer is the following:
public static int toByte(int number) {
int tmp = number & 0xff;
if ((tmp & 0x80) == 0x80) {
int bit = 1;
int mask = 0;
for(;;) {
mask |= bit;
if ((tmp & bit) == 0) {
bit <<=1;
continue;
}
int left = tmp & (~mask);
int right = tmp & mask;
left = ~left;
left &= (~mask);
tmp = left | right;
tmp = -(tmp & 0xff);
break;
}
}
return tmp;
}
As an echo to @Bactisme's response, the way one would go about retrieving the current timestamp (in milliseconds, for example) is:
msec := time.Now().UnixNano() / 1000000
Resource: https://gobyexample.com/epoch
Here is a version that I copied from https://gist.github.com/1847816, but rewritten so it's easier to read and debug. The purpose of copying the of the anchor data to another variable named "result" is because the anchor data is pretty long, and so copying a limited number of values to the result will help simplify the result.
/**
* See: https://gist.github.com/1847816
* Parse a URI, returning an object similar to Location
* Usage: var uri = parseUri("hello?search#hash")
*/
function parseUri(url) {
var result = {};
var anchor = document.createElement('a');
anchor.href = url;
var keys = 'protocol hostname host pathname port search hash href'.split(' ');
for (var keyIndex in keys) {
var currentKey = keys[keyIndex];
result[currentKey] = anchor[currentKey];
}
result.toString = function() { return anchor.href; };
result.requestUri = result.pathname + result.search;
return result;
}
i have found and easier solution to handle threads when orientation change. You can just keep an static reference to your activity/fragment and verify if its null before acting on the ui. I suggest using a try catch too:
public class DashListFragment extends Fragment {
private static DashListFragment ACTIVE_INSTANCE;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ACTIVE_INSTANCE = this;
new Handler().postDelayed(new Runnable() {
public void run() {
try {
if (ACTIVE_INSTANCE != null) {
setAdapter(); // this method do something on ui or use context
}
}
catch (Exception e) {}
}
}, 1500l);
}
@Override
public void onDestroy() {
super.onDestroy();
ACTIVE_INSTANCE = null;
}
}
I found that the above answer caused me an exception when I tried to instantiate the parser. I found the following code that resolved this at http://docstore.mik.ua/orelly/xml/sax2/ch03_02.htm.
import org.xml.sax.*;
import javax.xml.parsers.*;
XMLReader parser;
try {
SAXParserFactory factory;
factory = SAXParserFactory.newInstance ();
factory.setNamespaceAware (true);
parser = factory.newSAXParser ().getXMLReader ();
// success!
} catch (FactoryConfigurationError err) {
System.err.println ("can't create JAXP SAXParserFactory, "
+ err.getMessage ());
} catch (ParserConfigurationException err) {
System.err.println ("can't create XMLReader with namespaces, "
+ err.getMessage ());
} catch (SAXException err) {
System.err.println ("Hmm, SAXException, " + err.getMessage ());
}
I have decided that since browsers do not check for new versions of css and js files, I rename my css and js directories whenever I make a change. I use css1 to css9 and js1 to js9 as the directory names. When I get to 9, I next start over at 1. It is a pain, but it works perfectly every time. It is ridiculous to have to tell users to type .
Choosing a random pivot minimizes the chance that you will encounter worst-case O(n2) performance (always choosing first or last would cause worst-case performance for nearly-sorted or nearly-reverse-sorted data). Choosing the middle element would also be acceptable in the majority of cases.
Also, if you are implementing this yourself, there are versions of the algorithm that work in-place (i.e. without creating two new lists and then concatenating them).
Printf is actually pretty good to use if size matters. Meaning if you are running a program where memory is an issue, then printf is actually a very good and under rater solution. Cout essentially shifts bits over to make room for the string, while printf just takes in some sort of parameters and prints it to the screen. If you were to compile a simple hello world program, printf would be able to compile it in less than 60, 000 bits as opposed to cout, it would take over 1 million bits to compile.
For your situation, id suggest using cout simply because it is much more convenient to use. Although, I would argue that printf is something good to know.
Great question, and the answer is not a simple one. There is no "show me all .net core versions" command, but there's hope.
EDIT:
I'm not sure when it was added, but the info command now includes this information in its output. It will print out the installed runtimes and SDKs, as well as some other info:
dotnet --info
If you only want to see the SDKs: dotnet --list-sdks
If you only want to see installed runtimes: dotnet --list-runtimes
I'm on Windows, but I'd guess that would work on Mac or Linux as well with a current version.
Also, you can reference the .NET Core Download Archive to help you decipher the SDK versions.
OLDER INFORMATION: Everything below this point is old information, which is less relevant, but may still be useful.
See installed Runtimes:
Open C:\Program Files\dotnet\shared\Microsoft.NETCore.App
in Windows Explorer
See installed SDKs:
Open C:\Program Files\dotnet\sdk
in Windows Explorer
(Source for the locations: A developer's blog)
In addition, you can see the latest Runtime and SDK versions installed by issuing these commands at the command prompt:
dotnet
Latest Runtime version is the first thing listed. DISCLAIMER: This no longer works, but may work for older versions.
dotnet --version
Latest SDK version DISCLAIMER: Apparently the result of this may be affected by any global.json config files.
On macOS you could check .net core version by using below command.
ls /usr/local/share/dotnet/shared/Microsoft.NETCore.App/
On Ubuntu or Alpine:
ls /usr/share/dotnet/shared/Microsoft.NETCore.App/
It will list down the folder with installed version name.
I was facing the same problems and found a easy solution now.
Using pathman.
pathman /as %M2%
Adds for example %M2% to the system path. Nothing more and nothing less. No more problems getting a mixture of user PATH and system PATH. No more hardly trying to get the correct values from registry...
Tried at Windows 10
Put that in onResume method:
findViewById(R.id.root_view_of_your_activity_layout).post(
new Runnable() {
public void run() {
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(yourEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
yourEditText.requestFocus();
}
});
the runnable is needed because when the OS fires the onResume method you can't be sure that all the views where draw, so the post method called from your root layout makes it wait till every view is ready.
raise SystemExit
this worked on the first try, where
self.destroy()
root.destroy()
did not
Try something like this:
awk -vc=1 'NR%1000000==0{++c}{print $0 > c".txt"}' Datafile.txt
for filename in *.txt; do mv "$filename" "Prefix_$filename"; done;
In simpler words:
key=
parameter of sort
requires a key function (to be applied to be objects to be sorted) rather than a single key value and operator.itemgetter(1)
will give you: A function that grabs the first item from a list-like object. (More precisely those are callables, not functions, but that is a difference that can often be ignored.)
Given that both strings — argv[1]
and "--foo"
— are C strings, @FelixDombek's answer is hands-down the best solution.
Seeing the other answers, however, I thought it worth noting that, if your text is already available as a std::string
, then a simple, zero-copy, maximally efficient solution exists that hasn't been mentioned so far:
const char * foo = "--foo";
if (text.rfind(foo, 0) == 0)
foo_value = text.substr(strlen(foo));
And if foo is already a string:
std::string foo("--foo");
if (text.rfind(foo, 0) == 0)
foo_value = text.substr(foo.length());
First, see if you have splitunc()
as an available function within os.path
. The first item returned should be what you want... but I am on Linux and I do not have this function when I import os
and try to use it.
Otherwise, one semi-ugly way that gets the job done is to use:
>>> pathname = "\\C:\\mystuff\\project\\file.py"
>>> pathname
'\\C:\\mystuff\\project\\file.py'
>>> print pathname
\C:\mystuff\project\file.py
>>> "\\".join(pathname.split('\\')[:-2])
'\\C:\\mystuff'
>>> "\\".join(pathname.split('\\')[:-1])
'\\C:\\mystuff\\project'
which shows retrieving the directory just above the file, and the directory just above that.
you can also try with this answer :
<img src="~/Content/img/@Html.DisplayFor(model =>model.ImagePath)" style="height:200px;width:200px;"/>
if (MessageBox.Show("Please confirm before proceed" + "\n" + "Do you want to Continue ?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
//do something if YES
}
else
{
//do something if NO
}
He're the full migration for Laravel 5:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('user_id')->nullable()->change();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('user_id')->nullable(false)->change();
});
}
The point is, you can remove nullable
by passing false
as an argument.
The ascii values of the:
Up key - 224 72
Down key - 224 80
Left key - 224 75
Right key - 224 77
Each of these has two integer values for ascii value, because they are special keys, as opposed to the code for $, which is simply 36. These 2 byte special keys usually have the first digit as either 224, or 0. this can be found with the F# in windows, or the delete key.
EDIT : This may actually be unicode looking back, but they do work.
Had the same problem. For me it worked to call
viewPage.setAdapter( adapter );
again which caused reinstantiating the pages again.
Internet Explorer (under version 9) does not natively support rounded corners.
There's an amazing script that will magically add it for you: CSS3 PIE.
I've used it a lot of times, with amazing results.
I believe my input is controlled since it has a value.
For an input to be controlled, its value must correspond to that of a state variable.
That condition is not initially met in your example because this.state.name
is not initially set. Therefore, the input is initially uncontrolled. Once the onChange
handler is triggered for the first time, this.state.name
gets set. At that point, the above condition is satisfied and the input is considered to be controlled. This transition from uncontrolled to controlled produces the error seen above.
By initializing this.state.name
in the constructor:
e.g.
this.state = { name: '' };
the input will be controlled from the start, fixing the issue. See React Controlled Components for more examples.
Unrelated to this error, you should only have one default export. Your code above has two.
The object of synchronization Semaphore implements a classical traffic light. A traffic light controls access to a resource shared by a counter. If the counter is greater than zero, access is granted; If it is zero, access is denied. The counter counts the permissions that allow access to the shared resource. Then, to access the resource, a thread must receive permission from the traffic light. In general, to use a traffic light, the thread that wants to access the shared resource tries to acquire a permit. If the traffic light count is greater than zero, the thread acquires a permit, and the traffic light count is decremented. Otherwise the thread is locked until it can get a permission. When the thread no longer needs to access the shared resource, it releases the permission, so the traffic light count is increased. If there is another thread waiting for a permit, it acquires a permit at that time. The Semaphore class of Java implements this mechanism.
Semaphore has two builders:
Semaphore(int num)
Semaphore(int num, boolean come)
num specifies the initial count of the permit. Then num specifies the number of threads that can access a shared resource at a given time. If num is one, it can access the resource one thread at a time. By setting come as true, you can guarantee that the threads you are waiting for are granted permission in the order they requested.
You could use itertools's takewhile like this, it will stop once a condition is met that fails your statement. The opposite method would be dropwhile
for x in itertools.takewhile(lambda x: x[2] == 0, list)
print x
I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:
We can enable TCP/IP protocol with WMI:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocol " _
& "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")
if tcpProtocols.Count = 1 then
' set tcpProtocol = tcpProtocols(0)
' I wish this worked, but unfortunately
' there's no int-indexed Item property in this type
' Doing this instead
for each tcpProtocol in tcpProtocols
dim setEnableResult
setEnableResult = tcpProtocol.SetEnable()
if setEnableResult <> 0 then
Wscript.Echo "Failed!"
end if
next
end if
I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)
We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456
:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocolProperty " _
& "where InstanceName='SQLEXPRESS' and " _
& "ProtocolName='Tcp' and IPAddressName='IPAll'")
for each tcpProperty in tcpProperties
dim setValueResult, requestedValue
if tcpProperty.PropertyName = "TcpPort" then
requestedValue = "3456"
elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
requestedValue = ""
end if
setValueResult = tcpProperty.SetStringValue(requestedValue)
if setValueResult = 0 then
Wscript.Echo "" & tcpProperty.PropertyName & " set."
else
Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
end if
next
Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.
Just a reminder that when working with WMI, WBEMTest.exe is your best friend!
I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:
Use LoginMode
property of Microsoft.SqlServer.Management.Smo.Server
class, as described here.
Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS
, so for my SQL Server 2008 R2 Express instance the right registry key was
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer
.
You got this one covered.
Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.
SQLCMD -U sa -P newPassword -S 192.168.0.120,3456
Please let me know if this works for you (fingers crossed!).
Use this call
$objWriter->save('php://output');
To output the XLS sheet to the page you are on, just make sure that the page you are on has no other echo's,print's, outputs.
Alternatively you could update brew
by installing it again. (Think I did this as El Capitan changed something)
Note: this is a heavy handed approach that will remove all applications installed via brew!
Try to install brew a fresh and it will tell how to uninstall.
At original time of writing to uninstall:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
Edit: As of 2020 to uninstall:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"
You can't set a number in an arbitrary place in the array without telling the array how big it needs to be. For your example: int[] array = new int[4];
The following methods actually work.
if you wish - using a theme
By default a buttons color is android:colorAccent
. So, if you create a style like this...
<style name="Button.White" parent="ThemeOverlay.AppCompat">
<item name="colorAccent">@android:color/white</item>
</style>
You can use it like this...
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/Button.White"
/>
alternatively - using a tint
You can simply add android:backgroundTint
for API Level 21 and higher, or app:backgroundTint
for API Level 7 and higher.
For more information, see this blog.
If you replace the background with a color you will loose the effect of the button, and the color will be applied to the entire area of the button. It will not respect the padding, shadow, and corner radius.
To extend on the accepted answer, you can also do:
git commit --amend --no-edit -a
to add the currently changed files.
I tried this tool and it gave me good results.
use this..
@"(?></?\w+)(?>(?:[^>'""]+|'[^']*'|""[^""]*"")*)>"
Using HTML5 you can add the attribute 'download' to your links.
<a href="/path/to/image.png" download>
Compliant browsers will then prompt to download the image with the same file name (in this example image.png).
If you specify a value for this attribute, then that will become the new filename:
<a href="/path/to/image.png" download="AwesomeImage.png">
UPDATE: As of spring 2018 this is no longer possible for cross-origin href
s. So if you want to create <a href="https://i.imgur.com/IskAzqA.jpg" download>
on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement
I use div instead of tables and am able to target classes within the main class, as below:
.main {
.width: 800px;
.margin: 0 auto;
.text-align: center;
}
.main .table {
width: 80%;
}
.main .row {
/ ***something ***/
}
.main .column {
font-size: 14px;
display: inline-block;
}
.main .left {
width: 140px;
margin-right: 5px;
font-size: 12px;
}
.main .right {
width: auto;
margin-right: 20px;
color: #fff;
font-size: 13px;
font-weight: normal;
}
<div class="main">
<div class="table">
<div class="row">
<div class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:
.main #red { color: red; }
<div class="main">
<div class="table">
<div class="row">
<div id="red" class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
This is default by iOS7 design. try to do the below:
[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
You can set the 'Separator Inset' from the storyboard:
Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.
I tried to install scikit-image but got the following error when I tried to install the .whl file even though my installed version of python was 2.7 32-bit. scikit_image-0.12.3-cp27-cp27m-win32.whl is not a supported wheel on this platform.
However I also got this message before the error message:
You are using pip version 7.1.0, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
I then ran the command python -m pip install --upgrade pip
and then pip install scikit_image-0.12.3-cp27-cp27m-win32.whl
worked fine. I hope this can help someone!
Been looking into this for a while and not got any satisfactory answers, however...
1) ANSI escape sequences do work in a terminal on Linux
2) if you can tolerate a limited set of colo(u)rs try this:
print("hello", end=''); print("error", end='', file=sys.stderr); print("goodbye")
In idle "hello" and "goodbye" are in blue and "error" is in red.
Not fantastic, but good enough for now, and easy!
I have a very quick and simple workaround here, it does work for me, and no matter the event would be triggered once or twice or more times occasionally, check it out:
private int fireCount = 0;
private void inputFileWatcher_Changed(object sender, FileSystemEventArgs e)
{
fireCount++;
if (fireCount == 1)
{
MessageBox.Show("Fired only once!!");
dowork();
}
else
{
fireCount = 0;
}
}
}
I was having the same problem, with a value like 2016-08-8, then I solved adding a zero to have two digits days, and it works. Tested in chrome, firefox, and Edge
today:function(){
var today = new Date();
var d = (today.getDate() < 10 ? '0' : '' )+ today.getDate();
var m = ((today.getMonth() + 1) < 10 ? '0' :'') + (today.getMonth() + 1);
var y = today.getFullYear();
var x = String(y+"-"+m+"-"+d);
return x;
}
The "cd" command changes the directory, but not what drive you are working with. So when you go "cd d:\temp", you are changing the D drive's directory to temp, but staying in the C drive.
Execute these two commands:
D:
cd temp
That will get you the results you want.
You can do it by using window_handles
and switch_to_window
method.
Before clicking the link first store the window handle as
window_before = driver.window_handles[0]
after clicking the link store the window handle of newly opened window as
window_after = driver.window_handles[1]
then execute the switch to window method to move to newly opened window
driver.switch_to_window(window_after)
and similarly you can switch between old and new window. Following is the code example
import unittest
from selenium import webdriver
class GoogleOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_google_search_page(self):
driver = self.driver
driver.get("http://www.cdot.in")
window_before = driver.window_handles[0]
print window_before
driver.find_element_by_xpath("//a[@href='http://www.cdot.in/home.htm']").click()
window_after = driver.window_handles[1]
driver.switch_to_window(window_after)
print window_after
driver.find_element_by_link_text("ATM").click()
driver.switch_to_window(window_before)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
I had the same issue, ended up using the much more convenient Guava Resources:
Resources.getResource("my.file")
No need to get too complicated, try this one liner:
String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());
You can simply use the zoom property:
#myContainer{
zoom: 0.5;
-moz-transform: scale(0.5);
}
Where myContainer contains all the elements you're editing. This is supported in all major browsers.
If for some reasons while trying to add headers or set control policy you're still getting nowhere you may consider using apache ProxyPass…
For example in one <VirtualHost>
that uses SSL add the two following directives:
SSLProxyEngine On
ProxyPass /oauth https://remote.tld/oauth
Make sure the following apache modules are loaded (load them using a2enmod):
Obviously you'll have to change your AJAX requests url in order to use the apache proxy…
In my specific case I had to stop ENTER from submitting the form and also simulate the clicking of the submit button. This is because the submit button had a click handler on it because we were within a modal window (inherited old code). In any case here's my combo solutions for this case.
$('input,select').keypress(function(event) {
// detect ENTER key
if (event.keyCode == 13) {
// simulate submit button click
$("#btn-submit").click();
// stop form from submitting via ENTER key press
event.preventDefault ? event.preventDefault() : event.returnValue = false;
}
});
This use case is specifically useful for people working with IE8.
You can make symbolic link to you pip3:
sudo ln -s $(which pip3) /usr/bin/pip3
It helps me in RHEL 7.6
The '::' is for static members.
It is possible to use the data field name, if not the title so easily, which solved the problem for me. For ASP.NET & VB:
e.g. For a string:
Dim Encoding = e.Row.DataItem("Encoding").ToString().Trim()
e.g. For an integer:
Dim MsgParts = Convert.ToInt32(e.Row.DataItem("CalculatedMessageParts").ToString())
Yes, sort of.
You can explicitly size a container using units relative to font-size:
In addition you can use a few CSS properties such as overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
to help limit the number as well.
Please use the below mentioned URL to encrypt string using AES excryption with
key and IV values.
You could use scipy.interpolate.spline
to smooth out your data yourself:
from scipy.interpolate import spline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
power_smooth = spline(T, power, xnew)
plt.plot(xnew,power_smooth)
plt.show()
spline is deprecated in scipy 0.19.0, use BSpline class instead.
Switching from spline
to BSpline
isn't a straightforward copy/paste and requires a little tweaking:
from scipy.interpolate import make_interp_spline, BSpline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
spl = make_interp_spline(T, power, k=3) # type: BSpline
power_smooth = spl(xnew)
plt.plot(xnew, power_smooth)
plt.show()
html, body{
width:100%;
}
This tells the html to be 100% wide. But 100% refers to the whole browser window width, so no more than that.
You may want to set a min width instead.
html, body{
min-width:100%;
}
So it will be 100% as a minimum, bot more if needed.
You can find the default Android menu icons here - link is broken now.
Update: You can find Material Design icons here.
Step 1 Included the cdn like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
Step 2 Code Like
$(document).ready(function(){
$("#submit").click(function () {
$('#myform').validate({ // initialize the plugin
rules: {
id: {
required: true,
email: true
},
password: {
required: true,
minlength: 1
}
},
messages: {
id: {
required: "Enter Email Id"
},
password: {
required: "Enter Email Password"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
}):
});
To expand upon dreamlax's example... If you want to send data along with the notification
In posting code:
NSDictionary *userInfo =
[NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
[[NSNotificationCenter defaultCenter] postNotificationName:
@"TestNotification" object:nil userInfo:userInfo];
In observing code:
- (void) receiveTestNotification:(NSNotification *) notification {
NSDictionary *userInfo = notification.userInfo;
MyObject *myObject = [userInfo objectForKey:@"someKey"];
}
Java 8
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
List<List<String>> stringListList = new ArrayList<>();
stringListList.add(Arrays.asList(new String[] {"(0,0)", "(0,1)"} ));
stringListList.add(Arrays.asList(new String[] {"(1,0)", "(1,1)", "(1,2)"} ));
stringListList.add(Arrays.asList(new String[] {"(2,0)", "(2,1)"} ));
int count=stringListList.stream().mapToInt(i -> i.size()).sum();
System.out.println("stringListList count: "+count);
}
}
If you want the sum of all bars to be equal unity, weight each bin by the total number of values:
weights = np.ones_like(myarray) / len(myarray)
plt.hist(myarray, weights=weights)
Hope that helps, although the thread is quite old...
Note for Python 2.x: add casting to float()
for one of the operators of the division as otherwise you would end up with zeros due to integer division
what about this simple inArray function:
Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
Root Cause: root has no password, and your python connect statement should reflect that.
To solve error 1698, change your python connect password to ''.
note: manually updating the user's password will not solve the problem, you will still get error 1698
Here is my platform specific code(unix)
public static List<File> findFiles(String dir, String... names)
{
LinkedList<String> command = new LinkedList<String>();
command.add("/usr/bin/find");
command.add(dir);
List<File> result = new LinkedList<File>();
if (names.length > 1)
{
List<String> newNames = new LinkedList<String>(Arrays.asList(names));
String first = newNames.remove(0);
command.add("-name");
command.add(first);
for (String newName : newNames)
{
command.add("-or");
command.add("-name");
command.add(newName);
}
}
else if (names.length > 0)
{
command.add("-name");
command.add(names[0]);
}
try
{
ProcessBuilder pb = new ProcessBuilder(command);
Process p = pb.start();
p.waitFor();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
// System.err.println(line);
result.add(new File(line));
}
p.destroy();
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
The range of char is 127 to -128. If you assign 212, ch stores -44 (212-128-128) not 212.So if you try to print a negative number as unsigned you get (MAX value of unsigned int)-abs(number) which in this case is 4294967252
So if you want to store 212 as it is in ch the only thing you can do is declare ch as
unsigned char ch;
now the range of ch is 0 to 255.
A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.
For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.
Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.
However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.
Read the Security section of the PHP manual as a starting point to keeping your code safe.
The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.
$.fn.extend( {
limiter: function(limit, elem) {
$(this).on("keyup focus", function() {
setCount(this, elem);
});
function setCount(src, elem) {
var chars = src.value.length;
if (chars > limit) {
src.value = src.value.substr(0, limit);
chars = limit;
}
elem.html( limit - chars );
}
setCount($(this)[0], elem);
}
});
var elem = $("#cntr");
$("#status_txt").limiter(160, elem);
There is no one-to-one correlation. For a really good article please see Efficient String Concatenation in Python:
Building long strings in the Python progamming language can sometimes result in very slow running code. In this article I investigate the computational performance of various string concatenation methods.
As the others are saying, they're the same. StyleCop rules, by default, will enforce you to use string
as a C# code style best practice, except when referencing System.String
static functions, such as String.Format
, String.Join
, String.Concat
, etc...
I'd like to thank the answer by Apostolos for bringing this to my attention. Here's a much more detailed example for Python 3 in the year 2019, with a clearer description and example code.
destroy()
(or not having a custom window closing handler at all) will destroy the window and all of its running callbacks instantly when the user closes it.This can be bad for you, depending on your current Tkinter activity, and especially when using tkinter.after
(periodic callbacks). You might be using a callback which processes some data and writes to disk... in that case, you obviously want the data writing to finish without being abruptly killed.
The best solution for that is to use a flag. So when the user requests window closing, you mark that as a flag, and then react to it.
(Note: I normally design GUIs as nicely encapsulated classes and separate worker threads, and I definitely don't use "global" (I use class instance variables instead), but this is meant to be a simple, stripped-down example to demonstrate how Tk abruptly kills your periodic callbacks when the user closes the window...)
from tkinter import *
import time
# Try setting this to False and look at the printed numbers (1 to 10)
# during the work-loop, if you close the window while the periodic_call
# worker is busy working (printing). It will abruptly end the numbers,
# and kill the periodic callback! That's why you should design most
# applications with a safe closing callback as described in this demo.
safe_closing = True
# ---------
busy_processing = False
close_requested = False
def close_window():
global close_requested
close_requested = True
print("User requested close at:", time.time(), "Was busy processing:", busy_processing)
root = Tk()
if safe_closing:
root.protocol("WM_DELETE_WINDOW", close_window)
lbl = Label(root)
lbl.pack()
def periodic_call():
global busy_processing
if not close_requested:
busy_processing = True
for i in range(10):
print((i+1), "of 10")
time.sleep(0.2)
lbl["text"] = str(time.time()) # Will error if force-closed.
root.update() # Force redrawing since we change label multiple times in a row.
busy_processing = False
root.after(500, periodic_call)
else:
print("Destroying GUI at:", time.time())
try: # "destroy()" can throw, so you should wrap it like this.
root.destroy()
except:
# NOTE: In most code, you'll wanna force a close here via
# "exit" if the window failed to destroy. Just ensure that
# you have no code after your `mainloop()` call (at the
# bottom of this file), since the exit call will cause the
# process to terminate immediately without running any more
# code. Of course, you should NEVER have code after your
# `mainloop()` call in well-designed code anyway...
# exit(0)
pass
root.after_idle(periodic_call)
root.mainloop()
This code will show you that the WM_DELETE_WINDOW
handler runs even while our custom periodic_call()
is busy in the middle of work/loops!
We use some pretty exaggerated .after()
values: 500 milliseconds. This is just meant to make it very easy for you to see the difference between closing while the periodic call is busy, or not... If you close while the numbers are updating, you will see that the WM_DELETE_WINDOW
happened while your periodic call "was busy processing: True". If you close while the numbers are paused (meaning that the periodic callback isn't processing at that moment), you see that the close happened while it's "not busy".
In real-world usage, your .after()
would use something like 30-100 milliseconds, to have a responsive GUI. This is just a demonstration to help you understand how to protect yourself against Tk's default "instantly interrupt all work when closing" behavior.
In summary: Make the WM_DELETE_WINDOW
handler set a flag, and then check that flag periodically and manually .destroy()
the window when it's safe (when your app is done with all work).
PS: You can also use WM_DELETE_WINDOW
to ask the user if they REALLY want to close the window; and if they answer no, you don't set the flag. It's very simple. You just show a messagebox in your WM_DELETE_WINDOW
and set the flag based on the user's answer.
All these solutions don't work for me, although the right way of thinking.
The following works for me:
if(mytime.isAfter(fromtime) || mytime.isBefore(totime)
// mytime is between fromtime and totime
Before I tried I thought about your solution with && too
You can use an extension.
import UIKit
extension UILabel {
func sizeFont(_ size: CGFloat) {
self.font = self.font.withSize(size)
}
}
To use it:
self.myLabel.fontSize(100)
The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.
If the URL of your website is: http://www.example.com/mywebsite/
then starting at the root level starts above the "mywebsite" folder path.
Change div to span. And space the icons using
HTML
<div class="nav3" style="height:705px;">
<span class="icons"><a href="http://www.facebook.com/"><img src="images/facebook.png"></a>
</span>
<span class="icons"><a href="https://twitter.com"><img src="images/twitter.png"></a>
</span>
</div>
CSS
.nav3 {
background-color: #E9E8C7;
height: auto;
width: 150px;
float: left;
padding-left: 20px;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #333333;
padding-top: 20px;
padding-right: 20px;
}
.icons{
display:inline-block;
width: 64px;
height: 64px;
}
a.icons:hover {
background: #C93;
}
span does not break line, div does.
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
You need to include a declaration of the printf()
function.
#include <stdio.h>
The Problem is related to MySql Driver
Class.forName("com.mysql.jdbc.Driver");
Add the MySQL jdbc driver jar file in to your classpath.
Also i have this error on JDK. I build the ClassPath Properly then I put the "mysql-connector-java-5.1.25-bin" in dir "C:\Program Files\Java\jre7\lib\ext" in this dir i have my JDK. then compile and Run again then it's working fine.
I tried:
ps aux | grep -w Z # returns the zombies pid
ps o ppid {returned pid from previous command} # returns the parent
kill -1 {the parent id from previous command}
this will work :)
To do this, I had to come up with an intermediate data structure:
class KeyDataPoint {
String key;
DateTime timestamp;
Number data;
// obvious constructor and getters
}
With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.
Then, we apply a groupingBy
operation on the string key in order to gather the data for each key together. Note that a simple groupingBy
would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy
which is a mapping
operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping
operation is simply toList
which collects the DataPoint objects of the same group into a list.
Now we have a Map<String, List<DataPoint>>
and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.
The code ends up looking like this:
Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.flatMap(mdp -> mdp.getData().entrySet().stream()
.map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
.collect(groupingBy(KeyDataPoint::getKey,
mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
.entrySet().stream()
.map(e -> new DataSet(e.getKey(), e.getValue()))
.collect(toList());
}
I took some liberties with constructors and getters, but I think they should be obvious.
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
string::c.str()
returns a string of type const char *
as seen here
A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str())
;
While the above may work, it is undefined behaviour, and unsafe.
Here's a nicer solution using templates:
char * my_argument = const_cast<char*> ( ...c_str() );
mysqldump
has options for CSV formatting:
--fields-terminated-by=name
Fields in the output file are terminated by the given
--lines-terminated-by=name
Lines in the output file are terminated by the given
The name
should contain one of the following:
`--fields-terminated-by`
\t
or "\""
`--fields-enclosed-by=name`
Fields in the output file are enclosed by the given
and
--lines-terminated-by
\r
\n
\r\n
Naturally you should mysqldump each table individually.
I suggest you gather all table names in a text file. Then, iterate through all tables running mysqldump. Here is a script that will dump and gzip 10 tables at a time:
MYSQL_USER=root
MYSQL_PASS=rootpassword
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
SQLSTMT="SELECT CONCAT(table_schema,'.',table_name)"
SQLSTMT="${SQLSTMT} FROM information_schema.tables WHERE table_schema NOT IN "
SQLSTMT="${SQLSTMT} ('information_schema','performance_schema','mysql')"
mysql ${MYSQL_CONN} -ANe"${SQLSTMT}" > /tmp/DBTB.txt
COMMIT_COUNT=0
COMMIT_LIMIT=10
TARGET_FOLDER=/path/to/csv/files
for DBTB in `cat /tmp/DBTB.txt`
do
DB=`echo "${DBTB}" | sed 's/\./ /g' | awk '{print $1}'`
TB=`echo "${DBTB}" | sed 's/\./ /g' | awk '{print $2}'`
DUMPFILE=${DB}-${TB}.csv.gz
mysqldump ${MYSQL_CONN} -T ${TARGET_FOLDER} --fields-terminated-by="," --fields-enclosed-by="\"" --lines-terminated-by="\r\n" ${DB} ${TB} | gzip > ${DUMPFILE}
(( COMMIT_COUNT++ ))
if [ ${COMMIT_COUNT} -eq ${COMMIT_LIMIT} ]
then
COMMIT_COUNT=0
wait
fi
done
if [ ${COMMIT_COUNT} -gt 0 ]
then
wait
fi
In Python, overloading is not an applied concept. However, if you are trying to create a case where, for instance, you want one initializer to be performed if passed an argument of type foo
and another initializer for an argument of type bar
then, since everything in Python is handled as object, you can check the name of the passed object's class type and write conditional handling based on that.
class A:
def __init__(self, arg)
# Get the Argument's class type as a String
argClass = arg.__class__.__name__
if argClass == 'foo':
print 'Arg is of type "foo"'
...
elif argClass == 'bar':
print 'Arg is of type "bar"'
...
else
print 'Arg is of a different type'
...
This concept can be applied to multiple different scenarios through different methods as needed.
Please check that your key exists in the array or not, instead of simply trying to access it.
Replace:
$myVar = $someArray['someKey']
With something like:
if (isset($someArray['someKey'])) {
$myVar = $someArray['someKey']
}
or something like:
if(is_array($someArray['someKey'])) {
$theme_img = 'recent_works_iso_thumbnail';
}else {
$theme_img = 'recent_works_iso_thumbnail';
}
Better approach may be a polyfill like this
jQuery.fn.load = function(callback){ $(window).on("load", callback) };
With this you can leave the legacy code untouched. If you use webpack be sure to use script-loader.
Try <input type="number" step="0.01" />
if you are targeting 2 decimal places :-).
The problem is with sprintf
sprintf(aa,"%lf",a);
%lf says to interpet "a" as a "long double" (16 bytes) but it is actually a "double" (8 bytes). Use this instead:
sprintf(aa, "%f", a);
More details here on cplusplus.com
pow() doesn't work with int
, hence the error "error C2668:'pow': ambiguous call to overloaded function"
http://www.cplusplus.com/reference/clibrary/cmath/pow/
Write your own power function for int
s:
int power(int base, int exp)
{
int result = 1;
while(exp) { result *= base; exp--; }
return result;
}
I found information about .bashrc and .bash_profile here to sum it up:
.bash_profile is executed when you login. Stuff you put in there might be your PATH and other important environment variables.
.bashrc is used for non login shells. I'm not sure what that means. I know that RedHat executes it everytime you start another shell (su to this user or simply calling bash again) You might want to put aliases in there but again I am not sure what that means. I simply ignore it myself.
.profile is the equivalent of .bash_profile for the root. I think the name is changed to let other shells (csh, sh, tcsh) use it as well. (you don't need one as a user)
There is also .bash_logout wich executes at, yeah good guess...logout. You might want to stop deamons or even make a little housekeeping . You can also add "clear" there if you want to clear the screen when you log out.
Also there is a complete follow up on each of the configurations files here
These are probably even distro.-dependant, not all distros choose to have each configuraton with them and some have even more. But when they have the same name, they usualy include the same content.
This problem is caused by a mismatch between your pip installation and your requests installation.
As of requests version 2.4.0 requests.compat.IncompleteRead
has been removed. Older versions of pip, e.g. from July 2014, still relied on IncompleteRead
. In the current version of pip, the import of IncompleteRead
has been removed.
So the one to blame is either:
You can solve this issue, by either updating pip via Ubuntu (if there is a newer version) or by installing pip aside from Ubuntu.
So all you need to do for this to work is add:
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
as a field to your post request and it'll work.
Maybe another question is, "what are you going to do with those indices once you get them?" If you are going to use them to create another list, then in Python, they are an unnecessary middle step. If you want all the values that match a given condition, just use the builtin filter:
matchingVals = filter(lambda x : x>2, a)
Or write your own list comprhension:
matchingVals = [x for x in a if x > 2]
If you want to remove them from the list, then the Pythonic way is not to necessarily remove from the list, but write a list comprehension as if you were creating a new list, and assigning back in-place using the listvar[:]
on the left-hand-side:
a[:] = [x for x in a if x <= 2]
Matlab supplies find
because its array-centric model works by selecting items using their array indices. You can do this in Python, certainly, but the more Pythonic way is using iterators and generators, as already mentioned by @EliBendersky.
I think there is little difference between the two events. To understand this, I created a simple example to manipulation:
XAML
<Window x:Class="LoadedAndContentRendered.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="MyWindow"
Title="MainWindow" Height="1000" Width="525"
WindowStartupLocation="CenterScreen"
ContentRendered="Window_ContentRendered"
Loaded="Window_Loaded">
<Grid Name="RootGrid">
</Grid>
</Window>
Code behind
private void Window_ContentRendered(object sender, EventArgs e)
{
MessageBox.Show("ContentRendered");
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Loaded");
}
In this case the message Loaded
appears the first after the message ContentRendered
. This confirms the information in the documentation.
In general, in WPF the Loaded
event fires if the element:
is laid out, rendered, and ready for interaction.
Since in WPF the Window
is the same element, but it should be generally content that is arranged in a root panel (for example: Grid
). Therefore, to monitor the content of the Window
and created an ContentRendered
event. Remarks from MSDN:
If the window has no content, this event is not raised.
That is, if we create a Window
:
<Window x:Class="LoadedAndContentRendered.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="MyWindow"
ContentRendered="Window_ContentRendered"
Loaded="Window_Loaded" />
It will only works Loaded
event.
With regard to access to the elements in the Window
, they work the same way. Let's create a Label
in the main Grid
of Window
. In both cases we have successfully received access to Width
:
private void Window_ContentRendered(object sender, EventArgs e)
{
MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());
}
As for the Styles
and Templates
, at this stage they are successfully applied, and in these events we will be able to access them.
For example, we want to add a Button
:
private void Window_ContentRendered(object sender, EventArgs e)
{
MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());
Button b1 = new Button();
b1.Content = "ContentRendered Button";
RootGrid.Children.Add(b1);
b1.Height = 25;
b1.Width = 200;
b1.HorizontalAlignment = HorizontalAlignment.Right;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());
Button b1 = new Button();
b1.Content = "Loaded Button";
RootGrid.Children.Add(b1);
b1.Height = 25;
b1.Width = 200;
b1.HorizontalAlignment = HorizontalAlignment.Left;
}
In the case of Loaded
event, Button
to add to Grid
immediately at the appearance of the Window
. In the case of ContentRendered
event, Button
to add to Grid
after all its content will appear.
Therefore, if you want to add items or changes before load Window
you must use the Loaded
event. If you want to do the operations associated with the content of Window
such as taking screenshots you will need to use an event ContentRendered
.
1. First should understand the error meaning
Error not enough values to unpack (expected 3, got 2)
means:
a 2 part tuple, but assign to 3 values
and I have written demo code to show for you:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)'
# Author: Crifan Li
# Update: 20191212
def notEnoughUnpack():
"""Showing how to understand python error `not enough values to unpack (expected 3, got 2)`"""
# a dict, which single key's value is two part tuple
valueIsTwoPartTupleDict = {
"name1": ("lastname1", "email1"),
"name2": ("lastname2", "email2"),
}
# Test case 1: got value from key
gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK
print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail))
# gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2)
# Test case 2: got from dict.items()
for eachKey, eachValues in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValues=%s" % (eachKey, eachValues))
# same as following:
# Background knowledge: each of dict.items() return (key, values)
# here above eachValues is a tuple of two parts
for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2))
# but following:
for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2)
pass
if __name__ == "__main__":
notEnoughUnpack()
using VSCode
debug effect:
2. For your code
for name, email, lastname in unpaidMembers.items():
but error
ValueError: not enough values to unpack (expected 3, got 2)
means each item(a tuple value) in unpaidMembers
, only have 1 parts:email
, which corresponding above code
unpaidMembers[name] = email
so should change code to:
for name, email in unpaidMembers.items():
to avoid error.
But obviously you expect extra lastname
, so should change your above code to
unpaidMembers[name] = (email, lastname)
and better change to better syntax:
for name, (email, lastname) in unpaidMembers.items():
then everything is OK and clear.
Declare separate functions in the <head> section and invoke those in your onClick method. If you have lots you could use a naming scheme that numbers them, or pass an integer in in your onClicks and have a big fat switch statement in the function.
If you don't have Homebrew or don't know what is it
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew update && brew upgrade
brew uninstall openssl; brew uninstall openssl; brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb
Or if you already have Homebrew installed
brew update && brew upgrade
brew uninstall openssl; brew uninstall openssl; brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb
This works for me on Mac 10.15
List<Tuple<string, DateTime, string>> mylist = new List<Tuple<string, DateTime,string>>();
mylist.Add(new Tuple<string, DateTime, string>(Datei_Info.Dateiname, Datei_Info.Datum, Datei_Info.Größe));
for (int i = 0; i < mylist.Count; i++)
{
Console.WriteLine(mylist[i]);
}
It blurs the separation of concerns.
Supposed that you have a singleton, you can call this instance from anywhere inside your class. Your class is no longer as pure as it should be. Your class will now no longer operate on its members and the members that it receives explicitly. This will create confusion, because the users of the class don't know what is the sufficient information the class needs. The whole idea of encapsulation is to hide the how of a method from the users, but if a singleton is used inside the method, one will have to know the state of the singleton in order to use the method correctly. This is anti-OOP.
Found the code that I referred to in my comment above. To test it, do this:
Sheet1
change the cell height and width of say A1
as shown in the snapshot below. Start Timer
button on the sheet and click on Assign Macros
. Select StartTimer
macro.End Timer
button on the sheet and click on Assign Macros
. Select EndTimer
macro.Now click on Start Timer button and you will see the time getting updated in cell A1
. To stop time updates, Click on End Timer button.
Code (TRIED AND TESTED)
Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long
Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long
'~~> Start Timer
Sub StartTimer()
'~~ Set the timer for 1 second
TimerSeconds = 1
TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub
'~~> End Timer
Sub EndTimer()
On Error Resume Next
KillTimer 0&, TimerID
End Sub
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
'~~> Update value in Sheet 1
Sheet1.Range("A1").Value = Time
End Sub
SNAPSHOT
For MS SQL 2016, passing ints into the in, it looks like it can handle close to 38,000 records.
select * from user where userId in (1,2,3,etc)
Frequently used Boolean operations in C++ produce many branches in the compiled program. If these branches are inside loops and are hard to predict they can slow down execution significantly. Boolean variables are stored as 8-bit integers with the value 0
for false
and 1
for true
.
Boolean variables are overdetermined in the sense that all operators that have Boolean variables as input check if the inputs have any other value than 0
or 1
, but operators that have Booleans as output can produce no other value than 0
or 1
. This makes operations with Boolean variables as input less efficient than necessary.
Consider example:
bool a, b, c, d;
c = a && b;
d = a || b;
This is typically implemented by the compiler in the following way:
bool a, b, c, d;
if (a != 0) {
if (b != 0) {
c = 1;
}
else {
goto CFALSE;
}
}
else {
CFALSE:
c = 0;
}
if (a == 0) {
if (b == 0) {
d = 0;
}
else {
goto DTRUE;
}
}
else {
DTRUE:
d = 1;
}
This code is far from optimal. The branches may take a long time in case of mispredictions. The Boolean operations can be made much more efficient if it is known with certainty that the operands have no other values than 0
and 1
. The reason why the compiler does not make such an assumption is that the variables might have other values if they are uninitialized or come from unknown sources. The above code can be optimized if a
and b
has been initialized to valid values or if they come from operators that produce Boolean output. The optimized code looks like this:
char a = 0, b = 1, c, d;
c = a & b;
d = a | b;
char
is used instead of bool
in order to make it possible to use the bitwise operators (&
and |
) instead of the Boolean operators (&&
and ||
). The bitwise operators are single instructions that take only one clock cycle. The OR operator (|
) works even if a
and b
have other values than 0
or 1
. The AND operator (&
) and the EXCLUSIVE OR operator (^
) may give inconsistent results if the operands have other values than 0
and 1
.
~
can not be used for NOT. Instead, you can make a Boolean NOT on a variable which is known to be 0
or 1
by XOR'ing it with 1
:
bool a, b;
b = !a;
can be optimized to:
char a = 0, b;
b = a ^ 1;
a && b
cannot be replaced with a & b
if b
is an expression that should not be evaluated if a
is false
( &&
will not evaluate b
, &
will). Likewise, a || b
can not be replaced with a | b
if b
is an expression that should not be evaluated if a
is true
.
Using bitwise operators is more advantageous if the operands are variables than if the operands are comparisons:
bool a; double x, y, z;
a = x > y && z < 5.0;
is optimal in most cases (unless you expect the &&
expression to generate many branch mispredictions).
Activator.CreateInstance()
returns an object, which doesn't have an Output method.
It looks like you come from dynamic programming languages? C# is definetly not that, and what you are trying to do will be difficult.
Since you are loading a specific dll from a specific location, maybe you just want to add it as a reference to your console application?
If you absolutely want to load the assembly via Assembly.Load
, you will have to go via reflection to call any members on c
Something like type.GetMethod("Output").Invoke(c, null);
should do it.
I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:
vars:
myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"
The other answers are WRONG.
Running argsort
once is not the solution.
For example, the following code:
import numpy as np
x = [3,1,2]
np.argsort(x)
yields array([1, 2, 0], dtype=int64)
which is not what we want.
The answer should be to run argsort
twice:
import numpy as np
x = [3,1,2]
np.argsort(np.argsort(x))
gives array([2, 0, 1], dtype=int64)
as expected.
UPDATE: Suggest using Dataframes
, plus something like ... .write.mode(SaveMode.Overwrite) ...
.
Handy pimp:
implicit class PimpedStringRDD(rdd: RDD[String]) {
def write(p: String)(implicit ss: SparkSession): Unit = {
import ss.implicits._
rdd.toDF().as[String].write.mode(SaveMode.Overwrite).text(p)
}
}
For older versions try
yourSparkConf.set("spark.hadoop.validateOutputSpecs", "false")
val sc = SparkContext(yourSparkConf)
In 1.1.0 you can set conf settings using the spark-submit script with the --conf flag.
WARNING (older versions): According to @piggybox there is a bug in Spark where it will only overwrite files it needs to to write it's part-
files, any other files will be left unremoved.
If you're looking for some ESP alternatives, you should have a look at Mailjet for Microsoft Azure too! As a global email service and infrastructure provider, they enable you to send, deliver and track transactional and marketing emails via their APIs, SMTP Relay or UI all from one single platform, thought both for developers and emails owners.
Disclaimer: I’m working at Mailjet as a Developer Evangelist.
Installation
pip install pkgutil
Code
import pkgutil
for i in pkgutil.iter_modules(None): # returns a tuple (path, package_name, ispkg_flag)
print(i[1]) #or you can append it to a list
Sample Output:
multiprocessing
netrc
nntplib
ntpath
nturl2path
numbers
opcode
pickle
pickletools
pipes
pkgutil
I think most of the important stuff has been said, but I just thought I'd add one thing: If you compile as Any CPU and run on an x64 platform, then you won't be able to load 32-bit DLL files, because your application wasn't started in WoW64, but those DLL files need to run there.
If you compile as x86, then the x64 system will run your application in WoW64, and you'll be able to load 32-bit DLL files.
So I think you should choose "Any CPU" if your dependencies can run in either environment, but choose x86 if you have 32-bit dependencies. This article from Microsoft explains this a bit:
/CLRIMAGETYPE (Specify Type of CLR Image)
Incidentally, this other Microsoft documentation agrees that x86 is usually a more portable choice:
Choosing x86 is generally the safest configuration for an app package since it will run on nearly every device. On some devices, an app package with the x86 configuration won't run, such as the Xbox or some IoT Core devices. However, for a PC, an x86 package is the safest choice and has the largest reach for device deployment. A substantial portion of Windows 10 devices continue to run the x86 version of Windows.
If you use the SQLite DB-Browser you can change the default value in this way:
I recommend to make an update of your database before, because a wrong format in the value can lead to problems in the SQLLite Browser.
Do you really need to do that programmatically?
Just considering the title: You could use a ShapeDrawable as android:background…
For example, let's define res/drawable/my_custom_background.xml
as:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="2dp"
android:topRightRadius="0dp"
android:bottomRightRadius="0dp"
android:bottomLeftRadius="0dp" />
<stroke
android:width="1dp"
android:color="@android:color/white" />
</shape>
and define android:background="@drawable/my_custom_background".
I've not tested but it should work.
Update:
I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/border"
android:padding="10dip" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
[... more TextView ...]
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
</LinearLayout>
and a res/drawable/border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="5dip"
android:color="@android:color/white" />
</shape>
Reported to work on a gingerbread device. Note that you'll need to relate android:padding
of the LinearLayout to the android:width
shape/stroke's value. Please, do not use @android:color/white
in your final application but rather a project defined color.
You could apply android:background="@drawable/border" android:padding="10dip"
to each of the LinearLayout from your provided sample.
As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…
Your problem resides clearly in the use of getBorder.set{Width,Height}(100);
. Why do you do that in an onClick method?
I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.
To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…
For is because is not have 2 function
@implementation CellTableView
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
return [self init];
}
- (void)awakeFromNib {
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
@end
Here are some:
"Ali".eql? "Ali"
=> true
The spaceship (<=>
) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:
"Apples" <=> "Apples"
=> 0
"Apples" <=> "Pears"
=> -1
"Pears" <=> "Apples"
=> 1
A case insensitive comparison may be performed using the casecmp method which returns the same values as the <=> method described above:
"Apples".casecmp "apples"
=> 0
These have the same end result, but I would simply add that using the literal syntax can help one become accustomed to the syntax of JSON (a string-ified subset of JavaScript literal object syntax), so it might be a good practice to get into.
One other thing: you might have subtle errors if you forget to use the new
operator. So, using literals will help you avoid that problem.
Ultimately, it will depend on the situation as well as preference.
At times the error code 409
occurs when you name you folder or files a reserved or blocked name. These could be names like register
, contact
In my case I named a folder contact
, turns out the name was blocked from being used as folder names.
When testing my script on postman
, I was getting this error:
<script>
document.cookie = "humans_21909=1"; document.location.reload(true)
</script>
I changed the folder name from contact to contacts and it worked. The error was gone.
Please note that I solved this problem by putting the AutoGenerateBindingRedirects
right after the TargetFramework
in the csproj
file:
<TargetFramework>net462</TargetFramework>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
Installing freetype:
sudo apt update && sudo apt install freetype2-demos
I have used bellow like in java 8. it is working for me
double amount = 1000.431;
NumberFormat formatter = new DecimalFormat("##.00");
String output = formatter.format(amount);
System.out.println("output = " + output);
Output:
output = 1000.43
Just a small correction for Marko's answer: exact number can't be produced out of some general calculations straight forward due to the next fact: Valid IP addresses should also not end with binary 0 or 1 sequences that have same length as zero sequence in subnet mask. So the final answer really depends on the total number of subnets (Marko's answer - 2 * total subnet count).
Before you try searching for the elements within the iframe you will have to switch Selenium focus to the iframe.
Try this before searching for the elements within the iframe:
driver.switchTo().frame(driver.findElement(By.name("iFrameTitle")));
Make sure first that you have certificates installed on your Debian in /etc/ssl/certs
.
If not, reinstall them:
sudo apt-get install --reinstall ca-certificates
Since that package does not include root certificates, add:
sudo mkdir /usr/local/share/ca-certificates/cacert.org
sudo wget -P /usr/local/share/ca-certificates/cacert.org http://www.cacert.org/certs/root.crt http://www.cacert.org/certs/class3.crt
sudo update-ca-certificates
Make sure your git does reference those CA:
git config --global http.sslCAinfo /etc/ssl/certs/ca-certificates.crt
Jason C mentions another potential cause (in the comments):
It was the clock. The NTP server was down, the system clock wasn't set properly, I didn't notice or think to check initially, and the incorrect time was causing verification to fail.
You can use the attribute if you want your code to do overloading.
[ActionName("MyOverloadedName")]
But, you'll have to use a different action name for the same http method (as others have said). So it's just semantics at that point. Would you rather have the name in your code or your attribute?
Phil has an article related to this: http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx
$this->db->get()->row()->campaign_id;
let obj = {"a": 3, "b": 2, "6": "a"}
Object.keys(obj).map((item) => {console.log("item", obj[item])})
// a
// 3
// 2
Check if a modal is open
$('.modal:visible').length && $('body').hasClass('modal-open')
To attach an event listener
$(document).on('show.bs.modal', '.modal', function () {
// run your validation... ( or shown.bs.modal )
});
std::string replace(std::string str, const std::string& sub1, const std::string& sub2)
{
if (sub1.empty())
return str;
std::size_t pos;
while ((pos = str.find(sub1)) != std::string::npos)
str.replace(pos, sub1.size(), sub2);
return str;
}
Try this code ...
Integer perc = 5;
BigDecimal spread = BigDecimal.ZERO;
BigDecimal perc = spread.setScale(perc,BigDecimal.ROUND_HALF_UP);
System.out.println(perc);
Result: 0.00000
For situations when I need to replace or match(find) something against string I prefer using regular expressions.
Since, the regular expressions are not fully supported in T-SQL
you can implement them using CLR
functions. Furthermore, you do not need any C#
or CLR
knowledge at all as all you need is already available in the MSDN String Utility Functions Sample.
In your case, the solution using regular expressions is:
SELECT [dbo].[RegexReplace] ([MyColumn], '(;.*)', '')
FROM [dbo].[MyTable]
But implementing such function in your database is going to help you solving more complex issues at all.
The example below shows how to deploy only the [dbo].[RegexReplace]
function, but I will recommend to you to deploy the whole String Utility
class.
Enabling CLR Integration. Execute the following Transact-SQL commands:
sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO
Bulding the code (or creating the .dll
). Generraly, you can do this using the Visual Studio or .NET Framework command prompt (as it is shown in the article), but I prefer to use visual studio.
create new class library project:
copy and paste the following code in the Class1.cs
file:
using System;
using System.IO;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;
public sealed class RegularExpression
{
public static string Replace(SqlString sqlInput, SqlString sqlPattern, SqlString sqlReplacement)
{
string input = (sqlInput.IsNull) ? string.Empty : sqlInput.Value;
string pattern = (sqlPattern.IsNull) ? string.Empty : sqlPattern.Value;
string replacement = (sqlReplacement.IsNull) ? string.Empty : sqlReplacement.Value;
return Regex.Replace(input, pattern, replacement);
}
}
build the solution and get the path to the created .dll
file:
replace the path to the .dll
file in the following T-SQL
statements and execute them:
IF OBJECT_ID(N'RegexReplace', N'FS') is not null
DROP Function RegexReplace;
GO
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'StringUtils')
DROP ASSEMBLY StringUtils;
GO
DECLARE @SamplePath nvarchar(1024)
-- You will need to modify the value of the this variable if you have installed the sample someplace other than the default location.
Set @SamplePath = 'C:\Users\gotqn\Desktop\StringUtils\StringUtils\StringUtils\bin\Debug\'
CREATE ASSEMBLY [StringUtils]
FROM @SamplePath + 'StringUtils.dll'
WITH permission_set = Safe;
GO
CREATE FUNCTION [RegexReplace] (@input nvarchar(max), @pattern nvarchar(max), @replacement nvarchar(max))
RETURNS nvarchar(max)
AS EXTERNAL NAME [StringUtils].[RegularExpression].[Replace]
GO
That's it. Test your function:
declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part'
union all select 7, ';' -- test semicolon by itself
SELECT [dbo].[RegexReplace] ([MyText], '(;.*)', '')
FROM @MyTable
select * from @MyTable
Use the mkdtemp()
function from the tempfile
module:
import tempfile
import shutil
dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)
If a
is your array:
In [11]: a[:,:2]
Out[11]:
array([[-0.57098887, -0.4274751 ],
[-0.22279713, -0.51723555],
[ 0.67492385, -0.69294472],
[ 0.41086611, 0.26374238]])
I'm guessing public Method AddMethod(string aName)
is defined on a public interface that FBlock implements. Consumers of that interface are not guaranteed to have access to Method.
Not only double quotes, you will be in need for single quote ('
), double quote ("
), backslash (\
) and NUL (the NULL byte).
Use fputcsv()
to write, and fgetcsv()
to read, which will take care of all.
// Form A
public void loaddata()
{
//do what you do in load data in order to update data in datagrid
}
then on Form B define:
// Form B
FormA obj = (FormA)Application.OpenForms["FormA"];
private void button1_Click(object sender, EventArgs e)
{
obj.loaddata();
datagridview1.Update();
datagridview1.Refresh();
}