You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php
If you just need the name of the device here is a little hack which i wrote in bash. To run it in python you need the following snippet. Just replace $1 and $2 with Bus number and Device number eg 001 or 002.
import os
os.system("lsusb | grep \"Bus $1 Device $2\" | sed 's/\// /' | awk '{for(i=7;i<=NF;++i)print $i}'")
Alternately you can save it as a bash script and run it from there too. Just save it as a bash script like foo.sh make it executable.
#!/bin/bash
myvar=$(lsusb | grep "Bus $1 Device $2" | sed 's/\// /' | awk '{for(i=7;i<=NF;++i)print $i}')
echo $myvar
Then call it in python script as
import os
os.system('foo.sh')
A span tag is only as wide as its contents, so there is no 'center' of a span tag. There is no extra space on either side of the content.
A div tag, however, is as wide as its containing element, so the content of that div can be centered using any extra space that the content doesn't take up.
So if your div is 100px width and your content only takes 50px, the browser will divide the remaining 50px by 2 and pad 25px on each side of your content to center it.
readlink -f filename
gives the full absolute path. but if the file is a symlink, u'll get the final resolved name.
Using this command,
git log -r --oneline --no-merges --simplify-by-decoration --pretty=format:"%n %Cred CommitID %Creset: %h %n %Cred Remote Branch %Creset :%d %n %Cred Commit Message %Creset: %s %n"
CommitID : 27385d919
Remote Branch : (origin/ALPHA)
Commit Message : New branch created
It lists all remote branches including commit messages and commit IDs that are referred to by remote branches.
Use the tag @import
@import url('http://fonts.googleapis.com/css?family=Kavoon');
I think scrollViewDidEndDecelerating is the one you want. Its UIScrollViewDelegates optional method:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
Tells the delegate that the scroll view has ended decelerating the scrolling movement.
Some of these answers do work, but setting position: absolute;
and z-index: 10;
seemed pretty strong just to achieve the required effect. I found the following was all that was required, though unfortunately, I've not been able to reduce it any further.
HTML:
<div class="wrapper">
<div class="parent">
<div class="child">
...
</div>
</div>
</div>
CSS:
.wrapper {
position: relative;
z-index: 0;
}
.child {
position: relative;
z-index: -1;
}
I used this technique to achieve a bordered hover effect for image links. There's a bit more code here but it uses the concept above to show the border over the top of the image.
After experimenting for a few hours I figured it out.
<% if @user.errors.full_messages.any? %>
<% @user.errors.full_messages.each do |error_message| %>
<%= error_message if @user.errors.full_messages.first == error_message %> <br />
<% end %>
<% end %>
Even better:
<%= @user.errors.full_messages.first if @user.errors.any? %>
To identify which x86/x64 version of VC is needed:
Go to IIS Manager > Handler Mappings > right click then Edit *.php path. In the "Executable (optional)" field note in which version of Program Files is the php-cgi.exe installed.
You could use strcmp()
:
/* strcmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
char szKey[] = "apple";
char szInput[80];
do {
printf ("Guess my favourite fruit? ");
gets (szInput);
} while (strcmp (szKey,szInput) != 0);
puts ("Correct answer!");
return 0;
}
Thread
is a lower-level concept: if you're directly starting a thread, you know it will be a separate thread, rather than executing on the thread pool etc.
Task
is more than just an abstraction of "where to run some code" though - it's really just "the promise of a result in the future". So as some different examples:
Task.Delay
doesn't need any actual CPU time; it's just like setting a timer to go off in the futureWebClient.DownloadStringTaskAsync
won't take much CPU time locally; it's representing a result which is likely to spend most of its time in network latency or remote work (at the web server)Task.Run()
really is saying "I want you to execute this code separately"; the exact thread on which that code executes depends on a number of factors.Note that the Task<T>
abstraction is pivotal to the async support in C# 5.
In general, I'd recommend that you use the higher level abstraction wherever you can: in modern C# code you should rarely need to explicitly start your own thread.
If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.
If you have an instance, and you want to ensure it's not null, simply check for null:
if (value != null)
{
// it's not null.
}
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
Use Glib::ustring from glibmm.
It is the only widespread UTF-8 string container (AFAIK). While glyph (not byte) based, it has the same method signatures as std::string
so the port should be simple search and replace (just make sure that your data is valid UTF-8 before loading it into a ustring
).
You can try setting the target attribute of your form to a hidden iframe, so the page containing the form won't get reloaded.
I tried it with file uploads (which we know can't be done via AJAX), and it worked beautifully.
In case your Java class is in some package. Suppose your Java class named ABC.java
is present in com.hello.programs
, then you need to run it with the package name.
Compile it in the usual way:
C:\SimpleJavaProject\src\com\hello\programs > javac ABC.java
But to run it, you need to give the package name and then your java class name:
C:\SimpleJavaProject\src > java com.hello.programs.ABC
i would recommend using this:
background-repeat:no-repeat;
background-image: url(your file location here);
background-size:cover;(will only work with css3)
hope it helps :D
And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.
You need to do empty_set = set()
to initialize an empty set. {}
is an empty dict
.
You are getting AttributeError
because you're calling groups
on None
, which hasn't any methods.
regex.search
returning None
means the regex couldn't find anything matching the pattern from supplied string.
when using regex, it is nice to check whether a match has been made:
Result = re.search(SearchStr, htmlString)
if Result:
print Result.groups()
I got the same error and this is what helped me:
$ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents
$launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
$mysql -uroot
mysql>
you can use
reader.GetInt32(3);
to read an 32 bit int from the data reader.
If you know the type of your data I think its better to read using the Get*
methods which are strongly typed rather than just reading an object and casting.
Have you considered using
reader.GetInt32(reader.GetOrdinal(columnName))
rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.
I moved VS Code from Downloads folder to Applications, and then i was able to run code in the terminal. I guess, it might help you too.
According to documentation:
You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets.
You need to escape these three characters %_[
:
'5%' LIKE '5[%]' -- true
'5$' LIKE '5[%]' -- false
'foo_bar' LIKE 'foo[_]bar' -- true
'foo$bar' LIKE 'foo[_]bar' -- false
'foo[bar' LIKE 'foo[[]bar' -- true
'foo]bar' LIKE 'foo]bar' -- true
For micro-optimisation freaks:
if ($num % 6 != 0)
$num += 6 - $num % 6;
More evaluations of %
, but less branching/looping. :-P
You can use NetworkInterface.GetIsNetworkAvailable
method which indicates whether any network connection is available.
Try this:
bool connection = NetworkInterface.GetIsNetworkAvailable();
if (connection == true)
{
MessageBox.Show("The system is online");
}
else {
MessageBox.Show("The system is offline";
}
Replace:
Response.Write("<script language=javascript>alert('ERROR');</script>);
With
Response.Write("<script language=javascript>alert('ERROR');</script>");
In other words, you're missing a closing "
at the end of the Response.Write
statement.
It's worth mentioning that the code shown in the screenshot appears to correctly contain a closing double quote, however your best bet overall would be to use the ClientScriptManager.RegisterScriptBlock method:
var clientScript = Page.ClientScript;
clientScript.RegisterClientScriptBlock(this.GetType(), "AlertScript", "alert('ERROR')'", true);
This will take care of wrapping the script with <script>
tags and writing the script into the page for you.
In your view:
{% if user.is_authenticated %}
<p>{{ user }}</p>
{% endif %}
In you controller functions add decorator:
from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):
I did it this way. Firstly, don't push your changes or you are out of luck. Grab and install the collapse extension. Commit another dummy changeset. Then use collapse to combine the previous two changesets into one. It will prompt you for a new commit message, giving you the messages that you already have as a starting point. You have effectively changed your original commit message.
I don't like the auto-commit that git revert
does, so this might be helpful for some.
If you just want the modified files not the auto-commit, you can use --no-commit
% git revert --no-commit <commit hash>
which is the same as the -n
% git revert -n <commit hash>
i tried to reproduce your findings, but when I watched 'i' in the debugger it showed up as '6.8999999999999995' not as '6.89999999999999946709' as you wrote in the question. Can you provide steps to reproduce what you saw?
To see what the debugger shows you, you can use a DoubleConverter as in the following line of code:
Console.WriteLine(TypeDescriptor.GetConverter(i).ConvertTo(i, typeof(string)));
Hope this helps!
Edit: I guess I'm more tired than I thought, of course this is the same as formatting to the roundtrip value (as mentioned before).
In case you want jquery validate to auto pick validations on dynamically added items, you can simply remove and add validation on the whole form like below
//remove validations on entire form
$("#yourFormId")
.removeData("validator")
.removeData("unobtrusiveValidation");
//Simply add it again
$.validator
.unobtrusive
.parse("#yourFormId");
SELECT *
FROM table1, table2
This will join every row in table1 with table2 (the Cartesian product) returning all columns.
Generally speaking, it is set in the "Project Structure" dialog.
Go to File > Project Structure > SDK Location. The third field is "JDK Location" where you can set it. This will set it for the current project.
To set the default for new projects, go to File > Other Settings > Default Project Structure > SDK Location and set the "JDK Location".
Go to File > Project Structure > [Platform Settings] > SDKs. You'll need to either update you current SDK configuration to use the new directory, or define a new one and then change your project's settings to use the new one. This will set it for the current project.
To set the default for new projects, go to File > Other Settings > Structure for New Projects > [Platform Settings] > SDKs and set the SDK to use when creating a new project.
Streams are often accessed by threads that periodically empty their content and, for example, display it on the screen, send it to a socket or write it to a file. This is done for performance reasons. Flushing an output stream means that you want to stop, wait for the content of the stream to be completely transferred to its destination, and then resume execution with the stream empty and the content sent.
The solution you want is the one proposed here:
https://stackoverflow.com/a/542802/50776
Basically, you do this:
cast(floor(cast(@dateVariable as float)) as datetime)
There is a function definition in the link which will allow you to consolidate the functionality and call it anywhere (instead of having to remember it) if you wish.
Simple. Text-align: justify; (to get the elements aligned) Padding-left: ?px; (to center the elements)
Simply do this
var key = "keyOne";
var obj = {};
obj[key] = someValue;
this file starts to appear when you choose the system shows you the hidden files: $defaults write com.apple.finder AppleShowAllFiles TRUE If you run this command disapear $defaults write com.apple.finder AppleShowAllFiles FALSE Use terminal
Consider the case in which a service worker acts as an agnostic cache. Your only goal is serve the same resources that you would get from the network, but faster. Of course you can't ensure all the resources will be part of your origin (consider libraries served from CDNs, for instance). As the service worker has the potential of altering network responses, you need to guarantee you are not interested in the contents of the response, nor on its headers, nor even on the result. You're only interested on the response as a black box to possibly cache it and serve it faster.
This is what { mode: 'no-cors' }
was made for.
To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).
file://///server/path/to/file.txt
Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:
For security purposes, Mozilla applications block links to local files (and directories) from remote files.
And less directly, from Google:
Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.
The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.
try FocusManager.SetFocusedElement
FocusManager.SetFocusedElement(parentElement, txtCompanyID)
If you think the space before and after "=" is mandatory, try it as separate item in the list.
Out = subprocess.Popen(['/usr/local/bin/script', 'hostname', '=', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
SHOW ENGINE INNODB STATUS \G
Look for the Section -
TRANSACTIONS
We can use INFORMATION_SCHEMA Tables.
Useful Queries
To check about all the locks transactions are waiting for:
USE INFORMATION_SCHEMA;
SELECT * FROM INNODB_LOCK_WAITS;
A list of blocking transactions:
SELECT *
FROM INNODB_LOCKS
WHERE LOCK_TRX_ID IN (SELECT BLOCKING_TRX_ID FROM INNODB_LOCK_WAITS);
OR
SELECT INNODB_LOCKS.*
FROM INNODB_LOCKS
JOIN INNODB_LOCK_WAITS
ON (INNODB_LOCKS.LOCK_TRX_ID = INNODB_LOCK_WAITS.BLOCKING_TRX_ID);
A List of locks on particular table:
SELECT * FROM INNODB_LOCKS
WHERE LOCK_TABLE = db_name.table_name;
A list of transactions waiting for locks:
SELECT TRX_ID, TRX_REQUESTED_LOCK_ID, TRX_MYSQL_THREAD_ID, TRX_QUERY
FROM INNODB_TRX
WHERE TRX_STATE = 'LOCK WAIT';
Reference - MySQL Troubleshooting: What To Do When Queries Don't Work, Chapter 6 - Page 96.
The gradle guys are doing their best to solve all (y)our problems ;-). They recently (since 1.9) added a new feature (incubating): the "build init" plugin.
The basic problem is that the JSON encoder json.dumps()
only knows how to serialize a limited set of object types by default, all built-in types. List here: https://docs.python.org/3.3/library/json.html#encoders-and-decoders
One good solution would be to make your class inherit from JSONEncoder
and then implement the JSONEncoder.default()
function, and make that function emit the correct JSON for your class.
A simple solution would be to call json.dumps()
on the .__dict__
member of that instance. That is a standard Python dict
and if your class is simple it will be JSON serializable.
class Foo(object):
def __init__(self):
self.x = 1
self.y = 2
foo = Foo()
s = json.dumps(foo) # raises TypeError with "is not JSON serializable"
s = json.dumps(foo.__dict__) # s set to: {"x":1, "y":2}
The above approach is discussed in this blog posting:
I had the same issue, so I first SSH into the server to confirm that I able to log in to the server by using the command:
ssh -i /Users/Desktop/mypemfile.pem [email protected]
Then in New Terminal
I copied a small file to the server by using SCP, to make sure I am able to make a connection:
scp -i /Users/Desktop/mypemfile.pem /Users/Desktop/test.file [email protected]:/home/user/test/
Then In the same new terminal, I tried running rsync:
rsync -avz -e "ssh -i /Users/Desktop/mypemfile.pem" /Users/Desktop/backup/image.img.gz [email protected]:
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
You can use inline css :
<td style = "text-align: center;">
I can't believe all of the people that say using it always is a "best practice" and such.
Use "this" when there is ambiguity, as in Corey's example or when you need to pass the object as a parameter, as in Ryan's example. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.
EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - for declaring indexers
EDIT: @Juan: Huh, I don't see any inconsistency in my statements - there are 3 instances when I would use the "this" keyword (as documented in the C# documentation), and those are times when you actually need it. Sticking "this" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.
There is the easy way
HTML:
<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]" />y
<input type="checkbox" name="test[]" />z
<button type="button" id="submit">Submit</button>
JQUERY:
$("#submit").on("click",function(){
if (($("input[name*='test']:checked").length)<=0) {
alert("You must check at least 1 box");
}
return true;
});
For this you not need any plugin. Enjoy;)
This will compare full string XMLs (reformatting them on the way). It makes it easy to work with your IDE (IntelliJ, Eclipse), cos you just click and visually see the difference in the XML files.
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
import org.w3c.dom.Element;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.io.StringReader;
import static org.apache.xml.security.Init.init;
import static org.junit.Assert.assertEquals;
public class XmlUtils {
static {
init();
}
public static String toCanonicalXml(String xml) throws InvalidCanonicalizerException, ParserConfigurationException, SAXException, CanonicalizationException, IOException {
Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
byte canonXmlBytes[] = canon.canonicalize(xml.getBytes());
return new String(canonXmlBytes);
}
public static String prettyFormat(String input) throws TransformerException, ParserConfigurationException, IOException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException {
InputSource src = new InputSource(new StringReader(input));
Element document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
Boolean keepDeclaration = input.startsWith("<?xml");
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);
return writer.writeToString(document);
}
public static void assertXMLEqual(String expected, String actual) throws ParserConfigurationException, IOException, SAXException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {
String canonicalExpected = prettyFormat(toCanonicalXml(expected));
String canonicalActual = prettyFormat(toCanonicalXml(actual));
assertEquals(canonicalExpected, canonicalActual);
}
}
I prefer this to XmlUnit because the client code (test code) is cleaner.
The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.
From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/
the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.
var wordOccurrences = words
.GroupBy(w => w)
.Select(intermediate => new
{
Word = intermediate.Key,
Frequency = intermediate.Sum(w => 1)
})
.Where(w => w.Frequency > 10)
.OrderBy(w => w.Frequency);
For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx
I've seen occasional problems with Eclipse forgetting that built-in classes (including Object
and String
) exist. The way I've resolved them is to:
This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.
You can try and do this:
tryTrans = string.maketrans(",!", " ")
str = "This is a string, with words!"
str = str.translate(tryTrans)
listOfWords = str.split()
I think what you are looking for is a utility which enables you to save a complete page opened in your browser into a png file. Most probably you are looking for a utility like commandlineprint2.
After installing the extension, you just need to type the command:
firefox -print http://google.com -printfile ~/foo.png
Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.
HTML sample:
<body>
<ul class="nav-tabs">
<li><a id="btn-tab-business" class="btn-tab nav-tab-selected" onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
<li><a id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
<li><a id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
</ul>
</body>
CSS sample:
.nav-tabs{
position: relative;
padding-bottom: 50px;
}
.nav-tabs li {
display: inline-block;
position: absolute;
list-style: none;
}
.nav-tabs li:first-child{
top: 0px;
left: 0px;
}
.nav-tabs li:last-child{
top: 0px;
right: 0px;
}
.nav-tabs li:nth-child(2){
top: 0px;
left: 50%;
transform: translate(-50%, 0%);
}
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
Does it have to be String.Format
?
This looks like a job for String.Padleft
myString=myString.PadLeft(3, '0');
Or, if you are converting direct from an int:
myInt.toString("D3");
People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.
Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.
Here's a summary of what we found...
Conclusion
SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.
You hide Bootstrap modals with:
$('#modal').modal('hide');
Saying $().hide()
makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.
You can use the function toprettyxml()
from xml.dom.minidom
in order to do that:
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
The idea is to print your Element
in a string, parse it using minidom and convert it again in XML using the toprettyxml
function.
Source: http://pymotw.com/2/xml/etree/ElementTree/create.html
Try this, maybe can help, it do what you want:
var listArray = new ListArray();_x000D_
let element = {name: 'Edy', age: 27, country: "Brazil"};_x000D_
let element2 = {name: 'Marcus', age: 27, country: "Brazil"};_x000D_
listArray.push(element);_x000D_
listArray.push(element2);_x000D_
_x000D_
console.log(listArray.array)
_x000D_
<script src="https://marcusvi200.github.io/list-array/script/ListArray.js"></script>
_x000D_
simple:
Tags are expected to always point at the same version of a project, while heads are expected to advance as development progresses.
Its very simple, use this one line code dataSheet.autoSizeColumn(0)
or give the number of column in bracket dataSheet.autoSizeColumn(cell number )
I had this problem, and since overriding the onKeyDown() method didn't accomplish anything because of the underlying android system didn't call this method, I solved this with overriding onBackPressed(), and I had a boolean value set there to false, because I pressed back, let me show you what I mean in code:
import android.util.Log;
public class HomeButtonActivity extends Activity {
boolean homePressed = false;
// override onCreate() here.
@Override
public void onBackPressed() {
homePressed = false; // simply set homePressed to false
}
@Overide
public void onResume() {
super.onResume();
homePressed = true; // default: other wise onBackPressed will set it to false
}
@Override
public void onPause() {
super.onPause();
if(homePressed) { Log.i("homePressed", "yay"); }
}
So the reason why this worked is because the only way to navigate outside this activity is by pressing back or home so if back was pressed then i know the cause wasn't home, but otherwise the cause was home, therefore i set the default boolean value for homePressed to be true. However this will only work with a single activity instance in your application because otherwise you have more possibilities to cause the onPause() method to be called.
You can't resolve a promise with multiple properties just like you can't return multiple values from a function. A promise conceptually represents a value over time so while you can represent composite values you can't put multiple values in a promise.
A promise inherently resolves with a single value - this is part of how Q works, how the Promises/A+ spec works and how the abstraction works.
The closest you can get is use Q.spread
and return arrays or use ES6 destructuring if it's supported or you're willing to use a transpilation tool like BabelJS.
As for passing context down a promise chain please refer to Bergi's excellent canonical on that.
I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference.
A valid JSON always starts with either curly braces {
or square brackets [
, nothing else.
{
will start an object
:{ "key": value, "another key": value }
Hint: although javascript accepts single quotes
'
, JSON only takes double ones"
.
[
will start an array
:[value, value]
Hint: spaces among elements are always ignored by any JSON parser.
value
is an object
, array
, string
, number
, bool
or null
:So yeah, ["a", "b"]
is a perfectly valid JSON, like you could try on the link Manish pointed.
Here are a few extra valid JSON examples, one per block:
{}
[0]
{"__comment": "json doesn't accept comments and you should not be commenting even in this way", "avoid!": "also, never add more than one key per line, like this"}
[{ "why":null} ]
{
"not true": [0, false],
"true": true,
"not null": [0, 1, false, true, {
"obj": null
}, "a string"]
}
Isn't neither localStorage or httpOnly cookie acceptable? In regards to a compromised 3rd party library, the only solution I know of that will reduce / prevent sensitive information from being stolen would be enforced Subresource Integrity.
Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.
As long as the compromised 3rd party library is active on your website, a keylogger can start collecting info like username, password, and whatever else you input into the site.
An httpOnly cookie will prevent access from another computer but will do nothing to prevent the hacker from manipulating the user's computer.
Add the following code within the constructor like so:
public Calculator() {
initComponents();
//the code to be added this.setIconImage(newImageIcon(getClass().getResource("color.png")).getImage()); }
Change "color.png" to the file name of the picture you want to insert. Drag and drop this picture onto the package (under Source Packages) of your project.
Run your project.
You just missed an initialization step I think.
You can see what fonts you have available with the command windowsFonts()
. For example mine looks like this when I started looking at this:
> windowsFonts()
$serif
[1] "TT Times New Roman"
$sans
[1] "TT Arial"
$mono
[1] "TT Courier New"
After intalling the package extraFont and running font_import
like this (it took like 5 minutes):
library(extrafont)
font_import()
loadfonts(device = "win")
I had many more available - arguable too many, certainly too many to list here.
Then I tried your code:
library(ggplot2)
library(extrafont)
loadfonts(device = "win")
a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text=element_text(size=16, family="Comic Sans MS"))
print(a)
yielding this:
You can find the name of a font you need for the family
parameter of element_text
with the following code snippet:
> names(wf[wf=="TT Times New Roman"])
[1] "serif"
And then:
library(ggplot2)
library(extrafont)
loadfonts(device = "win")
a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text=element_text(size=16, family="serif"))
print(a)
Based on https://developer.android.com/studio/releases/gradle-plugin.html ...
The following table lists which version of Gradle is required for each version of the Android plugin for Gradle. For the best performance, you should use the latest possible version of both Gradle and the Android plugin.
So, the Plugin version with Required Gradle version should be match.
I had the same problem today. Try it!
sudo chown -R [yourgroup] /home/[youruser]/.composer/cache/repo/https---packagist.org/
sudo chown -R [yourgroup] /home/[youruser]/.composer/cache/files/
This works fine for me:
while True:
answer = input('Do you want to continue?:')
if answer.lower().startswith("y"):
print("ok, carry on then")
elif answer.lower().startswith("n"):
print("sayonara, Robocop")
exit()
edit: use input
in python 3.2 instead of raw_input
To put it simple you will need to follow the step.
Assuming the List Name is Test and it has only one Field "Title" here is the code.
using (SPSite oSite=new SPSite("http://mysharepoint"))
{
using (SPWeb oWeb=oSite.RootWeb)
{
SPList oList = oWeb.Lists["Test"];
SPListItem oSPListItem = oList.Items.Add();
oSPListItem["Title"] = "Hello SharePoint";
oSPListItem.Update();
}
}
Note that you need to run this application in the Same server where the SharePoint is installed.
You dont need to create a Custom Class for Custom Content Type
All these answers are superficially correct. However, the proper answer is
apropos disk # And pray your admin maintains the whatis database
because asking questions the answers of which lay at your fingertips in the manual wastes everybody's time.
You can achieve what you are trying to do, using a Stored Procedure
which returns a query result. Views
are not suitable / developed for operations like this one.
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
Here's a one-module Python replacement for perl -p
:
# Provide compatibility with `perl -p`
# Usage:
#
# python -mloop_over_stdin_lines '<program>'
# In, `<program>`, use the variable `line` to read and change the current line.
# Example:
#
# python -mloop_over_stdin_lines 'line = re.sub("pattern", "replacement", line)'
# From the perlrun documentation:
#
# -p causes Perl to assume the following loop around your
# program, which makes it iterate over filename arguments
# somewhat like sed:
#
# LINE:
# while (<>) {
# ... # your program goes here
# } continue {
# print or die "-p destination: $!\n";
# }
#
# If a file named by an argument cannot be opened for some
# reason, Perl warns you about it, and moves on to the next
# file. Note that the lines are printed automatically. An
# error occurring during printing is treated as fatal. To
# suppress printing use the -n switch. A -p overrides a -n
# switch.
#
# "BEGIN" and "END" blocks may be used to capture control
# before or after the implicit loop, just as in awk.
#
import re
import sys
for line in sys.stdin:
exec(sys.argv[1], globals(), locals())
try:
print line,
except:
sys.exit('-p destination: $!\n')
This way:
$instance = new Functions(); // create an instance (object) of functions class
$instance->filter($data); // now call it
Use CSS, it makes for much easier management of the style itself.
I think it is important to post this quote:
Git for Windows supports four levels of configuration. At the lowest level is the machine specific configuration settings known as "portable" and lives a "%ProgramData%\Git\config". One priority level us the installation specific configuration settings known as "system", which live at "\mingw64\etc\gitconfig". Both of these configuration file, generally require elevated privileges to modify.
Starting with the use specific values known as "global" configuration, which can be found at "%UserProfile%.gitconfig", we find the "user editable" configuration files. The highest priority configuration settings are in the "local" configuration, which can usually be found at ".git\config".
It see the recommendation in the blog linked is to modify the "system" or "installation" specific configuration settings, which is fine but users should expect that other installations of Git would not absorb said settings. If you want machine wide settings, use the "portable" configuration file, otherwise choose the "global" or "local" configuration files.
Hopefully, people find this information useful.
Similar problem here: Given a string and a list of keywords, detect which, if any, of the keywords are contained in the string.
Recommendations from this thread suggest stringr
's str_detect
and grepl
. Here are the benchmarks from the microbenchmark
package:
Using
map_keywords = c("once", "twice", "few")
t = "yes but only a few times"
mapper1 <- function (x) {
r = str_detect(x, map_keywords)
}
mapper2 <- function (x) {
r = sapply(map_keywords, function (k) grepl(k, x, fixed = T))
}
and then
microbenchmark(mapper1(t), mapper2(t), times = 5000)
we find
Unit: microseconds
expr min lq mean median uq max neval
mapper1(t) 26.401 27.988 31.32951 28.8430 29.5225 2091.476 5000
mapper2(t) 19.289 20.767 24.94484 23.7725 24.6220 1011.837 5000
As you can see, over 5,000 iterations of the keyword search using str_detect
and grepl
over a practical string and vector of keywords, grepl
performs quite a bit better than str_detect
.
The outcome is the boolean vector r
which identifies which, if any, of the keywords are contained in the string.
Therefore, I recommend using grepl
to determine if any keywords are in a string.
That should work if the dates you saved in the DB are without time (just year, month, day).
Chances are that the dates you saved were new Date()
, which includes the time components. To query those times you need to create a date range that includes all moments in a day.
db.posts.find({ //query today up to tonight
created_on: {
$gte: new Date(2012, 7, 14),
$lt: new Date(2012, 7, 15)
}
})
So the 50x50 size is a good choice.
Disable pointer events in the first line of your callback, and then resume them on the last line.
element.on('click', function() {
element.css('pointer-events', 'none');
//do all of your stuff
element.css('pointer-events', 'auto');
};
I found this to be a more elegant solution, without flex:
.wrapper {
overflow: hidden;
}
.wrapper img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* height: 100%; */ /* optional */
}
Slight update to cumul's solution.
The function upperFirstAll doesn't work properly if there is more than one space between words. Replace the regular expression for this one to solve it:
$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)+(.)/g,
Use QString::arg()
for the same effect.
OK, I am a Ruby noob, but I did get this fixed slightly differently than the answers here, so hopefully this helps someone else (tl;dr: I used RVM to switch the system Ruby version to the same one expected by rubygems).
First off, listing all Rubies as mentioned by Eimantas was a great starting point:
> which -a ruby
/opt/local/bin/ruby
/Users/Brian/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
/Users/Brian/.rvm/bin/ruby
/usr/bin/ruby
/opt/local/bin/ruby
The default Ruby instance in use by the system appeared to be 1.8.7:
> ruby -v
ruby 1.8.7 (2010-06-23 patchlevel 299) [i686-darwin10]
while the version in use by Rubygems was the 1.9.2 version managed by RVM:
> gem env | grep 'RUBY EXECUTABLE'
- RUBY EXECUTABLE: /Users/Brian/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
So that was definitely the issue. I don't actively use Ruby myself (this is simply a dependency of a build system script I'm trying to run) so I didn't care which version was active for other purposes. Since rubygems expected the 1.9.2 that was already managed by RVM, I simply used RVM to switch the system to use the 1.9.2 version as the default:
> rvm use 1.9.2
Using /Users/Brian/.rvm/gems/ruby-1.9.2-p290
> ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.3.0]
After doing that my "no such file" issue went away and my script started working.
Use android.support.v4.app
for FragmentManager & FragmentTransaction in your code, it has worked for me.
DetailsFragment detailsFragment = new DetailsFragment();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.details,detailsFragment);
fragmentTransaction.commit();
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to the <div>
this css:
display:flex;
align-items:center;
justify-content:center;
Live Example:
.img_thumb {_x000D_
float: left;_x000D_
height: 120px;_x000D_
margin-bottom: 5px;_x000D_
margin-left: 9px;_x000D_
position: relative;_x000D_
width: 147px;_x000D_
background-color: rgba(0, 0, 0, 0.5);_x000D_
border-radius: 3px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
<a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
<img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
</a>_x000D_
</div>
_x000D_
Change 1D array into 2D array without using Numpy.
l = [i for i in range(1,21)]
part = 3
new = []
start, end = 0, part
while end <= len(l):
temp = []
for i in range(start, end):
temp.append(l[i])
new.append(temp)
start += part
end += part
print("new values: ", new)
# for uneven cases
temp = []
while start < len(l):
temp.append(l[start])
start += 1
new.append(temp)
print("new values for uneven cases: ", new)
do you want to write code for that or just use command-line feature 'command redirection' as follows:
app.exe >> output.txt
as demonstrated here: http://discomoose.org/2006/05/01/output-redirection-to-a-file-from-the-windows-command-line/ (Archived at archive.org)
EDIT: link dead, here's another example: http://pcsupport.about.com/od/commandlinereference/a/redirect-command-output-to-file.htm
I don't think what your asking is possible.
Basically, adding a class is the only way to accomplish this that I am aware of.
Hey how about to copy all fields, change one of them to the same value + something else.
INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, Event_ID+"155"
FROM Table
WHERE Event_ID = "120"
??????????
As many have already answered, mounting host volumes during the build is not possible. I just would like to add docker-compose
way, I think it'll be nice to have, mostly for development/testing usage
Dockerfile
FROM node:10
WORKDIR /app
COPY . .
RUN npm ci
CMD sleep 999999999
docker-compose.yml
version: '3'
services:
test-service:
image: test/image
build:
context: .
dockerfile: Dockerfile
container_name: test
volumes:
- ./export:/app/export
- ./build:/app/build
And run your container by docker-compose up -d --build
I found the answer to this problem here
Just do
mb_convert_encoding($data['name'], 'UTF-8', 'UTF-8');
Similar to older answers, but a bit simpler, without the lambda:
filter_kwargs = {
'field_a': 123,
'field_b__in': (3, 4, 5, ),
}
To filter these two conditions using OR
:
Item.objects.filter(Q(field_a=123) | Q(field_b__in=(3, 4, 5, ))
To get the same result programmatically:
list_of_Q = [Q(**{key: val}) for key, val in filter_kwargs.items()]
Item.objects.filter(reduce(operator.or_, list_of_Q))
(broken in two lines here, for clarity)
operator
is in standard library: import operator
From docstring:
or_(a, b) -- Same as a | b.
For Python3, reduce
is not a builtin any more but is still in the standard library: from functools import reduce
P.S.
Don't forget to make sure list_of_Q
is not empty - reduce()
will choke on empty list, it needs at least one element.
Just use the below code. It will shadow surround the entire DIV
-webkit-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
-moz-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
Hope this will work
I have try twitter geo api, failed.
Google map api, failed, so far, no way you can get city limit by any api.
twitter api geo endpoint will NOT give you city boundary,
what they provide you is ONLY bounding box with 5 point(lat, long)
A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.
Whereas a GridLayout is a layout that places its children in a rectangular grid.
It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.
I think you are looking for below method:
var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
var friends= db.Friends.Where(f=>idList.Contains(f.ID));
friends.ForEachAsync(a=>a.msgSentBy='1234');
await db.SaveChangesAsync();
}
This should be the efficient way of handling this.
Database access on main thread locking the UI is the error, like Dale said.
--EDIT 2--
Since many people may come across this answer... The best option nowadays, generally speaking, is Kotlin Coroutines. Room now supports it directly (currently in beta). https://kotlinlang.org/docs/reference/coroutines-overview.html https://developer.android.com/jetpack/androidx/releases/room#2.1.0-beta01
--EDIT 1--
For people wondering... You have other options. I recommend taking a look into the new ViewModel and LiveData components. LiveData works great with Room. https://developer.android.com/topic/libraries/architecture/livedata.html
Another option is the RxJava/RxAndroid. More powerful but more complex than LiveData. https://github.com/ReactiveX/RxJava
--Original answer--
Create a static nested class (to prevent memory leak) in your Activity extending AsyncTask.
private static class AgentAsyncTask extends AsyncTask<Void, Void, Integer> {
//Prevent leak
private WeakReference<Activity> weakActivity;
private String email;
private String phone;
private String license;
public AgentAsyncTask(Activity activity, String email, String phone, String license) {
weakActivity = new WeakReference<>(activity);
this.email = email;
this.phone = phone;
this.license = license;
}
@Override
protected Integer doInBackground(Void... params) {
AgentDao agentDao = MyApp.DatabaseSetup.getDatabase().agentDao();
return agentDao.agentsCount(email, phone, license);
}
@Override
protected void onPostExecute(Integer agentsCount) {
Activity activity = weakActivity.get();
if(activity == null) {
return;
}
if (agentsCount > 0) {
//2: If it already exists then prompt user
Toast.makeText(activity, "Agent already exists!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(activity, "Agent does not exist! Hurray :)", Toast.LENGTH_LONG).show();
activity.onBackPressed();
}
}
}
Or you can create a final class on its own file.
Then execute it in the signUpAction(View view) method:
new AgentAsyncTask(this, email, phone, license).execute();
In some cases you might also want to hold a reference to the AgentAsyncTask in your activity so you can cancel it when the Activity is destroyed. But you would have to interrupt any transactions yourself.
Also, your question about the Google's test example... They state in that web page:
The recommended approach for testing your database implementation is writing a JUnit test that runs on an Android device. Because these tests don't require creating an activity, they should be faster to execute than your UI tests.
No Activity, no UI.
In Android, application-level meta data is accessed through the Context
reference, which an activity is a descendant of.
For example, you can get the source directory via the getApplicationInfo().sourceDir
property.
There are methods for other folders as well (assets directory, data dir, database dir, etc.).
Numpy solution. We will shuffle the whole dataset first (df.sample(frac=1, random_state=42)
) and then split our data set into the following parts:
In [305]: train, validate, test = \
np.split(df.sample(frac=1, random_state=42),
[int(.6*len(df)), int(.8*len(df))])
In [306]: train
Out[306]:
A B C D E
0 0.046919 0.792216 0.206294 0.440346 0.038960
2 0.301010 0.625697 0.604724 0.936968 0.870064
1 0.642237 0.690403 0.813658 0.525379 0.396053
9 0.488484 0.389640 0.599637 0.122919 0.106505
8 0.842717 0.793315 0.554084 0.100361 0.367465
7 0.185214 0.603661 0.217677 0.281780 0.938540
In [307]: validate
Out[307]:
A B C D E
5 0.806176 0.008896 0.362878 0.058903 0.026328
6 0.145777 0.485765 0.589272 0.806329 0.703479
In [308]: test
Out[308]:
A B C D E
4 0.521640 0.332210 0.370177 0.859169 0.401087
3 0.333348 0.964011 0.083498 0.670386 0.169619
[int(.6*len(df)), int(.8*len(df))]
- is an indices_or_sections
array for numpy.split().
Here is a small demo for np.split()
usage - let's split 20-elements array into the following parts: 80%, 10%, 10%:
In [45]: a = np.arange(1, 21)
In [46]: a
Out[46]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
In [47]: np.split(a, [int(.8 * len(a)), int(.9 * len(a))])
Out[47]:
[array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]),
array([17, 18]),
array([19, 20])]
Quite amazing how all answers talk about IIS, as if that were the only web server that mattered. Even back in 2010 when the question was asked, Apache had between 60% and 70% of the market share. Anyway,
min(serverMaximumSize, clientMaximumSize)
.Here are the POST body sizes for some of the more popular HTTP servers:
You need to pass IP/hostname of the rempote machine in the connection string.
import java.sql.*;
import javax.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String url = "jdbc:mysql://localhost:3306/mydb";
Class.forName ("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection (url,"root"," ");
System.out.println ("Database connection established");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
There is actually a way to do this with html only. Just sets:
<img src="#" width height="50%">
Just use your window with the WindowsInteropHelper class:
// ... Window myWindow = get your Window instance...
IntPtr windowHandle = new WindowInteropHelper(myWindow).Handle;
Right now, you're asking for the Application's main window, of which there will always be one. You can use this same technique on any Window, however, provided it is a System.Windows.Window derived Window class.
for me $('#element').val('...').change()
is the best way.
This should do what you want.
public function up()
{
DB::table('user')->insert(array('username'=>'dude', 'password'=>'z19pers!'));
}
It might be better to use communicate
:
from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]
"Better", because of this warning:
Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.
PHP manual has a good read on the question here.
The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.
Copy of one list into second is quite simple , you can do that as below:-
ArrayList<List1> list1= new ArrayList<>();
ArrayList<List1> list2= new ArrayList<>();
//this will your copy your list1 into list2
list2.addAll(list1);
Try this:
File\Other Settings\Preferences
for New Projects\Teminal\Start Directory
eldNew <- eld[-14,]
See ?"["
for a start ...
For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.
(emphasis added)
edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?
edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame
...
Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame
This is an example :
for(var i=0; i<=3; i++) {
window['p'+i] = "hello " + i;
}
alert(p0); // hello 0
alert(p1); // hello 1
alert(p2); // hello 2
alert(p3); // hello 3
Another example :
var myVariable = 'coco';
window[myVariable] = 'riko';
alert(coco); // display : riko
So, the value "coco" of myVariable becomes a variable coco.
Because all the variables in the global scope are properties of the Window object.
ANSI (aka Windows-1252/WinLatin1) is a character encoding of the Latin alphabet, fairly similar to ISO-8859-1. You may want to take a look of it at Wikipedia.
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
openpyxl
: https://openpyxl.readthedocs.io/en/stable/df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx
Set-ExecutionPolicy RemoteSigned
Run this python script on your powershell script helloworld.py
:
# -*- coding: iso-8859-1 -*-
import subprocess, sys
p = subprocess.Popen(["powershell.exe",
"C:\\Users\\USER\\Desktop\\helloworld.ps1"],
stdout=sys.stdout)
p.communicate()
This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.
C:\Users\MacEwin\Desktop>python helloworld.py
Hello World
Here is my solution, I was using Thread and Event:
import subprocess
from threading import Thread, Event
def kill_on_timeout(done, timeout, proc):
if not done.wait(timeout):
proc.kill()
def exec_command(command, timeout):
done = Event()
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
watcher = Thread(target=kill_on_timeout, args=(done, timeout, proc))
watcher.daemon = True
watcher.start()
data, stderr = proc.communicate()
done.set()
return data, stderr, proc.returncode
In action:
In [2]: exec_command(['sleep', '10'], 5)
Out[2]: ('', '', -9)
In [3]: exec_command(['sleep', '10'], 11)
Out[3]: ('', '', 0)
You are modifying the list book_shop.values()[i]
, which is not getting updated in the dictionary. Whenever you call the values()
method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.
From Python Cookbook v.30
def myfun():
return 1, 2, 3
a, b, c = myfun()
Although it looks like
myfun()
returns multiple values, atuple
is actually being created. It looks a bit peculiar, but it’s actually the comma that forms a tuple, not the parentheses
So yes, what's going on in Python is an internal transformation from multiple comma separated values to a tuple and vice-versa.
Though there's no equivalent in java you can easily create this behaviour using array
's or some Collection
s like List
s:
private static int[] sumAndRest(int x, int y) {
int[] toReturn = new int[2];
toReturn[0] = x + y;
toReturn[1] = x - y;
return toReturn;
}
Executed in this way:
public static void main(String[] args) {
int[] results = sumAndRest(10, 5);
int sum = results[0];
int rest = results[1];
System.out.println("sum = " + sum + "\nrest = " + rest);
}
result:
sum = 15
rest = 5
Use SVD or QR-decomposition to calculate exact solution in real or complex number fields:
numpy.linalg.svd numpy.linalg.qr
If your tiles are not in your bundle, either copied from the bundle or downloaded from the internet you can get the directory like this
NSString *documentdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *tileDirectory = [documentdir stringByAppendingPathComponent:@"xxxx/Tiles"];
NSLog(@"Tile Directory: %@", tileDirectory);
@since 2.10
version we can use JsonMapper.Builder and accepted answer could look like:
JsonMapper mapper = JsonMapper.builder()
.visibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
.visibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
.visibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)
.visibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.NONE)
.build();
This boils down to that the managed bean instance itself could not be found by exactly that identifier (managed bean name) in EL like so #{bean}
.
Identifying the cause can be broken down into three steps:
a. Who's managing the bean?
b. What's the (default) managed bean name?
c. Where's the backing bean class?
First step would be checking which bean management framework is responsible for managing the bean instance. Is it CDI via @Named
? Or is it JSF via @ManagedBean
? Or is it Spring via @Component
? Can you make sure that you're not mixing multiple bean management framework specific annotations on the very same backing bean class? E.g. @Named @ManagedBean
, @Named @Component
, or @ManagedBean @Component
. This is wrong. The bean must be managed by at most one bean management framework and that framework must be properly configured. If you already have no idea which to choose, head to Backing beans (@ManagedBean) or CDI Beans (@Named)? and Spring JSF integration: how to inject a Spring component/service in JSF managed bean?
In case it's CDI who's managing the bean via @Named
, then you need to make sure of the following:
CDI 1.0 (Java EE 6) requires an /WEB-INF/beans.xml
file in order to enable CDI in WAR. It can be empty or it can have just the following content:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
CDI 1.1 (Java EE 7) without any beans.xml
, or an empty beans.xml
file, or with the above CDI 1.0 compatible beans.xml
will behave the same as CDI 1.0. When there's a CDI 1.1 compatible beans.xml
with an explicit version="1.1"
, then it will by default only register @Named
beans with an explicit CDI scope annotation such as @RequestScoped
, @ViewScoped
, @SessionScoped
, @ApplicationScoped
, etc. In case you intend to register all beans as CDI managed beans, even those without an explicit CDI scope, use the below CDI 1.1 compatible /WEB-INF/beans.xml
with bean-discovery-mode="all"
set (the default is bean-discovery-mode="annotated"
).
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>
When using CDI 1.1+ with bean-discovery-mode="annotated"
(default), make sure that you didn't accidentally import a JSF scope such as javax.faces.bean.RequestScoped
instead of a CDI scope javax.enterprise.context.RequestScoped
. Watch out with IDE autocomplete.
When using Mojarra 2.3.0-2.3.2 and CDI 1.1+ with bean-discovery-mode="annotated"
(default), then you need to upgrade Mojarra to 2.3.3 or newer due to a bug. In case you can't upgrade, then you need either to set bean-discovery-mode="all"
in beans.xml
, or to put the JSF 2.3 specific @FacesConfig
annotation on an arbitrary class in the WAR (generally some sort of an application scoped startup class).
When using JSF 2.3 on a Servlet 4.0 container with a web.xml
declared conform Servlet 4.0, then you need to explicitly put the JSF 2.3 specific @FacesConfig
annotation on an arbitrary class in the WAR (generally some sort of an application scoped startup class). This is not necessary in Servlet 3.x.
Non-Java EE containers like Tomcat and Jetty doesn't ship with CDI bundled. You need to install it manually. It's a bit more work than just adding the library JAR(s). For Tomcat, make sure that you follow the instructions in this answer: How to install and use CDI on Tomcat?
Your runtime classpath is clean and free of duplicates in CDI API related JARs. Make sure that you're not mixing multiple CDI implementations (Weld, OpenWebBeans, etc). Make sure that you don't provide another CDI or even Java EE API JAR file along webapp when the target container already bundles CDI API out the box.
If you're packaging CDI managed beans for JSF views in a JAR, then make sure that the JAR has at least a valid /META-INF/beans.xml
(which can be kept empty).
In case it's JSF who's managing the bean via the since 2.3 deprecated @ManagedBean
, and you can't migrate to CDI, then you need to make sure of the following:
The faces-config.xml
root declaration is compatible with JSF 2.0. So the XSD file and the version
must at least specify JSF 2.0 or higher and thus not 1.x.
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
For JSF 2.1, just replace 2_0
and 2.0
by 2_1
and 2.1
respectively.
If you're on JSF 2.2 or higher, then make sure you're using xmlns.jcp.org
namespaces instead of java.sun.com
over all place.
<faces-config
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
For JSF 2.3, just replace 2_2
and 2.2
by 2_3
and 2.3
respectively.
You didn't accidentally import javax.annotation.ManagedBean
instead of javax.faces.bean.ManagedBean
. Watch out with IDE autocomplete, Eclipse is known to autosuggest the wrong one as first item in the list.
You didn't override the @ManagedBean
by a JSF 1.x style <managed-bean>
entry in faces-config.xml
on the very same backing bean class along with a different managed bean name. This one will have precedence over @ManagedBean
. Registering a managed bean in faces-config.xml
is not necessary since JSF 2.0, just remove it.
Your runtime classpath is clean and free of duplicates in JSF API related JARs. Make sure that you're not mixing multiple JSF implementations (Mojarra and MyFaces). Make sure that you don't provide another JSF or even Java EE API JAR file along webapp when the target container already bundles JSF API out the box. See also "Installing JSF" section of our JSF wiki page for JSF installation instructions. In case you intend to upgrade container-bundled JSF from the WAR on instead of in container itself, make sure that you've instructed the target container to use WAR-bundled JSF API/impl.
If you're packaging JSF managed beans in a JAR, then make sure that the JAR has at least a JSF 2.0 compatible /META-INF/faces-config.xml
. See also How to reference JSF managed beans which are provided in a JAR file?
If you're actually using the jurassic JSF 1.x, and you can't upgrade, then you need to register the bean via <managed-bean>
in faces-config.xml
instead of @ManagedBean
. Don't forget to fix your project build path as such that you don't have JSF 2.x libraries anymore (so that the @ManagedBean
annotation wouldn't confusingly successfully compile).
In case it's Spring who's managing the bean via @Component
, then you need to make sure of the following:
Spring is being installed and integrated as per its documentation. Importantingly, you need to at least have this in web.xml
:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
And this in faces-config.xml
:
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
(above is all I know with regard to Spring — I don't do Spring — feel free to edit/comment with other probable Spring related causes; e.g. some XML configuration related trouble)
In case it's a repeater component who's managing the (nested) bean via its var
attribute (e.g. <h:dataTable var="item">
, <ui:repeat var="item">
, <p:tabView var="item">
, etc) and you actually got a "Target Unreachable, identifier 'item' resolved to null", then you need to make sure of the following:
The #{item}
is not referenced in binding
attribtue of any child component. This is incorrect as binding
attribute runs during view build time, not during view render time. Moreover, there's physically only one component in the component tree which is simply reused during every iteration round. In other words, you should actually be using binding="#{bean.component}"
instead of binding="#{item.component}"
. But much better is to get rid of component bining to bean altogether and investigate/ask the proper approach for the problem you thought to solve this way. See also How does the 'binding' attribute work in JSF? When and how should it be used?
Second step would be checking the registered managed bean name. JSF and Spring use conventions conform JavaBeans specification while CDI has exceptions depending on CDI impl/version.
A FooBean
backing bean class like below,
@Named
public class FooBean {}
will in all bean management frameworks have a default managed bean name of #{fooBean}
, as per JavaBeans specification.
A FOOBean
backing bean class like below,
@Named
public class FOOBean {}
whose unqualified classname starts with at least two capitals will in JSF and Spring have a default managed bean name of exactly the unqualified class name #{FOOBean}
, also conform JavaBeans specificiation. In CDI, this is also the case in Weld versions released before June 2015, but not in Weld versions released after June 2015 (2.2.14/2.3.0.B1/3.0.0.A9) nor in OpenWebBeans due to an oversight in CDI spec. In those Weld versions and in all OWB versions it is only with the first character lowercased #{fOOBean}
.
If you have explicitly specified a managed bean name foo
like below,
@Named("foo")
public class FooBean {}
or equivalently with @ManagedBean(name="foo")
or @Component("foo")
, then it will only be available by #{foo}
and thus not by #{fooBean}
.
Third step would be doublechecking if the backing bean class is at the right place in the built and deployed WAR file. Make sure that you've properly performed a full clean, rebuild, redeploy and restart of the project and server in case you was actually busy writing code and impatiently pressing F5 in the browser. If still in vain, let the build system produce a WAR file, which you then extract and inspect with a ZIP tool. The compiled .class
file of the backing bean class must reside in its package structure in /WEB-INF/classes
. Or, when it's packaged as part of a JAR module, the JAR containing the compiled .class
file must reside in /WEB-INF/lib
and thus not e.g. EAR's /lib
or elsewhere.
If you're using Eclipse, make sure that the backing bean class is in src
and thus not WebContent
, and make sure that Project > Build Automatically is enabled. If you're using Maven, make sure that the backing bean class is in src/main/java
and thus not in src/main/resources
or src/main/webapp
.
If you're packaging the web application as part of an EAR with EJB+WAR(s), then you need to make sure that the backing bean classes are in WAR module and thus not in EAR module nor EJB module. The business tier (EJB) must be free of any web tier (WAR) related artifacts, so that the business tier is reusable across multiple different web tiers (JSF, JAX-RS, JSP/Servlet, etc).
This boils down to that the nested property entity
as in #{bean.entity.property}
returned null
. This usually only exposes when JSF needs to set the value for property
via an input component like below, while the #{bean.entity}
actually returned null
.
<h:inputText value="#{bean.entity.property}" />
You need to make sure that you have prepared the model entity beforehand in a @PostConstruct
, or <f:viewAction>
method, or perhaps an add()
action method in case you're working with CRUD lists and/or dialogs on same view.
@Named
@ViewScoped
public class Bean {
private Entity entity; // +getter (setter is not necessary).
@Inject
private EntityService entityService;
@PostConstruct
public void init() {
// In case you're updating an existing entity.
entity = entityService.getById(entityId);
// Or in case you want to create a new entity.
entity = new Entity();
}
// ...
}
As to the importance of @PostConstruct
; doing this in a regular constructor would fail in case you're using a bean management framework which uses proxies, such as CDI. Always use @PostConstruct
to hook on managed bean instance initialization (and use @PreDestroy
to hook on managed bean instance destruction). Additionally, in a constructor you wouldn't have access to any injected dependencies yet, see also NullPointerException while trying to access @Inject bean in constructor.
In case the entityId
is supplied via <f:viewParam>
, you'd need to use <f:viewAction>
instead of @PostConstruct
. See also When to use f:viewAction / preRenderView versus PostConstruct?
You also need to make sure that you preserve the non-null
model during postbacks in case you're creating it only in an add()
action method. Easiest would be to put the bean in the view scope. See also How to choose the right bean scope?
This has actually the same cause as #2, only the (older) EL implementation being used is somewhat buggy in preserving the property name to display in the exception message, which ultimately incorrectly exposed as 'null'. This only makes debugging and fixing a bit harder when you've quite some nested properties like so #{bean.entity.subentity.subsubentity.property}
.
The solution is still the same: make sure that the nested entity in question is not null
, in all levels.
This has also the same cause as #2, only the (older) EL implementation being used is buggy in formulating the exception message. This exposes only when you use the brace notation []
in EL as in #{bean.collection[index]}
where the #{bean.collection}
itself is non-null, but the item at the specified index doesn't exist. Such a message must then be interpreted as:
Target Unreachable, 'collection[0]' returned null
The solution is also the same as #2: make sure that the collection item is available.
This has actually the same cause as #4, only the (older) EL implementation being used is somewhat buggy in preserving the iteration index to display in the exception message, which ultimately incorrectly exposed as 'BracketSuffix' which is really the character ]
. This only makes debugging and fixing a bit harder when you've multiple items in the collection.
javax.el.PropertyNotFoundException
:Friend comes handy when you are building a container and you want to implement an iterator for that class.
I want to add something on @Michael Laffargue's post:
jqXHR.done()
is faster!
jqXHR.success()
have some load time in callback and sometimes can overkill script. I find that on hard way before.
UPDATE:
Using jqXHR.done()
, jqXHR.fail()
and jqXHR.always()
you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:
/* Initialize some your AJAX function */
function call_ajax(attr){
var settings=$.extend({
call : 'users',
option : 'list'
}, attr );
return $.ajax({
type: "POST",
url: "//exapmple.com//ajax.php",
data: settings,
cache : false
});
}
/* .... Somewhere in your code ..... */
call_ajax({
/* ... */
id : 10,
option : 'edit_user'
change : {
name : 'John Doe'
}
/* ... */
}).done(function(data){
/* DO SOMETHING AWESOME */
});
As a one liner using list comprehension and numpy:
[ax.annotate(x[0], (x[1], x[2])) for x in np.array([n,z,y]).T]
setup is ditto to Rutger's answer.
In your Fragments onCreateView(...)
you can remove a view by calling container.removeView(view);
.
So if you want to remove the fragment, then view
should be the return value of onCreateView
,
for example
public View onCreateView(...){
final View view = inflater.inflate(R.layout.your_fragments_layout,container,false);
//Do something
finishButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
container.removeView(view);
}
});
return view;
}
I like pygame, and the command below should work:
pygame.init()
pygame.mixer.Sound('sound.wav').play()
but it doesn't on either of my computers, and there is limited help on the subject out there. edit: I figured out why the pygame sound isn't working for me, it's not loading most sounds correctly, the 'length' attribute is ~0.0002 when I load them. maybe loading them using something other than mygame will get it morking more generally.
with pyglet I'm getting a resource not found error Using the above example, wigh both relative and full paths to the files.
using pyglet.media.load()
instead of pyglet.resource.media()
lets me load the files.
but sound.play()
only plays the first fraction of a second of the file, unless I run pyglet.app.run()
which blocks everything else...
I just saw another question very similar to this!
Here is the canonical NORTHWIND (spelled just slightly different for some reason) database example.
SELECT *
FROM [NORTHWND].[dbo].[Products]
SELECT CategoryId,
MAX( CASE seq WHEN 1 THEN ProductName ELSE '' END ) + ', ' +
MAX( CASE seq WHEN 2 THEN ProductName ELSE '' END ) + ', ' +
MAX( CASE seq WHEN 3 THEN ProductName ELSE '' END ) + ', ' +
MAX( CASE seq WHEN 4 THEN ProductName ELSE '' END )
FROM ( SELECT p1.CategoryId, p1.ProductName,
( SELECT COUNT(*)
FROM NORTHWND.dbo.Products p2
WHERE p2.CategoryId = p1.CategoryId
AND p2.ProductName <= p1.ProductName )
FROM NORTHWND.dbo.Products p1 ) D ( CategoryId, ProductName, seq )
GROUP BY CategoryId ;
To change the XAMPP Apache server port here the procedure :
The default port used by Apache is 80
.
Take a look to all your used ports with Netstat (integrated to XAMPP Control Panel).
Then you can see all used ports and here we see that the 80
port is already used by System
.
Choose a free port number (8012
, for this exemple).
httpd.conf
"This file should be found in
C:\xampp\apache\conf
on Windows or inbin/apache
for Linux.:
Listen 80
ServerName localhost:80
Replace them by:
Listen 8012
ServerName localhost:8012
Save the file.
Access to : http://localhost:8012 for check if it's work.
If not, you must to edit the http-ssl.conf
file as explain in step 3 below. ?
http-ssl.conf
"This file should be found in
C:\xampp\apache\conf\extra
on Windows or see this link for Linux.
Locate the following lines:
Listen 443
<VirtualHost _default_:443>
ServerName localhost:443
Replace them by with a other port number (8013
for this example) :
Listen 8013
<VirtualHost _default_:8013>
ServerName localhost:8013
Save the file.
Restart the Apache Server.
Access to : http://localhost:8012 for check if it's work.
If your want to access localhost without specify the port number in the URL
http://localhost instead of http://localhost:8012.
8012
and 8013
).If this configuration isn't hiding port number in URL it's because your web browser is not configured for. See : Tools ? Options ? General ? Connection Settings... will allow you to choose different ports or change proxy settings.
If step 4 and Web browser configuration are not working for you the only way to do this is to change back to 80, or to install a listener on port 80 (like a proxy) that redirects all your traffic to port 8012.
If you still have this message in Control Panel Console :
Apache Started [Port 80]
xampp-control.exe
file (probably in C:\xampp
)XAMPP.INI
in that directory (so XAMPP.ini
and xampp-control.exe
are in the same directory)Put following lines in the XAMPP.INI
file:
[PORTS]
apache = 8012
Now , you will always get:
Apache started [Port 8012]
Please note that, this is for display purpose only.
It has no relation with your httpd.conf
.
Try this
SELECT
DateAppr,
TimeAppr,
TAT,
LaserLTR,
Permit,
LtrPrinter,
JobName,
JobNumber,
JobDesc,
ActQty,
(ActQty-LtrPrinted) AS L,
(ActQty-QtyInserted) AS M,
((ActQty-LtrPrinted)-(ActQty-QtyInserted)) AS N
FROM
[test].[dbo].[MM]
WHERE
DateDropped = 0
AND (
(ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0)
OR
(ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)
)
Use this code
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp"
android:radius="0.1dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp" />
<solid android:color="#Efffff" />
<stroke
android:width="2dp"
android:color="#25aaff" />
</shape>
Another approach depending on how you are changing the div. If you are using JQuery to change a div's contents with its html() method, you can extend that method and call a registration function each time you put html into a div.
(function( $, oldHtmlMethod ){
// Override the core html method in the jQuery object.
$.fn.html = function(){
// Execute the original HTML method using the
// augmented arguments collection.
var results = oldHtmlMethod.apply( this, arguments );
com.invisibility.elements.findAndRegisterElements(this);
return results;
};
})( jQuery, jQuery.fn.html );
We just intercept the calls to html(), call a registration function with this, which in the context refers to the target element getting new content, then we pass on the call to the original jquery.html() function. Remember to return the results of the original html() method, because JQuery expects it for method chaining.
For more info on method overriding and extension, check out http://www.bennadel.com/blog/2009-Using-Self-Executing-Function-Arguments-To-Override-Core-jQuery-Methods.htm, which is where I cribbed the closure function. Also check out the plugins tutorial at JQuery's site.
Yes using Option Explicit
is a good habit. Using .Select
however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet
which might not be what you actually wanted.
Is this what you are trying?
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
Else
Exit For
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
NOTE
If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10
If you want to copy all rows which have data then use this code.
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
Hope this is what you wanted?
Sid
There is one more important difference between a HashTable and Dictionary. If you use indexers to get a value out of a HashTable, the HashTable will successfully return null for a non-existent item, whereas the Dictionary will throw an error if you try accessing a item using a indexer which does not exist in the Dictionary
For Zoom In: CTRL + SHIFT + +
For Zoom Out: `CTRL + SHIFT + -
It looks like there is a really good way to handle this:
WPF Single Instance Application
This provides a class you can add that manages all the mutex and messaging cruff to simplify the your implementation to the point where it's simply trivial.
What I needed: A document number with a fixed number of integers that would also act like an AutoField
.
My searches took me all over incl. this page.
Finally I did something like this:
I created a table with a DocuNumber
field as an IntegerField with foll. attributes:
max_length=6
primary_key=True
unique=True
default=100000
The max_length
value anything as required (and thus the corresponding default=
value).
A warning is issued while creating the said model, which I could ignore.
Afterwards, created a document (dummy) whence as expected, the document had an integer field value of 100000.
Afterwards changed the model key field as:
AutoField
max_length
And default
attributesprimary_key = True
attributeThe next (desired document) created had the value as 100001 with subsequent numbers getting incremented by 1.
So far so good.
In version 3, they changed "export" to "unload". It still functions more or less the same.
It means the class is not yet added to the repository.
If your project was checked-out (most probably a CVS project) and you added a new class file, it will have the ? icon.
For other CVS Label Decorations, check http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.platform.doc.user/reference/ref-cvs-decorations.htm
I faced the same question. I want to add some info to the user-agent, also need to keep the original user-agent of webview. I solved it by using the code below:
//get the original user-agent of webview
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSLog(@"old agent :%@", oldAgent);
//add my info to the new agent
NSString *newAgent = [oldAgent stringByAppendingString:@" Jiecao/2.4.7 ch_appstore"];
NSLog(@"new agent :%@", newAgent);
//regist the new agent
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
Use it before you instancing webview.
I know this was answered long ago, but if you don't mind creating the button dynamically, this works using only the jQuery framework:
$(document).ready(function() {_x000D_
$button = $('<input id="1" type="button" value="ahaha" />');_x000D_
$('body').append($button);_x000D_
$button.click(function() {_x000D_
console.log("Id clicked: " + this.id ); // or $(this) or $button_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>And here is my HTML page:</p>_x000D_
_x000D_
<div class="Title">Welcome!</div>
_x000D_
Thought I'd add an answer since the introduction of the
android:translationZ
XML field changed things a tad. The other answers that suggest running
childView1.bringToFront();
parentView.invalidate();
are totally spot on EXCEPT for that this code will NOT bring childView1 in front of any view with a hardcoded android:translationZ in the XML file. I was having problems with this, and once I removed this field from the other views, bringToFront() worked just fine.
Here is an interesting blog entry about numbers / limitations of Excel 2007. According to the author the new limit is approximately one million rows.
Sounds like you have a pre-Excel 2007 workbook open in Excel 2007 in compatibility mode (look in the title bar and see if it says compatibility mode). If so, the workbook has 65,536 rows, not 1,048,576. You can save the workbook as an Excel workbook which will be in Excel 2007 format, close the workbook and re-open it.
You can use Create USer to create a user
CREATE LOGIN sam
WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
USE AdventureWorks;
CREATE USER sam FOR LOGIN sam;
GO
and to Grant (Read-only access) you can use the following
GRANT SELECT TO sam
Hope that helps.
fyi, this can happen if you are using the html type="number" attribute on your input tag. Entering a non-number will clear it before your script knows what's going on.
This is a very confusing topic. django stores all applied migrations in a table called django_migrations. perform this sql ( i am using postgres . so in query tool section)
select * from django_migrations where app='your appname' (app in which u have issue with).
This will list all applied migrations for that app.
Go to your app/migration folder and check all migrations . find the migration file associated with your error . file where your table was created or column added or modified.
look for the id of this migration file in django_migrations table( select * from django_migrations where app='your app') .
Then do :
delete from django_migrations where id='id of your migration';
delete multiple id's if you have multiple migrations file associated with your issue.
now reapply migrate
Python manage.py migrate yourappname
second option
Drop tables in your app where you have issue.
delete all migrations for that app from app/migrations folder.(don't delete init.py from that folder).
now run
python manage.py makemigrations appname
now run
python manage.py migrate appname
By my knowledge there is no overall way to do this. If you look at the headers of cross platform/multiple compiler supporting libraries you'll always find a lot of defines that use compiler specific constructs to determine such things:
/*Define Microsoft Visual C++ .NET (32-bit) compiler */
#if (defined(_M_IX86) && defined(_MSC_VER) && (_MSC_VER >= 1300)
...
#endif
/*Define Borland 5.0 C++ (16-bit) compiler */
#if defined(__BORLANDC__) && !defined(__WIN32__)
...
#endif
You probably will have to do such defines yourself for all compilers you use.
def xml_to_dict(node):
u'''
@param node:lxml_node
@return: dict
'''
return {'tag': node.tag, 'text': node.text, 'attrib': node.attrib, 'children': {child.tag: xml_to_dict(child) for child in node}}
I recommend Charles Web Proxy
Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. This includes requests, responses and the HTTP headers (which contain the cookies and caching information).
It's cross-platform, written in JAVA, and pretty good. Not nearly as overwhelming as Wireshark, and does a lot of the annoying stuff like setting up the proxies, etc. for you. The only bad part is that it costs money, $50 at that. Not cheap, but a useful tool.
You'll need to add the other repository as a remote, then fetch its changes. From there you see the commit and you can cherry-pick it.
Like that:
git remote add other https://example.link/repository.git
git fetch other
Now you have all the information to simply do git cherry-pick
.
More info about working with remotes here: https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes
In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue or defaultChecked attribute instead of value.
<input
type="checkbox"
defaultChecked={true}
/>
Or
React.createElement('input',{type: 'checkbox', defaultChecked: true});
Please checkout more details regarding defaultChecked
for checkbox below:
https://reactjs.org/docs/uncontrolled-components.html#default-values
You had the identity
node as a child of authentication
node. That was the issue. As in the example above, authentication
and identity
nodes must be children of the system.web
node
I'd say
chunks = [data[x:x+100] for x in range(0, len(data), 100)]
If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange()
, changing the above code to:
chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]
The increasingly popular D3 library handles the oddities of appending/manipulating svg very nicely. You may want to consider using it as opposed to the jQuery hacks mentioned here.
HTML
<svg xmlns="http://www.w3.org/2000/svg"></svg>
Javascript
var circle = d3.select("svg").append("circle")
.attr("r", "10")
.attr("style", "fill:white;stroke:black;stroke-width:5");
Like this:
sed 's/aaa=.*/aaa=xxx/'
If you want to guarantee that the aaa=
is at the start of the line, make it:
sed 's/^aaa=.*/aaa=xxx/'
In the documentation it's stated: Use the prefix option together with the global option:
The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary. On Unix systems, it's one level up, since node is typically installed at {prefix}/bin/node rather than {prefix}/node.exe.
When the global flag is set, npm installs things into this prefix. When it is not set, it uses the root of the current package, or the current working directory if not in a package already.
(Emphasis by them)
So in your root directory you could install with
npm install --prefix <path/to/prefix_folder> -g
and it will install the node_modules
folder into the folder
<path/to/prefix_folder>/lib/node_modules
signingConfigs should be before buildTypes
signingConfigs {
debug {
storeFile file("debug.keystore")
}
myConfig {
storeFile file("other.keystore")
storePassword "android"
keyAlias "androidotherkey"
keyPassword "android"
}
}
buildTypes {
bar {
debuggable true
jniDebugBuild true
signingConfig signingConfigs.debug
}
foo {
debuggable false
jniDebugBuild false
signingConfig signingConfigs.myConfig
}
}
GET
/POST
/whatever) endpoint from somewhere, or consuming a webservice using SOA, etc...) you do not want to transmit the big sized object with code that is not necessary for the endpoint, will consume data, and slow down the transfer.zlib
handles the deflate compression/decompression algorithm, but there is more than that in a ZIP file.
You can try libzip. It is free, portable and easy to use.
UPDATE: Here I attach quick'n'dirty example of libzip, with all the error controls ommited:
#include <zip.h>
int main()
{
//Open the ZIP archive
int err = 0;
zip *z = zip_open("foo.zip", 0, &err);
//Search for the file of given name
const char *name = "file.txt";
struct zip_stat st;
zip_stat_init(&st);
zip_stat(z, name, 0, &st);
//Alloc memory for its uncompressed contents
char *contents = new char[st.size];
//Read the compressed file
zip_file *f = zip_fopen(z, name, 0);
zip_fread(f, contents, st.size);
zip_fclose(f);
//And close the archive
zip_close(z);
//Do something with the contents
//delete allocated memory
delete[] contents;
}
this really is a question for Serverfault.
Windows:
nslookup
and hit enterset type=MX
and hit enterLinux:
dig domain.name MX
and hit enter where domain.name is the domain you are trying to find out the smtp server for.If you do not get any answers back from your dns server, there is a good chance that there isn't any SMTP Servers set up for that domain. If this is the case, do like other's have suggested and call the hosting companies tech support.
In my system, I use the update alternatives.
sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1
sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip2 2
If I want to switch between them I use the following command.
sudo update-alternatives --config pip
Note: The 1st line is enough if you have only pip3 installed and not pip2.
Here are the all keycodes.
Here is a table with some keycodes for the three platforms. It is based on a US Extended keyboard layout.
http://web.archive.org/web/20100501161453/http://www.classicteck.com/rbarticles/mackeyboard.php
Or, there is an app in the Mac App Store named "Key Codes". Download it to see the keycodes of the keys you press.
Key Codes:
https://itunes.apple.com/tr/app/key-codes/id414568915?l=tr&mt=12
i := 23
i64 := int64(i)
fmt.Printf("%T %T", i, i64) // to print the data types of i and i64
set /a number=%random% %% [maximum]-[minimum]
example "
set /a number=%random% %% 100-50
will give a random number between 100 and 50. Be sure to only use one percentage sign as the operand if you are not using the line in a batch script!
I've created a github repo summing up this article basically: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec
I'll try to explain as good as possible, hope I help some of you out there:
(1) app.js: Creation of authentication constants on app definition
var loginApp = angular.module('loginApp', ['ui.router', 'ui.bootstrap'])
/*Constants regarding user login defined here*/
.constant('USER_ROLES', {
all : '*',
admin : 'admin',
editor : 'editor',
guest : 'guest'
}).constant('AUTH_EVENTS', {
loginSuccess : 'auth-login-success',
loginFailed : 'auth-login-failed',
logoutSuccess : 'auth-logout-success',
sessionTimeout : 'auth-session-timeout',
notAuthenticated : 'auth-not-authenticated',
notAuthorized : 'auth-not-authorized'
})
(2) Auth Service: All following functions are implemented in auth.js service. The $http service is used to communicate with the server for the authentication procedures. Also contains functions on authorization, that is if the user is allowed to perform a certain action.
angular.module('loginApp')
.factory('Auth', [ '$http', '$rootScope', '$window', 'Session', 'AUTH_EVENTS',
function($http, $rootScope, $window, Session, AUTH_EVENTS) {
authService.login() = [...]
authService.isAuthenticated() = [...]
authService.isAuthorized() = [...]
authService.logout() = [...]
return authService;
} ]);
(3) Session: A singleton to keep user data. The implementation here depends on you.
angular.module('loginApp').service('Session', function($rootScope, USER_ROLES) {
this.create = function(user) {
this.user = user;
this.userRole = user.userRole;
};
this.destroy = function() {
this.user = null;
this.userRole = null;
};
return this;
});
(4) Parent controller: Consider this as the "main" function of your application, all controllers inherit from this controller, and it's the backbone of the authentication of this app.
<body ng-controller="ParentController">
[...]
</body>
(5) Access control: To deny access on certain routes 2 steps have to be implemented:
a) Add data of the roles allowed to access each route, on ui router's $stateProvider service as can be seen below (same can work for ngRoute).
.config(function ($stateProvider, USER_ROLES) {
$stateProvider.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard/index.html',
data: {
authorizedRoles: [USER_ROLES.admin, USER_ROLES.editor]
}
});
})
b) On $rootScope.$on('$stateChangeStart') add the function to prevent state change if the user is not authorized.
$rootScope.$on('$stateChangeStart', function (event, next) {
var authorizedRoles = next.data.authorizedRoles;
if (!Auth.isAuthorized(authorizedRoles)) {
event.preventDefault();
if (Auth.isAuthenticated()) {
// user is not allowed
$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
} else {
// user is not logged in
$rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
}
}
});
(6) Auth interceptor: This is implemented, but can't be checked on the scope of this code. After each $http request, this interceptor checks the status code, if one of the below is returned, then it broadcasts an event to force the user to log-in again.
angular.module('loginApp')
.factory('AuthInterceptor', [ '$rootScope', '$q', 'Session', 'AUTH_EVENTS',
function($rootScope, $q, Session, AUTH_EVENTS) {
return {
responseError : function(response) {
$rootScope.$broadcast({
401 : AUTH_EVENTS.notAuthenticated,
403 : AUTH_EVENTS.notAuthorized,
419 : AUTH_EVENTS.sessionTimeout,
440 : AUTH_EVENTS.sessionTimeout
}[response.status], response);
return $q.reject(response);
}
};
} ]);
P.S. A bug with the form data autofill as stated on the 1st article can be easily avoided by adding the directive that is included in directives.js.
P.S.2 This code can be easily tweaked by the user, to allow different routes to be seen, or display content that was not meant to be displayed. The logic MUST be implemented server-side, this is just a way to show things properly on your ng-app.
Check click area is not in the targeted element or in it's child
$(document).click(function (e) {
if ($(e.target).parents(".dropdown").length === 0) {
$(".dropdown").hide();
}
});
UPDATE:
jQuery stop propagation is the best solution
$(".button").click(function(e){
$(".dropdown").show();
e.stopPropagation();
});
$(".dropdown").click(function(e){
e.stopPropagation();
});
$(document).click(function(){
$(".dropdown").hide();
});
upvoted itsadok's answer because it led me to the installation for python 2.7 as well, which is located here: http://www.codegood.com/archives/129
To skip the test case during maven clean install i used -DskipTests paramater in following command
mvn clean install -DskipTests
into terminal window
The timer has special functions.
if you use StartAsync ()
or Start ()
, the thread does not block the user interface element
namespace UITimer
{
using thread = System.Threading;
public class Timer
{
public event Action<thread::SynchronizationContext> TaskAsyncTick;
public event Action Tick;
public event Action AsyncTick;
public int Interval { get; set; } = 1;
private bool canceled = false;
private bool canceling = false;
public async void Start()
{
while(true)
{
if (!canceled)
{
if (!canceling)
{
await Task.Delay(Interval);
Tick.Invoke();
}
}
else
{
canceled = false;
break;
}
}
}
public void Resume()
{
canceling = false;
}
public void Cancel()
{
canceling = true;
}
public async void StartAsyncTask(thread::SynchronizationContext
context)
{
while (true)
{
if (!canceled)
{
if (!canceling)
{
await Task.Delay(Interval).ConfigureAwait(false);
TaskAsyncTick.Invoke(context);
}
}
else
{
canceled = false;
break;
}
}
}
public void StartAsync()
{
thread::ThreadPool.QueueUserWorkItem((x) =>
{
while (true)
{
if (!canceled)
{
if (!canceling)
{
thread::Thread.Sleep(Interval);
Application.Current.Dispatcher.Invoke(AsyncTick);
}
}
else
{
canceled = false;
break;
}
}
});
}
public void StartAsync(thread::SynchronizationContext context)
{
thread::ThreadPool.QueueUserWorkItem((x) =>
{
while(true)
{
if (!canceled)
{
if (!canceling)
{
thread::Thread.Sleep(Interval);
context.Post((xfail) => { AsyncTick.Invoke(); }, null);
}
}
else
{
canceled = false;
break;
}
}
});
}
public void Abort()
{
canceled = true;
}
}
}
For those of you who are building on a MacOS, and don't like leaving your password in clear text on your machine, you can use the keychain tool to store the credentials and then inject it into the build. Credits go to Viktor Eriksson. https://pilloxa.gitlab.io/posts/safer-passwords-in-gradle/
Just as Diodeus said, you're comparing an Image
to a HTMLDomObject
. Instead compare their .src
attribute:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';
/* ... more images ... */
imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';
/*------------------------------------*/
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src) // << check this
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
I had the same problem It happens because files can't contain special characters like ":", "?", ">" and etc. You should replace these files by using replace() function:
filename = filename.replace("special character to replace", "-")
I struggled with this for a while and finally figured it out on my own. I didn't find any help at the time, but wanted to share my approach. I have done this several times and used a different method than what is above. Not sure how robust it is, but it has worked for me.
Let's say you have a textbox named "txtName", a button named "btnSave" and you want to save the name so the next time you run your program the name you typed appears in that textbox.
Save your settings file.
//This tells your program to save the value you have to the properties file (app.config);
//"Name" here is the name you used in your settings file above.
Properties.Settings.Default.Name = txtName.txt;
//This tells your program to make these settings permanent, otherwise they are only
//saved for the current session
Properties.Settings.Default.Save();
//This tells your program to load the setting you saved above to the textbox
txtName.txt = Properties.Settings.Default.Name;
Notes -
polynomial time O(n)^k means Number of operations are proportional to power k of the size of input
exponential time O(k)^n means Number of operations are proportional to the exponent of the size of input
The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
By default, in Spring boot applications, component scan is done inside the package where your main class resides. any bean which is outside the package will not the created and thus gives the above mentioned exception.
Solution: you could either move the beans to the main spring boot class(which is not a good approach) or create a seperate configutation file and import it:
@Import({CustomConfigutation1.class, CustomConfiguration2.class})
@SpringBootpplication
public class BirthdayApplication {
public static void main(String [] args) {
springApplication.run(BirthdayApplication.class, args );
}
}
Add beans to these CustomConfiguration files.
You could use JavaScript. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for PDF you will have to change the mime type and the magic number):
<form id="form-id">
<input type="file" id="input-id" accept="image/jpeg"/>
</form>
<script type="text/javascript">
$(function(){
$("#input-id").on('change', function(event) {
var file = event.target.files[0];
if(file.size>=2*1024*1024) {
alert("JPG images of maximum 2MB");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
if(!file.type.match('image/jp.*')) {
alert("only JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
var fileReader = new FileReader();
fileReader.onload = function(e) {
var int32View = new Uint8Array(e.target.result);
//verify the magic number
// for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
alert("ok!");
} else {
alert("only valid JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
};
fileReader.readAsArrayBuffer(file);
});
});
</script>
Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.
try parsing a default value which can be returned by max if length of v none
max(v, default=0)
There is a new cross plateform (java) and open source tool, that enable you to do that, just checkout https://bytecodeviewer.com
=========
EDIT: As of April 2017, there is a new open source tool developed by google, that is meant to do just what we have been looking for => https://github.com/google/android-classyshark
In linux shell, many commands accept multiple parameters and therefore could be used with wild cards. So, for example if you want to move all files from folder A to folder B, you write:
mv A/* B
If you want to move all files with a certain "look" to it, you could do like this:
mv A/*.txt B
Which copies all files that are blablabla.txt to folder B
Star (*) can substitute any number of characters or letters while ? can substitute one. For example if you have many files in the shape file_number.ext and you want to move only the ones that have two digit numbers, you could use a command like this:
mv A/file_??.ext B
Or more complicated examples:
mv A/fi*_??.e* B
For files that look like fi<-something->_<-two characters->.e<-something->
Unlike many commands in shell that require -R to (for example) copy or remove subfolders, mv does that itself.
Remember that mv overwrites without asking (unless the files being overwritten are read only or you don't have permission) so make sure you don't lose anything in the process.
For your future information, if you have subfolders that you want to copy, you could use the -R option, saying you want to do the command recursively. So it would look something like this:
cp A/* B -R
By the way, all I said works with rm (remove, delete) and cp (copy) too and beware, because once you delete, there is no turning back! Avoid commands like rm * -R
unless you are sure what you are doing.
I just faced the same issue, I managed to make it work on my machine, however the change I did is not the same way it is mentioned in the documentation so it could be an issue of angular version routing module, mine is Angular 7
It only worked when I changed the lazy module main route entry path with same path as configured at the app-routes.ts
routes = [{path:'', redirectTo: '\home\default', pathMatch: 'full'},
{path: '',
children: [{
path:'home',
loadChildren :'lazy module path'
}]
}];
routes configured at HomeModule
const routes = [{path: 'home', redirectTo: 'default', pathMatch: 'full'},
{path: 'default', component: MyPageComponent},
]
instead of
const routes = [{path: '', redirectTo: 'default', pathMatch: 'full'},
{path: 'default', component: MyPageComponent},
]
This article is clearly explained, how to install MySqli with EachApache. This works for me too.
To install mysqli using EachApache:
Login to WHM as 'root' user.
Either search for "EasyApache" or go to Software > EasyApache
Scroll down and select a build option (Previously Saved Config)
Click Start "Start customizing based on profile"
Select the version of Apache and click "Next Step".
Select the version of PHP and click "Next Step".
Chose additional options within the "Short Options List"
Select "Exhaustive Options List" and look for "MySQL Improved extension"
Click "Save and Build"
Although silly mistake but make sure to use correct module name and respect capitalization
I installed this package via command line as pip install cx_oracle
in my windows machine. While importing it in spyder as cx_oracle
, it kept on giving following error:
ModuleNotFoundError: No module named 'cx_oracle'
.
Upon correcting the module name in import command to cx_Oracle
(i.e. capital letter 'O' in oracle), it was a successful import.
You should use the grep
-q
flag for quiet output. See the man pages below:
man grep output :
General Output Control
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immediately with zero status
if any match is found, even if an error was detected. Also see the -s or
--no-messages option. (-q is specified by POSIX.)
This KornShell (ksh) script demos the grep
quiet output and is a solution to your question.
grepUtil.ksh :
#!/bin/ksh
#Initialize Variables
file=poet.txt
var=""
dir=tempDir
dirPath="/"${dir}"/"
searchString="poet"
#Function to initialize variables
initialize(){
echo "Entering initialize"
echo "Exiting initialize"
}
#Function to create File with Input
#Params: 1}Directory 2}File 3}String to write to FileName
createFileWithInput(){
echo "Entering createFileWithInput"
orgDirectory=${PWD}
cd ${1}
> ${2}
print ${3} >> ${2}
cd ${orgDirectory}
echo "Exiting createFileWithInput"
}
#Function to create File with Input
#Params: 1}directoryName
createDir(){
echo "Entering createDir"
mkdir -p ${1}
echo "Exiting createDir"
}
#Params: 1}FileName
readLine(){
echo "Entering readLine"
file=${1}
while read line
do
#assign last line to var
var="$line"
done <"$file"
echo "Exiting readLine"
}
#Check if file exists
#Params: 1}File
doesFileExit(){
echo "Entering doesFileExit"
orgDirectory=${PWD}
cd ${PWD}${dirPath}
#echo ${PWD}
if [[ -e "${1}" ]]; then
echo "${1} exists"
else
echo "${1} does not exist"
fi
cd ${orgDirectory}
echo "Exiting doesFileExit"
}
#Check if file contains a string quietly
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainStringQuiet(){
echo "Entering doesFileContainStringQuiet"
orgDirectory=${PWD}
cd ${PWD}${1}
#echo ${PWD}
grep -q ${3} ${2}
if [ ${?} -eq 0 ];then
echo "${3} found in ${2}"
else
echo "${3} not found in ${2}"
fi
cd ${orgDirectory}
echo "Exiting doesFileContainStringQuiet"
}
#Check if file contains a string with output
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainString(){
echo "Entering doesFileContainString"
orgDirectory=${PWD}
cd ${PWD}${1}
#echo ${PWD}
grep ${3} ${2}
if [ ${?} -eq 0 ];then
echo "${3} found in ${2}"
else
echo "${3} not found in ${2}"
fi
cd ${orgDirectory}
echo "Exiting doesFileContainString"
}
#-----------
#---Main----
#-----------
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
#initialize #function call#
createDir ${dir} #function call#
createFileWithInput ${dir} ${file} ${searchString} #function call#
doesFileExit ${file} #function call#
if [ ${?} -eq 0 ];then
doesFileContainStringQuiet ${dirPath} ${file} ${searchString} #function call#
doesFileContainString ${dirPath} ${file} ${searchString} #function call#
fi
echo "Exiting: ${PWD}/${0}"
grepUtil.ksh Output :
user@foo /tmp
$ ksh grepUtil.ksh
Starting: /tmp/grepUtil.ksh with Input Parameters: {1: {2: {3:
Entering createDir
Exiting createDir
Entering createFileWithInput
Exiting createFileWithInput
Entering doesFileExit
poet.txt exists
Exiting doesFileExit
Entering doesFileContainStringQuiet
poet found in poet.txt
Exiting doesFileContainStringQuiet
Entering doesFileContainString
poet
poet found in poet.txt
Exiting doesFileContainString
Exiting: /tmp/grepUtil.ksh
I like to place all my sql connections in using
statements. I think they look cleaner, and they clean up after themselves when your done with them. I also recommend parameterizing every query, not only is it much safer but it is easier to maintain if you need to come back and make changes.
// create/open connection
using (SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI")
{
try
{
conn.Open();
// initialize command
using (SqlCommand cmd = conn.CreateCommand())
{
// generate query with parameters
with cmd
{
.CommandType = CommandType.Text;
.CommandText = "insert into time(project,iteration) values(@name, @iteration)";
.Parameters.Add(new SqlParameter("@name", this.name1.SelectedValue));
.Parameters.Add(new SqlParameter("@iteration", this.iteration.SelectedValue));
.ExecuteNonQuery();
}
}
}
catch (Exception)
{
//throw;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
{
conn.Close;
}
}
}
Basically, 1
is not a valid index of y
. If the visitor is comming from his own code he should check if his y
contains the index which he tries to access (in this case the index is 1
).
You need to wrap the text in a div
element and include the absolutely positioned element inside of it.
<div class="container">
<div class="inner">
<div class="full-height"></div>
[Your text here]
</div>
</div>
Css:
.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }
Setting the inner div's position to relative
makes the absolutely position elements inside of it base their position and height on it rather than on the .container
div, which has a fixed height. Without the inner, relatively positioned div
, the .full-height
div will always calculate its dimensions and position based on .container
.
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
position: relative;_x000D_
border: solid 1px red;_x000D_
height: 256px;_x000D_
width: 256px;_x000D_
overflow: auto;_x000D_
float: left;_x000D_
margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
position: relative;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 128px;_x000D_
bottom: 0;_x000D_
height: 100%;_x000D_
background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
<div class="inner">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
quidem._x000D_
</div>_x000D_
</div>
_x000D_
What you are looking for is this:
SHOW VARIABLES;
You can modify it further like any query:
SHOW VARIABLES LIKE '%max%';
VI search and replace command examples
Let us say you would like to find a word called “foo” and replace with “bar”.
First hit [Esc]
key
Type : (colon) followed by %s/foo/bar/
and hit [Enter] key
:%s/foo/bar/