You can create a method that looks like this:
public static DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2)
{
DataTable TempTable = RecordDT_;
System.Data.DataView view = new System.Data.DataView(TempTable);
System.Data.DataTable selected = view.ToTable("Selected", false, col1, col2);
return selected;
}
You can return as many columns as possible.. just add the columns as call parameters as shown below:
public DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2,string col3,...)
and also add the parameters to this line:
System.Data.DataTable selected = view.ToTable("Selected", false,col1, col2,col3,...);
Then simply implement the function as:
DataTable myselectedColumnTable=SelectedColumns(OriginalTable,"Col1","Col2",...);
Thanks...
The System.Math.Round
method uses the Double
structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round
method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:
Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)
Result: 0.58
<?php
$variable1 = "foo";
$variable2 = "bar";
header('Location: http://linkhere.com?fieldname1=$variable1&fieldname2=$variable2&fieldname3=$variable3);
?>
This works without any quotations.
nzd$date <- format(as.Date(nzd$date), "%Y/%m/%d")
In the above piece of code, there are two mistakes. First of all, when you are reading nzd$date
inside as.Date
you are not mentioning in what format you are feeding it the date
. So, it tries it's default set format to read it. If you see the help
doc, ?as.Date
you will see
format
A character string. If not specified, it will try "%Y-%m-%d" then "%Y/%m/%d" on the first non-NA element, and give an error if neither works. Otherwise, the processing is via strptime
The second mistake is: even though you would like to read it in %Y-%m-%d
format, inside format
you wrote "%Y/%m/%d"
.
Now, the correct way of doing it is:
> nzd <- data.frame(date=c("31/08/2011", "31/07/2011", "30/06/2011"),
+ mid=c(0.8378,0.8457,0.8147))
> nzd
date mid
1 31/08/2011 0.8378
2 31/07/2011 0.8457
3 30/06/2011 0.8147
> nzd$date <- format(as.Date(nzd$date, format = "%d/%m/%Y"), "%Y-%m-%d")
> head(nzd)
date mid
1 2011-08-31 0.8378
2 2011-07-31 0.8457
3 2011-06-30 0.8147
Have you tried:
var connection = new ConnectionFactory().GetConnection(
ConfigurationManager.ConnectionStrings["Test"]
.ConnectionString, DataBaseProvider);
In C++, your source files are usually parsed from top to bottom in a single pass, so any variable or function must be declared before they can be used. There are some exceptions to this, like when defining functions inline in a class definition, but that's not the case for your code.
Either move the definition of integrate
above the one for getSkewNormal
, or add a forward declaration above getSkewNormal
:
double integrate (double start, double stop, int numSteps, Evaluatable evalObj);
The same applies for sum
.
I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create
, not having point.c will cause the compilation to fail.
I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:
gcc point.c testpoint.c
As others have pointed out, you also need to remove one of your main
functions, since you can only have one.
Tim Stone's solution is on the right track, but his initial rewriterule and and his cookie name in the final condition are different, and you can not write and read a cookie in the same request.
Here is the finalized working code:
RewriteEngine on
RewriteBase /
# Check if this is the noredirect query string
RewriteCond %{QUERY_STRING} (^|&)m=0(&|$)
# Set a cookie, and skip the next rule
RewriteRule ^ - [CO=mredir:0:www.website.com]
# Check if this looks like a mobile device
# (You could add another [OR] to the second one and add in what you
# had to check, but I believe most mobile devices should send at
# least one of these headers)
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP:Profile} !^$ [OR]
RewriteCond %{HTTP_USER_AGENT} "acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "wapp|wapr|webc|winw|winw|xda|xda-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "up.browser|up.link|windowssce|iemobile|mini|mmp" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "symbian|midp|wap|phone|pocket|mobile|pda|psp" [NC]
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC]
# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST} !^m\.
# Can not read and write cookie in same request, must duplicate condition
RewriteCond %{QUERY_STRING} !(^|&)m=0(&|$)
# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP_COOKIE} !^.*mredir=0.*$ [NC]
# Now redirect to the mobile site
RewriteRule ^ http://m.website.com [R,L]
If you want to get a sub list including the last element, you leave blank after colon:
>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Here is an extension method:
public static decimal? TruncateDecimalPlaces(this decimal? value, int places)
{
if (value == null)
{
return null;
}
return Math.Floor((decimal)value * (decimal)Math.Pow(10, places)) / (decimal)Math.Pow(10, places);
} // end
I've experimented with typing "exit for" a few times and noticed it worked and VB didn't yell at me. It's an option I guess but it just looked bad.
I think the best option is similar to that shared by Tobias. Just put your code in a function and have it return when you want to break out of your loops. Looks cleaner too.
For Each item In itemlist
For Each item1 In itemlist1
If item1 = item Then
Return item1
End If
Next
Next
One case where *args and **kwargs are useful is when writing wrapper functions (such as decorators) that need to be able accept arbitrary arguments to pass through to the function being wrapped. For example, a simple decorator that prints the arguments and return value of the function being wrapped:
def mydecorator( f ):
@functools.wraps( f )
def wrapper( *args, **kwargs ):
print "Calling f", args, kwargs
v = f( *args, **kwargs )
print "f returned", v
return v
return wrapper
here you have simple solution (other write about it) http://www.benlesh.com/2012/05/calling-javascript-function.html
And here you have above ready solution:
function async(your_function, callback) {
setTimeout(function() {
your_function();
if (callback) {callback();}
}, 0);
}
TEST 1 (may output '1 x 2 3' or '1 2 x 3' or '1 2 3 x'):
console.log(1);
async(function() {console.log('x')}, null);
console.log(2);
console.log(3);
TEST 2 (will always output 'x 1'):
async(function() {console.log('x');}, function() {console.log(1);});
This function is executed with timeout 0 - it will simulate asynchronous task
You can deploy an images folder as a separate webapp and define the location of that folder to be anywhere in the file system.
Create a Context element in an XML file in the directory $CATALINA_HOME/conf/[enginename]/[hostname]/
where enginename might be 'Catalina' and hostname might be 'localhost'.
Name the file based on the path URL you want the images to be viewed from, so if your webapp has path 'blog', you might name the XML file blog#images.xml
and so that your images would be visible at example.com/blog/images/
The content of the XML file should be <Context docBase="/filesystem/path/to/images"/>
Be careful not to undeploy this webapp, as that could delete all your images!
TL; DR
This might also be caused by applying OR
to string columns / literals.
Full version
I got the same error message for a simple INSERT
statement involving a view:
insert into t1 select * from v1
although all the source and target columns were of type VARCHAR
. After some debugging, I found the root cause; the view contained this fragment:
string_col1 OR '_' OR string_col2 OR '_' OR string_col3
which presumably was the result of an automatic conversion of the following snippet from Oracle:
string_col1 || '_' || string_col2 || '_' || string_col3
(||
is string concatenation in Oracle). The solution was to use
concat(string_col1, '_', string_col2, '_', string_col3)
instead.
In case the OP wants to squash the 2 commits specified into 1, here is an alternate way to do it without rebasing
git checkout HEAD^ # go to the first commit you want squashed
git reset --soft HEAD^ # go to the second one but keep the tree and index the same
git commit --amend -C HEAD@{1} # use the message from first commit (omit this to change)
git checkout HEAD@{3} -- . # get the tree from the commit you did not want to touch
git add -A # add everything
git commit -C HEAD@{3} # commit again using the message from that commit
The @{N)
syntax is handy to know as it will allow you to reference the history of where your references were. In this case it's HEAD which represents your current commit.
A stable sorting algorithm is the one that sorts the identical elements in their same order as they appear in the input, whilst unstable sorting may not satisfy the case. - I thank my algorithm lecturer Didem Gozupek to have provided insight into algorithms.
Stable Sorting Algorithms:
Unstable Sorting Algorithms:
You can't modify the default dialogue for onbeforeunload
, so your best bet may be to work with it.
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
Here's a reference to this from Microsoft:
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
The problem seems to be:
onbeforeunload
is called, it will take the return value of the handler as window.event.returnValue
.false
is parsed as a string, the dialogue box will fire, which will then pass an appropriate true
/false
.The result is, there doesn't seem to be a way of assigning false
to onbeforeunload
to prevent it from the default dialogue.
Additional notes on jQuery:
onbeforeunload
events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.jQuery doesn't have a shortcut for onbeforeunload
so you'd have to use the generic bind
syntax.
$(window).bind('beforeunload', function() {} );
Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)
A common approach to follow to solve this problem.
1.CHECK your SDK manager by running from your android studio and stand alons sdk folder by executing ./android.sh
helps you to find broken packages
Try installing System emulator images with google API support than the Intel one. Just like , i solved my problem by running into another system image.
Experment on KVM based Virtulaization suggested by Google for Linux
Try this before your first editable field:
<TextView
android:id="@+id/dummyfocus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/foo"
/>
----
findViewById(R.id.dummyfocus).setFocusableInTouchMode(true);
findViewById(R.id.dummyfocus).requestFocus();
If you use
std::vector<std::reference_wrapper<std::string>> names{ };
Do not forget, when you use auto in the for loop, to use also get, like this:
for (auto element in : names)
{
element.get()//do something
}
I'll try to answer the why question: The Java array is very simple and rudimentary compared to classes like ArrayList, that are more dynamic. Java wants to know at declaration time how much memory should be allocated for the array. An ArrayList is much more dynamic and the size of it can vary over time.
If you initialize your array with the length of two, and later on it turns out you need a length of three, you have to throw away what you've got, and create a whole new array. Therefore the 'new' keyword.
In your first two examples, you tell at declaration time how much memory to allocate. In your third example, the array name becomes a pointer to nothing at all, and therefore, when it's initialized, you have to explicitly create a new array to allocate the right amount of memory.
I would say that (and if someone knows better, please correct me) the first example
AClass[] array = {object1, object2}
actually means
AClass[] array = new AClass[]{object1, object2};
but what the Java designers did, was to make quicker way to write it if you create the array at declaration time.
The suggested workarounds are good. If the time or memory usage is critical at runtime, use arrays. If it's not critical, and you want code that is easier to understand and to work with, use ArrayList.
Run this command in your project folder location in cmd
php artisan --version
I had the same error using Symfony 5 / Doctrine 2. One of my fields was named using a MySQL reserved word "order", causing a DBALException. When you want to use a reserved word, you have to escape it's name using back-ticks. In annotation form :
@ORM\Column(name="`order`", type="integer", nullable=false)
Because they're measuring different things.
Propagation delay is how long it takes one bit to travel from one end of the "wire" to the other (it's proportional to the length of the wire, crudely).
Transmission delay is how long it takes to get all the bits into the wire in the first place (it's packet_length/data_rate).
// In MyClass.h
MyClass<T>& operator+=(const MyClass<T>& classObj);
// In MyClass.cpp
template <class T>
MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) {
// ...
return *this;
}
This is invalid for templates. The full source code of the operator must be in all translation units that it is used in. This typically means that the code is inline in the header.
Edit: Technically, according to the Standard, it is possible to export templates, however very few compilers support it. In addition, you CAN also do the above if the template is explicitly instantiated in MyClass.cpp for all types that are T- but in reality, that normally defies the point of a template.
More edit: I read through your code, and it needs some work, for example overloading operator[]. In addition, typically, I would make the dimensions part of the template parameters, allowing for the failure of + or += to be caught at compile-time, and allowing the type to be meaningfully stack allocated. Your exception class also needs to derive from std::exception. However, none of those involve compile-time errors, they're just not great code.
What you need is to use the DateTime classs Subtract method, which returns a TimeSpan.
var dateOne = DateTime.Now;
var dateTwo = DateTime.Now.AddMinutes(-5);
var diff = dateTwo.Subtract(dateOne);
var res = String.Format("{0}:{1}:{2}", diff.Hours,diff.Minutes,diff.Seconds));
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
Here's an example of how to convert DATETIME
to UNIX timestamp:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))
Here's an example of how to change date format:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p')
Documentation: UNIX_TIMESTAMP
, FROM_UNIXTIME
HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
you can use this for lists of the same length
def lstsum(a, b):
c=0
pos = 0
for element in a:
c+= element*b[pos]
pos+=1
return c
Just adding another way to perform a selection programatically - this is probably what was the intention in the first place or maybe this was added later on.
Menu bottomNavigationMenu = myBottomNavigationMenu.getMenu();
bottomNavigationMenu.performIdentifierAction(selected_menu_item_id, 0);
The performIdentifierAction
takes a Menu
item id and a flag.
See the documentation for more info.
As an alternative, you could add it as a script parameter for input as part of script execution
param(
[Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value1,
[Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value2
)
Here's the magic you want:
autocomplete="new-password"
Chrome intentionally ignores autocomplete="off"
and autocomplete="false"
. However, they put new-password
in as a special clause to stop new password forms from being auto-filled.
I put the above line in my password input, and now I can edit other fields in my form and the password is not auto-filled.
Just do Ctrl + Enter inside the text box
You can use JQuery .load() method:
$( "#content" ).load( "ajax/test.html div#content" );
If you want the while loop to stop after some condition, and your foo
command returns non-zero when this condition is met then you can get the loop to break like this:
while foo; do echo 'sleeping...'; sleep 5; done;
For example, if the foo
command is deleting things in batches, and it returns 1 when there is nothing left to delete.
This works well if you have a custom script that needs to run a command many times until some condition. You write the script to exit with 1
when the condition is met and exit with 0
when it should be run again.
For example, say you have a python script batch_update.py
which updates 100 rows in a database and returns 0
if there are more to update and 1
if there are no more. The the following command will allow you to update rows 100 at a time with sleeping for 5 seconds between updates:
while batch_update.py; do echo 'sleeping...'; sleep 5; done;
This CSS might work for <input type="button" ..
:
white-space: normal
The following worked for me:
Put your curl statement in a script named abc.sh
Now run:
sh abc.sh 1>stdout_output 2>stderr_output
You will get your curl's results in stdout_output
and the progress info in stderr_output
.
< img style="vertical-align: bottom" src="blah.png" >
Works for me. Inside a parallax div as well.
After reading the http://wiki.debian.org/Multiarch/LibraryPathOverview that jeremiah posted, i found the gcc flag that works without the symlink:
gcc -B/usr/lib/x86_64-linux-gnu hello.c
So, you can just add -B/usr/lib/x86_64-linux-gnu
to the CFLAGS variable in your Makefile.
You can use sum
to sum the elements of a list, however if your list is coming from raw_input
, you probably want to convert the items to int
or float
first:
l = raw_input().split(' ')
sum(map(int, l))
You need something like this, maybe it can be improved. This is a first attempt:
...
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
...
@Configuration
...
@org.springframework.context.annotation.PropertySource("classpath:/config/default.properties")
...
public class GeneralApplicationConfiguration implements WebApplicationInitializer
{
@Autowired
Environment env;
public void someMethod() {
...
Map<String, Object> map = new HashMap();
for(Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) {
PropertySource propertySource = (PropertySource) it.next();
if (propertySource instanceof MapPropertySource) {
map.putAll(((MapPropertySource) propertySource).getSource());
}
}
...
}
...
Basically, everything from the Environment that's a MapPropertySource
(and there are quite a lot of implementations) can be accessed as a Map
of properties.
Using regex, string functions, parse_url() or their combinations it's not real solution. Just test any of proposed solutions with domain test.en.example.co.uk
, there will no any correct result.
Correct solution is use package that parses domain with Public Suffix List. I recomend TLDExtract, here is sample code:
$extract = new LayerShifter\TLDExtract\Extract();
$result = $extract->parse('test.en.example.co.uk');
$result->getSubdomain(); // will return (string) 'test.en'
$result->getSubdomains(); // will return (array) ['test', 'en']
$result->getHostname(); // will return (string) 'example'
$result->getSuffix(); // will return (string) 'co.uk'
If your array is not initialized then it contains randoms values and cannot be checked !
To initialize your array with 0 values:
int array[5] = {0};
Then you can check if the value is 0:
array[4] == 0;
When you compare to NULL, it compares to 0 as the NULL is defined as integer value 0 or 0L.
If you have an array of pointers, better use the nullptr
value to check:
char* array[5] = {nullptr}; // we defined an array of char*, initialized to nullptr
if (array[4] == nullptr)
// do something
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
Simply use an image extension like .jpeg
or .png
.
For the extension method fans:
public static bool RegexStartsWith(this string str, params string[] patterns)
{
return patterns.Any(pattern =>
Regex.Match(str, "^("+pattern+")").Success);
}
Usage
var answer = str.RegexStartsWith("mailto","ftp","joe");
//or
var answer2 = str.RegexStartsWith("mailto|ftp|joe");
//or
bool startsWithWhiteSpace = " does this start with space or tab?".RegexStartsWith(@"\s");
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
pd.DataFrame.loc
can take one or two indexers. For the rest of the post, I'll represent the first indexer as i
and the second indexer as j
.
If only one indexer is provided, it applies to the index of the dataframe and the missing indexer is assumed to represent all columns. So the following two examples are equivalent.
df.loc[i]
df.loc[i, :]
Where :
is used to represent all columns.
If both indexers are present, i
references index values and j
references column values.
Now we can focus on what types of values i
and j
can assume. Let's use the following dataframe df
as our example:
df = pd.DataFrame([[1, 2], [3, 4]], index=['A', 'B'], columns=['X', 'Y'])
loc
has been written such that i
and j
can be
scalars that should be values in the respective index objects
df.loc['A', 'Y']
2
arrays whose elements are also members of the respective index object (notice that the order of the array I pass to loc
is respected
df.loc[['B', 'A'], 'X']
B 3
A 1
Name: X, dtype: int64
Notice the dimensionality of the return object when passing arrays. i
is an array as it was above, loc
returns an object in which an index with those values is returned. In this case, because j
was a scalar, loc
returned a pd.Series
object. We could've manipulated this to return a dataframe if we passed an array for i
and j
, and the array could've have just been a single value'd array.
df.loc[['B', 'A'], ['X']]
X
B 3
A 1
boolean arrays whose elements are True
or False
and whose length matches the length of the respective index. In this case, loc
simply grabs the rows (or columns) in which the boolean array is True
.
df.loc[[True, False], ['X']]
X
A 1
In addition to what indexers you can pass to loc
, it also enables you to make assignments. Now we can break down the line of code you provided.
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
iris_data['class'] == 'versicolor'
returns a boolean array.class
is a scalar that represents a value in the columns object.iris_data.loc[iris_data['class'] == 'versicolor', 'class']
returns a pd.Series
object consisting of the 'class'
column for all rows where 'class'
is 'versicolor'
When used with an assignment operator:
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
We assign 'Iris-versicolor'
for all elements in column 'class'
where 'class'
was 'versicolor'
Only one plugin help me: Role-Based Strategy :
wiki.jenkins-ci.org/display/JENKINS/Role+Strategy+Plugin
But official documentation (wiki.jenkins-ci.org/display/JENKINS/Role+Strategy+Plugin) is deficient.
The following configurations worked for me:
configure-role-strategy-plugin-in-jenkins
Basically you just need to create roles and match them with job names using regex.
The underlying problem revolves around accessing the data within the array, as Felix Kling points out in the first response.
In the following code, I've accessed the values of the array with the print and echo constructs.
function data()
{
$a = "abc";
$b = "def";
$c = "ghi";
$array = array($a, $b, $c);
print_r($array);//outputs the key/value pair
echo "<br>";
echo $array[0].$array[1].$array[2];//outputs a concatenation of the values
}
data();
This is a possible implementation of the required Bash function:
# Print the newest file, if any, matching the given pattern
# Example usage:
# newest_matching_file 'b2*'
# WARNING: Files whose names begin with a dot will not be checked
function newest_matching_file
{
# Use ${1-} instead of $1 in case 'nounset' is set
local -r glob_pattern=${1-}
if (( $# != 1 )) ; then
echo 'usage: newest_matching_file GLOB_PATTERN' >&2
return 1
fi
# To avoid printing garbage if no files match the pattern, set
# 'nullglob' if necessary
local -i need_to_unset_nullglob=0
if [[ ":$BASHOPTS:" != *:nullglob:* ]] ; then
shopt -s nullglob
need_to_unset_nullglob=1
fi
newest_file=
for file in $glob_pattern ; do
[[ -z $newest_file || $file -nt $newest_file ]] \
&& newest_file=$file
done
# To avoid unexpected behaviour elsewhere, unset nullglob if it was
# set by this function
(( need_to_unset_nullglob )) && shopt -u nullglob
# Use printf instead of echo in case the file name begins with '-'
[[ -n $newest_file ]] && printf '%s\n' "$newest_file"
return 0
}
It uses only Bash builtins, and should handle files whose names contain newlines or other unusual characters.
Did you try this?
UPDATE table
SET col1 = NULL
WHERE col1 = ''
As the commenters point out, you don't have to do ltrim()
or rtrim()
, and NULL
columns will not match ''
.
Depends on what you have. If your svg icon is just a path, then it's easy enough to add that glyph by just copying the 'd' attribute to a new <glyph> element. However, the path needs to be scaled to the font's coordinate system (the EM-square, which typically is [0,0,2048,2048] - the standard for Truetype fonts) and aligned with the baseline you want.
Not all browsers support svg fonts however, so you're going to have to convert it to other formats too if you want it to work everywhere.
Fontforge can import svg files (select a glyph slot, File > Import and then select your svg image), and you can then convert to all the relevant font formats (svg, truetype, woff etc).
These both work for me in JavaScript and TypeScript
<img src="@/assets/images/logo.png" alt="">
or
<img src="./assets/images/logo.png" alt="">
No CSS required, visible class should like this: visible-md-block
not just visible-md
and the code should be like this:
<div class="containerdiv hidden-sm hidden-xs visible-md-block visible-lg-block">
<div class="row">
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 logo">
</div>
</div>
</div>
<div class="mobile hidden-md hidden-lg ">
test
</div>
Extra css is not required at all.
global.myNumber; //Delclaration of the global variable - undefined
global.myNumber = 5; //Global variable initialized to value 5.
var myNumberSquared = global.myNumber * global.myNumber; //Using the global variable.
Node.js is different from client Side JavaScript when it comes to global variables. Just because you use the word var at the top of your Node.js script does not mean the variable will be accessible by all objects you require such as your 'basic-logger' .
To make something global just put the word global and a dot in front of the variable's name. So if I want company_id to be global I call it global.company_id. But be careful, global.company_id and company_id are the same thing so don't name global variable the same thing as any other variable in any other script - any other script that will be running on your server or any other place within the same code.
Simply set includeantruntime="false"
:
<javac includeantruntime="false" ...>...</javac>
If you have to use the javac
-task multiple times you might want to consider using PreSetDef
to define your own javac
-task that always sets includeantruntime="false"
.
From http://www.coderanch.com/t/503097/tools/warning-includeantruntime-was-not-set:
That's caused by a misfeature introduced in Ant 1.8. Just add an attribute of that name to the javac task, set it to false, and forget it ever happened.
From http://ant.apache.org/manual/Tasks/javac.html:
Whether to include the Ant run-time libraries in the classpath; defaults to yes, unless build.sysclasspath is set. It is usually best to set this to false so the script's behavior is not sensitive to the environment in which it is run.
Does document.getElementById("blue") exist? if it doesn't then blue_box will be equal to null. you can't set a onclick on something that's null
<context:property-placeholder ... />
is the XML equivalent to the PropertyPlaceholderConfigurer. So, prefer that. The <util:properties/>
simply factories a java.util.Properties instance that you can inject.
In Spring 3.1 (not 3.0...) you can do something like this:
@Configuration
@PropertySource("/foo/bar/services.properties")
public class ServiceConfiguration {
@Autowired Environment environment;
@Bean public javax.sql.DataSource dataSource( ){
String user = this.environment.getProperty("ds.user");
...
}
}
In Spring 3.0, you can "access" properties defined using the PropertyPlaceHolderConfigurer mechanism using the SpEl annotations:
@Value("${ds.user}") private String user;
If you want to remove the XML all together, simply register the PropertyPlaceholderConfigurer manually using Java configuration. I prefer the 3.1 approach. But, if youre using the Spring 3.0 approach (since 3.1's not GA yet...), you can now define the above XML like this:
@Configuration
public class MySpring3Configuration {
@Bean
public static PropertyPlaceholderConfigurer configurer() {
PropertyPlaceholderConfigurer ppc = ...
ppc.setLocations(...);
return ppc;
}
@Bean
public class DataSource dataSource(
@Value("${ds.user}") String user,
@Value("${ds.pw}") String pw,
...) {
DataSource ds = ...
ds.setUser(user);
ds.setPassword(pw);
...
return ds;
}
}
Note that the PPC is defined using a static
bean definition method. This is required to make sure the bean is registered early, because the PPC is a BeanFactoryPostProcessor
- it can influence the registration of the beans themselves in the context, so it necessarily has to be registered before everything else.
This sometimes works.
Check that the processor architecture under Test menu matches the one you use to build the solution.
Test -> Test Settings -> Default Processor Architecture -> x86 / x64
As mentioned in other posts, make sure you have the Test Explorer window open. Test -> Windows -> Test Explorer
Then rebuilding the project with the tests should make the tests appear in Test Explorer.
Edit: As Ourjamie pointed out below, doing a clean build may also help. In addition to that, here is one more thing I encountered:
The "Build" checkbox was unticked in Configuration Manager for a new test project I had created under the solution.
Go to Build -> Configuration Manager. Make sure your test project has build checkbox checked for all solution configurations and solution platforms.
I know this is an old question, but I stumbled across it when I was having a similar issue, and just wanted to share how I ended achieving the results you requested so future people can pick what works best for their situation.
First, I utilize the onsubmit
event in the form, and pass this
to the function to make it easier to deal with this particular form.
<form action="/system/wpacert" onsubmit="return closeSelf(this);" method="post" enctype="multipart/form-data" name="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div>Certificate 3: <input type="file" name="cert3"/></div>
<div><input type="submit" value="Upload"/></div>
</form>
In our function, we'll submit the form data, and then we'll close the window. This will allow it to submit the data, and once it's done, then it'll close the window and return you to your original window.
<script type="text/javascript">
function closeSelf (f) {
f.submit();
window.close();
}
</script>
Hope this helps someone out. Enjoy!
Option 2: This option will let you submit via AJAX, and if it's successful, it'll close the window. This prevents windows from closing prior to the data being submitted. Credits to http://jquery.malsup.com/form/ for their work on the jQuery Form Plugin
First, remove your onsubmit/onclick events from the form/submit button. Place an ID on the form so AJAX can find it.
<form action="/system/wpacert" method="post" enctype="multipart/form-data" id="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div>Certificate 3: <input type="file" name="cert3"/></div>
<div><input type="submit" value="Upload"/></div>
</form>
Second, you'll want to throw this script at the bottom, don't forget to reference the plugin. If the form submission is successful, it'll close the window.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function () {
$('#certform').ajaxForm(function () {
window.close();
});
});
</script>
This happened to me on VS2013(Update 5)/ASP.NET 4.5, under project type "Web Application" that includes MVC and Web API 2. Error happened right after creating the project and before adding any code. Adding the following configuration fix it for me. After resolving "System.Web.Helpers" issue two more similar errors surfaced for "System.Web.Mvc" and "System.Web.WebPages".
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
For any of you calling back to the same server for your IFRAME, pass this simple header inside the IFRAME page:
Content-Security-Policy: frame-ancestors 'self'
Or, add this to your web server's CSP configuration.
Build on what you already know and have a look at lot of job adverts. E.g I have seen jobs asking for WinForms/WPF AND electronics for the writing of a UI to control a custom bit of hardware.
You may find the “robotics” .net toolkit interesting.
.Net is now too big for anyone to learn both WEB and Desktop so you have to decide the way you are going to go. Web has lots more jobs, but there are very few people with good desktop stills.
Resolved the issue... you need to add the ssh public key to your github account.
ssh-keygen
~/.ssh/id_rsa
)~/.ssh/id_rsa.pub
) to github account git clone
. It works!
Initial status (public key not added to git hub account)
foo@bn18-251:~$ rm -rf test foo@bn18-251:~$ ls foo@bn18-251:~$ git clone [email protected]:devendra-d-chavan/test.git Cloning into 'test'... Permission denied (publickey). fatal: The remote end hung up unexpectedly foo@bn18-251:~$
Now, add the public key ~/.ssh/id_rsa.pub
to the github account (I used cat ~/.ssh/id_rsa.pub
)
foo@bn18-251:~$ ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/home/foo/.ssh/id_rsa): Created directory '/home/foo/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/foo/.ssh/id_rsa. Your public key has been saved in /home/foo/.ssh/id_rsa.pub. The key fingerprint is: xxxxx The key's randomart image is: +--[ RSA 2048]----+ xxxxx +-----------------+ foo@bn18-251:~$ cat ./.ssh/id_rsa.pub xxxxx foo@bn18-251:~$ git clone [email protected]:devendra-d-chavan/test.git Cloning into 'test'... The authenticity of host 'github.com (207.97.227.239)' can't be established. RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'github.com,207.97.227.239' (RSA) to the list of known hosts. Enter passphrase for key '/home/foo/.ssh/id_rsa': warning: You appear to have cloned an empty repository. foo@bn18-251:~$ ls test foo@bn18-251:~/test$ git status # On branch master # # Initial commit # nothing to commit (create/copy files and use "git add" to track)
You can use div to achieve this. without img tag :) hope this helps.
.img{_x000D_
width:100px;_x000D_
height:100px;_x000D_
background-image:url('http://www.mandalas.com/mandala/htdocs/images/Lrg_image_Pages/Flowers/Large_Orange_Lotus_8.jpg');_x000D_
background-repeat:no-repeat;_x000D_
background-position:center center;_x000D_
border:1px solid red;_x000D_
background-size:cover;_x000D_
}_x000D_
.img1{_x000D_
width:100px;_x000D_
height:100px;_x000D_
background-image:url('https://images.freeimages.com/images/large-previews/9a4/large-pumpkin-1387927.jpg');_x000D_
background-repeat:no-repeat;_x000D_
background-position:center center;_x000D_
border:1px solid red;_x000D_
background-size:cover;_x000D_
}
_x000D_
<div class="img"> _x000D_
</div>_x000D_
<div class="img1"> _x000D_
</div>
_x000D_
Use the STL find function.
Keep in mind that there is also a find_if function, which you can use if your search is more complex, i.e. if you're not just looking for an element, but, for example, want see if there is an element that fulfills a certain condition, for example, a string that starts with "abc". (find_if
would give you an iterator that points to the first such element).
It's not necessary, as interfaces are by default abstract as all the methods in an interface are abstract.
By default Entity Framework uses lazy-loading for navigation properties. That's why these properties should be marked as virtual - EF creates proxy class for your entity and overrides navigation properties to allow lazy-loading. E.g. if you have this entity:
public class MemberLoan
{
public string LoandProviderCode { get; set; }
public virtual Membership Membership { get; set; }
}
Entity Framework will return proxy inherited from this entity and provide DbContext instance to this proxy in order to allow lazy loading of membership later:
public class MemberLoanProxy : MemberLoan
{
private CosisEntities db;
private int membershipId;
private Membership membership;
public override Membership Membership
{
get
{
if (membership == null)
membership = db.Memberships.Find(membershipId);
return membership;
}
set { membership = value; }
}
}
So, entity has instance of DbContext which was used for loading entity. That's your problem. You have using
block around CosisEntities usage. Which disposes context before entities are returned. When some code later tries to use lazy-loaded navigation property, it fails, because context is disposed at that moment.
To fix this behavior you can use eager loading of navigation properties which you will need later:
IQueryable<MemberLoan> query = db.MemberLoans.Include(m => m.Membership);
That will pre-load all memberships and lazy-loading will not be used. For details see Loading Related Entities article on MSDN.
fyi The code I ended up with:
IF UPDATE (QtyToRepair)
begin
INSERT INTO tmpQtyToRepairChanges (OrderNo, PartNumber, ModifiedDate, ModifiedUser, ModifiedHost, QtyToRepairOld, QtyToRepairNew)
SELECT S.OrderNo, S.PartNumber, GETDATE(), SUSER_NAME(), HOST_NAME(), D.QtyToRepair, I.QtyToRepair FROM SCHEDULE S
INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber
WHERE I.QtyToRepair <> D.QtyToRepair
end
I originally wrote this answer when TypeScript was still hot-off-the-presses. Five years later, this is an OK overview, but look at Lodewijk's answer below for more depth
TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.
To get an idea of what I mean, watch Microsoft's introductory video on the language.
For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.
It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza). These days, other IDEs offer TypeScript support too.
There's CoffeeScript, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for tools through its optional static typing (see this recent blog post for a little more critique). There's also Dart but that's a full on replacement for JavaScript (though it can produce JavaScript code)
As an example, here's some TypeScript (you can play with this in the TypeScript Playground)
class Greeter {
greeting: string;
constructor (message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
And here's the JavaScript it would produce
var Greeter = (function () {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
})();
Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.
It's also capable of inferring types which aren't explicitly declared, for example, it would determine the greet()
method returns a string.
Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio
I originally wrote this answer when TypeScript was still hot-off-the-presses. Check out Lodewijk's answer to this question for some more current detail.
It's frustrating that what works great in one browser doesn't work in others. The following works in Firefox, but not in Chrome or IE:
<table width="80%">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody style="height:50px; overflow:auto">
<tr>
<td>Cell A1</td>
<td>Cell B1</td>
<td>Cell C1</td>
</tr>
<tr>
<td>Cell A2</td>
<td>Cell B2</td>
<td>Cell C2</td>
</tr>
<tr>
<td>Cell A3</td>
<td>Cell B3</td>
<td>Cell C3</td>
</tr>
</tbody>
</table>
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
y_true = # true labels
y_probas = # predicted results
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_probas, pos_label=0)
# Print ROC curve
plt.plot(fpr,tpr)
plt.show()
# Print AUC
auc = np.trapz(tpr,fpr)
print('AUC:', auc)
The bug is probably somewhere else in your code, because it should work fine:
>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True
Or with tuples:
>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True
I solved the problem in my case by deleting file
C:\Users\username.AndroidStudioX\studio64.exe.vmoptions
( x denotes the version of your android studio so it can be different ) , because I created it before to customize VM options. It's that simple
If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory
return this.http.get('<json file path inside assets folder>.json'))
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json
If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.
document.getElementById('username').value="moo"
document.forms[0].submit()
The lattice
library is another good option. Here I've added a legend on the right side and jittered the points because some of them overlapped.
xyplot(Sepal.Width ~ Sepal.Length, group=Species, data=iris,
auto.key=list(space="right"),
jitter.x=TRUE, jitter.y=TRUE)
I'm still learning Android, so I cannot provide a rich context or reason for my suggestion, but this is what I am using to retrive files from both https and local urls. I am using this in my onActivity result (for both taking pictures and selecting from gallery), as well in an AsyncTask to retrieve the https urls.
InputStream input = new URL("your_url_string").openStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
$conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
edittext.setFocusable(false);
edittext.setEnabled(false);
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
//removes on screen keyboard
My solution for this problem is to put an xml drawable resource on the background field of every cell. In this manner you could define a shape with the border you want for all cells. The only inconvenience is that the borders of the extreme cells have half the width of the others but it's no problem if your table fills the entire screen.
An Example:
drawable/cell_shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape= "rectangle" >
<solid android:color="#000"/>
<stroke android:width="1dp" android:color="#ff9"/>
</shape>
layout/my_table.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TableRow
android:id="@+id/tabla_cabecera"
android:layout_width="match_parent"
android:layout_height="match_parent"></TableRow>
<TableLayout
android:id="@+id/tabla_cuerpo"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:id="@+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:padding="5dp"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
</TableRow>
</TableLayout>
</LinearLayout>
Edit: An example
Edit2: Another example (with more elements: circle corners, gradients...)
I have explained this issue with more details in http://blog.intelligenia.com/2012/02/programacion-movil-en-android.html#more. It's in spanish but there are some codes and images of more complex tables.
Redirect and Request dispatcher are two different methods to move form one page to another. if we are using redirect to a new page actually a new request is happening from the client side itself to the new page. so we can see the change in the URL. Since redirection is a new request the old request values are not available here.
try to change the order: right click on you project-> BuildPath->Configure...->Order and Export tab -> move jre7 UP.
By default link color is blue and the visited color is purple. Also, the text-decoration is underlined and the color is blue. If you want to keep the same color for visited, hover and focus then follow below code-
For example color is: #000
a:visited, a:hover, a:focus {
text-decoration: none;
color: #000;
}
If you want to use a different color for hover, visited and focus. For example Hover color: red visited color: green and focus color: yellow then follow below code
a:hover {
color: red;
}
a:visited {
color: green;
}
a:focus {
color: yellow;
}
NB: good practice is to use color code.
You can pass custom http headers with RestTemplate exchange method as below.
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");
HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(request, headers);
RestTemplate template = new RestTemplate();
ResponseEntity<RestResponse> respEntity = template
.exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);
EDIT : Below is the updated code. This link has several ways of calling rest service with examples
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Mall[]> respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Mall[].class);
Mall[] resp = respEntity.getBody();
I was having same problem.
1 option: Download junit 4.12.jar and copy it in your lib folder and restart android studio. Benefit u don't have to create any new project
2 option: Create a new project having a internet connections and copy all the java and XML code in the newly created project. Benefit this problem will be solved permantly
I used to have this problem sometimes, the solution was to change the USB cable to a new one
PS> alias | Where-Object {$_.Definition -match 'alias'}
CommandType Name Definition
----------- ---- ----------
Alias epal Export-Alias
Alias gal Get-Alias
Alias ipal Import-Alias
Alias nal New-Alias
Alias sal Set-Alias
what would be contradict of match in PS then as in to get field not matching a certain value in a column
let documentsURL = try! FileManager().url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:
let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)
NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
This should do it:
for (var i = 0; i < bank_holidays.length; i++) {
if (bank_holidays[i] === '06/04/2012') {
alert('LOL');
}
}
The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:
c.sendall()
instead of c.send()
to prevent possible issues where you may not have sent the entire msg with one call (see docs).'b'
for bytes string: c.sendall(b'Thank you for connecting')
Best solution (should work w/both 2.x & 3.x):
output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))
Epilogue/background: this isn't an issue in Python 2 because strings are bytes strings already -- your OP code would work perfectly in that environment. Unicode strings were added to Python in releases 1.6 & 2.0 but took a back seat until 3.0 when they became the default string type. Also see this similar question as well as this one.
You could add justify-content: space-between
to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.
#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
You could also add margin-left: auto
to the second element in order to align it to the right.
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
Solution with utl_encode.base64_encode
and utl_encode.base64_decode
have one limitation, they work only with strings up to 32,767 characters/bytes.
In case you have to convert bigger strings you will face several obstacles.
BASE64_ENCODE
the function has to read 3 Bytes and transform them. In case of Multi-Byte characters (e.g. öäüè€
stored at UTF-8, aka AL32UTF8
) 3 Character are not necessarily also 3 Bytes. In order to read always 3 Bytes you have to convert your CLOB
into BLOB
first.BASE64_DECODE
. The function has to read 4 Bytes and transform them into 3 Bytes. Those 3 Bytes are not necessarily also 3 CharactersCR
and/or LF
) character each 64 characters. Such new-line characters have to be ignored while decoding.Taking all this into consideration the full featured solution could be this one:
CREATE OR REPLACE FUNCTION DecodeBASE64(InBase64Char IN OUT NOCOPY CLOB) RETURN CLOB IS
blob_loc BLOB;
clob_trim CLOB;
res CLOB;
lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
dest_offset INTEGER := 1;
src_offset INTEGER := 1;
read_offset INTEGER := 1;
warning INTEGER;
ClobLen INTEGER := DBMS_LOB.GETLENGTH(InBase64Char);
amount INTEGER := 1440; -- must be a whole multiple of 4
buffer RAW(1440);
stringBuffer VARCHAR2(1440);
-- BASE64 characters are always simple ASCII. Thus you get never any Mulit-Byte character and having the same size as 'amount' is sufficient
BEGIN
IF InBase64Char IS NULL OR NVL(ClobLen, 0) = 0 THEN
RETURN NULL;
ELSIF ClobLen<= 32000 THEN
RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(InBase64Char)));
END IF;
-- UTL_ENCODE.BASE64_DECODE is limited to 32k, process in chunks if bigger
-- Remove all NEW_LINE from base64 string
ClobLen := DBMS_LOB.GETLENGTH(InBase64Char);
DBMS_LOB.CREATETEMPORARY(clob_trim, TRUE);
LOOP
EXIT WHEN read_offset > ClobLen;
stringBuffer := REPLACE(REPLACE(DBMS_LOB.SUBSTR(InBase64Char, amount, read_offset), CHR(13), NULL), CHR(10), NULL);
DBMS_LOB.WRITEAPPEND(clob_trim, LENGTH(stringBuffer), stringBuffer);
read_offset := read_offset + amount;
END LOOP;
read_offset := 1;
ClobLen := DBMS_LOB.GETLENGTH(clob_trim);
DBMS_LOB.CREATETEMPORARY(blob_loc, TRUE);
LOOP
EXIT WHEN read_offset > ClobLen;
buffer := UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(DBMS_LOB.SUBSTR(clob_trim, amount, read_offset)));
DBMS_LOB.WRITEAPPEND(blob_loc, DBMS_LOB.GETLENGTH(buffer), buffer);
read_offset := read_offset + amount;
END LOOP;
DBMS_LOB.CREATETEMPORARY(res, TRUE);
DBMS_LOB.CONVERTTOCLOB(res, blob_loc, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset, DBMS_LOB.DEFAULT_CSID, lang_context, warning);
DBMS_LOB.FREETEMPORARY(blob_loc);
DBMS_LOB.FREETEMPORARY(clob_trim);
RETURN res;
END DecodeBASE64;
CREATE OR REPLACE FUNCTION EncodeBASE64(InClearChar IN OUT NOCOPY CLOB) RETURN CLOB IS
dest_lob BLOB;
lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
dest_offset INTEGER := 1;
src_offset INTEGER := 1;
read_offset INTEGER := 1;
warning INTEGER;
ClobLen INTEGER := DBMS_LOB.GETLENGTH(InClearChar);
amount INTEGER := 1440; -- must be a whole multiple of 3
-- size of a whole multiple of 48 is beneficial to get NEW_LINE after each 64 characters
buffer RAW(1440);
res CLOB := EMPTY_CLOB();
BEGIN
IF InClearChar IS NULL OR NVL(ClobLen, 0) = 0 THEN
RETURN NULL;
ELSIF ClobLen <= 24000 THEN
RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(UTL_RAW.CAST_TO_RAW(InClearChar)));
END IF;
-- UTL_ENCODE.BASE64_ENCODE is limited to 32k/(3/4), process in chunks if bigger
DBMS_LOB.CREATETEMPORARY(dest_lob, TRUE);
DBMS_LOB.CONVERTTOBLOB(dest_lob, InClearChar, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset, DBMS_LOB.DEFAULT_CSID, lang_context, warning);
LOOP
EXIT WHEN read_offset >= dest_offset;
DBMS_LOB.READ(dest_lob, amount, read_offset, buffer);
res := res || UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(buffer));
read_offset := read_offset + amount;
END LOOP;
DBMS_LOB.FREETEMPORARY(dest_lob);
RETURN res;
END EncodeBASE64;
If you only need the standard functionality of hide only with visibility:hidden to keep the current layout you can use the callback function of hide to alter the css in the tag. Hide docs in jquery
An example :
$('#subs_selection_box').fadeOut('slow', function() {
$(this).css({"visibility":"hidden"});
$(this).css({"display":"block"});
});
This will use the normal cool animation to hide the div, but after the animation finish you set the visibility to hidden and display to block.
An example : http://jsfiddle.net/bTkKG/1/
I know you didnt want the $("#aa").css() solution, but you did not specify if it was because using only the css() method you lose the animation.
You could use the cut
command to remove the last two extensions (the ".tar.gz"
part):
$ echo "foo.tar.gz" | cut -d'.' --complement -f2-
foo
As noted by Clayton Hughes in a comment, this will not work for the actual example in the question. So as an alternative I propose using sed
with extended regular expressions, like this:
$ echo "mpc-1.0.1.tar.gz" | sed -r 's/\.[[:alnum:]]+\.[[:alnum:]]+$//'
mpc-1.0.1
It works by removing the last two (alpha-numeric) extensions unconditionally.
[Updated again after comment from Anders Lindahl]
I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.
Just provide another implementation of Jason's answer by C.
After discussing with my classmates, based on Jason's explanation, I like the recursive version more if you don't care about the performance very much:
For example:
#include<stdio.h>
int mypow( int base, int pow, int mod ){
if( pow == 0 ) return 1;
if( pow % 2 == 0 ){
int tmp = mypow( base, pow >> 1, mod );
return tmp * tmp % mod;
}
else{
return base * mypow( base, pow - 1, mod ) % mod;
}
}
int main(){
printf("%d", mypow(5,55,221));
return 0;
}
With ruby:
ruby -e "File.write('output.txt', File.read('input.txt').encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: ''))"
Source: https://robots.thoughtbot.com/fight-back-utf-8-invalid-byte-sequences
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
null
is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL
value) and hence cannot accurately represent the JSON null
. So they will sometimes represent it as an empty array.
Whether null
is a legal value in that particular element of that particular API is entirely up to the API designer.
For is()
import static org.hamcrest.CoreMatchers.*;
For assertThat()
import static org.junit.Assert.*;
For when() and verify()
import static org.mockito.Mockito.*;
By default, Java 8 Function does not allow to throw exception and as suggested in multiple answers there are many ways to achieve it, one way is:
@FunctionalInterface
public interface FunctionWithException<T, R, E extends Exception> {
R apply(T t) throws E;
}
Define as:
private FunctionWithException<String, Integer, IOException> myMethod = (str) -> {
if ("abc".equals(str)) {
throw new IOException();
}
return 1;
};
And add throws
or try/catch
the same exception in caller method.
Yeah it's possible.
Button myBtn = (Button)findViewById(R.id.myButtonId);
myBtn.requestFocus();
or in XML
<Button ...><requestFocus /></Button>
Important Note: The button widget needs to be focusable
and focusableInTouchMode
. Most widgets are focusable
but not focusableInTouchMode
by default. So make sure to either set it in code
myBtn.setFocusableInTouchMode(true);
or in XML
android:focusableInTouchMode="true"
You don't have the last version of typescript.
Running :
npm install -g typescript
npm
checks if tsc
command is already installed.
And it might be, by another software like Visual Studio
. If so, npm
doesn't override it. So you have to remove the previous deprecated tsc
installed command.
Run where tsc
to know its bin location. It should be in C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\
in windows. Once found, delete the folder, and re-run npm install -g typescript
. This should now install the last version of typescript.
=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")
I use Visual Studio git plugin, and I have some websites running on IIS I wanted to move. A simple way that worked for me:
Close Visual Studio.
Move the code (including git folder, etc)
Click on the solution file from the new location
This refreshes the mapping to the new location, using the existing local git files that were moved. Once i was back in Visual Studio, my Team Explorer window showed the repos in the new location.
Stack memory allocation (function variables, local variables) can be problematic when your stack is too "deep" and you overflow the memory available to stack allocations. The heap is for objects that need to be accessed from multiple threads or throughout the program lifecycle. You can write an entire program without using the heap.
You can leak memory quite easily without a garbage collector, but you can also dictate when objects and memory is freed. I have run in to issues with Java when it runs the GC and I have a real time process, because the GC is an exclusive thread (nothing else can run). So if performance is critical and you can guarantee there are no leaked objects, not using a GC is very helpful. Otherwise it just makes you hate life when your application consumes memory and you have to track down the source of a leak.
Have a look at ?options
and use warn
:
options( warn = -1 )
<?php
function is_valid_domain_name($domain_name)
{
return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name) //valid chars check
&& preg_match("/^.{1,253}$/", $domain_name) //overall length check
&& preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name) ); //length of each label
}
?>
Test cases:
is_valid_domain_name? [a] Y
is_valid_domain_name? [0] Y
is_valid_domain_name? [a.b] Y
is_valid_domain_name? [localhost] Y
is_valid_domain_name? [google.com] Y
is_valid_domain_name? [news.google.co.uk] Y
is_valid_domain_name? [xn--fsqu00a.xn--0zwm56d] Y
is_valid_domain_name? [goo gle.com] N
is_valid_domain_name? [google..com] N
is_valid_domain_name? [google.com ] N
is_valid_domain_name? [google-.com] N
is_valid_domain_name? [.google.com] N
is_valid_domain_name? [<script] N
is_valid_domain_name? [alert(] N
is_valid_domain_name? [.] N
is_valid_domain_name? [..] N
is_valid_domain_name? [ ] N
is_valid_domain_name? [-] N
is_valid_domain_name? [] N
For the complete system you can add the Microsoft.VisualBasic Framework as a reference;
Console.WriteLine("You have {0} bytes of RAM",
new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
Console.ReadLine();
I had the similar error.
All recommendations didn't help.
The only replacement www-data with nginx has helped:
$ sudo chown nginx:nginx /var/run/php/php7.2-fpm.sock
/var/www/php/fpm/pool.d/www.conf
user = nginx
group = nginx
...
listen.owner = nginx
listen.group = nginx
listen.mode = 0660
Delete All Records
#for all records
db.session.query(Model).delete()
db.session.commit()
Deleted Single Row
here DB is the object Flask-SQLAlchemy class. It will delete all records from it and if you want to delete specific records then try filter
clause in the query.
ex.
#for specific value
db.session.query(Model).filter(Model.id==123).delete()
db.session.commit()
Delete Single Record by Object
record_obj = db.session.query(Model).filter(Model.id==123).first()
db.session.delete(record_obj)
db.session.commit()
https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records
I have same issue and I have read answers in another topic then I solve another similar way. I do not know which is more effective. similar issue
//play button
@IBAction func startIt(sender: AnyObject) {
startThrough();
};
//play button
func startThrough() {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true);
let pauseButton = UIBarButtonItem(barButtonSystemItem: .Pause, target: self, action: "pauseIt");
self.toolBarIt.items?.removeLast();
self.toolBarIt.items?.append( pauseButton );
}
func pauseIt() {
timer.invalidate();
let play = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: "startThrough");
self.toolBarIt.items?.removeLast();
self.toolBarIt.items?.append( play );
}
Same answer as Brad Parks... more text though
I had the exact same problem and tried the above solutions along with many others, all with negative results. I even started out with a new, fresh Dev env and simply installed a spring-mvc-template and tried to run it directly after install (should work, but failed for me)
For me the problem was that I was using jdk1.6 in my project, but my selected execution environment in eclipse was jdk1.7. The solution was to change the project specific execution environment settings so that this project is set to jdk1.6. Right click project --> Properties --> Java Compiler --> Check "Enable project specific settings" if it's not already checked --> select the appropriate jdk (or add if it's not installed).
I hope this can help someone and save that persons time, because I have spent the last few days looking for the answer on every corner of the Internet. I accidently stumbled upon it myself when I started to get desperate and look for the solution in areas where it (according to my brain) was less likely to be found. =)
My 2 cents. Thanks!
Edit1: Use project specific settings
Edit2: Just realized Brad Parks already answered this in this very thread. Well, at least I got the "Editor"-badge out of this one =D
Adding below lines in build.gradle solved my issue .
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
Try this:
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
Remove the spaces around your =
:
<div>
<input type="text" [(ngModel)]="str" name="str">
</div>
But you need to have the variable named str
on back-end, than its should work fine.
I had the same problem on OSX OpenSSL 1.0.1i from Macports, and also had to specify CApath as a workaround (and as mentioned in the Ubuntu bug report, even an invalid CApath will make openssl look in the default directory). Interestingly, connecting to the same server using PHP's openssl functions (as used in PHPMailer 5) worked fine.
css cannot be directly applied for the alignment of the anchor tag. The css (text-align:center;) should be applied to the parent div/element for the alignment effect to take place on the anchor tag.
Are you sure you need a regex? It seems that you only need to know if a word is present in a string, so you can do:
>>> line = 'This,is,a,sample,string'
>>> "sample" in line
True
On windows you can use a graphic interface of scp using winSCP. A nice free software that implements SFTP protocol.
In the case you want to download a single file, you can try the following command:
aws s3 cp s3://bucket/filename /path/to/dest/folder
The primary advantage is type safety. With a set of constants, any value of the same intrinsic type could be used, introducing errors. With an enum only the applicable values can be used.
For example
public static final int SIZE_SMALL = 1;
public static final int SIZE_MEDIUM = 2;
public static final int SIZE_LARGE = 3;
public void setSize(int newSize) { ... }
obj.setSize(15); // Compiles but likely to fail later
vs
public enum Size { SMALL, MEDIUM, LARGE };
public void setSize(Size s) { ... }
obj.setSize( ? ); // Can't even express the above example with an enum
@Georgiy Ivankin made a suggestion in a comment, I used it successfully :) -- , but with slight changes:
$('#note').on('keyup',function(e){
var maxHeight = 200;
var f = document.getElementById('note');
if (f.clientHeight < f.scrollHeight && f.scrollHeight < maxHeight )
{ f.style.height = f.scrollHeight + 'px'; }
});
It stops expanding after it reaches max height of 200px
You have to bind your event handlers to correct context (this
):
onChange={this.setAuthorState.bind(this)}
Also make sure the div is currently appended to the DOM and visible.
public class SQLCon
{
public static string cs =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
protected void Page_Load(object sender, EventArgs e)
{
SqlDataAdapter MyDataAdapter;
SQLCon cs = new SQLCon();
DataSet RsUser = new DataSet();
RsUser = new DataSet();
using (SqlConnection MyConnection = new SqlConnection(SQLCon.cs))
{
MyConnection.Open();
MyDataAdapter = new SqlDataAdapter("GetAPPID", MyConnection);
//'Set the command type as StoredProcedure.
MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
RsUser = new DataSet();
MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@organizationID",
SqlDbType.Int));
MyDataAdapter.SelectCommand.Parameters["@organizationID"].Value = TxtID.Text;
MyDataAdapter.Fill(RsUser, "GetAPPID");
}
if (RsUser.Tables[0].Rows.Count > 0) //data was found
{
Session["AppID"] = RsUser.Tables[0].Rows[0]["AppID"].ToString();
}
else
{
}
}
See: Local dependency in package.json
It looks like the answer is npm link
: https://docs.npmjs.com/cli/link
Only mozilla implements a simple property in css : http://caniuse.com/#search=scroll-behavior
you will have to use JS at least.
I personally use this because its easy to use (I use JQ but you can adapt it I guess):
/*Scroll transition to anchor*/
$("a.toscroll").on('click',function(e) {
var url = e.target.href;
var hash = url.substring(url.indexOf("#")+1);
$('html, body').animate({
scrollTop: $('#'+hash).offset().top
}, 500);
return false;
});
just add class toscroll to your a tag
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
).
Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.
Server side Comments:
Razor .cshtml
@* Comment goes here *@
.aspx
For those looking for the older .aspx
view (and Asp.Net WebForms) server side comment syntax:
<%-- Comment goes here --%>
Client Side Comments
HTML Comment
<!-- Comment goes here -->
Javascript Comment
// One line Comment goes Here
/* Multiline comment
goes here */
As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).
I'm not sure if this answers your question, but for example:
if (A || B)
{
Console.WriteLine("Or");
}
if (A && B)
{
Console.WriteLine("And");
}
You have to implement KeyListener
,take a look here:
http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.html
More details on how to use it: http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
I had the same issue. My problem was that my header type wasn't set properly.
I just added this before my json echo
header('Content-type: application/json');
Json.NET does this...
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");
string json = JsonConvert.SerializeObject(values);
// {
// "key1": "value1",
// "key2": "value2"
// }
More examples: Serializing Collections with Json.NET
You can consider using a very small, dependency-free library like Not. Solves all problems:
// at the basic level it supports primitives
let number = 10
let array = []
not('number', 10) // returns false
not('number', []) // throws error
// so you need to define your own:
let not = Object.create(Not)
not.defineType({
primitive: 'number',
type: 'integer',
pass: function(candidate) {
// pre-ECMA6
return candidate.toFixed(0) === candidate.toString()
// ECMA6
return Number.isInteger(candidate)
}
})
not.not('integer', 4.4) // gives error message
not.is('integer', 4.4) // returns false
not.is('integer', 8) // returns true
If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.
function test (string, boolean) {
// any of these below will throw errors to protect you
not('string', string)
not('boolean', boolean)
// continue with your code.
}
If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8
but you can use any other version):
generate all .ll
files
clang-3.8 -S -emit-llvm *.c
link them into a single one
llvm-link-3.8 -S -v -o single.ll *.ll
(Optional) Optimise your code (maybe some alias analysis)
opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
Generate assembly (generates a optimised.s
file)
llc-3.8 optimised.ll
Create executable (named a.out
)
clang-3.8 optimised.s
If possible use Visual Studio. The Microsoft SQL Server Data Tools (SSDT) bring a built in functionality for this since the March 2014 release:
Note: Be careful, the "View Data" window is just like SSMS "Edit Top 200 Rows"- you can edit data right away
(Tested with Visual Studio 2015 with Microsoft SQL Server Data Tools (SSDT) Version 14.0.60812.0 and Microsoft SQL Server 2012)
e.g:
Your controller name is YourController
Your url must be:
http://example.com/index.php/YourController/method
Not be:
You don't need jQuery for this, as simple javascript will suffice:
alert(document.domain);
See it in action:
console.log("Output;"); _x000D_
console.log(location.hostname);_x000D_
console.log(document.domain);_x000D_
alert(window.location.hostname)_x000D_
_x000D_
console.log("document.URL : "+document.URL);_x000D_
console.log("document.location.href : "+document.location.href);_x000D_
console.log("document.location.origin : "+document.location.origin);_x000D_
console.log("document.location.hostname : "+document.location.hostname);_x000D_
console.log("document.location.host : "+document.location.host);_x000D_
console.log("document.location.pathname : "+document.location.pathname);
_x000D_
For further domain-related values, check out the properties of window.location
online. You may find that location.host
is a better option, as its content could differ from document.domain
. For instance, the url http://192.168.1.80:8080
will have only the ipaddress in document.domain
, but both the ipaddress and port number in location.host
.
You set an element's id by setting its corresponding property:
myPara.id = ID;
It's worth mentioning that you can specify argument ranges with this syntax.
function example() {
echo "line1 ${@:1:1}"; #First argument
echo "line2 ${@:2:1}"; #Second argument
echo "line3 ${@:3}"; #Third argument onwards
}
I hadn't seen it mentioned.
time.monotonic() (basically your computer's uptime in seconds) is guarranteed to not misbehave when your computer's clock is adjusted (such as when transitioning to/from daylight saving time).
>>> import time
>>>
>>> time.monotonic()
452782.067158593
>>>
>>> a = time.monotonic()
>>> time.sleep(1)
>>> b = time.monotonic()
>>> print(b-a)
1.001658110995777
To anyone who doesn't want to use DATE_SUB
, use CURRENT_DATE
:
SELECT CURRENT_DATE - INTERVAL 30 DAY
The "braces" are making an object literal, i.e. they create an object. It is one argument.
Example:
function someFunc(arg) {
alert(arg.foo);
alert(arg.bar);
}
someFunc({foo: "This", bar: "works!"});
the object can be created beforehand as well:
var someObject = {
foo: "This",
bar: "works!"
};
someFunc(someObject);
I recommend to read the MDN JavaScript Guide - Working with Objects.
Here is an iterative solution using object-scan. The advantage is that you can easily do other processing in the filter function and specify the paths in a more readable format. There is a trade-off in introducing a dependency though, so it really depends on your use case.
// const objectScan = require('object-scan');
const search = (haystack, k, v) => objectScan([`list[*].${k}`], {
rtn: 'parent',
filterFn: ({ value }) => value === v
})(haystack);
const obj = { list: [ { name: 'my Name', id: 12, type: 'car owner' }, { name: 'my Name2', id: 13, type: 'car owner2' }, { name: 'my Name4', id: 14, type: 'car owner3' }, { name: 'my Name4', id: 15, type: 'car owner5' } ] };
console.log(search(obj, 'name', 'my Name'));
// => [ { name: 'my Name', id: 12, type: 'car owner' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
try this code:
.absolute {
position: absolute;
top: 0; left: 0;
width: 200px;
height: 50px;
background: yellow;
}
Simply prevent the default browser action:
window.addEventListener("keydown", function(e) {
// space and arrow keys
if([32, 37, 38, 39, 40].indexOf(e.code) > -1) {
e.preventDefault();
}
}, false);
If you need to support Internet Explorer or other older browsers, use e.keyCode
instead of e.code
, but keep in mind that keyCode
is deprecated.
I used the following function in my own game:
var keys = {};
window.addEventListener("keydown",
function(e){
keys[e.code] = true;
switch(e.code){
case 37: case 39: case 38: case 40: // Arrow keys
case 32: e.preventDefault(); break; // Space
default: break; // do not block other keys
}
},
false);
window.addEventListener('keyup',
function(e){
keys[e.code] = false;
},
false);
The magic happens in e.preventDefault();
. This will block the default action of the event, in this case moving the viewpoint of the browser.
If you don't need the current button states you can simply drop keys
and just discard the default action on the arrow keys:
var arrow_keys_handler = function(e) {
switch(e.code){
case 37: case 39: case 38: case 40: // Arrow keys
case 32: e.preventDefault(); break; // Space
default: break; // do not block other keys
}
};
window.addEventListener("keydown", arrow_keys_handler, false);
Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:
window.removeEventListener("keydown", arrow_keys_handler, false);
window.addEventListener
window.removeEventListener
KeyboardEvent.code
interfaceMake sure HttpClient has access to the full client certificate (including the private key).
You are calling GetCert with a file "ClientCertificate.cer" which leads to the assumption that there is no private key contained - should rather be a pfx file within windows. It may be even better to access the certificate from the windows cert store and search it using the fingerprint.
Be careful when copying the fingerprint: There are some non-printable characters when viewing in cert management (copy the string over to notepad++ and check the length of the displayed string).
There is an implementation in my TypeScript utilities based on JavaScript GUID generators.
Here is the code:
class Guid {_x000D_
static newGuid() {_x000D_
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
var r = Math.random() * 16 | 0,_x000D_
v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
return v.toString(16);_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
var id = Guid.newGuid();_x000D_
console.log(id);_x000D_
}
_x000D_
Please note the following:
C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.
JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).
A simple example to illustrate how java.util.Scanner
works would be reading a single integer from System.in
. It's really quite simple.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
To retrieve a username I would probably use sc.nextLine()
.
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);
You could also use next(String pattern)
if you want more control over the input, or just validate the username
variable.
You'll find more information on their implementation in the API Documentation for java.util.Scanner
My issue was I was placing the methods inside my data object. just format it like this and it'll work nicely.
<script>
module.exports = {
data: () => {
return {
name: ""
}
},
methods: {
myFunc() {
// code
}
}
}
</script>
I find that if I try things that others say do not work, it's how I learn the most.
<p> </p>
<p>README.txt</p>
<p> </p>
<div id="list">
<p><iframe src="README.txt" frameborder="0" height="400"
width="95%"></iframe></p>
</div>
This worked for me. I used the yellow background-color that I set in the stylesheet.
#list p {
font: arial;
font-size: 14px;
background-color: yellow ;
}
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
declare @counts int
SET @city = 'New York'
SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75),@cnt int OUTPUT', @city = @city, @cnt=@counts OUTPUT
select @counts as Counts
i think, your image size is also same as button size then you put image in background of the button like :
[myLikesButton setBackgroundImage:[UIImage imageNamed:@"icon-heart.png"] forState:UIControlStateNormal];
you mast have same size of image and button.i hope you understand my point.
You can achieve almost everything in PROCESS_NUM
with this one-liner:
[ `pgrep $1` ] && return 1 || return 0
if you're looking for a partial match, i.e. program is named foobar and you want your $1
to be just foo you can add the -f switch
to pgrep:
[[ `pgrep -f $1` ]] && return 1 || return 0
Putting it all together your script could be reworked like this:
#!/bin/bash
check_process() {
echo "$ts: checking $1"
[ "$1" = "" ] && return 0
[ `pgrep -n $1` ] && return 1 || return 0
}
while [ 1 ]; do
# timestamp
ts=`date +%T`
echo "$ts: begin checking..."
check_process "dropbox"
[ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
sleep 5
done
Running it would look like this:
# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox
# SHELL #2
$ dropbox stop
Dropbox daemon stopped.
# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox
Hope this helps!
$('div#someDiv').css('height', '');
This helped me get to my answer. There are two php.ini
files located, in my case, for wamp. One is under the php folder and the other one is in the C:\wamp\bin\apache\Apachex.x.x\bin
folder. When connecting to SQL through sqlsrv_connect
function, we are referring to the php.ini
file in the apache
folder. Add the following (as per your version) to this file:
extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll
slight change in syntax from the accepted answer for Angular 5 and angular-cli 1.7.0
ng g service backendApi --module=app.module
I am a novice and I did it this way:
Create table Name1
(
F_Name varchar(20),
L_Name varchar(20),
Age INTEGER
)
Insert into Name1
Values
('Tom', 'Bombadil', 32),
('Danny', 'Fartman', 43),
('Stephine', 'Belchlord', 33),
('Corry', 'Smallpants', 95)
Go
Update Name1
Set F_Name = CONCAT(F_Name, ' ', L_Name)
Go
Alter Table Name1
Drop column L_Name
Go
Update Table_Name
Set F_Name
I know that this has been exhaustively answered, but I wanted to share my FUNCTION with everyone. It gives you the option to choose if you want your answer to be in days, hours, minutes, seconds, or milliseconds. You can modify it to fit your needs.
CREATE OR REPLACE FUNCTION Return_Elapsed_Time (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
FUNCTION Core (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
day_ VARCHAR2(7); /* This means this FUNCTION only supports up to 99 days */
hour_ VARCHAR2(9); /* This means this FUNCTION only supports up to 999 hours, which is over 41 days */
minute_ VARCHAR2(12); /* This means this FUNCTION only supports up to 9999 minutes, which is over 17 days */
second_ VARCHAR2(18); /* This means this FUNCTION only supports up to 999999 seconds, which is over 11 days */
msecond_ VARCHAR2(22); /* This means this FUNCTION only supports up to 999999999 milliseconds, which is over 11 days */
d1_ NUMBER;
h1_ NUMBER;
m1_ NUMBER;
s1_ NUMBER;
ms_ NUMBER;
/* If you choose 1, you only get seconds. If you choose 2, you get minutes and seconds etc. */
precision_ NUMBER; /* 0 => milliseconds; 1 => seconds; 2 => minutes; 3 => hours; 4 => days */
format_ VARCHAR2(2) := ', ';
return_ VARCHAR2(50);
BEGIN
IF (syntax_ IS NULL) THEN
precision_ := 0;
ELSE
IF (syntax_ = 0) THEN
precision_ := 0;
ELSIF (syntax_ = 1) THEN
precision_ := 1;
ELSIF (syntax_ = 2) THEN
precision_ := 2;
ELSIF (syntax_ = 3) THEN
precision_ := 3;
ELSIF (syntax_ = 4) THEN
precision_ := 4;
ELSE
precision_ := 0;
END IF;
END IF;
SELECT EXTRACT(DAY FROM (end_ - start_)) INTO d1_ FROM DUAL;
SELECT EXTRACT(HOUR FROM (end_ - start_)) INTO h1_ FROM DUAL;
SELECT EXTRACT(MINUTE FROM (end_ - start_)) INTO m1_ FROM DUAL;
SELECT EXTRACT(SECOND FROM (end_ - start_)) INTO s1_ FROM DUAL;
IF (precision_ = 4) THEN
IF (d1_ = 1) THEN
day_ := ' day';
ELSE
day_ := ' days';
END IF;
IF (h1_ = 1) THEN
hour_ := ' hour';
ELSE
hour_ := ' hours';
END IF;
IF (m1_ = 1) THEN
minute_ := ' minute';
ELSE
minute_ := ' minutes';
END IF;
IF (s1_ = 1) THEN
second_ := ' second';
ELSE
second_ := ' seconds';
END IF;
return_ := d1_ || day_ || format_ || h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
RETURN return_;
ELSIF (precision_ = 3) THEN
h1_ := (d1_ * 24) + h1_;
IF (h1_ = 1) THEN
hour_ := ' hour';
ELSE
hour_ := ' hours';
END IF;
IF (m1_ = 1) THEN
minute_ := ' minute';
ELSE
minute_ := ' minutes';
END IF;
IF (s1_ = 1) THEN
second_ := ' second';
ELSE
second_ := ' seconds';
END IF;
return_ := h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
RETURN return_;
ELSIF (precision_ = 2) THEN
m1_ := (((d1_ * 24) + h1_) * 60) + m1_;
IF (m1_ = 1) THEN
minute_ := ' minute';
ELSE
minute_ := ' minutes';
END IF;
IF (s1_ = 1) THEN
second_ := ' second';
ELSE
second_ := ' seconds';
END IF;
return_ := m1_ || minute_ || format_ || s1_ || second_;
RETURN return_;
ELSIF (precision_ = 1) THEN
s1_ := (((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_;
IF (s1_ = 1) THEN
second_ := ' second';
ELSE
second_ := ' seconds';
END IF;
return_ := s1_ || second_;
RETURN return_;
ELSE
ms_ := ((((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_) * 1000;
IF (ms_ = 1) THEN
msecond_ := ' millisecond';
ELSE
msecond_ := ' milliseconds';
END IF;
return_ := ms_ || msecond_;
RETURN return_;
END IF;
END Core;
BEGIN
RETURN(Core(start_, end_, syntax_));
END Return_Elapsed_Time;
For example, if I called this function right now (12.10.2018 11:17:00.00) using Return_Elapsed_Time(TO_TIMESTAMP('12.04.2017 12:00:00.00', 'DD.MM.YYYY HH24:MI:SS.FF'),SYSTIMESTAMP), it should return something like:
47344620000 milliseconds
Newer JDK distributions ship with JConsole and VisualVM. Both are fantastic tools for getting the dirty details from a running Java process. If you have to do this programmatically, investigate JMX.
This worked for me and was as easy as adding a gradle dependancy:
https://bintray.com/seesaa/maven/opencv#
https://github.com/seesaa/opencv-android
The one caveat being that I had to use a hardware debugging device as arm emulators were running too slow for me (as AVD Manager says they will), and, as described at the repo README, this version does not include x86 or x86_64 support.
It seems to build and the suggested test:
static {
OpenCVLoader.initDebug();
}
spits out a bunch of output that looks about right to me.
An approximation of what I was doing:
import module.submodule
class MyClass:
constant = submodule.constant
To which pylint said:
E: 4,15: Undefined variable 'submodule' (undefined-variable)
from module.submodule import CONSTANT
class MyClass:
constant = CONSTANT
Note: I also renamed by imported variable to have an uppercase name to reflect its constant nature.
preferred way, using MySQLi extension:
$mysqli = new mysqli(SERVER, DBUSER, DBPASS, DATABASE);
$result = $mysqli->query("SELECT id FROM mytable WHERE city = 'c7'");
if($result->num_rows == 0) {
// row not found, do stuff...
} else {
// do other stuff...
}
$mysqli->close();
deprecated:
$result = mysql_query("SELECT id FROM mytable WHERE city = 'c7'");
if(mysql_num_rows($result) == 0) {
// row not found, do stuff...
} else {
// do other stuff...
}
This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.
Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.
$param = isset($_GET['param']) ? $_GET['param'] : 'default';
There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:
$result = $x ?: 'default';
It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset
or a null coalescing operator which is introduced in PHP7:
$param = $_GET['param'] ?? 'default';
Nobody noticed the html attibute "accesskey" which is available since a while.
This is a no javascript way to keyboard shortcuts stuffs.
The accesskey attributes shortcuts on MDN
Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny bowser
let client = navigator.userAgent.toLowerCase(),_x000D_
isLinux = client.indexOf("linux") > -1,_x000D_
isWin = client.indexOf("windows") > -1,_x000D_
isMac = client.indexOf("apple") > -1,_x000D_
isFirefox = client.indexOf("firefox") > -1,_x000D_
isWebkit = client.indexOf("webkit") > -1,_x000D_
isOpera = client.indexOf("opera") > -1,_x000D_
input = document.getElementById('guestInput');_x000D_
_x000D_
if(isFirefox) {_x000D_
input.setAttribute("placeholder", "ALT+SHIFT+Z");_x000D_
} else if (isWin) {_x000D_
input.setAttribute("placeholder", "ALT+Z");_x000D_
} else if (isMac) {_x000D_
input.setAttribute("placeholder", "CTRL+ALT+Z");_x000D_
} else if (isOpera) {_x000D_
input.setAttribute("placeholder", "SHIFT+ESCAPE->Z");_x000D_
} else {'Point me to operate...'}
_x000D_
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>
_x000D_
I had the same problem: I love the resolve
object, but that only works for the content of ng-view. What if you have controllers (for top-level nav, let's say) that exist outside of ng-view and which need to be initialized with data before the routing even begins to happen? How do we avoid mucking around on the server-side just to make that work?
Use manual bootstrap and an angular constant. A naiive XHR gets you your data, and you bootstrap angular in its callback, which deals with your async issues. In the example below, you don't even need to create a global variable. The returned data exists only in angular scope as an injectable, and isn't even present inside of controllers, services, etc. unless you inject it. (Much as you would inject the output of your resolve
object into the controller for a routed view.) If you prefer to thereafter interact with that data as a service, you can create a service, inject the data, and nobody will ever be the wiser.
Example:
//First, we have to create the angular module, because all the other JS files are going to load while we're getting data and bootstrapping, and they need to be able to attach to it.
var MyApp = angular.module('MyApp', ['dependency1', 'dependency2']);
// Use angular's version of document.ready() just to make extra-sure DOM is fully
// loaded before you bootstrap. This is probably optional, given that the async
// data call will probably take significantly longer than DOM load. YMMV.
// Has the added virtue of keeping your XHR junk out of global scope.
angular.element(document).ready(function() {
//first, we create the callback that will fire after the data is down
function xhrCallback() {
var myData = this.responseText; // the XHR output
// here's where we attach a constant containing the API data to our app
// module. Don't forget to parse JSON, which `$http` normally does for you.
MyApp.constant('NavData', JSON.parse(myData));
// now, perform any other final configuration of your angular module.
MyApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/someroute', {configs})
.otherwise({redirectTo: '/someroute'});
}]);
// And last, bootstrap the app. Be sure to remove `ng-app` from your index.html.
angular.bootstrap(document, ['NYSP']);
};
//here, the basic mechanics of the XHR, which you can customize.
var oReq = new XMLHttpRequest();
oReq.onload = xhrCallback;
oReq.open("get", "/api/overview", true); // your specific API URL
oReq.send();
})
Now, your NavData
constant exists. Go ahead and inject it into a controller or service:
angular.module('MyApp')
.controller('NavCtrl', ['NavData', function (NavData) {
$scope.localObject = NavData; //now it's addressable in your templates
}]);
Of course, using a bare XHR object strips away a number of the niceties that $http
or JQuery would take care of for you, but this example works with no special dependencies, at least for a simple get
. If you want a little more power for your request, load up an external library to help you out. But I don't think it's possible to access angular's $http
or other tools in this context.
(SO related post)
a difference:
.cmd files are loaded into memory before being executed. .bat files execute a line, read the next line, execute that line...
you can come across this when you execute a script file and then edit it before it's done executing. bat files will be messed up by this, but cmd files won't.
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
a.append(random.randint(1,20))
print('Randomised list is: ',a)
Sometimes it is not eligible to set height to pixel values.
However, it is possible to show vertical scrollbar through setting height of div to 100%
and overflow
to auto
.
Let me show an example:
<div id="content" style="height: 100%; overflow: auto">
<p>some text</p>
<ul>
<li>text</li>
.....
<li>text</li>
</div>
string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";
I'm making a guess, but if you want an actual handshake to occur, you have to let android know of your certificate. If you want to just accept no matter what, then use this pseudo-code to get what you need with the Apache HTTP Client:
SchemeRegistry schemeRegistry = new SchemeRegistry ();
schemeRegistry.register (new Scheme ("http",
PlainSocketFactory.getSocketFactory (), 80));
schemeRegistry.register (new Scheme ("https",
new CustomSSLSocketFactory (), 443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager (
params, schemeRegistry);
return new DefaultHttpClient (cm, params);
CustomSSLSocketFactory:
public class CustomSSLSocketFactory extends org.apache.http.conn.ssl.SSLSocketFactory
{
private SSLSocketFactory FACTORY = HttpsURLConnection.getDefaultSSLSocketFactory ();
public CustomSSLSocketFactory ()
{
super(null);
try
{
SSLContext context = SSLContext.getInstance ("TLS");
TrustManager[] tm = new TrustManager[] { new FullX509TrustManager () };
context.init (null, tm, new SecureRandom ());
FACTORY = context.getSocketFactory ();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public Socket createSocket() throws IOException
{
return FACTORY.createSocket();
}
// TODO: add other methods like createSocket() and getDefaultCipherSuites().
// Hint: they all just make a call to member FACTORY
}
FullX509TrustManager is a class that implements javax.net.ssl.X509TrustManager, yet none of the methods actually perform any work, get a sample here.
Good Luck!
After some time I will just copy all array elements (excluding these unwanted) to new array
In regards to the "at the same time" definition of synchronous execution (which is sometimes confusing), here's a good way to understand it:
Synchronous Execution: All tasks within a block of code are all executed at the same time.
Asynchronous Execution: All tasks within a block of code are not all executed at the same time.
I. In your build.gradle add latest appcompat library, at the time 24.2.1
dependencies {
compile 'com.android.support:appcompat-v7:X.X.X'
// where X.X.X version
}
II. Make your activity extend android.support.v7.app.AppCompatActivity
and implement the DatePickerDialog.OnDateSetListener
interface.
public class MainActivity extends AppCompatActivity
implements DatePickerDialog.OnDateSetListener {
III. Create your DatePickerDialog
setting a context, the implementation of the listener and the start year, month and day of the date picker.
DatePickerDialog datePickerDialog = new DatePickerDialog(
context, MainActivity.this, startYear, starthMonth, startDay);
IV. Show your dialog on the click event listener of your button
((Button) findViewById(R.id.myButton))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
datePickerDialog.show();
}
});
Ok this is a few years later but with java 8 you can use Comparator.naturalOrder():
http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#naturalOrder--
From javadoc:
static <T extends Comparable<? super T>> Comparator<T> naturalOrder()
Returns a comparator that compares Comparable objects in natural order. The returned comparator is serializable and throws NullPointerException when comparing null.
What everyone here is missing is Java's guarantee of definite assignment for final member variables.
For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.
C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.
So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.
Try this,
x in mylist
is better and more readable than x in mylist[:]
and your len(x)
should be equal to 3
.
>>> mylist = [[1,2,3],[4,5,6,7],[8,9,10]]
>>> for x in mylist:
... if len(x)==3:
... print x
...
[1, 2, 3]
[8, 9, 10]
or if you need more pythonic use list-comprehensions
>>> [x for x in mylist if len(x)==3]
[[1, 2, 3], [8, 9, 10]]
>>>
If you don't need a plot per say, and you're simply interested in adding color to represent the values in a table format, you can use the style.background_gradient()
method of the pandas data frame. This method colorizes the HTML table that is displayed when viewing pandas data frames in e.g. the JupyterLab Notebook and the result is similar to using "conditional formatting" in spreadsheet software:
import numpy as np
import pandas as pd
index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
cols = ['A', 'B', 'C', 'D']
df = pd.DataFrame(abs(np.random.randn(5, 4)), index=index, columns=cols)
df.style.background_gradient(cmap='Blues')
For detailed usage, please see the more elaborate answer I provided on the same topic previously and the styling section of the pandas documentation.
I was having similar problem but I came out of the solution the problem was that you were using any thing in the dependency that correspond to same domain but with different versions make sure those all are same
For Laravel 3
Just a heads up on @giannis christofakis answer; for anyone using Laravel 3 replace
return Redirect::back()->withErrors(['msg', 'The Message']);
with:
return Redirect::back()->with_errors(['msg', 'The Message']);
Because like many have said here, references are not objects. they are simply aliases. True some compilers might implement them as pointers, but the standard does not force/specify that. And because references are not objects, you cannot point to them. Storing elements in an array means there is some kind of index address (i.e., pointing to elements at a certain index); and that is why you cannot have arrays of references, because you cannot point to them.
Use boost::reference_wrapper, or boost::tuple instead; or just pointers.
TRUE
and FALSE
are keywords, and should not be quoted as strings:
INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);
By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT
in MySQL), which translates into zero for any non-numeric string. Thus, you get 0
for both values in your table.
mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
| 0 | 0 | 12345 |
+------------------------+-------------------------+-------------------------+
INT
representation:mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
| 1 | 0 |
+------+-------+
Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id
with NULL
. The empty string may issue a warning.
This solution is based on schulwitz answer (encoding/decoding using OpenSSL), but it is for C++ (well, original question was about C, but there are already another C++ answers here) and it uses error checking (so it's safer to use):
#include <openssl/bio.h>
std::string base64_encode(const std::string &input)
{
BIO *p_bio_b64 = nullptr;
BIO *p_bio_mem = nullptr;
try
{
// make chain: p_bio_b64 <--> p_bio_mem
p_bio_b64 = BIO_new(BIO_f_base64());
if (!p_bio_b64) { throw std::runtime_error("BIO_new failed"); }
BIO_set_flags(p_bio_b64, BIO_FLAGS_BASE64_NO_NL); //No newlines every 64 characters or less
p_bio_mem = BIO_new(BIO_s_mem());
if (!p_bio_mem) { throw std::runtime_error("BIO_new failed"); }
BIO_push(p_bio_b64, p_bio_mem);
// write input to chain
// write sequence: input -->> p_bio_b64 -->> p_bio_mem
if (BIO_write(p_bio_b64, input.c_str(), input.size()) <= 0)
{ throw std::runtime_error("BIO_write failed"); }
if (BIO_flush(p_bio_b64) <= 0)
{ throw std::runtime_error("BIO_flush failed"); }
// get result
char *p_encoded_data = nullptr;
auto encoded_len = BIO_get_mem_data(p_bio_mem, &p_encoded_data);
if (!p_encoded_data) { throw std::runtime_error("BIO_get_mem_data failed"); }
std::string result(p_encoded_data, encoded_len);
// clean
BIO_free_all(p_bio_b64);
return result;
}
catch (...)
{
if (p_bio_b64) { BIO_free_all(p_bio_b64); }
throw;
}
}
std::string base64_decode(const std::string &input)
{
BIO *p_bio_mem = nullptr;
BIO *p_bio_b64 = nullptr;
try
{
// make chain: p_bio_b64 <--> p_bio_mem
p_bio_b64 = BIO_new(BIO_f_base64());
if (!p_bio_b64) { throw std::runtime_error("BIO_new failed"); }
BIO_set_flags(p_bio_b64, BIO_FLAGS_BASE64_NO_NL); //Don't require trailing newlines
p_bio_mem = BIO_new_mem_buf((void*)input.c_str(), input.length());
if (!p_bio_mem) { throw std::runtime_error("BIO_new failed"); }
BIO_push(p_bio_b64, p_bio_mem);
// read result from chain
// read sequence (reverse to write): buf <<-- p_bio_b64 <<-- p_bio_mem
std::vector<char> buf((input.size()*3/4)+1);
std::string result;
for (;;)
{
auto nread = BIO_read(p_bio_b64, buf.data(), buf.size());
if (nread < 0) { throw std::runtime_error("BIO_read failed"); }
if (nread == 0) { break; } // eof
result.append(buf.data(), nread);
}
// clean
BIO_free_all(p_bio_b64);
return result;
}
catch (...)
{
if (p_bio_b64) { BIO_free_all(p_bio_b64); }
throw;
}
}
Note that base64_decode returns empty string, if input is incorrect base64 sequence (openssl works in such way).
string strData = "This is much easier"
int intDelimiterIndx = strData.IndexOf("is");
int intDelimiterLength = "is".Length;
str1 = strData.Substring(0, intDelimiterIndx);
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength));
Simply add height: 100%;
onto the #B2
styling. min-height
shouldn't be necessary.
I use http://gregpike.net/demos/bootstrap-file-input/demo.html:
$('input[type=file]').bootstrapFileInput();
or
$('.file-inputs').bootstrapFileInput();
Application Private Data files are stored within <internal_storage>/data/data/<package>
Files being stored in the internal storage can be accessed with openFileOutput() and openFileInput()
When those files are created as MODE_PRIVATE it is not possible to see/access them within another application such as a FileManager.
The Most simple code you can write:
persons.stream().map(x-> x.getName()).distinct().collect(Collectors.toList());
You can iterate over this.form.errors property.
To get rid of the bad looking datepicker you need to add jquery-ui css
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
lace to store your loaded class definition and metadata. If a large code-base project is loaded, the insufficient Perm Gen size will cause the popular Java.Lang.OutOfMemoryError: PermGen.
This is generally referred to as an Indeterminate Progress Bar or Indeterminate Progress Dialog.
Combine this with a Thread and a Handler to get exactly what you want. There are a number of examples on how to do this via Google or right here on SO. I would highly recommend spending the time to learn how to use this combination of classes to perform a task like this. It is incredibly useful across many types of applications and will give you a great insight into how Threads and Handlers can work together.
I'll get you started on how this works:
The loading event starts the dialog:
//maybe in onCreate
showDialog(MY_LOADING_DIALOG);
fooThread = new FooThread(handler);
fooThread.start();
Now the thread does the work:
private class FooThread extends Thread {
Handler mHandler;
FooThread(Handler h) {
mHandler = h;
}
public void run() {
//Do all my work here....you might need a loop for this
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("state", 1);
msg.setData(b);
mHandler.sendMessage(msg);
}
}
Finally get the state back from the thread when it is complete:
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
int state = msg.getData().getInt("state");
if (state == 1){
dismissDialog(MY_LOADING_DIALOG);
removeDialog(MY_LOADING_DIALOG);
}
}
};
As a string extension:
public static string RemoveIntegers(this string input)
{
return Regex.Replace(input, @"[\d-]", string.Empty);
}
Usage:
"My text 1232".RemoveIntegers(); // RETURNS "My text "
Try like below... it will help you...
Some time in Window Form Focus()
doesn't work correctly. So better you can use Select()
to focus the textbox.
txtbox.Select(); // to Set Focus
txtbox.Select(txtbox.Text.Length, 0); //to set cursor at the end of textbox
You can do it code behind.
Set visible= false
for columns after data binding .
After that you can again do visibility "true" in row_selection function from grid view .It will work!!
If no other process is using the port 8080, Eventhough eclipse shows the port 8080 is used while starting the server in eclipse, first you have to stop the server by hitting the stop button in "Configure Tomcat"(which you can find in your start menu under tomcat folder), then try to start the server in eclipse then it will be started.
If any other process is using the port 8080 and as well as you no need to disturb it. then you can change the port.
This prints 10 lines of trailing context after matching lines
grep -i "my_regex" -A 10
If you need to print 10 lines of leading context before matching lines,
grep -i "my_regex" -B 10
And if you need to print 10 lines of leading and trailing output context.
grep -i "my_regex" -C 10
Example
user@box:~$ cat out
line 1
line 2
line 3
line 4
line 5 my_regex
line 6
line 7
line 8
line 9
user@box:~$
Normal grep
user@box:~$ grep my_regex out
line 5 my_regex
user@box:~$
Grep exact matching lines and 2 lines after
user@box:~$ grep -A 2 my_regex out
line 5 my_regex
line 6
line 7
user@box:~$
Grep exact matching lines and 2 lines before
user@box:~$ grep -B 2 my_regex out
line 3
line 4
line 5 my_regex
user@box:~$
Grep exact matching lines and 2 lines before and after
user@box:~$ grep -C 2 my_regex out
line 3
line 4
line 5 my_regex
line 6
line 7
user@box:~$
Reference: manpage grep
-A num
--after-context=num
Print num lines of trailing context after matching lines.
-B num
--before-context=num
Print num lines of leading context before matching lines.
-C num
-num
--context=num
Print num lines of leading and trailing output context.
To print to any printer on the network you can send a PJL/PCL print job directly to a network printer on port 9100.
Please have a look at the below link that should give a good start:
http://frank.zinepal.com/printing-directly-to-a-network-printer
Also, If there is a way to call Windows cmd you can use FTP put to print your page on 9100. Below link should give you details, I have used this method for HP printers but I believe it will work for other printers.
http://h20000.www2.hp.com/bizsupport/TechSupport/Document.jsp?objectID=bpj06165