to change the object owner try the following
EXEC sp_changedbowner 'sa'
that however is not your problem, to see diagrams the Da Vinci Tools objects have to be created (you will see tables and procs that start with dt_) after that
You're misinformed about fcntl()
not always being reliable. It's untrue.
To mark a socket as non-blocking the code is as simple as:
// where socketfd is the socket you want to make non-blocking
int status = fcntl(socketfd, F_SETFL, fcntl(socketfd, F_GETFL, 0) | O_NONBLOCK);
if (status == -1){
perror("calling fcntl");
// handle the error. By the way, I've never seen fcntl fail in this way
}
Under Linux, on kernels > 2.6.27 you can also create sockets non-blocking from the outset using socket()
and accept4()
.
e.g.
// client side
int socketfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
// server side - see man page for accept4 under linux
int socketfd = accept4( ... , SOCK_NONBLOCK);
It saves a little bit of work, but is less portable so I tend to set it with fcntl()
.
Interestingly no one answers the question, OP isn't using a strongly typed int[]
but an Array
.
You have to cast the Array
to what it actually is, an int[]
, then you can use ToList
:
List<int> intList = ((int[])ints).ToList();
Note that Enumerable.ToList
calls the list constructor that first checks if the argument can be casted to ICollection<T>
(which an array implements), then it will use the more efficient ICollection<T>.CopyTo
method instead of enumerating the sequence.
Here is a version that wraps the homebrew installer in a bash function that can be run from your deployment scripts:
install_homebrew_if_not_present() {
echo "Checking for homebrew installation"
which -s brew
if [[ $? != 0 ]] ; then
echo "Homebrew not found. Installing..."
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
else
echo "Homebrew already installed! Updating..."
brew update
fi
}
And another function which will install a homebrew formula if it is not already installed:
brew_install () {
if brew ls --versions $1 > /dev/null; then
echo "already installed: $1"
else
echo "Installing forumula: $1..."
brew install $1
fi
}
Once you have these functions defined you can use them as follows in your bash script:
install_homebrew_if_not_present
brew_install wget
brew_install openssl
...
Yes,
with open('filename.txt') as fp:
for line in fp:
print line
is the way to go.
It is not more verbose. It is more safe.
With some little changes to hobodave's code, here is a codesnippet you can use to crawl pages. This needs the curl extension to be enabled in your server.
<?php
//set_time_limit (0);
function crawl_page($url, $depth = 5){
$seen = array();
if(($depth == 0) or (in_array($url, $seen))){
return;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result = curl_exec ($ch);
curl_close ($ch);
if( $result ){
$stripped_file = strip_tags($result, "<a>");
preg_match_all("/<a[\s]+[^>]*?href[\s]?=[\s\"\']+"."(.*?)[\"\']+.*?>"."([^<]+|.*?)?<\/a>/", $stripped_file, $matches, PREG_SET_ORDER );
foreach($matches as $match){
$href = $match[1];
if (0 !== strpos($href, 'http')) {
$path = '/' . ltrim($href, '/');
if (extension_loaded('http')) {
$href = http_build_url($href , array('path' => $path));
} else {
$parts = parse_url($href);
$href = $parts['scheme'] . '://';
if (isset($parts['user']) && isset($parts['pass'])) {
$href .= $parts['user'] . ':' . $parts['pass'] . '@';
}
$href .= $parts['host'];
if (isset($parts['port'])) {
$href .= ':' . $parts['port'];
}
$href .= $path;
}
}
crawl_page($href, $depth - 1);
}
}
echo "Crawled {$href}";
}
crawl_page("http://www.sitename.com/",3);
?>
I have explained this tutorial in this crawler script tutorial
Yes, with a lexical cast. Use a stringstream and the << operator, or use Boost, they've already implemented it.
Your own version could look like:
template<typename to, typename from>to lexical_cast(from const &x) {
std::stringstream os;
to ret;
os << x;
os >> ret;
return ret;
}
You can use:
CurrentDb.Execute "ALTER TABLE yourTable ALTER COLUMN myID COUNTER(1,1)"
I hope you have no relationships that use this table, I hope it is empty, and I hope you understand that all you can (mostly) rely on an autonumber to be is unique. You can get gaps, jumps, very large or even negative numbers, depending on the circumstances. If your autonumber means something, you have a major problem waiting to happen.
Oneliner:
do_X() if len(your_list) > your_index else do_something_else()
Full example:
In [10]: def do_X():
...: print(1)
...:
In [11]: def do_something_else():
...: print(2)
...:
In [12]: your_index = 2
In [13]: your_list = [1,2,3]
In [14]: do_X() if len(your_list) > your_index else do_something_else()
1
Just for info. Imho, try ... except IndexError
is better solution.
Since you don't care which id to return I stick with MAX id for each email to simplify SQL query, give it a try
;WITH ue(id)
AS
(
SELECT MAX(id)
FROM table
GROUP BY email
)
SELECT * FROM table t
INNER JOIN ue ON ue.id = t.id
I have recently implemented the receipt printing simply by pressing a button on a web page, without having to enter the printer options. I have done it using EPSON javascript SDK for ePOS. I have test it on EPSON TM-m30 receipt printer.
Here is the sample code.
var printer = null;
var ePosDev = null;
function InitMyPrinter() {
console.log("Init Printer");
var printerPort = 8008;
var printerAddress = "192.168.198.168";
if (isSSL) {
printerPort = 8043;
}
ePosDev = new epson.ePOSDevice();
ePosDev.connect(printerAddress, printerPort, cbConnect);
}
//Printing
function cbConnect(data) {
if (data == 'OK' || data == 'SSL_CONNECT_OK') {
ePosDev.createDevice('local_printer', ePosDev.DEVICE_TYPE_PRINTER,
{'crypto': false, 'buffer': false}, cbCreateDevice_printer);
} else {
console.log(data);
}
}
function cbCreateDevice_printer(devobj, retcode) {
if (retcode == 'OK') {
printer = devobj;
printer.timeout = 60000;
printer.onreceive = function (res) { //alert(res.success);
console.log("Printer Object Created");
};
printer.oncoveropen = function () { //alert('coveropen');
console.log("Printer Cover Open");
};
} else {
console.log(retcode);
isRegPrintConnected = false;
}
}
function print(salePrintObj) {
debugger;
if (isRegPrintConnected == false
|| printer == null) {
return;
}
console.log("Printing Started");
printer.addLayout(printer.LAYOUT_RECEIPT, 800, 0, 0, 0, 35, 0);
printer.addTextAlign(printer.ALIGN_CENTER);
printer.addTextSmooth(true);
printer.addText('\n');
printer.addText('\n');
printer.addTextDouble(true, true);
printer.addText(CompanyName + '\n');
printer.addTextDouble(false, false);
printer.addText(CompanyHeader + '\n');
printer.addText('\n');
printer.addTextAlign(printer.ALIGN_LEFT);
printer.addText('DATE: ' + currentDate + '\t\t');
printer.addTextAlign(printer.ALIGN_RIGHT);
printer.addText('TIME: ' + currentTime + '\n');
printer.addTextAlign(printer.ALIGN_LEFT);
printer.addTextAlign(printer.ALIGN_RIGHT);
printer.addText('REGISTER: ' + RegisterName + '\n');
printer.addTextAlign(printer.ALIGN_LEFT);
printer.addText('SALE # ' + SaleNumber + '\n');
printer.addTextAlign(printer.ALIGN_CENTER);
printer.addTextStyle(false, false, true, printer.COLOR_1);
printer.addTextStyle(false, false, false, printer.COLOR_1);
printer.addTextDouble(false, true);
printer.addText('* SALE RECEIPT *\n');
printer.addTextDouble(false, false);
....
....
....
}
I use this as part of my utils. With this we can not only set shadow but also can get a rounded corner for any UIView
. Also you could set what color shadow you prefer. Normally black is preferred but sometimes, when the background is non-white you might want something else. Here's what I use -
in utils.m
+ (void)roundedLayer:(CALayer *)viewLayer
radius:(float)r
shadow:(BOOL)s
{
[viewLayer setMasksToBounds:YES];
[viewLayer setCornerRadius:r];
[viewLayer setBorderColor:[RGB(180, 180, 180) CGColor]];
[viewLayer setBorderWidth:1.0f];
if(s)
{
[viewLayer setShadowColor:[RGB(0, 0, 0) CGColor]];
[viewLayer setShadowOffset:CGSizeMake(0, 0)];
[viewLayer setShadowOpacity:1];
[viewLayer setShadowRadius:2.0];
}
return;
}
To use this we need to call this - [utils roundedLayer:yourview.layer radius:5.0f shadow:YES];
Matt's answer is fine, but just to avoid this to propagate to other elements inside the navbar (like when you also have a dropdown), use
.navbar-nav > li > a {
line-height: 50px;
}
PIE
makes Internet Explorer 6-9
capable of rendering several of the most useful CSS3
decoration features
................................................................................
JButton#isEnabled
changes the user interactivity of a component, that is, whether a user is able to interact with it (press it) or not.
When a JButton
is pressed, it fires a actionPerformed
event.
You are receiving Add button is pressed
when you press the confirm button because the add button is enabled. As stated, it has nothing to do with the pressed start of the button.
Based on you code, if you tried to check the "pressed" start of the add button within the confirm button's ActionListener
it would always be false, as the button will only be in the pressed state while the add button's ActionListener
s are being called.
Based on all this information, I would suggest you might want to consider using a JCheckBox
which you can then use JCheckBox#isSelected
to determine if it has being checked or not.
Take a closer look at How to Use Buttons for more details
What you want is called a zone transfer. You can request a zone transfer using dig -t axfr
.
A zone is a domain and all of the domains below it that are not delegated to another server.
Note that zone transfers are not always supported. They're not used in normal lookup, only in replicating DNS data between servers; but there are other protocols that can be used for that (such as rsync over ssh), there may be a security risk from exposing names, and zone transfer responses cost more to generate and send than usual DNS lookups.
What do you mean by merging? JSON objects are key-value data structure. What would be a key and a value in this case? I think you need to create new directory and populate it with old data:
d = {}
d["new_key"] = jsonStringA[<key_that_you_did_not_mention_here>] + \
jsonStringB["timestamp_in_ms"]
Merging method is obviously up to you.
Besides zfill
, you can use general string formatting:
print(f'{number:05d}') # (since Python 3.6), or
print('{:05d}'.format(number)) # or
print('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection)
print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
print(format(number, '05d'))
Documentation for string formatting and f-strings.
in ts, [].push(bufferPart) is not compatible;
so:
getBufferFromStream(stream: Part | null): Promise<Buffer> {
if (!stream) {
throw 'FILE_STREAM_EMPTY';
}
return new Promise(
(r, j) => {
let buffer = Buffer.from([]);
stream.on('data', buf => {
buffer = Buffer.concat([buffer, buf]);
});
stream.on('end', () => r(buffer));
stream.on('error', j);
}
);
}
It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:
unspecified
emailAddress
– e.g. [email protected]
X509SubjectName
– e.g. CN=john,O=Company Ltd.,C=US
WindowsDomainQualifiedName
– e.g. CompanyDomain\John
kerberos
– e.g. john@realm
entity
– this one in used to identify entities that provide SAML-based services and looks like a URIpersistent
– this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.transient
– opaque identifier which should be treated as temporary.if(success == true)
{
//For wait 5 seconds
setTimeout(function()
{
location.reload(); //Refresh page
}, 5000);
}
No offence, but none of the other answers (so far) has it quite right.
break
is used to immediately terminate a for
loop, a while
loop or a switch
statement. You can not break
from an if
block.
return
is used the terminate a method (and possibly return a value).
A return
within any loop or block will of course also immediately terminate that loop/block.
Are you sure a core dump is what you want here? That will contain the raw guts of the running JVM, rather than java-level information. Perhaps a JVM heap dump is more what you need.
minimumFontSize
has been deprecated with iOS 6. You can use minimumScaleFactor
.
yourLabel.adjustsFontSizeToFitWidth=YES;
yourLabel.minimumScaleFactor=0.5;
This will take care of your font size according width of label and text.
Well, your solution almost works. There are a few things to take into account to keep it simple:
Cancel the default navigation only for specific URLs you know a download will occur, or the user won't be able to navigate anywhere. This means you musn't change your website download URLs.
DownloadFileAsync
doesn't know the name reported by the server in the Content-Disposition
header so you have to specify one, or compute one from the original URL if that's possible. You cannot just specify the folder and expect the file name to be retrieved automatically.
You have to handle download server errors from the DownloadCompleted
callback because the web browser control won't do it for you anymore.
Sample piece of code, that will download into the directory specified in textBox1
, but with a random file name, and without any additional error handling:
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
/* change this to match your URL. For example, if the URL always is something like "getfile.php?file=xxx", try e.Url.ToString().Contains("getfile.php?") */
if (e.Url.ToString().EndsWith(".zip")) {
e.Cancel = true;
string filePath = Path.Combine(textBox1.Text, Path.GetRandomFileName());
var client = new WebClient();
client.DownloadFileCompleted += client_DownloadFileCompleted;
client.DownloadFileAsync(e.Url, filePath);
}
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
MessageBox.Show("File downloaded");
}
This solution should work but can be broken very easily. Try to consider some web service listing the available files for download and make a custom UI for it. It'll be simpler and you will control the whole process.
If you are looking for a 1 line solution, this is it:
s.Substring(s.IndexOf("eT") + "eT".Length).Split("97".ToCharArray()).First()
The whole 1 line solution, with System.Linq
:
using System;
using System.Linq;
class OneLiner
{
static void Main()
{
string s = "TextHereTisImortant973End"; //Between "eT" and "97"
Console.WriteLine(s.Substring(s.IndexOf("eT") + "eT".Length)
.Split("97".ToCharArray()).First());
}
}
Open the installed visual studio software and click the Help menu select the About Microsoft Visual studio--> Get the visual studio Version
In your batch file do this
set source=C:\Users\Habib\test
set destination=C:\Users\Habib\testdest\
xcopy %source% %destination% /y
If you want to copy the sub directories including empty directories then do:
xcopy %source% %destination% /E /y
If you only want to copy sub directories and not empty directories then use /s
like:
xcopy %source% %destination% /s /y
Here is a monkeyrunner script that sends touch and drags to an application. I have been using this to test that my application can handle rapid repetitive swipe gestures.
# This is a monkeyrunner jython script that opens a connection to an Android
# device and continually sends a stream of swipe and touch gestures.
#
# See http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html
#
# usage: monkeyrunner swipe_monkey.py
#
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
# Connects to the current device
device = MonkeyRunner.waitForConnection()
# A swipe left from (x1, y) to (x2, y) in 2 steps
y = 400
x1 = 100
x2 = 300
start = (x1, y)
end = (x2, y)
duration = 0.2
steps = 2
pause = 0.2
for i in range(1, 250):
# Every so often inject a touch to spice things up!
if i % 9 == 0:
device.touch(x2, y, 'DOWN_AND_UP')
MonkeyRunner.sleep(pause)
# Swipe right
device.drag(start, end, duration, steps)
MonkeyRunner.sleep(pause)
# Swipe left
device.drag(end, start, duration, steps)
MonkeyRunner.sleep(pause)
I'd recommend you to create a shortcut to eclipse.exe with the -data
command line option. This way you can create a separate shortcut to each workspace you use, and avoid unnecessary dialogs and mouse clicks.
Windows: Just create an Eclipse shortcut on your desktop, then right-click to open Properties
and under Shortcut
set something like this as Target
: C:\eclipse\eclipse.exe -data C:\Path\to\your\workspace1
. This will launch Eclipse and automatically open workspace1
.
Repeat the steps for all the workspaces you use often.
try http://code.google.com/p/swinghtmltemplate/
this will allow you to create gui with html-like syntax
No need to initialize an empty DataFrame (you weren't even doing that, you'd need pd.DataFrame()
with the parens).
Instead, to create a DataFrame where each series is a column,
series
, and df = pd.concat(series, axis=1)
Something like:
series = [pd.Series(mat[name][:, 1]) for name in Variables]
df = pd.concat(series, axis=1)
So, I hear this works:
Data$X1<-as.character(Data$X1)
Data$GEOID<-as.character(Data$BLKIDFP00)
Data<-within(Data,X1<-ifelse(is.na(Data$X1),GEOID,Data$X2))
But I admit I have only intermittent luck with it.
I am using Visual Studio 2013 & SQL Server 2014. I got the below error Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0 not found by visual studio. I have tried all the things like installing
ENU\x64\SharedManagementObjects.msi for X64 OS or
ENU\x86\SharedManagementObjects.msi for X86 OS
ENU\x64\SQLSysClrTypes.msi
Reinstalling Sql Server 2014
What actually solved my problem is to repair the visual studio 2013(or any other version you are using) now the problem is removed . What i think it is problem of Visual Studio not Sql Server as i was able to access and use the Sql Server tool.
All scripts should be imported in order:
Bootstrap-datetimepicker requires moment.js
to be loaded before datepicker.js
.
Working snippet:
$(function() {_x000D_
$('#datetimepicker1').datetimepicker();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class='col-sm-6'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker1'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Unfortunately I do not believe it's possible in fully-conforming HTML5 with just HTML and CSS properties. Fortunately however, most browsers do still support the scrolling
property (which was removed from the HTML5 specification).
overflow
isn't a solution for HTML5 as the only modern browser which wrongly supports this is Firefox.
A current solution would be to combine the two:
<iframe src="" scrolling="no"></iframe>
iframe {
overflow: hidden;
}
But this could be rendered obsolete as browsers update. You may want to check this for a JavaScript solution: http://www.christersvensson.com/html-tool/iframe.htm
Edit: I've checked and scrolling="no"
will work in IE10, Chrome 25 and Opera 12.12.
Your problem is that the top
and left
properties require a unit of measure, not just a bare number:
div.style.top = "200px";
div.style.left = "200px";
In my case, I also had to add the line "FcgidMaxRequestLen 1073741824" (without the quotes) in /etc/apache2/mods-available/fcgid.conf. It's documented here http://forum.ispsystem.com/en/showthread.php?p=6611 . Since mod_fcgid 2.3.6, they changed the default for FcgidMaxRequestLen from 1GB to 128K (see https://svn.apache.org/repos/asf/httpd/mod_fcgid/trunk/CHANGES-FCGID )
If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:
//make sure to include the random number generators and such
#include <random>
//the random device that will seed the generator
std::random_device seeder;
//then make a mersenne twister engine
std::mt19937 engine(seeder());
//then the easy part... the distribution
std::uniform_int_distribution<int> dist(min, max);
//then just generate the integer like this:
int compGuess = dist(engine);
That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...
Hope this helps - Luke
You should use the facade rather than Illuminate\Http\Request
. Import it at the top:
use Request;
And make sure it doesn't conflict with the other class.
Edit: This answer was written a few years ago. I now favour the approach suggested by shuvrow below.
You can get the IP address from hostvars
, dict ansible_default_ipv4
and key address
hostvars[inventory_hostname]['ansible_default_ipv4']['address']
and IPv6 address respectively
hostvars[inventory_hostname]['ansible_default_ipv6']['address']
An example playbook:
---
- hosts: localhost
tasks:
- debug: var=hostvars[inventory_hostname]['ansible_default_ipv4']['address']
- debug: var=hostvars[inventory_hostname]['ansible_default_ipv6']['address']
Make another column that determines if the referenced cell is blank using the function "CountBlank". Then use count on the values created in the new "CountBlank" column.
You just have to put this code into cellForRowAtIndexPath
To disable the cell's selection property: (while tapping the cell)
cell.selectionStyle = UITableViewCellSelectionStyleNone;
To enable being able to select (tap) the cell: (tapping the cell)
// Default style
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
// Gray style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
Note that a cell with selectionStyle = UITableViewCellSelectionStyleNone;
will still cause the UI to call didSelectRowAtIndexPath
when touched by the user. To avoid this, do as suggested below and set.
cell.userInteractionEnabled = NO;
instead. Also note you may want to set cell.textLabel.enabled = NO;
to gray out the item.
In a nutshell, the more a programming style emphasizes What (to do) abstracting away the details of How (to do it) the more that style is considered to be declarative. The opposite is true for imperative. Functional programming is associated with the declarative style.
You need to use WITH ROLLBACK IMMEDIATE
to boot other conections out with no regards to what or who is is already using it.
Or use WITH NO_WAIT
to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details
There are two options to handle/avoid this situation.
Open the console --> right click --> terminate all.
_.unescape
does what you're looking for
Set
Dictionary<int, string> states = new Dictionary<int, string>()
as a property outside the function and inside the function insert the entries, it should work.
What's the default superuser username/password for postgres after a new install?:
CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!
This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.
What you should do is follow Chris James's answer:
sudo -u postgres psql postgres # \password postgres Enter new password:
To explain it a little bit...
Same think can be done using lambda function. Here I am reading the data from a xlsx file.
import pandas as pd
df = pd.read_excel("data.xlsx", sheet_name = 4)
print df
Output:
cluster Unnamed: 1 date budget actual
0 a 2014-01-01 00:00:00 11000 10000
1 a 2014-02-01 00:00:00 1200 1000
2 a 2014-03-01 00:00:00 200 100
3 b 2014-04-01 00:00:00 200 300
4 b 2014-05-01 00:00:00 400 450
5 c 2014-06-01 00:00:00 700 1000
6 c 2014-07-01 00:00:00 1200 1000
7 c 2014-08-01 00:00:00 200 100
8 c 2014-09-01 00:00:00 200 300
Sum two columns into 3rd new one.
df['variance'] = df.apply(lambda x: x['budget'] + x['actual'], axis=1)
print df
Output:
cluster Unnamed: 1 date budget actual variance
0 a 2014-01-01 00:00:00 11000 10000 21000
1 a 2014-02-01 00:00:00 1200 1000 2200
2 a 2014-03-01 00:00:00 200 100 300
3 b 2014-04-01 00:00:00 200 300 500
4 b 2014-05-01 00:00:00 400 450 850
5 c 2014-06-01 00:00:00 700 1000 1700
6 c 2014-07-01 00:00:00 1200 1000 2200
7 c 2014-08-01 00:00:00 200 100 300
8 c 2014-09-01 00:00:00 200 300 500
I think the problems comes from the following: The internet connection with u was unavailable so Android Studio asked you to enable the "offline work" and you just enabled it
To fix this:
why might unchecking the offline work solves the problem, because in the Gradle sometimes some dependencies need to update (the ones containing '+'), so internet connection is needed.
I guess you could use curl
and wget
, but since Oracle requires you to check of some checkmarks this will be painfull to emulate with the tools mentioned. You would have to download the page with the license agreement and from looking at it figure out what request is needed to get to the actual download.
Of course you could simply start a browser, but this might not qualify as 'from the command line'. So you might want to look into lynx
, a text based browser.
Create a file named .gitignore on the root of your repository. In this file you put the relative path to each file you wish to ignore in a single line. You can use the *
wildcard.
You should use any()
In [98]: a['Names'].str.contains('Mel').any()
Out[98]: True
In [99]: if a['Names'].str.contains('Mel').any():
....: print "Mel is there"
....:
Mel is there
a['Names'].str.contains('Mel')
gives you a series of bool values
In [100]: a['Names'].str.contains('Mel')
Out[100]:
0 False
1 False
2 False
3 False
4 True
Name: Names, dtype: bool
while this might set the properties, it doesnt actually reflect in IB. So if you're essentially writing code in IB, you might as well then do it in your source code
This might be a problem of the parameter that you are passing to request body. I was also facing the same issue. But then I came across CMash's answer here https://stackoverflow.com/a/34181221/5867445 and I changed my parameter and it works.
Issue in a parameter that I was passing is about String Encoding
.
Hope this helps.
Fork Vs. Clone - two words that both mean copy
Please see this diagram. (Originally from http://www.dataschool.io/content/images/2014/Mar/github1.png).
.-------------------------. 1. Fork .-------------------------.
| Your GitHub repo | <-------------- | Joe's GitHub repo |
| github.com/you/coolgame | | github.com/joe/coolgame |
| ----------------------- | 7. Pull Request | ----------------------- |
| master -> c224ff7 | --------------> | master -> c224ff7 (c) |
| anidea -> 884faa1 (a) | | anidea -> 884faa1 (b) |
'-------------------------' '-------------------------'
| ^
| 2. Clone |
| |
| |
| |
| |
| | 6. Push (anidea => origin/anidea)
v |
.-------------------------.
| Your computer | 3. Create branch 'anidea'
| $HOME/coolgame |
| ----------------------- | 4. Update a file
| master -> c224ff7 |
| anidea -> 884faa1 | 5. Commit (to 'anidea')
'-------------------------'
(a) - after you have pushed it
(b) - after Joe has accepted it
(c) - eventually Joe might merge 'anidea' (make 'master -> 884faa1')
Fork
Clone
There is no built-in method for Node to change the CWD of the underlying shell running the Node process.
You can change the current working directory of the Node process through the command process.chdir()
.
var process = require('process');
process.chdir('../');
When the Node process exists, you will find yourself back in the CWD you started the process in.
@agstudy's answer didn't work for me with the latest version of ggplot2
, but this did, using maggritr
pipes:
ggplot(data=dat)+
geom_line(aes(Value1, Value2, group=ID, colour=ID),
data = . %>% filter(ID %in% c("P1" , "P3")))
It works because if geom_line
sees that data
is a function, it will call that function with the inherited version of data
and use the output of that function as data
.
There is no way.
This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.
If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern
attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.
For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}">
could be adequate. It is of course implementation-dependent how it will be handled.
for SWIFT
func topMostController() -> UIViewController {
var topController: UIViewController = UIApplication.sharedApplication().keyWindow!.rootViewController!
while (topController.presentedViewController != nil) {
topController = topController.presentedViewController!
}
return topController
}
This link helped me a lot for the same problem:
p = ggplot() +
geom_line(data = df_plot, aes(x = idx, y = col1), color = "blue") +
geom_line(data = df_plot, aes(x = idx, y = col2), color = "red")
print(p)
You can use std::filesystem::recursive_directory_iterator
. But beware, this includes symbolic (soft) links. If you want to avoid them you can use is_symlink
. Example usage:
size_t directory_size(const std::filesystem::path& directory)
{
size_t size{ 0 };
for (const auto& entry : std::filesystem::recursive_directory_iterator(directory))
{
if (entry.is_regular_file() && !entry.is_symlink())
{
size += entry.file_size();
}
}
return size;
}
If the commit you want to revert is a merged commit (has been merged already), then you should either -m 1
or -m 2
option as shown below. This will let git know which parent commit of the merged commit to use. More details can be found HERE.
git revert <commit> -m 1
git revert <commit> -m 2
The solution at my end was to explicitly add a JoinColumn annotation like this:
@JoinColumn(name="mapping_type_id")
The column name is usually the table name + "_id" if there is an id field. Additionally, keep in mind which field it should be based on the relationship, OneToMany or ManyToOne.
Hope this helps.
From what I can tell, per the documentation here: http://jqueryui.com/demos/tabs/#event-select, it seems as though you're not quite initializing it right. The demos state that you need a main wrapped <div>
element, with a <ul>
or possibly <ol>
element representing the tabs, and then an element for each tab page (presumable a <div>
or <p>
, possibly a <section>
if we're using HTML5). Then you call $().tabs() on the main <div>
, not the <ul>
element.
After that, you can bind to the tabsselect event no problem. Check out this fiddle for basic, basic example:
Use .prop()
:
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
If you're working with just one element, you can always just access the underlying HTMLInputElement
and modify its .checked
property:
$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;
The benefit to using the .prop()
and .attr()
methods instead of this is that they will operate on all matched elements.
The .prop()
method is not available, so you need to use .attr()
.
$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);
Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using $('.myCheckbox').removeAttr('checked');
since the latter will, if the box was initially checked, change the behaviour of a call to .reset()
on any form that contains it – a subtle but probably unwelcome behaviour change.
For more context, some incomplete discussion of the changes to the handling of the checked
attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop()
documentation.
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
Use "\\"
to escape the \ character.
These all are ways:
String imageUri = "drawable://" + R.drawable.image;
Other ways I tested
Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");
String path = path.toString();
String path = otherPath .toString();
I know this is old (and I am new to java), but I ran into the same problem. And the answers were not as clear to me as a newbie... so I thought I would add what I learned.
I used a third-party library to aid in the endeavor: org.codehaus.jackson
All of the downloads for this can be found here.
For base JSON functionality, you need to add the following jars to your project's libraries: jackson-mapper-asl and jackson-core-asl
Choose the version your project needs. (Typically you can go with the latest stable build).
Once they are imported in to your project's libraries, add the following import
lines to your code:
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service
User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "[email protected]";
ObjectMapper mapper = new ObjectMapper();
try {
// convert user object to json string and return it
return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException e) {
// catch various errors
e.printStackTrace();
}
The result should looks like this:
{"firstName":"Sample","lastName":"User","email":"[email protected]"}
The wizard likely created the package as a file. Do a search on your system for files with an extension of .dtsx. This is the actual "SSIS Package" file.
As for loading it in Management Studio, you don't actually view it through there. If you have SQL Server 2005 loaded on your machine, look in the program group. You should find an application with the same icon as Visual Studio called "SQL Server Business Intelligence Development Studio". It's basically a stripped down version of VS 2005 which allows you to create SSIS packages.
Create a blank solution and add your .dtsx file to that to edit/view it.
ok I figured out a crude way of doing it.
I store the "n" value in the for loop when condition is satisfied in a list (lets call it delList) then do the following:
for ii in sorted(delList, reverse=True):
tupleX.pop(ii)
Any other suggestions are welcome too.
Although purely from engineering perspective, indexed views sound like something everybody could use to improve performance but the real life scenario is very different. I have been unsuccessful is using indexed views where I most need them because of too many restrictions on what can be indexed and what cannot.
If you have outer joins in the views, they cannot be used. Also, common table expressions are not allowed... In fact if you have any ordering in subselects or derived tables (such as with partition by clause), you are out of luck too.
That leaves only very simple scenarios to be utilizing indexed views, something in my opinion can be optimized by creating proper indexes on underlying tables anyway.
I will be thrilled to hear some real life scenarios where people have actually used indexed views to their benefit and could not have done without them
I would like to add that Lin's answer is correct.
If you improperly delete the MDF you will have to fix it. To fix the screwed up connections in the project to the MDF. Short answer; recreate and delete it properly.
update-database -force
[Use force if necessary]Done, enjoy your new db
UPDATE 11/12/14 - I use this all the time when I make a breaking db change. I found this is a great way to roll back your migrations to the original db:
Run the normal migration to put it back to current
Update-Database -TargetMigration:0 -force
[This will destroy all tables and all data.] Update-Database -force
[use force if necessary]public class Texttovoice extends ActionBarActivity implements OnInitListener {
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_texttovoice);
tts = new TextToSpeech(this, this);
// Refer 'Speak' button
btnSpeak = (Button) findViewById(R.id.btnSpeak);
// Refer 'Text' control
txtText = (EditText) findViewById(R.id.txtText);
// Handle onClick event for button 'Speak'
btnSpeak.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Method yet to be defined
speakOut();
}
});
}
private void speakOut() {
// Get the text typed
String text = txtText.getText().toString();
// If no text is typed, tts will read out 'You haven't typed text'
// else it reads out the text you typed
if (text.length() == 0) {
tts.speak("You haven't typed text", TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.texttovoice, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onInit(int status) {
// TODO Auto-generated method stub
// TTS is successfully initialized
if (status == TextToSpeech.SUCCESS) {
// Setting speech language
int result = tts.setLanguage(Locale.US);
// If your device doesn't support language you set above
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
// Cook simple toast message with message
Toast.makeText(getApplicationContext(), "Language not supported",
Toast.LENGTH_LONG).show();
Log.e("TTS", "Language is not supported");
}
// Enable the button - It was disabled in main.xml (Go back and
// Check it)
else {
btnSpeak.setEnabled(true);
}
// TTS is not initialized properly
} else {
Toast.makeText(this, "TTS Initilization Failed", Toast.LENGTH_LONG)
.show();
Log.e("TTS", "Initilization Failed");
}
}
//-------------------------------XML---------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:orientation="vertical"
tools:ignore="HardcodedText" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="15dip"
android:text="listen your text"
android:textColor="#0587d9"
android:textSize="26dip"
android:textStyle="bold" />
<EditText
android:id="@+id/txtText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:layout_marginTop="20dip"
android:hint="Enter text to speak" />
<Button
android:id="@+id/btnSpeak"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:enabled="false"
android:text="Speak"
android:onClick="speakout"/>
Although the ffile:////.exe used to work (for example - some versions of early html 4) it appears html 5 disallows this. Tested using the following:
<a href="ffile:///<path name>/<filename>.exe" TestLink /a>
<a href="ffile://<path name>/<filename>.exe" TestLink /a>
<a href="ffile:/<path name>/<filename>.exe" TestLink /a>
<a href="ffile:<path name>/<filename>.exe" TestLink /a>
<a href="ffile://///<path name>/<filename>.exe" TestLink /a>
<a href="file://<path name>/<filename>.exe" TestLink /a>
<a href="file:/<path name>/<filename>.exe" TestLink /a>
<a href="file:<path name>/<filename>.exe" TestLink /a>
<a href="ffile://///<path name>/<filename>.exe" TestLink /a>
as well as ... 1/ substituted the "ffile" with just "file" 2/ all the above variations with the http:// prefixed before the ffile or file.
The best I could see was there is a possibility that if one wanted to open (edit) or save the file, it could be accomplished. However, the exec file would not execute otherwise.
As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.
new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1
If you want to get the full path of the directory of the current rb file:
File.expand_path('../', __FILE__)
I also had the same problem. So I tried by installing a lesser version say jdk1.5 and running the netbeans installation from command prompt as: Linux: netbeans-5_5-linux.bin -is:javahome /usr/jdk/jdk1.5.0_06 Windows: netbeans-5_5-windows.exe -is:javahome "C:\Program Files\Java\jdk1.5.0_06"
Hope it helps
app.run(function ($rootScope, $location) {
$rootScope.$on('$routeChangeSuccess', function(){
ga('send', 'pageview', $location.path());
});
});
so simple :
outline-color : blue !important;
the whole CSS for my react-boostrap button is:
.custom-btn { font-size:1.9em; background: #2f5bff; border: 2px solid #78e4ff; border-radius: 3px; padding: 50px 70px; outline-color : blue !important; text-transform: uppercase; user-select: auto; -moz-box-shadow: inset 0 0 4px rgba(0,0,0,0.2); -webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2); -webkit-border-radius: 3px; -moz-border-radius: 3px; }
Another alternative is the old school NET USER commands:
NET USER username "password" /ADD
OK - you can't set all the options but it's a lot less convoluted for simple user creation & easy to script up in Powershell.
NET LOCALGROUP "group" "user" /add
to set group membership.
This is the method I used, with a server-side include, e.g. <!--#include file="emailObfuscator.include" -->
where emailObfuscator.include
contains the following:
<!-- // http://lists.evolt.org/archive/Week-of-Mon-20040202/154813.html -->
<script type="text/javascript">
function gen_mail_to_link(lhs,rhs,subject) {
document.write("<a href=\"mailto");
document.write(":" + lhs + "@");
document.write(rhs + "?subject=" + subject + "\">" + lhs + "@" + rhs + "<\/a>");
}
</script>
To include an address, I use JavaScript:
<script type="text/javascript">
gen_mail_to_link('john.doe','example.com','Feedback about your site...');
</script>
<noscript>
<em>Email address protected by JavaScript. Activate JavaScript to see the email.</em>
</noscript>
Because I have been getting email via Gmail since 2005, spam is pretty much a non-issue. So, I can't speak of how effective this method is. You might want to read this study (although it's old) that produced this graph:
It involves eyeballing it (well I suppose you could get out a calculator and calculate) but just insert said control on the form and then remove any anchoring (anchor = None).
Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).
The command line option
-verbose:gc
causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:[GC 325407K->83000K(776768K), 0.2300771 secs] [GC 325816K->83372K(776768K), 0.2454258 secs] [Full GC 267628K->83769K(776768K), 1.8479984 secs]
Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g.,
325407K->83000K
from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.The next number in parentheses (e.g.,
(776768K)
again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.The last item on the line (e.g.,
0.2300771 secs
) indicates the time taken to perform the collection; in this case approximately a quarter of a second.The format for the major collection in the third line is similar.
The format of the output produced by
-verbose:gc
is subject to change in future releases.
I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?
Just do:
$object = new stdClass();
$object->name = "My name";
$myArray[] = $object;
You need to create the object first (the new
line) and then push it onto the end of the array (the []
line).
You can also do this:
$myArray[] = (object) ['name' => 'My name'];
However I would argue that's not as readable, even if it is more succinct.
Delete first, second and fourth columns:
df.drop(df.columns[[0,1,3]], axis=1, inplace=True)
Delete first column:
df.drop(df.columns[[0]], axis=1, inplace=True)
There is an optional parameter inplace
so that the original
data can be modified without creating a copy.
Column selection, addition, deletion
Delete column column-name
:
df.pop('column-name')
df = DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6]), ('C', [7,8, 9])], orient='index', columns=['one', 'two', 'three'])
print df
:
one two three
A 1 2 3
B 4 5 6
C 7 8 9
df.drop(df.columns[[0]], axis=1, inplace=True)
print df
:
two three
A 2 3
B 5 6
C 8 9
three = df.pop('three')
print df
:
two
A 2
B 5
C 8
A quick note: Assume.assumeTrue(condition)
ignores rest of the steps but passes the test.
To fail the test, use org.junit.Assert.fail()
inside the conditional statement. Works same like Assume.assumeTrue()
but fails the test.
while using Header array
String auth = Base64.getEncoder().encodeToString(("test1:test1").getBytes());
Header[] headers = {
new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()),
new BasicHeader("Authorization", "Basic " +auth)
};
If you need to extend ActionBarActivity you need on your style.xml:
<!-- Base application theme. -->
<style name="AppTheme" parent="AppTheme.Base"/>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
If you set as main theme of your application as android:Theme.Material.Light instead of AppTheme.Base then you’ll get an “IllegalStateException:You need to use a Theme.AppCompat theme (or descendant) with this activity” error.
Take a look at class java.lang.Character
static member methods (isDigit, isLetter, isLowerCase, ...)
Example:
String str = "Hello World 123 !!";
int specials = 0, digits = 0, letters = 0, spaces = 0;
for (int i = 0; i < str.length(); ++i) {
char ch = str.charAt(i);
if (!Character.isDigit(ch) && !Character.isLetter(ch) && !Character.isSpace(ch)) {
++specials;
} else if (Character.isDigit(ch)) {
++digits;
} else if (Character.isSpace(ch)) {
++spaces;
} else {
++letters;
}
}
One gotcha arises when you want to instantiate a public type defined in an external package and that type embeds other types that are private.
Example:
package animals
type otherProps{
Name string
Width int
}
type Duck{
Weight int
otherProps
}
How do you instantiate a Duck
in your own program? Here's the best I could come up with:
package main
import "github.com/someone/animals"
func main(){
var duck animals.Duck
// Can't instantiate a duck with something.Duck{Weight: 2, Name: "Henry"} because `Name` is part of the private type `otherProps`
duck.Weight = 2
duck.Width = 30
duck.Name = "Henry"
}
function Errormessage(txt) {
$("#message").fadeIn("slow");
$("#message span:first").text(txt);
// find the span inside the div and assign a text
$("#message a.close-notify").click(function() {
$("#message").fadeOut("slow");
});
}
You just have to double up on the single quotes...
insert into Person (First, Last)
values ('Joe', 'O''Brien')
For those using bootstrap 4 beta you can add max-width on your navbar link to have control on the size of your logo with img-fluid class on the image element.
<a class="navbar-brand" href="#" style="max-width: 30%;">
<img src="images/logo.png" class="img-fluid">
</a>
I solve this problem by adding Full control
permission for both .mdf
and .ldf
files for Users
group.
Using sed
, just for variety:
ls -l | sed -n 2p
Using this alternative, which looks more efficient since it stops reading the input when the required line is printed, may generate a SIGPIPE in the feeding process, which may in turn generate an unwanted error message:
ls -l | sed -n -e '2{p;q}'
I've seen that often enough that I usually use the first (which is easier to type, anyway), though ls
is not a command that complains when it gets SIGPIPE.
For a range of lines:
ls -l | sed -n 2,4p
For several ranges of lines:
ls -l | sed -n -e 2,4p -e 20,30p
ls -l | sed -n -e '2,4p;20,30p'
All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.
If you have accidentally removed DLL file from php/ext
folder, just add it back (get the copy from XAMPP zip archive - its downloadable).
If you have deleted the accompanying INI configuration line from php.ini
file, add it back as well:
extension=php_mbstring.dll
Also, ensure to restart your webserver (Apache) using XAMPP control panel.
Additional Info on Enabling PHP Extensions
/XAMPP/php/ext
directory)extension_dir = "ext"
)Using PHP Function.
Of course query function ($this->model) you have to change to your own.
/**
* Creating a copy table based on the current one
*
* @param type $table_to_copy
* @param type $new_table_name
* @return type
* @throws Exception
*/
public function create($table_to_copy, $new_table_name)
{
$sql = "SHOW CREATE TABLE ".$table_to_copy;
$res = $this->model->queryRow($sql, PDO::FETCH_ASSOC);
if(!filled($res['Create Table']))
throw new Exception('Could not get the create code for '.$table_to_copy);
$newCreateSql = preg_replace(array(
'@CREATE TABLE `'.$table_to_copy.'`@',
'@KEY `'.$table_to_copy.'(.*?)`@',
'@CONSTRAINT `'.$table_to_copy.'(.*?)`@',
'@AUTO_INCREMENT=(.*?) @',
), array(
'CREATE TABLE `'.$new_table_name.'`',
'KEY `'.$new_table_name.'$1`',
'CONSTRAINT `'.$new_table_name.'$1`',
'AUTO_INCREMENT=1 ',
), $res['Create Table']);
return $this->model->exec($newCreateSql);
}
my problem was to copy the whole source files contains .idea directory and my webstorm terminal commands were run on the original directory of the source
I delete the .idea directory and it worked fine
Like others have said, it's not possible with just JavaScript due to the security model of such.
If you are able to, I'd recommend one of the below solutions..both of which use a flash component for the client side validations; however, are wired up using Javascript/jQuery. Both work very well and can be used with any server-side tech.
If you have an array of keys that you want to use then use array_combine
Given $keys = array('a', 'b', 'c', ...) and your array, $list, then do this:
$list = array_combine($keys, array_values($list));
List will now be array('a' => 'blabla 1', ...) etc.
You have to use array_values
to extract just the values from the array and not the old, numeric, keys.
That's nice and simple looking but array_values makes an entire copy of the array so you could have space issues. All we're doing here is letting php do the looping for us, not eliminate the loop. I'd be tempted to do something more like:
foreach ($list as $k => $v) {
unset ($list[$k]);
$new_key = *some logic here*
$list[$new_key] = $v;
}
I don't think it's all that more efficient than the first code but it provides more control and won't have issues with the length of the arrays.
Simple:
byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);
Do not access or modify the collection in the Comparator
. The comparator should be used only to determine which object is comes before another. The two objects that are to be compared are supplied as arguments.
Date
itself is comparable, so, using generics:
class MovieComparator implements Comparator<Movie> {
public int compare(Movie m1, Movie m2) {
//possibly check for nulls to avoid NullPointerException
return m1.getDate().compareTo(m2.getDate());
}
}
And do not instantiate the comparator on each sort. Use:
private static final MovieComparator comparator = new MovieComparator();
For Ubuntu users: First You need to install mailutils
sudo apt-get install mailutils
Setup an email server, if you are using gmail or smtp. follow this link. then use this command to send email.
echo "this is a test mail" | mail -s "Subject of mail" [email protected]
In case you are using gmail and still you are getting some authentication error then you need to change setting of gmail:
Turn on Access for less secure apps from here
You can also use a function within stat_summary to calculate the mean and the hjust argument to place the text, you need a additional function but no additional data frame:
fun_mean <- function(x){
return(data.frame(y=mean(x),label=mean(x,na.rm=T)))}
ggplot(PlantGrowth,aes(x=group,y=weight)) +
geom_boxplot(aes(fill=group)) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=3) +
stat_summary(fun.data = fun_mean, geom="text", vjust=-0.7)
Use this way:
$selectOption = $_POST['taskOption'];
But it is always better to give values to your <option>
tags.
<select name="taskOption">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
Source: java-implementation-of-rubys-gsub
Usage:
// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
public String replacement() {
float inches = Float.parseFloat(group(1));
return Float.toString(2.54f * inches) + " cm";
}
}.rewrite("a 17 inch display");
System.out.println(result);
// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
public String replacement() {
return group(1).toUpperCase();
}
}.rewrite("ab12 cd efg34");
System.out.println(result);
Implementation (redesigned):
import static java.lang.String.format;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class Rewriter {
private Pattern pattern;
private Matcher matcher;
public Rewriter(String regularExpression) {
this.pattern = Pattern.compile(regularExpression);
}
public String group(int i) {
return matcher.group(i);
}
public abstract String replacement() throws Exception;
public String rewrite(CharSequence original) {
return rewrite(original, new StringBuffer(original.length())).toString();
}
public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
try {
this.matcher = pattern.matcher(original);
while (matcher.find()) {
matcher.appendReplacement(destination, "");
destination.append(replacement());
}
matcher.appendTail(destination);
return destination;
} catch (Exception e) {
throw new RuntimeException("Cannot rewrite " + toString(), e);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(pattern.pattern());
for (int i = 0; i <= matcher.groupCount(); i++)
sb.append(format("\n\t(%s) - %s", i, group(i)));
return sb.toString();
}
}
You need to compile and link all your source files together:
g++ main.c function_file.c
Run either this in your app :
FacebookSdk.sdkInitialize(getApplicationContext());
Log.d("AppLog", "key:" + FacebookSdk.getApplicationSignature(this)+"=");
Or this:
public static void printHashKey(Context context) {
try {
final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures) {
final MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
final String hashKey = new String(Base64.encode(md.digest(), 0));
Log.i("AppLog", "key:" + hashKey + "=");
}
} catch (Exception e) {
Log.e("AppLog", "error:", e);
}
}
And then look at the logs.
The result should end with "=" .
As mentioned earlier, you'll create the add and delete commands. You can use svn move on both your working copy or the repository url. If you use your working copy, the changes won't be committed - you'll need to commit in a separate operation.
If you svn move a URL, you'll need to supply a --message, and the changes will be reflected in the repository immediately.
A more recent way to do this is to use the .to_numpy() function.
If I have a dataframe with a column 'price', I can convert it as follows:
priceArray = df['price'].to_numpy()
You can also pass the data type, such as float or object, as an argument of the function
The previously linked solution is a horrible piece of code; nearly every line contains a bug. Use fgetcsv instead:
<?php
echo "<html><body><table>\n\n";
$f = fopen("so-csv.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
You can use a 1 pixel per 1 pixel Java applet embedded in the page and use that for compression.
It's not JavaScript and the clients will need a Java runtime but it will do what you need.
Well, NSOperations are simply an API built on top of Grand Central Dispatch. So when you’re using NSOperations, you’re really still using Grand Central Dispatch. It’s just that NSOperations give you some fancy features that you might like. You can make some operations dependent on other operations, reorder queues after you sumbit items, and other things like that. In fact, ImageGrabber is already using NSOperations and operation queues! ASIHTTPRequest uses them under the hood, and you can configure the operation queue it uses for different behavior if you’d like. So which should you use? Whichever makes sense for your app. For this app it’s pretty simple so we just used Grand Central Dispatch directly, no need for the fancy features of NSOperation. But if you need them for your app, feel free to use it!
If you insist on using yum
, try yum install apt
.
As read on this site:
Link
I got a trick working as follows: [have not tested cross-browser!]
Define iframe's onload event handler defined as
$('#myIframe').on('load', function() {_x000D_
setTimeout(function() {_x000D_
try {_x000D_
console.log($('#myIframe')[0].contentWindow.document);_x000D_
} catch (e) {_x000D_
console.log(e);_x000D_
if (e.message.indexOf('Blocked a frame with origin') > -1 || e.message.indexOf('from accessing a cross-origin frame.') > -1) {_x000D_
alert('Same origin Iframe error found!!!');_x000D_
//Do fallback handling if you want here_x000D_
}_x000D_
}_x000D_
}, 1000);_x000D_
_x000D_
});
_x000D_
Disclaimer: It works only for SAME ORIGIN IFRAME documents.
Use static method valueOf(String)
defined for each enum
.
For example if you have enum MyEnum
you can say MyEnum.valueOf("foo")
Try this
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions
ON user_category_subscriptions.category_id = categories.category_id
WHERE user_category_subscriptions.user_id = 1
or user_category_subscriptions.user_id is null
Launch chrome like so to bypass this restriction: open -a "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --args --allow-file-access-from-files
.
Derived from Josh Lee's comment but I needed to specify the full path to Google Chrome so as to avoid having Google Chrome opening from my Windows partition (in Parallels).
In practice, it is O(1), but this actually is a terrible and mathematically non-sense simplification. The O() notation says how the algorithm behaves when the size of the problem tends to infinity. Hashmap get/put works like an O(1) algorithm for a limited size. The limit is fairly large from the computer memory and from the addressing point of view, but far from infinity.
When one says that hashmap get/put is O(1) it should really say that the time needed for the get/put is more or less constant and does not depend on the number of elements in the hashmap so far as the hashmap can be presented on the actual computing system. If the problem goes beyond that size and we need larger hashmaps then, after a while, certainly the number of the bits describing one element will also increase as we run out of the possible describable different elements. For example, if we used a hashmap to store 32bit numbers and later we increase the problem size so that we will have more than 2^32 bit elements in the hashmap, then the individual elements will be described with more than 32bits.
The number of the bits needed to describe the individual elements is log(N), where N is the maximum number of elements, therefore get and put are really O(log N).
If you compare it with a tree set, which is O(log n) then hash set is O(long(max(n)) and we simply feel that this is O(1), because on a certain implementation max(n) is fixed, does not change (the size of the objects we store measured in bits) and the algorithm calculating the hash code is fast.
Finally, if finding an element in any data structure were O(1) we would create information out of thin air. Having a data structure of n element I can select one element in n different way. With that, I can encode log(n) bit information. If I can encode that in zero bit (that is what O(1) means) then I created an infinitely compressing ZIP algorithm.
Raw
button.I've had to do this before using Paramiko in a case where I wanted to run a dynamic, local PyQt4 script on a host running an ssh server that has connected my OpenVPN server and ask for their routing preference (split tunneling).
So long as the ssh server you are connecting to has all of the required dependencies of your script (PyQt4 in my case), you can easily encapsulate the data by encoding it in base64 and use the exec()
built-in function on the decoded message. If I remember correctly my one-liner for this was:
stdout = client.exec_command('python -c "exec(\\"' + open('hello.py','r').read().encode('base64').strip('\n') + '\\".decode(\\"base64\\"))"' )[1]
It is hard to read and you have to escape the escape sequences because they are interpreted twice (once by the sender and then again by the receiver). It also may need some debugging, I've packed up my server to PCS or I'd just reference my OpenVPN routing script.
The difference in doing it this way as opposed to sending a file is that it never touches the disk on the server and is run straight from memory (unless of course they log the command). You'll find that encapsulating information this way (although inefficient) can help you package data into a single file.
For instance, you can use this method to include raw data from external dependencies (i.e. an image) in your main script.
use this regex: /<[^<]+?>/g
$val = preg_replace('/<[^<]+?>/g', ' ', $row_get_Business['business_description']);
$businessDesc = substr(val,0,110);
from your example should stay: Ref no: 30001
I'm sorry, I don't know why you get the error message. However, I'm using Java 7 and Windows 10 and the solution for me was to temporarily use Java 8 by changing the JAVA_HOME
environment variable. Then I could run mvn install
and fetch from Maven Central Repository.
In my experience this error is pretty common, for some reason jersey sometimes has problems parsing custom java types. Usually all you have to do is make sure that you respect the following 3 conditions:
However, I have ran into cases where this just was not enough. Then you can always wrap you custom data type in a GenericEntity and pass it as such to your ResponseBuilder:
GenericEntity<CustomDataType> entity = new GenericEntity<CustomDataType>(myObj) {};
return Response.status(httpCode).entity(entity).build();
This way you are trying to help jersey to find the proper/relevant serialization provider for you object. Well, sometimes this also is not enough. In my case I was trying to produce a text/plain from a custom data type. Theoretically jersey should have used the StringMessageProvider, but for some reason that I did not manage to discover it was giving me this error:
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/plain
So what solved the problem for me was to do my own serialization with jackson's writeValueAsString(). I'm not proud of it but at the end of the day I can deliver an acceptable solution.
You can just use exec
to replace your current shell with a new shell:
Switch to bash
:
exec bash
Switch to zsh
:
exec zsh
This won't affect new terminal windows or anything, but it's convenient.
This is resolved. The problem was elsewhere. Another code in cron job was truncating XML to 0 length file. I have taken care of that.
In Ruby, the Windows version anyways, I just checked and __FILE__
does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.
In PHP __FILE__
is the full path (which in my opinion is preferable). This is why, in order to make your paths portable in Ruby, you really need to use this:
File.expand_path(File.dirname(__FILE__) + "relative/path/to/file")
I should note that in Ruby 1.9.1 __FILE__
contains the full path to the file, the above description was for when I used Ruby 1.8.7.
In order to be compatible with both Ruby 1.8.7 and 1.9.1 (not sure about 1.9) you should require files by using the construct I showed above.
Just remember to add quotes into the path if you have a space in your path to java home. C:\Program Files\java\javaxxx\ doesn't work but "C:\Program Files\java\javaxxx\" does.
Regarding some points mentioned in previous answers, and to improve readability:
No need for data.loc or query, but I do think it is a bit long.
The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators.
I like to write such expressions as follows - less brackets, faster to type, easier to read. Closer to R, too.
q_product = df.Product == p_id
q_start = df.Time > start_time
q_end = df.Time < end_time
df.loc[q_product & q_start & q_end, c('Time,Product')]
# c is just a convenience
c = lambda v: v.split(',')
On Linux use below to test (it would replace the whitespaces with comma)
sed 's/\s/,/g' /tmp/test.txt | head
later you can take the output into the file using below command:
sed 's/\s/,/g' /tmp/test.txt > /tmp/test_final.txt
PS: test is the file which you want to use
The most fundamental thing here probably is that you don't want to transmit static images but only changes to the images, which essentially is analogous to video stream.
My best guess is some very efficient (and heavily specialized and optimized) motion compensation algorithm, because most of the actual change in generic desktop usage is linear movement of elements (scrolling text, moving windows, etc. opposed to transformation of elements).
The DirectX 3D performance of 1 FPS seems to confirm my guess to some extent.
export class Car {
id: number;
make: string;
model: string;
color: string;
year: Date;
constructor(car) {
{
this.id = car.id;
this.make = car.make || '';
this.model = car.model || '';
this.color = car.color || '';
this.year = new Date(car.year).getYear();
}
}
}
The || can become super useful for very complex data objects to default data that doesn't exist.
. .
In your component.ts or service.ts file you can deserialize response data into the model:
// Import the car model
import { Car } from './car.model.ts';
// If single object
car = new Car(someObject);
// If array of cars
cars = someDataToDeserialize.map(c => new Car(c));
I don't program Scala, but I use another language with implicit returns (Ruby). You have code after your if (elem.isEmpty)
block -- the last line of code is what's returned, which is why you're not getting what you're expecting.
EDIT: Here's a simpler way to write your function too. Just use the boolean value of isEmpty and count to return true or false automatically:
def balanceMain(elem: List[Char]): Boolean =
{
elem.isEmpty && count == 0
}
Don't know Scala at all, however a few weeks ago I could not read Clojure. Now I can read most of it, but can not write anything yet beyond the most simplistic examples. I suspect Scala is no different. You need a good book or course depending on how you learn. Just reading the map declaration above, I got maybe 1/3 of it.
I believe the bigger problems are not the syntax of these languages, but adopting and internalizing the paradigms that make them usable in everyday production code. For me Java was not a huge leap from C++, which was not a huge leap from C, which was not a leap at all from Pascal, nor Basic etc... But coding in a functional language like Clojure is a huge leap (for me anyway). I guess in Scala you can code in Java style or Scala style. But in Clojure you will create quite the mess trying to keep your imperative habits from Java.
<head>
<link rel="shortcut icon" href="favicon.ico">
</head>
you can build and execute dynamic sql to do this, but its really not ideal
check versions of node, npm, npx as given below. if npx is not installed then use npm i -g npx
node -v
npm -v
npx -v
You have indented part of your code in settings.py:
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
#'django.contrib.admindocs',
'tinymce',
'sorl.thumbnail',
'south',
'django_facebook',
'djcelery',
'devserver',
'main',
Therefore, it is giving you an error.
The ->
operator, which is applied exclusively to pointers, is needed to obtain the specified field or method of the object referenced by the pointer. (this applies also to structs
just for their fields)
If you have a variable ptr
declared as a pointer you can think of it as (*ptr).field
.
A side node that I add just to make pedantic people happy: AS ALMOST EVERY OPERATOR you can define a different semantic of the operator by overloading it for your classes.
How about something like
=LEFT(A1,SEARCH(" ",A1)-1)
or
=LEFT(A1,SEARCH("<b>",A1)-1)
Have a look at MS Excel: Search Function and Excel 2007 LEFT Function
It depends on what is in test.py
. The following is an appropriate structure:
# suppose this is your 'test.py' file
def main():
"""This function runs the core of your program"""
print("running main")
if __name__ == "__main__":
# if you call this script from the command line (the shell) it will
# run the 'main' function
main()
If you keep this structure, you can run it like this in the command line (assume that $
is your command-line prompt):
$ python test.py
$ # it will print "running main"
If you want to run it from the Python shell, then you simply do the following:
>>> import test
>>> test.main() # this calls the main part of your program
There is no necessity to use the subprocess
module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.
Based on @Jay Seth's answer, I made a version of FormErrors class especially for Ajax Forms:
// src/AppBundle/Form/FormErrors.php
namespace AppBundle\Form;
class FormErrors
{
/**
* @param \Symfony\Component\Form\Form $form
*
* @return array $errors
*/
public function getArray(\Symfony\Component\Form\Form $form)
{
return $this->getErrors($form, $form->getName());
}
/**
* @param \Symfony\Component\Form\Form $baseForm
* @param \Symfony\Component\Form\Form $baseFormName
*
* @return array $errors
*/
private function getErrors($baseForm, $baseFormName) {
$errors = array();
if ($baseForm instanceof \Symfony\Component\Form\Form) {
foreach($baseForm->getErrors() as $error) {
$errors[] = array(
"mess" => $error->getMessage(),
"key" => $baseFormName
);
}
foreach ($baseForm->all() as $key => $child) {
if(($child instanceof \Symfony\Component\Form\Form)) {
$cErrors = $this->getErrors($child, $baseFormName . "_" . $child->getName());
$errors = array_merge($errors, $cErrors);
}
}
}
return $errors;
}
}
Usage (e.g. in your action):
$errors = $this->get('form_errors')->getArray($form);
Symfony version: 2.8.4
Example JSON response:
{
"success": false,
"errors": [{
"mess": "error_message",
"key": "RegistrationForm_user_firstname"
}, {
"mess": "error_message",
"key": "RegistrationForm_user_lastname"
}, {
"mess": "error_message",
"key": "RegistrationForm_user_email"
}, {
"mess": "error_message",
"key": "RegistrationForm_user_zipCode"
}, {
"mess": "error_message",
"key": "RegistrationForm_user_password_password"
}, {
"mess": "error_message",
"key": "RegistrationForm_terms"
}, {
"mess": "error_message2",
"key": "RegistrationForm_terms"
}, {
"mess": "error_message",
"key": "RegistrationForm_marketing"
}, {
"mess": "error_message2",
"key": "RegistrationForm_marketing"
}]
}
The error object contains the "key" field, which is the id of the input DOM element, so you can easily populate error messages.
If you have child forms inside the parent, don't forget to add the cascade_validation
option inside the parent form's setDefaults
.
In this case I might just simply avoid regular expressions altogether and go with something like:
if (StringToTest.IndexOf("ab") < 0)
//do stuff
This is likely also going to be much faster (a quick test vs regexes above showed this method to take about 25% of the time of the regex method). In general, if I know the exact string I'm looking for, I've found regexes are overkill. Since you know you don't want "ab", it's a simple matter to test if the string contains that string, without using regex.
Short answer: no. window.location.href
is not capable of passing POST data.
Somewhat more satisfying answer: You can use this function to clone all your form data and submit it.
var submitMe = document.createElement("form");
submitMe.action = "YOUR_URL_HERE"; // Remember to change me
submitMe.method = "post";
submitMe.enctype = "multipart/form-data";
var nameJoiner = "_";
// ^ The string used to join form name and input name
// so that you can differentiate between forms when
// processing the data server-side.
submitMe.importFields = function(form){
for(k in form.elements){
if(input = form.elements[k]){
if(input.type!="submit"&&
(input.nodeName=="INPUT"
||input.nodeName=="TEXTAREA"
||input.nodeName=="BUTTON"
||input.nodeName=="SELECT")
){
var output = input.cloneNode(true);
output.name = form.name + nameJoiner + input.name;
this.appendChild(output);
}
}
}
}
submitMe.importFields(form_element);
for each of the three forms you want to submit. <input name="email">
in <form name="login">
, the submitted name will be login_name
. nameJoiner
variable to something other than _
so it doesn't conflict with your input naming scheme.submitMe.submit();
I tried the Visual Studio Project Renamer, but, it threw exceptions in the few cases where I tried it.
I have had good success with CopyWiz.
I am in no way affiliated with them, and I have not yet paid for it, but I may have to soon, as it is the only tool that seems to work for both my C# and C++ projects. I do hope they make a little money, and continue to improve it, though.
Try Server.UrlEncode()
, or System.Web.HttpUtility.UrlEncode()
for instances when you don't have access to the Server
object. You can also use System.Uri.EscapeUriString()
to avoid adding a reference to the System.Web
assembly.
In my case it was because I switched to master using
git checkout -B master
Just to pull the new version of it instead of
git checkout master
The first command resets the head of master to my latest commits
I used
git reset --hard origin/master
To fix that
If you are using C++11, and you need the value as a C++ compile-time constant, a very elegant solution is this:
#include <tuple>
#define MACRO(...) \
std::cout << "num args: " \
<< std::tuple_size<decltype(std::make_tuple(__VA_ARGS__))>::value \
<< std::endl;
Please note: the counting happens entirely at compile time, and the value can be used whenever compile-time integer is required, for instance as a template parameter to std::array.
An example for subtraction is given below:
Select value1 - (select value2 from AnyTable1) from AnyTable2
value1 & value2 can be count,sum,average output etc. But the values should be comapatible
Use psexec -s
The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.
To run another Python environment according to the official Virtualenv documentation, in the command line you can specify the full path to the executable Python binary, just that (no need to active the virtualenv before):
/path/to/virtualenv/bin/python
The same applies if you want to invoke a script from the command line with your virtualenv. You don't need to activate it before:
me$ /path/to/virtualenv/bin/python myscript.py
The same for a Windows environment (whether it is from the command line or from a script):
> \path\to\env\Scripts\python.exe myscript.py
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
SQLite out-of-the-box is not really feature-full regarding concurrency. You will get into trouble if you have hundreds of web requests hitting the same SQLite database.
You should definitely go with MySQL or PostgreSQL.
If it is for a single-person project, SQLite will be easier to setup though.
Unrecognized option: - Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit.
I was getting this Error due to incorrect syntax using in the terminal. I was using java - version. But its actually is java -version. there is no space between - and version. you can also cross check by using java -help.
i hope this will help.
Updated for RC.5
With Angular 2 we can debounce using RxJS operator debounceTime()
on a form control's valueChanges
observable:
import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/throttleTime';
import 'rxjs/add/observable/fromEvent';
@Component({
selector: 'my-app',
template: `<input type=text [value]="firstName" [formControl]="firstNameControl">
<br>{{firstName}}`
})
export class AppComponent {
firstName = 'Name';
firstNameControl = new FormControl();
formCtrlSub: Subscription;
resizeSub: Subscription;
ngOnInit() {
// debounce keystroke events
this.formCtrlSub = this.firstNameControl.valueChanges
.debounceTime(1000)
.subscribe(newValue => this.firstName = newValue);
// throttle resize events
this.resizeSub = Observable.fromEvent(window, 'resize')
.throttleTime(200)
.subscribe(e => {
console.log('resize event', e);
this.firstName += '*'; // change something to show it worked
});
}
ngDoCheck() { console.log('change detection'); }
ngOnDestroy() {
this.formCtrlSub.unsubscribe();
this.resizeSub .unsubscribe();
}
}
The code above also includes an example of how to throttle window resize events, as asked by @albanx in a comment below.
Although the above code is probably the Angular-way of doing it, it is not efficient. Every keystroke and every resize event, even though they are debounced and throttled, results in change detection running. In other words, debouncing and throttling do not affect how often change detection runs. (I found a GitHub comment by Tobias Bosch that confirms this.) You can see this when you run the plunker and you see how many times ngDoCheck()
is being called when you type into the input box or resize the window. (Use the blue "x" button to run the plunker in a separate window to see the resize events.)
A more efficient technique is to create RxJS Observables yourself from the events, outside of Angular's "zone". This way, change detection is not called each time an event fires. Then, in your subscribe callback methods, manually trigger change detection – i.e., you control when change detection is called:
import {Component, NgZone, ChangeDetectorRef, ApplicationRef,
ViewChild, ElementRef} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/throttleTime';
import 'rxjs/add/observable/fromEvent';
@Component({
selector: 'my-app',
template: `<input #input type=text [value]="firstName">
<br>{{firstName}}`
})
export class AppComponent {
firstName = 'Name';
keyupSub: Subscription;
resizeSub: Subscription;
@ViewChild('input') inputElRef: ElementRef;
constructor(private ngzone: NgZone, private cdref: ChangeDetectorRef,
private appref: ApplicationRef) {}
ngAfterViewInit() {
this.ngzone.runOutsideAngular( () => {
this.keyupSub = Observable.fromEvent(this.inputElRef.nativeElement, 'keyup')
.debounceTime(1000)
.subscribe(keyboardEvent => {
this.firstName = keyboardEvent.target.value;
this.cdref.detectChanges();
});
this.resizeSub = Observable.fromEvent(window, 'resize')
.throttleTime(200)
.subscribe(e => {
console.log('resize event', e);
this.firstName += '*'; // change something to show it worked
this.cdref.detectChanges();
});
});
}
ngDoCheck() { console.log('cd'); }
ngOnDestroy() {
this.keyupSub .unsubscribe();
this.resizeSub.unsubscribe();
}
}
I use ngAfterViewInit()
instead of ngOnInit()
to ensure that inputElRef
is defined.
detectChanges()
will run change detection on this component and its children. If you would rather run change detection from the root component (i.e., run a full change detection check) then use ApplicationRef.tick()
instead. (I put a call to ApplicationRef.tick()
in comments in the plunker.) Note that calling tick()
will cause ngDoCheck()
to be called.
Some of these answers have you using /dev/zero
for the source of your data. If your testing network upload speeds, this may not be the best idea if your application is doing any compression, a file full of zeros compresses really well. Using this command to generate the file
dd if=/dev/zero of=upload_test bs=10000 count=1
I could compress upload_test
down to about 200 bytes. So you could put yourself in a situation where you think your uploading a 10KB file but it would actually be much less.
What I suggest is using /dev/urandom
instead of /dev/zero
. I couldn't compress the output of /dev/urandom
very much at all.
Just check for
if(table.rows[0][0] == null)
{
//Whatever I want to do
}
or you could
if(t.Rows[0].IsNull(0))
{
//Whatever I want to do
}
I have seen other code which I have inherited which uses SELECT TOP 100 PERCENT
The reason for this is simple: Enterprise Manager used to try to be helpful and format your code to include this for you. There was no point ever trying to remove it as it didn't really hurt anything and the next time you went to change it EM would insert it again.
This is jQuery Email Validation using Regex Expression. you can also use the same concept for AngularJS if you have idea of AngularJS.
var expression = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
I ran into this issue when I was trying to restore a backed up mysql database from a different server. What solved this issue for me was adding certain settings to my.conf (like in the questions above) and additionally changing the sql backup file:
Step 1: add or edit the following lines in my.conf:
innodb_page_size=32K
innodb_file_format=Barracuda
innodb_file_per_table=1
Step 2 add ROW_FORMAT=DYNAMIC to the table create statement in the sql backup file for the table that is causing this error:
DROP TABLE IF EXISTS `problematic_table`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `problematic_table` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
...
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 ROW_FORMAT=DYNAMIC;
the important change above is ROW_FORMAT=DYNAMIC; (that was not included in the orignal sql backup file)
source that helped me to resolve this issue: MariaDB and InnoDB MySQL Row size too large
I solved this installing the 'postgresql-common' package. This package provides the pg_config
binary which is most likely what you were missing.
I have same problem after update android studio to 1.5, and i fix it by update the gradle location,
Hope this method works for you,
To check if a character is lower case, use the islower
method of str
. This simple imperative program prints all the lowercase letters in your string:
for c in s:
if c.islower():
print c
Note that in Python 3 you should use print(c)
instead of print c
.
Possibly ending up with assigning those letters to a different variable.
To do this I would suggest using a list comprehension, though you may not have covered this yet in your course:
>>> s = 'abCd'
>>> lowercase_letters = [c for c in s if c.islower()]
>>> print lowercase_letters
['a', 'b', 'd']
Or to get a string you can use ''.join
with a generator:
>>> lowercase_letters = ''.join(c for c in s if c.islower())
>>> print lowercase_letters
'abd'
You can force a "session-wide caching" if you add the session-id as a spurious parameter of the JavaScript/CSS file:
<link rel="stylesheet" src="myStyles.css?ABCDEF12345sessionID" />
<script language="javascript" src="myCode.js?ABCDEF12345sessionID"></script>
If you want a version-wide caching, you could add some code to print the file date or similar. If you're using Java you can use a custom-tag to generate the link in an elegant way.
<link rel="stylesheet" src="myStyles.css?20080922_1020" />
<script language="javascript" src="myCode.js?20080922_1120"></script>
Here is a one line Pythonic version:
import os
dir = 'given_directory_name'
filenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]
This code lists the full path of all files and directories in the given directory name.
Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Then you could use
Call fso.CopyFile(source, destination[, overwrite] )
where source and destination are the full names (including paths) of the file.
See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:
public interface Predicate<ARGTYPE>
{
public boolean evaluate(ARGTYPE arg);
}
And then you might have an implementation such as:
public class Tautology<E> implements Predicate<E>
{
public boolean evaluate(E arg){
return true;
}
}
To get a better conceptual understanding, you might want to read about first-order logic.
Edit
There is a standard Predicate interface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicate interface from Guava.
Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> true
to a function instead of defining a named Tautology subclass like the above.
Install Entity framework to the current project using the below command: PM> Install-Package EntityFramework -IncludePrerelease
Add a class "MyDBContext" in the Model folder as given below:
public class MyDBContext : DbContext { public MyDBContext() { } }
Now enable migrations for the current project with the below command: PM> enable-migrations
The derived table would work, but if this is SQL 2005, a CTE and ROW_NUMBER might be cleaner:
WITH UserStatus (User, Date, Status, Notes, Ord)
as
(
SELECT Date, User, Status, Notes,
ROW_NUMBER() OVER (PARTITION BY User ORDER BY Date DESC)
FROM [SOMETABLE]
)
SELECT User, Date, Status, Notes from UserStatus where Ord = 1
This would also facilitate the display of the most recent x statuses from each user.
Use the hex code for a non-breaking space. Something like this:
.breadcrumbs a:before {
content: '>\00a0';
}
I think it is way more safer to rely on the browser than any ingenious regex:
const parseUrl = function(url) { _x000D_
const a = document.createElement('a')_x000D_
a.href = url_x000D_
return {_x000D_
protocol: a.protocol ? a.protocol : null,_x000D_
hostname: a.hostname ? a.hostname : null,_x000D_
port: a.port ? a.port : null,_x000D_
path: a.pathname ? a.pathname : null,_x000D_
query: a.search ? a.search : null,_x000D_
hash: a.hash ? a.hash : null,_x000D_
host: a.host ? a.host : null _x000D_
}_x000D_
}_x000D_
_x000D_
console.log( parseUrl(window.location.href) ) //stacksnippet_x000D_
//to obtain a query_x000D_
console.log( parseUrl( 'https://example.com?qwery=this').query )
_x000D_
mongorestore -d db_name /path/
make sure you run this query in bin folder of mongoDb
C:\Program Files\MongoDB\Server\4.2\bin -
then run this above command.
in HQL you can use query parameter and set Collection with setParameterList method.
Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
q.setParameterList("names", names);
If you have the HTML
<form name="formname" .... id="form-first">
<iframe id="one" src="iframe2.html">
</iframe>
</form>
and JavaScript
function iframeRef( frameRef ) {
return frameRef.contentWindow
? frameRef.contentWindow.document
: frameRef.contentDocument
}
var inside = iframeRef( document.getElementById('one') )
inside
is now a reference to the document, so you can do getElementsByTagName('textarea')
and whatever you like, depending on what's inside the iframe src.
If you are using macOS then => sudo ./gradlew clean
will work for you.
You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.
Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.
You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.
The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.
You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.
Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.
But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).
You should provide @2x images for the Retina Macbook Pro and future Retina Macs.
try this rather than redirect...
Response.Write("<script>");
Response.Write("window.open('ClickPicture.aspx','_blank')");
Response.Write("</script>");
For comparison, here is another way to read the file. It has one advantage that you don't need to know how many integers there are in the file.
File file = new File("Tall.txt");
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
String[] valueStr = new String(bytes).trim().split("\\s+");
int[] tall = new int[valueStr.length];
for (int i = 0; i < valueStr.length; i++)
tall[i] = Integer.parseInt(valueStr[i]);
System.out.println(Arrays.asList(tall));
It sounds like you have file in the git repo owned by root. Since you're ssh'ing in as 'username' to do the push, the files must be writable by username. The easiest thing is probably to create the repo as the user, and use the same user to do your pushes. Another option is to create a group, make everything writable by the group, and make your user a member of that group.
var res = from element in list
group element by element.F1
into groups
select groups.OrderBy(p => p.F2).First();
VBA is not VB/VB.NET
The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:
Do While counter < 20
counter = counter + 1
Loop
(But a For..Next might be more appropriate here.)
Happy coding.
Confirm "Certificates" category is selected.
Remove expired Apple Worldwide Developer Relations Certificate Authority certificates from "login" tab and "System" tab.
Here's Apple's answer.
Thanks for bringing this to the attention of the community and apologies for the issues you’ve been having. This issue stems from having a copy of the expired WWDR Intermediate certificate in both your System and Login keychains. To resolve the issue, you should first download and install the new WWDR intermediate certificate (by double-clicking on the file). Next, in the Keychain Access application, select the System keychain. Make sure to select “Show Expired Certificates” in the View menu and then delete the expired version of the Apple Worldwide Developer Relations Certificate Authority Intermediate certificate (expired on February 14, 2016). Your certificates should now appear as valid in Keychain Access and be available to Xcode for submissions to the App Store.
You defined your method as non-static and you are trying to invoke it as static. That said...
1.if you want to invoke a static method, you should use the ::
and define your method as static.
// Defining a static method in a Foo class.
public static function getAll() { /* code */ }
// Invoking that static method
Foo::getAll();
2.otherwise, if you want to invoke an instance method you should instance your class, use ->
.
// Defining a non-static method in a Foo class.
public function getAll() { /* code */ }
// Invoking that non-static method.
$foo = new Foo();
$foo->getAll();
Note: In Laravel, almost all Eloquent methods return an instance of your model, allowing you to chain methods as shown below:
$foos = Foo::all()->take(10)->get();
In that code we are statically calling the all
method via Facade. After that, all other methods are being called as instance methods.
The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..
<asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
AutoPostBack="True" AppendDataBoundItems="true">
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList2
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList3
}
it might sound strange but for me worked restarting my mac..i cant explain why and what happened but it works now. hope it will helps someone
Are you using a database code generation tool like SQLMETAL in your project?
If so, you may be facing a pluralized to unpluralized transition issue.
In my case, I have noted that some old pluralized (*) table names (upon which SQLMETAL adds, by default, an "s" letter at the end) table references to classes generated by SQLMETAL.
Since, I have recently disabled Pluralization of names, after regerating some database related classes, some of them lost their "s" prefix. Therefore, all references to affected table classes became invalid. For this reason, I have several compilation errors like the following:
'xxxx' does not contain a definition for 'TableNames' and no extension method 'TableNames' accepting a first argument of type 'yyyy' could be found (are you missing a using directive or an assembly reference?)
As you know, I takes only on error to prevent an assembly from compiling. And that is the missing assemply is linkable to dependent assemblies, causing the original "Metadata file 'XYZ' could not be found"
After fixing affected class tables references manually to their current names (unpluralized), I was finnaly able to get my project back to life!
(*) If option Visual Studio > Tools menu > Options > Database Tools > O/R Designer > Pluralization of names is enabled, some SQLMETALl code generator will add an "s" letter at the end of some generated table classes, although table has no "s" suffix on target database. For further information, please refer to http://msdn.microsoft.com/en-us/library/bb386987(v=vs.110).aspx
Hope it helps!
For cases where you use pandas.DataFrame.hist
:
plt = df.Column_A.hist(bins=10)
Note that you get an ARRAY of plots, rather than a plot. Thus to set the x label you will need to do something like this
plt[0][0].set_xlabel("column A")
You can use the following.
@using (Html.BeginForm("MyAction", "MyController", new { area = "MyArea" }, FormMethod.Post, new { @class = "" }))
{
<div class="col-md-6">
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
@Html.LabelFor(m => m.MyData, new { @class = "col-form-label" })
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-12">
@Html.TextBoxFor(m => m.MyData, new { @class = "form-control" })
</div>
</div>
<div class="col-md-6">
<div class="">
<button class="btn btn-primary" type="submit">Send</button>
<button class="btn btn-danger" type="reset"> Clear</button>
</div>
</div>
}
Then clear the form:
$('.btn:reset').click(function (ev) {
ev.preventDefault();
$(this).closest('form').find("input").each(function(i, v) {
$(this).val("");
});
});
Wikipedia has the best description
In C++03, the compiler must instantiate a template whenever a fully specified template is encountered in a translation unit. If the template is instantiated with the same types in many translation units, this can dramatically increase compile times. There is no way to prevent this in C++03, so C++11 introduced extern template declarations, analogous to extern data declarations.
C++03 has this syntax to oblige the compiler to instantiate a template:
template class std::vector<MyClass>;
C++11 now provides this syntax:
extern template class std::vector<MyClass>;
which tells the compiler not to instantiate the template in this translation unit.
nonstandard extension used...
Microsoft VC++ used to have a non-standard version of this feature for some years already (in C++03). The compiler warns about that to prevent portability issues with code that needed to compile on different compilers as well.
Look at the sample in the linked page to see that it works roughly the same way. You can expect the message to go away with future versions of MSVC, except of course when using other non-standard compiler extensions at the same time.
the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face
@font-face {
font-family: 'Name You Font';
src: url('assets/font/xxyourfontxxx.eot');
src: local('Cera Pro Medium'), local('CeraPro-Medium'),
url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
url('assets/font/xxyourfontxxx.woff') format('woff'),
url('assets/font/xxyourfontxxx.ttf') format('truetype');
font-weight: 500;
font-style: normal;
}
So you can just indicate your fontfamily name that you already choosed
NOTE: the font-weight and font-style depend on your .woff .ttf ... files
I would like to emphasize @icza answer and simplify it a bit since it is a crucial concept. I assume that reader is familiar with slices.
c := append(a, b...)
This is a valid answer to the question. BUT if you need to use slices 'a' and 'c' later in code in different context, this is not the safe way to concatenate slices.
To explain, lets read the expression not in terms of slices, but in terms of underlying arrays:
"Take (underlying) array of 'a' and append elements from array 'b' to it. If array 'a' has enough capacity to include all elements from 'b' - underlying array of 'c' will not be a new array, it will actually be array 'a'. Basically, slice 'a' will show len(a) elements of underlying array 'a', and slice 'c' will show len(c) of array 'a'."
append() does not necessarily create a new array! This can lead to unexpected results. See Go Playground example.
Always use make() function if you want to make sure that new array is allocated for the slice. For example here are few ugly but efficient enough options for the task.
la := len(a)
c := make([]int, la, la + len(b))
_ = copy(c, a)
c = append(c, b...)
la := len(a)
c := make([]int, la + len(b))
_ = copy(c, a)
_ = copy(c[la:], b)
Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:
$('#myButton').on('click', function(event) {
event.preventDefault(); // To prevent following the link (optional)
...
});
You can also use inline javascript in the onclick attribute:
<a ... onclick="myFunc();">..</a>
From the Wikipedia article on Java package naming:
In general, a package name begins with the top level domain name of the organization and then the organization's domain and then any subdomains, listed in reverse order. The organization can then choose a specific name for its package. Package names should be all lowercase characters whenever possible.
For example, if an organization in Canada called MySoft creates a package to deal with fractions, naming the package ca.mysoft.fractions distinguishes the fractions package from another similar package created by another company. If a US company named MySoft also creates a fractions package, but names it us.mysoft.fractions, then the classes in these two packages are defined in a unique and separate namespace.
I found this post through the fact that I had this error myself in my own code and I know that it has been a while since this was posted and you already got some answers and fixed issue for that situation but just wanted to explain how I fixed it just in case it could help someone else!! Basically what I thought at first was that the code editor as was using REPL.it as was making something for a friend and knew that she wouldn't want to have to download like a code editor anyways the point is I thought that it couldn't handle the code because the complexity was at 139 at that point got even higher afterwards, but then I began experimenting and realized that within my set of functions just outside of a true loop within my a_loop function for that letter to register it needed to define it! So basically I wasn't defining the Value in this case a counting feature actually within the code! I would share my code here but it's kind of personal as in the print statements and also it's 2349 lines long and yeah anyway hope this helps! Also recommend using if you can in my case for some of the code I could, putting it into way more scripts if you can to make it easier on your brain! Once again hope this helps, if you have any questions, please feel free to ask and I will answer to the best of my ability! I hope this helps!!!
-Sam