If trigger("chosen:updated");
not working, use .trigger("liszt:updated");
of @Nhan Tran it is working fine.
strcat
has the declaration:
char *strcat(char *dest, const char *src)
It expects 2 strings. While this compiles:
char str[1024] = "Hello World";
char tmp = '.';
strcat(str, tmp);
It will cause bad memory issues because strcat
is looking for a null terminated cstring. You can do this:
char str[1024] = "Hello World";
char tmp[2] = ".";
strcat(str, tmp);
If you really want to append a char you will need to make your own function. Something like this:
void append(char* s, char c) {
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
append(str, tmp)
Of course you may also want to check your string size etc to make it memory safe.
This is another dark Eclipse theme: http://blog.prabir.me/post/Dark-Eclipse-Theme.aspx.
I have the Visual Studio equivalent of the theme.
An easy way I'm using:
file_put_contents($output_file, file_get_contents($base64_string));
This works well because file_get_contents
can read data from a URI, including a data:// URI.
If you want to disable a single transition property, you can do:
transition: color 0s;
(since a zero second transition is the same as no transition.)
The syntax is wrong, it should instead be
svn merge <what(the range)> <from(your dev branch)> <to(trunk/trunk local copy)>
You should learn objective c and program native apps. Do not rely on these things you think will make life easier. Apple has made sure the easiest way is using their native tools and language. For your 100 lines of javascript I can do the same in 3 lines of code or no code at all depending on the element. Watch some tutorials - if you understand javascript then objective c is not hard. Workarounds are miserable and apple can pull the plug on you anytime they want.
Instead of getting IMEI from TelephonyManager use ANDROID_ID.
Settings.Secure.ANDROID_ID
This works for each android device irrespective of having telephony.
a = np.empty(0)
for x in y:
a = np.append(a, x)
Requests doesn't have an equivalent to Urlib2's read()
.
>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True
It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.
Edit for Python 3:
Python now handles data types differently. response.content
returns a sequence of bytes
(integers that represent ASCII) while response.text
is a string
(sequence of chars).
Thus,
>>> print response.content == response.text
False
>>> print str(response.content) == response.text
True
Building on Alex's answer, here is a more generic function:
applyToGivenRow = @(func, matrix) @(row) func(matrix(row, :));
newApplyToRows = @(func, matrix) arrayfun(applyToGivenRow(func, matrix), 1:size(matrix,1), 'UniformOutput', false)';
takeAll = @(x) reshape([x{:}], size(x{1},2), size(x,1))';
genericApplyToRows = @(func, matrix) takeAll(newApplyToRows(func, matrix));
Here is a comparison between the two functions:
>> % Example
myMx = [1 2 3; 4 5 6; 7 8 9];
myFunc = @(x) [mean(x), std(x), sum(x), length(x)];
>> genericApplyToRows(myFunc, myMx)
ans =
2 1 6 3
5 1 15 3
8 1 24 3
>> applyToRows(myFunc, myMx)
??? Error using ==> arrayfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
Error in ==> @(func,matrix)arrayfun(applyToGivenRow(func,matrix),1:size(matrix,1))'
For primitives, if you want to avoid boxing, Guava has helpers for primitive arrays e.g. Ints.indexOf(int[] array, int target)
function truncateString(str, length) {
return str.length > length ? str.substring(0, length - 3) + '...' : str
}
If you really want to run Jenkins as you, I suggest you check out my Jenkins.app. An alternative, easy way to run Jenkins on Mac.
See https://github.com/stisti/jenkins-app/
Download it from https://github.com/stisti/jenkins-app/downloads
When ever I got this problem:
AttributeError: module 'enum' has no attribute 'IntFlag'
simply first i run the command:
unset PYTHONPATH
and then run my desired command then got success in that.
Go to Start
> Programs
> Microsoft SQL Server
> Enterprise Manager
Right-click the SQL Server instance name > Select Properties
from the context menu > Select Security
node in left navigation bar
Under Authentication section, select SQL Server and Windows Authentication
Note: The server must be stopped and re-started before this will take effect
Error 18452 (not associated with a trusted sql server connection)
I find this the best and cleanest solution to it. Using text-indent on the input
element
CSS:
#icon{
background-image:url(../images/icons/dollar.png);
background-repeat: no-repeat;
background-position: 2px 3px;
}
HTML:
<input id="icon" style="text-indent:17px;" type="text" placeholder="Username" />
services.msc
Find MySql and change properties to the disabled.Xampp
uninstall MySql by the checkbox on the left side, and install again by the click in the same checkbox.You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):
Sub Count_Selection()
Dim cell As Object
Dim count As Integer
count = 0
For Each cell In Selection
count = count + 1
Next cell
MsgBox count & " item(s) selected"
End Sub
I picked node-sass implementer for libsass because it is based on node.js.
$ npm install -g node-sass
installs node-sass globally -g
.This will hopefully install all you need, if not read libsass at the bottom.
General format:
$ node-sass [options] <input.scss> [output.css]
$ cat <input.scss> | node-sass > output.css
Examples:
$ node-sass my-styles.scss my-styles.css
compiles a single file manually.$ node-sass my-sass-folder/ -o my-css-folder/
compiles all the files in a folder manually.$ node-sass -w sass/ -o css/
compiles all the files in a folder automatically whenever the source file(s) are modified. -w
adds a watch for changes to the file(s).More usefull options like 'compression' @ here. Command line is good for a quick solution, however, you can use task runners like Grunt.js or Gulp.js to automate the build process.
You can also add the above examples to npm scripts. To properly use npm scripts as an alternative to gulp read this comprehensive article @ css-tricks.com especially read about grouping tasks.
package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions. "sass": "node-sass -w sass/ -o css/"
to scripts
in package.json
file. It should look something like this:"scripts": {
"test" : "bla bla bla",
"sass": "node-sass -w sass/ -o css/"
}
$ npm run sass
will compile your files.$ npm install -g gulp
installs Gulp globally.package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions.$ npm install --save-dev gulp
installs Gulp locally. --save-dev
adds gulp
to devDependencies
in package.json
.$ npm install gulp-sass --save-dev
installs gulp-sass locally.gulpfile.js
file in your project root folder with this content:'use strict';
var gulp = require('gulp');
A basic example to transpile
Add this code to your gulpfile.js:
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
$ gulp sass
runs the above task which compiles .scss file(s) in the sass
folder and generates .css file(s) in the css
folder.
To make life easier, let's add a watch so we don't have to compile it manually. Add this code to your gulpfile.js
:
gulp.task('sass:watch', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});
All is set now! Just run the watch task:
$ gulp sass:watch
As the name of node-sass implies, you can write your own node.js scripts for transpiling. If you are curious, check out node-sass project page.
Libsass is a library that needs to be built by an implementer such as sassC or in our case node-sass. Node-sass contains a built version of libsass which it uses by default. If the build file doesn't work on your machine, it tries to build libsass for your machine. This process requires Python 2.7.x (3.x doesn't work as of today). In addition:
LibSass requires GCC 4.6+ or Clang/LLVM. If your OS is older, this version may not compile. On Windows, you need MinGW with GCC 4.6+ or VS 2013 Update 4+. It is also possible to build LibSass with Clang/LLVM on Windows.
$("#yourbuttonid").click(function(){ document.location = "<%= Url.Action("Youraction") %>";})
There can be 2 issues :=
1. Your are trying the command in machine that does not support apt-get command
because apt-get is suitable for Linux based Ubuntu machines; for MAC, try
apt-get equivalent such as Brew
2. The other issue can be that your installation was not completed properly So
Re-install Ubuntu from a Live CD or USB.
The long version would be a waste of your time: your system will never
be clean, but if you insist you could try:
==> Copying everything (missing) except for the /home folder from the Live
CD/USB to your HDD.
OR
==> Do a re-install/repair over the broken system again with the Live
CD / USB stick.
OR
==> Download the deb file for apt-get and install as explained on above posts.
I would definitely go for a fresh new install as there are so many things to
do and so little time.
From the Jenkins wiki:
The JVM launch parameters of these Windows services are controlled by an XML file jenkins.xml and jenkins-slave.xml respectively. These files can be found in $JENKINS_HOME and in the slave root directory respectively, after you've install them as Windows services.
The file format should be self-explanatory. Tweak the arguments for example to give JVM a bigger memory.
https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+as+a+Windows+service
In Python, "privacy" depends on "consenting adults'" levels of agreement - you can't force it (any more than you can in real life;-). A single leading underscore means you're not supposed to access it "from the outside" -- two leading underscores (w/o trailing underscores) carry the message even more forcefully... but, in the end, it still depends on social convention and consensus: Python's introspection is forceful enough that you can't handcuff every other programmer in the world to respect your wishes.
((Btw, though it's a closely held secret, much the same holds for C++: with most compilers, a simple #define private public
line before #include
ing your .h
file is all it takes for wily coders to make hash of your "privacy"...!-))
Example of uppercasedFirstCharacter
convenience property in Swift3 and Swift4.
Property uppercasedFirstCharacterNew
demonstrates how to use String slicing subscript in Swift4.
extension String {
public var uppercasedFirstCharacterOld: String {
if characters.count > 0 {
let splitIndex = index(after: startIndex)
let firstCharacter = substring(to: splitIndex).uppercased()
let sentence = substring(from: splitIndex)
return firstCharacter + sentence
} else {
return self
}
}
public var uppercasedFirstCharacterNew: String {
if characters.count > 0 {
let splitIndex = index(after: startIndex)
let firstCharacter = self[..<splitIndex].uppercased()
let sentence = self[splitIndex...]
return firstCharacter + sentence
} else {
return self
}
}
}
let lorem = "lorem".uppercasedFirstCharacterOld
print(lorem) // Prints "Lorem"
let ipsum = "ipsum".uppercasedFirstCharacterNew
print(ipsum) // Prints "Ipsum"
Subscribing to the IUS Community Project Repository
cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh
Run the script:
sudo bash setup-ius.sh
Upgrading mod_php with Apache
This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.
Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.
sudo yum remove php-cli mod_php php-common
Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.
sudo yum install mod_php70u php70u-cli php70u-mysqlnd
Finally, restart Apache to load the new version of mod_php:
sudo apachectl restart
You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:
systemctl status httpd
Why do you want to generate all the sql by hand? Have you looked at an ORM like Hibernate Depending on your project it will probably do at least 95% of what you need, do it in a cleaner way then raw SQL, and if you need to get the last bit of performance you can create the SQL queries that need to be hand tuned.
We can create a custom DropDown class for this and add a method as:
async selectSingleValue(value: string) {
await this.element.element(by.xpath('.//option[normalize-space(.)=\'' + value + '\']')).click();
}
Also, to verify what value is currently selected, we can have:
async getSelectedValues() {
return await this.element.$('option:checked').getText();
}
If you want to display 24 hours format use:
SELECT FORMAT(GETDATE(),'HH:mm')
and to display 12 hours format use:
SELECT FORMAT(GETDATE(),'hh:mm')
Array.prototype.slice will do the work as well.
const result = Array.prototype.slice.call("Hello world!");_x000D_
console.log(result);
_x000D_
This is how you do it in your $(document).ready()
function with FontAwesome Icons:
$( ".owl-prev").html('<i class="fa fa-chevron-left"></i>');
$( ".owl-next").html('<i class="fa fa-chevron-right"></i>');
There is also some more detail on the use of <mvc:annotation-driven />
in the Spring docs. In a nutshell, <mvc:annotation-driven />
gives you greater control over the inner workings of Spring MVC. You don't need to use it unless you need one or more of the features outlined in the aforementioned section of the docs.
Also, there are other "annotation-driven" tags available to provide additional functionality in other Spring modules. For example, <transaction:annotation-driven />
enables the use of the @Transaction annotation, <task:annotation-driven />
is required for @Scheduled et al...
You can use the dig/host command to look up the MX records to see which mail server is handling mails for this domain.
On Linux you can do it as following for example:
$ host google.com
google.com has address 74.125.127.100
google.com has address 74.125.67.100
google.com has address 74.125.45.100
google.com mail is handled by 10 google.com.s9a2.psmtp.com.
google.com mail is handled by 10 smtp2.google.com.
google.com mail is handled by 10 google.com.s9a1.psmtp.com.
google.com mail is handled by 100 google.com.s9b2.psmtp.com.
google.com mail is handled by 10 smtp1.google.com.
google.com mail is handled by 100 google.com.s9b1.psmtp.com.
(as you can see, google has quite a lot of mail servers)
If you are working with windows, you might use nslookup (?) or try some web tool (e.g. that one) to display the same information.
Although that will only tell you the mail server for that domain. All other settings which are required can't be gathered that way. You might have to ask the provider.
Its not recommended to overwrite bootstrap file, just in your local style.css use
body{background: your color !important;
here !important declaration overwrite bootstrap value.
As mentioned here, Dispatcher.Invoke
could freeze the UI. Should use Dispatcher.BeginInvoke
instead.
Here is a handy extension class to simplify the checking and calling dispatcher invocation.
Sample usage: (call from WPF window)
this Dispatcher.InvokeIfRequired(new Action(() =>
{
logTextbox.AppendText(message);
logTextbox.ScrollToEnd();
}));
Extension class:
using System;
using System.Windows.Threading;
namespace WpfUtility
{
public static class DispatcherExtension
{
public static void InvokeIfRequired(this Dispatcher dispatcher, Action action)
{
if (dispatcher == null)
{
return;
}
if (!dispatcher.CheckAccess())
{
dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);
return;
}
action();
}
}
}
you could use look-ahead assertion for this:
^(?=.*\d).+$
Like this?
$string = 'FirstPart SecondPart'
$a,$b = $string.split(' ')
$a
$b
As @Hesham Eraqi suggested, it worked for me in this way (transfering from Ubuntu to Windows (I tried to add a comment in that answer but because of reputation, I couldn't)):
pscp -v -r -P 53670 [email protected]:/data/genetic_map/sample/P2_283/* \\Desktop-mojbd3n\d\cc_01-1940_data\
where:
-v
: show verbose messages.
-r
: copy directories recursively.
-P
: connect to specified port.
53670
: the port number to connect the Ubuntu server.
\\Desktop-mojbd3n\d\genetic_map_data\
: I needed to transfer to an external HDD, thus I had to give permissions of sharing to this device.
The terms "background page", "popup", "content script" are still confusing you; I strongly suggest a more in-depth look at the Google Chrome Extensions Documentation.
Regarding your question if content scripts or background pages are the way to go:
Content scripts: Definitely
Content scripts are the only component of an extension that has access to the web-page's DOM.
Background page / Popup: Maybe (probably max. 1 of the two)
You may need to have the content script pass the DOM content to either a background page or the popup for further processing.
Let me repeat that I strongly recommend a more careful study of the available documentation!
That said, here is a sample extension that retrieves the DOM content on StackOverflow pages and sends it to the background page, which in turn prints it in the console:
background.js:
// Regex-pattern to check URLs against.
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;
// A function to use as callback
function doStuffWithDom(domContent) {
console.log('I received the following DOM content:\n' + domContent);
}
// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
// ...check the URL of the active tab against our pattern and...
if (urlRegex.test(tab.url)) {
// ...if it matches, send a message specifying a callback too
chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
}
});
content.js:
// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
// If the received message has the expected format...
if (msg.text === 'report_back') {
// Call the specified callback, passing
// the web-page's DOM content as argument
sendResponse(document.all[0].outerHTML);
}
});
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
...
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.stackoverflow.com/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Test Extension"
},
"permissions": ["activeTab"]
}
If I remember correctly, this is the default property for controls.
Can you try by going into Design-View for the admin_reasons that contains the specified Control, then changing the control's Modifiers property to Public or Internal.
This was totally my bad.
I was using standard node http.request on a part of the code which should be sending requests to only http adresses. Seems like the db had a single https address which was queried with a random interval.
Simply, I was trying to send a http request to https.
Here i post my code, after i have pushed myself for one working day to find this solution.
Function to get the last saved record :
private function getLastId($query) {
$conn = $this->getDoctrine()->getConnection();
$stmt = $conn->prepare($query);
$stmt->execute();
$lastId = $stmt->fetch()['id'];
return $lastId;
}
Another Function which call the above function
private function clientNum() {
$lastId = $this->getLastId("SELECT id FROM client ORDER BY id DESC LIMIT 1");
$noClient = 'C' . sprintf("%06d", $lastId + 1); // C000002 if the last record ID is 1
return $noClient;
}
You could put an application.properties file in your test/resources folder. There you set
spring.profiles.active=test
This is kind of a default test profile while running tests.
You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button
, but also for other widgets and non-gui objects such as StringVar
.
Quick fix: add the frame new
as the first argument to your Button
in Demo2
.
Possibly better: Currently you have Demo2
inheriting from tk.Frame
but I think this makes more sense if you change Demo2
to be something like this,
class Demo2(tk.Toplevel):
def __init__(self):
tk.Toplevel.__init__(self)
self.title("Demo 2")
self.button = tk.Button(self, text="Button 2", # specified self as master
width=25, command=self.close_window)
self.button.pack()
def close_window(self):
self.destroy()
Just as a suggestion, you should only import tkinter
once. Pick one of your first two import statements.
Typically you add a class selector to the :not()
pseudo-class like so:
:not(.printable) {
/* Styles */
}
:not([attribute]) {
/* Styles */
}
But if you need better browser support (IE8 and older don't support :not()
), you're probably better off creating style rules for elements that do have the "printable" class. If even that isn't feasible despite what you say about your actual markup, you may have to work your markup around that limitation.
Keep in mind that, depending on the properties you're setting in this rule, some of them may either be inherited by descendants that are .printable
, or otherwise affect them one way or another. For example, although display
is not inherited, setting display: none
on a :not(.printable)
will prevent it and all of its descendants from displaying, since it removes the element and its subtree from layout completely. You can often get around this by using visibility: hidden
instead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did. In short, just be careful.
TL;DR; Are you even on the correct repository?
My story is bit funny but I thought it can happen with someone who might be having a similar scenario so sharing it here.
Actually on my machine, I had two separate git repositories repo1
and repo2
configured in the same root directory named source
. These two repositories are essentially the repositories of two products I work off and on in my company. Now the thing is that as a standard guideline, the directory structure of source code of all the products is exactly the same in my company.
So without realizing I modified an exactly same named file in repo2
which I was supposed to change in repo1
. So, I just kept running command git status
on repo1
and it kept giving the same message
On branch master
nothing to commit, working directory clean
for half an hour. Then colleague of mine observed it as independent pair of eyes and brought this thing to my notice that I was in wrong but very similar looking repository. The moment I switched to repo1
Git started noticing the changed files.
Not so common case. But you never know!
You can use System.IO.Directory.GetParent()
to retrieve the parent directory of a given directory.
// pop back stack all the way
final FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
int entryCount = fm.getBackStackEntryCount();
while (entryCount-- > 0) {
fm.popBackStack();
}
Swift 4:
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(deviceRotated), name: UIDevice.orientationDidChangeNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
}
@objc func deviceRotated(){
if UIDevice.current.orientation.isLandscape {
//Code here
} else {
//Code here
}
}
A lot of answers dont help when needing to detect across various view controllers. This one does the trick.
In my case, it goes well after I installed CMake in my system:)
sudo pacman -S cmake
for manjaro operating system.
Also if you want to save some money you don't must buy a Mac. There is other ways how to do it:
1.) You can use practically any OS to run latest MacOS in virtual machine (look at YouTube). I am using this method really long time without any problems on windows with VMWare.
2.) Hackintosh. Install MacOS to your PC. You must have compatible components, but if you have, this is the best way, because you eliminate the lags in VM... I am using this in this time. Perfect. On my laptop, but please don't tell this to Apple, because practically this is illegal
3.) If you are making simple apps with minimum UI, you can use Theos. Also with Theos you can create cydia tweaks. Only one problem: codesign. If you want to publish app on App Store you still must have MacOS, but if you want to make app in home you can use CydiaImpactor to sign the apps with Apple ID.
I used all of this ways and all is working. By my VM is best solution if you don't want to spend lot of time by installing Hackintosh.
For me the error was:
Error: unexpected input in "?"
and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.
EDIT: OP requested an example. Here it goes.
? ~ cat a.R
cat('hello world\n')
? ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f ...cat('hello wo
00000010: 726c 645c 6e27 290a rld\n').
? ~ R -f a.R
R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> cat('hello world\n')
Error: unexpected input in "?"
Execution halted
There is more than one way to do it.
1). A long statement:
>>> def print_something():
print 'This is a really long line,', \
'but we can make it across multiple lines.'
2). Using parenthesis:
>>> def print_something():
print ('Wow, this also works?',
'I never knew!')
3). Using \
again:
>>> x = 10
>>> if x == 10 or x > 0 or \
x < 100:
print 'True'
Quoting PEP8:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.
Thank you for planting a seed, Cel! I've been struggling with this for hours, finally got it. I was counting a text field, oops, calculation failed.
Created 2 helper columns in my raw data, each resulting in 1 if condition met, 0 if not. Then pulled each into a pivot column, mine are called, "Inbd" (for Inbound), "Back", where "Back" is a return to sending facility, so in reality the total is one trip, not 2 trips, i.e., back is a subset of inbound and not every inbd has a back (obviously). Trying to calculate in the pivot table so I can sort on the field the rate of back to inbound for each sending facility.
For my calculated field I used: =IFERROR(IF(Pvt_Back>0,Pvt_Back/Pvt_Inbd,0),0)
So: if we sent back to sending some number of times greater than 0, divide Back/Inbd to give me a rate; if equal to 0, then 0; if Inbd = 0, then 0 to avoid Div/0 error.
Thanks again!! :)
This is how the ORM maps blank
& null
fields for Django 1.8
class Test(models.Model):
charNull = models.CharField(max_length=10, null=True)
charBlank = models.CharField(max_length=10, blank=True)
charNullBlank = models.CharField(max_length=10, null=True, blank=True)
intNull = models.IntegerField(null=True)
intBlank = models.IntegerField(blank=True)
intNullBlank = models.IntegerField(null=True, blank=True)
dateNull = models.DateTimeField(null=True)
dateBlank = models.DateTimeField(blank=True)
dateNullBlank = models.DateTimeField(null=True, blank=True)
The database fields created for PostgreSQL 9.4 are :
CREATE TABLE Test (
id serial NOT NULL,
"charNull" character varying(10),
"charBlank" character varying(10) NOT NULL,
"charNullBlank" character varying(10),
"intNull" integer,
"intBlank" integer NOT NULL,
"intNullBlank" integer,
"dateNull" timestamp with time zone,
"dateBlank" timestamp with time zone NOT NULL,
"dateNullBlank" timestamp with time zone,
CONSTRAINT Test_pkey PRIMARY KEY (id)
)
The database fields created for MySQL 5.6 are :
CREATE TABLE Test (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`charNull` VARCHAR(10) NULL DEFAULT NULL,
`charBlank` VARCHAR(10) NOT NULL,
`charNullBlank` VARCHAR(10) NULL DEFAULT NULL,
`intNull` INT(11) NULL DEFAULT NULL,
`intBlank` INT(11) NOT NULL,
`intNullBlank` INT(11) NULL DEFAULT NULL,
`dateNull` DATETIME NULL DEFAULT NULL,
`dateBlank` DATETIME NOT NULL,
`dateNullBlank` DATETIME NULL DEFAULT NULL
)
This is changed in Java 6 update 18.
Assuming that we have more than 1 GB of physical memory (quite common these days), it's always 1/4th of your physical memory for the server vm.
.container {_x000D_
padding: 10px;_x000D_
}_x000D_
.parent {_x000D_
width: 100%;_x000D_
background: #7b7b7b;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
height: 4px;_x000D_
}_x000D_
.child {_x000D_
color: #fff;_x000D_
background: green;_x000D_
padding: 10px 10px;_x000D_
border-radius: 50%;_x000D_
position: relative;_x000D_
top: -8px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="parent">_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
</div>_x000D_
</div>
_x000D_
I'm posting this in case someone faces the same problem I am facing right now. I've got a Zebra thermal printer, equipped with the ZebraNet print server, which offers a HTML-based user interface for editing multiple settings, seeing the printer's current status, etc. I need to get the status of the printer, which is displayed in one of those html pages, offered by the ZebraNet server and, for example, alert() a message to the user in the browser. This means that I have to get that html page in Javascript first. Although the printer is within the LAN of the user's PC, that Same Origin Policy is still staying firmly in my way. I tried JSONP, but the server returns html and I haven't found a way to modify its functionality (if I could, I would have already set the magic header Access-control-allow-origin: *). So I decided to write a small console app in C#. It has to be run as Admin to work properly, otherwise it trolls :D an exception. Here is some code:
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
//foreach (string s in prefixes)
//{
// listener.Prefixes.Add(s);
//}
listener.Prefixes.Add("http://*:1234/"); // accept connections from everywhere,
//because the printer is accessible only within the LAN (no portforwarding)
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context;
string urlForRequest = "";
HttpWebRequest requestForPage = null;
HttpWebResponse responseForPage = null;
string responseForPageAsString = "";
while (true)
{
context = listener.GetContext();
HttpListenerRequest request = context.Request;
urlForRequest = request.RawUrl.Substring(1, request.RawUrl.Length - 1); // remove the slash, which separates the portNumber from the arg sent
Console.WriteLine(urlForRequest);
//Request for the html page:
requestForPage = (HttpWebRequest)WebRequest.Create(urlForRequest);
responseForPage = (HttpWebResponse)requestForPage.GetResponse();
responseForPageAsString = new StreamReader(responseForPage.GetResponseStream()).ReadToEnd();
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Send back the response.
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseForPageAsString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
response.AddHeader("Access-Control-Allow-Origin", "*"); // the magic header in action ;-D
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
//listener.Stop();
All the user needs to do is run that console app as Admin. I know it is way too ... frustrating and complicated, but it is sort of a workaround to the Domain Policy problem in case you cannot modify the server in any way.
edit: from js I make a simple ajax call:
$.ajax({
type: 'POST',
url: 'http://LAN_IP:1234/http://google.com',
success: function (data) {
console.log("Success: " + data);
},
error: function (e) {
alert("Error: " + e);
console.log("Error: " + e);
}
});
The html of the requested page is returned and stored in the data variable.
Extending Dave Delong's answer.
Swift Version that takes care of iOS 9 and previous versions as well. I have also covered Error handling in this:
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let fetchRequest = NSFetchRequest(entityName: "Car")
if #available(iOS 9.0, *) {
let delete = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try appDelegate.persistentStoreCoordinator.executeRequest(delete, withContext: appDelegate.managedObjectContext)
} catch let error as NSError {
print("Error occured while deleting: \(error)")
}
} else {
// Fallback on earlier versions
let carRequest = NSFetchRequest()
carRequest.entity = NSEntityDescription.entityForName("Cars", inManagedObjectContext: appDelegate.managedObjectContext)
carRequest.includesPropertyValues = false
do {
let cars: NSArray = try appDelegate.managedObjectContext.executeFetchRequest(carRequest)
for car in cars {
appDelegate.managedObjectContext.delete(car)
}
try appDelegate.managedObjectContext.save()
} catch let error as NSError {
print("Error occured while fetching or saving: \(error)")
}
}
git config --global http.postBuffer 524288000
Work in my case - AWS code commit
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
Python 3 includes an improved super() which allows use like this:
super().__init__(args)
Take a look at the FluentEmail library. I've blogged about it here
You have a nice and fluent api for your needs:
Email.FromDefault()
.To("[email protected]")
.Subject("New order has arrived!")
.Body("The order details are…")
.Send();
As Jon Skeet already said, java.util.Date
does not have a time zone. A Date
object represents a number of milliseconds since January 1, 1970, 12:00 AM, UTC. It does not contain time zone information.
When you format a Date object into a string, for example by using SimpleDateFormat
, then you can set the time zone on the DateFormat
object to let it know in which time zone you want to display the date and time:
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
System.out.println("Date and time in Madrid: " + df.format(date));
If you want the local time zone of the computer that your program is running on, use:
df.setTimeZone(TimeZone.getDefault());
json.loads()
takes a JSON encoded string, not a filename. You want to use json.load()
(no s
) instead and pass in an open file object:
with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
data = json.load(jsonfile)
The open()
command produces a file object that json.load()
can then read from, to produce the decoded Python object for you. The with
statement ensures that the file is closed again when done.
The alternative is to read the data yourself and then pass it into json.loads()
.
The function distinct()
in the dplyr
package performs arbitrary duplicate removal, either from specific columns/variables (as in this question) or considering all columns/variables. dplyr
is part of the tidyverse
.
Data and package
library(dplyr)
dat <- data.frame(a = rep(c(1,2),4), b = rep(LETTERS[1:4],2))
Remove rows duplicated in a specific column (e.g., columna
)
Note that .keep_all = TRUE
retains all columns, otherwise only column a
would be retained.
distinct(dat, a, .keep_all = TRUE)
a b
1 1 A
2 2 B
Remove rows that are complete duplicates of other rows:
distinct(dat)
a b
1 1 A
2 2 B
3 1 C
4 2 D
window.location = myUrl;
Anyway, this is not jQuery: it's plain javascript
Is there a command that does?
thread apply all where
Loop through the results and place each one in an array
use mysqli_fetch_all()
to get them all at one time
I'm working on an open-source project called Todoc which analyzes words to produce proper documentation output automatically when saving a file. It respects existing comments and is really fast and fluid.
Redmi/xiaomi user
Go to "Settings" -> "Password & security" -> "Privacy" -> "Special app access" -> "Device admin apps"
and select the account which you want to uninstall.
Or Simply
go to setting -> Then search for Device admin apps -> click and select the account which you want to uninstall.
We use couchdb in production and have since just before the project went under the Apache umbrella.
We use it to store everything that we might otherwise use a dbms, plus all sorts of unstructured data. Personally, I really like how you can just throw all sorts of data into it and use the views to cull what you don't need depending on the situation.
The hardest part was moving away from the dbms mindset. We wrote our own migration utils when the storage format changed just to be safe, so that wasn't really a problem.
We haven't had any negative experiences yet, but then again we haven't had the setup under any kind of huge load. I think things would work pretty well since we have two slave type servers that replicate from a single master server that gets all of the writes. I'm pretty sure that we don't have to do it that way for replication to work correctly, but it's how we set it up in the beginning and it stuck.
This snippet of code helped me to fix browser caching problems:
$("#my_image").on('load', function() {
console.log("image loaded correctly");
}).each(function() {
if($(this).prop('complete')) $(this).load();
});
When the browser cache is disabled, only this code doesn't work:
$("#my_image").on('load', function() {
console.log("image loaded correctly");
})
to make it work you have to add:
.each(function() {
if($(this).prop('complete')) $(this).load();
});
Consider using INTERSECT like this:
SELECT contactid WHERE flag = 'Volunteer'
INTERSECT
SELECT contactid WHERE flag = 'Uploaded'
I think it it the most logistic solution.
I have found an specific approach for solving a similar issue. The idea is pointing the cacert file stored at the system and used by another ssl based applications.
In Debian (I'm not sure if same in other distributions) the certificate files (.pem) are stored at /etc/ssl/certs/
So, this is the code that work for me:
import requests
verify='/etc/ssl/certs/cacert.org.pem'
response = requests.get('https://lists.cacert.org', verify=verify)
For guessing what pem
file choose, I have browse to the url and check which Certificate Authority (CA) has generated the certificate.
EDIT: if you cannot edit the code (because you are running a third app) you can try to add the pem
certificate directly into /usr/local/lib/python2.7/dist-packages/requests/cacert.pem
(e.g. copying it to the end of the file).
An addition to the current marked answer:
Place the addhandler inside the following scope, like so:
<IfModule mod_rewrite.c>
AddHandler application/x-httpd-php71 .php
RewriteEngine On
....
</IfModule>
You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.
hi.sh
echo "Hi There!"
node_program.js
const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
Here, when I run the nodejs file, it will execute the shell file and the output would be:
Run
node node_program.js
output
Hi There!
You can execute any script just by mentioning the shell command or shell script in exec
callback.
Hope this helps! Happy coding :)
You're almost there. Use the following regex (with multi-line option enabled)
\bObject Name:\s+(.*)$
The complete match would be
Object Name: D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log
while the captured group one would contain
D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log
If you want to capture the file path directly use
(?m)(?<=\bObject Name:).*$
Those who updated their device to Android 4.2 Jelly Bean or higher or having a 4.2 JB or higher android powered device, will not found the Developers Options in Settings menu. The Developers Options hide by default on 4.2 jelly bean and later android versions. Follow the below steps to Unhide Developers Options.
Go to Settings>> More/General tab>> About (On Samsung Galaxy S3, Galaxy S4, Galaxy Note 8.0, Galaxy Tab 3 and other galaxy Smartphone and tablet having Android 4.2/4.3 Jelly Bean) OR
Go to Settings>> General>> About (On Samsung Galaxy Note 2, Galaxy Note 3 and some other Galaxy devices having Android 4.3 Jelly Bean or 4.4 KitKat) OR
Go to Settings> About> Software Information> More (On HTC One or other HTC devices having Android 4.2 Jelly Bean or higher) 2. Now Scroll onto Build Number and tap it 7 times repeatedly. A message will appear saying that u are now a developer.
Credit to www.androidofficer.com
I would recommend using a hash instead of a param string:
data = {id: id, name: name}
var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
var constraints = new {httpMethod = new HttpMethodConstraint(HttpMethod.Options)};
config.Routes.IgnoreRoute("OPTIONS", "*pathInfo",constraints);
Maybe a simple bank situation.
class Account {
double balance;
void withdraw(double amount){
balance -= amount;
}
void deposit(double amount){
balance += amount;
}
void transfer(Account from, Account to, double amount){
sync(from);
sync(to);
from.withdraw(amount);
to.deposit(amount);
release(to);
release(from);
}
}
Obviously, should there be two threads which attempt to run transfer(a, b) and transfer(b, a) at the same time, then a deadlock is going to occur because they try to acquire the resources in reverse order.
This code is also great for looking at solutions to the deadlock as well. Hope this helps!
Arrays:
{{#each array}}
{{@index}}: {{this}}
{{/each}}
If you have arrays of objects... you can iterate through the children:
{{#each array}}
//each this = { key: value, key: value, ...}
{{#each this}}
//each key=@key and value=this of child object
{{@key}}: {{this}}
//Or get index number of parent array looping
{{@../index}}
{{/each}}
{{/each}}
Objects:
{{#each object}}
{{@key}}: {{this}}
{{/each}}
If you have nested objects you can access the key
of parent object with
{{@../key}}
The Double
and Float
types have the POSITIVE_INFINITY
constant.
If file really exists and you want to replace it use below code:
string file = "c:\test\SomeFile.txt"
string moveTo = "c:\test\test\SomeFile.txt"
if (File.Exists(moveTo))
{
File.Delete(moveTo);
}
File.Move(file, moveTo);
To copy a sheet to a workbook called TARGET:
Sheets("xyz").Copy After:=Workbooks("TARGET.xlsx").Sheets("abc")
This will put the copied sheet xyz in the TARGET workbook after the sheet abc Obviously if you want to put the sheet in the TARGET workbook before a sheet, replace Before for After in the code.
To create a workbook called TARGET you would first need to add a new workbook and then save it to define the filename:
Application.Workbooks.Add (xlWBATWorksheet)
ActiveWorkbook.SaveAs ("TARGET")
However this may not be ideal for you as it will save the workbook in a default location e.g. My Documents.
Hopefully this will give you something to go on though.
Try this, what i use every time :
function myFunction() {_x000D_
var hash = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789";_x000D_
var random8 = '';_x000D_
for(var i = 0; i < 5; i++){_x000D_
random8 += hash[parseInt(Math.random()*hash.length)];_x000D_
}_x000D_
console.log(random8);_x000D_
document.getElementById("demo").innerHTML = "Your 5 character string ===> "+random8;_x000D_
} _x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>Click the button to genarate 5 character random string .</p>_x000D_
_x000D_
<button onclick="myFunction()">Click me</button>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Depending on who you ask, some people report that executing select count(1) from random_table;
runs faster than select count(*) from random_table
. Others claim they are exactly the same.
This link claims that the speed difference between the 2 is due to a FULL TABLE SCAN vs FAST FULL SCAN.
On a Windows 64 bit machine, echo %programfiles(x86)% does print C:\Program Files (x86)
Swift 3.0
Through a small abstraction https://github.com/daltoniam/swiftHTTP
Example
do {
let opt = try HTTP.GET("https://google.com")
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
print("opt finished: \(response.description)")
//print("data is: \(response.data)") access the response of the data with response.data
}
} catch let error {
print("got an error creating the request: \(error)")
}
Try CSS:
<h2 style="color:#069">Process Report</h2>
If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:
<style type="text/css">
h2 {
color:#069;
}
</style>
In my case, I hadn't agreed to the newest Developer Agreement. Just run Application Loader once, click on [Accept] to agree, then quit the Application Loader and the Upload to App Store should work fine.
To add to Sonz's answer above, following worked for us.
//Instead of
XmlString.Replace("�", "[0x00]");
// use this
XmlString.Replace("\x00", "[0x00]");
You can also use:
@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")
To specify the format of your output in a scenario where you need to use Charset, Type, etc.
I had the same problem but with an other cause. The solution was to deactivate Avira Browser Protection (in german Browser-Schutz). I took the solusion from m2e cannot transfer metadata from nexus, but maven command line can. It can be activated again ones maven has the needed plugin.
You are single quoting your SQL statement which is making the variables text instead of variables.
$sql = "SELECT *
FROM $usertable
WHERE PartNumber = $partid";
set -x
is fine.
Another way to print each executed command is to use trap
with DEBUG
.
Put this line at the beginning of your script :
trap 'echo "# $BASH_COMMAND"' DEBUG
You can find a lot of other trap
usages here.
There are two packages available in the community for this task (both are maintained):
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
It doesn't set the default value because your model isn't bound to the id or name properties, it's bound to each version
object. Try setting the versionID
to one of the objects and it should work, ie $scope.item.versionID = $scope.versions[2];
If you want to set by the id property then you need to add the select as
syntax:
ng-options="version.id as version.name for version in versions"
Had problems even when init.py existed in subfolder and all that was missing was adding 'as' after import
from folder.file import Class as Class
import folder.file as functions
My branch list (only master now)
My tag list (have three tags)
Switch to new branch feature/codec from opus_codec tag
git checkout -b feature/codec opus_codec
The answers are working fine with xls format but, in my case, it didn't work for xlsx format. Thus I added some code here. it works both xls and xlsx format.
I took the sample from the official sample link.
Hope it may help !
function fileReader(oEvent) {
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
var reader = new FileReader();
var result = {};
reader.onload = function (e) {
var data = e.target.result;
data = new Uint8Array(data);
var workbook = XLSX.read(data, {type: 'array'});
console.log(workbook);
var result = {};
workbook.SheetNames.forEach(function (sheetName) {
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1});
if (roa.length) result[sheetName] = roa;
});
// see the result, caution: it works after reader event is done.
console.log(result);
};
reader.readAsArrayBuffer(oFile);
}
// Add your id of "File Input"
$('#fileUpload').change(function(ev) {
// Do something
fileReader(ev);
}
.bash_profile
is loaded for a "login shell". I am not sure what that would be on OS X, but on Linux that is either X11 or a virtual terminal.
.bashrc
is loaded every time you run Bash. That is where you should put stuff you want loaded whenever you open a new Terminal.app window.
I personally put everything in .bashrc
so that I don't have to restart the application for changes to take effect.
I was having issues attaching screenshots to ExtentReports using a relative path to my image file. My current directory when executing is "C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic". Under this, I created the folder ExtentReports for both the report.html and the image.png screenshot as below.
private String className = getClass().getName();
private String outputFolder = "ExtentReports\\";
private String outputFile = className + ".html";
ExtentReports report;
ExtentTest test;
@BeforeMethod
// initialise report variables
report = new ExtentReports(outputFolder + outputFile);
test = report.startTest(className);
// more setup code
@Test
// test method code with log statements
@AfterMethod
// takeScreenShot returns the relative path and filename for the image
String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);
This creates the report and image in the ExtentReports folder, but when the report is opened and the (blank) image inspected, hovering over the image src shows "Could not load the image" src=".\ExtentReports\QXKmoVZMW7.png".
This is solved by prefixing the relative path and filename for the image with the System Property "user.dir". So this works perfectly and the image appears in the html report.
Chris
String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);
Change your server settings to allow file uploads larger than 12 mb and you should be fine. Usually the server settings are set to 5 to 8 mb for file uploads.
After reading all the answers and comments on this question, I thought to do a small experiment.
I generated 50,000 random booleans and called sum
and count
on them.
Here are my results:
>>> a = [bool(random.getrandbits(1)) for x in range(50000)]
>>> len(a)
50000
>>> a.count(False)
24884
>>> a.count(True)
25116
>>> def count_it(a):
... curr = time.time()
... counting = a.count(True)
... print("Count it = " + str(time.time() - curr))
... return counting
...
>>> def sum_it(a):
... curr = time.time()
... counting = sum(a)
... print("Sum it = " + str(time.time() - curr))
... return counting
...
>>> count_it(a)
Count it = 0.00121307373046875
25015
>>> sum_it(a)
Sum it = 0.004102230072021484
25015
Just to be sure, I repeated it several more times:
>>> count_it(a)
Count it = 0.0013530254364013672
25015
>>> count_it(a)
Count it = 0.0014507770538330078
25015
>>> count_it(a)
Count it = 0.0013344287872314453
25015
>>> sum_it(a)
Sum it = 0.003480195999145508
25015
>>> sum_it(a)
Sum it = 0.0035257339477539062
25015
>>> sum_it(a)
Sum it = 0.003350496292114258
25015
>>> sum_it(a)
Sum it = 0.003744363784790039
25015
And as you can see, count
is 3 times faster than sum
. So I would suggest to use count
as I did in count_it
.
Python version: 3.6.7
CPU cores: 4
RAM size: 16 GB
OS: Ubuntu 18.04.1 LTS
As Frank pointed out, you need to use DISTINCT. Also, since you are using composite primary keys (which is perfectly fine, BTW) you need to make sure that you use the whole key in your joins:
SELECT
P.pe_name,
COUNT(DISTINCT O.ord_id) AS num_orders,
COUNT(I.item_id) AS num_items
FROM
People P
INNER JOIN Orders O ON
O.pe_id = P.pe_id
INNER JOIN Items I ON
I.ord_id = O.ord_id AND
I.pe_id = O.pe_id
GROUP BY
P.pe_name
Without I.ord_id = O.ord_id it was joining each item row to every order row for a person.
Let's keep it simple. Loved @digitaldreamer 's answer but it might leave the beginners confused. So, I am going to try and simplify it.
The only HTML comment is <!-- -->
It can be used as a single line comment or double, it is really up to the developer.
So, an HTML comment starts with <!--
and ends with -->
. It is really that simple. You should not use any other format, to avoid any compatibility issue even if the comment format is legit or not.
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
What are disadvantages of the following solution? Seems to be faster and shorter.
var options = {
set0: ['Option 1','Option 2'],
set1: ['First Option','Second Option','Third Option']
};
var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;
long dateTime = DateTime.Now.Ticks;
Console.WriteLine(dateTime);
Console.WriteLine(new DateTime(dateTime));
Console.ReadKey();
CSS selectors perform far better than Xpath and it is well documented in Selenium community. Here are some reasons,
However there are some situations where, you need to use xpath, for example, searching for a parent element or searching element by its text (I wouldn't recommend the later).
You can read blog from Simon here . He also recommends CSS over Xpath.
If you are testing content then do not use selectors that are dependent on the content of the elements. That will be a maintenance nightmare for every locale. Try talking with developers and use techniques that they used to externalize the text in the application, like dictionaries or resource bundles etc. Here is my blog that explains it in detail.
Thanks to @parishodak, here is the link which provides the numbers proving that CSS performance is better
CSS file
.selectDD {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
JS file
$(document).ready(function () {
$("#selectDropdownID").next().children().eq(0).addClass("selectDD");
});
You can proceed as follow:
First, do not use DataOutputStream
unless it’s really necessary. Second:
Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);
Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.
Give vertical-align:top;
in a
& span
. Like this:
a, span{
vertical-align:top;
}
Check this http://jsfiddle.net/TFPx8/10/
It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.
function textbox()_x000D_
{_x000D_
var ctl = document.getElementById('Javascript_example');_x000D_
var startPos = ctl.selectionStart;_x000D_
var endPos = ctl.selectionEnd;_x000D_
alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart
and selectionEnd
.
You can download a custom compiled bootstrap 3, just customize the @modal-backdrop-opacity from:
https://getbootstrap.com/docs/3.4/customize/
Customizing bootstrap 4 requires compiling from source, overriding $modal-backdrop-bg as described in:
https://getbootstrap.com/docs/4.4/getting-started/theming/
In the answers to Bootstrap 4 custom build generator / download there is a NodeJS workflow for compiling Bootstrap 4 from source, alone with some non-official Bootstrap 4 customizers.
Follow this steps:
-Build
-Generate Signed Apk
-Create new
Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)
I had a similar issue/error..
fixed it by moving
apply plugin: 'com.google.gms.google-services'
to the end of app level gradle file.
And updated the version of gms:play-services
and gms:play-services auth
.val()
always works with textarea
elements.
.text()
works sometimes and fails other times! It's not reliable (tested in Chrome 33)
What's best is that .val()
works seamlessly with other form elements too (like input
) whereas .text()
fails.
I adapted one of the above answers from cdhowie as I could not get it to work. This seems to work for me. I suspect it's also possible to do this with the UNIX_TIMESTAMP function been used.
SELECT * FROM your_table
WHERE UNIX_TIMESTAMP(DateVisited) >= UNIX_TIMESTAMP(CAST(NOW() - INTERVAL 1 DAY AS DATE))
AND UNIX_TIMESTAMP(DateVisited) <= UNIX_TIMESTAMP(CAST(NOW() AS DATE));
In a new version of mysql-server recipes above will crush "mysql" database. In old version it works. In new some tables switches to table type INNODB, and by doing so you will damage them. The easiest way is to:
[mysqld]
innodb_file_per_table=1
You're mapping this JSON
{
"id": 2,
"socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
"type": "getDashboard",
"data": {
"workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
},
"reply": true
}
that contains an element named data
that has a JSON object as its value. You are trying to deserialize the element named workstationUuid
from that JSON object into this setter.
@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {
This won't work directly because Jackson sees a JSON_OBJECT, not a String.
Try creating a class Data
public class Data { // the name doesn't matter
@JsonProperty("workstationUuid")
private String workstationUuid;
// getter and setter
}
the switch up your method
@JsonProperty("data")
public void setWorkstation(Data data) {
// use getter to retrieve it
Try this
$('#add_here').text('new-dynamic-text');
Try this:
XmlDocument bodyDoc = new XmlDocument();
bodyDoc.XMLResolver = null;
bodyDoc.Load(body);
Sub Scrape()
Dim Browser As InternetExplorer
Dim Document As htmlDocument
Dim Elements As IHTMLElementCollection
Dim Element As IHTMLElement
Set Browser = New InternetExplorer
Browser.Visible = True
Browser.navigate "http://www.stackoverflow.com"
Do While Browser.Busy And Not Browser.readyState = READYSTATE_COMPLETE
DoEvents
Loop
Set Document = Browser.Document
Set Elements = Document.getElementById("hmenus").getElementsByTagName("li")
For Each Element In Elements
Debug.Print Element.innerText
'Questions
'Tags
'Users
'Badges
'Unanswered
'Ask Question
Next Element
Set Document = Nothing
Set Browser = Nothing
End Sub
No, they're not the same. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution. Which means you can do:
$sth = $db->prepare("SELECT * FROM table WHERE foo = ?");
$sth->execute(array(1));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
$sth->execute(array(2));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
They generally will give you a performance improvement, although not noticeable on a small scale. Read more on prepared statements (MySQL version).
We tried a few applications, both trials of commercial products and freely available ones. Ultimately, it was the trial edition of the Team Test Load Agent software that we tried. It definitely works great and is fairly simple to use. In the long run, it bolstered our argument to move to Team Foundation Server and equip all parts of the department with the appropriate tooling.
The obvious downside, however, is the price.
According to maven's Guide to installing 3rd party JARs, the command is:
mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>
You need indeed the packaging option. This answers the original question.
Now, in your context, you are fighting with a jar provided by Sun. You should read the Coping with Sun JARs page too. There, you'll learn how to help maven to provide you better information about Sun jars location and how to add Java.net Maven 2 repository which contains jta-1.0.1B.jar
. Add this in your settings.xml
(not portable) orpom.xml
(portable):
<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
$cfg['Servers'][$i]['auth_type'] = 'cookie';
should work.
From the manual:
auth_type = 'cookie' prompts for a MySQL username and password in a friendly HTML form. This is also the only way by which one can log in to an arbitrary server (if $cfg['AllowArbitraryServer'] is enabled). Cookie is good for most installations (default in pma 3.1+), it provides security over config and allows multiple users to use the same phpMyAdmin installation. For IIS users, cookie is often easier to configure than http.
I know that the question is very old, but I will leave my implementation here:
char *ft_strdelchr(const char *str,char c)
{
int i;
int j;
char *s;
char *newstr;
i = 0;
j = 0;
// cast to char* to be able to modify, bc the param is const
// you guys can remove this and change the param too
s = (char*)str;
// malloc the new string with the necessary length.
// obs: strcountchr returns int number of c(haracters) inside s(tring)
if (!(newstr = malloc(ft_strlen(s) - ft_strcountchr(s, c) + 1 * sizeof(char))))
return (NULL);
while (s[i])
{
if (s[i] != c)
{
newstr[j] = s[i];
j++;
}
i++;
}
return (newstr);
}
just throw to a new string the characters that are not equal to the character you want to remove.
I'm a bit late, what worked for me was this:
* npm uninstall npm -g
* brew uninstall node
* brew install node
* sudo rm -rf /usr/local/lib/dtrace/node.d
* brew link node (caused error with permissions)
* sudo chmod 777 /usr/local/lib/dtrace/node.d
* brew link node
Everything was successful after this sequence
Using ansible 2.4.1.0 and the following shall work:
[all]
17.26.131.10
17.26.131.11
17.26.131.12
17.26.131.13
17.26.131.14
[all:vars]
ansible_connection=ssh
ansible_user=per
ansible_ssh_pass=per
ansible_sudo_pass=per
And just run the playbook with this inventory as:
ansible-playbook -i inventory copyTest.yml
user: USER
this.user = ({} as USER)
var http = require('http');
var options = {
host: 'localhost',
port: 80,
path: '/broadcast'
};
var requestLoop = setInterval(function(){
http.get (options, function (resp) {
resp.on('data', function (d) {
console.log ('data!', d.toString());
});
resp.on('end', function (d) {
console.log ('Finished !');
});
}).on('error', function (e) {
console.log ('error:', e);
});
}, 10000);
var dns = require('dns'), cache = {};
dns._lookup = dns.lookup;
dns.lookup = function(domain, family, done) {
if (!done) {
done = family;
family = null;
}
var key = domain+family;
if (key in cache) {
var ip = cache[key],
ipv = ip.indexOf('.') !== -1 ? 4 : 6;
return process.nextTick(function() {
done(null, ip, ipv);
});
}
dns._lookup(domain, family, function(err, ip, ipv) {
if (err) return done(err);
cache[key] = ip;
done(null, ip, ipv);
});
};
// Works fine (100%)
You could simply do this
<input [disabled]="true" id="name" type="text">
For DSA keys, use
openssl dsa -pubin -in dsa.pub -modulus -noout
to print the public keys, then
openssl dsa -in dsa.key -modulus -noout
to display the public keys corresponding to a private key, then compare them.
I have added text in ToolBar :
menu_skip.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/action_settings"
android:title="@string/text_skip"
app:showAsAction="never" />
</menu>
MainActivity.java
@Override
boolean onCreateOptionsMenu(Menu menu) {
inflater = getMenuInflater();
inflater.inflate(R.menu.menu_otp_skip, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.menu_item_skip:
Toast.makeText(this, "Skip selected", Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
return true;
}
TL;DR
SQLCMD -S (LOCAL) -E -V 16 -Q "IF(ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS INT),0)<11) RAISERROR('You need SQL 2012 or later!',16,1)"
IF ERRORLEVEL 1 GOTO :ExitFail
This uses SQLCMD (comes with SQL Server) to connect to the local server instance using Windows auth, throw an error if a version check fails and return the @@ERROR
as the command line ERRORLEVEL
if >= 16 (and the second line goes to the :ExitFail
label if the aforementioned ERRORLEVEL
is >= 1).
Watchas, Gotchas & More Info
For SQL 2000+ you can use the SERVERPROPERTY to determine a lot of this info.
While SQL 2008+ supports the ProductMajorVersion
& ProductMinorVersion
properties, ProductVersion
has been around since 2000 (remembering that if a property is not supported the function returns NULL
).
If you are interested in earlier versions you can use the PARSENAME
function to split the ProductVersion
(remembering the "parts" are numbered right to left i.e. PARSENAME('a.b.c', 1)
returns c
).
Also remember that PARSENAME('a.b.c', 4)
returns NULL
, because SQL 2005 and earlier only used 3 parts in the version number!
So for SQL 2008+ you can simply use:
SELECT
SERVERPROPERTY('ProductVersion') AS ProductVersion,
CAST(SERVERPROPERTY('ProductMajorVersion') AS INT) AS ProductMajorVersion,
CAST(SERVERPROPERTY ('ProductMinorVersion') AS INT) AS ProductMinorVersion;
For SQL 2000-2005 you can use:
SELECT
SERVERPROPERTY('ProductVersion') AS ProductVersion,
CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) AS ProductVersion_Major,
CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 2 ELSE 3 END) AS INT) AS ProductVersion_Minor,
CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 1 ELSE 2 END) AS INT) AS ProductVersion_Revision,
CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 0 ELSE 1 END) AS INT) AS ProductVersion_Build;
(the PARSENAME(...,0)
is a hack to improve readability)
So a check for a SQL 2000+ version would be:
IF (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) < 10) -- SQL2008
OR (
(CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) = 10) -- SQL2008
AND (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 2 ELSE 1 END) AS INT) < 5) -- R2 (this may need to be 50)
)
RAISERROR('You need SQL 2008R2 or later!', 16, 1);
This is a lot simpler if you're only only interested in SQL 2008+ because SERVERPROPERTY('ProductMajorVersion')
returns NULL
for earlier versions, so you can use:
IF (ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS INT), 0) < 11) -- SQL2012
RAISERROR('You need SQL 2012 or later!', 16, 1);
And you can use the ProductLevel
and Edition
(or EngineEdition
) properties to determine RTM / SPn / CTPn and Dev / Std / Ent / etc respectively.
SELECT
CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME) AS ProductVersion,
CAST(SERVERPROPERTY('ProductLevel') AS SYSNAME) AS ProductLevel,
CAST(SERVERPROPERTY('Edition') AS SYSNAME) AS Edition,
CAST(SERVERPROPERTY('EngineEdition') AS INT) AS EngineEdition;
FYI the major SQL version numbers are:
And this all works for SQL Azure too!
EDITED: You may also want to check your DB compatibility level since it could be set to a lower compatibility.
IF EXISTS (SELECT * FROM sys.databases WHERE database_id=DB_ID() AND [compatibility_level] < 110)
RAISERROR('Database compatibility level must be SQL2008R2 or later (110)!', 16, 1)
I know this is an old question. This is a neat way I came across if you are on a liunx machine.
import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))
IIF
is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END
. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.
CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.
A simpler way, if you are using .NET 3.5, is to use XDocument
and XmlSchemaSet
validation.
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schemaNamespace, schemaFileName);
XDocument doc = XDocument.Load(filename);
string msg = "";
doc.Validate(schemas, (o, e) => {
msg += e.Message + Environment.NewLine;
});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);
See the MSDN documentation for more assistance.
First of all you have to fetch the remote repository:
git fetch remoteName
Than you can create the new branch and set it up to track the remote branch you want:
git checkout -b newLocalBranch remoteName/remoteBranch
You can also use "git branch --track" instead of "git checkout -b" as max specified.
git branch --track newLocalBranch remoteName/remoteBranch
Use a Border of height 1 and don't set the Width (i.e. Width = Auto, HorizontalAlignment = Stretch, the default)
Define the width as 960px, or whatever you prefer, and you're good to go!
#main {
margin: 0 auto !important;
float: none !important;
text-align: center;
width: 960px;
}
(I couldn't figure this out until I fixed the width, nothing else worked.)
Just add
ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8
into your Dockerfile. (You may need to make sure the locales
package is installed.) Nothing else is needed for the basic operation.
Meanwhile, outside of Ubuntu, locale-gen
doesn’t accept any arguments, that’s why none of the ‘fixes’ using it work e.g. on Debian. Ubuntu have patched locale-gen
to accept a list of locales to generate but the patch at the moment has not been accepted in Debian of anywhere else.
I know this is kind of late but this plugin should work. http://remysharp.com/2009/01/26/element-in-view-event-plugin/
$('p.inview').bind('inview', function (event, visible) {
if (visible) {
$(this).text('You can see me!');
} else {
$(this).text('Hidden again');
}
Try using Joda Time instead of standard java.util.Date classes. Joda Time library has much better API for handling dates.
DateTime dt = new DateTime(); // current time
int month = dt.getMonth(); // gets the current month
int hours = dt.getHourOfDay(); // gets hour of day
See this question for pros and cons of using Joda Time library.
Joda Time may also be included to some future version of Java as a standard component, see JSR-310.
If you must use traditional java.util.Date and java.util.Calendar classes, see their JavaDoc's for help (java.util.Calendar and java.util.Date).
You can use the traditional classes like this to fetch fields from given Date instance.
Date date = new Date(); // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date); // assigns calendar to given date
calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
calendar.get(Calendar.HOUR); // gets hour in 12h format
calendar.get(Calendar.MONTH); // gets month number, NOTE this is zero based!
I tried all of stack overflow and all didn't works. But this works for me:
You can use the Search & Replace feature with this regex ^([\w\d\_\.\s\-]*)$
to find text and the replaced text is "$1"
.
This,
public enum MySingleton {
INSTANCE;
}
has an implicit empty constructor. Make it explicit instead,
public enum MySingleton {
INSTANCE;
private MySingleton() {
System.out.println("Here");
}
}
If you then added another class with a main()
method like
public static void main(String[] args) {
System.out.println(MySingleton.INSTANCE);
}
You would see
Here
INSTANCE
enum
fields are compile time constants, but they are instances of their enum
type. And, they're constructed when the enum type is referenced for the first time.
JRockit Mission Control is becoming Java Mission Control and will be dedicated exclusively to Hotspot. If you are an Oracle customer, you can download the 5.x versions of Java Mission Control from MOS (My Oracle Support). Java Mission Control will eventually be released together with the Oracle JDK. The reason it is not yet generally available is that there are some serious limitations, especially when using the Flight Recorder. However, if you are only interested in using the JMX console, you should be golden!
System properties are set on the Java command line using the -Dpropertyname=value
syntax. They can also be added at runtime
using System.setProperty(String key, String value)
or via the various
System.getProperties().load()
methods.
To get a specific system property you can use System.getProperty(String key)
or System.getProperty(String key, String def)
.
Environment variables are set in the OS, e.g. in Linux export HOME=/Users/myusername
or on Windows SET WINDIR=C:\Windows
etc,
and, unlike properties, may not be set at runtime.
To get a specific environment variable you can use System.getenv(String name)
.
Probably the simplest way is using subplot2grid
, described in Customizing Location of Subplot Using GridSpec.
ax = plt.subplot2grid((2, 2), (0, 0))
is equal to
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])
so bmu's example becomes:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
I think this will meet your requirements:
With local variable type inference you only have to specify the type once:
var values = new int[] { 1, 2, 3 };
Or
int[] values = { 1, 2, 3 }
Swift 5/iOS 13
To change color of title in controller:
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
Just wanted to add my python implementation to the long list of solutions. This non-recursive algorithm has discovery and finished events.
worklist = [root_node]
visited = set()
while worklist:
node = worklist[-1]
if node in visited:
# Node is finished
worklist.pop()
else:
# Node is discovered
visited.add(node)
for child in node.children:
worklist.append(child)
if you're more technically minded, this site is probably what you want: http://www.zytrax.com/tech/survival/ssl.html
warning: the rabbit hole goes deep :).
Here is a general function implementing Henrik's solution on dplyr
0.7.1.
freq_table <- function(x,
group_var,
prop_var) {
group_var <- enquo(group_var)
prop_var <- enquo(prop_var)
x %>%
group_by(!!group_var, !!prop_var) %>%
summarise(n = n()) %>%
mutate(freq = n /sum(n)) %>%
ungroup
}
PROGRESS 4GL (apparently now known as "OpenEdge Advanced Business Language").
PROGRESS is both a language and a database system. The whole language is designed to make it easy to write crappy green-screen data-entry screens. (So start by imagining how well this translates to Windows.) Anything fancier than that, whether pretty screens, program logic, or batch processing... not so much.
I last used version 7, back in the late '90s, so it's vaguely possible that some of this is out-of-date, but I wouldn't bet on it.
Counter
field in the current record in the State
table, you just say State.Counter = State.Counter + 1
. Which isn't so bad, except...Index
, you can refer to it as Index
or as Ind
or even as I
. (Typos can have very interesting results.) And if you want to access a database field, not only can you abbreviate the field name, but you don't even have to qualify it with the table name; they'll guess the table too. For truly frightening results, combine this with:The guessing is the worst. Between the abbreviations and the field-by-default, you could get some nasty stuff if you weren't careful. (Forgot to declare I
as a local variable before using it as a loop variable? No problem, we'll just randomly pick a table, grab its current record, and completely trash an arbitrarily-chosen field whose name starts with I
!)
Then add in the fact that an accidental field-by-default access could change the scope it guessed for your tables, thus breaking some completely unrelated piece of code. Fun, yes?
They also have a reporting system built into the language, but I have apparently repressed all memories of it.
When I got another job working with Netscape LiveWire (an ill-fated attempt at server-side JavaScript) and classic ASP (VBScript), I was in heaven.
Your code actually works on FF, it doesn't work on Chrome.
This works on FF and Chrome.
$(document).ready(function() {
// Solution for disabling the submit temporarily for all the submit buttons.
// Avoids double form submit.
// Doing it directly on the submit click made the form not to submit in Chrome.
// This works in FF and Chrome.
$('form').on('submit', function(e){
//console.log('submit2', e, $(this).find('[clicked=true]'));
var submit = $(this).find('[clicked=true]')[0];
if (!submit.hasAttribute('disabled'))
{
submit.setAttribute('disabled', true);
setTimeout(function(){
submit.removeAttribute('disabled');
}, 1000);
}
submit.removeAttribute('clicked');
e.preventDefault();
});
$('[type=submit]').on('click touchstart', function(){
this.setAttribute('clicked', true);
});
});
</script>
If the culture of the result doesn't matters or we're only talking of integer values, CONVERT
or CAST
will be fine.
However, if the result must match a specific culture, FORMAT
might be the function to go:
DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value) --> 1505.5698
SELECT FORMAT(@value, 'N2', 'en-us') --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de') --> 1.505,57
For more information on FORMAT
see here.
Of course, formatting the result should be a matter of the UI layer of the software.
I know this is a bit old, but instead of looping through the array with a for loop, it would be much easier to use the method <array>.indexOf(<element>[, fromIndex])
It loops through an array, finding and returning the first index of a value. If the value is not contained in the array, it returns -1.
<array>
is the array to look through, <element>
is the value you are looking for, and [fromIndex]
is the index to start from (defaults to 0).
I hope this helps reduce the size of your code!
You can achieve this by setting content mode of image view to UIViewContentModeScaleAspectFill.
Then use following method method to get the resized uiimage object.
- (UIImage*)setProfileImage:(UIImage *)imageToResize onImageView:(UIImageView *)imageView
{
CGFloat width = imageToResize.size.width;
CGFloat height = imageToResize.size.height;
float scaleFactor;
if(width > height)
{
scaleFactor = imageView.frame.size.height / height;
}
else
{
scaleFactor = imageView.frame.size.width / width;
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), NO, 0.0);
[imageToResize drawInRect:CGRectMake(0, 0, width * scaleFactor, height * scaleFactor)];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resizedImage;
}
Edited Here (Swift Version)
func setProfileImage(imageToResize: UIImage, onImageView: UIImageView) -> UIImage
{
let width = imageToResize.size.width
let height = imageToResize.size.height
var scaleFactor: CGFloat
if(width > height)
{
scaleFactor = onImageView.frame.size.height / height;
}
else
{
scaleFactor = onImageView.frame.size.width / width;
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), false, 0.0)
imageToResize.drawInRect(CGRectMake(0, 0, width * scaleFactor, height * scaleFactor))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage;
}
You can have a mix of PHP and HTML in your PHP files... just do something like this...
<?php
$string = htmlentities("Résumé");
?>
<html>
<head></head>
<body>
<p><?= $string ?></p>
</body>
</html>
That should output Résumé
just how you want it to.
If you don't have short tags enabled, replace the <?= $string ?>
with <?php echo $string; ?>
To make a translation in the controller you could use $translate
service:
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope
event: $translateChangeSuccess
and do the same translation there:
$rootScope.$on('$translateChangeSuccess', function () {
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
});
Of course, you could encapsulate the $translate
service in a method and call it in the controller and in the $translateChangeSucess
listener.
The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).
This will force the DefaultWebProxy
to use default credentials, similar effect as done through UseDefaultCredentials = true
.
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
Hence all newly created WebRequest
instances will use default proxy which has been configured to use proxy's default credentials.
This is because width
when provided a %
doesn't account for padding
/margin
s. You will need to reduce the amount to possibly 24%
or 24.5%
. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.
Iterator is super class of ListIterator.
Here are the differences between them:
iterator
you can move only forward, but with ListIterator
you can move backword also while reading the elements.ListIterator
you can obtain the index at any point while traversing, which is not possible with iterator
s.iterator
you can check only for next element available or not, but in listiterator
you can check previous and next elements.listiterator
you can add new element at any point of time, while traversing. Not possible with iterator
.listiterator
you can modify an element while traversing, which is not possible with iterator
.Iterator look and feel:
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional-->use only once with next(),
dont use it when u use for:each
}
ListIterator look and feel:
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove(); //optional
void set(E e); //optional
void add(E e); //optional
}
I think a 2 step approach is best, because c 2-d arrays are just and array of arrays. The first step is to allocate a single array, then loop through it allocating arrays for each column as you go. This article gives good detail.
You can use py2exe as already answered and use Cython to convert your key .py
files in .pyc
, C compiled files, like .dll
in Windows and .so
on Linux.
It is much harder to revert than common .pyo
and .pyc
files (and also gain in performance!).
In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:
>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)
The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)
The type of a complex number is complex
, and you can use the type as a constructor if you prefer:
>>> complex(2,3)
(2+3j)
A complex number has some built-in accessors:
>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)
Several built-in functions support complex numbers:
>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)
The standard module cmath
has more functions that handle complex numbers:
>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)
That is partly possible (for max 2 devices), because device can be connected only to one other device same time. Better solution in your case will be create an TCP server which sends informations to other devices - but that, of course, requires internet connection. Read also about Samsung Chord API - it provides functions which you need, but then every devices have to be connected to one and the same Wi-Fi network
To add on to chepner's answer for Python 3.0 you can alternatively do:
x = lambda x: list(map(print, x))
Of course this is only if you have the means of using Python > 3 in the future... Looks a bit cleaner in my opinion, but it also has a weird return value, but you're probably discarding it anyway.
I'll just leave this here for reference.
The use
keyword is for aliasing in PHP and it does not import the classes. This really helps
1) When you have classes with same name in different namespaces
2) Avoid using really long class name over and over again.
Get a handle to the root ThreadGroup
, like this:
ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
ThreadGroup parentGroup;
while ((parentGroup = rootGroup.getParent()) != null) {
rootGroup = parentGroup;
}
Now, call the enumerate()
function on the root group repeatedly. The second argument lets you get all threads, recursively:
Thread[] threads = new Thread[rootGroup.activeCount()];
while (rootGroup.enumerate(threads, true ) == threads.length) {
threads = new Thread[threads.length * 2];
}
Note how we call enumerate() repeatedly until the array is large enough to contain all entries.
Never mind got the way to do it.
def plotGraph(X,Y):
fignum = random.randint(0,sys.maxint)
fig = plt.figure(fignum)
### Plotting arrangements ###
return fig
------ plotting module ------
----- mainModule ----
import matplotlib.pyplot as plt
### tempDLStats, tempDLlabels are the argument
plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
plt.show()
plot1.savefig('plot1.png')
plot2.savefig('plot2.png')
plot3.savefig('plot3.png')
----- mainModule -----
string stringToDecrypt = CypherText.Replace(" ", "+");
int len = stringToDecrypt.Length;
byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt);
Simple way to compare time is :
$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
// your code
}
Adding my localhost on Valid OAuth redirect URIs at https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/ solved the problem!
And pay attention for one detail here:
In this case http://localhost:3000 is not the same of http://0.0.0.0:3000 or http://127.0.0.1:3000
Make sure you are using exactly the running url of you sandbox server. I spend some time to discover that...
If you don't wish to use 3rd party classes then the following is how you set the post body...
NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
delegate:self];
Simply append your key/value pair to the post string
Simply do this:
def which_index(self):
return [
i for i in range(len(self.states))
if self.states[i] == True
]
If you only want to commit all the changes in one commit as if you typed yourself, --squash will do too
$ git merge --squash v1.0
$ git commit
You'll need to use javascript/css to fake it.
Try here for an example: http://www.dynamicdrive.com/forums/archive/index.php/t-26322.html
In page header, add
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-sacle=1, maximum-scale=1, user-scalable=no">
In page stylesheet, add
html, body {
overflow-x: hidden;
overflow-y: hidden;
}
It is both html and body!
I would recommend you using the Conditional Attribute!
Update: 3.5 years later
You can use #if
like this (example copied from MSDN):
// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass
{
static void Main()
{
#if (DEBUG && !VC_V7)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
Console.WriteLine("DEBUG and VC_V7 are defined");
#else
Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
}
}
Only useful for excluding parts of methods.
If you use #if
to exclude some method from compilation then you will have to exclude from compilation all pieces of code which call that method as well (sometimes you may load some classes at runtime and you cannot find the caller with "Find all references"). Otherwise there will be errors.
If you use conditional compilation on the other hand you can still leave all pieces of code that call the method. All parameters will still be validated by the compiler. The method just won't be called at runtime. I think that it is way better to hide the method just once and not have to remove all the code that calls it as well. You are not allowed to use the conditional attribute on methods which return value - only on void methods. But I don't think this is a big limitation because if you use #if
with a method that returns a value you have to hide all pieces of code that call it too.
Here is an example:
// calling Class1.ConditionalMethod() will be ignored at runtime // unless the DEBUG constant is defined using System.Diagnostics; class Class1 { [Conditional("DEBUG")] public static void ConditionalMethod() { Console.WriteLine("Executed Class1.ConditionalMethod"); } }
Summary:
I would use #ifdef
in C++ but with C#/VB I would use Conditional attribute. This way you hide the method definition without having to hide the pieces of code that call it. The calling code is still compiled and validated by the compiler, the method is not called at runtime though.
You may want to use #if
to avoid dependencies because with Conditional attribute your code is still compiled.
I had the same issue, and it appears Gidon's answer has one tiny flaw: it generates a relative URL, which cannot be sent by mail.
My solution looks like this:
string link = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("ResetPassword", "Account", new { key = randomString });
This way, a full URL is generated, and it works even if the application is several levels deep on the hosting server, and uses a port other than 80.
EDIT: I found this useful as well.
In case you know the password of that user, or you would like to guess it, do the following:
connect user/password
If this command connects successufully, you will see the message "connected", otherwise you'd see an error message. If you are then successufull logging, that means that you know the password. In that case, just do:
alter user NAME_OF_THE_USER identified by OLD_PASSWORD;
and this will reset the password to the same password as before and also reset the account_status for that user.
Assuming you know the position and the length of the substring:
char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);
You could achieve the same thing by copying the substring to another memory destination, but it's not reasonable since you already have it in memory.
This is a good example of avoiding unnecessary copying by using pointers.
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
The code is correct so I'm guessing that you are using an older JDK. The javadoc for that method says it has been there since 1.6. At the command line type:
java -version
I'm guessing that you are not running 1.6
I just looked into my code. In one application, I just add the controls, but without specifying the index, and when done, I just loop through the row styles and set the size type to AutoSize. So just adding them without specifying the indices seems to add the rows as intended (provided the GrowStyle is set to AddRows).
In another application, I clear the controls and set the RowCount property to the needed value. This does not add the RowStyles. Then I add my controls, this time specifying the indices, and add a new RowStyle (RowStyles.Add(new RowStyle(...)
) and this also works.
So, pick one of these methods, they both work. I remember the headaches the table layout panel caused me.
Element is not supported in IE8 out of the box you have to do some work to make IE8 accept custom tags.
One advantage of using an attribute over an element is that you can apply multiple directives to the same DOM node. This is particularly handy for things like form controls where you can highlight, disable, or add labels etc. with additional attributes without having to wrap the element in a bunch of tags.
By using pandas we can read excel easily.
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
DataF=pd.read_excel("Test.xlsx",sheet_name='Sheet1')
print("Column headings:")
print(DataF.columns)
Test at :https://repl.it Reference: https://pythonspot.com/read-excel-with-pandas/