I would go with Collections.emptyList()
if the returned list is not being modified in any way (as the list is immutable), otherwise I would go with option 2.
The benefit of Collections.emptyList()
is that the same static instance is returned each time and so there is not instance creation occurring for each call.
You can turn an array into a stream by using Arrays.stream()
:
int[] ns = new int[] {1,2,3,4,5};
Arrays.stream(ns);
Once you've got your stream, you can use any of the methods described in the documentation, like sum()
or whatever. You can map
or filter
like in Python by calling the relevant stream methods with a Lambda function:
Arrays.stream(ns).map(n -> n * 2);
Arrays.stream(ns).filter(n -> n % 4 == 0);
Once you're done modifying your stream, you then call toArray()
to convert it back into an array to use elsewhere:
int[] ns = new int[] {1,2,3,4,5};
int[] ms = Arrays.stream(ns).map(n -> n * 2).filter(n -> n % 4 == 0).toArray();
In my case, i had installed only the JRE so you could check to make sure you actually have a valid jdk. if not i advise you to uninstall whatever java is installed and download a correct jdk from here (the jdk comes with a jre so no need to download anything else) after set the environment variable and your done
Take a look at the Collections.sort(List<T> list)
.
You can simply remove the first element, sort the list and then add it back again.
This function convert wildcard to regexp and make test (it supports .
and *
wildcharts)
function wildTest(wildcard, str) {
let w = wildcard.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // regexp escape
const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
return re.test(str); // remove last 'i' above to have case sensitive
}
function wildTest(wildcard, str) {_x000D_
let w = wildcard.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // regexp escape _x000D_
const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');_x000D_
return re.test(str); // remove last 'i' above to have case sensitive_x000D_
}_x000D_
_x000D_
_x000D_
// Example usage_x000D_
_x000D_
let arr = ["birdBlue", "birdRed", "pig1z", "pig2z", "elephantBlua" ];_x000D_
_x000D_
let resultA = arr.filter( x => wildTest('biRd*', x) );_x000D_
let resultB = arr.filter( x => wildTest('p?g?z', x) );_x000D_
let resultC = arr.filter( x => wildTest('*Blu?', x) );_x000D_
_x000D_
console.log('biRd*',resultA);_x000D_
console.log('p?g?z',resultB);_x000D_
console.log('*Blu?',resultC);
_x000D_
Have you tried not setting the responseType and just type casting the response?
This is what worked for me:
/**
* Client for consuming recordings HTTP API endpoint.
*/
@Injectable({
providedIn: 'root'
})
export class DownloadUrlClientService {
private _log = Log.create('DownloadUrlClientService');
constructor(
private _http: HttpClient,
) {}
private async _getUrl(url: string): Promise<string> {
const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
// const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
// const res = await (this._http.get(url, httpOptions)).toPromise();
return res;
}
}
your understanding is right. For detailed info on {} see bash ref - parameter expansion
'for' and 'while' have different syntax and offer different styles of programmer control for an iteration. Most non-asm languages offer a similar syntax.
With while, you would probably write i=0; while [ $i -lt 10 ]; do echo $i; i=$(( i + 1 )); done
in essence manage everything about the iteration yourself
You need to do a deep copy from user to usercopy, and then after your login you can reassign your userCopy reference to user.
User userCopy = new User();
userCopy.Age = user.Age
userCopy.ID = user.ID
foreach(...)
{
user.Age = 1;
user.ID = -1;
UserDao.Update(user)
user = userCopy;
}
I have to add that bundles are used by activities to pass data to themselves in the future.
When the screen rotates, or when another activity is started, the method protected void onSaveInstanceState(Bundle outState)
is invoked, and the activity is destroyed. Later, another instance of the activity is created, and public void onCreate(Bundle savedInstanceState)
is called. When the first instance of activity is created, the bundle is null; and if the bundle is not null, the activity continues some business started by its predecessor.
Android automatically saves the text in text fields, but it does not save everything, and subtle bugs sometimes appear.
The most common anti-pattern, though, is assuming that onCreate()
does just initialization. It is wrong, because it also must restore the state.
There is an option to disable this "re-create activity on rotation" behavior, but it will not prevent restart-related bugs, it will just make them more difficult to mention.
Note also that the only method whose call is guaranteed when the activity is going to be destroyed is onPause()
. (See the activity life cycle graph in the docs.)
This might be the simplest of all.
You can use string::find
and string::rfind
to find whitespace from both sides and reduce the string.
void TrimWord(std::string& word)
{
if (word.empty()) return;
// Trim spaces from left side
while (word.find(" ") == 0)
{
word.erase(0, 1);
}
// Trim spaces from right side
size_t len = word.size();
while (word.rfind(" ") == --len)
{
word.erase(len, len + 1);
}
}
http://www.eclipsezone.com/eclipse/forums/t53459.html
Basically run it with:
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044
The application, at launch, will wait until you connect from another source.
Best way to design table is add one temporary row as auto increment and keep as primary key. So we can avoid such above issues.
double.Parse("-"); raises an exception, while double.TryParse("-", out parsed); parses to 0 so I guess TryParse does more complex conversions.
On Ubuntu, this worked:
I went to home/username/.android
and I renamed keystore.debug
to keystoreold.debug
. I then closed Eclipse, started Eclipse, and SDK created new certificate keystore.debug
in that folder.
You then have to uninstall/reinstall apps you installed via USB Debugging or an unsigned APK ("unsigned" APK = signed with debug certificate).
You could use the Google Font API. They say it works from IE 6 and up. (I've not tested this.)
Google’s serving infrastructure takes care of converting the font into a format compatible with any modern browser (including Internet Explorer 6 and up), ...
<input type="text" id="firstname" placeholder="First Name"
Note: You can change the placeholder, id and type value to "email" or whatever suits your need.
More details by W3Schools at:http://www.w3schools.com/tags/att_input_placeholder.asp
But by far the best solutions are by Floern and Vivek Mhatre ( edited by j0k )
The foreign keys in your schema (on Account_Name
and Account_Type
) do not require any special treatment or syntax. Just declare two separate foreign keys on the Customer table. They certainly don't constitute a composite key in any meaningful sense of the word.
There are numerous other problems with this schema, but I'll just point out that it isn't generally a good idea to build a primary key out of multiple unique columns, or columns in which one is functionally dependent on another. It appears that at least one of these cases applies to the ID and Name columns in the Customer table. This allows you to create two rows with the same ID (different name), which I'm guessing you don't want to allow.
check your branch on your repo. maybe someone delete it.
Maybe this will do the trick for you?
$FoundRows = $DataObject->query('SELECT FOUND_ROWS() AS Count')->fetchColumn();
Raw queries are more vulnerable to SQL Injection. I will suggest using query()
method instead.
public boolean Exists(String searchItem) {
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = { searchItem };
String limit = "1";
Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null, limit);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
Source: here
I have created my own git alias to do exactly this. I'm calling it git freebase
! It will take your existing messy, unrebasable feature branch and recreate it so that it becomes a new branch with the same name with its commits squashed into one commit and rebased onto the branch you specify (master by default). At the very end, it will allow you to use whatever commit message you like for your newly "freebased" branch.
Install it by placing the following alias in your .gitconfig:
[alias]
freebase = "!f() { \
TOPIC="$(git branch | grep '\\*' | cut -d ' ' -f2)"; \
NEWBASE="${1:-master}"; \
PREVSHA1="$(git rev-parse HEAD)"; \
echo "Freebaseing $TOPIC onto $NEWBASE, previous sha1 was $PREVSHA1"; \
echo "---"; \
git reset --hard "$NEWBASE"; \
git merge --squash "$PREVSHA1"; \
git commit; \
}; f"
Use it from your feature branch by running:
git freebase <new-base>
I've only tested this a few times, so read it first and make sure you want to run it. As a little safety measure it does print the starting sha1 so you should be able to restore your old branch if anything goes wrong.
I'll be maintaining it in my dotfiles repo on github: https://github.com/stevecrozz/dotfiles/blob/master/.gitconfig
Bash script for adding cron job without the interactive editor. Below code helps to add a cronjob using linux files.
#!/bin/bash
cron_path=/var/spool/cron/crontabs/root
#cron job to run every 10 min.
echo "*/10 * * * * command to be executed" >> $cron_path
#cron job to run every 1 hour.
echo "0 */1 * * * command to be executed" >> $cron_path
For make a list, simply do that
colors=(red orange white "light gray")
Technically is an array, but - of course - it has all list features.
Even python list are implemented with array
Activity.getResources().getConfiguration().orientation
Why use python at all? You might forget to remove it and check it into a repository. Just run your python command with && and another command to run to do the alerting.
python myscript.py &&
notify-send 'Alert' 'Your task is complete' &&
paplay /usr/share/sounds/freedesktop/stereo/suspend-error.oga
or drop a function into your .bashrc. I use apython here but you could override 'python'
function apython() {
/usr/bin/python $*
notify-send 'Alert' "python $* is complete"
paplay /usr/share/sounds/freedesktop/stereo/suspend-error.oga
}
Or simply:
Date.now
From MDN documentation:
The Date.now() method returns the number of milliseconds elapsed since January 1, 1970
Available since ECMAScript 5.1
It's the same as was mentioned above (new Date().getTime()
), but more shortcutted version.
You can use GroupBy
with anonymous type, and then get First
:
list.GroupBy(e => new {
empLoc = e.empLoc,
empPL = e.empPL,
empShift = e.empShift
})
.Select(g => g.First());
From the manual:
If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).
The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.
$qry = '
INSERT INTO non-existant-table (id, score)
SELECT id, 40
FROM another-non-existant-table
WHERE description LIKE "%:search_string%"
AND available = "yes"
ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());
Deleting registry keys as suggested above got my service stuck in the stopping state. The following procedure worked for me:
open task manager > select services tab > select the service > right click and select "go to process" > right click on the process and select End process
Service should be gone after that
Since no one else said it, the short-cut to compile (build) a C# app in Visual Studio Code (VSCode) is SHIFT+CTRL+B
.
If you want to see the build errors (because they don't pop-up by default), the shortcut is SHIFT+CTRL+M
.
(I know this question was asking for more than just the build shortcut. But I wanted to answer the question in the title, which wasn't directly answered by other answers/comments.)
There is a simple concise way, using regex flag (case insensitive {i}):
String s1 = "hello abc efg";
String s2 = "ABC";
s1.matches(".*(?i)"+s2+".*");
/*
* .* denotes every character except line break
* (?i) denotes case insensitivity flag enabled for s2 (String)
* */
I use extension methods to write things like that :
if (letter.IsFlagSet(Letter.AB))
...
Here's the code :
public static class EnumExtensions
{
private static void CheckIsEnum<T>(bool withFlags)
{
if (!typeof(T).IsEnum)
throw new ArgumentException(string.Format("Type '{0}' is not an enum", typeof(T).FullName));
if (withFlags && !Attribute.IsDefined(typeof(T), typeof(FlagsAttribute)))
throw new ArgumentException(string.Format("Type '{0}' doesn't have the 'Flags' attribute", typeof(T).FullName));
}
public static bool IsFlagSet<T>(this T value, T flag) where T : struct
{
CheckIsEnum<T>(true);
long lValue = Convert.ToInt64(value);
long lFlag = Convert.ToInt64(flag);
return (lValue & lFlag) != 0;
}
public static IEnumerable<T> GetFlags<T>(this T value) where T : struct
{
CheckIsEnum<T>(true);
foreach (T flag in Enum.GetValues(typeof(T)).Cast<T>())
{
if (value.IsFlagSet(flag))
yield return flag;
}
}
public static T SetFlags<T>(this T value, T flags, bool on) where T : struct
{
CheckIsEnum<T>(true);
long lValue = Convert.ToInt64(value);
long lFlag = Convert.ToInt64(flags);
if (on)
{
lValue |= lFlag;
}
else
{
lValue &= (~lFlag);
}
return (T)Enum.ToObject(typeof(T), lValue);
}
public static T SetFlags<T>(this T value, T flags) where T : struct
{
return value.SetFlags(flags, true);
}
public static T ClearFlags<T>(this T value, T flags) where T : struct
{
return value.SetFlags(flags, false);
}
public static T CombineFlags<T>(this IEnumerable<T> flags) where T : struct
{
CheckIsEnum<T>(true);
long lValue = 0;
foreach (T flag in flags)
{
long lFlag = Convert.ToInt64(flag);
lValue |= lFlag;
}
return (T)Enum.ToObject(typeof(T), lValue);
}
public static string GetDescription<T>(this T value) where T : struct
{
CheckIsEnum<T>(false);
string name = Enum.GetName(typeof(T), value);
if (name != null)
{
FieldInfo field = typeof(T).GetField(name);
if (field != null)
{
DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
}
Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.
I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.
Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.
Remote pick directory path should be the exact path on the ftp server you are tryng to access.. here is the script to download files from the server.. you can add or modify with SSLMode..
#ftp server
$ftp = "ftp://example.com/"
$user = "XX"
$pass = "XXX"
$SetType = "bin"
$remotePickupDir = Get-ChildItem 'c:\test' -recurse
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
foreach($item in $remotePickupDir){
$uri = New-Object System.Uri($ftp+$item.Name)
#$webclient.UploadFile($uri,$item.FullName)
$webclient.DownloadFile($uri,$item.FullName)
}
You can try it by adding
This may not be a technical solution, but it works. (if anyone of your teammate has the same branch in local)
Let's assume your branch name as branch-xxx.
Steps to Solve:
Note: Again, this is not a technical solution, but it will help for sure.
You can access your keys and/or values by calling items() on your dictionary.
for key, value in d.iteritems():
print(key, value)
Do this way:-
String newline = System.getProperty("line.separator");
private static final String mText = "SHOP MA" + newline +
+ "----------------------------" + newline +
+ "Pannampitiya" + newline +
+ "09-10-2012 harsha no: 001" + newline +
+ "No Item Qty Price Amount" + newline +
+ "1 Bread 1 50.00 50.00" + newline +
+ "____________________________" + newline;
An open source GUI tool is available at keystore-explorer.org
KeyStore Explorer
KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.
Following screens will help (they are from the official site)
Default screen that you get by running the command:
shantha@shantha:~$./Downloads/kse-521/kse.sh
And go to Examine
and Examine a URL
option and then give the web URL that you want to import.
The result window will be like below if you give google site link.
This is one of Use case and rest is up-to the user(all credits go to the keystore-explorer.org)
If your DBMS supports the notation, you need a separate set of parentheses for each row:
INSERT INTO Data(Col1) VALUES ('Hello'), ('World');
The cross-referenced question shows examples for inserting into two columns.
Alternatively, every SQL DBMS supports the notation using separate statements, one for each row to be inserted:
INSERT INTO Data (Col1) VALUES ('Hello');
INSERT INTO Data (Col1) VALUES ('World');
If you completely want to clear the session you can use this:
session_unset();
session_destroy();
Actually both are not neccessary but it does not hurt.
If you want to clear only a specific part I think you need this:
unset($_SESSION['Products']);
//or
$_SESSION['Products'] = "";
depending on what you need.
This concise example demonstrates common way how to create custom tooltip in d3.
var w = 500;_x000D_
var h = 150;_x000D_
_x000D_
var dataset = [5, 10, 15, 20, 25];_x000D_
_x000D_
// firstly we create div element that we can use as_x000D_
// tooltip container, it have absolute position and_x000D_
// visibility: hidden by default_x000D_
_x000D_
var tooltip = d3.select("body")_x000D_
.append("div")_x000D_
.attr('class', 'tooltip');_x000D_
_x000D_
var svg = d3.select("body")_x000D_
.append("svg")_x000D_
.attr("width", w)_x000D_
.attr("height", h);_x000D_
_x000D_
// here we add some circles on the page_x000D_
_x000D_
var circles = svg.selectAll("circle")_x000D_
.data(dataset)_x000D_
.enter()_x000D_
.append("circle");_x000D_
_x000D_
circles.attr("cx", function(d, i) {_x000D_
return (i * 50) + 25;_x000D_
})_x000D_
.attr("cy", h / 2)_x000D_
.attr("r", function(d) {_x000D_
return d;_x000D_
})_x000D_
_x000D_
// we define "mouseover" handler, here we change tooltip_x000D_
// visibility to "visible" and add appropriate test_x000D_
_x000D_
.on("mouseover", function(d) {_x000D_
return tooltip.style("visibility", "visible").text('radius = ' + d);_x000D_
})_x000D_
_x000D_
// we move tooltip during of "mousemove"_x000D_
_x000D_
.on("mousemove", function() {_x000D_
return tooltip.style("top", (event.pageY - 30) + "px")_x000D_
.style("left", event.pageX + "px");_x000D_
})_x000D_
_x000D_
// we hide our tooltip on "mouseout"_x000D_
_x000D_
.on("mouseout", function() {_x000D_
return tooltip.style("visibility", "hidden");_x000D_
});
_x000D_
.tooltip {_x000D_
position: absolute;_x000D_
z-index: 10;_x000D_
visibility: hidden;_x000D_
background-color: lightblue;_x000D_
text-align: center;_x000D_
padding: 4px;_x000D_
border-radius: 4px;_x000D_
font-weight: bold;_x000D_
color: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
I'd recommend using boto. Then it's a quick couple of lines of python:
from boto.s3.connection import S3Connection
conn = S3Connection('access-key','secret-access-key')
bucket = conn.get_bucket('bucket')
for key in bucket.list():
print key.name.encode('utf-8')
Save this as list.py, open a terminal, and then run:
$ python list.py > results.txt
I ended up doing something like this for AngularJS in case someone stumbles across this question:
const imageElem = angular.element('#awardImg');
if (imageElem[0].files[0])
vm.award.imageElem = imageElem;
vm.award.image = imageElem[0].files[0];
And then:
if (vm.award.imageElem)
$('#awardImg').replaceWith(vm.award.imageElem);
delete vm.award.imageElem;
Just for those new to iOS buddies (like me) who decided to have multiple cells and in a different xib file, the solution is not to have identifier but to do this:
let cell = Bundle.main.loadNibNamed("newsDetails", owner: self, options: nil)?.first as! newsDetailsTableViewCell
here newsDetails is xib file name.
I used a deque... seems to work for me. This example has a vector, but you could skip that aspect and simply add them to deque.
#include <deque>
template <typename T>
double mov_avg(vector<T> vec, int len){
deque<T> dq = {};
for(auto i = 0;i < vec.size();i++){
if(i < len){
dq.push_back(vec[i]);
}
else {
dq.pop_front();
dq.push_back(vec[i]);
}
}
double cs = 0;
for(auto i : dq){
cs += i;
}
return cs / len;
}
//Skip the vector portion, track the input number (or size of deque), and the value.
double len = 10;
double val; //Accept as input
double instance; //Increment each time input accepted.
deque<double> dq;
if(instance < len){
dq.push_back(val);
}
else {
dq.pop_front();
dq.push_back(val);
}
}
double cs = 0;
for(auto i : dq){
cs += i;
}
double rolling_avg = cs / len;
//To simplify further -- add values to this, then simply average the deque.
int MAX_DQ = 3;
void add_to_dq(deque<double> &dq, double value){
if(dq.size() < MAX_DQ){
dq.push_back(value);
}else {
dq.pop_front();
dq.push_back(value);
}
}
Another sort of hack I use occasionally is using mod to overwrite values in a vector.
vector<int> test_mod = {0,0,0,0,0};
int write = 0;
int LEN = 5;
int instance = 0; //Filler for N -- of Nth Number added.
int value = 0; //Filler for new number.
write = instance % LEN;
test_mod[write] = value;
//Will write to 0, 1, 2, 3, 4, 0, 1, 2, 3, ...
//Then average it for MA.
//To test it...
int write_idx = 0;
int len = 5;
int new_value;
for(auto i=0;i<100;i++){
cin >> new_value;
write_idx = i % len;
test_mod[write_idx] = new_value;
This last (hack) has no buckets, buffers, loops, nothing. Simply a vector that's overwritten. And it's 100% accurate (for avg / values in vector). Proper order is rarely maintained, as it starts rewriting backwards (at 0), so 5th index would be at 0 in example {5,1,2,3,4}, etc.
The oneliner:
open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l])
Recommended with with
:
with open("in.txt") as f:
lines = f.readlines()
lines = [l for l in lines if "ROW" in l]
with open("out.txt", "w") as f1:
f1.writelines(lines)
Using less memory:
with open("in.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
if "ROW" in line:
f1.write(line)
The only way I know is by copying:
List<TestB> list = new ArrayList<TestB> (
Arrays.asList (
testAList.toArray(new TestB[0])
)
);
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b><centre>Redirecting to Google<br>");
response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url after 5 seconds
pw.close();
}
}
This question is very helpfully BUT Don't forget to mount SD Card in your emulator, if you don't do this its doesn't work.
I lose my time before discover this.
Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming
Update March 2013
Git 1.8.2 added the possibility to track branches.
"
git submodule
" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).
# add submodule to track master branch
git submodule add -b master [URL to Git repo];
# update your submodule
git submodule update --remote
If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".
Also see Vogella's tutorial on submodules for general information on submodules.
Note:
git submodule add -b . [URL to Git repo];
^^^
A special value of
.
is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.
See commit b928922727d6691a3bdc28160f93f25712c565f6:
submodule add
: If --branch
is given, record it in .gitmodules
This allows you to easily record a
submodule.<name>.branch
option in.gitmodules
when you add a new submodule. With this patch,
$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>
reduces to
$ git submodule add -b <branch> <repository> [<path>]
This means that future calls to
$ git submodule update --remote ...
will get updates from the same branch that you used to initialize the submodule, which is usually what you want.
Signed-off-by: W. Trevor King [email protected]
Original answer (February 2012):
A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log
within that submodule.
So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:
gitslave (that you already looked at) seems to be the best fit, including for the commit operation.
It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).
Other alternatives are detailed here.
Follow these two steps:
git add remote origin https://github.com/userName/repo.git
Here the repo.git will be your newly created remote repo.This will work like a charm. No need to worry about the SSH or HTTPS ways. I first faced the same issue and spent hours for solution. But this worked for me.
Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:
You can have a look at dozer which is a
Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
Figured it out
class AnimatedFlutterLogo extends StatefulWidget {
@override
State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}
class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
Timer _timer;
FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;
_AnimatedFlutterLogoState() {
_timer = new Timer(const Duration(milliseconds: 400), () {
setState(() {
_logoStyle = FlutterLogoStyle.horizontal;
});
});
}
@override
void dispose() {
super.dispose();
_timer.cancel();
}
@override
Widget build(BuildContext context) {
return new FlutterLogo(
size: 200.0,
textColor: Palette.white,
style: _logoStyle,
);
}
}
The update statement in all versions of SQL looks like:
update table
set col1 = expr1,
col2 = expr2,
. . .
coln = exprn
where some condition
So, the answer is that you separate the assignments using commas and don't repeat the set
statement.
If you are using Java 7+, you may want to use NIO.2, e.g.:
❍ Code:
public static void main(String[] args) throws Exception {
File file = new File("test.csv");
List<String> lines = Files.readAllLines(file.toPath(),
StandardCharsets.UTF_8);
for (String line : lines) {
String[] array = line.split(",", -1);
System.out.println(array[0]);
}
}
❍ Output:
a
1RW
1RW
1RW
1RW
1RW
1RW
1R1W
1R1W
1R1W
You can use the --append
feature of tee
:
cat file01.txt | tee --append bothFiles.txt
cat file02.txt | tee --append bothFiles.txt
Or shorter,
cat file01.txt file02.txt | tee --append bothFiles.txt
I assume the request for no redirection (>>
) comes from the need to use this in xargs
or similar. So if that doesn't count, you can mute the output with >/dev/null
.
as docs say:
Note:
object
does not have a__dict__
, so you can’t assign arbitrary attributes to an instance of theobject
class.
You could just use dummy-class instance.
Use a single formatted text column[1] for storing the tags and use a capable full text search engine to index this. Else you will run into scaling problems when trying to implement boolean queries.
If you need details about the tags you have, you can either keep track of it in a incrementally maintained table or run a batch job to extract the information.
[1] Some RDBMS even provide a native array type which might be even better suited for storage by not needing a parsing step, but might cause problems with the full text search.
There is no official, universal, convention for naming JavaScript files.
There are some various options:
scriptName.js
script-name.js
script_name.js
are all valid naming conventions, however I prefer the jQuery suggested naming convention (for jQuery plugins, although it works for any JS)
jquery.pluginname.js
The beauty to this naming convention is that it explicitly describes the global namespace pollution being added.
foo.js
adds window.foo
foo.bar.js
adds window.foo.bar
Because I left out versioning: it should come after the full name, preferably separated by a hyphen, with periods between major and minor versions:
foo-1.2.1.js
foo-1.2.2.js
foo-2.1.24.js
The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:
document.onkeydown = TabExample;
function TabExample(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var tabKey = 9;
if(evt.keyCode == tabKey) {
// do work
}
}
Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.
$scope.storage = $localStorage; //connects an object to $localstorage
$scope.storage.hasSeenPopup = "false"; // they haven't seen it
$scope.showPopup = function() { // popup to tell people to turn sound on
$scope.data = {}
// An elaborate, custom popup
var myPopup = $ionicPopup.show({
template: '<p class="popuptext">Turn Sound On!</p>',
cssClass: 'popup'
});
$timeout(function() {
myPopup.close(); //close the popup after 3 seconds for some reason
}, 2000);
$scope.storage.hasSeenPopup = "true"; // they've now seen it
};
$scope.playStream = function(show) {
PlayerService.play(show);
$scope.audioObject = audioObject; // this allow for styling the play/pause icons
if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
$scope.showPopup();
}
}
Note: This solution only works for Webkit browsers, which incorrectly apply pseudo-elements to self-closing tags.
As an addendum to above answers it is worth noting that in some cases one needs to insert a space instead of merely ignoring <br>
:
For instance the above answers will turn
Monday<br>05 August
to
Monday05 August
as I had verified while I tried to format my weekly event calendar. A space after "Monday" is preferred to be inserted. This can be done easily by inserting the following in the CSS:
br {
content: ' '
}
br:after {
content: ' '
}
This will make
Monday<br>05 August
look like
Monday 05 August
You can change the content
attribute in br:after
to ', '
if you want to separate by commas, or put anything you want within ' '
to make it the delimiter! By the way
Monday, 05 August
looks neat ;-)
See here for a reference.
As in the above answers, if you want to make it tag-specific, you can. As in if you want this property to work for tag <h3>
, just add a h3
each before br
and br:after
, for instance.
It works most generally for a pseudo-tag.
One can replace unicode
with u''.__class__
to handle the missing unicode
class in Python 3. For both Python 2 and 3, you can use the construct
isinstance(unicode_or_str, u''.__class__)
or
type(unicode_or_str) == type(u'')
Depending on your further processing, consider the different outcome:
Python 3
>>> isinstance('text', u''.__class__)
True
>>> isinstance(u'text', u''.__class__)
True
Python 2
>>> isinstance(u'text', u''.__class__)
True
>>> isinstance('text', u''.__class__)
False
You can make a custom Request class that extends the StringRequest and override the getHeaders() method inside it like this:
public class CustomVolleyRequest extends StringRequest {
public CustomVolleyRequest(int method, String url,
Response.Listener<String> listener,
Response.ErrorListener errorListener) {
super(method, url, listener, errorListener);
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("key1","value1");
headers.put("key2","value2");
return headers;
}
}
put a int
infront of the all the voxelCoord
's...Like this below :
patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]
Your example fails because Thread methods take either one or zero arguments. To create a thread without passing arguments, your code looks like this:
void Start()
{
// do stuff
}
void Test()
{
new Thread(new ThreadStart(Start)).Start();
}
If you want to pass data to the thread, you need to encapsulate your data into a single object, whether that is a custom class of your own design, or a dictionary object or something else. You then need to use the ParameterizedThreadStart delegate, like so:
void Start(object data)
{
MyClass myData = (MyClass)myData;
// do stuff
}
void Test(MyClass data)
{
new Thread(new ParameterizedThreadStart(Start)).Start(data);
}
Using VueJS I tried every method in this question but none worked. So in case somebody is struggling whit the same:
mounted() {
$(document).ready(function() { //<<====== wont work without this
$(window).scroll(function() {
console.log('logging');
});
});
},
First install jquery using npm,
npm install jquery --save
I use:
global.jQuery = require('jquery');
var $ = global.jQuery;
window.$ = $;
You should be able to do this quite easily:
SELECT *
FROM WebPageContent
WHERE data.value('(/PageContent/Text)[1]', 'varchar(100)') LIKE 'XYZ%'
The .value
method gives you the actual value, and you can define that to be returned as a VARCHAR(), which you can then check with a LIKE statement.
Mind you, this isn't going to be awfully fast. So if you have certain fields in your XML that you need to inspect a lot, you could:
With this, you'd basically "extract" a certain portion of the XML into a computed field, make it persisted, and then you can search very efficiently on it (heck: you can even INDEX that field!).
Marc
One of the options is to use the Javascript.
Here is a quick reference where you can start from.
Use Python 2.7, is has more 3rd party libs at the moment. (Edit: see below).
I recommend you using the stdlib module urllib2
, it will allow you to comfortably get web resources.
Example:
import urllib2
response = urllib2.urlopen("http://google.de")
page_source = response.read()
For parsing the code, have a look at BeautifulSoup
.
BTW: what exactly do you want to do:
Just for background, I need to download a page and replace any img with ones I have
Edit: It's 2014 now, most of the important libraries have been ported, and you should definitely use Python 3 if you can. python-requests
is a very nice high-level library which is easier to use than urllib2
.
This is a more general answer to the missing "Select cond1, stmt1, ... else stmtelse" connstruction in R. It's a bit gassy, but it works an resembles the switch statement present in C
while (TRUE) {
if (is.na(val)) {
val <- "NULL"
break
}
if (inherits(val, "POSIXct") || inherits(val, "POSIXt")) {
val <- paste0("#", format(val, "%Y-%m-%d %H:%M:%S"), "#")
break
}
if (inherits(val, "Date")) {
val <- paste0("#", format(val, "%Y-%m-%d"), "#")
break
}
if (is.numeric(val)) break
val <- paste0("'", gsub("'", "''", val), "'")
break
}
you'll probably want to look into jquery-ui dialog. it's highly customizable and can be made to work exactly like lightbox/fancybox and supports everything you would need for a contact form from a regular link.
there is even an example with a form.
Very easy:
To set a menu item's image dynamically, only do the following:
MyMenuItem.ImageSource =
new BitmapImage(new Uri("Resource/icon.ico",UriKind.Relative));
...whereas "icon.ico" can be located everywhere (currently it's located in the 'Resources' directory) and must be linked as Resource...
The keyword extends
can be used for interfaces and classes only.
If you just want to declare a type that has additional properties, you can use intersection type:
type UserEvent = Event & {UserId: string}
UPDATE for TypeScript 2.2, it's now possible to have an interface that extends object-like type, if the type satisfies some restrictions:
type Event = {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent extends Event {
UserId: string;
}
It does not work the other way round - UserEvent
must be declared as interface, not a type
if you want to use extends
syntax.
And it's still impossible to use extend
with arbitrary types - for example, it does not work if Event
is a type parameter without any constraints.
Define an interface, and implement it in the class that will receive the callback.
Have attention to the multi-threading in your case.
Code example from http://cleancodedevelopment-qualityseal.blogspot.com.br/2012/10/understanding-callbacks-with-java.html
interface CallBack { //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
void methodToCallBack();
}
class CallBackImpl implements CallBack { //class that implements the method to callback defined in the interface
public void methodToCallBack() {
System.out.println("I've been called back");
}
}
class Caller {
public void register(CallBack callback) {
callback.methodToCallBack();
}
public static void main(String[] args) {
Caller caller = new Caller();
CallBack callBack = new CallBackImpl(); //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
caller.register(callBack);
}
}
In your case, apart from multi-threading you could do like this:
interface ServerInterface {
void newSeverConnection(Socket socket);
}
public class Server implements ServerInterface {
public Server(int _address) {
System.out.println("Starting Server...");
serverConnectionHandler = new ServerConnections(_address, this);
workers.execute(serverConnectionHandler);
System.out.println("Do something else...");
}
void newServerConnection(Socket socket) {
System.out.println("A function of my child class was called.");
}
}
public class ServerConnections implements Runnable {
private ServerInterface serverInterface;
public ServerConnections(int _serverPort, ServerInterface _serverInterface) {
serverPort = _serverPort;
serverInterface = _serverInterface;
}
@Override
public void run() {
System.out.println("Starting Server Thread...");
if (serverInterface == null) {
System.out.println("Server Thread error: callback null");
}
try {
mainSocket = new ServerSocket(serverPort);
while (true) {
serverInterface.newServerConnection(mainSocket.accept());
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Multi-threading
Remember this does not handle multi-threading, this is another topic and can have various solutions depending on the project.
The observer-pattern
The observer-pattern does nearly this, the major difference is the use of an ArrayList
for adding more than one listener. Where this is not needed, you get better performance with one reference.
Machine A:
In the Visual Studio Code PowerShell terminal:
code --list-extensions > extensions.list
Machine B:
Copy extension.list to the machine B
In the Visual Studio Code PowerShell terminal:
cat extensions.list |% { code --install-extension $_}
You didn't paste the part where you call startActivity
, that's the interesting part.
You might be calling startActivity
in a Service
context, or in an Application
context.
Print "this" to log cat before making the startActivity
call, and see what it refers to, it's sometimes a case of using an inner "this" accidentally.
As per PHP Documentation,
Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won't collide with another thread.
So what do I choose? If you choose to run PHP as a CGI binary, then you won't need thread safety, because the binary is invoked at each request. For multithreaded webservers, such as IIS5 and IIS6, you should use the threaded version of PHP.
Following Libraries are not thread safe. They are not recommended for use in a multi-threaded environment.
Most times SDL is in /usr/include/SDL
. If so then your #include <SDL.h>
directive is wrong, it should be #include <SDL/SDL.h>
.
An alternative for that is adding the /usr/include/SDL
directory to your include directories. To do that you should add -I/usr/include/SDL
to the compiler flags...
If you are using an IDE this should be quite easy too...
it is possible to remove leading and trailing zeros in TSQL
Convert it to string using STR TSQL function if not string, Then
Remove both leading & trailing zeros
SELECT REPLACE(RTRIM(LTRIM(REPLACE(AccNo,'0',' '))),' ','0') AccNo FROM @BankAccount
More info on forum.
Please use chomp()
or chomp()
with STDIN
i.e. test1.rb
print 'Enter File name: '
fname = STDIN.gets.chomp() # or fname = gets.chomp()
fname_read = File.open(fname)
puts fname_read.read()
Try this:
public static boolean isAvailable(Context ctx, Intent intent) {
final PackageManager mgr = ctx.getPackageManager();
List<ResolveInfo> list =
mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
Another way, is simply add the headers to your route:
router.get('/', function(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
res.setHeader('Access-Control-Allow-Credentials', true); // If needed
res.send('cors problem fixed:)');
});
"Better" is subjective.
querySelector
is the newer feature.
getElementById
is better supported than querySelector
.
querySelector
is better supported than getElementsByClassName
.
querySelector
lets you find elements with rules that can't be expressed with getElementById
and getElementsByClassName
You need to pick the appropriate tool for any given task.
(In the above, for querySelector
read querySelector
/ querySelectorAll
).
I believe you are not the only one who has problems when trying to deploy Crystal Report for VS 2010. Based on the error message you had, have you checked:
Please make sure you just have one CR version installed on your system. If you do have other CR version installed, consider to uninstall it so that your application is not "confused" about the CR version.
You need to make sure you download the correct CR version. Since you are using VS 2010, you need to refer to CRforVS_redist_install_64bit_13_0_1.zip (for 64 bit machine) or CRforVS_redist_install_32bit_13_0_1.zip (for 32 bit machine). These two are the redistributable packages. You can download full package from the below link as well: CRforVS_13_0_1.exe Note: It is sometimes necessary to install 32bit CR runtime even on 64bit OS
Make sure you setup FULL TRUST permission on your root folder
The LOCAL SERVICE permission must be setup on your application pool
Make sure the aspnet_client folder exists on your root folder.
If you can make sure all the 5 points above, your Crystal Report should work without any fuss.
Another important thing to note down here is that if you host your Crystal Report with a shared host, you need to check it with them of whether they really support Crystal Report. If you still have problems, you can switch to http://www.asphostcentral.com, who provides Crystal Report support.
Good luck!
One global solution is to put <base target="_blank">
into your page's <head>
element. That effectively adds a default target to every anchor element. I use markdown to create content on my Wordpress-based web site, and my theme customizer will let me inject that code into the top of every page. If your theme doesn't do that, there's a plug-in
I was struggling for hours on this until I figured out it can be done in one line of powershell:
invoke-webrequest -Uri "http://myserver/Reports/Pages/ReportViewer.aspx?%2fClients%2ftest&rs:Format=PDF&rs:ClearSession=true&CaseCode=12345678" -OutFile "C:\Temp\test.pdf" -UseDefaultCredentials
I looked into doing it purely in VBA but it runs to several pages, so I just call my powershell script from VBA every time I want to download a file.
Simple.
Two important notes:
You need to call layoutIfNeeded
within the animation block. Apple actually recommends you call it once before the animation block to ensure that all pending layout operations have been completed
You need to call it specifically on the parent view (e.g. self.view
), not the child view that has the constraints attached to it. Doing so will update all constrained views, including animating other views that might be constrained to the view that you changed the constraint of (e.g. View B is attached to the bottom of View A and you just changed View A's top offset and you want View B to animate with it)
Try this:
Objective-C
- (void)moveBannerOffScreen {
[self.view layoutIfNeeded];
[UIView animateWithDuration:5
animations:^{
self._addBannerDistanceFromBottomConstraint.constant = -32;
[self.view layoutIfNeeded]; // Called on parent view
}];
bannerIsVisible = FALSE;
}
- (void)moveBannerOnScreen {
[self.view layoutIfNeeded];
[UIView animateWithDuration:5
animations:^{
self._addBannerDistanceFromBottomConstraint.constant = 0;
[self.view layoutIfNeeded]; // Called on parent view
}];
bannerIsVisible = TRUE;
}
Swift 3
UIView.animate(withDuration: 5) {
self._addBannerDistanceFromBottomConstraint.constant = 0
self.view.layoutIfNeeded()
}
The encodings are spelled out in the buffer documentation.
Character Encodings
utf8
: Multi-byte encoded Unicode characters. Many web pages and other document formats use UTF-8. This is the default character encoding.utf16le
: Multi-byte encoded Unicode characters. Unlikeutf8
, each character in the string will be encoded using either 2 or 4 bytes.latin1
: Latin-1 stands for ISO-8859-1. This character encoding only supports the Unicode characters fromU+0000
toU+00FF
.Binary-to-Text Encodings
base64
: Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC 4648, Section 5.hex
: Encode each byte as two hexadecimal characters.Legacy Character Encodings
ascii
: For 7-bit ASCII data only. Generally, there should be no reason to use this encoding, as 'utf8' (or, if the data is known to always be ASCII-only, 'latin1') will be a better choice when encoding or decoding ASCII-only text.binary
: Alias for 'latin1'.ucs2
: Alias of 'utf16le'.
If you want the .wrapper
to be fullscreen, just add the following in the wrapper class:
position: absolute;
width: 100%;
height: 100%;
You can also add top: 0
and left:0
You should use the arc4random_uniform()
function. It uses a superior algorithm to rand
. You don't even need to set a seed.
#include <stdlib.h>
// ...
// ...
int r = arc4random_uniform(74);
The arc4random
man page:
NAME arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <stdlib.h> u_int32_t arc4random(void); void arc4random_stir(void); void arc4random_addrandom(unsigned char *dat, int datlen); DESCRIPTION The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo- random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and random(3). The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via arc4random_addrandom(). There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically initializes itself. EXAMPLES The following produces a drop-in replacement for the traditional rand() and random() functions using arc4random(): #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))
From http://www.sqlite.org/lang_createtable.html:
CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);
from pandas.io import sql
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
.format(user="root",
pw="your_password",
db="pandas"))
df.to_sql(con=engine, name='table_name', if_exists='replace')
open Terminal
cd /usr/local/mysql/support-files
sudo nano mysql.server
Find the lines:
basedir=
datadir=
change them to
basedir=/usr/local/mysql
datadir=/usr/local/mysql/data
Morgan should not be used to log in the way you're describing. Morgan was built to do logging in the way that servers like Apache and Nginx log to the error_log or access_log. For reference, this is how you use morgan:
var express = require('express'),
app = express(),
morgan = require('morgan'); // Require morgan before use
// You can set morgan to log differently depending on your environment
if (app.get('env') == 'production') {
app.use(morgan('common', { skip: function(req, res) { return res.statusCode < 400 }, stream: __dirname + '/../morgan.log' }));
} else {
app.use(morgan('dev'));
}
Note the production line where you see morgan called with an options hash {skip: ..., stream: __dirname + '/../morgan.log'}
The stream
property of that object determines where the logger outputs. By default it's STDOUT (your console, just like you want) but it'll only log request data. It isn't going to do what console.log()
does.
If you want to inspect things on the fly use the built in util
library:
var util = require('util');
console.log(util.inspect(anyObject)); // Will give you more details than console.log
So the answer to your question is that you're asking the wrong question. But if you still want to use Morgan for logging requests, there you go.
What is the difference between Attribute and Property?
What is the difference between Feature and Function?
What is the difference between Characteristic and Character?
What is the difference between Act and Behavior?
Its just a change in context.
Object,Product,Personality,Person
A Person Acts in a Behavior. A Personality has Characteristics of a given Character. A Product has Feature that derive Functionality. An Object had Attributes that give it Properties.
If you don't want to have to specify the version every time you use pip:
Install pip:
$ curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python3
and export the path:
$ export PATH=/Library/Frameworks/Python.framework/Versions/<version number>/bin:$PATH
SELECT * INTO newtable
FROM oldtable
WHERE 1 = 0;
Create a new, empty table using the schema of another. Just add a WHERE clause that causes the query to return no data:
My first impression was that you were wanting a looping command-prompt with looping user-input inside of that looping command-prompt. (Nested user-input.) Maybe it's not what you wanted, but I already wrote this answer before I realized that. So, I'm going to post it in case other people (or even you) find it useful.
You just need nested loops with an input statement at each loop's level.
For instance,
data=""
while 1:
data=raw_input("Command: ")
if data in ("test", "experiment", "try"):
data2=""
while data2=="":
data2=raw_input("Which test? ")
if data2=="chemical":
print("You chose a chemical test.")
else:
print("We don't have any " + data2 + " tests.")
elif data=="quit":
break
else:
pass
Assuming staff_id + date form a uk, this is another method:
SELECT STAFF_ID, SITE_ID, PAY_LEVEL
FROM TABLE t
WHERE END_ENROLLMENT_DATE is null
AND DATE = (SELECT MAX(DATE)
FROM TABLE
WHERE staff_id = t.staff_id
AND DATE <= SYSDATE)
I had the same problem. 2.0 worked fine. after installing up to 3.5 sp1, application gets Access Violation.
installed http://support.microsoft.com/kb/971030 and my problem is solved, even though I am not using LCG.
SELECT CONVERT(INT, 11.4)
RESULT: 11
SELECT CONVERT(INT, 11.6)
RESULT: 11
I use this technique for pagination. I do not fetch all the rows. For example, if my page needs to display the top 100 rows I fetch only the 100 with where clause. The output of the SQL should have a unique key.
The table has the following:
ID, KeyId, Rank
The same rank will be assigned for more than one KeyId.
SQL is select top 2 * from Table1 where Rank >= @Rank and ID > @Id
For the first time I pass 0 for both. The second time pass 1 & 14. 3rd time pass 2 and 6....
The value of the 10th record Rank & Id is passed to the next
11 21 1
14 22 1
7 11 1
6 19 2
12 31 2
13 18 2
This will have the least stress on the system
As a comment, I had to allow a customer to execute a class in a jar which meant that the manifest file couldn't be modified (they couldn't be expected to do that). Thanks to the post by Anthony and samy-delux's comment, this is what the customer can now run to access the main of the specific class:
java -cp c:\path\to\jar\jarFile.jar com.utils.classpath -e -v textString
Old style classes are still marginally faster for attribute lookup. This is not usually important, but it may be useful in performance-sensitive Python 2.x code:
In [3]: class A: ...: def __init__(self): ...: self.a = 'hi there' ...: In [4]: class B(object): ...: def __init__(self): ...: self.a = 'hi there' ...: In [6]: aobj = A() In [7]: bobj = B() In [8]: %timeit aobj.a 10000000 loops, best of 3: 78.7 ns per loop In [10]: %timeit bobj.a 10000000 loops, best of 3: 86.9 ns per loop
.row {
letter-spacing: -.31em;
word-spacing: -.43em;
}
.col-md-4 {
float: none;
display: inline-block;
vertical-align: middle;
}
Note: .col-md-4 could be any grid column, its just an example here.
Unfortunately, there is no guaranteed way to do it at time of selection.
Some browsers support the accept
attribute for input
tags. This is a good start, but cannot be relied upon completely.
<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
You can use a cfinput
and run a validation to check the file extension at submission, but not the mime-type. This is better, but still not fool-proof. Files on OSX often have no file extensions or users could maliciously mislabel the file types.
ColdFusion's cffile
can check the mime-type using the contentType
property of the result (cffile.contentType
), but that can only be done after the upload. This is your best bet, but is still not 100% safe as mime-types could still be wrong.
Nope, this is not possible at all. There is no provision for it in the mailto:
protocol, and it would be a gaping security hole if it were possible.
The best idea to send a file, but have the client send the E-Mail that I can think of is:
mailto:
link that contains the URL to the uploaded file in the message body Not having a compiler by me right now, I'll answer by asking a question:
Have you tried this? Does it work?
long key = -1L;
PreparedStatement statement = connection.prepareStatement();
statement.executeUpdate(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
key = rs.getLong(1);
}
Disclaimer: Obviously, I haven't compiled this, but you get the idea.
PreparedStatement is a subinterface of Statement, so I don't see a reason why this wouldn't work, unless some JDBC drivers are buggy.
On Windows (IIS) in order to be able to SET GLOBAL time_zone = 'Europe/Helsinki' (or whatever) the MySQL time_zone description tables need to be populated first.
I downloaded these from this link https://dev.mysql.com/downloads/timezones.html
After running the downloaded SQL query I was able to set the GLOBAL time_zone and resolve the issue I had where SELECT NOW(); was returning GMT rather than BST.
"Not equals" can be expressed with the "not" operator !
and the standard .equals
.
if (a.equals(b)) // a equals b
if (!a.equals(b)) // a not equal to b
This is a variation on hexacyanide's answer above. This middleware also handles the 'data' event but does not wait for the data to be consumed before calling 'next'. This way both this middleware and bodyParser may coexist, consuming the stream in parallel.
app.use(function(req, res, next) {
req.rawBody = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
req.rawBody += chunk;
});
next();
});
app.use(express.bodyParser());
Posting another script solution DateX (author) for anyone interested
DateX does NOT wrap the original Date
object, but instead offers an identical interface with additional methods to format, localise, parse, diff and validate dates easily. So one can just do new DateX(..)
instead of new Date(..)
or use the lib as date utilities or even as wrapper or replacement around Date
class.
The date format used is identical to php date format.
c-like format is also supported (although not fully)
for the example posted (YYYY/mm/dd hh:m:sec
) the format to use would be Y/m/d H:i:s
eg
var formatted_date = new DateX().format('Y/m/d H:i:s');
or
var formatted_now_date_gmt = new DateX(DateX.UTC()).format('Y/m/d H:i:s');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC
Following on from LachlanB's answer, if your ApiController doesn't sit within a particular directory (like /api) you can instead test the request using RouteTable.Routes.GetRouteData, for example:
protected void Application_PostAuthorizeRequest()
{
// WebApi SessionState
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
if (routeData != null && routeData.RouteHandler is HttpControllerRouteHandler)
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
simple and easier solution:
select extract(hour from systimestamp) from dual;
EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
16
You also follow this code:
var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("Users doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
StatusCode = HttpStatusCode.NotFound
}
throw new HttpResponseException(response);
You can do it with Linq, as mamoo showed, but the oldies are good too:
var filteredDataTable = dt.Select(@"EmpId > 2
AND (EmpName <> 'abc' OR EmpName <> 'xyz')
AND EmpName like '%il%'" );
Try this:
function reload(){_x000D_
var container = document.getElementById("yourDiv");_x000D_
var content = container.innerHTML;_x000D_
container.innerHTML= content; _x000D_
_x000D_
//this line is to watch the result in console , you can remove it later _x000D_
console.log("Refreshed"); _x000D_
}
_x000D_
<a href="javascript: reload()">Click to Reload</a>_x000D_
<div id="yourDiv">The content that you want to refresh/reload</div>
_x000D_
Hope it works. Let me know
To write simpler,
enum class Color
{
Red = 1,
Green = 11,
Blue = 111
};
int value = static_cast<int>(Color::Blue); // 111
a simple line , after that you can see also a doted line
import java.awt.*;
import javax.swing.*;
import java.awt.Graphics.*;
import java.awt.Graphics2D.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BasicStroke;
import java.awt.Event.*;
import java.awt.Component.*;
import javax.swing.SwingUtilities;
/**
*
* @author junaid
*/
public class JunaidLine extends JPanel{
//private Graphics Graphics;
private void doDrawing(Graphics g){
Graphics2D g2d=(Graphics2D) g;
float[] dash1 = {2f,0f,2f};
g2d.drawLine(20, 40, 250, 40);
BasicStroke bs1 = new BasicStroke(1,BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND,1.0f,dash1,2f);
g2d.setStroke(bs1);
g2d.drawLine(20, 80, 250, 80);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent( g);
doDrawing(g);
}
}
class BasicStrokes extends JFrame{
public BasicStrokes(){
initUI();
}
private void initUI(){
setTitle("line");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
add(new JunaidLine());
setSize(280,270);
setLocationRelativeTo(null);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
BasicStrokes bs = new BasicStrokes();
bs.setVisible(true);
}
});
}
}
I was facing exactly the same problem. With Windows Vista I could not reproduce the problem but on Ubuntu I reproduced the 'connection reset'-Error constantly.
I found http://forums.oracle.com/forums/thread.jspa?threadID=941911&tstart=0&messageID=3793101
According to a user on that forum:
I opened a ticket with Oracle and this is what they told me.
java.security.SecureRandom is a standard API provided by sun. Among various methods offered by this class void nextBytes(byte[]) is one. This method is used for generating random bytes. Oracle 11g JDBC drivers use this API to generate random number during login. Users using Linux have been encountering SQLException("Io exception: Connection reset").
The problem is two fold
The JVM tries to list all the files in the /tmp (or alternate tmp directory set by -Djava.io.tmpdir) when SecureRandom.nextBytes(byte[]) is invoked. If the number of files is large the method takes a long time to respond and hence cause the server to timeout
The method void nextBytes(byte[]) uses /dev/random on Linux and on some machines which lack the random number generating hardware the operation slows down to the extent of bringing the whole login process to a halt. Ultimately the the user encounters SQLException("Io exception: Connection reset")
Users upgrading to 11g can encounter this issue if the underlying OS is Linux which is running on a faulty hardware.
Cause The cause of this has not yet been determined exactly. It could either be a problem in your hardware or the fact that for some reason the software cannot read from dev/random
Solution Change the setup for your application, so you add the next parameter to the java command:
-Djava.security.egd=file:/dev/../dev/urandom
We made this change in our java.security file and it has gotten rid of the error.
which solved my problem.
In my case the database statistics had become corrupt. The statement
delete from tablename where col1 = 'v1'
was taking 30 seconds even though there were no matching records but
delete from tablename where col1 = 'rubbish'
ran instantly
running
update statistics tablename
fixed the issue
This should work:
for /F "tokens=*" %i in ('temperature') do prismcom.exe usb %i
If running in a batch file, you need to use %%i
instead of just %i
(in both places).
I may have found a fix: "make sure all shapes on the worksheet have unique names" (including checkboxes/radio buttons (OLE controls) as well as Pictures and other shape types...)
Because the problem is intermittent, I can not guarantee this. I have two forms now working fine using this fix, but "two" is a very small sample set, and could just be coincidence. Never the less, these are steps I took:
I listed all shapes in the problem sheet (wsForm) on a blank sheet (Sheet1):
Sub ListShapes()
Dim spShape As Shape
Dim intRow As Integer
Sheet1.Range("A1:F1") = Array("Name", "Left", "Top", "Width", "Height", "Bottom Right Cell")
intRow = 2
For Each spShape In wsForm.Shapes
Sheet1.Cells(intRow, 1).Value = spShape.Name
Sheet1.Cells(intRow, 2).Value = spShape.Left
Sheet1.Cells(intRow, 3).Value = spShape.Top
Sheet1.Cells(intRow, 4).Value = spShape.Width
Sheet1.Cells(intRow, 5).Value = spShape.Height
Sheet1.Cells(intRow, 6).Value = spShape.BottomRightCell.Address
intRow = intRow + 1
Next
End Sub
I then counted each shape name in column A, using a formula in column G:
=COUNTIF($A$2:$A$120,A2)
Obviously adjust range to suit... You can then filter on all shapes that don't have a "1" in this column. The "bottom right cell" helps you find the shape on your worksheet: rename by selecting the shape, then entering new unique value in the name/reference box at top left of Excel.
This shape list also helped find some "dead" shapes (0 height or 0 width) which were long forgotten and unused.
I hope this works for you! For that matter... I hope it works for ME for future occurrences...
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
Initially starting with a pyspark dataframes - I got type conversion errors (when converting to pandas df's and then appending to csv) given the schema/column types in my pyspark dataframes
Solved the problem by forcing all columns in each df to be of type string and then appending this to csv as follows:
with open('testAppend.csv', 'a') as f:
df2.toPandas().astype(str).to_csv(f, header=False)
var img = new Image();
img.onload = function(){
var height = img.height;
var width = img.width;
// code here to use the dimensions
}
img.src = url;
You can use password from text box like key... With this code you can encrypt/decrypt text, picture, word document, pdf....
public class Rijndael
{
private byte[] key;
private readonly byte[] vector = { 255, 64, 191, 111, 23, 3, 113, 119, 231, 121, 252, 112, 79, 32, 114, 156 };
ICryptoTransform EnkValue, DekValue;
public Rijndael(byte[] key)
{
this.key = key;
RijndaelManaged rm = new RijndaelManaged();
rm.Padding = PaddingMode.PKCS7;
EnkValue = rm.CreateEncryptor(key, vector);
DekValue = rm.CreateDecryptor(key, vector);
}
public byte[] Encrypt(byte[] byte)
{
byte[] enkByte= byte;
byte[] enkNewByte;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, EnkValue, CryptoStreamMode.Write))
{
cs.Write(enkByte, 0, enkByte.Length);
cs.FlushFinalBlock();
ms.Position = 0;
enkNewByte= new byte[ms.Length];
ms.Read(enkNewByte, 0, enkNewByte.Length);
}
}
return enkNeyByte;
}
public byte[] Dekrypt(byte[] enkByte)
{
byte[] dekByte;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, DekValue, CryptoStreamMode.Write))
{
cs.Write(enkByte, 0, enkByte.Length);
cs.FlushFinalBlock();
ms.Position = 0;
dekByte= new byte[ms.Length];
ms.Read(dekByte, 0, dekByte.Length);
}
}
return dekByte;
}
}
Convert password from text box to byte array...
private byte[] ConvertPasswordToByte(string password)
{
byte[] key = new byte[32];
for (int i = 0; i < passwprd.Length; i++)
{
key[i] = Convert.ToByte(passwprd[i]);
}
return key;
}
If "debugging information" means the values present when exception was raised, then logging.exception(...)
won't help. So you'll need a tool that logs all variable values along with the traceback lines automatically.
Out of the box you'll get log like
2020-03-30 18:24:31 main ERROR File "./temp.py", line 13, in get_ratio
2020-03-30 18:24:31 main ERROR return height / width
2020-03-30 18:24:31 main ERROR height = 300
2020-03-30 18:24:31 main ERROR width = 0
2020-03-30 18:24:31 main ERROR builtins.ZeroDivisionError: division by zero
Have a look at some pypi tools, I'd name:
Some of them give you pretty crash messages:
But you might find some more on pypi
If you are looking to do this from Windows 10 IoT, then there is a built in command you can use:
setcomputername [newname]
Unfortunately, this command does not exist in the full build of Windows 10.
For SQL Server, if using a newer version, you can use
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'
There are different ways to get the schema. Using ADO.NET, you can use the schema methods. Use the DbConnection
's GetSchema
method or the DataReader
'sGetSchemaTable
method.
Provided that you have a reader for the for the query, you can do something like this:
using(DbCommand cmd = ...)
using(var reader = cmd.ExecuteReader())
{
var schema = reader.GetSchemaTable();
foreach(DataRow row in schema.Rows)
{
Debug.WriteLine(row["ColumnName"] + " - " + row["DataTypeName"])
}
}
See this article for further details.
Sqlite database override two methods
1) onCreate(): This method invoked only once when the application is start at first time . So it called only once
2)onUpgrade() This method called when we change the database version,then this methods gets invoked.It is used for the alter the table structure like adding new column after creating DB Schema
This also works fine, testing by type against undefined
.
if (currentData[index] === undefined){return}
Test:
const fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
_x000D_
if (fruits["Raspberry"] === undefined){_x000D_
console.log("No Raspberry entry in fruits!")_x000D_
}
_x000D_
In .net VB - you could achieve control over columns and rows with the following in your razor file:
@Html.EditorFor(Function(model) model.generalNotes, New With {.htmlAttributes = New With {.class = "someClassIfYouWant", .rows = 5,.cols=6}})
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
Assuming you already have a application created under google developer console, Follow the below steps
https://console.cloud.google.com/apis/dashboard?
you will be getting the below page Note: Please use a server to load the html
file
Convert binary to Hex
Convert.ToString(Convert.ToUInt32(binary1, 2), 16).ToUpper()
If you're willing to adopt the practice of always using curly braces in your if statements,
Your macro would simply be missing the last semicolon:
#define MACRO(X,Y) \
cout << "1st arg is:" << (X) << endl; \
cout << "2nd arg is:" << (Y) << endl; \
cout << "Sum is:" << ((X)+(Y)) << endl
Example 1: (compiles)
if (x > y) {
MACRO(x, y);
}
do_something();
Example 2: (compiles)
if (x > y) {
MACRO(x, y);
} else {
MACRO(y - x, x - y);
}
Example 3: (doesn't compile)
do_something();
MACRO(x, y)
do_something();
I think I have an idea. This has been doing my nut in too and I'm still having trouble getting it to display in Chrome.
Save document(name.docx) in word as single file webpage (name.mht) In your html use
<iframe src= "name.mht" width="100%" height="800"> </iframe>
Alter the heights and widths as you see fit.
Just to reword Itai's excellent (and working!) code, here's what a sample helper class would look like, to return the year value of a given NSDate variable.
As you can see, it's easy enough to modify this code to get the month or day.
+(int)getYear:(NSDate*)date
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
int year = [components year];
int month = [components month];
int day = [components day];
return year;
}
(I can't believe we're having to write our own basic iOS date functions like this, in 2013...)
One other thing: don't ever use < and > to compare two NSDate values.
XCode will happily accept such code (without any errors or warnings), but its results are a lottery. You must use the "compare" function to compare NSDates:
if ([date1 compare:date2] == NSOrderedDescending) {
// date1 is greater than date2
}
In C++17 there exists a class std::filesystem::path
using the method parent_path
.
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
for(fs::path p : {"/var/tmp/example.txt", "/", "/var/tmp/."})
std::cout << "The parent path of " << p
<< " is " << p.parent_path() << '\n';
}
Possible output:
The parent path of "/var/tmp/example.txt" is "/var/tmp"
The parent path of "/" is ""
The parent path of "/var/tmp/." is "/var/tmp"
The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.
src: ##
##https://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator
Take some base date which is the 31st of some month e.g. '20011231'. Then use the
following procedure (I have given 3 identical examples below, only the @dt value differs).
declare @dt datetime;
set @dt = '20140312'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
set @dt = '20140208'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
set @dt = '20140405'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
This is example how to use all columns from worksheet:
$sheet = $PHPExcel->getActiveSheet();
$cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
$cellIterator->setIterateOnlyExistingCells( true );
/** @var PHPExcel_Cell $cell */
foreach( $cellIterator as $cell ) {
$sheet->getColumnDimension( $cell->getColumn() )->setAutoSize( true );
}
Using SSH
git remote add origin ssh://login@IP/path/to/repository
Using HTTP
git remote add origin http://IP/path/to/repository
However having a simple git pull
as a deployment process is usually a bad idea and should be avoided in favor of a real deployment script.
You need to name the file in both directory paths.
scp [email protected]:/dir/of/file.txt \local\dir\file.txt
If you are looping through a lot of cells, use the binary function, it is much faster. Using "<> 0" in place of "> 0" also makes it faster:
If InStrB(1, myString, "a", vbBinaryCompare) <> 0
Plain old Java on plain old Java 7 and no other dependencies demonstrates the difference...
I put file.txt
in c:\temp\
and I put c:\temp\
on the classpath.
There is only one case where there is a difference between the two call.
class J {
public static void main(String[] a) {
// as "absolute"
// ok
System.err.println(J.class.getResourceAsStream("/file.txt") != null);
// pop
System.err.println(J.class.getClassLoader().getResourceAsStream("/file.txt") != null);
// as relative
// ok
System.err.println(J.class.getResourceAsStream("./file.txt") != null);
// ok
System.err.println(J.class.getClassLoader().getResourceAsStream("./file.txt") != null);
// no path
// ok
System.err.println(J.class.getResourceAsStream("file.txt") != null);
// ok
System.err.println(J.class.getClassLoader().getResourceAsStream("file.txt") != null);
}
}
The mistake I made that coerced this error was attempting to rename a column in a loop that I was no longer selecting in my SQL. This could also be caused by trying to do the same thing in a column that you were planning to select. Make sure the column that you are trying to change actually exists.
Taken from here:
The following command finds folders that are greater than 100 MB in size on the D: drive:
diruse /s /m /q:100 /d d:
The /s option causes subdirectories to be searched, the /m option displays disk usage in megabytes, the /q:100 option causes folders that are greater than 100 MB to be marked, and the /d option displays only folders that exceed the threshold specified by /q.
Use the diskuse command to find files over a certain size. The following command displays files over 100 MB in size on the D: drive:
diskuse D: /x:104857600 /v /s
The /x:104857600 option causes files over 104,857,600 bytes to be displayed and is valid only if you include the /v option (verbose). The /s option means subdirectories from the specified path (in this case, the D: drive) are searched.
Using VBScript
' This code finds all files over a certain size.
' ------ SCRIPT CONFIGURATION ------
strComputer = "**<ServerName>**"
intSizeBytes = 1024 * 1024 * 500 ' = 500 MB
' ------ END CONFIGURATION ---------
set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
set colFiles = objWMI.ExecQuery _
("Select * from CIM_DataFile where FileSize > '" & intSizeBytes & "'")
for each objFile in colFiles
Wscript.Echo objFile.Name & " " & objFile.Filesize / 1024 / 1024 & "MB"
next
There are certain things you have to take care:
NotFoundException
that are encountered by default in the until
condition.To invoke click()
as soon as the element is returned, you can use:
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]"))).click();
To simply validate if the element is located and clickable, wrap up the WebDriverWait in a try-catch{}
block as follows:
try {
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")));
System.out.println("Element is clickable");
}
catch(TimeoutException e) {
System.out.println("Element isn't clickable");
}
If WebDriverWait returns the located and clickable element but the element is still not clickable, you need to invoke executeScript()
method as follows:
WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);
I dont know how many of you noticed this. Support library "appcompat_v7" and your project should be in a same directory(I mean workspace directory). Dont clean your project until its error free else you will have tough time with R.java
G'day, I too can say that I tried everything mentioned in these posts and a few more from elsewhere. The #1 problem for me was that the new Intent always had a null bundle. My issue was in focusing too much on the details of "have I included .this or .that". My solution was in taking a step back from the detail and looking at the overall structure of the notification. When I did that I managed to place the key parts of the code in the correct sequence. So, if you're having similar issues check for:
1. Intent notificationIntent = new Intent(MainActivity.this, NotificationActivity.class);
2a. Bundle bundle = new Bundle();
//I like specifying the data type much better. eg bundle.putInt
2b. notificationIntent.putExtras(bundle);
3. PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, WIZARD_NOTIFICATION_ID, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
4. NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
5. NotificationCompat.Builder nBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(title)
.setContentText(content)
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setAutoCancel(false)//false is standard. true == automatically removes the notification when the user taps it.
.setColor(getResources().getColor(R.color.colorPrimary))
.setCategory(Notification.CATEGORY_REMINDER)
.setPriority(Notification.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationManager.notify(WIZARD_NOTIFICATION_ID, nBuilder.build());
With this sequence I get a valid bundle.
It seems you don't want to keep the whole DataTable as a copy, because you only need some rows, right? If you got a creteria you can specify with a select on the table, you could copy just those rows to an extra backup array of DataRow like
DataRow[] rows = sourceTable.Select("searchColumn = value");
The .Select() function got several options and this one e.g. can be read as a SQL
SELECT * FROM sourceTable WHERE searchColumn = value;
Then you can import the rows you want as described above.
targetTable.ImportRows(rows[n])
...for any valid n you like, but the columns need to be the same in each table.
Some things you should know about ImportRow is that there will be errors during runtime when using primary keys!
First I wanted to check whether a row already existed which also failed due to a missing primary key, but then the check always failed. In the end I decided to clear the existing rows completely and import the rows I wanted again.
The second issue did help to understand what happens. The way I'm using the import function is to duplicate rows with an exchanged entry in one column. I realized that it always changed and it still was a reference to the row in the array. I first had to import the original and then change the entry I wanted.
The reference also explains the primary key errors that appeared when I first tried to import the row as it really was doubled up.
plt.close()
will close current instance.
plt.close(2)
will close figure 2
plt.close(plot1)
will close figure with instance plot1
plt.close('all')
will close all fiures
Found here.
Remember that plt.show()
is a blocking function, so in the example code you used above, plt.close()
isn't being executed until the window is closed, which makes it redundant.
You can use plt.ion()
at the beginning of your code to make it non-blocking, although this has other implications.
After our discussion in the comments, I've put together a bit of an example just to demonstrate how the plot functionality can be used.
Below I create a plot:
fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
....
par_plot, = plot(x_data,y_data, lw=2, color='red')
In this case, ax
above is a handle to a pair of axes. Whenever I want to do something to these axes, I can change my current set of axes to this particular set by calling axes(ax)
.
par_plot
is a handle to the line2D instance. This is called an artist. If I want to change a property of the line, like change the ydata, I can do so by referring to this handle.
I can also create a slider widget by doing the following:
axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)
The first line creates a new axes for the slider (called axsliderA
), the second line creates a slider instance sA
which is placed in the axes, and the third line specifies a function to call when the slider value changes (update
).
My update function could look something like this:
def update(val):
A = sA.val
B = sB.val
C = sC.val
y_data = A*x_data*x_data + B*x_data + C
par_plot.set_ydata(y_data)
draw()
The par_plot.set_ydata(y_data)
changes the ydata property of the Line2D object with the handle par_plot
.
The draw()
function updates the current set of axes.
Putting it all together:
from pylab import *
import matplotlib.pyplot as plt
import numpy
def update(val):
A = sA.val
B = sB.val
C = sC.val
y_data = A*x_data*x_data + B*x_data + C
par_plot.set_ydata(y_data)
draw()
x_data = numpy.arange(-100,100,0.1);
fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)
ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')
axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)
axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)
axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)
axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;
par_plot, = plot(x_data,y_data, lw=2, color='red')
show()
A note about the above: When I run the application, the code runs sequentially right through (it stores the update
function in memory, I think), until it hits show(), which is blocking. When you make a change to one of the sliders, it runs the update function from memory (I think?).
This is the reason why show() is implemented in the way it is, so that you can change values in the background by using functions to process the data.
You can have just one ng-view
.
You can change its content in several ways: ng-include
, ng-switch
or mapping different controllers and templates through the routeProvider.
You can use retainAll method and get the intersection of your two sets.
// import
const fs = require('fs') // in javascript
import * as fs from "fs" // in typescript
import fs from "fs" // in typescript
// use
!fs.existsSync(`./assets/`) && fs.mkdirSync(`./assets/`, { recursive: true })
//in html
<nav class="navbar navbar-default" id="mainnav">
<nav>
// add in jquery
$(document).ready(function() {
var navpos = $('#mainnav').offset();
console.log(navpos.top);
$(window).bind('scroll', function() {
if ($(window).scrollTop() > navpos.top) {
$('#mainnav').addClass('navbar-fixed-top');
}
else {
$('#mainnav').removeClass('navbar-fixed-top');
}
});
});
Here is the jsfiddle to play around : -http://jsfiddle.net/shubhampatwa/46ovg69z/
EDIT: if you want to apply this code only for mobile devices the you can use:
var newWindowWidth = $(window).width();
if (newWindowWidth < 481) {
//Place code inside it...
}
A friendly helper method using apache commons.io
Reader reader = clob.getCharacterStream();
StringWriter writer = new StringWriter();
IOUtils.copy(reader, writer);
String clobContent = writer.toString();
Here is a simple way to do it using plain JavaScript. This is the vanilla equivalent of the jQuery script posted by pimvdb. You can test it here.
<script type='text/javascript'>
window.onload = function(){
document.getElementById('id_here').selectedIndex = -1;
}
</script>
.
<select id="id_here">
<option>aaaa</option>
<option>bbbb</option>
</select>
Make sure the "id_here" matches in the form and in the JavaScript.
for iphones safari up to iOS 10 "viewport" is not a solution, i don't like this way, but i have used this javascript code and it helped me
document.addEventListener('touchmove', function(event) {
event = event.originalEvent || event;
if(event.scale > 1) {
event.preventDefault();
}
}, false);
I had to use Take(n) method, then transform to list, Worked like a charm:
var listTest = (from x in table1
join y in table2
on x.field1 equals y.field1
orderby x.id descending
select new tempList()
{
field1 = y.field1,
active = x.active
}).Take(10).ToList();
There is no way to do it in one line with assignment as value.
var a = b = 0;
makes b global. A correct way (without leaking variables) is the slightly longer:
var a = 0, b = a;
which is useful in the case:
var a = <someLargeExpressionHere>, b = a, c = a, d = a;
I changed my DNS network and it fixed the problem
You don't need awk for this...
echo aaa0.bbb.ccc | cut -d. -f1
cut -d. -f1 <<< aaa0.bbb.ccc
echo aaa0.bbb.ccc | { IFS=. read a _ ; echo $a ; }
{ IFS=. read a _ ; echo $a ; } <<< aaa0.bbb.ccc
x=aaa0.bbb.ccc; echo ${x/.*/}
Heavier options:
sed:
echo aaa0.bbb.ccc | sed 's/\..*//'
sed 's/\..*//' <<< aaa0.bbb.ccc
awk:
echo aaa0.bbb.ccc | awk -F. '{print $1}'
awk -F. '{print $1}' <<< aaa0.bbb.ccc
You can use the struct's pack:
In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'
The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:
In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'
In [13]: struct.pack("B", 1)
Out[13]: '\x01'
This works the same on both python 2 and python 3.
Note: the inverse operation (bytes to int) can be done with unpack.
Please note: this answer is obsolete, the functionality was removed from iOS simulator.
I have just found that you don't need to copy the mobile application bundle to the iPhone Simulator's folder to start it on the simulator, as described in the forum. That way you need to click on the app to get it started, not confortable when you want to do testing and start the app numerous times.
There are undocumented command line parameters for the iOS Simulator, which can be used for such purposes. The one you are looking for is: -SimulateApplication
An example command line starting up YourFavouriteApp:
/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app/Contents/MacOS/iPhone\ Simulator -SimulateApplication path_to_your_app/YourFavouriteApp.app/YourFavouriteApp
This will start up your application without any installation and works with iOS Simulator 4.2 at least. You cannot reach the home menu, though.
There are other unpublished command line parameters, like switching the SDK. Happy hunting for those...
{path: 'users', redirectTo: 'users/', pathMatch: 'full'},
{path: 'users/:userId', component: UserComponent}
This way the component isn't re-rendered when the parameter is added.
Change both Project and Package Properties ProtectionLevel to "DontSaveSensitive"
Usually, you create a Makefile in each subdirectory, and write in the top-level Makefile to call make in the subdirectories.
This page may help: http://www.gnu.org/software/make/
Here is a more literal answer (parent window as opposed to opener) to the original question that can be used within an iframe, assuming the domain name in the iframe matches that of the parent window:
window.parent.$("#serverMsg")
Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')
use your jsonsimpleobject direclty like below
JSONObject unitsObj = parser.parse(new FileReader("file.json");
This function will do as JohnFx suggested and allow for varied lengths on the arrays
Function mergeArrays(ByVal arr1 As Variant, ByVal arr2 As Variant) As Variant
Dim holdarr As Variant
Dim ub1 As Long
Dim ub2 As Long
Dim bi As Long
Dim i As Long
Dim newind As Long
ub1 = UBound(arr1) + 1
ub2 = UBound(arr2) + 1
bi = IIf(ub1 >= ub2, ub1, ub2)
ReDim holdarr(ub1 + ub2 - 1)
For i = 0 To bi
If i < ub1 Then
holdarr(newind) = arr1(i)
newind = newind + 1
End If
If i < ub2 Then
holdarr(newind) = arr2(i)
newind = newind + 1
End If
Next i
mergeArrays = holdarr
End Function
The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".
If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.
Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.
Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.
So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.
A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.
The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.
FYI:
git log tagA...tagB
provides standard log output in a range.
Since you have not mentioned what needs to be copied, I have left that section empty in the code below.
Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.
This will get you started. I have commented the code so that you will not face any problem understanding it.
First paste the below mentioned code in the outlook module.
Then
When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.
UNTESTED
Const xlUp As Long = -4162
Sub ExportToExcel(MyMail As MailItem)
Dim strID As String, olNS As Outlook.Namespace
Dim olMail As Outlook.MailItem
Dim strFileName As String
'~~> Excel Variables
Dim oXLApp As Object, oXLwb As Object, oXLws As Object
Dim lRow As Long
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set olMail = olNS.GetItemFromID(strID)
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
'~~> Show Excel
oXLApp.Visible = True
'~~> Open the relevant file
Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")
'~~> Set the relevant output sheet. Change as applicable
Set oXLws = oXLwb.Sheets("Sheet1")
lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1
'~~> Write to outlook
With oXLws
'
'~~> Code here to output data from email to Excel File
'~~> For example
'
.Range("A" & lRow).Value = olMail.Subject
.Range("B" & lRow).Value = olMail.SenderName
'
End With
'~~> Close and Clean up Excel
oXLwb.Close (True)
oXLApp.Quit
Set oXLws = Nothing
Set oXLwb = Nothing
Set oXLApp = Nothing
Set olMail = Nothing
Set olNS = Nothing
End Sub
FOLLOWUP
To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example
Dim MyAr() As String
MyAr = Split(olMail.body, vbCrLf)
For i = LBound(MyAr) To UBound(MyAr)
'~~> This will give you the contents of your email
'~~> on separate lines
Debug.Print MyAr(i)
Next i
While many options above function well, I found coercion of non-target variables to chr
problematic. Using ifelse
and grepl
within lapply
resolves this off-target effect (in limited testing). Using slarky's regular expression in grepl
:
set.seed(42)
x1 <- sample(c("a","b"," ", "a a", NA), 10, TRUE)
x2 <- sample(c(rnorm(length(x1),0, 1), NA), length(x1), TRUE)
df <- data.frame(x1, x2, stringsAsFactors = FALSE)
The problem of coercion to character class:
df2 <- lapply(df, function(x) gsub("^$|^ $", NA, x))
lapply(df2, class)
$x1
[1] "character"
$x2 [1] "character"
Resolution with use of ifelse:
df3 <- lapply(df, function(x) ifelse(grepl("^$|^ $", x)==TRUE, NA, x))
lapply(df3, class)
$x1
[1] "character"
$x2 [1] "numeric"
According with the HTTP/1.1 standard, the shared IP hosted site can be accessed by a GET request with the IP as URL and a header of the host.
Here there are two examples(wget and curl):
$ wget --header 'Host:somerandomservice.com' http://67.225.235.59
$ curl --header 'Host:somerandomservice.com' http://67.225.235.59
Resources:
https://en.wikipedia.org/wiki/Shared_web_hosting_service
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23
In short, it lets you assign values to a variable in an outer (but non-global) scope. See PEP 3104 for all the gory details.
Maybe you want to try this: https://bootstrap-datepicker.readthedocs.org/en/latest/index.html
It's a flexible datepicker widget in the Bootstrap style.
A common mistake during development of an android app running on a Virtual Device on your dev machine is to forget that the virtual device is not the same host as your dev machine. So if your server is running on your dev machine you cannot use a "http://localhost/..." url as that will look for the server endpoint on the virtual device not your dev machine.
Instead of naming my invoking class, I started using the following:
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.
There is no i
in XPath.
Either you use literal numbers: //img[@title='Modify'][1]
Or you build the expression string dynamically: '//img[@title='Modify']['+i+']'
(but keep in mind that dynamic XPath expressions do not work from within XSLT).
Or does XPath support specified selection of nodes which are not under same parent node?
Yes: (//img[@title='Modify'])[13]
This //img[@title='Modify'][i]
means "any <img>
with a title of 'Modify' and a child element named <i>
."
You can also use sequence unpacking with zip
:
L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
_, res = zip(*L)
print(res)
# (2, 3, 5, 4, 7, 7, 8)
This also creates a tuple _
from the discarded first elements. Extracting only the second is possible, but more verbose:
from itertools import islice
res = next(islice(zip(*L), 1, None))
I am doing about the same thing, and here's what I did.
I used separate tables for name, address, email, and numbers, each with a NameID column that is a foreign key on everything except the Name table, on which it is the primary clustered key. I used MainName and FirstName instead of LastName and FirstName to allow for business entries as well as personal entries, but you may not have a need for that.
The NameID column gets to be a smallint in all the tables because I'm fairly certain I won't make more than 32000 entries. Almost everything else is varchar(n) ranging from 20 to 200, depending on what you wanna store (Birthdays, comments, emails, really long names). That is really dependent on what kind of stuff you're storing.
The Numbers table is where I deviate from that. I set it up to have five columns labeled NameID, Phone#, CountryCode, Extension, and PhoneType. I already discussed NameID. Phone# is varchar(12) with a check constraint looking something like this: CHECK (Phone# like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'). This ensures that only what I want makes it into the database and the data stays very consistent. The extension and country codes I called nullable smallints, but those could be varchar if you wanted to. PhoneType is varchar(20) and is not nullable.
Hope this helps!
Datatype: array_name:datatype[]=[];
Example string: users:string[]=[];
For array of objects:
Objecttype: object_name:objecttype[]=[{}];
Example user: Users:user[]=[{}];
And if in some cases it's coming undefined in binding, make sure to initialize it on Oninit()
.
Use pax.
Pax is a deprecated package but does the job perfectly and in a simple fashion.
pax -w > mydir.tar mydir
According to this page.
NOTE: The accepted answer works for associative arrays, but it will not work as expected with indexed arrays (explained below). If you want to compare either of them, then use this solution. Also, this function may not works with multidimensional arrays (due to the nature of array_diff function).
Testing two indexed arrays, which elements are in different order, using $a == $b
or $a === $b
fails, for example:
<?php
(array("x","y") == array("y","x")) === false;
?>
That is because the above means:
array(0 => "x", 1 => "y")
vs. array(0 => "y", 1 => "x")
.
To solve that issue, use:
<?php
function array_equal($a, $b) {
return (
is_array($a)
&& is_array($b)
&& count($a) == count($b)
&& array_diff($a, $b) === array_diff($b, $a)
);
}
?>
Comparing array sizes was added (suggested by super_ton) as it may improve speed.
You can easily subtract with calendar with SimpleDateFormat
public static String subtractDate(String time,int subtractDay) throws ParseException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
cal.setTime(sdf.parse(time));
cal.add(Calendar.DATE,-subtractDay);
String wantedDate = sdf.format(cal.getTime());
Log.d("tag",wantedDate);
return wantedDate;
}
bind
is deprecated. Use on
:
$("#textarea").on('change keyup paste', function() {
// your code here
});
Note: The code above will fire multiple times, once for each matching trigger-type. To handle that, do something like this:
var oldVal = "";
$("#textarea").on("change keyup paste", function() {
var currentVal = $(this).val();
if(currentVal == oldVal) {
return; //check to prevent multiple simultaneous triggers
}
oldVal = currentVal;
//action to be performed on textarea changed
alert("changed!");
});
you can also use ranges by using:
b = df[(df['a'] > 1) & (df['a'] < 5)]
string str = Console.ReadLine(); //Reads a character from console
double a = double.Parse(str); //Converts str into the type double
double b = a * Math.PI; // Multiplies by PI
Console.WriteLine("{0}", b); // Writes the number to console
Console.Read()
reads a string from console A SINGLE CHARACTER AT A TIME (but waits for an enter before going on. You normally use it in a while
cycle). So if you write 25
+ Enter, it will return the unicode value of 2
that is 50
. If you redo a second Console.Read()
it will return immediately with 53
(the unicode value of 5
). A third and a fourth Console.Read()
will return the end of line/carriage characters. A fifth will wait for new input.
Console.ReadLine()
reads a string
(so then you need to change the string to a double
)
Try this:
$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
In addition to the fine answers above, I think it should be said that Tomcat has it's own HTTP server built into it, and is fully functional at serving static content too. Depending on your java virtual machine configuration it can actually outperform going through traditional connectors in apache such as mod_proxy and mod_jk.
That said a fully optimized Tomcat server should serve static files fast and if you have Java servlets, JSPs and ColdFusion files in addition to static content you may find tomcat does an excellent job by itself.