Removing Null elements from a list in single line :
x=x[-(which(sapply(x,is.null),arr.ind=TRUE))]
Cheers
The syntax to statically initialize an array uses curly braces, like this:
int array[10] = { 0 };
This will zero-initialize the array.
For multi-dimensional arrays, you need nested curly braces, like this:
int cipher[Array_size][Array_size]= { { 0 } };
Note that Array_size
must be a compile-time constant for this to work. If Array_size
is not known at compile-time, you must use dynamic initialization. (Preferably, an std::vector
).
you should be using the .Value of the datetime parameter. All Nullable structs have a value property which returns the concrete type of the object. but you must check to see if it is null beforehand otherwise you will get a runtime error.
i.e:
datetime.Value
but check to see if it has a value first!
if (datetime.HasValue)
{
// work with datetime.Value
}
For Meteor or Cordova users,
It can be caused by the Java version you use, for meteor and cordova stick with version 8 for now.
1- Check available Java versions /usr/libexec/java_home -V
and look for the path name for Java version 8
2- Set the path for Java version 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home
3- Check if it is done
echo $JAVA_HOME
Go on and contiune coding.
Why not use index or rindex?
array = %w( a b c d e)
# get FIRST index of element searched
puts array.index('a')
# get LAST index of element searched
puts array.rindex('a')
index: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-index
rindex: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-rindex
You can use an svn changelist to keep track of a set of files that you want to commit together.
The linked page goes into lots of details, but here's an executive summary example:
$ svn changelist my-changelist mydir/dir1/file1.c mydir/dir2/myfile1.h
$ svn changelist my-changelist mydir/dir3/myfile3.c etc.
... (add all the files you want to commit together at your own rate)
$ svn commit -m"log msg" --changelist my-changelist
>>> some_string='A,B,C,D,E'
>>> new_tuple= tuple(some_string.split(','))
>>> new_tuple
('A', 'B', 'C', 'D', 'E')
This is just torazaburo's answer, updated to use a MouseEvent object.
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
el.dispatchEvent(ev);
}
Connection timeouts (assuming a local network and several client machines) typically result from
a) some kind of firewall on the way that simply eats the packets without telling the sender things like "No Route to host"
b) packet loss due to wrong network configuration or line overload
c) too many requests overloading the server
d) a small number of simultaneously available threads/processes on the server which leads to all of them being taken. This happens especially with requests that take a long time to run and may combine with c).
Hope this helps.
I surveyed a few Excel modules for Python, and found openpyxl to be the best.
The free book Automate the Boring Stuff with Python has a chapter on openpyxl with more details or you can check the Read the Docs site. You won't need Office or Excel installed in order to use openpyxl.
Your program would look something like this:
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
stimulusTimes = [1, 2, 3]
reactionTimes = [2.3, 5.1, 7.0]
for i in range(len(stimulusTimes)):
sheet['A' + str(i + 6)].value = stimulusTimes[i]
sheet['B' + str(i + 6)].value = reactionTimes[i]
wb.save('example.xlsx')
I know this is an old question, but it worries me that there are no properly correct answers here. Most answers just talk about iterating through all the documents and saving each of them individually, which is a BAD idea if you have more than a few documents, and the process gets repeated for even one in many requests.
MongoDB specifically has a batchInsert()
call for inserting multiple documents, and this should be used from the native mongodb driver. Mongoose is built on this driver, and it doesn't have support for batch inserts. It probably makes sense as it is supposed to be a Object document modelling tool for MongoDB.
Solution: Mongoose comes with the native MongoDB driver. You can use that driver by requiring it require('mongoose/node_modules/mongodb')
(not too sure about this, but you can always install the mongodb npm again if it doesn't work, but I think it should) and then do a proper batchInsert
This happened to me, and once I removed this: enctype="multipart/form-data" It started working without the warning
There is a module datetime_truncate which handlers this for you. It just calls datetime.replace.
Shift-tab does that in Flex Builder (Based on Eclipse) - SO it hopefully should work in regular eclipse :)
https://www.postgresql.org/docs/8.4/functions-formatting.html
SELECT to_char(date_field, 'DD/MM/YYYY')
FROM table
Like you said remote_repo_url
is indeed the IP of the server, and yes it needs to be added on each PC, but it's easier to understand if you create the server first then ask each to clone it.
There's several ways to connect to the server, you can use ssh, http, or even a network drive, each has it's pros and cons. You can refer to the documentation about protocols and how to connect to the server
You can check the rest of chapter 4 for more detailed information, as it's talking about how to set up your own server
on the p element, add 3 styling rules.
.myCenteredPElement{
margin-left: auto;
margin-right: auto;
text-align: center;
}
From GIT documentation: Git Docs
Below gives the full information. In short, simple
will only push the current working branch
and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0
Whereas matching
will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.
In my personal usage, I generally use a different option: current
which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple
push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.
current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.
upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).
simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.
When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.
This mode will become the default in Git 2.0.
matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).
To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.
This is currently the default, but Git 2.0 will change the default to simple.
Passing structs to functions by reference: simply :)
#define maxn 1000
struct solotion
{
int sol[maxn];
int arry_h[maxn];
int cat[maxn];
int scor[maxn];
};
void inser(solotion &come){
come.sol[0]=2;
}
void initial(solotion &come){
for(int i=0;i<maxn;i++)
come.sol[i]=0;
}
int main()
{
solotion sol1;
inser(sol1);
solotion sol2;
initial(sol2);
}
You can do that in some methods:
One is the type
command: type filename
Another is the more
command: more filename
With more
you can also do that: type filename | more
The last option is using a for
for /f "usebackq delims=" %%A in (filename) do (echo.%%A)
This will go for each line and display it's content. This is an equivalent of the type
command, but it's another method of reading the content.
If you are asking what to use, use the more
command as it will make a pause.
You'd need to use JavaScript to accomplish this, I think.
jQuery:
$(function(){
$("#innerContainer").hover(
function(){
$("#innerContainer").css('border-color','#FFF');
$("#outerContainer").css('border-color','#FFF');
},
function(){
$("#innerContainer").css('border-color','#000');
$("#outerContainer").css('border-color','#000');
}
);
});
Adjust the values and element id's accordingly :)
Update based on latest Android documentation (March 2017):
When you get this type of error:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:374)
at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
the issue could be one of the following:
The solution is to teach HttpsURLConnection
to trust a specific set of CAs. How? Please check https://developer.android.com/training/articles/security-ssl.html#CommonProblems
Others who are using AsyncHTTPClient
from com.loopj.android:android-async-http
library, please check Setup AsyncHttpClient to use HTTPS.
INSERT INTO `test`.`product` ( `p1`, `p2`, `p3`)
SELECT sum(p1), sum(p2), sum(p3)
FROM `test`.`product`;
I think converting the var to a string decreases the performance, at least this test performed in the latest browsers shows so.
So if you care about performance, I would, I'd use this:
typeof str === "string" || str instanceof String
for checking if the variable is a string (even if you use var str = new String("foo")
, str instanceof String
would return true).
As for checking if it's a number I would go for the native: isNaN
; function.
There are some clients (in Python, Ruby, etc) which do exactly that. For my taste, it isn't sustainable to install a runtime (e.g. Python) on my registry server, just to housekeep my registry!
So deckschrubber
is my solution:
go get github.com/fraunhoferfokus/deckschrubber
$GOPATH/bin/deckschrubber
images older than a given age are automatically deleted. Age can be specified using -year
, -month
, -day
, or a combination of them:
$GOPATH/bin/deckschrubber -month 2 -day 13 -registry http://registry:5000
UPDATE: here's a short introduction on deckschrubber.
Mathematicians have their own little funny ways, so instead of saying "then we call function f
passing it x
as a parameter" as we programmers would say, they talk about "applying function f
to its argument x
".
In mathematics and computer science, Apply is a function that applies functions to arguments.
Wikipedia
apply
serves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes an Int
parameter and returns an Int
will have OO type of Function1[Int,Int]
.
// define a function in scala
(x:Int) => x + 1
// assign an object representing the function to a variable
val f = (x:Int) => x + 1
Since everything is an object in Scala f
can now be treated as a reference to Function1[Int,Int]
object. For example, we can call toString
method inherited from Any
, that would have been impossible for a pure function, because functions don't have methods:
f.toString
Or we could define another Function1[Int,Int]
object by calling compose
method on f
and chaining two different functions together:
val f2 = f.compose((x:Int) => x - 1)
Now if we want to actually execute the function, or as mathematician say "apply a function to its arguments" we would call the apply
method on the Function1[Int,Int]
object:
f2.apply(2)
Writing f.apply(args)
every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such as f(args)
. That's where Scala compiler steps in and whenever we have a reference f
to a function object and write f (args)
to apply arguments to the represented function the compiler silently expands f (args)
to the object method call f.apply (args)
.
Every function in Scala can be treated as an object and it works the other way too - every object can be treated as a function, provided it has the apply
method. Such objects can be used in the function notation:
// we will be able to use this object as a function, as well as an object
object Foo {
var y = 5
def apply (x: Int) = x + y
}
Foo (1) // using Foo object in function notation
There are many usage cases when we would want to treat an object as a function. The most common scenario is a factory pattern. Instead of adding clutter to the code using a factory method we can apply
object to a set of arguments to create a new instance of an associated class:
List(1,2,3) // same as List.apply(1,2,3) but less clutter, functional notation
// the way the factory method invocation would have looked
// in other languages with OO notation - needless clutter
List.instanceOf(1,2,3)
So apply
method is just a handy way of closing the gap between functions and objects in Scala.
For showing a particular trigger in a particular schema you can try the following:
select * from information_schema.triggers where
information_schema.triggers.trigger_name like '%trigger_name%' and
information_schema.triggers.trigger_schema like '%data_base_name%'
I think you need some sort of regular expression matching (the following code is in Python 3):
import string
import re
import nltk
s = "I can't do this now, because I'm so tired. Please give me some time."
l = nltk.word_tokenize(s)
ll = [x for x in l if not re.fullmatch('[' + string.punctuation + ']+', x)]
print(l)
print(ll)
Output:
['I', 'ca', "n't", 'do', 'this', 'now', ',', 'because', 'I', "'m", 'so', 'tired', '.', 'Please', 'give', 'me', 'some', 'time', '.']
['I', 'ca', "n't", 'do', 'this', 'now', 'because', 'I', "'m", 'so', 'tired', 'Please', 'give', 'me', 'some', 'time']
Should work well in most cases since it removes punctuation while preserving tokens like "n't", which can't be obtained from regex tokenizers such as wordpunct_tokenize
.
Making a start.bat was the only thing that worked for me.
open a text document and enter. java -jar whatever yours is called .jar
save as start.bat in the same folder as the .jar file you want to execute. and then run the. bat
Here is the code to set up a MediaPlayer
to play off of the SD card:
String PATH_TO_FILE = "/sdcard/music.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare();
mediaPlayer.start()
You can see the full example here. Let me know if you have any problems.
If you don't want a separate CSS file, you can use inline CSS:
<h1>This text should be bold, <span style="font-weight:normal">but this text should not</span></h1>
However, as Madara's comment suggests, you might want to consider putting the unbolded part in a different header, depending on the use case involved.
I've more simpler way to understand the time complexity he most common metric for calculating time complexity is Big O notation. This removes all constant factors so that the running time can be estimated in relation to N as N approaches infinity. In general you can think of it like this:
statement;
Is constant. The running time of the statement will not change in relation to N
for ( i = 0; i < N; i++ )
statement;
Is linear. The running time of the loop is directly proportional to N. When N doubles, so does the running time.
for ( i = 0; i < N; i++ )
{
for ( j = 0; j < N; j++ )
statement;
}
Is quadratic. The running time of the two loops is proportional to the square of N. When N doubles, the running time increases by N * N.
while ( low <= high )
{
mid = ( low + high ) / 2;
if ( target < list[mid] )
high = mid - 1;
else if ( target > list[mid] )
low = mid + 1;
else break;
}
Is logarithmic. The running time of the algorithm is proportional to the number of times N can be divided by 2. This is because the algorithm divides the working area in half with each iteration.
void quicksort ( int list[], int left, int right )
{
int pivot = partition ( list, left, right );
quicksort ( list, left, pivot - 1 );
quicksort ( list, pivot + 1, right );
}
Is N * log ( N ). The running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm is a combination of linear and logarithmic.
In general, doing something with every item in one dimension is linear, doing something with every item in two dimensions is quadratic, and dividing the working area in half is logarithmic. There are other Big O measures such as cubic, exponential, and square root, but they're not nearly as common. Big O notation is described as O ( ) where is the measure. The quicksort algorithm would be described as O ( N * log ( N ) ).
Note: None of this has taken into account best, average, and worst case measures. Each would have its own Big O notation. Also note that this is a VERY simplistic explanation. Big O is the most common, but it's also more complex that I've shown. There are also other notations such as big omega, little o, and big theta. You probably won't encounter them outside of an algorithm analysis course.
You can just use the one-liner
echo colorscheme koehler >> ~/.vimrc
and replace koehler
with any other available colorscheme. Imho, all of them are better than default.
As gratitude to the timely help I got from here - a minor update to above.
$query = "UPDATE `db`.`table` SET `fieldname`= str_to_date( fieldname, '%d/%m/%Y')";
You need to move type parameter to the method level to indicate that you have a generic method rather than generic class:
public class ArrayUtils {
public static <T> E[] appendToArray(E[] array, E item) {
E[] result = (E[])new Object[array.length+1];
result[array.length] = item;
return result;
}
}
There is now an XML alternative:
<ImageView
android:id="@+id/example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/example"
android:alpha="0.7" />
It is: android:alpha="0.7"
With a value from 0 (transparent) to 1 (opaque).
To check if a Windows service named MySuperServiceVersion1
exists, even when you might not be sure of its exact name, you could employ a wildcard, using a substring like so:
if (Get-Service -Name "*SuperService*" -ErrorAction SilentlyContinue)
{
# do something
}
Edit: @WickyNilliams has noted that setting display: block on a table body will strip the table of semantics and thus is not a good solution due to accessibility issues.
I had good success with the solution proposed by @Serge Stroobandt, but I encountered the problem @Shevy had with the cells then not filling the full width of the table. I was able to fix this by adding some styles to the tbody
.
table {
display: block;
overflow-x: auto;
white-space: nowrap;
}
table tbody {
display: table;
width: 100%;
}
This worked for me in Firefox, Chrome, and Safari on Mac.
This might be helpful. You have to just trigger an event.
$("#DropDownID").trigger("liszt:updated");
Where "DropDownID" is ID of <select>
.
More info here: http://harvesthq.github.com/chosen/
I can' t comment yet but, just a hint: use try/catch clauses to avoid breaking the pipeline (if you are sure the file exists, disregard)
pipeline {
agent any
stages {
stage("foo") {
steps {
script {
try {
env.FILENAME = readFile 'output.txt'
echo "${env.FILENAME}"
}
catch(Exception e) {
//do something, e.g. echo 'File not found'
}
}
}
}
Another hint (this was commented by @hao, and think is worth to share): you may want to trim like this readFile('output.txt').trim()
I have done it accessing the controls inside the cell control. Find in all control collections.
ControlCollection cc = (ControlCollection)e.Row.Controls[1].Controls;
Label lbCod = (Label)cc[1];
For me
Adding this line
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
Before this line.
<script id="microloader" type="text/javascript" src=".sencha/app/microloader/development.js"></script>
worked
The > null does not work in the quotes. It sees the > null as the batch filename.
The robocopy no output worked!!!
Here is the new batch file:
robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\EnvBackup c:\offsite_backup\EnvBackup
robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\shares c:\offsite_backup\shares
robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\Quickbooks_Backup c:\offsite_backup\Quickbooks_Backup
from this page:
I found this info:
The mod_fastcgi process manager isn't particularly patient though (there's room for improvement here) and since it has to shutdown too, sends a SIGTERM to all of the FastCGI applications it is responsible for. Apache will restart the process manager and it will restart its managed applications (as if the server was just started). SIGTERM is, well, SIGTERM - your application should exit quickly.
What this implies to me is that if Database I/O, or some other part of the CGI script, fails to respond in a timely fashion (ie getting slower with data-volume growth), that mod_fastcgi is killing the script......is that how other people interpret these docs or what am I missing..
dynamic data = List<x> val;
List<y> val2 = ((IEnumerable)data).Cast<y>().ToList();
I have had a similar scenario where I needed to set the focus on a text box within a panel when the panel was shown. The panel was loaded on application startup, so I couldn't set the focus in the constructor. As the panel wasn't being loaded or being given focus on show, this meant that I had no event to fire the focus request from.
To solve this, I added a global method to my main that called a method in the panel that invoked requestFocusInWindow()
on the text area. I put the call to the global method in the button that showed the panel, after the call to show. This meant that the panel would be shown and then the text area assigned the focus after showing the panel. Hope that makes sense and helps!
Also, you can edit most of the auto-generated code by right clicking on the object in design view and selecting customize code, however I don't think that it allows you to edit panels.
make iframe with align="middle" and put it in paragraph with style="text-aling:center":
<p style="text-align:center;">
<iframe width="420" height="315" align="middle" src="https://www.youtube.com/embed/YOURVIDEO">
</iframe>
</p>
Try:
alert(arguments.callee.toString());
In Xcode 7 - 13,
when you change storyboard IDs and you get errors like this,
just CLEAN your project (CMD+SHIFT+K)
To concatenate multiple strings into a single string, separated by another character, there are a couple of ways.
The nicest I have seen is using the join
method on an array:
fn main() {
let a = "Hello";
let b = "world";
let result = [a, b].join("\n");
print!("{}", result);
}
Depending on your use case you might also prefer more control:
fn main() {
let a = "Hello";
let b = "world";
let result = format!("{}\n{}", a, b);
print!("{}", result);
}
There are some more manual ways I have seen, some avoiding one or two allocations here and there. For readability purposes I find the above two to be sufficient.
/C
Carries out the command specified by the string and then terminates.
You can get all the cmd command line switches by typing cmd /?
.
I had similar issue Cannot resolve com.google.android.gms.common.
I followed setup guide http://developer.android.com/google/play-services/setup.html and it works!
Summary:
compile 'com.google.android.gms:play-services:4.0.30'
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...
for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}
Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.
If you are using angular ui-router this will be the best solution.
$scope.myLoadingFunction = function() {
$state.reload();
};
Sometimes you can play with padding and margin top, add line-height, etc.
See fiddle.
Style and text forked from @aspirinemaga
.parent
{
width:300px;
line-height:30px;
border:1px solid red;
padding-top:20px;
}
select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()
or using >=
and <=
:
select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()
your <%= //map.size() %>
doesnt simply work because it should have been
<% //= map.size() %>
I use the requests library. It seems to be more robust.
from PIL import Image
import requests
from StringIO import StringIO
response = requests.get(url)
img = Image.open(StringIO(response.content))
You need to set the text after the replace call:
$('.element span').each(function() {_x000D_
console.log($(this).text());_x000D_
var text = $(this).text().replace('N/A, ', '');_x000D_
$(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
<span>N/A, Category</span>_x000D_
</div>
_x000D_
Here's another cool way you can do it (hat tip @Felix King):
$(".element span").text(function(index, text) {
return text.replace("N/A, ", "");
});
You can disable scrolling by freezing your RecyclerView.
To freeze:
recyclerView.setLayoutFrozen(true)
To unfreeze: recyclerView.setLayoutFrozen(false)
In Kotlin
evLoginPassword.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
doTheLoginWork()
}
true
}
Partial Xml Code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<EditText
android:id="@+id/evLoginUserEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/email"
android:inputType="textEmailAddress"
android:textColor="@color/black_54_percent" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<EditText
android:id="@+id/evLoginPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/password"
android:inputType="textPassword"
android:imeOptions="actionDone"
android:textColor="@color/black_54_percent" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
You can use select ... into ...
to create and populate a temp table and then query the temp table to return the result.
select *
into #TempTable
from YourTable
select *
from #TempTable
To create a Windows Service from an executable, you can use sc.exe
:
sc.exe create <new_service_name> binPath= "<path_to_the_service_executable>"
You must have quotation marks around the actual exe
path, and a space after the binPath=
.
More information on the sc
command can be found in Microsoft KB251192.
Note that it will not work for just any executable: the executable must be a Windows Service (i.e. implement ServiceMain). When registering a non-service executable as a service, you'll get the following error upon trying to start the service:
Error 1053: The service did not respond to the start or control request in a timely fashion.
There are tools that can create a Windows Service from arbitrary, non-service executables, see the other answers for examples of such tools.
Both getSingleResult()
and getOneOrNullResult()
will throw an exception if there is more than one result.
To fix this problem you could add setMaxResults(1)
to your query builder.
$firstSubscriber = $entity->createQueryBuilder()->select('sub')
->from("\Application\Entity\Subscriber", 'sub')
->where('sub.subscribe=:isSubscribe')
->setParameter('isSubscribe', 1)
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
You could also use CEILING
which rounds up to an integer or desired multiple of significance
ie
=CEILING(A1,10)
rounds up to a multiple of 10
12340.0001
will become 12350
You suggested "Catching any unexpected errors and return some error code signaling "unexpected situation" " but couldn't find an appropriate error code.
Guess what: That's what 5xx is there for.
Also beware that "setup" (i.e. localhost/phpmyadmin/setup) has an error in the way it handles the "no password" option. While it creates a line that says:
$cfg['Servers'][$i]['nopassword'] = true;
the actual name of the parameter should be as shown here:
$cfg['Servers'][$i]['AllowNoPassword'] = true;
This "setup" error exists as of today, Oct 20, 2015.
You can set the value in the HTML and then init datepicker to start/highlight the actual date
<input name="datefrom" type="text" class="datepicker" value="20-1-2011">
<input name="dateto" type="text" class="datepicker" value="01-01-2012">
<input name="dateto2" type="text" class="datepicker" >
$(".datepicker").each(function() {
$(this).datepicker('setDate', $(this).val());
});
The above even works with danish date formats
In XML Serializing, you can use the [XmlIgnore] attribute (System.Xml.Serialization.XmlIgnoreAttribute) to ignore a property when serializing a class.
This may be of use to you (Or it just may be of use to anyone who found this question when attempting to find out how to ignore a property when Serializing in XML, as I was).
//Convert a float to integer_x000D_
_x000D_
Math.floor(5.95)_x000D_
//5_x000D_
_x000D_
Math.ceil(5.95)_x000D_
//6_x000D_
_x000D_
Math.round(5.4)_x000D_
//5_x000D_
_x000D_
Math.round(5.5)_x000D_
//6_x000D_
_x000D_
Math.trunc(5.5)_x000D_
//5_x000D_
_x000D_
//Quick Ways_x000D_
console.log(5.95| 0)_x000D_
console.log(~~5.95) _x000D_
console.log(5.95 >> 0)_x000D_
//5
_x000D_
Take a look into NSColorWell class reference.
"Hello! world!".TrimEnd('!');
EDIT:
What I've noticed in this type of questions that quite everyone suggest to remove the last char of given string. But this does not fulfill the definition of Trim method.
Trim - Removes all occurrences of white space characters from the beginning and end of this instance.
Under this definition removing only last character from string is bad solution.
So if we want to "Trim last character from string" we should do something like this
Example as extension method:
public static class MyExtensions
{
public static string TrimLastCharacter(this String str)
{
if(String.IsNullOrEmpty(str)){
return str;
} else {
return str.TrimEnd(str[str.Length - 1]);
}
}
}
Note if you want to remove all characters of the same value i.e(!!!!)the method above removes all existences of '!' from the end of the string, but if you want to remove only the last character you should use this :
else { return str.Remove(str.Length - 1); }
When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:
import pygame
def text_to_screen(screen, text, x, y, size = 50,
color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
try:
text = str(text)
font = pygame.font.Font(font_type, size)
text = font.render(text, True, color)
screen.blit(text, (x, y))
except Exception, e:
print 'Font Error, saw it coming'
raise e
Then when that has been imported when I want to display text taht updates E.G score I do:
Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)
If it is just normal text that isn't being updated:
Funk.text_to_screen(screen, 'Text', xpos, ypos)
You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)
strScriptFullname = WScript.ScriptFullName
strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\"))
Inkscape is a vector drawing program that exports PNG images. So, you end up editing SVG documents and exporting them to PNGs. Inkscape is good if you're starting from scratch, but wouldn't be ideal if you just want to edit existing PNGs.
Note--Inkscape is open source and available for free on multiple platforms.
You can do it in Python 2.7+ with python-dateutil
(which is insalled on Mac by default):
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> datetime.now(tzlocal()).isoformat()
'2016-10-22T12:45:45.353489-03:00'
Or you if you want to convert from an existed stored string:
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> from dateutil.parser import parse
>>> parse("2016-10-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-10-21T16:33:27.696173-03:00' <-- Atlantic Daylight Time (ADT)
>>> parse("2016-01-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-01-21T16:33:27.696173-04:00' <-- Atlantic Standard Time (AST)
With RxJS 5.5+, the catch
operator is now deprecated. You should now use the catchError
operator in conjunction with pipe
.
RxJS v5.5.2 is the default dependency version for Angular 5.
For each RxJS Operator you import, including catchError
you should now import from 'rxjs/operators' and use the pipe operator.
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...
export class ExampleClass {
constructor(private http: HttpClient) {
this.http.request(method, url, options).pipe(
catchError((err: HttpErrorResponse) => {
...
}
)
}
...
}
Notice here that catch
is replaced with catchError
and the pipe
operator is used to compose the operators in similar manner to what you're used to with dot-chaining.
See the rxjs documentation on pipable (previously known as lettable) operators for more info.
Another alternative:
myPlanetsList.Select(i => i.Moons).Sum();
NFC enabled phones can ONLY read NFC and passive high frequency RFID (HF-RFID). These must be read at an extremely close range, typically a few centimeters. For longer range or any other type of RFID/active RFID, you must use an external reader for handling them with mobile devices.
You can get some decent readers from a lot of manufacturers by simply searching on google. There are a lot of plug in ones for all device types.
I deal a lot with HID readers capable of close proximity scans of HID enabled ID cards as well as NFC from smart phones and smart cards. I use SerialIO badge readers that I load a decryption profile onto that allows our secure company cards to be read and utilized by an application I built. They are great for large scale reliable bluetooth scanning. Because they are bluetooth, they work for PC/Android/iOS/Linux. The only problem is, HID readers are very expensive and are meant for enterprise use. Ours cost about $400 each, but again, they read HID, SmartCards, NFC, and RFID.
If this is a personal project, I suggest just using the phone and purchasing some HF-RFID tags. The tag manufacturer should have an SDK for you to use to connect to and manage the tags. You can also just use androids NFC docs to get started https://developer.android.com/guide/topics/connectivity/nfc/. Most android phones from the last 8 years have NFC, only iPhone 6 and newer apple phones have NFC, but only iOS 11 and newer will work for what you want to do.
What is happening is that stock_list.toArray()
is creating an Object[]
rather than a String[]
and hence the typecast is failing1.
The correct code would be:
String [] stockArr = stockList.toArray(new String[stockList.size()]);
or even
String [] stockArr = stockList.toArray(new String[0]);
For more details, refer to the javadocs for the two overloads of List.toArray
.
The latter version uses the zero-length array to determine the type of the result array. (Surprisingly, it is faster to do this than to preallocate ... at least, for recent Java releases. See https://stackoverflow.com/a/4042464/139985 for details.)
From a technical perspective, the reason for this API behavior / design is that an implementation of the List<T>.toArray()
method has no information of what the <T>
is at runtime. All it knows is that the raw element type is Object
. By contrast, in the other case, the array parameter gives the base type of the array. (If the supplied array is big enough to hold the list elements, it is used. Otherwise a new array of the same type and a larger size is allocated and returned as the result.)
1 - In Java, an Object[]
is not assignment compatible with a String[]
. If it was, then you could do this:
Object[] objects = new Object[]{new Cat("fluffy")};
Dog[] dogs = (Dog[]) objects;
Dog d = dogs[0]; // Huh???
This is clearly nonsense, and that is why array types are not generally assignment compatible.
Quite a while later, and thanks to @arne, I created this similar small function to handle where the input should be disabled AND hidden, or enabled AND shown:
function toggleInputState(el, on) {
// 'on' = true(visible) or false(hidden)
// If a field is to be shown, enable it; if hidden, disable it.
// Disabling will prevent the field's value from being submitted
$(el).prop('disabled', !on).toggle(on);
}
Then a jQuery object (such as $('input[name="something"]') ) is simply switched using:
toggleInputState(myElement, myBoolean)
You should retrieve RecyclerView
in a Fragment
after inflating core View using that View. Perhaps it can't find your recycler because it's not part of Activity
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
final FragmentActivity c = getActivity();
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
recyclerView.setLayoutManager(layoutManager);
new Thread(new Runnable() {
@Override
public void run() {
final RecyclerAdapter adapter = new RecyclerAdapter(c);
c.runOnUiThread(new Runnable() {
@Override
public void run() {
recyclerView.setAdapter(adapter);
}
});
}
}).start();
return view;
}
If you are looking in linux..
npm update will not work mostly am not sure reason but following steps will help you to resolve issue...
Terminal process to upgrade node 4.x to 6.x.
$ node -v
v4.x
Check node path
$ which node
/usr/bin/node
Download latest(6.x) node files from [Download][1]
[1]: https://nodejs.org/dist/v6.9.2/node-v6.9.2-linux-x64.tar.xz and unzip files keep in /opt/node-v6.9.2-linux-x64/.
Now unlink current node and link with latest as following
$ unlink /usr/bin/node
$ ln -s /opt/node-v6.9.2-linux-x64/bin/node node
$ node -v
$ v6.9.2
The transparent parts mostly have RGBA value (0,0,0,0). Since the JPG has no transparency, the jpeg value is set to (0,0,0), which is black.
Around the circular icon, there are pixels with nonzero RGB values where A = 0. So they look transparent in the PNG, but funny-colored in the JPG.
You can set all pixels where A == 0 to have R = G = B = 255 using numpy like this:
import Image
import numpy as np
FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
x = np.array(img)
r, g, b, a = np.rollaxis(x, axis = -1)
r[a == 0] = 255
g[a == 0] = 255
b[a == 0] = 255
x = np.dstack([r, g, b, a])
img = Image.fromarray(x, 'RGBA')
img.save('/tmp/out.jpg')
Note that the logo also has some semi-transparent pixels used to smooth the edges around the words and icon. Saving to jpeg ignores the semi-transparency, making the resultant jpeg look quite jagged.
A better quality result could be made using imagemagick's convert
command:
convert logo.png -background white -flatten /tmp/out.jpg
To make a nicer quality blend using numpy, you could use alpha compositing:
import Image
import numpy as np
def alpha_composite(src, dst):
'''
Return the alpha composite of src and dst.
Parameters:
src -- PIL RGBA Image object
dst -- PIL RGBA Image object
The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing
'''
# http://stackoverflow.com/a/3375291/190597
# http://stackoverflow.com/a/9166671/190597
src = np.asarray(src)
dst = np.asarray(dst)
out = np.empty(src.shape, dtype = 'float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
src_a = src[alpha]/255.0
dst_a = dst[alpha]/255.0
out[alpha] = src_a+dst_a*(1-src_a)
old_setting = np.seterr(invalid = 'ignore')
out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]
np.seterr(**old_setting)
out[alpha] *= 255
np.clip(out,0,255)
# astype('uint8') maps np.nan (and np.inf) to 0
out = out.astype('uint8')
out = Image.fromarray(out, 'RGBA')
return out
FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
white = Image.new('RGBA', size = img.size, color = (255, 255, 255, 255))
img = alpha_composite(img, white)
img.save('/tmp/out.jpg')
You can do this with very simple class.
class CheckInternet {
fun isNetworkAvailable(context: Context): Boolean {
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
val activeNetworkInfo = connectivityManager!!.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
}
}
Now you can check this from any class.
if (CheckInternet().isNetworkAvailable(this)) {
//connected with internet
}else{
//Not connected with internet
}
http://jqapi.com/ Traversing--> Tree Traversal --> Children
Note that the right format is ("dd/MM/yyyy") before the code works. "mm" means minuts !
String valid_until = "01/07/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = null;
try {
strDate = sdf.parse(valid_until);
} catch (ParseException e) {
e.printStackTrace();
}
if (new Date().after(strDate)) {
catalog_outdated = 1;
}
Relative:
An element with position: relative;
is positioned relative to its normal position.
If you add no positioning attributes (top, left, bottom or right) on a relative element it will have no effect on it's positioning at all. It will behave exactly as a position: static
element.
But if you do add some other positioning attribute, say, top: 10px;, it will shift its position 10 pixels down from where it would normally be.
An element with this type of positioning gets affected by other elements and it itself also affects others.
Absolute:
An element with position: absolute;
allows you to place any element exactly where you want it to be. You use the positioning attributes top, left, bottom. and right to set the location.
It is placed relative to the nearest non-static ancestor. If there is no such container, it is placed relative to the page itself.
It gets removed from the normal flow of elements on the page.
An element with this type of positioning is not affected by other elements and also it doesn't affect flow of other elements.
See this self-explanatory example for better clarity. https://codepen.io/nyctophiliac/pen/BJMqjX
As noted above, it appears that the cover photo of the profile album is a hi-res profile picture. I would check for the album type of "profile" rather than the name though, as the name may not be consistent across different languages, but the type should be.
To reduce the number of requests / parsing, you can use this fql: "select cover_object_id from album where type='profile' and owner = user_id"
And then you can construct the image url with: "https://graph.facebook.com/" + cover_object_id + "/picture&type=normal&access_token=" + access_token
Looks like there is no "large" type for this image, but the "normal" one is still quite large.
As noted above, this photo may be less accessible than the public profile picture. You need the user_photos or friend_photos permission to access it.
For windows universal apps Path.GetFullPath()
is not available, you can use the System.Uri
class instead:
Uri uri = new Uri(Path.Combine(@"C:\blah\",@"..\bling"));
Console.WriteLine(uri.LocalPath);
I'd do
for i in `seq 0 2 10`; do echo $i; done
(though of course seq 0 2 10
will produce the same output on its own).
Note that seq
allows floating-point numbers (e.g., seq .5 .25 3.5
) but bash's brace expansion only allows integers.
try something like
public static Document loadXML(String xml) throws Exception
{
DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
DocumentBuilder bldr = fctr.newDocumentBuilder();
InputSource insrc = new InputSource(new StringReader(xml));
return bldr.parse(insrc);
}
Here's a working function that I uses in one of my application.
This checks if item exit
let ifExist = (item, strings = [ '' ], position = 0) => {
// output into an array with empty string. Important just in case their is no item.
let output = [ '' ];
// check to see if the item that will be positioned exist.
if (item) {
// output should equal to array of strings.
output = strings;
// use splice in order to break the array.
// use positition param to state where to put the item
// and 0 is to not replace an index. Item is the actual item we are placing at the prescribed position.
output.splice(position, 0, item);
}
//empty string is so we do not concatenate with comma or anything else.
return output.join("");
};
And then I call it below.
ifExist("friends", [ ' ( ', ' )' ], 1)} // output: ( friends )
ifExist("friends", [ ' - '], 1)} // output: - friends
ifExist("friends", [ ':'], 0)} // output: friends:
I prefer this solution:
df = spark.table(selected_table).filter(condition)
counter = df.count()
df = df.select([(counter - count(c)).alias(c) for c in df.columns])
You can (should) declare it as extern
in a header file, and define it in exactly 1 .c file.
Note that that .c file should also use the header and that the standard pattern looks like:
// file.h
extern int x; // declaration
// file.c
#include "file.h"
int x = 1; // definition and re-declaration
Use the start and end delimiters: ^abc$
Try using the overload that takes CharSequence
arguments (eg, String
) rather than char
:
str = str.replace("X", "");
CRLF could cause some problem while using your "code" in two different OS (Linux and Windows). My python script was written in Linux docker container and then pushed using Windows git-bash. It gave me the warning that LF will be replaced by CRLF. I didn't give it much thought but then when I started the script later, it said /usr/bin/env: 'python\r': No such file or directory
. Now that an \r
for ramification for you. Windows uses "CR" - carriage return - on top of '\n' as new line character - \n\r
. That's something you might have to consider.
I found that you can detect the command key in the latest version of Safari (7.0: 9537.71) if it is pressed in conjunction with another key. For example, if you want to detect ?+x:, you can detect the x key AND check if event.metaKey is set to true. For example:
var key = event.keyCode || event.charCode || 0;
console.log(key, event.metaKey);
When pressing x on it's own, this will output 120, false
. When pressing ?+x, it will output 120, true
This only seems to work in Safari - not Chrome
This is for Phonegap 3.0.x to 3.3.x. For PhoneGap 3.4.0 and higher see below.
Found part of the answer here, at Phonegap documentation. The full process is the following:
Open a command line window, and go to /path/to/your/project/platforms/android/cordova.
Run build --release
. This creates an unsigned release APK at /path/to/your/project/platforms/android/bin folder, called YourAppName-release-unsigned.apk.
Sign and align the APK using the instructions at android developer official docs.
Thanks to @LaurieClark for the link (http://iphonedevlog.wordpress.com/2013/08/16/using-phonegap-3-0-cli-on-mac-osx-10-to-build-ios-and-android-projects/), and the blogger who post it, because it put me on the track.
As commented by Thomas W. - I almost missed this comment but I had the same issues so it's worth rewriting as an answer I think.
The main issue being that after the first assignment of webBrowser1.DocumentText
to some html, subsequent assignments had no effect.
The solution as linked by Thomas can be found in detail at http://weblogs.asp.net/gunnarpeipman/archive/2009/08/15/displaying-custom-html-in-webbrowser-control.aspx however I will summarize below in case this page becomes unavailable in the future.
In short, due to the way the webBrowser control works, you must navigate to a new page each time you wish to change the content. Therefore the author proposes a method to update the control as:
private void DisplayHtml(string html)
{
webBrowser1.Navigate("about:blank");
if (webBrowser1.Document != null)
{
webBrowser1.Document.Write(string.Empty);
}
webBrowser1.DocumentText = html;
}
I have however found that in my current application I get a CastException from the line if(webBrowser1.Document != null)
. I'm not sure why this is, but I've found that if I wrap the whole if
block in a try catch the desired effect still works. See:
private void DisplayHtml(string html)
{
webBrowser1.Navigate("about:blank");
try
{
if (webBrowser1.Document != null)
{
webBrowser1.Document.Write(string.Empty);
}
}
catch (CastException e)
{ } // do nothing with this
webBrowser1.DocumentText = html;
}
So every time the function to DisplayHtml
is executed I receive a CastException
from the if
statement, so the contents of the if statement are never reached. However if I comment out the if
statement so as not to receive the CastException
, then the browser control doesn't get updated. I suspect there is another side effect of the code behind the Document property which causes this effect despite the fact that it also throws an exception.
Anyway I hope this helps people.
Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.
Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.
String withoutQuotes_line1 = line1.replace("\"", "");
have a look here
If you are having trouble tracing the definitions, you can use the preprocessed output of the compiler which will tell you all you need to know. E.g.
$ cat test.c
#include <stdio.h>
$ cc -E test.c | grep off_t
typedef long int __off_t;
typedef __off64_t __loff_t;
__off_t __pos;
__off_t _old_offset;
typedef __off_t off_t;
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;
If you look at the complete output you can even see the exact header file location and line number where it was defined:
# 132 "/usr/include/bits/types.h" 2 3 4
typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;
...
# 91 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;
In python you must always pass in at least one argument to class methods, the argument is self
and it is not meaningless its a reference to the instance itself
The problem with :scriptnames
, :commands
, :functions
, and similar Vim commands, is that they display information in a large slab of text, which is very hard to visually parse.
To get around this, I wrote Headlights, a plugin that adds a menu to Vim showing all loaded plugins, TextMate style. The added benefit is that it shows plugin commands, mappings, files, and other bits and pieces.
what about changing the position: relative on your #content #text div to position: absolute
#content #text {
position:absolute;
width:950px;
height:215px;
color:red;
}
then you can use the css properties left and top to position within the #content div
@Alwin Doss You should provide the -L option before -l. You would have done the other way round probably. Try this :)
By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.
So just set it to:
<style name="AppTheme" parent="android:Theme.Holo" />
The better way is using 'background-size'.
.pnx-msg-icon .pnx-icon-msg-warning{
background-image: url("../pics/edit.png");
background-repeat: no-repeat;
background-size: 10px;
width: 10px;
height: 10px;
cursor: pointer;
}
even if your icon dimensions is bigger than 10px it will be 10px.
To have a more in-depth knowledge of what's happening, I created the following example. Have a look at the activity_main.xml and content_profile.xml files.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/content_profile" />
</LinearLayout>
content_profile.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Howdy" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hi there" />
</LinearLayout>
In here, the entire layout file when inflated looks like this.
<LinearLayout>
<LinearLayout>
<TextView />
<TextView />
</LinearLayout>
</LinearLayout>
See that there is a LinearLayout inside the parent LinearLayout which doesn't serve any purpose and is redundant. A look at the layout through Layout Inspector tool clearly explains this.
content_profile.xml after updating the code to use merge instead of a ViewGroup like LinearLayout.
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Howdy" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hi there" />
</merge>
Now our layout looks like this
<LinearLayout>
<TextView />
<TextView />
</LinearLayout>
Here we see that the redundant LinearLayout ViewGroup is removed. Now Layout Inspector tool gives the following layout hierarchy.
So always try to use merge when your parent layout can position your child layouts, or more precisely use merge when you understand that there is going to be a redundant view group in the hierarchy.
A StringBuffer is used to create a single string from many strings, e.g. when you want to append parts of a String in a loop.
You should use a StringBuilder instead of a StringBuffer when you have only a single Thread accessing the StringBuffer, since the StringBuilder is not synchronized and thus faster.
AFAIK there is no upper limit for String size in Java as a language, but the JVMs probably have an upper limit.
CI Session Class track information about each user while they browse site.Ci Session class generates its own session data, offering more flexibility for developers.
Initializing a Session
To initialize the Session class manually in our controller constructor use following code.
Adding Custom Session Data
We can add our custom data in session array.To add our data to the session array involves passing an array containing your new data to this function.
$this->session->set_userdata($newarray);
Where $newarray is an associative array containing our new data.
$newarray = array( 'name' => 'manish', 'email' => '[email protected]'); $this->session->set_userdata($newarray);
Retrieving Session
$session_id = $this->session->userdata('session_id');
Above function returns FALSE (boolean) if the session array does not exist.
Retrieving All Session Data
$this->session->all_userdata()
I have taken reference from http://www.tutsway.com/codeigniter-session.php.
My opinions on these are:
1) No, table names should be singular.
While it appears to make sense for the simple selection (select * from Orders
) it makes less sense for the OO equivalent (Orders x = new Orders
).
A table in a DB is really the set of that entity, it makes more sense once you're using set-logic:
select Orders.*
from Orders inner join Products
on Orders.Key = Products.Key
That last line, the actual logic of the join, looks confusing with plural table names.
I'm not sure about always using an alias (as Matt suggests) clears that up.
2) They should be singular as they only hold 1 property
3) Never, if the column name is ambiguous (as above where they both have a column called [Key]) the name of the table (or its alias) can distinguish them well enough. You want queries to be quick to type and simple - prefixes add unnecessary complexity.
4) Whatever you want, I'd suggest CapitalCase
I don't think there's one set of absolute guidelines on any of these.
As long as whatever you pick is consistent across the application or DB I don't think it really matters.
In this particular example, you can use:
#container:hover #cube {
background-color: yellow;
}
This example only works since cube
is a child of container
. For more complicated scenarios, you'd need to use different CSS, or use JavaScript.
Method 2. Self hosting Developer Guide
Download the latest release from github (assets: zip file), unzip, and copy the font folder, containing the material design icons files, into your local project -- https://github.com/google/material-design-icons/releases
You only need to use the font folder from the archive: it contains the icons fonts in the different formats (for multiple browser support) and boilerplate css.
@font-face
, with the relative path to the iconfont folder in your local project, (where the font files are located) eg. url("iconfont/MaterialIcons-Regular.ttf")
@font-face { font-family: 'Material Icons'; font-style: normal; font-weight: 400; src: url(iconfont/MaterialIcons-Regular.eot); /* For IE6-8 */ src: local('Material Icons'), local('MaterialIcons-Regular'), url(iconfont/MaterialIcons-Regular.woff2) format('woff2'), url(iconfont/MaterialIcons-Regular.woff) format('woff'), url(iconfont/MaterialIcons-Regular.ttf) format('truetype'); } .material-icons { font-family: 'Material Icons'; font-weight: normal; font-style: normal; font-size: 24px; /* Preferred icon size */ display: inline-block; line-height: 1; text-transform: none; letter-spacing: normal; word-wrap: normal; white-space: nowrap; direction: ltr; /* Support for all WebKit browsers. */ -webkit-font-smoothing: antialiased; /* Support for Safari and Chrome. */ text-rendering: optimizeLegibility; /* Support for Firefox. */ -moz-osx-font-smoothing: grayscale; /* Support for IE. */ font-feature-settings: 'liga'; }
<i class="material-icons">face</i>
NPM / Bower Packages
Google officially has a Bower and NPM dependency option -- follow Material Icons Guide 1
Using bower : bower install material-design-icons --save
Using NPM : npm install material-design-icons --save
Material Icons : Alternatively look into Material design icon font and CSS framework for self hosting the icons, from @marella's https://marella.me/material-icons/
Note
It seems google has the project on low maintenance mode. The last release was, at time of writing, 3 years ago!
There are several issues on GitHub regarding this, but I'd like to refer to @cyberalien comment on the issue
Is this project actively maintained? #951
where it refers several community projects that forked and continue maintaining material icons.
In your click function, you can write:
function addMoreRows(frm) {
rowCount ++;
var recRow = '<p id="rowCount'+rowCount+'"><tr><td><input name="" type="text" size="17%" maxlength="120" /></td><td><input name="" type="text" maxlength="120" style="margin: 4px 5px 0 5px;"/></td><td><input name="" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/></td></tr> <a href="javascript:void(0);" onclick="removeRow('+rowCount+');">Delete</a></p>';
jQuery('#addedRows').append(recRow);
}
Or follow this link: http://www.discussdesk.com/add-remove-more-rows-dynamically-using-jquery.htm
The code you tried is in fact two statements. A DELETE
followed by a SELECT
.
You don't define TOP
as ordered by what.
For a specific ordering criteria deleting from a CTE or similar table expression is the most efficient way.
;WITH CTE AS
(
SELECT TOP 1000 *
FROM [mytab]
ORDER BY a1
)
DELETE FROM CTE
You can do these conversions also with the .NET Framework:
JSON to XML: by using System.Runtime.Serialization.Json
var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));
XML to JSON: by using System.Web.Script.Serialization
var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));
private static Dictionary<string, object> GetXmlData(XElement xml)
{
var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
else if (!xml.IsEmpty) attr.Add("_value", xml.Value);
return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}
This specific example will just check for inputs but you could tweak it however, Add something like this to your .ajax function:
beforeSend: function() {
$empty = $('form#yourForm').find("input").filter(function() {
return this.value === "";
});
if($empty.length) {
alert('You must fill out all fields in order to submit a change');
return false;
}else{
return true;
};
},
I wrote a shell script called fullpath that contains this code, use it everyday:
#!/bin/sh
for i in $* ; do
echo $(pwd)/$i
done
Put it somewhere in your PATH, and make it executable(chmod 755 fullpath) then just use
fullpath file_or_directory
After some trials, knowing that I had all the factors stated in this thread and other threads properly configured, I still got this error in Android Studio.
Even after installing externally, it seems Android Studio could not discover that HAXM is already installed, unless it gets to install it itself.
As a solution that worked for me, under User\AppData\Local\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager
which android has downloaded when attempting to install HAXM, click the installer and uninstall the software, then re-try from Android Studio to install it, it should work now.
You have several options if you use BufferedReader
. This buffered reader is faster than Reader so you can wrap it.
BufferedReader reader = new BufferedReader(new FileReader(path));
reader.read(char[] buffer);
this reads line into char array. You have similar options. Look at documentation.
ALTER TABLE <table_name> MODIFY <column_name> DEFAULT <defult_value>
EX: ALTER TABLE AAA MODIFY ID DEFAULT AAA_SEQUENCE.nextval
Tested on Oracle Database 12c Enterprise Edition Release 12.2.0.1.0
change your code to:
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async: false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;
},
error: function (textStatus, errorThrown) {
Success = false;
}
});
//done after here
return Success;
}
You can only return the values from a synchronous
function. Otherwise you will have to make a callback
.
So I just added async:false,
to your ajax call
Update:
jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.
A better approach will be:
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
and call the ajax as:
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);
It'll vary depending on resources, but you could run the script bellow and see for yourself ;)
<?php
$tests = 100000;
for ($i = 0; $i < $tests; $i++)
{
$string = md5(rand());
$position = rand(0, 31);
$start1 = microtime(true);
$char1 = $string[$position];
$end1 = microtime(true);
$time1[$i] = $end1 - $start1;
$start2 = microtime(true);
$char2 = substr($string, $position, 1);
$end2 = microtime(true);
$time2[$i] = $end2 - $start2;
$start3 = microtime(true);
$char3 = $string{$position};
$end3 = microtime(true);
$time3[$i] = $end3 - $start3;
}
$avg1 = array_sum($time1) / $tests;
echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL;
$avg2 = array_sum($time2) / $tests;
echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL;
$avg3 = array_sum($time3) / $tests;
echo 'the average float microtime using "array{}" is '. $avg3 . PHP_EOL;
?>
Some reference numbers (on an old CoreDuo machine)
$ php 1.php
the average float microtime using "array[]" is 1.914701461792E-6
the average float microtime using "substr()" is 2.2536706924438E-6
the average float microtime using "array{}" is 1.821768283844E-6
$ php 1.php
the average float microtime using "array[]" is 1.7251944541931E-6
the average float microtime using "substr()" is 2.0931363105774E-6
the average float microtime using "array{}" is 1.7225742340088E-6
$ php 1.php
the average float microtime using "array[]" is 1.7293763160706E-6
the average float microtime using "substr()" is 2.1037721633911E-6
the average float microtime using "array{}" is 1.7249774932861E-6
It seems that using the []
or {}
operators is more or less the same.
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
It's short hand for the ternary operator.
FormsAuth = (formsAuth != null) ? formsAuth : new FormsAuthenticationWrapper();
Or for those who don't do ternary:
if (formsAuth != null)
{
FormsAuth = formsAuth;
}
else
{
FormsAuth = new FormsAuthenticationWrapper();
}
It means that you should not share an iterator object among multiple threads. Creating multiple iterators and using them concurrently in separate threads is fine.
To create an option that needs no value, set the action
[docs] of it to 'store_const'
, 'store_true'
or 'store_false'
.
Example:
parser.add_argument('-s', '--simulate', action='store_true')
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "YOURBATCHFILE.bat";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Code is from MSDN.
Use zip(*list)
:
>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]
The zip()
function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l
you apply all tuples in l
as separate arguments to the zip()
function, so zip()
pairs up 1
with 3
with 8
first, then 2
with 4
and 9
. Those happen to correspond nicely with the columns, or the transposition of l
.
zip()
produces tuples; if you must have mutable list objects, just map()
the tuples to lists or use a list comprehension to produce a list of lists:
map(list, zip(*l)) # keep it a generator
[list(t) for t in zip(*l)] # consume the zip generator into a list of lists
That's not the behavior I'm seeing:
irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]
Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?
brew services start mysql
defualt set --bind-address=127.0.0.1 with /usr/local/Cellar/mysql/5.6.27/homebrew.mxcl.mysql.plist,so replace --bind-address=127.0.0.1 with --bind-address=* or --bind-address=0.0.0.0
This is what I used for checking if any checkboxes in a list of checkboxes had changed:
$('input[type="checkbox"]').change(function(){
var itemName = $('select option:selected').text();
//Do something.
});
Add &autoplay=1 to your syntax, like this
<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&autoplay=1" frameborder="0" allowfullscreen></iframe>
This will help
1- First Define This Constants
public static final String FACEBOOK_PACKAGE_NAME = "com.facebook.katana";
public static final String TWITTER_PACKAGE_NAME = "com.twitter.android";
public static final String INSTAGRAM_PACKAGE_NAME = "com.instagram.android";
public static final String PINTEREST_PACKAGE_NAME = "com.pinterest";
public static final String WHATS_PACKAGE_NAME = "com.whatsapp";
2- Second Use This method
public static void shareAppWithSocial(Context context, String application, String title,
String description) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setPackage(application);
intent.putExtra(android.content.Intent.EXTRA_TITLE, title);
intent.putExtra(Intent.EXTRA_TEXT, description);
intent.setType("text/plain");
try {
// Start the specific social application
context.startActivity(intent);
} catch (android.content.ActivityNotFoundException ex) {
// The application does not exist
Toast.makeText(context, "app have not been installed.", Toast.LENGTH_SHORT).show();
}
}
For Photoshop you need to download Photoshop portable.... Load image e press "w" click in image e suave as png or gif....
Ansible uses the become
, become_user
, and become_method
directives to achieve privilege escalation. You can apply them to an entire play or playbook, set them in an included playbook, or set them for a particular task.
- name: checkout repo
git: repo=https://github.com/some/repo.git version=master dest={{ dst }}
become: yes
become_user: some_user
You can use become_with
to specify how the privilege escalation is achieved, the default being sudo
.
The directive is in effect for the scope of the block in which it is used (examples).
See Hosts and Users for some additional examples and Become (Privilege Escalation) for more detailed documentation.
In addition to the task-scoped become
and become_user
directives, Ansible 1.9 added some new variables and command line options to set these values for the duration of a play in the absence of explicit directives:
become
/become_user
directives.As of Ansible 2.0.2.0, the older sudo
/sudo_user
syntax described below still works, but the deprecation notice states, "This feature will be removed in a future release."
- name: checkout repo
git: repo=https://github.com/some/repo.git version=master dest={{ dst }}
sudo: yes
sudo_user: some_user
You can't set colour of the padding.
You will have to create a wrapper element with the desired background colour. Add border to this element and set it's padding.
Look here for an example: http://jsbin.com/abanek/1/edit
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
If you use the java keyword abstract
you cannot provide an implementation.
Sometimes this idea comes from having a background in C++ and mistaking the virtual
keyword in C++ as being "almost the same" as the abstract
keyword in Java.
In C++ virtual
indicates that a method can be overridden and polymorphism will follow, but abstract
in Java is not the same thing. In Java abstract
is more like a pure virtual
method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual
from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.
Now to protect a method from being overridden, Java uses the keyword final
in coordination with the method declaration to indicate that subclasses cannot override the method.
For a more complete list as of 2015:
* html .ie6 {property:value;}
or
.ie6 { _property:value;}
*+html .ie7 {property:value;}
or
*:first-child+html .ie7 {property:value;}
@media screen\9 {
.ie67 {property:value;}
}
or
.ie67 { *property:value;}
or
.ie67 { #property:value;}
@media \0screen\,screen\9 {
.ie678 {property:value;}
}
html>/**/body .ie8 {property:value;}
or
@media \0screen {
.ie8 {property:value;}
}
.ie8 { property /*\**/: value\9 }
@media screen\0 {
.ie8910 {property:value;}
}
@media screen and (min-width:0) and (min-resolution: .001dpcm) {
// IE9 CSS
.ie9{property:value;}
}
@media screen and (min-width:0) and (min-resolution: +72dpi) {
// IE9+ CSS
.ie9up{property:value;}
}
@media screen and (min-width:0) {
.ie910{property:value;}
}
_:-ms-lang(x), .ie10 { property:value\9; }
_:-ms-lang(x), .ie10up { property:value; }
or
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.ie10up{property:value;}
}
_:-ms-fullscreen, :root .ie11up { property:value; }
Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element
The Javascript:
var b = document.documentElement;
b.setAttribute('data-useragent', navigator.userAgent);
b.setAttribute('data-platform', navigator.platform );
b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');
Adds (e.g) the below to the html
element:
data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'
Allowing very targetted CSS selectors, e.g.:
html[data-useragent*='Chrome/13.0'] .nav{
background:url(img/radial_grad.png) center bottom no-repeat;
}
If possible, avoid browser targeting. Identify and fix any issue(s) you identify. Support progressive enhancement and graceful degradation. With that in mind, this is an 'ideal world' scenario not always obtainable in a production environment, as such- the above should help provide some good options.
In practice, it is possible, if you use span
element instead of font
:
<style>
u { color: black; }
.red { color: red }
</style>
<u><span class='red'><br>$username</span></u>
See jsfiddle. Appears to work on Chrome, Safari, Firefox, IE, Opera (tested on Win 7 with newest versions).
The code in the question should work, too, but it does not work for some reason on WebKit browsers (Chrome, Safari).
By the CSS spec: “The color(s) required for the text decoration must be derived from the 'color' property value of the element on which 'text-decoration' is set. The color of decorations must remain the same even if descendant elements have different 'color' values.”
It depends, if you are referring to unsigned long the formatting character is "%lu"
. If you're referring to signed long the formatting character is "%ld"
.
For everyone using Eclipse, this is how you should do it.
Eclipse -> import -> existing android code -> browse -> navigate to google-play-services_lib FOLDER (android-sdk/extras/google/google_play_services/libproject).
Then, on your project
control click -> properties -> android -> libraries, add -> select the project you just imported -> ok
Update table set column = (select...)
never worked for me since set only expects 1 value - SQL Error: ORA-01427: single-row subquery returns more than one row.
here's the solution:
BEGIN
For i in (select id, name, desc from table1)
LOOP
Update table2 set name = i.name, desc = i.desc where id = i.id;
END LOOP;
END;
That's how exactly you run it on SQLDeveloper worksheet. They say it's slow but that's the only solution that worked for me on this case.
You can use the adb
command which comes in the tools dir of the SDK:
adb shell
It will give you a command line prompt where you can browse and access the filesystem. Or you can extract the files you want:
adb pull /sdcard/the_file_you_want.txt
Also, if you use eclipse with the ADT, there's a view to browse the file system (Window->Show View->Other... and choose Android->File Explorer)
Here is a query which you can use to search for anything in from your database as a search result ,
SELECT * FROM tbl_customer
WHERE CustomerName LIKE '%".$search."%'
OR Address LIKE '%".$search."%'
OR City LIKE '%".$search."%'
OR PostalCode LIKE '%".$search."%'
OR Country LIKE '%".$search."%'
Using this code will help you search in for multiple columns easily
You should add:
android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude '...'
}
}
to your build.gradle
file.
According to comment 14 in this bug: https://issuetracker.google.com/issues/36982149#comment14 this is a bug in v0.7.0 of the Android Gradle plugin, and is due to be fixed soon in 0.7.1.
Here are the notes from that bug about the addition for 0.7.1:
0.7.1 is out with the fix for this.
The DSL to exclude files is:
android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
}
}
You can add as many exclude statement as you want. The value is the archive path. No wildcard or glob support yet.
Filenames "LICENSE.txt" and "NOTICE.txt" are case sensitive. Please try out with "license.txt" and "notice.txt" as well.
How about a good old fashioned for loop?
for (int i = 0; i < Model.Results.Count; i++) {
if (i == Model.Results.Count - 1) {
// this is the last item
}
}
Or using Linq and the foreach:
foreach (Item result in Model.Results)
{
if (Model.Results.IndexOf(result) == Model.Results.Count - 1) {
// this is the last item
}
}
ACTIONS = {
1 : "Created",
2 : "Deleted",
3 : "Updated",
4 : "Renamed from something",
5 : "Renamed to something"
}
FILE_LIST_DIRECTORY = 0x0001
class myThread (threading.Thread):
def __init__(self, threadID, fileName, directory, origin):
threading.Thread.__init__(self)
self.threadID = threadID
self.fileName = fileName
self.daemon = True
self.dir = directory
self.originalFile = origin
def run(self):
startMonitor(self.fileName, self.dir, self.originalFile)
def startMonitor(fileMonitoring,dirPath,originalFile):
hDir = win32file.CreateFile (
dirPath,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None
)
# Wait for new data and call ProcessNewData for each new chunk that's
# written
while 1:
# Wait for a change to occur
results = win32file.ReadDirectoryChangesW (
hDir,
1024,
False,
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
None,
None
)
# For each change, check to see if it's updating the file we're
# interested in
for action, file_M in results:
full_filename = os.path.join (dirPath, file_M)
#print file, ACTIONS.get (action, "Unknown")
if len(full_filename) == len(fileMonitoring) and action == 3:
#copy to main file
...
Both examples work like a charm :)
JAVASCRIPT:
function CopyToClipboard(containerid) {_x000D_
if (document.selection) {_x000D_
var range = document.body.createTextRange();_x000D_
range.moveToElementText(document.getElementById(containerid));_x000D_
range.select().createTextRange();_x000D_
document.execCommand("copy");_x000D_
} else if (window.getSelection) {_x000D_
var range = document.createRange();_x000D_
range.selectNode(document.getElementById(containerid));_x000D_
window.getSelection().addRange(range);_x000D_
document.execCommand("copy");_x000D_
alert("Text has been copied, now paste in the text-area")_x000D_
}_x000D_
}
_x000D_
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>_x000D_
<br /><br />_x000D_
<div id="div1">Text To Copy </div>_x000D_
<br />_x000D_
<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
_x000D_
JQUERY (relies on Adobe Flash): https://paulund.co.uk/jquery-copy-to-clipboard
Use the function cast() to convert from timestamp to date
select to_char(cast(sysdate as date),'DD-MM-YYYY') from dual;
For more info of function cast oracle11g http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions016.htm#SQLRF51256
If you are using ASP.NET Core MVC project. This error message can be shown then you have the correct cshtml
file in your Views
folder but the action is missing in your controller.
Adding the missing action to the controller will fix it.
DEMO : http://jsfiddle.net/shfj70qp/
//dd/mm/yyyy
var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
console.log(month+"/"+day+"/"+year);
Update with Java 9+ with takeWhile
:
MutableBoolean ongoing = MutableBoolean.of(true);
someobjects.stream()...takeWhile(t -> ongoing.value()).forEach(t -> {
// doing something.
if (...) { // want to break;
ongoing.setFalse();
}
});
Consider the following example: If you want to change a single CSS property(say, color to 'blue'), then the below statement works fine.
document.getElementById("ele_id").style.color="blue";
But, for changing multiple properies the more robust way is using Object.assign()
or, object spread operator {...}
;
const ele=document.getElementById("ele_id");
const custom_style={
display: "block",
color: "red"
}
//Object.assign():
Object.assign(ele.style,custum_style);
Spread operator works similarly, just the syntax is a little different.
You do not have to use final
, but the final
is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.
Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.
An aspect the other answers are missing out unfortunately, is that using the combination of public final
needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public
).
Here's why:
final
, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.public
, the compiler will also inline this value into any other compile unit. That means other classes using this field.What are the consequences?
Imagine you have this:
class Foo {
public static final String VERSION = "1.0";
}
class Bar {
public static void main(String[] args) {
System.out.println("I am using version " + Foo.VERSION);
}
}
After compiling and running Bar
, you'll get:
I am using version 1.0
Now, you improve Foo
and change the version to "1.1".
After recompiling Foo
, you run Bar
and get this wrong output:
I am using version 1.0
This happens, because VERSION
is declared final
, so the actual value of it was already in-lined in Bar
during the first compile run. As a consequence, to let the example of a public static final ...
field propagate properly after actually changing what was declared final
(you lied!;), you'd need to recompile every class using it.
I've seen this a couple of times and it is really hard to debug.
If by final
you mean a constant that might change in later versions of your program, a better solution would be this:
class Foo {
private static String version = "1.0";
public static final String getVersion() {
return version;
}
}
The performance penalty of this is negligible, since JIT code generator will inline it at run-time.
I would start by turning off TCP offloading. There have been a few things that cause intermittent connectivity issues and this is the one that is usually the culprit.
Note: I have seen this setting cause problems on Win Server 2003 and Win Server 2008
http://blogs.msdn.com/b/mssqlisv/archive/2008/05/27/sql-server-intermittent-connectivity-issue.aspx
http://technet.microsoft.com/en-us/library/gg162682(v=ws.10).aspx
The following are the major differences between procedure and function,
I'm not 100% on why (actually came here to search for the answer), but this also works, and doesn't require replacing all nan values.
import pandas as pd
import numpy as np
df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])
newdf = df.loc[df['a'].str.contains('foo') == True]
Works with or without .loc
.
I have no idea why this works, as I understand it when you're indexing with brackets pandas evaluates whatever's inside the bracket as either True
or False
. I can't tell why making the phrase inside the brackets 'extra boolean' has any effect at all.
I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.
attachEvent / addEventListening allow multiple event handlers to be created.
If you need to resume an scp transfer from local to remote, try with rsync:
rsync --partial --progress --rsh=ssh local_file user@host:remote_file
Short version, as pointed out by @aurelijus-rozenas:
rsync -P -e ssh local_file user@host:remote_file
In general the order of args for rsync is
rsync [options] SRC DEST
this is not possible in "mailto" function.
please go with server side coding(C#).make sure open vs in administrative permission.
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
oMsg.Subject = "emailSubject";
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
oMsg.BCC = "emailBcc";
oMsg.To = "emailRecipient";
string body = "emailMessage";
oMsg.HTMLBody = "body";
oMsg.Attachments.Add(Convert.ToString(@"/my_location_virtual_path/myfile.txt"), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
oMsg.Display(false); //In order to displ
private static function lineCount($file) {
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
if (fgets($handle) !== false) {
$linecount++;
}
}
fclose($handle);
return $linecount;
}
I wanted to add a little fix to the function above...
in a specific example where i had a file containing the word 'testing' the function returned 2 as a result. so i needed to add a check if fgets returned false or not :)
have fun :)
You can use the SqlDependency Class
. Its intended use is mostly for ASP.NET pages (low number of client notifications).
ALTER DATABASE UrDb SET ENABLE_BROKER
Implement the OnChange
event to get notified:
void OnChange(object sender, SqlNotificationEventArgs e)
And in code:
SqlCommand cmd = ...
cmd.Notification = null;
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += OnChange;
It uses the Service Broker
(a message-based communication platform) to receive messages from the database engine.
Python string comparison is lexicographic:
From Python Docs: http://docs.python.org/reference/expressions.html
Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior.
Hence in your example, 'abc' < 'bac'
, 'a' comes before (less-than) 'b' numerically (in ASCII and Unicode representations), so the comparison ends right there.
For Kotlin developers, remember the Java transient
keyword becomes the built-in Kotlin @Transient
annotation. Therefore, make sure you have the JPA import if you're using JPA @Transient
in your entity:
import javax.persistence.Transient
I was missing several DLLs. Even if I manually copied them to the directory the next time I published they would disappear. Each one was already set to Copy Locally in VS. The fix for me was to set each one to Copy Locally false, save, build then set each one to copy locally true. This time when I published all of the DLLs published correctly. Strange
Here, using github
and git version 2.1.4
, just do:
$ git clone [email protected]:user/repo.git
And remotes come by itelsef, even if not linked locally:
$ git remote show origin
* remote origin
Fetch URL: [email protected]:user/repo.git
Push URL: [email protected]:user/repo.git
HEAD branch: master
Remote branches:
develop tracked <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
But of course, still no local branch:
$ git branch
* master <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
See? Now if you just checkout develp, it will do the magic automatically:
$ git checkout develop
Branch develop set up to track remote branch develop from origin.
Switched to a new branch 'develop'
So easy!
Summary. Just run this 2 commands:
$ git clone [email protected]:user/repo.git
$ git checkout develop
Assuming the .resx file was added using Visual Studio under the project properties, there is an easier and less error prone way to access the string.
Accessing the string is then as easy as:
var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager;
var exampleXmlString = resourceManager.GetString("exampleXml");
Replace JoshCodes.Core.Testing.Unit
with the project's default namespace.
A class that will play a WAV file, blocking until the sound has finished playing:
class Sound implements Playable {
private final Path wavPath;
private final CyclicBarrier barrier = new CyclicBarrier(2);
Sound(final Path wavPath) {
this.wavPath = wavPath;
}
@Override
public void play() throws LineUnavailableException, IOException, UnsupportedAudioFileException {
try (final AudioInputStream audioIn = AudioSystem.getAudioInputStream(wavPath.toFile());
final Clip clip = AudioSystem.getClip()) {
listenForEndOf(clip);
clip.open(audioIn);
clip.start();
waitForSoundEnd();
}
}
private void listenForEndOf(final Clip clip) {
clip.addLineListener(event -> {
if (event.getType() == LineEvent.Type.STOP) waitOnBarrier();
});
}
private void waitOnBarrier() {
try {
barrier.await();
} catch (final InterruptedException ignored) {
} catch (final BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
private void waitForSoundEnd() {
waitOnBarrier();
}
}
I suspect that the reason that transitions are disabled if display
is changed is because of what display actually does. It does not change anything that could conceivably be smoothly animated.
display: none;
and visibility: hidden;
are two entirely different things.
Both do have the effect of making the element invisible, but with visibility: hidden;
it’s still rendered in the layout, but just not visibly so.
The hidden element still takes up space, and is still rendered inline or as a block or block-inline or table or whatever the display
element tells it to render as, and takes up space accordingly.
Other elements do not automatically move to occupy that space. The hidden element just doesn’t render its actual pixels to the output.
display: none
on the other hand actually prevents the element from rendering entirely.
It does not take up any layout space.
Other elements that would’ve occupied some or all of the space taken up by this element now adjust to occupy that space, as if the element simply did not exist at all.
display
is not just another visual attribute.
It establishes the entire rendering mode of the element, such as whether it’s a block
, inline
, inline-block
, table
, table-row
, table-cell
, list-item
, or whatever!
Each of those have very different layout ramifications, and there would be no reasonable way to animate or smoothly transition them (try to imagine a smooth transition from block
to inline
or vice-versa, for instance!).
This is why transitions are disabled if display changes (even if the change is to or from none
— none
isn’t merely invisibility, it’s its own element rendering mode that means no rendering at all!).
Threads share a process and a process runs on a core, but you can use python's multiprocessing module to call your functions in separate processes and use other cores, or you can use the subprocess module, which can run your code and non-python code too.
public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String url = obj.getString("url");
System.out.println(name);
System.out.println(url);
}
}
Output:
name1
url1
name2
url2
JSON strings must use double quotes. The JSON python library enforces this so you are unable to load your string. Your data needs to look like this:
{"http://example.org/about": {"http://purl.org/dc/terms/title": [{"type": "literal", "value": "Anna's Homepage"}]}}
If that's not something you can do, you could use ast.literal_eval()
instead of json.loads()
I had a very similar problem and want to share my solution
Given this table (all MySQL 5.6):
create table DailySchedule
(
id int auto_increment primary key,
start_time time not null,
stop_time time not null
);
Select all rows where a given time x (hh:mm:ss)
is between start and stop time. Including the next day.
Note: replace NOW()
with the any time x
you like
SELECT id
FROM DailySchedule
WHERE
(start_time < stop_time AND NOW() BETWEEN start_time AND stop_time)
OR
(stop_time < start_time AND NOW() < start_time AND NOW() < stop_time)
OR
(stop_time < start_time AND NOW() > start_time)
Results
Given
id: 1, start_time: 10:00:00, stop_time: 15:00:00
id: 2, start_time: 22:00:00, stop_time: 12:00:00
NOW = 09:00:00
: 2
NOW = 14:00:00
: 1
NOW = 11:00:00
: 1,2
NOW = 20:00:00
: nothingstd::max_element
takes two iterators delimiting a sequence and returns an iterator pointing to the maximal element in that sequence. You can additionally pass a predicate to the function that defines the ordering of elements.
I had a similar issue on Mac OS and I was able to fix it this way:
From the terminal, run:
mysql -u root -p -h 127.0.0.1 -P 3306
Then, I was asked to enter the password. I just pressed enter since no password was setup.
I got a message as follows:
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 181. Server version: 8.0.11 Homebrew.
If you succeeded to log into mysql>, run the following command:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
You should get a message like this:
Query OK, 0 rows affected (0.19 sec)
Now, your password is "password" and your username is "root".
Happy coding :)
Using React on my IPad, type="number"
does not work perfectly for me.
For my floating point numbers in the range between 99.99999 - .00000 I use the regular expression (^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)
. The first group (...)
is true for all positive two digit numbers without the floating point (e.g. 23), |
or e.g. .12345 for the second group (...)
. You can adopt it for any positive floating point number by simply changing the range {0,2}
or {0,5}
respectively.
<input
className="center-align"
type="text"
pattern="(^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)"
step="any"
maxlength="7"
validate="true"
/>
dochoffiday's answer is a great starting point, but for me it did not cut it (the CSS part needed a buff) so I made a modified version with several improvements.
See it in action, then come back for the description.
(function ($) {
$.fn.styleTable = function (options) {
var defaults = {
css: 'ui-styled-table'
};
options = $.extend(defaults, options);
return this.each(function () {
$this = $(this);
$this.addClass(options.css);
$this.on('mouseover mouseout', 'tbody tr', function (event) {
$(this).children().toggleClass("ui-state-hover",
event.type == 'mouseover');
});
$this.find("th").addClass("ui-state-default");
$this.find("td").addClass("ui-widget-content");
$this.find("tr:last-child").addClass("last-child");
});
};
})(jQuery);
Differences with the original version:
ui-styled-table
(it sounds more consistent).live
call was replaced with the recommended .on
for jQuery 1.7 upwards.toggleClass
(a terser equivalent)first
on table cells has been removed.last-child
to the last table row is necessary to fix a visual glitch on Internet Explorer 7 and Internet Explorer 8; for browsers that support :last-child
it is not necessary/* Internet Explorer 7: setting "separate" results in bad visuals; all other browsers work fine with either value. */
/* If set to "separate", then this rule is also needed to prevent double vertical borders on hover:
table.ui-styled-table tr * + th, table.ui-styled-table tr * + td { border-left-width: 0px !important; } */
table.ui-styled-table { border-collapse: collapse; }
/* Undo the "bolding" that jQuery UI theme may cause on hovered elements
/* Internet Explorer 7: does not support "inherit", so use a MS proprietary expression along with an Internet Explorer <= 7 targeting hack
to make the visuals consistent across all supported browsers */
table.ui-styled-table td.ui-state-hover {
font-weight: inherit;
*font-weight: expression(this.parentNode.currentStyle['fontWeight']);
}
/* Initally remove bottom border for all cells. */
table.ui-styled-table th, table.ui-styled-table td { border-bottom-width: 0px !important; }
/* Hovered-row cells should show bottom border (will be highlighted) */
table.ui-styled-table tbody tr:hover th,
table.ui-styled-table tbody tr:hover td
{ border-bottom-width: 1px !important; }
/* Remove top border if the above row is being hovered to prevent double horizontal borders. */
table.ui-styled-table tbody tr:hover + tr th,
table.ui-styled-table tbody tr:hover + tr td
{ border-top-width: 0px !important; }
/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 7, Internet Explorer 8: selector dependent on CSS classes because of no support for :last-child */
table.ui-styled-table tbody tr.last-child th,
table.ui-styled-table tbody tr.last-child td
{ border-bottom-width: 1px !important; }
/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 8 BUG: if these (unsupported) selectors are added to a rule, other selectors for that rule will stop working as well! */
/* Internet Explorer 9 and later, Firefox, Chrome: make sure the visuals are working even without the CSS classes crutch. */
table.ui-styled-table tbody tr:last-child th,
table.ui-styled-table tbody tr:last-child td
{ border-bottom-width: 1px !important; }
I have tested this on Internet Explorer 7 and upwards, Firefox 11 and Google Chrome 18 and confirmed that it works perfectly. I have not tested reasonably earlier versions of Firefox and Chrome or any version of Opera; however, those browsers are well-known for good CSS support and since we are not using any bleeding-edge functionality here I assume it will work just fine there as well.
If you are not interested in Internet Explorer 7 support there is one CSS attribute (introduced with the star hack) that can go.
If you are not interested in Internet Explorer 8 support either, the CSS and JavaScript related to adding and targeting the last-child
CSS class can go as well.
You can do it like this, but sorry my english is not good enough.
First, get home base url with this simple code..
I've tested this code on my local server and public and the result is good.
<?php
function home_base_url(){
// first get http protocol if http or https
$base_url = (isset($_SERVER['HTTPS']) &&
$_SERVER['HTTPS']!='off') ? 'https://' : 'http://';
// get default website root directory
$tmpURL = dirname(__FILE__);
// when use dirname(__FILE__) will return value like this "C:\xampp\htdocs\my_website",
//convert value to http url use string replace,
// replace any backslashes to slash in this case use chr value "92"
$tmpURL = str_replace(chr(92),'/',$tmpURL);
// now replace any same string in $tmpURL value to null or ''
// and will return value like /localhost/my_website/ or just /my_website/
$tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'],'',$tmpURL);
// delete any slash character in first and last of value
$tmpURL = ltrim($tmpURL,'/');
$tmpURL = rtrim($tmpURL, '/');
// check again if we find any slash string in value then we can assume its local machine
if (strpos($tmpURL,'/')){
// explode that value and take only first value
$tmpURL = explode('/',$tmpURL);
$tmpURL = $tmpURL[0];
}
// now last steps
// assign protocol in first value
if ($tmpURL !== $_SERVER['HTTP_HOST'])
// if protocol its http then like this
$base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/';
else
// else if protocol is https
$base_url .= $tmpURL.'/';
// give return value
return $base_url;
}
?>
// and test it
echo home_base_url();
output will like this :
local machine : http://localhost/my_website/ or https://myhost/my_website
public : http://www.my_website.com/ or https://www.my_website.com/
use home_base_url
function at index.php
of your website and define it
and then you can use this function to load scripts, css and content via url like
<?php
echo '<script type="text/javascript" src="'.home_base_url().'js/script.js"></script>'."\n";
?>
will create output like this :
<script type="text/javascript" src="http://www.my_website.com/js/script.js"></script>
and if this script works fine,,!
Try:
mysql -u username -p database_name < file.sql
Check MySQL Options.
Note: It is better to use the full path of the SQL file file.sql
.
The Access-Control-Allow-Origin response header indicates whether the response can be shared with requesting code from the given origin.
Header type Response header
Forbidden header name no
A response that tells the browser to allow code from any origin to access a resource will include the following:
Access-Control-Allow-Origin: *
For more info, visit here....
Use whatever service manager your system offers - for example under Ubuntu use upstart. This will handle all the details for you such as start on boot, restart on crash, etc.
You have many options. Collating some of the answers above and the accepted answer from this post you can do:
1. df[-df["column"].isin(["value"])]
2. df[~df["column"].isin(["value"])]
3. df[df["column"].isin(["value"]) == False]
4. df[np.logical_not(df["column"].isin(["value"]))]
Note: for option 4 for you'll need to import numpy as np
Update: You can also use the .query
method for this too. This allows for method chaining:
5. df.query("column not in @values")
.
where values
is a list of the values that you don't want to include.
Setting locales in terminal resolved the issue for me. Open the terminal and
Check if locale settings are missing
> locale
LANG=
LC_COLLATE="C"
LC_CTYPE="UTF-8"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL=
Edit ~/.profile
or ~/.bashrc
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
Run . ~/.profile
or . ~/.bashrc
to read from the file.
Open a new terminal window and check that the locales are properly set
> locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
For Drupal 8 users looking for solution for DB import failure:
At end of sql dump file there can commands inserting data to "webprofiler" table. That's I guess some debug log file and is not really important for site to work so all this can be removed. I deleted all those inserts including LOCK TABLES and UNLOCK TABLES (and everything between). It's at very bottom of the sql file. Issue is described here:
https://www.drupal.org/project/devel/issues/2723437
But there is no solution for it beside truncating that table.
BTW I tried all solutions from answers above and nothing else helped.
Don't waste your time trying to resolve this issue, this was made clear by the makers themselves. Instead of cv2.imshow()
use this:
img = cv2.imread('path_to_image')
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
The negation pseudo-class seems to be what you are looking for.
table:not(.dojoxGrid) {color:red;}
If you are not using Laravel but using Eloquent package then:
use \Illuminate\Database\Capsule\Manager as Capsule;
use \Illuminate\Events\Dispatcher;
use \Illuminate\Container\Container;
$capsule = new Capsule;
$capsule->addConnection([
// connection details
]);
// Set the event dispatcher used by Eloquent models... (optional)
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();
// Setup the Eloquent ORM...(optional unless you've used setEventDispatcher())
$capsule->bootEloquent();
// Listen for Query Events for Debug
$events = new Dispatcher;
$events->listen('illuminate.query', function($query, $bindings, $time, $name)
{
// Format binding data for sql insertion
foreach ($bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else if (is_string($binding)) {
$bindings[$i] = "'$binding'";`enter code here`
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $query);
$query = vsprintf($query, $bindings);
// Debug SQL queries
echo 'SQL: [' . $query . ']';
});
$capsule->setEventDispatcher($events);
If you want to add row
before the <tr>
first child.
$("#myTable > tbody").prepend("<tr><td>my data</td><td>more data</td></tr>");
If you want to add row
after the <tr>
last child.
$("#myTable > tbody").append("<tr><td>my data</td><td>more data</td></tr>");
Please try this command to solve it -
git push origin master --force
Or
git push origin master -f
If there are are no duplicate elements or you don't care about them, then you can use the Set class:
a1 = Set.new [5, 1, 6, 14, 2, 8]
a2 = Set.new [2, 6, 15]
a1.subset?(a2)
=> false
Behind the scenes this uses
all? { |o| set.include?(o) }
Wrap your all statements in !IsPostBack
condition on page load.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// all statements
}
}
This will fix your issue.
Here is an immutable version for those who are interested:
function immutableMove(arr, from, to) {
return arr.reduce((prev, current, idx, self) => {
if (from === to) {
prev.push(current);
}
if (idx === from) {
return prev;
}
if (from < to) {
prev.push(current);
}
if (idx === to) {
prev.push(self[from]);
}
if (from > to) {
prev.push(current);
}
return prev;
}, []);
}
Normally the parameter -d
is interpreted as form-encoded. You need the -H
parameter:
curl -v -H "Content-Type: application/json" -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
Sure you can. Eg.
<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>
Output
<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
<content type="latest"/>
</news>
Have fun.