Add &wmode=transparent
to the url and you're done, tested.
I use that technique in my own wordpress plugin YouTube shortcode
Check its source code if you encounter any issue.
Another solution that may help someone. There are 2 EditText which change instead of each other after editing. By default, it led to cyclicity.
use variable:
Boolean uahEdited = false;
Boolean usdEdited = false;
add TextWatcher
uahEdit = findViewById(R.id.uahEdit);
usdEdit = findViewById(R.id.usdEdit);
uahEdit.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (!usdEdited) {
uahEdited = true;
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String tmp = uahEdit.getText().toString();
if(!tmp.isEmpty() && uahEdited) {
uah = Double.valueOf(tmp);
usd = uah / 27;
usdEdit.setText(String.valueOf(usd));
} else if (tmp.isEmpty()) {
usdEdit.getText().clear();
}
}
@Override
public void afterTextChanged(Editable s) {
uahEdited = false;
}
});
usdEdit.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (!uahEdited) {
usdEdited = true;
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String tmp = usdEdit.getText().toString();
if (!tmp.isEmpty() && usdEdited) {
usd = Double.valueOf(tmp);
uah = usd * 27;
uahEdit.setText(String.valueOf(uah));
} else if (tmp.isEmpty()) {
uahEdit.getText().clear();
}
}
@Override
public void afterTextChanged(Editable s) {
usdEdited = false;
}
});
Don't criticize too much. I am a novice developer
I faced same issue. Plus while I was trying to resolve from picking solutions from other devs, I faced few more issues like one listed here.
Angular 9 ng new myapp gives error The Schematic workflow failed
https://medium.com/@codewin/npm-warn-deprecated-request-2-88-2-b6da20766fd7
Finally after trying cache clean and verify and reinstall node of different versions and npm update, nvm and many other solution like set proxy and better internet connection, I still could not arrive to a resolve.
What worked for me is : I browsed a bit inside my C:\Users--- folder, I found package-lock.json and .npmrc files. I deleted those and reinstalled angular and tried. npm install and uninstall of different modules started working.
This is a solution that saves the profile directory for Firefox (similar to the user-data-dir
(user data directory) in Chrome) (it involves manually copying the directory around. I haven't been able to find another way):
It was tested on Linux.
Short version:
driver.execute_script("window.close()")
time.sleep(0.5)
currentProfilePath = driver.capabilities["moz:profile"]
profileStoragePath = "/tmp/abc"
shutil.copytree(currentProfilePath, profileStoragePath,
ignore_dangling_symlinks=True
)
driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
firefox_profile=FirefoxProfile(profileStoragePath)
)
Long version (with demonstration that it works and a lot of explanation -- see comments in the code)
The code uses localStorage
for demonstration, but it works with cookies as well.
#initial imports
from selenium.webdriver import Firefox, FirefoxProfile
import shutil
import os.path
import time
# Create a new profile
driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
# * I'm using this particular version. If yours is
# named "geckodriver" and placed in system PATH
# then this is not necessary
)
# Navigate to an arbitrary page and set some local storage
driver.get("https://DuckDuckGo.com")
assert driver.execute_script(r"""{
const tmp = localStorage.a; localStorage.a="1";
return [tmp, localStorage.a]
}""") == [None, "1"]
# Make sure that the browser writes the data to profile directory.
# Choose one of the below methods
if 0:
# Wait for some time for Firefox to flush the local storage to disk.
# It's a long time. I tried 3 seconds and it doesn't work.
time.sleep(10)
elif 1:
# Alternatively:
driver.execute_script("window.close()")
# NOTE: It might not work if there are multiple windows!
# Wait for a bit for the browser to clean up
# (shutil.copytree might throw some weird error if the source directory changes while copying)
time.sleep(0.5)
else:
pass
# I haven't been able to find any other, more elegant way.
#`close()` and `quit()` both delete the profile directory
# Copy the profile directory (must be done BEFORE driver.quit()!)
currentProfilePath = driver.capabilities["moz:profile"]
assert os.path.isdir(currentProfilePath)
profileStoragePath = "/tmp/abc"
try:
shutil.rmtree(profileStoragePath)
except FileNotFoundError:
pass
shutil.copytree(currentProfilePath, profileStoragePath,
ignore_dangling_symlinks=True # There's a lock file in the
# profile directory that symlinks
# to some IP address + port
)
driver.quit()
assert not os.path.isdir(currentProfilePath)
# Selenium cleans up properly if driver.quit() is called,
# but not necessarily if the object is destructed
# Now reopen it with the old profile
driver=Firefox(executable_path="geckodriver-v0.28.0-linux64",
firefox_profile=FirefoxProfile(profileStoragePath)
)
# Note that the profile directory is **copied** -- see FirefoxProfile documentation
assert driver.profile.path!=profileStoragePath
assert driver.capabilities["moz:profile"]!=profileStoragePath
# Confusingly...
assert driver.profile.path!=driver.capabilities["moz:profile"]
# And only the latter is updated.
# To save it again, use the same method as previously mentioned
# Check the data is still there
driver.get("https://DuckDuckGo.com")
data = driver.execute_script(r"""return localStorage.a""")
assert data=="1", data
driver.quit()
assert not os.path.isdir(driver.capabilities["moz:profile"])
assert not os.path.isdir(driver.profile.path)
What doesn't work:
Firefox(capabilities={"moz:profile": "/path/to/directory"})
-- the driver will not be able to connect.options=Options(); options.add_argument("profile"); options.add_argument("/path/to/directory"); Firefox(options=options)
-- same as above.At first you need to understand first, that Tomcat is a Java application. So, to see which java version Tomcat is using, you can just simply find the script file from which Tomcat is started, usually catalina.sh.
Inside this file, you will get something like below:
catalina.sh:# JAVA_HOME Must point at your Java Development Kit installation.
catalina.sh:# Defaults to JAVA_HOME if empty.
catalina.sh: [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
catalina.sh: JAVA_HOME=`cygpath --absolute --windows "$JAVA_HOME"`
catalina.sh: echo "Using JAVA_HOME: $JAVA_HOME"
By default, JAVA_HOME should be empty, which mean it will use the default version of java, or you can test with: echo $JAVA_HOME
And then use "java -version" to see which version you default java is.
And vice versa by setting this property: JAVA_HOME, you can configure which Java version to use when starting Tomcat.
Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:
.no-overflow {
white-space: no-wrap;
text-overflow: ellipsis;
overflow: hidden;
}
and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.
When you have to reload the file, you can erase the value of input. Next time you add a file, 'on change' event will trigger.
document.getElementById('my_input').value = null;
// ^ that just erase the file path but do the trick
Try Adminer. The whole application is in one PHP file, which means that the deployment is as easy as it can get. It's more powerful than phpMyAdmin; it can edit views, procedures, triggers, etc.
Adminer is also a universal tool, it can connect to MySQL, PostgreSQL, SQLite, MS SQL, Oracle, SimpleDB, Elasticsearch and MongoDB.
You should definitely give it a try.
You can install on Ubuntu with sudo apt-get install adminer
or you can also download the latest version from adminer.org
This is the best .htaccess
I have used in my actual website:
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
##Tweaks##
Header set X-Frame-Options SAMEORIGIN
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##
<IfModule mod_headers.c>
Header set Connection keep-alive
<filesmatch "\.(ico|flv|gif|swf|eot|woff|otf|ttf|svg)$">
Header set Cache-Control "max-age=2592000, public"
</filesmatch>
<filesmatch "\.(jpg|jpeg|png)$">
Header set Cache-Control "max-age=1209600, public"
</filesmatch>
# css and js should use private for proxy caching https://developers.google.com/speed/docs/best-practices/caching#LeverageProxyCaching
<filesmatch "\.(css)$">
Header set Cache-Control "max-age=31536000, private"
</filesmatch>
<filesmatch "\.(js)$">
Header set Cache-Control "max-age=1209600, private"
</filesmatch>
<filesMatch "\.(x?html?|php)$">
Header set Cache-Control "max-age=600, private, must-revalidate"
</filesMatch>
</IfModule>
Here is the latest example of how to do it. From react docs, plus auto-binding "fat-arrow" method syntax.
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
}
handleChange = (event) =>
this.setState({value: event.target.value});
handleSubmit = (event) => {
alert('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
I am partial to ES2015 arrow function for finding values in an array
const result = data.find(x=> x.TEST1 === '46');
Checkout Array.prototype.find() HERE
Refreshing my memory on setting position, I'm coming to this so late I don't know if anyone else will see it, but --
I don't like setting position using css()
, though often it's fine. I think the best bet is to use jQuery UI's position()
setter as noted by xdazz. However if jQuery UI is, for some reason, not an option (yet jQuery is), I prefer this:
const leftOffset = 200;
const topOffset = 200;
let $div = $("#mydiv");
let baseOffset = $div.offsetParent().offset();
$div.offset({
left: baseOffset.left + leftOffset,
top: baseOffset.top + topOffset
});
This has the advantage of not arbitrarily setting $div
's parent to relative positioning (what if $div
's parent was, itself, absolute positioned inside something else?). I think the only major edge case is if $div
doesn't have any offsetParent
, not sure if it would return document
, null
, or something else entirely.
offsetParent
has been available since jQuery 1.2.6, sometime in 2008, so this technique works now and when the original question was asked.
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
objWMIService.Create "notepad.exe", null, null, intProcessID
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery _
("Select * From __InstanceDeletionEvent Within 1 Where TargetInstance ISA 'Win32_Process'")
Do Until i = 1
Set objLatestProcess = colMonitoredProcesses.NextEvent
If objLatestProcess.TargetInstance.ProcessID = intProcessID Then
i = 1
End If
Loop
Wscript.Echo "Notepad has been terminated."
Using Context,We can clear app specific files like preference,database file. I have used below code for UI testing using Espresso.
@Rule
public ActivityTestRule<HomeActivity> mActivityRule = new ActivityTestRule<>(
HomeActivity.class);
public static void clearAppInfo() {
Activity mActivity = testRule.getActivity();
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(mActivity);
prefs.edit().clear().commit();
mActivity.deleteDatabase("app_db_name.db");
}
Google posted a solution for this kind of problem here.
The steps:
3333
on the left part, and type localhost:5000
, and click add rule.Looking at the neural network from the outside, it is just a function that takes some arguments and produces a result. As with all functions, it has a domain (i.e. a set of legal arguments). You have to normalize the values that you want to pass to the neural net in order to make sure it is in the domain. As with all functions, if the arguments are not in the domain, the result is not guaranteed to be appropriate.
The exact behavior of the neural net on arguments outside of the domain depends on the implementation of the neural net. But overall, the result is useless if the arguments are not within the domain.
This may not apply to many of you, but I'm usually operating my computers under Linux, so by default I save my matplotlib plots as PNG and SVG. This works fine under Linux but is unbearably slow on my Windows 7 installations [MiKTeX under Python(x,y) or Anaconda], so I've taken to adding this code, and things work fine over there again:
import platform # Don't save as SVG if running under Windows.
#
# Plot code goes here.
#
fig.savefig('figure_name.png', dpi = 200)
if platform.system() != 'Windows':
# In my installations of Windows 7, it takes an inordinate amount of time to save
# graphs as .svg files, so on that platform I've disabled the call that does so.
# The first run of a script is still a little slow while everything is loaded in,
# but execution times of subsequent runs are improved immensely.
fig.savefig('figure_name.svg')
This is happening because your PHP code is getting executed before the form gets posted.
To avoid this wrap your PHP code in following if statement and it will handle the rest no need to set if statements for each variables
if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST))
{
//process PHP Code
}
else
{
//do nothing
}
Just as Daniel said "Git and TFVC are the two source control options in TFS
". Fortunately both are supported for now in VS Code.
You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.
Add the following lines to your user settings
If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe", "tfvc.restrictWorkspace": true }
Or for VS 2017:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe", "tfvc.restrictWorkspace": true }
Open a local folder (repository), From View -> Command Pallette ..., type team signin
Provide user name --> Enter --> Provide password to connect to TFS.
Please refer to below links for more details:
Note that Server Workspaces are not supported:
"TFVC support is limited to Local workspaces":
I meet the same issue on a Windows installed .NET Framework 4.0.
And I Solved this issue by installing .NET Framework 4.6.2.
Or you may download the newest package to have a try.
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
This can be done by using PsExec
which can be downloaded here
psexec \\computer_name -u username -p password ipconfig
If this isn't working try doing this :-
Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System.
Add a new DWORD value called LocalAccountTokenFilterPolicy
Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.
x=np.sort(array)
y=np.fliplr(x)
np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!
Hope it helps you out!
I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.
Arrays.toString: (from the API, at least for the Object[]
version of it)
public static String toString(Object[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(String.valueOf(a[i]));
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
So that means it inserts the [
at the start, the ]
at the end, and the ,
between elements.
If you want it without those characters: (StringBuilder is faster than the below, but it can't be the small amount of code)
String str = "";
for (String i:arr)
str += i;
System.out.println(str);
Side note:
String[] arr[3]= [1,2,3]
won't compile.
Presumably you wanted: String[] arr = {"1", "2", "3"};
Ok. I had to add. One line implementation for those who already have Spring and Apache Commons dependency or are planning to add it:
DigestUtils.md5DigestAsHex(FileUtils.readFileToByteArray(file))
For and Apache commons only option (credit @duleshi):
DigestUtils.md5Hex(FileUtils.readFileToByteArray(file))
Hope this helps someone.
Implement "use strict"
in all script tags to find inconsistencies and fix potential unscoped variables!
If I read Modules/cStringIO.c
correctly, this should be quite efficient (although somewhat verbose):
from cStringIO import StringIO
def iterbuf(buf):
stri = StringIO(buf)
while True:
nl = stri.readline()
if nl != '':
yield nl.strip()
else:
raise StopIteration
To transfer images from your local Docker installation to a minikube VM:
docker save <image> | (eval $(minikube docker-env) && docker load)
Jenkins Pipeline also provides the current build number as the property number
of the currentBuild
. It can be read as currentBuild.number
.
For example:
// Scripted pipeline
def buildNumber = currentBuild.number
// Declarative pipeline
echo "Build number is ${currentBuild.number}"
Other properties of currentBuild
are described in the Pipeline Syntax: Global Variables page that is included on each Pipeline job page. That page describes the global variables available in the Jenkins instance based on the current plugins.
Just from reading that i would have never understood that "$@"
expands into a list of separate parameters. Whereas, "$*"
is one parameter consisting of all the parameters added together.
If it still makes no sense do this.
http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/
For someone who need to update the PHP version in WAMP, I can recommend this http://wampserver.aviatechno.net/
I had a problems with updating too, but on this website are Wampserver addons like new php version (php 7.1.4 etc.) And you don't have to manually edit files like php.ini or phpForApache.
Enjoy!
You can also pass information in through the environment as is suggested here. The example by Ismail Amin is repeated here:
In the shell:
export name=plot_data_file
In a Gnuplot script:
#! /usr/bin/gnuplot
name=system("echo $name")
set title name
plot name using ($16 * 8):20 with linespoints notitle
pause -1
In addition to all other answers, there's an important difference for IE8: If you use display:none
and try to get the element's width or height, IE8 returns 0 (while other browsers will return the actual sizes). IE8 returns correct width or height only for visibility:hidden
.
Usually, the correct way of updating certain fields in one or more model instances is to use the update()
method on the respective queryset. Then you do something like this:
affected_surveys = Survey.objects.filter(
# restrict your queryset by whatever fits you
# ...
).update(active=True)
This way, you don't need to call save()
on your model anymore because it gets saved automatically. Also, the update()
method returns the number of survey instances that were affected by your update.
You could use JSON.stringify(array)
to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']);
in your PHP script to retrieve it.
If you want to $broadcast
use the $rootScope
:
$scope.startScanner = function() {
$rootScope.$broadcast('scanner-started');
}
And then to receive, use the $scope
of your controller:
$scope.$on('scanner-started', function(event, args) {
// do what you want to do
});
If you want you can pass arguments when you $broadcast
:
$rootScope.$broadcast('scanner-started', { any: {} });
And then receive them:
$scope.$on('scanner-started', function(event, args) {
var anyThing = args.any;
// do what you want to do
});
Documentation for this inside the Scope docs.
One way I found after some struggling is creating a function which gets data_plot matrix, file name and order as parameter to create boxplots from the given data in the ordered figure (different orders = different figures) and save it under the given file_name.
def plotFigure(data_plot,file_name,order):
fig = plt.figure(order, figsize=(9, 6))
ax = fig.add_subplot(111)
bp = ax.boxplot(data_plot)
fig.savefig(file_name, bbox_inches='tight')
plt.close()
Try adding parentheses around the row in table1
e.g.
DELETE
FROM table1
WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);
The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.
Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:
MERGE INTO table1 AS t1
USING table2 AS s1
ON t1.stn = s1.stn
AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;
<Ctrl> + W, V to split the screen vertically
<Ctrl> + W, W to shift between the windows
!python % [args] to run the script I am editing in this window
ZF in visual mode to fold arbitrary lines
This worked best for me when I wanted to check out the code, given the commit ID <commit_id_SHA1>
git fetch origin <commit_id_SHA1>
git checkout -b new_branch FETCH_HEAD
I usually do as you describe:
Add a separate column with a random value (=RAND()
) and then perform a sort on that column.
Might be more complex and prettyer ways (using macros etc), but this is fast enough and simple enough for me.
There are three parts to this:
The answer to that can be quite broad.
Essentially, the major difference for me that usually influences my decisions on which to use is that with a SQLDataReader, you are "streaming" data from the database. With a SQLDataAdapter, you are extracting the data from the database into an object that can itself be queried further, as well as performing CRUD operations on.
Obviously with a stream of data SQLDataReader is MUCH faster, but you can only process one record at a time. With a SQLDataAdapter, you have a complete collection of the matching rows to your query from the database to work with/pass through your code.
WARNING: If you are using a SQLDataReader, ALWAYS, ALWAYS, ALWAYS make sure that you write proper code to close the connection since you are keeping the connection open with the SQLDataReader. Failure to do this, or proper error handling to close the connection in case of an error in processing the results will CRIPPLE your application with connection leaks.
Pardon my VB, but this is the minimum amount of code you should have when using a SqlDataReader:
Using cn As New SqlConnection("..."), _
cmd As New SqlCommand("...", cn)
cn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
''# ...
End While
End Using
End Using
equivalent C#:
using (var cn = new SqlConnection("..."))
using (var cmd = new SqlCommand("..."))
{
cn.Open();
using(var rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
//...
}
}
}
There are data services that given a zip code will give you list of street names in that zip code.
Use a regex to extract Zip or City State - find the correct one or if a error get both. pull the list of streets from a data source Correct the city and state, and then street address. Once you get a valid Address line 1, city, state, and zip you can then make assumptions on address line 2..3
Improving on Reza's answer:
<html><head><style>
.splitter {
width: 100%;
height: 100px;
display: flex;
}
#separator {
cursor: col-resize;
background-color: #aaa;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='30'><path d='M2 0 v30 M5 0 v30 M8 0 v30' fill='none' stroke='black'/></svg>");
background-repeat: no-repeat;
background-position: center;
width: 10px;
height: 100%;
/* Prevent the browser's built-in drag from interfering */
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#first {
background-color: #dde;
width: 20%;
height: 100%;
min-width: 10px;
}
#second {
background-color: #eee;
width: 80%;
height: 100%;
min-width: 10px;
}
</style></head><body>
<div class="splitter">
<div id="first"></div>
<div id="separator" ></div>
<div id="second" ></div>
</div>
<script>
// A function is used for dragging and moving
function dragElement(element, direction)
{
var md; // remember mouse down info
const first = document.getElementById("first");
const second = document.getElementById("second");
element.onmousedown = onMouseDown;
function onMouseDown(e)
{
//console.log("mouse down: " + e.clientX);
md = {e,
offsetLeft: element.offsetLeft,
offsetTop: element.offsetTop,
firstWidth: first.offsetWidth,
secondWidth: second.offsetWidth
};
document.onmousemove = onMouseMove;
document.onmouseup = () => {
//console.log("mouse up");
document.onmousemove = document.onmouseup = null;
}
}
function onMouseMove(e)
{
//console.log("mouse move: " + e.clientX);
var delta = {x: e.clientX - md.e.clientX,
y: e.clientY - md.e.clientY};
if (direction === "H" ) // Horizontal
{
// Prevent negative-sized elements
delta.x = Math.min(Math.max(delta.x, -md.firstWidth),
md.secondWidth);
element.style.left = md.offsetLeft + delta.x + "px";
first.style.width = (md.firstWidth + delta.x) + "px";
second.style.width = (md.secondWidth - delta.x) + "px";
}
}
}
dragElement( document.getElementById("separator"), "H" );
</script></body></html>
_x000D_
Try this code to use:
/* For Mozile Firefox Browser */
::-moz-selection { background-color: #4CAF50; }
/* For Other Browser*/
::selection { background-color: #4CAF50; }
Brad Wilson has a couple great articles on unobtrusive validation and unobtrusive ajax.
It is also shown very nicely in this Pluralsight video in the section on " AJAX and JavaScript".
Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data-
attributes in HTML.
In seeking to fix the problem of pop-up, I discovered that Apple had a way around this concern.
Indeed, when you click on this link, if you installed the application, it is rerouted to it; otherwise, you will be redirected to the webpage, without any pop-up.
update @Marcel Jackwerth's answer for general.
and only working with class attribute, not working with method variable.
/**
* get variable name as string
* only work with class attributes
* not work with method variable
*
* @param headClass variable name space
* @param vars object variable
* @throws IllegalAccessException
*/
public static void printFieldNames(Object headClass, Object... vars) throws IllegalAccessException {
List<Object> fooList = Arrays.asList(vars);
for (Field field : headClass.getClass().getFields()) {
if (fooList.contains(field.get(headClass))) {
System.out.println(field.getGenericType() + " " + field.getName() + " = " + field.get(headClass));
}
}
}
In oracle-based products you may use the following statement:
update table set interfaceID=RowNum where condition;
Declare:
SET @a = 1;
Usage:
INSERT INTO `t` (`c`) VALUES (@a);
You can use Firephp an add-on to firebug to debug php in the same environment as javascript.
I also use Xdebug mentioned earlier for profiling php.
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
We can consider a telephone call In that Number is wsdl and exchange of information is soap.
WSDL is description how to connect with communication server.SOAP is have communication messages.
This is another method . Passing array as a pointer to the function
void generateArray(int *array, int size) {
srand(time(0));
for (int j=0;j<size;j++)
array[j]=(0+rand()%9);
}
int main(){
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
Ok guys I found a possible solution to this problem. I realized that joins do not exists in Mongo, that's why first you need to query the user's ids with the role you like, and after that do another query to the profiles document, something like this:
const exclude: string = '-_id -created_at -gallery -wallet -MaxRequestersPerBooking -active -__v';
// Get the _ids of users with the role equal to role.
await User.find({role: role}, {_id: 1, role: 1, name: 1}, function(err, docs) {
// Map the docs into an array of just the _ids
var ids = docs.map(function(doc) { return doc._id; });
// Get the profiles whose users are in that set.
Profile.find({user: {$in: ids}}, function(err, profiles) {
// docs contains your answer
res.json({
code: 200,
profiles: profiles,
page: page
})
})
.select(exclude)
.populate({
path: 'user',
select: '-password -verified -_id -__v'
// group: { role: "$role"}
})
});
For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:
I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 45.0f;
//set height according to row or section , whatever you want to do!
}
section label text are set.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *sectionHeaderView;
sectionHeaderView = [[UIView alloc] initWithFrame:
CGRectMake(0, 0, tableView.frame.size.width, 120.0)];
sectionHeaderView.backgroundColor = kColor(61, 201, 247);
UILabel *headerLabel = [[UILabel alloc] initWithFrame:
CGRectMake(sectionHeaderView.frame.origin.x,sectionHeaderView.frame.origin.y - 44, sectionHeaderView.frame.size.width, sectionHeaderView.frame.size.height)];
headerLabel.backgroundColor = [UIColor clearColor];
[headerLabel setTextColor:kColor(255, 255, 255)];
headerLabel.textAlignment = NSTextAlignmentCenter;
[headerLabel setFont:kFont(20)];
[sectionHeaderView addSubview:headerLabel];
switch (section) {
case 0:
headerLabel.text = @"Section 1";
return sectionHeaderView;
break;
case 1:
headerLabel.text = @"Section 2";
return sectionHeaderView;
break;
case 2:
headerLabel.text = @"Section 3";
return sectionHeaderView;
break;
default:
break;
}
return sectionHeaderView;
}
Using Jquery for active link:
$(function(){
$('#nav a').filter(function() {
return this.href==location.href
})
.parent().addClass('active').siblings().removeClass('active')
$('#nav a').click(function(){
$(this).parent().addClass('active').siblings().removeClass('active')
})
});
Use Component life cycle method or document ready function as specified in Jquery.
The view-source url prefix trick didn't work for me using chrome on an iphone. There are apps I could have installed to do this I guess but for whatever reason I just preferred to do it myself rather than install 'yet another app'.
I found this nice quick tutorial for how to setup a bookmark on mobile safari that will automatically open the view source of a page: https://appletoolbox.com/2014/03/how-to-view-webpage-html-source-codes-on-ipad-iphone-no-app-required/
It worked flawlessly for me and now I have it set as a permanent bookmark any time I want, with no app installed.
Edit: There are basically 6 steps which should work for either Chrome or Safari. Instructions for Safari are:
javascript:(function(){var a=window.open('about:blank').document;a.write('<!DOCTYPE html><html><head><title>Source of '+location.href+'</title><meta name="viewport" content="width=device-width" /></head><body></body></html>');a.close();var b=a.body.appendChild(a.createElement('pre'));b.style.overflow='auto';b.style.whiteSpace='pre-wrap';b.appendChild(a.createTextNode(document.documentElement.innerHTML))})();
simple with generated links :) html:
<span class='preview' data-image-url="imageUrl.png" data-container="body" data-toggle="popover" data-placement="top" >preview</span>
js:
$('.preview').popover({
'trigger':'hover',
'html':true,
'content':function(){
return "<img src='"+$(this).data('imageUrl')+"'>";
}
});
Just to extend the answers a bit with what to do with the parsed object:
# JSON Parsing example
require "rubygems" # don't need this if you're Ruby v1.9.3 or higher
require "json"
string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}'
parsed = JSON.parse(string) # returns a hash
p parsed["desc"]["someKey"]
p parsed["main_item"]["stats"]["a"]
# Read JSON from a file, iterate over objects
file = open("shops.json")
json = file.read
parsed = JSON.parse(json)
parsed["shop"].each do |shop|
p shop["id"]
end
The issue is with
At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?
Many people consider module.exports = ...
to be equivalent to export default ...
and exports.foo ...
to be equivalent to export const foo = ...
. That's not quite true though, or at least not how Babel does it.
ES6 default
exports are actually also named exports, except that default
is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:
// input
export const foo = 42;
export default 21;
// output
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var foo = exports.foo = 42;
exports.default = 21;
Here we can see that the default export becomes a property on the exports
object, just like foo
.
We can import the module in two ways: Either using CommonJS or using ES6 import
syntax.
Your issue: I believe you are doing something like:
var bar = require('./input');
new bar();
expecting that bar
is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default
property!
So in order to access the default export we actually have to do
var bar = require('./input').default;
If we use ES6 module syntax, namely
import bar from './input';
console.log(bar);
Babel will transform it to
'use strict';
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
console.log(_input2.default);
You can see that every access to bar
is converted to access .default
.
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
Yet another solution as my own reminder; I got this error with FacebookSDK, importing project fails to build because it doesn't have default.properties, it has project.properties.
I removed all lines mentioned below from /res/values-v21/styles.xml and now it is working fine.
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="windowActionBar">false</item>
<item name="android:windowDisablePreview">true</item>
<item name="windowNoTitle">true</item>
<item name="android:fitsSystemWindows">true</item>
try this.
String[] extension = "adadad.adad.adnandad.jpg".split("\\.(?=[^\\.]+$)"); // ['adadad.adad.adnandad','jpg']
extension[1] // jpg
GET vs. POST
1) Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
2) Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
3) $_GET is an array of variables passed to the current script via the URL parameters.
4) $_POST is an array of variables passed to the current script via the HTTP POST method.
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
I think the Java Service Wrapper works well. Note that there are three ways to integrate your application. It sounds like option 1 will work best for you given that you don't want to change the code. The configuration file can get a little crazy, but just remember that (for option 1) the program you're starting and for which you'll be specifying arguments, is their helper program, which will then start your program. They have an example configuration file for this.
To do this on storyboard (Interface Builder Inspector)
With help of IBDesignable
, we can add more options to Interface Builder Inspector for UINavigationController
and tweak them on storyboard. First, add the following code to your project.
@IBDesignable extension UINavigationController {
@IBInspectable var barTintColor: UIColor? {
set {
guard let uiColor = newValue else { return }
navigationBar.barTintColor = uiColor
}
get {
guard let color = navigationBar.barTintColor else { return nil }
return color
}
}
}
Then simply set the attributes for navigation controller on storyboard.
This approach may also be used to manage the color of the navigation bar text from the storyboard:
@IBInspectable var barTextColor: UIColor? {
set {
guard let uiColor = newValue else {return}
navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: uiColor]
}
get {
guard let textAttributes = navigationBar.titleTextAttributes else { return nil }
return textAttributes[NSAttributedStringKey.foregroundColor] as? UIColor
}
}
An ES6 approach to clearing a group of radio buttons:
Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );
You don't need a function at all. You can work on a whole column directly.
Example data:
>>> df = pd.DataFrame({'a': [100, 1000], 'b': [200, 2000], 'c': [300, 3000]})
>>> df
a b c
0 100 200 300
1 1000 2000 3000
Half all the values in column a
:
>>> df.a = df.a / 2
>>> df
a b c
0 50 200 300
1 500 2000 3000
You can also use any()
, map()
like so:
if any(map(l.startswith, x)):
pass # Do something
Or alternatively, using a generator expression:
if any(l.startswith(s) for s in x)
pass # Do something
I have found that the best approach to search for a character in a very large string (that is 1 000 000 characters long, for example) is to use the replace()
method.
window.count_replace = function (str, schar) {
return str.length - str.replace(RegExp(schar), '').length;
};
You can see yet another JSPerf suite to test this method along with other methods of finding a character in a string.
PHP native function exists for this. See http://php.net/manual/en/function.reset.php
Simply do this: mixed reset ( array &$array )
Not sure why no one says the obvious, as there's a built in javascript scrollTo
function:
scrollTo( $('#element').position().top );
This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.
When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).
Consider the following code:
$dom = new DOMDocument(); //create a document
$dom->preserveWhiteSpace = false; //disable whitespace preservation
$dom->formatOutput = true; //pretty print output
$documentElement = $dom->createElement("Entry"); //create a node
$dom->appendChild ($documentElement); //append it
$message = new DOMDocument(); //create another document
$message->loadXML($messageXMLtext); //populate the new document from XML text
$node=$dom->importNode($message->documentElement,true); //import the new document content to a new node in the original document
$documentElement->appendChild($node); //append the new node to the document Element
$dom->saveXML($dom->documentElement); //print the original document
In this context, the $dom->saveXML();
statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.
In order to achieve pretty printing for the entire $dom document, the line:
$message->preserveWhiteSpace = false;
must be included after the $message = new DOMDocument();
line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.
I would like to give another example in which multiple (3) joins are used.
DataClasses1DataContext ctx = new DataClasses1DataContext();
var Owners = ctx.OwnerMasters;
var Category = ctx.CategoryMasters;
var Status = ctx.StatusMasters;
var Tasks = ctx.TaskMasters;
var xyz = from t in Tasks
join c in Category
on t.TaskCategory equals c.CategoryID
join s in Status
on t.TaskStatus equals s.StatusID
join o in Owners
on t.TaskOwner equals o.OwnerID
select new
{
t.TaskID,
t.TaskShortDescription,
c.CategoryName,
s.StatusName,
o.OwnerName
};
To know SESSION decimal separator, you can use following SQL command:
ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';
select SUBSTR(value,1,1) as "SEPARATOR"
,'using NLS-PARAMETER' as "Explanation"
from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS'
UNION ALL
select SUBSTR(0.5,1,1) as "SEPARATOR"
,'using NUMBER IMPLICIT CASTING' as "Explanation"
from DUAL;
The first SELECT command find NLS Parameter defined in NLS_SESSION_PARAMETERS
table. The decimal separator is the first character of the returned value.
The second SELECT command convert IMPLICITELY the 0.5
rational number into a String using (by default) NLS_NUMERIC_CHARACTERS defined at session level.
The both command return same value.
I have already tested the same SQL command in PL/SQL script and this is always the same value COMMA or POINT that is displayed. Decimal Separator displayed in PL/SQL script is equal to what is displayed in SQL.
To test what I say, I have used following SQL commands:
ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';
select 'DECIMAL-SEPARATOR on CLIENT: (' || TO_CHAR(.5,) || ')' from dual;
DECLARE
S VARCHAR2(10) := '?';
BEGIN
select .5 INTO S from dual;
DBMS_OUTPUT.PUT_LINE('DECIMAL-SEPARATOR in PL/SQL: (' || S || ')');
END;
/
The shorter command to know decimal separator is:
SELECT .5 FROM DUAL;
That return 0,5
if decimal separator is a COMMA and 0.5
if decimal separator is a POINT.
you can use json_decode
function
foreach (json_decode($response) as $area)
{
print_r($area); // this is your area from json response
}
See this fiddle
set -o xtrace
or
bash -x myscript.sh
This works with standard /bin/sh as well IIRC (it might be a POSIX thing then)
And remember, there is bashdb (bash Shell Debugger, release 4.0-0.4
)
To revert to normal, exit the subshell or
set +o xtrace
you should use magic methods __Set and __get. Simple example:
class Foo
{
//This array stores your properties
private $content = array();
public function __set($key, $value)
{
//Perform data validation here before inserting data
$this->content[$key] = $value;
return $this;
}
public function __get($value)
{ //You might want to check that the data exists here
return $this->$content[$value];
}
}
Of course, don't use this example as this : no security at all :)
EDIT : seen your comments, here could be an alternative based on reflection and a decorator :
class Foo
{
private $content = array();
private $stdInstance;
public function __construct($stdInstance)
{
$this->stdInstance = $stdInstance;
}
public function __set($key, $value)
{
//Reflection for the stdClass object
$ref = new ReflectionClass($this->stdInstance);
//Fetch the props of the object
$props = $ref->getProperties();
if (in_array($key, $props)) {
$this->stdInstance->$key = $value;
} else {
$this->content[$key] = $value;
}
return $this;
}
public function __get($value)
{
//Search first your array as it is faster than using reflection
if (array_key_exists($value, $this->content))
{
return $this->content[$value];
} else {
$ref = new ReflectionClass($this->stdInstance);
//Fetch the props of the object
$props = $ref->getProperties();
if (in_array($value, $props)) {
return $this->stdInstance->$value;
} else {
throw new \Exception('No prop in here...');
}
}
}
}
PS : I didn't test my code, just the general idea...
You can also use uic
in PyQt5 with the following code.
from PyQt5 import uic, QtWidgets
import sys
class Ui(QtWidgets.QDialog):
def __init__(self):
super(Ui, self).__init__()
uic.loadUi('SomeUi.ui', self)
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Ui()
sys.exit(app.exec_())
org.apache.commons.lang3.tuple.Pair
implements java.util.Map.Entry
and can also be used standalone.
Also as others mentioned Guava's com.google.common.collect.Maps.immutableEntry(K, V)
does the trick.
I prefer Pair
for its fluent Pair.of(L, R)
syntax.
Negatives are your friend here:
SELECT Col1
FROM TABLE
WHERE Col1 like '%[^a-Z0-9]%'
Which says that you want any rows where Col1
consists of any number of characters, then one character not in the set a-Z0-9, and then any number of characters.
If you have a case sensitive collation, it's important that you use a range that includes both upper and lower case A
, a
, Z
and z
, which is what I've given (originally I had it the wrong way around. a
comes before A
. Z
comes after z
)
Or, to put it another way, you could have written your original WHERE
as:
Col1 LIKE '[!@#$%]'
But, as you observed, you'd need to know all of the characters to include in the []
.
Yes, Guava provides this in the Resources
class. For example:
URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);
You can execute
git status -s
This will show modified files name and then by copying the interested file path you can see changes using git diff
git diff <filepath + filename>
You can call net start "service name"
on your service. If it's not started, it'll start it and return errorlevel=0, if it's already started it'll return errorlevel=2.
To add to Oleg's answer:
I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath)
to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!
* I actually don't know if the $(ExecutablePath)
macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.
You may need to know the status during the file download or use credentials before making the request.
Here is an example that covers these options:
Uri ur = new Uri("http://remotehost.do/images/img.jpg");
using (WebClient client = new WebClient()) {
//client.Credentials = new NetworkCredential("username", "password");
String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
client.DownloadProgressChanged += WebClientDownloadProgressChanged;
client.DownloadDataCompleted += WebClientDownloadCompleted;
client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}
And the callback's functions implemented as follows:
void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
}
void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
Console.WriteLine("Download finished!");
}
(Ver 2) - Lambda notation: other possible option for handling the events
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) {
Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
});
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(delegate(object sender, DownloadDataCompletedEventArgs e){
Console.WriteLine("Download finished!");
});
(Ver 3) - We can do better
client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
{
Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
};
client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) =>
{
Console.WriteLine("Download finished!");
};
(Ver 4) - Or
client.DownloadProgressChanged += (o, e) =>
{
Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
};
client.DownloadDataCompleted += (o, e) =>
{
Console.WriteLine("Download finished!");
};
Here's my take how to detect the Unicode family of text encodings via BOM. The accuracy of this method is low, as this method only works on text files (specifically Unicode files), and defaults to ascii
when no BOM is present (like most text editors, the default would be UTF8
if you want to match the HTTP/web ecosystem).
Update 2018: I no longer recommend this method. I recommend using file.exe from GIT or *nix tools as recommended by @Sybren, and I show how to do that via PowerShell in a later answer.
# from https://gist.github.com/zommarin/1480974
function Get-FileEncoding($Path) {
$bytes = [byte[]](Get-Content $Path -Encoding byte -ReadCount 4 -TotalCount 4)
if(!$bytes) { return 'utf8' }
switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bytes[0],$bytes[1],$bytes[2],$bytes[3]) {
'^efbbbf' { return 'utf8' }
'^2b2f76' { return 'utf7' }
'^fffe' { return 'unicode' }
'^feff' { return 'bigendianunicode' }
'^0000feff' { return 'utf32' }
default { return 'ascii' }
}
}
dir ~\Documents\WindowsPowershell -File |
select Name,@{Name='Encoding';Expression={Get-FileEncoding $_.FullName}} |
ft -AutoSize
Recommendation: This can work reasonably well if the dir
, ls
, or Get-ChildItem
only checks known text files, and when you're only looking for "bad encodings" from a known list of tools. (i.e. SQL Management Studio defaults to UTF16, which broke GIT auto-cr-lf for Windows, which was the default for many years.)
b = email.message_from_string(a)
if b.is_multipart():
for payload in b.get_payload():
# if payload.is_multipart(): ...
print payload.get_payload()
else:
print b.get_payload()
Register your handler with signal.signal
like this:
#!/usr/bin/env python
import signal
import sys
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
Code adapted from here.
More documentation on signal
can be found here.
Flexbox spec editor here.
This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.
Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.
Since your header and footer aren't meant to flex, they should both have flex: none;
set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto
, so they start at their auto height and can shrink but not grow, but they're also overflow:visible
by default, which triggers their default min-height:auto
to prevent them from shrinking at all. If you ever set an overflow
on them, the behavior of min-height:auto
changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article>
element.)
You can simplify the <article>
flex
too - just set flex: 1;
and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.
If you have a very limited number of levels, you could try converting y
into factor and change its levels.
> xy <- data.frame(x = c(1, 2, 4), y = c(1, 4, 5))
> xy$w <- as.factor(xy$y)
> levels(xy$w) <- c("good", "fair", "bad")
> xy
x y w
1 1 1 good
2 2 4 fair
3 4 5 bad
Also you can use HRTime package. It has a class StopWatch.
check the context.xml
file in Web Pages -> META-INF, the username="user"
must be the same as the database user, in my case was root, that solved the connection error
Hope helps
In Eclipse, try Project > Open Project and select the projects to be opened.
i would suppose to set the EditText
s width to wrap_content
and put the two buttons into a LinearLayout
whose width is fill_parent
and weight set to 1.
In most cases a screen -RRx $username/
will suffice :)
If you still want to list all screens then put the following script in your path and call it screen or whatever you like:
#!/bin/bash
if [[ "$1" != "-ls-all" ]]; then
exec /usr/bin/screen "$@"
else
shopt -s nullglob
screens=(/var/run/screen/S-*/*)
if (( ${#screens[@]} == 0 )); then
echo "no screen session found in /var/run/screen"
else
echo "${screens[@]#*S-}"
fi
fi
It will behave exactly like screen except for showing all screen sessions, when giving the option -ls-all as first parameter.
Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own.
var stack = [];
stack.push(firstObject);
// while not empty
while (stack.length) {
// Pop off end of stack.
obj = stack.pop();
// Do stuff.
// Push other objects on the stack as needed.
...
}
Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack:
foo(first);
foo(second);
has to be replaced by
stack.push(second);
stack.push(first);
Edit: The article Stacks and Recursion Elimination (or Article Backup link) goes into more details on this subject.
You can't specify a range in the case statement, can do as follows.
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
break;
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
MessageBox.Show("You are only " + age + " years old\n That's too young!");
break;
...........etc.
If you don't mind installing a package for it, you can use json-tricks:
pip install json-tricks
After that you just need to import dump(s)
from json_tricks
instead of json, and it'll usually work:
from json_tricks import dumps
json_str = dumps(cls_instance, indent=4)
which'll give
{
"__instance_type__": [
"module_name.test_class",
"MyTestCls"
],
"attributes": {
"attr": "val",
"dct_attr": {
"hello": 42
}
}
}
And that's basically it!
This will work great in general. There are some exceptions, e.g. if special things happen in __new__
, or more metaclass magic is going on.
Obviously loading also works (otherwise what's the point):
from json_tricks import loads
json_str = loads(json_str)
This does assume that module_name.test_class.MyTestCls
can be imported and hasn't changed in non-compatible ways. You'll get back an instance, not some dictionary or something, and it should be an identical copy to the one you dumped.
If you want to customize how something gets (de)serialized, you can add special methods to your class, like so:
class CustomEncodeCls:
def __init__(self):
self.relevant = 42
self.irrelevant = 37
def __json_encode__(self):
# should return primitive, serializable types like dict, list, int, string, float...
return {'relevant': self.relevant}
def __json_decode__(self, **attrs):
# should initialize all properties; note that __init__ is not called implicitly
self.relevant = attrs['relevant']
self.irrelevant = 12
which serializes only part of the attributes parameters, as an example.
And as a free bonus, you get (de)serialization of numpy arrays, date & times, ordered maps, as well as the ability to include comments in json.
Disclaimer: I created json_tricks, because I had the same problem as you.
If you need a solution anyway (e.g. because you have too many implementations of the abstract class and the testing would always repeat the same procedures) then you could create an abstract test class with an abstract factory method which will be excuted by the implementation of that test class. This examples works or me with TestNG:
The abstract test class of Car
:
abstract class CarTest {
// the factory method
abstract Car createCar(int speed, int fuel);
// all test methods need to make use of the factory method to create the instance of a car
@Test
public void testGetSpeed() {
Car car = createCar(33, 44);
assertEquals(car.getSpeed(), 33);
...
Implementation of Car
class ElectricCar extends Car {
private final int batteryCapacity;
public ElectricCar(int speed, int fuel, int batteryCapacity) {
super(speed, fuel);
this.batteryCapacity = batteryCapacity;
}
...
Unit test class ElectricCarTest
of the Class ElectricCar
:
class ElectricCarTest extends CarTest {
// implementation of the abstract factory method
Car createCar(int speed, int fuel) {
return new ElectricCar(speed, fuel, 0);
}
// here you cann add specific test methods
...
If you want nice json without hardcoding attributes into your service classes,
use <webHttp defaultOutgoingResponseFormat="Json"/>
in your behavior config
Assuming you're using bash
#!/bin/bash
current_dir=$(pwd)
script_dir=$(dirname "$0")
echo $current_dir
echo $script_dir
This script should print the directory that you're in, and then the directory the script is in. For example, when calling it from /
with the script in /home/mez/
, it outputs
/
/home/mez
Remember, when assigning variables from the output of a command, wrap the command in $(
and )
- or you won't get the desired output.
Form myForm;
myForm.WindowState = FormWindowState.Minimized;
Just add in select2.css
/* Make Select2 boxes match Bootstrap3 as well as Bootstrap4 heights: */
.select2-selection__rendered {
line-height: 32px !important;
}
.select2-selection {
height: 34px !important;
}
This is a great place to use regular expressions.
By using a regular expression, you can replace all that code with just one line.
You can use the following regex to validate your requirements:
[0-9]*\.?[0-9]*
In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.
You can replace your code with this:
function validate(s) {
var rgx = /^[0-9]*\.?[0-9]*$/;
return s.match(rgx);
}
That code can replace your entire function!
Note that you have to escape the period with a backslash (otherwise it stands for 'any character').
For more reading on using regular expressions with javascript, check this out:
You can also test the above regex here:
Explanation of the regex used above:
The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.
The *
means "zero or more of the previous expression."
[0-9]*
means "zero or more numbers"
The backslash is used as an escape character for the period, because period usually stands for "any character."
The ?
means "zero or one of the previous character."
The ^
represents the beginning of a string.
The $
represents the end of a string.
Starting the regex with ^
and ending it with $
ensures that the entire string adheres to the regex pattern.
Hope this helps!
Apply the color to the li
and set the span
(or other child element) color to whatever color the text should be.
ul
{
list-style-type: square;
}
ul > li
{
color: green;
}
ul > li > span
{
color: black;
}
You need to replace \t
- make sure you use extended mode!
I had a similar issue using the Chrome driver (v2.23) / running the tests thru TeamCity. I was able to fix the issue by adding the "no-sandbox" flag to the Chrome options:
var options = new ChromeOptions();
options.AddArgument("no-sandbox");
I'm not sure if there is a similar option for the FF driver. From what I understand the issue has something to do with TeamCity running Selenium under the SYSTEM account.
astype(str)
!Prior to pandas 1.0 (well, 0.25 actually) this was the defacto way of declaring a Series/column as as string:
# pandas <= 0.25
# Note to pedants: specifying the type is unnecessary since pandas will
# automagically infer the type as object
s = pd.Series(['a', 'b', 'c'], dtype=str)
s.dtype
# dtype('O')
From pandas 1.0 onwards, consider using "string"
type instead.
# pandas >= 1.0
s = pd.Series(['a', 'b', 'c'], dtype="string")
s.dtype
# StringDtype
Here's why, as quoted by the docs:
You can accidentally store a mixture of strings and non-strings in an object dtype array. It’s better to have a dedicated dtype.
object
dtype breaks dtype-specific operations likeDataFrame.select_dtypes()
. There isn’t a clear way to select just text while excluding non-text but still object-dtype columns.When reading code, the contents of an
object
dtype array is less clear than'string'
.
See also the section on Behavioral Differences between "string"
and object
.
Extension types (introduced in 0.24 and formalized in 1.0) are closer to pandas than numpy, which is good because numpy types are not powerful enough. For example NumPy does not have any way of representing missing data in integer data (since type(NaN) == float
). But pandas can using Nullable Integer columns.
Accidentally mixing dtypes
The first reason, as outlined in the docs is that you can accidentally store non-text data in object columns.
# pandas <= 0.25
pd.Series(['a', 'b', 1.23]) # whoops, this should have been "1.23"
0 a
1 b
2 1.23
dtype: object
pd.Series(['a', 'b', 1.23]).tolist()
# ['a', 'b', 1.23] # oops, pandas was storing this as float all the time.
# pandas >= 1.0
pd.Series(['a', 'b', 1.23], dtype="string")
0 a
1 b
2 1.23
dtype: string
pd.Series(['a', 'b', 1.23], dtype="string").tolist()
# ['a', 'b', '1.23'] # it's a string and we just averted some potentially nasty bugs.
Challenging to differentiate strings and other python objects
Another obvious example example is that it's harder to distinguish between "strings" and "objects". Objects are essentially the blanket type for any type that does not support vectorizable operations.
Consider,
# Setup
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [{}, [1, 2, 3], 123]})
df
A B
0 a {}
1 b [1, 2, 3]
2 c 123
Upto pandas 0.25, there was virtually no way to distinguish that "A" and "B" do not have the same type of data.
# pandas <= 0.25
df.dtypes
A object
B object
dtype: object
df.select_dtypes(object)
A B
0 a {}
1 b [1, 2, 3]
2 c 123
From pandas 1.0, this becomes a lot simpler:
# pandas >= 1.0
# Convenience function I call to help illustrate my point.
df = df.convert_dtypes()
df.dtypes
A string
B object
dtype: object
df.select_dtypes("string")
A
0 a
1 b
2 c
Readability
This is self-explanatory ;-)
...No. As of writing this answer (version 1.1), there are no performance benefits but the docs expect future enhancements to significantly improve performance and reduce memory usage for "string"
columns as opposed to objects. With that said, however, it's never too early to form good habits!
If you just want a string/json to print it can be solved with:
print(df.to_string(index=False))
Buf if you want to serialize the data too or even send to a MongoDB, would be better to do something like:
document = df.to_dict(orient='list')
There are 6 ways by now to orient the data, check more in the panda docs which better fits you.
$abc=array("a"=>1,"b"=>2,"c"=>4,"e"=>7,"d"=>5);
/*program to find max value*/
$lagest = array();
$i=0;
foreach($abc as $key=>$a) {
if($i==0) $b=$a;
if($b<$a) {
$b=$a;
$k=$key;
}
$i++;
}
$lagest[$k]=$b;
print_r($lagest);
Another way of doing this is to use ravel
model = forest.fit(train_fold, train_y.values.reshape(-1,))
We use a lot of DLL's (> 100) in our project. These DLL's have dependencies on each other and therefore we chose the setup of dynamic linking. However it has the following disadvantages:
Maybe a better setup was to make everything a static library (and therefore you just have one executable). This works only if no code duplication takes place. A test seems to support this assumption, but i couldn't find an official MSDN quote. So for example make 1 exe with:
The code and variables of shared_lib2 should be present in the final merged executable only once. Can anyone support this question?
Responsive text alignment has been added in Bootstrap V4:
https://getbootstrap.com/docs/4.0/utilities/text/#text-alignment
For left, right, and center alignment, responsive classes are available that use the same viewport width breakpoints as the grid system.
<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
See the concept is very simple.
1) All threads are started in the constructor and thus are in ready to run state. Main is already the running thread.
2) Now you called the t1.join(). Here what happens is that the main thread gets knotted behind the t1 thread. So you can imagine a longer thread with main attached to the lower end of t1.
3) Now there are three threads which could run: t2, t3 and combined thread(t1 + main).
4)Now since till t1 is finished main can't run. so the execution of the other two join statements has been stopped.
5) So the scheduler now decides which of the above mentioned(in point 3) threads run which explains the output.
For a console application you can use System.Reflection.Assembly.GetExecutingAssembly().Location
as long as the call is made within the code of the console app itself, if you call this from within another dll or plugin this will return the location of that DLL and not the executable.
Define the values that you don't want to be used from Chrome's user agent style in your own CSS content.
You guys copied the wrong code.
Go into the "/build" folder and grab the jquery.datetimepicker.full.js or jquery.datetimepicker.full.min.js if you want the minified version. It should fix it! :)
MSDN FileInfo.Length says that it is "the size of the current file in bytes."
My typical Google search for something like this is: msdn FileInfo
I had a same problem, and I solved my problem.
First go to config.default.php
and change
$cfg['Servers'][$i]['AllowNoPassword'] = false;
to
$cfg['Servers'][$i]['AllowNoPassword'] = true;
Python opens files almost in the same way as in C:
r+
Open for reading and writing. The stream is positioned at the beginning of the file.
a+
Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is appended to the end of the file (but in some Unix systems regardless of the current seek position).
This is what you need :
if (Value1.StartsWith("abc"))
{
found = true;
}
Thanks to this post, I use this style to remove the red border that appears automatically with bootstrap when a required field is displayed, but user didn't have a chance to input anything already:
input.ng-pristine.ng-invalid {
-webkit-box-shadow: none;
-ms-box-shadow: none;
box-shadow:none;
}
Apparently, your class "Format" is involved in the problem. Check your declaration of this class, especially if you did it inside another class you probably forgot the @implementation or something similar.
I found the other examples unclear, so I did my own test which confirmed that a class instance is passed by reference and as such actions done to the class will affect the source instance.
In other words, my Increment method modifies its parameter myClass everytime its called.
class Program
{
static void Main(string[] args)
{
MyClass myClass = new MyClass();
Console.WriteLine(myClass.Value); // Displays 1
Increment(myClass);
Console.WriteLine(myClass.Value); // Displays 2
Increment(myClass);
Console.WriteLine(myClass.Value); // Displays 3
Increment(myClass);
Console.WriteLine(myClass.Value); // Displays 4
Console.WriteLine("Hit Enter to exit.");
Console.ReadLine();
}
public static void Increment(MyClass myClassRef)
{
myClassRef.Value++;
}
}
public class MyClass
{
public int Value {get;set;}
public MyClass()
{
Value = 1;
}
}
For the TL;DR, here are 2 cents and a simpler version for your questions:
WebSockets provides these benefits over HTTP:
WebSocket and HTTP protocol have been designed to solve different problems, I.E. WebSocket was designed to improve bi-directional communication whereas HTTP was designed to be stateless, distributed using a request/response model. Other than sharing the ports for legacy reasons (firewall/proxy penetration), there isn't much common ground to combine them into one protocol.
You can use typeof(N)
to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.
In that case, use the elem.tagName
or elem.nodeName
property.
if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.
How to copy directory and sub dirs's and files from ansible server to remote host
- name: copy nmonchart39 directory to {{ inventory_hostname }}
copy:
src: /home/ansib.usr.srv/automation/monitoring/nmonchart39
dest: /var/nmon/data
Where:
copy entire directory: src: /automation/monitoring/nmonchart39
copy directory contents src: nmonchart39/
How malloc() and free() works depends on the runtime library used. Generally, malloc() allocates a heap (a block of memory) from the operating system. Each request to malloc() then allocates a small chunk of this memory be returning a pointer to the caller. The memory allocation routines will have to store some extra information about the block of memory allocated to be able to keep track of used and free memory on the heap. This information is often stored in a few bytes just before the pointer returned by malloc() and it can be a linked list of memory blocks.
By writing past the block of memory allocated by malloc() you will most likely destroy some of the book-keeping information of the next block which may be the remaining unused block of memory.
One place where you program may also crash is when copying too many characters into the buffer. If the extra characters are located outside the heap you may get an access violation as you are trying to write to non-existing memory.
There is an NPM module for this:
It allows you to have a representation of a directory tree as a string or an object. Using it with the command line will allow you to save the representation in a txt file.
Example:
$ npm dree parse myDirectory --dest ./generated --name tree
A lot of these questions only address the Mac address. If you also require the IP address I just wrote this, may need some work but seems to work well on my machine...
- (NSString *)getLocalIPAddress
{
NSArray *ipAddresses = [[NSHost currentHost] addresses];
NSArray *sortedIPAddresses = [ipAddresses sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.allowsFloats = NO;
for (NSString *potentialIPAddress in sortedIPAddresses)
{
if ([potentialIPAddress isEqualToString:@"127.0.0.1"]) {
continue;
}
NSArray *ipParts = [potentialIPAddress componentsSeparatedByString:@"."];
BOOL isMatch = YES;
for (NSString *ipPart in ipParts) {
if (![numberFormatter numberFromString:ipPart]) {
isMatch = NO;
break;
}
}
if (isMatch) {
return potentialIPAddress;
}
}
// No IP found
return @"?.?.?.?";
}
The only benefit for the option B is having all the data in one system, yet it's a false benefit! You may argue that your code is also a form of data, and therefore also can be stored in database - how would you like it?
Unless you have some unique case:
It is not necessary to use filesystem to keep files. Instead you may use cloud storage (such as Amazon S3) or Infrastructure-as-a-service on top of it (such as Uploadcare):
https://uploadcare.com/upload-api-cloud-storage-and-cdn/
But storing files in the database is a bad idea.
For me, I couldn't get this to return a hash.
results = ActiveRecord::Base.connection.execute(sql)
But using the exec_query method worked.
results = ActiveRecord::Base.connection.exec_query(sql)
It's always annoyed me how Windows doesn't have some of more useful little scripting utilities of Unix, such as who/whoami, sed and AWK. Anyway, if you want something foolproof, get Visual Studio Express and compile the following:
#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv) {
printf("%s", GetUserName());
}
And just use that in your batch file.
As you can see in RFC 6068, this is not possible at all:
The special
<hfname>
"body" indicates that the associated<hfvalue>
is the body of the message. The "body" field value is intended to contain the content for the first text/plain body part of the message. The "body" pseudo header field is primarily intended for the generation of short text messages for automatic processing (such as "subscribe" messages for mailing lists), not for general MIME bodies.
I had this issue but it was fixed easily by going to the Internet Information Services (IIS) Manager, double clicking Directory Browsing and clicking Enable.
In my case, I could access files directly but could not access folders.
Performance wise, this should be comparable. Use Select statement and Sort to get a list and then pick the first or last (depending on your sort order).
var col = dt.Select("AccountLevel", "AccountLevel ASC");
var min = col.First();
var max = col.Last();
For linux ubuntu 18.04:
Go to terminal and command:$ sudo systemctl status tomcat
Have a same problem. My solution is after you handle with parsing arguments using argparse or other way, remove arguments from sys.argv
sys.argv = sys.argv[:1]
If you need you can filter unittest arguments from main.parseArgs()
setAllowUrlEncodedSlash(true)
didn't work for me. Still internal method isNormalized
return false
when having double slash.
I replaced StrictHttpFirewall
with DefaultHttpFirewall
by having the following code only:
@Bean
public HttpFirewall defaultHttpFirewall() {
return new DefaultHttpFirewall();
}
Working well for me.
Any risk by using DefaultHttpFirewall
?
I learned about order
with the following example which then confused me for a long time:
set.seed(1234)
ID = 1:10
Age = round(rnorm(10, 50, 1))
diag = c("Depression", "Bipolar")
Diagnosis = sample(diag, 10, replace=TRUE)
data = data.frame(ID, Age, Diagnosis)
databyAge = data[order(Age),]
databyAge
The only reason this example works is because order
is sorting by the vector Age
, not by the column named Age
in the data frame data
.
To see this create an identical data frame using read.table
with slightly different column names and without making use of any of the above vectors:
my.data <- read.table(text = '
id age diagnosis
1 49 Depression
2 50 Depression
3 51 Depression
4 48 Depression
5 50 Depression
6 51 Bipolar
7 49 Bipolar
8 49 Bipolar
9 49 Bipolar
10 49 Depression
', header = TRUE)
The above line structure for order
no longer works because there is no vector named age
:
databyage = my.data[order(age),]
The following line works because order
sorts on the column age
in my.data
.
databyage = my.data[order(my.data$age),]
I thought this was worth posting given how confused I was by this example for so long. If this post is not deemed appropriate for the thread I can remove it.
EDIT: May 13, 2014
Below is a generalized way of sorting a data frame by every column without specifying column names. The code below shows how to sort from left to right or by right to left. This works if every column is numeric. I have not tried with a character column added.
I found the do.call
code a month or two ago in an old post on a different site, but only after extensive and difficult searching. I am not sure I could relocate that post now. The present thread is the first hit for ordering a data.frame
in R
. So, I thought my expanded version of that original do.call
code might be useful.
set.seed(1234)
v1 <- c(0,0,0,0, 0,0,0,0, 1,1,1,1, 1,1,1,1)
v2 <- c(0,0,0,0, 1,1,1,1, 0,0,0,0, 1,1,1,1)
v3 <- c(0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1)
v4 <- c(0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1)
df.1 <- data.frame(v1, v2, v3, v4)
df.1
rdf.1 <- df.1[sample(nrow(df.1), nrow(df.1), replace = FALSE),]
rdf.1
order.rdf.1 <- rdf.1[do.call(order, as.list(rdf.1)),]
order.rdf.1
order.rdf.2 <- rdf.1[do.call(order, rev(as.list(rdf.1))),]
order.rdf.2
rdf.3 <- data.frame(rdf.1$v2, rdf.1$v4, rdf.1$v3, rdf.1$v1)
rdf.3
order.rdf.3 <- rdf.1[do.call(order, as.list(rdf.3)),]
order.rdf.3
Is there any disadvantages/consequences of pushing empty commits?
Aside from the extreme confusion someone might get as to why there's a bunch of commits with no content in them on master, not really.
You can change the commit that you pushed to remote, but the sha1 of the commit (basically it's id number) will change permanently, which alters the source tree -- You'd then have to do a git push -f
back to remote.
One way assuming filtered data in A1 downwards;
dim Rng as Range
set Rng = Range("A2", Range("A2").End(xlDown)).Cells.SpecialCells(xlCellTypeVisible)
...
for each cell in Rng
...
Previous answers got you list of torch.Size Here is how to get list of ints
listofints = [int(x) for x in tensor.shape]
I had the same problem in Visual Studio Pro 2017: missing MSVCP120.dll file in Release mode and missing MSVCP120d.dll file in Debug mode. I installed Visual C++ Redistributable Packages for Visual Studio 2013 and Update for Visual C++ 2013 and Visual C++ Redistributable Package as suggested here Microsoft answer this fixed the release mode. For the debug mode what eventually worked was to copy msvcp120d.dll and msvcr120d.dll from a different computer (with Visual studio 2013) into C:\Windows\System32
Source: java-implementation-of-rubys-gsub
Usage:
// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
public String replacement() {
float inches = Float.parseFloat(group(1));
return Float.toString(2.54f * inches) + " cm";
}
}.rewrite("a 17 inch display");
System.out.println(result);
// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
public String replacement() {
return group(1).toUpperCase();
}
}.rewrite("ab12 cd efg34");
System.out.println(result);
Implementation (redesigned):
import static java.lang.String.format;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class Rewriter {
private Pattern pattern;
private Matcher matcher;
public Rewriter(String regularExpression) {
this.pattern = Pattern.compile(regularExpression);
}
public String group(int i) {
return matcher.group(i);
}
public abstract String replacement() throws Exception;
public String rewrite(CharSequence original) {
return rewrite(original, new StringBuffer(original.length())).toString();
}
public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
try {
this.matcher = pattern.matcher(original);
while (matcher.find()) {
matcher.appendReplacement(destination, "");
destination.append(replacement());
}
matcher.appendTail(destination);
return destination;
} catch (Exception e) {
throw new RuntimeException("Cannot rewrite " + toString(), e);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(pattern.pattern());
for (int i = 0; i <= matcher.groupCount(); i++)
sb.append(format("\n\t(%s) - %s", i, group(i)));
return sb.toString();
}
}
As per Basil Bourque's comment, this is the updated answer for this question, taking into account the new API of Java 8:
String myDateString = "13:24:40";
LocalTime localTime = LocalTime.parse(myDateString, DateTimeFormatter.ofPattern("HH:mm:ss"));
int hour = localTime.get(ChronoField.CLOCK_HOUR_OF_DAY);
int minute = localTime.get(ChronoField.MINUTE_OF_HOUR);
int second = localTime.get(ChronoField.SECOND_OF_MINUTE);
//prints "hour: 13, minute: 24, second: 40":
System.out.println(String.format("hour: %d, minute: %d, second: %d", hour, minute, second));
Remarks:
====== Below is the old (original) answer for this question, using pre-Java8 API: =====
I'm sorry if I'm gonna upset anyone with this, but I'm actually gonna answer the question. The Java API's are pretty huge, I think it's normal that someone might miss one now and then.
A SimpleDateFormat might do the trick here:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
It should be something like:
String myDateString = "13:24:40";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
//the above commented line was changed to the one below, as per Grodriguez's pertinent comment:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(myDateString);
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date); // assigns calendar to given date
int hour = calendar.get(Calendar.HOUR);
int minute; /... similar methods for minutes and seconds
The gotchas you should be aware of:
the pattern you pass to SimpleDateFormat might be different then the one in my example depending on what values you have (are the hours in 12 hours format or in 24 hours format, etc). Look at the documentation in the link for details on this
Once you create a Date object out of your String (via SimpleDateFormat), don't be tempted to use Date.getHour(), Date.getMinute() etc. They might appear to work at times, but overall they can give bad results, and as such are now deprecated. Use the calendar instead as in the example above.
HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.
You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,
http://www.javaworld.com/javaworld/javatips/jw-javatip111.html
EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,
public SSLTunnelSocketFactory(String proxyhost, String proxyport){
tunnelHost = proxyhost;
tunnelPort = Integer.parseInt(proxyport);
dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
}
...
connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
connection.setDefaultHostnameVerifier( new HostnameVerifier()
{
public boolean verify( String arg0, SSLSession arg1 )
{
return true;
}
} );
EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,
http://bugs.sun.com/view_bug.do?bug_id=6614957
The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,
public class SSLContextTest {
public static void main(String[] args) {
System.setProperty("https.proxyHost", "proxy.xxx.com");
System.setProperty("https.proxyPort", "8888");
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
sslContext.getSocketFactory());
HttpsURLConnection
.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
System.out.println("hostnameVerifier =============");
return true;
}
});
URL url = new URL("https://www.verisign.net");
URLConnection conn = url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is what I get when I run the program,
checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......
As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.
You do not set such attributes in strings.xml
type of files. You need to set it in your code. or (which is better solution) create style with colors you want and apply to your TextView
More likely it is 400 Bad Request
6.5.1. 400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
As the request contains duplicate value(value that already exists), it can be perceived as a client error. Need to change the request before the next try.
By considering these facts we can conclude as HTTP STATUS 400 Bad Request.
https://github.com/jasonday/printThis
$("#myID").printThis();
Great Jquery plugin to do exactly what your after
You already accepted an answer, but I just thought I'd mention that the following also works in Cygwin:
cd "C:\Foo"
I think the cd /cygdrive/c
method is better, but sometimes it's useful to know that you can do this too.
In your Android Developer Tools , From the SDK Manager, install Extras > Google Cloud Messaging for Android Library . After the installation is complete restart your SDK.Then navigate to sdk\extras\google\gcm\gcm-client\dist . there will be your gcm.jar file.
When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:
def add(a,b):
return a + b
you would call the function like this:
add(3,5)
which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:
answer = add(4,7)
Which would set the variable answer equal to 11 in this case.
pandas version 0.23.4
df.rename(index=str,columns={'old_name':'new_name'},inplace=True)
For the record:
omitting index=str will give error replace has an unexpected argument 'columns'
Here is a pretty simple implementation:
with open('/etc/passwd', 'r') as f:
try:
f.seek(0,2)
s = ''
while s.count('\n') < 11:
cur = f.tell()
f.seek((cur - 10))
s = f.read(10) + s
f.seek((cur - 10))
print s
except Exception as e:
f.readlines()
The <prev>
tag doesn't exist, but it's probably the <pre>
HTML tag to put around debug output, to improve readability. It's not a secret PHP hack. :)
When it comes to labels, I would say it's up to you what you prefer. Some examples when it can be useful with HTML helper tags are, for instance
@Html.LabelFor
, @Html.TextBoxFor
, etc@Html.EditorFor
, as you can assign specific behavior och looks in a editor viewThis is very simple you need to keep different names of every radio input group.
<input type="radio" name="price">Thousand<br>_x000D_
<input type="radio" name="price">Lakh<br>_x000D_
<input type="radio" name="price">Crore_x000D_
_x000D_
</br><hr>_x000D_
_x000D_
<input type="radio" name="gender">Male<br>_x000D_
<input type="radio" name="gender">Female<br>_x000D_
<input type="radio" name="gender">Other
_x000D_
String date="Sat Jun 01 12:53:10 IST 2013";
SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
Date currentdate=sdf.parse(date);
SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");
System.out.println(sdf2.format(currentdate));
And when you use a case :
CASE
WHEN TB1.COD IS NULL THEN
TB1.COD || ' - ' || TB1.NAME
ELSE
TB1.COD || ' - ' || TB1.NAME || ' - ' || TB.NM_TABELAFRETE
END AS NR_FRETE,
I don't see the simplified formula in other responses. The logic is covered but I wanted a most basic form for my embedded use:
Unpadded = ((4 * n) + 2) / 3
Padded = 4 * ((n + 2) / 3)
NOTE: When calculating the unpadded count we round up the integer division i.e. add Divisor-1 which is +2 in this case
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
I'm sure you can use RAISERROR ... WITH NOWAIT
If you use severity 10 it's not an error. This also provides some handy formatting eg %s, %i and you can use state too to track where you are.
Creating new DOM elements is a core feature of the jQuery()
method, see:
Trivial example with an Animal and Dog: You mirror C++'s vtable mechanism (largely anyway). You also separate allocation and instantiation (Animal_Alloc, Animal_New) so we don't call malloc() multiple times. We must also explicitly pass the this
pointer around.
If you were to do non-virtual functions, that's trival. You just don't add them to the vtable and static functions don't require a this
pointer. Multiple inheritance generally requires multiple vtables to resolve ambiguities.
Also, you should be able to use setjmp/longjmp to do exception handling.
struct Animal_Vtable{
typedef void (*Walk_Fun)(struct Animal *a_This);
typedef struct Animal * (*Dtor_Fun)(struct Animal *a_This);
Walk_Fun Walk;
Dtor_Fun Dtor;
};
struct Animal{
Animal_Vtable vtable;
char *Name;
};
struct Dog{
Animal_Vtable vtable;
char *Name; // Mirror member variables for easy access
char *Type;
};
void Animal_Walk(struct Animal *a_This){
printf("Animal (%s) walking\n", a_This->Name);
}
struct Animal* Animal_Dtor(struct Animal *a_This){
printf("animal::dtor\n");
return a_This;
}
Animal *Animal_Alloc(){
return (Animal*)malloc(sizeof(Animal));
}
Animal *Animal_New(Animal *a_Animal){
a_Animal->vtable.Walk = Animal_Walk;
a_Animal->vtable.Dtor = Animal_Dtor;
a_Animal->Name = "Anonymous";
return a_Animal;
}
void Animal_Free(Animal *a_This){
a_This->vtable.Dtor(a_This);
free(a_This);
}
void Dog_Walk(struct Dog *a_This){
printf("Dog walking %s (%s)\n", a_This->Type, a_This->Name);
}
Dog* Dog_Dtor(struct Dog *a_This){
// Explicit call to parent destructor
Animal_Dtor((Animal*)a_This);
printf("dog::dtor\n");
return a_This;
}
Dog *Dog_Alloc(){
return (Dog*)malloc(sizeof(Dog));
}
Dog *Dog_New(Dog *a_Dog){
// Explict call to parent constructor
Animal_New((Animal*)a_Dog);
a_Dog->Type = "Dog type";
a_Dog->vtable.Walk = (Animal_Vtable::Walk_Fun) Dog_Walk;
a_Dog->vtable.Dtor = (Animal_Vtable::Dtor_Fun) Dog_Dtor;
return a_Dog;
}
int main(int argc, char **argv){
/*
Base class:
Animal *a_Animal = Animal_New(Animal_Alloc());
*/
Animal *a_Animal = (Animal*)Dog_New(Dog_Alloc());
a_Animal->vtable.Walk(a_Animal);
Animal_Free(a_Animal);
}
PS. This is tested on a C++ compiler, but it should be easy to make it work on a C compiler.
but select-String doesn't seem to have this option.
Correct. PowerShell is not a clone of *nix shells' toolset.
However it is not hard to build something like it yourself:
$regexes = Get-Content RegexFile.txt |
Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }
$fileList | Get-Content | Where-Object {
foreach ($r in $regexes) {
if ($r.IsMatch($_)) {
$true
break
}
}
$false
}
As some research,
Most commonly MIME type is
application/json
Let's see a example to differentiate with json and javascript.
It is used when it is not known how this data will be used. When the information is to be just extracted from the server in JSON format, it may be through a link or from any file, in that case, it is used.
For example-
<?php
header('Content-type:application/json');
$directory =[
['Id'=> 1, 'Name' => 'this' ],
['Id'=> 2, 'Name' => 'is'],
['Id'=> 3, 'Name' => 'stackoverflow'],
];
// Showing the json data
echo json_encode($directory);
?>
Output is,
[{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}]
it is used when the use of the data is predefined. It is used by applications in which there are calls by the client-side ajax applications. It is used when the data is of type JSON-P or JSONP.
For example
<?php
header('Content-type:application/javascript');
$dir =[
['Id'=> 1, 'Name' => 'this' ],
['Id'=> 2, 'Name' => 'is'],
['Id'=> 3, 'Name' => 'stackoverflow'],
];
echo "Function_call(".json_encode($dir).");";
?>
Output is,
Function_call([{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}])
And for other MIME Types see full detail here,
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
Unfortunately it's not very easy. You could create your own custom marker based on the OverlayView class (an example) and put your own HTML in it, including a counter. This will leave you with a very basic marker, that you can't drag around or add shadows easily, but it is very customisable.
Alternatively, you could add a label to the default marker. This will be less customisable but should work. It also keeps all the useful things the standard marker does.
You can read more about the overlays in Google's article Fun with MVC Objects.
Edit: if you don't want to create a JavaScript class, you could use Google's Chart API. For example:
Numbered marker:
http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000
Text marker:
http://chart.apis.google.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|foo
This is the quick and easy route, but it's less customisable, and requires a new image to be downloaded by the client for each marker.
I think problem is either incorrect layout name or invalid layout file path.
for IntelliJ, you can create resource directory and place layout files there.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/sample.fxml"));
rootLayout = loader.load();
I do also have a huge masochistic streak as that I've written yet another JSON parser. This one uses a procedural approach. It uses a similat SQL hierarchy list table to store the parsed data. Also in the package are:
Please feel free to use and have fun with it
http://www.codeproject.com/Articles/1000953/JSON-for-Sql-Server-Part
Here's a simple example demonstrating the creation of a comma delimited string using String.Join() from a list of Strings:
List<string> histList = new List<string>();
histList.Add(dt.ToString("MM/dd/yyyy::HH:mm:ss.ffff"));
histList.Add(Index.ToString());
/*arValue is array of Singles */
foreach (Single s in arValue)
{
histList.Add(s.ToString());
}
String HistLine = String.Join(",", histList.ToArray());
Unless otherwise definied (<tfoot>
, <thead>
), browsers put <tr>
implicitly in a <tbody>
.
You need to put a > tbody
in between > table
and > tr
:
$("div.custList > table > tbody > tr")
Alternatively, you can also be less strict in selecting the rows (the >
denotes the immediate child):
$("div.custList table tr")
That said, you can get the immediate <td>
children there by $(this).children('td')
.
If you are using Clojure and https://github.com/semperos/clj-webdriver you can use this snippet to resize the browser.
(require '[clj-webdriver.taxi :as taxi])
; Open browser
(taxi/set-driver! {:browser :chrome} "about:blank")
; Resize browser
(-> taxi/*driver* (.webdriver) (.manage) (.window)
(.setSize (org.openqa.selenium.Dimension. 0 0)))
I also ran into the error message invalid command 'bdist_wheel'
It turns out the package setup.py used distutils rather than setuptools. Changing it as follows enabled me to build the wheel.
#from distutils.core import setup
from setuptools import setup
If you are using logging then thread names will be helpful. A thread factory helps with this:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class Main {
static Logger LOG = LoggerFactory.getLogger(Main.class);
static class MyTask implements Runnable {
public void run() {
LOG.info("A pool thread is doing this task");
}
}
public static void main(String[] args) {
ExecutorService taskExecutor = Executors.newFixedThreadPool(5, new MyThreadFactory());
taskExecutor.execute(new MyTask());
taskExecutor.shutdown();
}
}
class MyThreadFactory implements ThreadFactory {
private int counter;
public Thread newThread(Runnable r) {
return new Thread(r, "My thread # " + counter++);
}
}
Output:
[ My thread # 0] Main INFO A pool thread is doing this task
Bootstrap4:
Comes with .no-gutters
out of the box.
source: https://github.com/twbs/bootstrap/pull/21211/files
Bootstrap3:
Requires custom CSS.
Stylesheet:
.row.no-gutters {
margin-right: 0;
margin-left: 0;
& > [class^="col-"],
& > [class*=" col-"] {
padding-right: 0;
padding-left: 0;
}
}
Then to use:
<div class="row no-gutters">
<div class="col-xs-4">...</div>
<div class="col-xs-4">...</div>
<div class="col-xs-4">...</div>
</div>
It will:
In case you're working with a regular old System.Collections.IEnumerable
instead of IEnumerable<T>
you can use enumerable.Cast<object>().ToList()
As Matt has said, use Console.Write
. I would also recommend explicitly flushing the output, however - I believe WriteLine
does this automatically, but I'd seen oddities when just using Console.Write
and then waiting. So Matt's code becomes:
Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();
$dateValue = '2012-01-05';
$year = date('Y',strtotime($dateValue));
$month = date('F',strtotime($dateValue));
All those ""
literals are the same object. Why make all that extra complexity? It's just longer to type and less clear (the cost to the compiler is minimal). Since Java's strings are immutable objects, there's never any need at all to distinguish between them except possibly as an efficiency thing, but with the empty string literal that's not a big deal.
If you really want an EmptyString
constant, make it yourself. But all it will do is encourage even more verbose code; there will never be any benefit to doing so.
It sounds like you are using Visual Studio's Web Compiler extension. There is an open issue for this found here: https://github.com/madskristensen/WebCompiler/issues/413
There is a workaround posted in that issue:
C:\Users\USERNAME\AppData\Local\Temp\WebCompilerX.X.X
(X is the version of WebCompiler)node_modules
folder: caniuse-lite
and browserslist
Open up CMD (inside C:\Users\USERNAME\AppData\Local\Temp\WebCompilerX.X.X
) and run: npm i caniuse-lite browserslist
buttion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new com.google.zxing.integration.android.IntentIntegrator(Fragment.this).initiateScan();
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
dependencies {
compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
compile 'com.google.zxing:core:3.2.1'
compile 'com.android.support:appcompat-v7:23.1.0'
}
If you need to know the Commit history only, So don't use much Meshed up and bulky plugins,
I will recommend you a Basic simple plugin like "Git Commits"
I use it too :
https://marketplace.visualstudio.com/items?itemName=exelord.git-commits
Enjoy
For Navigation Bar :
Writing this code :
self.navigationController.navigationBar.translucent = NO;
just did the trick for me.
Java doesn't have the concept of a "count" of the used elements in an array.
To get this, Java uses an ArrayList
. The List
is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big).
To get the count, you use mylist.size()
to ensure a capacity (the underlying array backing) you use mylist.ensureCapacity(20)
. To get rid of the extra capacity, you use mylist.trimToSize()
.
Old question, but in my case i found using position:fixed
solved it for me.
My situation might have been a little different though. I had an overlayed semi transparent div
with a loading animation in it that I needed displayed while the page was loading. So using height:auto / 100%
or min-height: 100%
both filled the window but not the off-screen area. Using position:fixed
made this overlay scroll with the user, so it always covered the visible area and kept my preloading animation centred on the screen.
for ascending order:
Reserved.objects.filter(client=client_id).order_by('check_in')
for descending order:
1. Reserved.objects.filter(client=client_id).order_by('-check_in')
or
2. Reserved.objects.filter(client=client_id).order_by('check_in')[::-1]
Constants in ruby cannot be defined inside methods. See the notes at the bottom of this page, for example
By using (
,)
, you are capturing the group, if you simply remove them you will not have this problem.
>>> str1 = "a b c d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']
However there is no need for regex, str.split
without any delimiter specified will split this by whitespace for you. This would be the best way in this case.
>>> str1.split()
['a', 'b', 'c', 'd']
If you really wanted regex you can use this ('\s'
represents whitespace and it's clearer):
>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']
or you can find all non-whitespace characters
>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']
There are two ways to do it: creating filter condition 1) Manually 2) Dynamically.
Sample DataFrame:
val df = spark.createDataFrame(Seq(
(0, "a1", "b1", "c1", "d1"),
(1, "a2", "b2", "c2", "d2"),
(2, "a3", "b3", null, "d3"),
(3, "a4", null, "c4", "d4"),
(4, null, "b5", "c5", "d5")
)).toDF("id", "col1", "col2", "col3", "col4")
+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
| 0| a1| b1| c1| d1|
| 1| a2| b2| c2| d2|
| 2| a3| b3|null| d3|
| 3| a4|null| c4| d4|
| 4|null| b5| c5| d5|
+---+----+----+----+----+
1) Creating filter condition manually i.e. using DataFrame where
or filter
function
df.filter(col("col1").isNotNull && col("col2").isNotNull).show
or
df.where("col1 is not null and col2 is not null").show
Result:
+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
| 0| a1| b1| c1| d1|
| 1| a2| b2| c2| d2|
| 2| a3| b3|null| d3|
+---+----+----+----+----+
2) Creating filter condition dynamically: This is useful when we don't want any column to have null value and there are large number of columns, which is mostly the case.
To create the filter condition manually in these cases will waste a lot of time. In below code we are including all columns dynamically using map
and reduce
function on DataFrame columns:
val filterCond = df.columns.map(x=>col(x).isNotNull).reduce(_ && _)
How filterCond
looks:
filterCond: org.apache.spark.sql.Column = (((((id IS NOT NULL) AND (col1 IS NOT NULL)) AND (col2 IS NOT NULL)) AND (col3 IS NOT NULL)) AND (col4 IS NOT NULL))
Filtering:
val filteredDf = df.filter(filterCond)
Result:
+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
| 0| a1| b1| c1| d1|
| 1| a2| b2| c2| d2|
+---+----+----+----+----+
It would be neater to create a folder named "c:\programs writable\" and put you app below that one. That way a jungle of low c-folders can be avoided.
The underlying trade-off is security versus ease-of-use. If you know what you are doing you want to be god on you own pc. If you must maintain healthy systems for your local anarchistic society, you may want to add some security.