I found the other ideas on this page to lose their efficacy when used on small buttons with small text lettering. This answer expands on RobertPitt's answer.
Here is the minor tweak:
text-shadow: 1px 1px transparent, -1px -1px black;
$('button').click(function(){
$('button').removeClass('btnActive');
$(this).addClass('btnActive');
});
_x000D_
body{background:#666;}
.btnActive{
border: 1px solid #aaa;
border-top: 1px solid #333;
border-left: 1px solid #333;
color: #ecf0f8;
background-color: #293d70;
background-image: none;
text-shadow: 1px 1px transparent, -1px -1px black;
outline:none;
}
button{
border: 1px solid #446;
border-radius: 3px;
color: white;
background-color: #385499;
background-image: linear-gradient(-180deg,##7d94cf,#1c294a 90%);
cursor: pointer;
font-size: 14px;
font-weight: 600;
padding: 6px 12px;
xxtext-shadow: 1px 1px 2px navy;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btnActive">Option One</button>
<button>Option Two</button>
_x000D_
I used this site to finesse the color shades.
You can find examples for writing OAuth clients here:
In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails
. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:
@EnableOAuth2Client
@Configuration
class MyConfig{
@Value("${oauth.resource:http://localhost:8082}")
private String baseUrl;
@Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
private String authorizeUrl;
@Value("${oauth.token:http://localhost:8082/oauth/token}")
private String tokenUrl;
@Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource;
resource = new ResourceOwnerPasswordResourceDetails();
List scopes = new ArrayList<String>(2);
scopes.add("write");
scopes.add("read");
resource.setAccessTokenUri(tokenUrl);
resource.setClientId("restapp");
resource.setClientSecret("restapp");
resource.setGrantType("password");
resource.setScope(scopes);
resource.setUsername("**USERNAME**");
resource.setPassword("**PASSWORD**");
return resource;
}
@Bean
public OAuth2RestOperations restTemplate() {
AccessTokenRequest atr = new DefaultAccessTokenRequest();
return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
}
}
@Service
@SuppressWarnings("unchecked")
class MyService {
@Autowired
private OAuth2RestOperations restTemplate;
public MyService() {
restTemplate.getAccessToken();
}
}
Do not forget about @EnableOAuth2Client
on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger
with debug
enabled set.
Good luck
I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .
The keys are accessed using an exclamation point: ${!array[@]}
, the values are accessed using ${array[@]}
.
You can iterate over the key/value pairs like this:
for i in "${!array[@]}"
do
echo "key : $i"
echo "value: ${array[$i]}"
done
Note the use of quotes around the variable in the for
statement (plus the use of @
instead of *
). This is necessary in case any keys include spaces.
The confusion in the other answer comes from the fact that your question includes "foo" and "bar" for both the keys and the values.
Swapping the values from 1st position to till the end of the list, this code loops for ( n*n-1)/2 times. Each time it pushes the greater value to the greater index starting from Zero index.
list2 = [40,-5,10,2,0,-4,-10]
for l in range(len(list2)):
for k in range(l+1,len(list2)):
if list2[k] < list2[l]:
list2[k] , list2[l] = list2[l], list2[k]
print(list2)
I had a similar issue with Docker for Windows and Hyper-V having reserved ports for its own use- in my case, it was port 3001
that couldn't be accessed.
netstat -ano | findstr 3001
in an Administrator Powershell prompt showed nothing.netsh interface ipv4 show excludedportrange protocol=tcp
showed that the port was in one of the exclusion ranges.I was able to follow the solution described in Docker for Windows issue #3171 (Unable to bind ports: Docker-for-Windows & Hyper-V excluding but not using important port ranges):
Disable Hyper-V:
dism.exe /Online /Disable-Feature:Microsoft-Hyper-V
After the required restarts, reserve the port you want so Hyper-V doesn't reserve it back:
netsh int ipv4 add excludedportrange protocol=tcp startport=3001 numberofports=1
Reenable Hyper-V:
dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All
After this, I was able to start my docker container.
You're calling both wait
and notifyAll
without using a synchronized
block. In both cases the calling thread must own the lock on the monitor you call the method on.
From the docs for notify
(wait
and notifyAll
have similar documentation but refer to notify
for the fullest description):
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
- By executing a synchronized instance method of that object.
- By executing the body of a synchronized statement that synchronizes on the object.
- For objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.
Only one thread will be able to actually exit wait
at a time after notifyAll
as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.
Superclass constructor CAN'T be inherited in extended class. Although it can be invoked in extended class constructor's with super() as the first statement.
Inspired by andrei-deusteanu answer, here is my version. This allows you to create a number of additional paths in your site-packages directory.
import os
# Add paths here. Then Run this block of code once and restart kernel. Paths should now be set.
paths_of_directories_to_add = [r'C:\GIT\project1', r'C:\GIT\project2', r'C:\GIT\project3']
# Find your site-packages directory
pathSitePckgs = os.path.join(os.path.dirname(os.__file__), 'site-packages')
# Write a .pth file in your site-packages directory
pthFile = os.path.join(pathSitePckgs,'current_machine_paths.pth')
with open(pthFile,'w') as pth_file:
pth_file.write('\n'.join(paths_of_directories_to_add))
print(pthFile)
1) Your cron is wrong. If you want to run job every 15 mins on Jenkins use this:
H/15 * * * *
2) Warning from Jenkins Spread load evenly by using ‘...’ rather than ‘...’
came with JENKINS-17311:
To allow periodically scheduled tasks to produce even load on the system, the symbol H (for “hash”) should be used wherever possible. For example, using 0 0 * * * for a dozen daily jobs will cause a large spike at midnight. In contrast, using H H * * * would still execute each job once a day, but not all at the same time, better using limited resources.
Examples:
H/15 * * * *
- every fifteen minutes (perhaps at :07, :22, :37, :52):H(0-29)/10 * * * *
- every ten minutes in the first half of every hour (three times, perhaps at :04, :14, :24)H 9-16/2 * * 1-5
- once every two hours every weekday (perhaps at 10:38 AM, 12:38 PM, 2:38 PM, 4:38 PM)H H 1,15 1-11 *
- once a day on the 1st and 15th of every month except DecemberIf you can't use tab.select() and you don't want to use a ViewPager, you can still programmatically select a tab. If you're using a custom view through TabLayout.Tab setCustomView(android.view.View view)
it is simpler. Here's how to do it both ways.
// if you've set a custom view
void updateTabSelection(int position) {
// get the position of the currently selected tab and set selected to false
mTabLayout.getTabAt(mTabLayout.getSelectedTabPosition()).getCustomView().setSelected(false);
// set selected to true on the desired tab
mTabLayout.getTabAt(position).getCustomView().setSelected(true);
// move the selection indicator
mTabLayout.setScrollPosition(position, 0, true);
// ... your logic to swap out your fragments
}
If you aren't using a custom view then you can do it like this
// if you are not using a custom view
void updateTabSelection(int position) {
// get a reference to the tabs container view
LinearLayout ll = (LinearLayout) mTabLayout.getChildAt(0);
// get the child view at the position of the currently selected tab and set selected to false
ll.getChildAt(mTabLayout.getSelectedTabPosition()).setSelected(false);
// get the child view at the new selected position and set selected to true
ll.getChildAt(position).setSelected(true);
// move the selection indicator
mTabLayout.setScrollPosition(position, 0, true);
// ... your logic to swap out your fragments
}
Use a StateListDrawable to toggle between selected and unselected drawables or something similar to do what you want with colors and/or drawables.
there is no standard, but most frameworks support both, you can see for example for java spring that it accepts both here
@GetMapping("/api/foos")
@ResponseBody
public String getFoos(@RequestParam List<String> id) {
return "IDs are " + id;
}
And Spring MVC will map a comma-delimited id parameter:
http://localhost:8080/api/foos?id=1,2,3
----
IDs are [1,2,3]
Or a list of separate id parameters:
http://localhost:8080/api/foos?id=1&id=2
----
IDs are [1,2]
May be the "\" char, try this one:
sed 's/\"http:\/\/www.fubar.com\"/URL_FUBAR/g'
$docker-compose build
If there is something new it will be rebuilt.
I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.
It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR
warning and problem at starting Firefox using Xfvb.
After adding +extension RANDR
it worked again.
$ vim /etc/init/xvfb.conf
#!upstart
description "Xvfb Server as a daemon"
start on filesystem and started networking
stop on shutdown
respawn
env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/xvfb.pid
exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1
You should use setAlignmentX(..)
on components you want to align, not on the container that has them..
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(c1);
panel.add(c2);
c1.setAlignmentX(Component.LEFT_ALIGNMENT);
c2.setAlignmentX(Component.LEFT_ALIGNMENT);
Previously we were using something like that:
// Some form.
SetFieldReadOnly( () => Entity.UserName );
...
// Base form.
private void SetFieldReadOnly(Expression<Func<object>> property)
{
var propName = GetPropNameFromExpr(property);
SetFieldsReadOnly(propName);
}
private void SetFieldReadOnly(string propertyName)
{
...
}
Reason - compile time safety. No one can silently rename property and break code logic. Now we can use nameof().
Use event delegation by assigning the onclick
to the <ol>
. Then pass the event
object as the argument, and using that, grab the text from the clicked element.
function addText(event) {_x000D_
var targ = event.target || event.srcElement;_x000D_
document.getElementById("alltext").value += targ.textContent || targ.innerText;_x000D_
}
_x000D_
<textarea id="alltext"></textarea>_x000D_
_x000D_
<ol onclick="addText(event)">_x000D_
<li>Hello</li>_x000D_
<li>World</li>_x000D_
<li>Earthlings</li>_x000D_
</ol>
_x000D_
Note that this method of passing the event
object works in older IE as well as W3 compliant systems.
You can use this following code. work just on chrome browser.
function failed(e) {_x000D_
// video playback failed - show a message saying why_x000D_
switch (e.target.error.code) {_x000D_
case e.target.error.MEDIA_ERR_ABORTED:_x000D_
alert('You aborted the video playback.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_NETWORK:_x000D_
alert('A network error caused the video download to fail part-way.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_DECODE:_x000D_
alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:_x000D_
alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');_x000D_
break;_x000D_
default:_x000D_
alert('An unknown error occurred.');_x000D_
break;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />_x000D_
<meta name="author" content="Amin Developer!" />_x000D_
_x000D_
<title>Untitled 1</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p><video src="http://jell.yfish.us/media/Jellyfish-3-Mbps.mkv" type='video/x-matroska; codecs="theora, vorbis"' autoplay controls onerror="failed(event)" ></video></p>_x000D_
<p><a href="YOU mkv FILE LINK GOES HERE TO DOWNLOAD">Download the video file</a>.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
This is the very basic
awk '/pattern/{ print $0 }' file
ask awk
to search for pattern
using //
, then print out the line, which by default is called a record, denoted by $0. At least read up the documentation.
If you only want to get print out the matched word.
awk '{for(i=1;i<=NF;i++){ if($i=="yyy"){print $i} } }' file
Given a group of radio buttons:
<input type="radio" id="radio1" name="radioGroup" value="1">
<input type="radio" id="radio2" name="radioGroup" value="2">
You can test whether a specific one is checked using jQuery as follows:
if ($("#radio1").prop("checked")) {
// do something
}
// OR
if ($("#radio1").is(":checked")) {
// do something
}
// OR if you don't have ids set you can go by group name and value
// (basically you need a selector that lets you specify the particular input)
if ($("input[name='radioGroup'][value='1']").prop("checked"))
You can get the value of the currently checked one in the group as follows:
$("input[name='radioGroup']:checked").val()
If your script is located in /var/www/dir/index.php
then the following would return:
dirname(__FILE__); // /var/www/dir
or
dirname( dirname(__FILE__) ); // /var/www
This is a technique used in many frameworks to determine relative paths from the app_root.
File structure:
/var/ www/ index.php subdir/ library.php
index.php is my dispatcher/boostrap file that all requests are routed to:
define(ROOT_PATH, dirname(__FILE__) ); // /var/www
library.php is some file located an extra directory down and I need to determine the path relative to the app root (/var/www/).
$path_current = dirname( __FILE__ ); // /var/www/subdir
$path_relative = str_replace(ROOT_PATH, '', $path_current); // /subdir
There's probably a better way to calculate the relative path then str_replace()
but you get the idea.
You can construct the intersection manually using UNION. It's easy if you have some unique field in both tables, e.g. ID:
SELECT * FROM T1
WHERE ID NOT IN (SELECT ID FROM T2)
UNION
SELECT * FROM T2
WHERE ID NOT IN (SELECT ID FROM T1)
If you don't have a unique value, you can still expand the above code to check for all fields instead of just the ID, and use AND to connect them (e.g. ID NOT IN(...) AND OTHER_FIELD NOT IN(...) etc)
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
You need to install “Visual Studio extension development” workload and “Class Designer” optional component from the Visual Studio 2017 Installer to get the feature.
See: Visual Studio Community 2017 component directory
But this kind of item is not available on all project types. Just try for yourself:
In a Console App (.NET Framework) is available;
In a Console App (.NET Core) is not available.
I couldn't find more info on future availability also for .NET Core projects.
An additional possible cause.
My HTML page had these starting tags:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
This was on a page that using the slick jquery slideshow.
I removed the tags and replaced with:
<html>
And everything is working again.
When renaming a project, it's a simple process
Dim strFirstAddress As String
Dim searchlast As Range
Dim search As Range
Set search = ActiveSheet.Range("A1:A100")
Set searchlast = search.Cells(search.Cells.Count)
Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues)
If Not rngFindValue Is Nothing Then
strFirstAddress = rngFindValue.Address
Do
Set rngFindValue = search.FindNext(rngFindValue)
Loop Until rngFindValue.Address = strFirstAddress
If you really want DELETE FROM some_table CASCADE;
which means "remove all rows from table some_table
", you can use TRUNCATE
instead of DELETE
and CASCADE
is always supported. However, if you want to use selective delete with a where
clause, TRUNCATE
is not good enough.
USE WITH CARE - This will drop all rows of all tables which have a foreign key constraint on some_table
and all tables that have constraints on those tables, etc.
Postgres supports CASCADE
with TRUNCATE command:
TRUNCATE some_table CASCADE;
Handily this is transactional (i.e. can be rolled back), although it is not fully isolated from other concurrent transactions, and has several other caveats. Read the docs for details.
If your git was already set to something and you only copied that folder to some other location, simply run:
git config --global http.proxy ""
And git will set itself straight, after what, you can pull again :)
If you missed to check the "generate web.xml" option when creating a new project, no worries If it is a Dynamic Web Project in your project right click on "Deployment Descriptor:...." and Click on "Generate Deployment Descriptor Stub" this will create a minimal /webapp/WEB-INF/web.xml.
Solved the problem with:
sudo chown -R $USER:$USER /var/www/folder-name
sudo chmod -R 755 /var/www
Grant permissions
I have just come back to this and I had to install scipy as matplotlib.mlab gave me the error message MatplotlibDeprecationWarning: scipy.stats.norm.pdf
when trying example above. So the sample is now:
%matplotlib inline
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats
mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma))
plt.show()
I got the same error, but my issue was that my fragment did not have an id in the xml layout of the parent activity.
I think you missed a key point in the documentation for .add()
Mutates the original moment by adding time.
You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)
If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.
You can work around this behavior by cloning the moment, as described here.
Also, you cannot just use ==
to test. You could format each moment to the same output and compare those, or you could just use the .isSame()
method.
Your code is now:
var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = moment(startdate).add(2, 'hours'); // see the cloning?
returned_endate.isSame(expected_enddate) // true
Syntax:
void sleep(unsigned seconds);
sleep() suspends execution for an interval (seconds). With a call to sleep, the current program is suspended from execution for the number of seconds specified by the argument seconds. The interval is accurate only to the nearest hundredth of a second or to the accuracy of the operating system clock, whichever is less accurate.
I am not sure, but might be what you want:
var c = 0;
function setBgPosition()
{
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run()
{
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c<=numbers.length)
{
setTimeout(run, 200);
}
else
{
Ext.get('common-spinner').setStyle('background-position', numbers[0] + 'px 0px');
}
}
setTimeout(run, 200);
}
setBgPosition();
Both id
and name
are bean identifiers in Spring IOC container/ApplicationContecxt. The id
attribute lets you specify exactly one id but using name
attribute you can give alias name to that bean.
You can check the spring doc here.
Presumably, since you're not providing a value for the DB_ID
column, that value is being populated by a row-level before insert trigger defined on the table. That trigger, presumably, is selecting the value from a sequence.
Since the data was moved (presumably recently) from the production database, my wager would be that when the data was copied, the sequence was not modified as well. I would guess that the sequence is generating values that are much lower than the largest DB_ID
that is currently in the table leading to the error.
You could confirm this suspicion by looking at the trigger to determine which sequence is being used and doing a
SELECT <<sequence name>>.nextval
FROM dual
and comparing that to
SELECT MAX(db_id)
FROM cmdb_db
If, as I suspect, the sequence is generating values that already exist in the database, you could increment the sequence until it was generating unused values or you could alter it to set the INCREMENT
to something very large, get the nextval once, and set the INCREMENT
back to 1.
As much as people like to say "order doesn't matter its just convention" this breaks down when entering cross domain interfaces, IE transfer from C ordering to Fortran ordering or some other ordering scheme. There, precisely how your data is layed out and how shape is represented in numpy is very important.
By default, numpy uses C ordering, which means contiguous elements in memory are the elements stored in rows. You can also do FORTRAN ordering ("F"), this instead orders elements based on columns, indexing contiguous elements.
Numpy's shape further has its own order in which it displays the shape. In numpy, shape is largest stride first, ie, in a 3d vector, it would be the least contiguous dimension, Z, or pages, 3rd dim etc... So when executing:
np.zeros((2,3,4)).shape
you will get
(2,3,4)
which is actually (frames, rows, columns)
. doing np.zeros((2,2,3,4)).shape
instead would mean (metaframs, frames, rows, columns)
. This makes more sense when you think of creating multidimensional arrays in C like langauges. For C++, creating a non contiguously defined 4D array results in an array [ of arrays [ of arrays [ of elements ]]]
. This forces you to de reference the first array that holds all the other arrays (4th dimension) then the same all the way down (3rd, 2nd, 1st) resulting in syntax like:
double element = array4d[w][z][y][x]
;
In fortran, this indexed ordering is reversed (x is instead first array4d[x][y][z][w]
), most contiguous to least contiguous and in matlab, it gets all weird.
Matlab tried to preserve both mathematical default ordering (row, column) but also use column major internally for libraries, and not follow C convention of dimensional ordering. In matlab, you order this way:
double element = array4d[y][x][z][w]
;
which deifies all convention and creates weird situations where you are sometimes indexing as if row ordered and sometimes column ordered (such as with matrix creation).
In reality, Matlab is the unintuitive one, not Numpy.
Here is example given which so how to use open
and "python close
from sys import argv
script,filename=argv
txt=open(filename)
print "filename %r" %(filename)
print txt.read()
txt.close()
print "Change the file name"
file_again=raw_input('>')
print "New file name %r" %(file_again)
txt_again=open(file_again)
print txt_again.read()
txt_again.close()
It's necessary to how many times you opened file have to close that times.
In my case i was trying to present the viewController (i have the reference of the viewController in the TabBarViewController) from different view controllers and it was crashing with the above message. In that case to avoid presenting you can use
viewController.isBeingPresented
!viewController.isBeingPresented {
// Present your ViewController only if its not present to the user currently.
}
Might help someone.
For me, once there was a mistake in spelling of function
For e.g. instead of
$(document).ready(function(){
});
I wrote
$(document).ready(funciton(){
});
So keep that also in check
I personally use the following batch script that can be used on many types of files (C, makefile, Perl scripts, shell scripts, batch, ...).
How to use it:
"$(SYS.APPDATA)\Notepad++\runNcompile.bat" "$(FULL_CURRENT_PATH)"
(optionally, you can put npp_save
on the first line to save the file before running it)This page explains quite clearly the global flow: https://www.thecrazyprogrammer.com/2015/08/configure-notepad-to-run-c-cpp-and-java-programs.html
Hope it can help
@echo off
REM ----------------------
REM ----- ARGUMENTS ------
REM ----------------------
set FPATH=%~1
set FILE=%~n1
set DIR=%~dp1
set EXTENSION=%~x1
REM ----------------------
REM ----------------------
REM ------- CONFIG -------
REM ----------------------
REM C Compiler (gcc.exe or cl.exe) + options + object extension
set CL_compilo=gcc.exe
set CFLAGS=-c "%FPATH%"
set OBJ_Ext=o
REM GNU make
set GNU_make=make.exe
REM ----------------------
IF /I "%FILE%"==Makefile GOTO _MAKEFILE
IF /I %EXTENSION%==.bat GOTO _BAT
IF /I %EXTENSION%==.sh GOTO _SH
IF /I %EXTENSION%==.pl GOTO _PL
IF /I %EXTENSION%==.tcl GOTO _TCL
IF /I %EXTENSION%==.c GOTO _C
IF /I %EXTENSION%==.mak GOTO _MAKEFILE
IF /I %EXTENSION%==.mk GOTO _MAKEFILE
IF /I %EXTENSION%==.html GOTO _HTML
echo Format of argument (%FPATH%) not supported!
GOTO END
REM Batch shell files (bat)
:_BAT
call "%FPATH%"
goto END
REM Linux shell scripts (sh)
:_SH
call sh.exe "%FPATH%"
goto END
REM Perl Script files (pl)
:_PL
call perl.exe "%FPATH%"
goto END
REM Tcl Script files (tcl)
:_TCL
call tclsh.exe "%FPATH%"
goto END
REM Compile C Source files (C)
:_C
REM MAKEFILES...
IF EXIST "%DIR%Makefile" ( cd "%DIR%" )
IF EXIST "%DIR%../Makefile" ( cd "%DIR%/.." )
IF EXIST "%DIR%../../Makefile" ( cd "%DIR%/../.." )
IF EXIST "Makefile" (
call %GNU_make% all
goto END
)
REM COMPIL...
echo -%CL_compilo% %CFLAGS%-
call %CL_compilo% %CFLAGS%
IF %ERRORLEVEL% EQU 0 (
echo -%CL_compilo% -o"%DIR%%FILE%.exe" "%DIR%%FILE%.%OBJ_Ext%"-
call %CL_compilo% -o"%DIR%%FILE%.exe" "%DIR%%FILE%.%OBJ_Ext%"
)
IF %ERRORLEVEL% EQU 0 (del "%DIR%%FILE%.%OBJ_Ext%")
goto END
REM Open HTML files in web browser (html and htm)
:_HTML
start /max /wait %FPATH%
goto END
REM ... END ...
:END
echo.
IF /I "%2" == "-pause" pause
Sharing one more way of checking if a key exists using boolean operators.
d = {'a': 1, 'b':2}
keys = 'abcd'
for k in keys:
x = (k in d and 'blah') or 'boo'
print(x)
This returns
>>> blah
>>> blah
>>> boo
>>> boo
Explanation
First you should know that in Python, 0
, None
, or objects with zero length evaluate to False
. Everything else evaluates to True
. Boolean operations are evaluated left to right and return the operand not True or False.
Let's see an example:
>>> 'Some string' or 1/0
'Some string'
>>>
Since 'Some string'
evaluates to True
, the rest of the or
is not evaluated and there is no division by zero error raised.
But if we switch the order 1/0
is evaluated first and raises an exception:
>>> 1/0 or 'Some string'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
We can use this for pattern for checking if a key exists.
(k in d and 'blah')
does the same as
if k in d:
'blah'
else:
False
This already returns the correct result if the key exists, but we want it to print 'boo' when it doesn't. So, we take the result and or
it with 'boo'
>>> False or 'boo'
'boo'
>>> 'blah' or 'boo'
'blah'
>>>
You can use the groupby command, if you already have some labels for your data.
out_list = [group[1] for group in in_series.groupby(label_series.values)]
Here's a detailed example:
Let's say we want to partition a pd series using some labels into a list of chunks
For example, in_series
is:
2019-07-01 08:00:00 -0.10
2019-07-01 08:02:00 1.16
2019-07-01 08:04:00 0.69
2019-07-01 08:06:00 -0.81
2019-07-01 08:08:00 -0.64
Length: 5, dtype: float64
And its corresponding label_series
is:
2019-07-01 08:00:00 1
2019-07-01 08:02:00 1
2019-07-01 08:04:00 2
2019-07-01 08:06:00 2
2019-07-01 08:08:00 2
Length: 5, dtype: float64
Run
out_list = [group[1] for group in in_series.groupby(label_series.values)]
which returns out_list
a list
of two pd.Series
:
[2019-07-01 08:00:00 -0.10
2019-07-01 08:02:00 1.16
Length: 2, dtype: float64,
2019-07-01 08:04:00 0.69
2019-07-01 08:06:00 -0.81
2019-07-01 08:08:00 -0.64
Length: 3, dtype: float64]
Note that you can use some parameters from in_series
itself to group the series, e.g., in_series.index.day
You could do this:
var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)
func someSelector() {
// Something after a delay
}
let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false)
func someSelector() {
// Something after a delay
}
There is no such thing: I recommend to write it for yourself and use it whenever you need.
C++ offers three different ways to create objects:
Consider your case,
Object* o;
o = new Object();
and:
Object* o = new Object();
Both forms are the same. This means that a pointer variable o is created on the stack (assume your variables does not belong to the 3 category above) and it points to a memory in the heap, which contains the object.
Try this, works for me very well:
/* Internet Explorer 10 */
display:-ms-flexbox;
-ms-flex-pack:center;
-ms-flex-align:center;
/* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
/* Safari, Opera, and Chrome */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
/* W3C */
display:box;
box-pack:center;
box-align:center;
The Swift 2 version:
// start detecting pan gesture
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(TTAltimeterDetailViewController.panGestureDetected(_:)))
panGestureRecognizer.minimumNumberOfTouches = 1
self.chartOverlayView.addGestureRecognizer(panGestureRecognizer)
func panGestureDetected(panGestureRecognizer: UIPanGestureRecognizer) {
print("pan gesture recognized")
}
// its with strongboard
@IBOutlet weak var mapView: MKMapView!
//12.9767415,77.6903967 - exact location latitude n longitude location
let cooridinate = CLLocationCoordinate2D(latitude: 12.9767415 , longitude: 77.6903967)
let spanDegree = MKCoordinateSpan(latitudeDelta: 0.2,longitudeDelta: 0.2)
let region = MKCoordinateRegion(center: cooridinate , span: spanDegree)
mapView.setRegion(region, animated: true)
I dont know if there is one already, but you can make it yourself easilly.
That different protocols example looks to me like a facade pattern. You have a common interface when there are different implementations for each case.
You could use the same principle, make a ResourceLoader class which takes the string from your properties file, and checks for a custom protocol of ours
myprotocol:a.xml
myprotocol:file:///tmp.txt
myprotocol:http://127.0.0.1:8080/a.properties
myprotocol:jar:http://www.foo.com/bar/baz.jar!/COM/foo/Quux.class
strips the myprotocol: from the start of the string and then makes a decision of which way to load the resource, and just gives you the resource.
The examples above are a bit out of date. One new example is here:
import pyhs2 as hive
import getpass
DEFAULT_DB = 'default'
DEFAULT_SERVER = '10.37.40.1'
DEFAULT_PORT = 10000
DEFAULT_DOMAIN = 'PAM01-PRD01.IBM.COM'
u = raw_input('Enter PAM username: ')
s = getpass.getpass()
connection = hive.connect(host=DEFAULT_SERVER, port= DEFAULT_PORT, authMechanism='LDAP', user=u + '@' + DEFAULT_DOMAIN, password=s)
statement = "select * from user_yuti.Temp_CredCard where pir_post_dt = '2014-05-01' limit 100"
cur = connection.cursor()
cur.execute(statement)
df = cur.fetchall()
In addition to the standard python program, a few libraries need to be installed to allow Python to build the connection to the Hadoop databae.
1.Pyhs2, Python Hive Server 2 Client Driver
2.Sasl, Cyrus-SASL bindings for Python
3.Thrift, Python bindings for the Apache Thrift RPC system
4.PyHive, Python interface to Hive
Remember to change the permission of the executable
chmod +x test_hive2.py ./test_hive2.py
Wish it helps you. Reference: https://sites.google.com/site/tingyusz/home/blogs/hiveinpython
method overloading is an example of compile time/static polymorphism because method binding between method call and method definition happens at compile time and it depends on the reference of the class (reference created at compile time and goes to stack).
method overriding is an example of run time/dynamic polymorphism because method binding between method call and method definition happens at run time and it depends on the object of the class (object created at runtime and goes to the heap).
There are 3 scenarios for using a class helper like SimpleDateFormat in multithread code, which best one is use ThreadLocal
Scenarios
1- Using like share object by the help of lock or synchronization mechanism which makes the app slow
2- Using as a local object inside a method
In this scenario, if we have 4 thread each one calls a method 1000 time then we have
4000 SimpleDateFormat object created and waiting for GC to erase them
3- Using ThreadLocal
if we have 4 thread and we gave to each thread one SimpleDateFormat instance
so we have 4 threads, 4 objects of SimpleDateFormat.
There is no need of lock mechanism and object creation and destruction. (Good time complexity and space complexity)
I faced the same issue and I resolved it by using: max-width: fit-content;
To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
What you tried was df['V1','V2']
this will raise a KeyError
as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]]
.
import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()
The typeof
operator isn't an infix (so the LHS of your example doesn't make sense).
You need to use it like so...
if (typeof a_string == 'string') {
// This is a string.
}
Remember, typeof
is an operator, not a function. Despite this, you will see typeof(var)
being used a lot in the wild. This makes as much sense as var a = 4 + (1)
.
Also, you may as well use ==
(equality comparison operator) since both operands are String
s (typeof
always returns a String
), JavaScript is defined to perform the same steps had I used ===
(strict comparison operator).
As Box9 mentions, this won't detect a instantiated String
object.
You can detect for that with....
var isString = str instanceof String;
...or...
var isString = str.constructor == String;
But this won't work in a multi window
environment (think iframe
s).
You can get around this with...
var isString = Object.prototype.toString.call(str) == '[object String]';
But again, (as Box9 mentions), you are better off just using the literal String
format, e.g. var str = 'I am a string';
.
Thanks to the other answers here and after some experimentation I've created some very useful extension methods:
public static string GetRelativePathFrom(this FileSystemInfo to, FileSystemInfo from)
{
return from.GetRelativePathTo(to);
}
public static string GetRelativePathTo(this FileSystemInfo from, FileSystemInfo to)
{
Func<FileSystemInfo, string> getPath = fsi =>
{
var d = fsi as DirectoryInfo;
return d == null ? fsi.FullName : d.FullName.TrimEnd('\\') + "\\";
};
var fromPath = getPath(from);
var toPath = getPath(to);
var fromUri = new Uri(fromPath);
var toUri = new Uri(toPath);
var relativeUri = fromUri.MakeRelativeUri(toUri);
var relativePath = Uri.UnescapeDataString(relativeUri.ToString());
return relativePath.Replace('/', Path.DirectorySeparatorChar);
}
Important points:
FileInfo
and DirectoryInfo
as method parameters so there is no ambiguity as to what is being worked with. Uri.MakeRelativeUri
expects directories to end with a trailing slash.DirectoryInfo.FullName
doesn't normalize the trailing slash. It outputs whatever path was used in the constructor. This extension method takes care of that for you.The main question for me would be, what are you actually trying to find out? Are you trying to find out, when a certain set of changes was introduced in that file?
You can use git blame
for this, it will anotate each line with a SHA1 and a date when it was changed. git blame
can also tell you when a certain line was deleted or where it was moved if you are interested in that.
If you are trying to find out, when a certain bug was introduced, git bisect
is a very powerfull tool. git bisect
will do a binary search on your history. You can use git bisect start
to start bisecting, then git bisect bad
to mark a commit where the bug is present and git bisect good
to mark a commit which does not have the bug. git will checkout a commit between the two and ask you if it is good or bad. You can usually find the faulty commit within a few steps.
Since I have used git, I hardly ever found the need to manually look through patch histories to find something, since most often git offers me a way to actually look for the information I need.
If you try to think less of how to do a certain workflow, but more in what information you need, you will probably many workflows which (in my opinion) are much more simple and faster.
Adding this script to my code fixed the dropdown menu.
<script>
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
JavaScript is a client-side language and your MySQL database is going to be running on a server.
So you have to rename your file to index.php
for example (.php is important) so you can use php code for that. It is not very difficult, but not directly possible with html.
(Somehow you can tell your server to let the html files behave like php files, but this is not the best solution.)
So after you renamed your file, go to the very top, before <html>
or <!DOCTYPE html>
and type:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
/*Creating variables*/
$name = $_POST["name"];
$address = $_POST["address"];
$age = $_POST["age"];
$dbhost = "localhost"; /*most of the time it's localhost*/
$username = "yourusername";
$password = "yourpassword";
$dbname = "mydatabase";
$mysql = mysqli_connect($dbhost, $username, $password, $dbname); //It connects
$query = "INSERT INTO yourtable (name,address,age) VALUES $name, $address, $age";
mysqli_query($mysql, $query);
}
?>
<!DOCTYPE html>
<html>
<head>.......
....
<form method="post">
<input name="name" type="text"/>
<input name="address" type="text"/>
<input name="age" type="text"/>
</form>
....
use the xclip
which is command line interface to X selections
apt-get install xclip
echo "test xclip " > /tmp/test.xclip
xclip -i < /tmp/test.xclip
xclip -o > /tmp/test.xclip.out
cat /tmp/test.xclip.out # "test xclip"
enjoy.
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
Put the following in your .cs file:
using System.Linq;
You will then be able to use the following extension method from System.Linq.Enumerable:
public static TSource[] ToArray<TSource>(this System.Collections.Generic.IEnumerable<TSource> source)
I.e.
IEnumerable<object> query = ...;
object[] bob = query.ToArray();
you also should specify def name in the project settings here:
Configuration > Properties/Input/Advanced/Module > Definition File
My own version of using Moment in Angular
npm i moment --save
import * as _moment from 'moment';
...
moment: _moment.Moment = _moment();
constructor() { }
ngOnInit() {
const unix = this.moment.format('X');
console.log(unix);
}
First import moment as _moment
, then declare moment
variable with type _moment.Moment
with an initial value of _moment()
.
Plain import of moment wont give you any auto completion but if you will declare moment with type Moment
interface from _moment
namespace from 'moment'
package initialized with moment namespace invoked _moment()
gives you auto completion of moment's api's.
I think this is the most angular way of using moment without using @types
typings
or angular providers, if you're looking auto completion for vanilla javascript libraries like moment.
So, to summarize:
I don't want to make things more confusing but note that Java EE 6 provides modern, standardized and very nice equivalent of the above frameworks: JSF 2.0 and Facelets for the presentation, JPA 2.0 for the persistence, Dependency Injection, etc. For a new development, this is IMO a serious option, Java EE 6 is a great stack.
I ran into similar problems using Python 3.4.3 & 3.5.2 and Django 1.11.3. However, when I upgraded to Python 3.6.1 the problems went away.
You can read more about it here: https://docs.python.org/3/whatsnew/3.6.html#json
If you're not tied to a specific version of Python, just consider upgrading to 3.6 or later.
Your arrayList:
ArrayList<String> yourArray = new ArrayList<>();
Write this code from where you want intent:
Intent newIntent = new Intent(this, NextActivity.class);
newIntent.putExtra("name",yourArray);
startActivity(newIntent);
In Next Activity:
ArrayList<String> myArray = new ArrayList<>();
Write this code in onCreate:
myArray =(ArrayList<String>)getIntent().getSerializableExtra("name");
I had the same problem.
To find out the exact source of it I switched on logging in web.config file:
<aspNetCore processPath="dotnet" arguments=".\MyWebService.dll" stdoutLogEnabled="**true**" stdoutLogFile=".\logs\stdout" />
and created logs subfolder in MyWebService root folder.
After restarting IIS and trying to execute API I got an error and it was missing of proper Core Runtime. After downloading an installing DotNetCore.1.0.5_1.1.2-WindowsHosting the error gone.
Just restart the IDE you are using, then it will work.
With HTML5, you can just create an anchor and click on it. There is no need to add it to the document as a child.
const a = document.createElement('a');
a.download = '';
a.href = urlForPdfFile;
a.click();
All done.
If you want to have a special name for the download, just pass it in the download
attribute:
const a = document.createElement('a');
a.download = 'my-special-name.pdf';
a.href = urlForPdfFile;
a.click();
To print the text my text
you can use either of the following Locator Strategies:
Using class_name
and get_attribute("textContent")
:
print(driver.find_element(By.CLASS_NAME, "current-stage").get_attribute("textContent"))
Using css_selector
and get_attribute("innerHTML")
:
print(driver.find_element(By.CSS_SELECTOR, "span.current-stage").get_attribute("innerHTML"))
Using xpath
and text attribute:
print(driver.find_element(By.XPATH, "//span[@class='current-stage']").text)
Ideally you need to induce WebDriverWait for the visibility_of_element_located()
and you can use either of the following Locator Strategies:
Using CLASS_NAME
and get_attribute("textContent")
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CLASS_NAME, "current-stage"))).get_attribute("textContent"))
Using CSS_SELECTOR
and text attribute:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.current-stage"))).text)
Using XPATH
and get_attribute("innerHTML")
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@class='current-stage']"))).get_attribute("innerHTML"))
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python
Link to useful documentation:
get_attribute()
method Gets the given attribute or property of the element.
text
attribute returns The text of the element.
The data-* attributes is used to store custom data private to the page or application
So Bootstrap uses these attributes for saving states of objects
Oh, I just found that command on PostgreSQL forum:
SELECT * FROM pg_stat_activity;
If you like to use a GUI, you can perform the entire operation with gitk.
gitk --reflog
This will allow you to see the branch's commit history as if the branch hadn't been deleted. Now simply right click on the most recent commit to the branch and select the menu option Create new branch
.
What I do so I don't specify a time zone is,
System.out.println("ldt " + LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
System.out.println("ctm " + System.currentTimeMillis());
gives
ldt 1424812121078
ctm 1424812121281
As you can see the numbers are the same except for a small execution time.
Just in case you don't like System.currentTimeMillis, use Instant.now().toEpochMilli()
Use composition:
class ClassC
{
public ClassA A { get; set; }
public ClassB B { get; set; }
public C (ClassA a, ClassB b)
{
this.A = a;
this.B = b;
}
}
Then you can call C.A.DoA()
. You also can change the properties to an interface or abstract class, like public InterfaceA A
or public AbstractClassA A
.
I figured out the answer to above problem. Below query will return rows which have even a signle occurrence of characters besides alphabets, numbers, square brackets, curly brackets,s pace and dot. Please note that position of closing bracket ']' in matching pattern is important.
Right ']' has the special meaning of ending a character set definition. It wouldn't make any sense to end the set before you specified any members, so the way to indicate a literal right ']' inside square brackets is to put it immediately after the left '[' that starts the set definition
SELECT * FROM test WHERE REGEXP_LIKE(sampletext, '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );
GridLayout is often not the best choice for buttons, although it might be for your application. A good reference is the tutorial on using Layout Managers. If you look at the GridLayout example, you'll see the buttons look a little silly -- way too big.
A better idea might be to use a FlowLayout for your buttons, or if you know exactly what you want, perhaps a GroupLayout. (Sun/Oracle recommend that GroupLayout or GridBag layout are better than GridLayout when hand-coding.)
Thanks to Chris for his awesome answer, I took it one step further and automated the process of running those statements (my table had over 8,000 permissions)
if object_id('dbo.tempPermissions') is not null
Drop table dbo.tempPermissions
Create table tempPermissions(ID int identity , Queries Varchar(255))
Insert into tempPermissions(Queries)
select 'GRANT ' + dp.permission_name collate latin1_general_cs_as
+ ' ON ' + s.name + '.' + o.name + ' TO ' + dpr.name
FROM sys.database_permissions AS dp
INNER JOIN sys.objects AS o ON dp.major_id=o.object_id
INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id
INNER JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
WHERE dpr.name NOT IN ('public','guest')
declare @count int, @max int, @query Varchar(255)
set @count =1
set @max = (Select max(ID) from tempPermissions)
set @query = (Select Queries from tempPermissions where ID = @count)
while(@count < @max)
begin
exec(@query)
set @count += 1
set @query = (Select Queries from tempPermissions where ID = @count)
end
select * from tempPermissions
drop table tempPermissions
additionally to restrict it to a single table add:
and o.name = 'tablename'
after the WHERE dpr.name NOT IN ('public','guest') and remember to edit the select statement so that it generates statements for the table you want to grant permissions 'TO' Not the table the permissions are coming 'FROM' (which is what the script does).
As a noobie I was confused by this until I realized that the so called "path" is the path relative to the MyClass.class file in the file system and not the MyClass.java file. My IDE copies the resources (like xx.jpg, xx.xml) to a directory local to the MyClass.class. For example, inside a pkg directory called "target/classes/pkg. The class-file location may be different for different IDE's and depending on how the build is structured for your application. You should first explore the file system and find the location of the MyClass.class file and the copied location of the associated resource you are seeking to extract. Then determine the path relative to the MyClass.class file and write that as a string value with "dots" and "slashes".
For example, here is how I make an app1.fxml file available to my javafx application where the relevant "MyClass.class" is implicitly "Main.class". The Main.java file is where this line of resource-calling code is contained. In my specific case the resources are copied to a location at the same level as the enclosing package folder. That is: /target/classes/pkg/Main.class and /target/classes/app1.fxml. So paraphrasing...the relative reference "../app1.fxml" is "start from Main.class, go up one directory level, now you can see the resource".
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("../app1.fxml"));
Note that in this relative-path string "../app1.fxml", the first two dots reference the directory enclosing Main.class and the single "." indicates a file extension to follow. After these details become second nature, you will forget why it was confusing.
You can use this:
select {
width:100px;
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
}
select option {
width:100px;
text-overflow:ellipsis;
overflow:hidden;
}
div {
border-style:solid;
width:100px;
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
}
I implemented UIGestureRecognizerDelegate methods to detect both singleTap and doubleTap.
Just do this .
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTapGesture:)];
[doubleTap setDelegate:self];
doubleTap.numberOfTapsRequired = 2;
[self.headerView addGestureRecognizer:doubleTap];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTapGesture:)];
singleTap.numberOfTapsRequired = 1;
[singleTap setDelegate:self];
[doubleTap setDelaysTouchesBegan:YES];
[singleTap setDelaysTouchesBegan:YES];
[singleTap requireGestureRecognizerToFail:doubleTap];
[self.headerView addGestureRecognizer:singleTap];
Then implement these delegate methods.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
I have resolved this problem by adding or changing variables in environment variables. Go to Win7 -> My Computer - > Properties - > Advanced system settings -> environment Variables
Good Luck
BEGIN
-END
blocks are the building blocks of PL/SQL, and each PL/SQL unit is contained within at least one such block. Nesting BEGIN
-END
blocks within PL/SQL blocks is usually done to trap certain exceptions and handle that special exception and then raise unrelated exceptions. Nevertheless, in PL/SQL you (the client) must always issue a commit or rollback for the transaction.
If you wish to have atomic transactions within a PL/SQL containing transaction, you need to declare a PRAGMA AUTONOMOUS_TRANSACTION
in the declaration block. This will ensure that any DML within that block can be committed or rolledback independently of the containing transaction.
However, you cannot declare this pragma for nested blocks. You can only declare this for:
Reference: Oracle
I resolved with the code below:
set escape on
and put a \ beside & in the left 'value_\&_intert'
Att
<style>
a:hover {
cursor:pointer;
}
</style>
<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".link").click(function(){
var href = $(this).attr("href").split("#");
$(".results").text(href[1]);
})
})
</script>
<a class="link" href="#one">one</a><br />
<a class="link" href="#two">two</a><br />
<a class="link" href="#three">three</a><br />
<a class="link" href="#four">four</a><br />
<a class="link" href="#five">five</a>
<br /><br />
<div class="results"></div>
This is a bit circuitous because touch
doesn't take a raw time_t
value, but it should do the job pretty safely in a script. (The -r
option to date
is present in MacOS X; I've not double-checked GNU.) The 'time' variable could be avoided by writing the command substitution directly in the touch
command line.
time=$(date -r 1312603983 '+%Y%m%d%H%M.%S')
marker=/tmp/marker.$$
trap "rm -f $marker; exit 1" 0 1 2 3 13 15
touch -t $time $marker
find . -type f -newer $marker
rm -f $marker
trap 0
Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL
I'm not sure what version of Windows introduced this command.
To encode a file:
certutil -encode inputFileName encodedOutputFileName
To decode a file:
certutil -decode encodedInputFileName decodedOutputFileName
There are a number of available verbs and options available to CERTUTIL.
To get a list of nearly all available verbs:
certutil -?
To get help on a particular verb (-encode for example):
certutil -encode -?
To get complete help for nearly all verbs:
certutil -v -?
Mysteriously, the -encodehex
verb is not listed with certutil -?
or certutil -v -?
. But it is described using certutil -encodehex -?
. It is another handy function :-)
Regarding David Morales' comment, there is a poorly documented type option to the -encodehex
verb that allows creation of base64 strings without header or footer lines.
certutil [Options] -encodehex inFile outFile [type]
A type of 1 will yield base64 without the header or footer lines.
See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.
Not investigated, but the -decodehex
verb also has an optional trailing type argument.
import static net.minidev.json.JSONValue.isValidJson;
and then call this function passing in your JSON String :)
A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.
For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.
Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.
However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.
Read the Security section of the PHP manual as a starting point to keeping your code safe.
You can use the --unset
flag of git config
to do this like so:
git config --global --unset user.name
git config --global --unset user.email
If you have more variables for one config you can use:
git config --global --unset-all user.name
I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.
Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!
Hope to help
That's where constructors come into play. If you have a default constructor (eg. with no parameters) that always creates a new Map, then you're sure that every instance of this class will always have an already instantiated Map.
The path is in the registry but usually you edit through this interface:
Control Panel
-> System
-> System settings
-> Environment Variables
.PATH
.c:\path;c:\path2
Since your controller actions execute on the server, and JavaScript (usually) executes on the client (browser), this doesn't make sense. If you need some action to happen by default once the page is loaded into the browser, you can use JavaScript's document.OnLoad event handler.
Formatter will work fine in this case.
import org.apache.poi.ss.usermodel.DataFormatter;
FileInputStream fis = new FileInputStream(workbookName);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheet(sheetName);
DataFormatter formatter = new DataFormatter();
String val = formatter.formatCellValue(sheet.getRow(row).getCell(col));
list.add(val); //Adding value to list
The steel is far from hot, but I combined @abatishchev's solution with the answer from this post and got to this result. Hope it's useful:
public static class GlobalVars
{
private const string GlobalKey = "AllMyVars";
static GlobalVars()
{
Hashtable table = HttpContext.Current.Application[GlobalKey] as Hashtable;
if (table == null)
{
table = new Hashtable();
HttpContext.Current.Application[GlobalKey] = table;
}
}
public static Hashtable Vars
{
get { return HttpContext.Current.Application[GlobalKey] as Hashtable; }
}
public static IEnumerable<SomeClass> SomeCollection
{
get { return GetVar("SomeCollection") as IEnumerable<SomeClass>; }
set { WriteVar("SomeCollection", value); }
}
internal static DateTime SomeDate
{
get { return (DateTime)GetVar("SomeDate"); }
set { WriteVar("SomeDate", value); }
}
private static object GetVar(string varName)
{
if (Vars.ContainsKey(varName))
{
return Vars[varName];
}
return null;
}
private static void WriteVar(string varName, object value)
{
if (value == null)
{
if (Vars.ContainsKey(varName))
{
Vars.Remove(varName);
}
return;
}
if (Vars[varName] == null)
{
Vars.Add(varName, value);
}
else
{
Vars[varName] = value;
}
}
}
I had a list of file names, and I wanted to exclude certain ones, with this sort of behavior (Ruby):
files = [
'mydir/states.rb', # don't match these
'countries.rb',
'mydir/states_bkp.rb', # match these
'mydir/city_states.rb'
]
excluded = ['states', 'countries']
# set my_rgx here
result = WankyAPI.filter(files, my_rgx) # I didn't write WankyAPI...
assert result == ['mydir/city_states.rb', 'mydir/states_bkp.rb']
Here's my solution:
excluded_rgx = excluded.map{|e| e+'\.'}.join('|')
my_rgx = /(^|\/)((?!#{excluded_rgx})[^\.\/]*)\.rb$/
My assumptions for this application:
.rb
..
character before the .rb
.new Thing();
is explicit that you want a constructor called whereas new Thing;
is taken to imply you don't mind if the constructor isn't called.
If used on a struct/class with a user-defined constructor, there is no difference. If called on a trivial struct/class (e.g. struct Thing { int i; };
) then new Thing;
is like malloc(sizeof(Thing));
whereas new Thing();
is like calloc(sizeof(Thing));
- it gets zero initialized.
The gotcha lies in-between:
struct Thingy {
~Thingy(); // No-longer a trivial class
virtual WaxOn();
int i;
};
The behavior of new Thingy;
vs new Thingy();
in this case changed between C++98 and C++2003. See Michael Burr's explanation for how and why.
Your'e almost there, you just need to get the properties from the type, rather than expect the properties to be accessible in the form of a collection or property bag:
var property in obj.GetType().GetProperties()
From there you can access like so:
property.Name
property.GetValue(obj, null)
With GetValue
the second parameter will allow you to specify index values, which will work with properties returning collections - since a string is a collection of chars, you can also specify an index to return a character if needs be.
Remove the extension altogether and then double-click it. Most system shell scripts are like this. As long as it has a shebang it will work.
Installation of multiple versions of Python and respective Packages.
Python version on the same windows machine : 2.7 , 3.4 and 3.6
Installation of all 3 versions of Python :
PATH for all 3 versions of Python :
Renaming the executables for versions :
Checked for the command prompt with all versions :
Installing the packages separately for each version
My Problem was from init.py . i made an app and wanted to do this :
from MY_APP import myfunc
instead of :
from MY_APP.views import myfunc
when i rolled back my changes to these parts . everything worked just fine.
I wouldn't bother looking for ASP.NET stuff specifically (probably won't find any anyways). Finding a good CSS theme easily can be used in ASP.NET.
Here's some sites that I love for CSS goodness:
http://www.freecsstemplates.org/
http://www.oswd.org/
http://www.openwebdesign.org/
http://www.styleshout.com/
http://www.freelayouts.com/
var ctrlKeyDown = false;
$(document).ready(function(){
$(document).on("keydown", keydown);
$(document).on("keyup", keyup);
});
function keydown(e) {
if ((e.which || e.keyCode) == 116 || ((e.which || e.keyCode) == 82 && ctrlKeyDown)) {
// Pressing F5 or Ctrl+R
e.preventDefault();
} else if ((e.which || e.keyCode) == 17) {
// Pressing only Ctrl
ctrlKeyDown = true;
}
};
function keyup(e){
// Key up Ctrl
if ((e.which || e.keyCode) == 17)
ctrlKeyDown = false;
};
I Concatenated my formula as normal but at the start I had '=
instead of =
.
Then I copy and paste as text to where I need it. Then I highlight the section saved as text and press ctrl + H to find and replace.
I replace '=
with =
and all of my functions are active.
Its a few stages but it avoids VBA.
I hope this helps,
Rob
In addition to substring answer, you can do it as mystring.SubString(0,3) and check in case statement if its "abc".
But before the switch statement you need to ensure that your mystring is atleast 3 in length.
Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.
Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:
TableModel datePicker = new DatePickerTable("01011999","12302000");
Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:
datePicker.interval = 15;
Attach your table model into your JTable:
JTable newtable = new JTable (datePicker);
Your Java application now has a drop-down date selection dialog.
import numpy as np
mylist = [3, 4, 5, np.nan]
l = [x for x in mylist if ~np.isnan(x)]
This should remove all NaN. Of course, I assume that it is not a string here but actual NaN (np.nan
).
If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.
What you can take away from my example: I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.
In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:
Front end code:
<div onclick="showHideModal();">
<asp:Calendar
OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server"
BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana"
Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%">
<OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle>
<DayHeaderStyle ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
<TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle>
<DayStyle BackColor="White"> </DayStyle>
<SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle>
</asp:Calendar>
</div>
Codebehind:
protected void DatepickerDateChange(object sender, EventArgs e)
{
if (toFromPicked.Value == "MainContent_fromDate")
{
fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
}
else
{
toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
}
}
Technically you can write code in a .NET language and use the Mono Framework (http://www.mono-project.com/) to run it on the iPhone. I haven't ever seen someone do this from scratch, but the folks that write the Unity Game Development platform (http://unity3d.com/) use it to make their games iPhone-compatible. The game itself is written in .NET, and then they provide an iPhone shell with the Mono frameworks that allows everything to run on the iPhone. I don't know whether they've contributed all of their modifications to Mono back to the open-source repository, but if you're serious about writing iPhone apps outside the Mac environment, it might be possible.
That said, I think you could dump weeks into getting that to work, and it might be best to invest in a Mac instead :-)
Take a look at the java.text.MessageFormat
class, MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.
Object[] params = new Object[]{"hello", "!"};
String msg = MessageFormat.format("{0} world {1}", params);
See the crypto.createHash()
function and the associated hash.update()
and hash.digest()
functions:
var crypto = require('crypto')
var shasum = crypto.createHash('sha1')
shasum.update('foo')
shasum.digest('hex') // => "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
The short-circuiting boolean operators (and
, or
) can't be overriden because there is no satisfying way to do this without introducing new language features or sacrificing short circuiting. As you may or may not know, they evaluate the first operand for its truth value, and depending on that value, either evaluate and return the second argument, or don't evaluate the second argument and return the first:
something_true and x -> x
something_false and x -> something_false
something_true or x -> something_true
something_false or x -> x
Note that the (result of evaluating the) actual operand is returned, not truth value thereof.
The only way to customize their behavior is to override __nonzero__
(renamed to __bool__
in Python 3), so you can affect which operand gets returned, but not return something different. Lists (and other collections) are defined to be "truthy" when they contain anything at all, and "falsey" when they are empty.
NumPy arrays reject that notion: For the use cases they aim at, two different notions of truth are common: (1) Whether any element is true, and (2) whether all elements are true. Since these two are completely (and silently) incompatible, and neither is clearly more correct or more common, NumPy refuses to guess and requires you to explicitly use .any()
or .all()
.
&
and |
(and not
, by the way) can be fully overriden, as they don't short circuit. They can return anything at all when overriden, and NumPy makes good use of that to do element-wise operations, as they do with practically any other scalar operation. Lists, on the other hand, don't broadcast operations across their elements. Just as mylist1 - mylist2
doesn't mean anything and mylist1 + mylist2
means something completely different, there is no &
operator for lists.
Also, if your service is sending an object instead of an array add isArray:false to its declaration.
'query': {method: 'GET', isArray: false }
since you mentioned you are quite new to access, i had to invite you to first remove the errors in the code (the incomplete for loop and the SQL statement). Otherwise, you surely need the for loop to insert dates in a certain range.
Now, please use the code below to insert the date values into your table. I have tested the code and it works. You can try it too. After that, add your for loop to suit your scenario
Dim StrSQL As String
Dim InDate As Date
Dim DatDiff As Integer
InDate = Me.FromDateTxt
StrSQL = "INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
The change
event is limited to input
, textarea
& and select
.
See http://api.jquery.com/change/ for more information.
You need to create a new Font
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
You should check this MSDN article and download the .docx file and read it carefully , it was very helpful for me.
However this is a class which works fine for my case :
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SECURITY_ATTRIBUTES
{
public uint nLength;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
internal enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
internal enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}
public static class ProcessAsUser
{
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool CreateProcessAsUser(
IntPtr hToken,
string lpApplicationName,
string lpCommandLine,
ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx", SetLastError = true)]
private static extern bool DuplicateTokenEx(
IntPtr hExistingToken,
uint dwDesiredAccess,
ref SECURITY_ATTRIBUTES lpThreadAttributes,
Int32 ImpersonationLevel,
Int32 dwTokenType,
ref IntPtr phNewToken);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(
IntPtr ProcessHandle,
UInt32 DesiredAccess,
ref IntPtr TokenHandle);
[DllImport("userenv.dll", SetLastError = true)]
private static extern bool CreateEnvironmentBlock(
ref IntPtr lpEnvironment,
IntPtr hToken,
bool bInherit);
[DllImport("userenv.dll", SetLastError = true)]
private static extern bool DestroyEnvironmentBlock(
IntPtr lpEnvironment);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(
IntPtr hObject);
private const short SW_SHOW = 5;
private const uint TOKEN_QUERY = 0x0008;
private const uint TOKEN_DUPLICATE = 0x0002;
private const uint TOKEN_ASSIGN_PRIMARY = 0x0001;
private const int GENERIC_ALL_ACCESS = 0x10000000;
private const int STARTF_USESHOWWINDOW = 0x00000001;
private const int STARTF_FORCEONFEEDBACK = 0x00000040;
private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock)
{
bool result = false;
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
saThread.nLength = (uint)Marshal.SizeOf(saThread);
STARTUPINFO si = new STARTUPINFO();
si.cb = (uint)Marshal.SizeOf(si);
//if this member is NULL, the new process inherits the desktop
//and window station of its parent process. If this member is
//an empty string, the process does not inherit the desktop and
//window station of its parent process; instead, the system
//determines if a new desktop and window station need to be created.
//If the impersonated user already has a desktop, the system uses the
//existing desktop.
si.lpDesktop = @"WinSta0\Default"; //Modify as needed
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;
si.wShowWindow = SW_SHOW;
//Set other si properties as required.
result = CreateProcessAsUser(
token,
null,
cmdLine,
ref saProcess,
ref saThread,
false,
CREATE_UNICODE_ENVIRONMENT,
envBlock,
null,
ref si,
out pi);
if (result == false)
{
int error = Marshal.GetLastWin32Error();
string message = String.Format("CreateProcessAsUser Error: {0}", error);
FilesUtilities.WriteLog(message,FilesUtilities.ErrorType.Info);
}
return result;
}
private static IntPtr GetPrimaryToken(int processId)
{
IntPtr token = IntPtr.Zero;
IntPtr primaryToken = IntPtr.Zero;
bool retVal = false;
Process p = null;
try
{
p = Process.GetProcessById(processId);
}
catch (ArgumentException)
{
string details = String.Format("ProcessID {0} Not Available", processId);
FilesUtilities.WriteLog(details, FilesUtilities.ErrorType.Info);
throw;
}
//Gets impersonation token
retVal = OpenProcessToken(p.Handle, TOKEN_DUPLICATE, ref token);
if (retVal == true)
{
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.nLength = (uint)Marshal.SizeOf(sa);
//Convert the impersonation token into Primary token
retVal = DuplicateTokenEx(
token,
TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY,
ref sa,
(int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
(int)TOKEN_TYPE.TokenPrimary,
ref primaryToken);
//Close the Token that was previously opened.
CloseHandle(token);
if (retVal == false)
{
string message = String.Format("DuplicateTokenEx Error: {0}", Marshal.GetLastWin32Error());
FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);
}
}
else
{
string message = String.Format("OpenProcessToken Error: {0}", Marshal.GetLastWin32Error());
FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);
}
//We'll Close this token after it is used.
return primaryToken;
}
private static IntPtr GetEnvironmentBlock(IntPtr token)
{
IntPtr envBlock = IntPtr.Zero;
bool retVal = CreateEnvironmentBlock(ref envBlock, token, false);
if (retVal == false)
{
//Environment Block, things like common paths to My Documents etc.
//Will not be created if "false"
//It should not adversley affect CreateProcessAsUser.
string message = String.Format("CreateEnvironmentBlock Error: {0}", Marshal.GetLastWin32Error());
FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);
}
return envBlock;
}
public static bool Launch(string appCmdLine /*,int processId*/)
{
bool ret = false;
//Either specify the processID explicitly
//Or try to get it from a process owned by the user.
//In this case assuming there is only one explorer.exe
Process[] ps = Process.GetProcessesByName("explorer");
int processId = -1;//=processId
if (ps.Length > 0)
{
processId = ps[0].Id;
}
if (processId > 1)
{
IntPtr token = GetPrimaryToken(processId);
if (token != IntPtr.Zero)
{
IntPtr envBlock = GetEnvironmentBlock(token);
ret = LaunchProcessAsUser(appCmdLine, token, envBlock);
if (envBlock != IntPtr.Zero)
DestroyEnvironmentBlock(envBlock);
CloseHandle(token);
}
}
return ret;
}
}
And to execute , simply call like this :
string szCmdline = "AbsolutePathToYourExe\\ExeNameWithoutExtension";
ProcessAsUser.Launch(szCmdline);
2018 here, this is what I do:
$(inputs).on('change keydown paste input propertychange click keyup blur',handler);
If you can point out flaws in this approach, I would be grateful.
Windows.System.UserProfile.GlobalizationPreferences.Languages[0]
This is the correct way to obtain the currently set system language. System language setting is completely different than culture setting from which you all want to get the language.
For example: User may use "en-GB" language along with "en-US" culture at the same time. Using CurrentCulture and other cultures you will get "en-US", hope you get the difference (that may be innoticable with GB-US, but with other languages?)
You can include the following lines in the file you want to debug:
error_reporting(E_ALL);
ini_set('display_errors', '1');
This overrides the default settings in php.ini, which just make PHP report the errors to the log.
new table inherits only "not null" constraint and no other constraint. Thus you can alter the table after creating it with "create table as" command or you can define all constraint that you need by following the
create table t1 (id number default 1 not null);
insert into t1 (id) values (2);
create table t2 as select * from t1;
This will create table t2 with not null constraint. But for some other constraint except "not null" you should use the following syntax
create table t1 (id number default 1 unique);
insert into t1 (id) values (2);
create table t2 (id default 1 unique)
as select * from t1;
As an alternative you can try testing exceptions are in fact being thrown with the next 2 lines in your test.
var testDelegate = () => MyService.Method(params);
Assert.Throws<Exception>(testDelegate);
Right click on your project > Open Module Setting > Select "Project" in "Project Setting" section
Change the Project SDK to latest(may be API 21) and Project language level to 7+
Here's a simpler solution using what Akhil Sekharan has provided but with a little change.
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i += 1) {
if(parseInt(inputs[i].value)){
inputs[i].value = '';
}
}????
document.getElementById('total').value = total;
Just create a data.frame
with 0 length variables
eg
nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)
## 'data.frame': 0 obs. of 3 variables:
## $ x: num
## $ y: int
## $ z: Factor w/ 0 levels:
or to create a data.frame with 5 columns named a,b,c,d,e
nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))
Remember that collections in C# are zero-based (in other words, the first item in a collection is at position zero). If you have two items in your list, and you want to select the last item, use SelectedIndex = 1
.
Try annotating your Configuration Class(es) with the @ComponentScan("com.esri.birthdays")
annotation.
Generally spoken: If you have sub-packages in your project, then you have to scan for your relevant classes on project-root. I guess for your case it'll be "com.esri.birthdays".
You won't need the ComponentScan, if you have no sub-packaging in your project.
If you are using the Mono toolchain, you can use the monodis
utility with the --assemblyref
argument to list the dependencies of a .NET assembly. This will work on both .exe
and .dll
files.
monodis --assemblyref somefile.exe
$ monodis --assemblyref monop.exe
AssemblyRef Table
1: Version=4.0.0.0
Name=System
Flags=0x00000000
Public Key:
0x00000000: B7 7A 5C 56 19 34 E0 89
2: Version=4.0.0.0
Name=mscorlib
Flags=0x00000000
Public Key:
0x00000000: B7 7A 5C 56 19 34 E0 89
$ monodis --assemblyref Mono.CSharp.dll
AssemblyRef Table
1: Version=4.0.0.0
Name=mscorlib
Flags=0x00000000
Public Key:
0x00000000: B7 7A 5C 56 19 34 E0 89
2: Version=4.0.0.0
Name=System.Core
Flags=0x00000000
Public Key:
0x00000000: B7 7A 5C 56 19 34 E0 89
3: Version=4.0.0.0
Name=System
Flags=0x00000000
Public Key:
0x00000000: B7 7A 5C 56 19 34 E0 89
4: Version=4.0.0.0
Name=System.Xml
Flags=0x00000000
Public Key:
0x00000000: B7 7A 5C 56 19 34 E0 89
What you describe is the correct way to handle this.
You said that you want to stay in the GUI. You can usually set the execute bit through the file properties menu. You could also learn how to create a custom action for the context menu to do this for you if you're so inclined. This depends on your desktop environment of course.
If you use a more advanced editor, you can script the action to happen when the file is saved. For example (I'm only really familiar with vim), you could add this to your .vimrc to make any new file that starts with "#!/*/bin/*
" executable.
au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod +x <afile> | endif | endif
Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.
As a very blunt hammer, useful for testing, you can use the enable_seqscan
and enable_indexscan
parameters. See:
These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_
params and walk away.
Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?
See also this old newsgroup post.
Include the facebook button on the page which you want to share
<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://trial.com/news.php?newsid=<?php echo $content; ?>">
<img src="http://trial/new_img/facebook_link.png" style=" border: 1px solid #d9d9d9; box-shadow: 0 4px 7px 0 #a5a5a5; padding: 5px;" title="facebook_link" alt="facebook_link" />
</a>
It seems from your question that you would like to simply increment the year of your given date rather than worry about leap year implications. You can use the date class to do this by accessing its member year.
from datetime import date
startDate = date(2012, 12, 21)
# reconstruct date fully
endDate = date(startDate.year + 1, startDate.month, startDate.day)
# replace year only
endDate = startDate.replace(startDate.year + 1)
If you're having problems creating one given your format, let us know.
I got same problem lot of time. Check your request url, if you are requesting on local server like 127.1.1/api or 192.168...., try to change it, make sure you are hitting cloud.
First pre-generate column names, second use rs.getString(i)
instead of rs.getString(column_name)
.
The following is an implementation of this:
/*
* Convert ResultSet to a common JSON Object array
* Result is like: [{"ID":"1","NAME":"Tom","AGE":"24"}, {"ID":"2","NAME":"Bob","AGE":"26"}, ...]
*/
public static List<JSONObject> getFormattedResult(ResultSet rs) {
List<JSONObject> resList = new ArrayList<JSONObject>();
try {
// get column names
ResultSetMetaData rsMeta = rs.getMetaData();
int columnCnt = rsMeta.getColumnCount();
List<String> columnNames = new ArrayList<String>();
for(int i=1;i<=columnCnt;i++) {
columnNames.add(rsMeta.getColumnName(i).toUpperCase());
}
while(rs.next()) { // convert each object to an human readable JSON object
JSONObject obj = new JSONObject();
for(int i=1;i<=columnCnt;i++) {
String key = columnNames.get(i - 1);
String value = rs.getString(i);
obj.put(key, value);
}
resList.add(obj);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return resList;
}
I have seen solutions for aligning drawable at start/left but nothing for drawable end/right, so I came up with this solution. It uses dynamically calculated paddings for aligning drawable and text on both left and right side.
class IconButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = R.attr.buttonStyle
) : AppCompatButton(context, attrs, defStyle) {
init {
maxLines = 1
}
override fun onDraw(canvas: Canvas) {
val buttonContentWidth = (width - paddingLeft - paddingRight).toFloat()
val textWidth = paint.measureText(text.toString())
val drawable = compoundDrawables[0] ?: compoundDrawables[2]
val drawableWidth = drawable?.intrinsicWidth ?: 0
val drawablePadding = if (textWidth > 0 && drawable != null) compoundDrawablePadding else 0
val bodyWidth = textWidth + drawableWidth.toFloat() + drawablePadding.toFloat()
canvas.save()
val padding = (buttonContentWidth - bodyWidth).toInt() / 2
val leftOrRight = if (compoundDrawables[0] != null) 1 else -1
setPadding(leftOrRight * padding, 0, -leftOrRight * padding, 0)
super.onDraw(canvas)
canvas.restore()
}
}
It is important to set gravity in your layout to either "center_vertical|start" or "center_vertical|end" depending on where do you set the icon. For example:
<com.stackoverflow.util.IconButton
android:id="@+id/cancel_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableStart="@drawable/cancel"
android:drawablePadding="@dimen/padding_small"
android:gravity="center_vertical|start"
android:text="Cancel" />
Only problem with this implementation is that button can only have single line of text, otherwise the area of the text fills the button and paddings will be 0.
The particular format for strptime
:
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)
Native Documents (in which I have an interest) makes a viewer (and editor) specifically for Word documents (both legacy binary .doc and modern docx formats). It does so without lossy conversion to HTML. Here's how to get started https://github.com/NativeDocuments/nd-WordFileEditor/blob/master/README.md
The problem is caused by the fact that cmbDataSourceExtractor.CancelAsync()
is an asynchronous method, the Cancel
operation has not yet completed when cmdDataSourceExtractor.RunWorkerAsync(...)
exitst. You should wait for cmdDataSourceExtractor
to complete before calling RunWorkerAsync
again. How to do this is explained in this SO question.
Just adding some more operations on data. Suppose we have a dataframe df
, we can do several operations to get desired outputs
ID cost tax label
1 216590 1600 test
2 523213 1800 test
3 250 1500 experiment
(df['label'].value_counts().to_frame().reset_index()).sort_values('label', ascending=False)
will give sorted
output of labels as a dataframe
index label
0 test 2
1 experiment 1
It should be mentioned that the Accept
header tells the server something about what we are accepting back, whereas the relevant header in this context is Content-Type
It's often advisable to specify Content-Type
as application/json
when sending JSON. For curl the syntax is:
-H 'Content-Type: application/json'
So the complete curl command will be:
curl -H 'Content-Type: application/json' -H 'Accept: application/json' -X PUT -d '{"tags":["tag1","tag2"],"question":"Which band?","answers":[{"id":"a0","answer":"Answer1"},{"id":"a1","answer":"answer2"}]}' http://example.com/service`
at the lowest level, a framework is an environment, where you are given a set of tools to work with
this tools come in the form of libraries, configuration files, etc.
this so-called "environment" provides you with the basic setup (error reportings, log files, language settings, etc)...which can be modified,extended and built upon.
People actually do not need frameworks, it's just a matter of wanting to save time, and others just a matter of personal preferences.
People will justify that with a framework, you don't have to code from scratch. But those are just people confusing libraries with frameworks.
I'm not being biased here, I am actually using a framework right now.
I think the simplest solution is:
window.scrollTo({top: 0, behavior: 'smooth'});
If you wanted instant scrolling then just use:
window.scrollTo({top: 0});
Can be used as a function:
// Scroll To Top
function scrollToTop() {
window.scrollTo({top: 0, behavior: 'smooth'});
}
Or as an onclick handler:
<button onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Scroll to Top</button>
It depends on nature of your data. The answer varies based on its size and data type. I saw a lot of SQL solutions based on ORDER BY
. I would like to suggest javascript alternatives.
In all answers, I don't see anyone mentioning pagination problem for your future table. Let's make it easier for you. If your table doesn't have pagination, it's more likely that a javascript solution makes everything neat and clean for you on the client side. If you think this table will explode after you put data in it, you have to think about pagination as well. (you have to go to first page every time when you change the sorting column)
Another aspect is the data type. If you use SQL you have to be careful about the type of your data and what kind of sorting suites for it. For example, if in one of your VARCHAR columns you store integer numbers, the sorting will not take their integer value into account: instead of 1, 2, 11, 22
you will get 1, 11, 2, 22
.
You can find jquery plugins or standalone javascript sortable tables on google. It worth mentioning that the <table>
in HTML5 has sortable
attribute, but apparently it's not implemented yet.
HTML page
<div id="overlay">
<img src="<?php echo base_url()?>assest/website/images/loading1.gif" alt="Loading" />
Loading...
</div>
Script
$(window).load(function(){
//PAGE IS FULLY LOADED
//FADE OUT YOUR OVERLAYING DIV
$('#overlay').fadeOut();
});
Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).
Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?
// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;
int main()
{
pt::ptime current_date_microseconds = pt::microsec_clock::local_time();
long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();
pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);
pt::ptime current_date_milliseconds(current_date_microseconds.date(),
current_time_milliseconds);
std::cout << "Microseconds: " << current_date_microseconds
<< " Milliseconds: " << current_date_milliseconds << std::endl;
// Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}
Three ways you can do this - from the form designer, select the form, and where you normally see the list of properties, just above it there should be a little lightning symbol - this shows you all the events of the form. Find the form load event in the list, and you should be able to pick ProgramViwer_Load
from the dropdown.
A second way to do it is programmatically - somewhere (constructor maybe) you'd need to add it, something like: ProgramViwer.Load += new EventHandler(ProgramViwer_Load);
A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code. Then you can just add your two lines and you're good to go!
Many answers are already there, I just need to identify one difference which is not there.
for loop is fail-safe while foreach loop is fail-fast.
Fail-fast iteration throws ConcurrentModificationException
if iteration and modification are done at the same time in object.
However, fail-safe iteration keeps the operation safe from failing even if the iteration goes in infinite loop.
public class ConcurrentModification {
public static void main(String[] args) {
List<String> str = new ArrayList<>();
for(int i=0; i<1000; i++){
str.add(String.valueOf(i));
}
/**
* this for loop is fail-safe. It goes into infinite loop but does not fail.
*/
for(int i=0; i<str.size(); i++){
System.out.println(str.get(i));
str.add(i+ " " + "10");
}
/**
* throws ConcurrentModificationexception
for(String st: str){
System.out.println(st);
str.add("10");
}
*/
/* throws ConcurrentModificationException
Iterator<String> itr = str.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
str.add("10");
}*/
}
}
Hope this helps to understand the difference between for and foreach loop through different angle.
I found a good blog to go through the differences between fail-safe and fail-fast, if anyone interested:
To diagnose this error quickly drop to a terminal or use the terminal built into Android Studio (accessible on in bottom status bar). Change to the main directory for your PROJECT (where settings.gradle
is located).
1.) Check to make sure your settings.gradle
includes the subproject. Something like this. This ensures your multi-project build knows about your library sub-project.
include ':apps:App1', ':apps:App2', ':library:Lib1'
Where the text between the colons are sub-directories.
2.) Run the following gradle command just see if Gradle can give you a list of tasks for the library. Use the same qualifier in the settings.gradle
definition. This will uncover issues with the Library build script in isolation.
./gradlew :library:Lib1:tasks --info
3.) Make sure the output from the last step listed an "assembleDefault" task. If it didn't make sure the Library is including the Android Library plugin in build.gradle
. Like this at the very top.
apply plugin: 'com.android.library'
I know the original poster's question was answered but I believe the answer has evolved over the past year and I think there are multiple reasons for the error. I think this resolution flow should assist those who run into the various issues.
use this Tutorial
<?php
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
function arrayToObject($d) {
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return (object) array_map(__FUNCTION__, $d);
}
else {
// Return object
return $d;
}
}
// Create new stdClass Object
$init = new stdClass;
// Add some test data
$init->foo = "Test data";
$init->bar = new stdClass;
$init->bar->baaz = "Testing";
$init->bar->fooz = new stdClass;
$init->bar->fooz->baz = "Testing again";
$init->foox = "Just test";
// Convert array to object and then object back to array
$array = objectToArray($init);
$object = arrayToObject($array);
// Print objects and array
print_r($init);
echo "\n";
print_r($array);
echo "\n";
print_r($object);
//OUTPUT
stdClass Object
(
[foo] => Test data
[bar] => stdClass Object
(
[baaz] => Testing
[fooz] => stdClass Object
(
[baz] => Testing again
)
)
[foox] => Just test
)
Array
(
[foo] => Test data
[bar] => Array
(
[baaz] => Testing
[fooz] => Array
(
[baz] => Testing again
)
)
[foox] => Just test
)
stdClass Object
(
[foo] => Test data
[bar] => stdClass Object
(
[baaz] => Testing
[fooz] => stdClass Object
(
[baz] => Testing again
)
)
[foox] => Just test
)
Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?
Another way to do it would be to inspect the url bar in chrome to find the id of the element, have your WebDriver click that element, and then send the keys you use to copy and paste using the keys common function from selenium, and then printing it out or storing it as a variable, etc.
Here is an example of accessing the ith
index of a std::vector
using an std::iterator
within a loop which does not require incrementing two iterators.
std::vector<std::string> strs = {"sigma" "alpha", "beta", "rho", "nova"};
int nth = 2;
std::vector<std::string>::iterator it;
for(it = strs.begin(); it != strs.end(); it++) {
int ith = it - strs.begin();
if(ith == nth) {
printf("Iterator within a for-loop: strs[%d] = %s\n", ith, (*it).c_str());
}
}
Without a for-loop
it = strs.begin() + nth;
printf("Iterator without a for-loop: strs[%d] = %s\n", nth, (*it).c_str());
and using at
method:
printf("Using at position: strs[%d] = %s\n", nth, strs.at(nth).c_str());
Use this code:
internal void SomeFunction() {
Dictionary<string, string> formField = new Dictionary<string, string>();
formField.Add("Name", "Henry");
formField.Add("Age", "21");
string body = GetBodyStringFromDictionary(formField);
// output : Name=Henry&Age=21
}
internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
string body = string.Empty;
foreach (var pair in formField)
{
body += $"{pair.Key}={pair.Value}&";
}
// delete last "&"
body = body.Substring(0, body.Length - 1);
return body;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);
This works. You have to use two SimpleDateFormats, one for input and one for output, but it will give you just what you are wanting.
Just a quick little function I drummed up that moves DIVs from their current spot to a target spot, one pixel step at a time. I tried to comment as best as I could, but the part you're interested in, is in example 1 and example 2, right after [$(function() { // jquery document.ready]. Put your bounds checking code there, and then exit the interval if conditions are met. Requires jQuery.
First the Demo: http://jsfiddle.net/pnYWY/
First the DIVs...
<style>
.moveDiv {
position:absolute;
left:20px;
top:20px;
width:10px;
height:10px;
background-color:#ccc;
}
.moveDivB {
position:absolute;
left:20px;
top:20px;
width:10px;
height:10px;
background-color:#ccc;
}
</style>
<div class="moveDiv"></div>
<div class="moveDivB"></div>
example 1) Start
// first animation (fire right away)
var myVar = setInterval(function(){
$(function() { // jquery document.ready
// returns true if it just took a step
// returns false if the div has arrived
if( !move_div_step(55,25,'.moveDiv') )
{
// arrived...
console.log('arrived');
clearInterval(myVar);
}
});
},50); // set speed here in ms for your delay
example 2) Delayed Start
// pause and then fire an animation..
setTimeout(function(){
var myVarB = setInterval(function(){
$(function() { // jquery document.ready
// returns true if it just took a step
// returns false if the div has arrived
if( !move_div_step(25,55,'.moveDivB') )
{
// arrived...
console.log('arrived');
clearInterval(myVarB);
}
});
},50); // set speed here in ms for your delay
},5000);// set speed here for delay before firing
Now the Function:
function move_div_step(xx,yy,target) // takes one pixel step toward target
{
// using a line algorithm to move a div one step toward a given coordinate.
var div_target = $(target);
// get current x and current y
var x = div_target.position().left; // offset is relative to document; position() is relative to parent;
var y = div_target.position().top;
// if x and y are = to xx and yy (destination), then div has arrived at it's destination.
if(x == xx && y == yy)
return false;
// find the distances travelled
var dx = xx - x;
var dy = yy - y;
// preventing time travel
if(dx < 0) dx *= -1;
if(dy < 0) dy *= -1;
// determine speed of pixel travel...
var sx=1, sy=1;
if(dx > dy) sy = dy/dx;
else if(dy > dx) sx = dx/dy;
// find our one...
if(sx == sy) // both are one..
{
if(x <= xx) // are we going forwards?
{
x++; y++;
}
else // .. we are going backwards.
{
x--; y--;
}
}
else if(sx > sy) // x is the 1
{
if(x <= xx) // are we going forwards..?
x++;
else // or backwards?
x--;
y += sy;
}
else if(sy > sx) // y is the 1 (eg: for every 1 pixel step in the y dir, we take 0.xxx step in the x
{
if(y <= yy) // going forwards?
y++;
else // .. or backwards?
y--;
x += sx;
}
// move the div
div_target.css("left", x);
div_target.css("top", y);
return true;
} // END :: function move_div_step(xx,yy,target)
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
On my machine:
C:\Program Files\PostgreSQL\8.4\data\postgresql.conf
Without For loop:
Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))
newColumn.DefaultValue = "Your DropDownList value"
table.Columns.Add(newColumn)
C#:
System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);
Summary of existing answers plus my own two cents:
You can use the header()
function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...>
declaration, for example).
header('Location: '.$newURL);
die() or exit()
header("Location: http://example.com/myOtherPage.php");
die();
Why you should use die()
or exit()
: The Daily WTF
Absolute or relative URL
Since June 2014 both absolute and relative URLs can be used. See RFC 7231 which had replaced the old RFC 2616, where only absolute URLs were allowed.
Status Codes
PHP's "Location"-header still uses the HTTP 302-redirect code, this is a "temporary" redirect and may not be the one you should use. You should consider either 301 (permanent redirect) or 303 (other).
Note: W3C mentions that the 303-header is incompatible with "many pre-HTTP/1.1 user agents. Currently used browsers are all HTTP/1.1 user agents. This is not true for many other user agents like spiders and robots.
HTTP Headers and the header()
function in PHP
You may use the alternative method of http_redirect($url);
which needs the PECL package pecl to be installed.
This function doesn't incorporate the 303 status code:
function Redirect($url, $permanent = false)
{
header('Location: ' . $url, true, $permanent ? 301 : 302);
exit();
}
Redirect('http://example.com/', false);
This is more flexible:
function redirect($url, $statusCode = 303)
{
header('Location: ' . $url, true, $statusCode);
die();
}
As mentioned header()
redirects only work before anything is written out. They usually fail if invoked inmidst HTML output. Then you might use a HTML header workaround (not very professional!) like:
<meta http-equiv="refresh" content="0;url=finalpage.html">
Or a JavaScript redirect even.
window.location.replace("http://example.com/");
try
var children = null;
$('tr').each(function(){
var td = $(this).children('td:first');
if(children == null)
children = td;
else
children.add(td);
});
// children should now hold all the first td elements
my test java config (for MySql)
@Bean(destroyMethod = "close")
public DataSource dataSource(){
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setDriverClassName("com.mysql.jdbc.Driver");
hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/spring-test");
hikariConfig.setUsername("root");
hikariConfig.setPassword("admin");
hikariConfig.setMaximumPoolSize(5);
hikariConfig.setConnectionTestQuery("SELECT 1");
hikariConfig.setPoolName("springHikariCP");
hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");
HikariDataSource dataSource = new HikariDataSource(hikariConfig);
return dataSource;
}
If you don't have borders, or have borders and want the spacing inside the cells, you can use padding
, or line-height
. As far as I know, margin has no effect on cells and rows.
A CSS property for spacing of cells is border-spacing
, but it doesn't work on IE6/7 (so you can use it depending on your crowd).
If all else fails you can use the old cellspacing
attribute in your markup - but this will also give you spacing between the columns. Some CSS reset suggest you should set it anyway to get cross-browser support:
/* tables still need
cellspacing="0"
in the markup */
In any situation, if you have to bind a value with a checkbox which is not boolean then you can try the below options
In the Html file:
<div class="checkbox">
<label for="favorite-animal">Without boolean Value</label>
<input type="checkbox" value="" [checked]="ischeckedWithOutBoolean == 'Y'"
(change)="ischeckedWithOutBoolean = $event.target.checked ? 'Y': 'N'">
</div>
in the componentischeckedWithOutBoolean: any = 'Y';
See in the stackblitz https://stackblitz.com/edit/angular-5szclb?embed=1&file=src/app/app.component.html
if there is no value inserted, the default value should be null,empty
In the table definition, make this datetime
column allows null, be not defining NOT NULL
:
...
DateTimeColumn DateTime,
...
I HAVE ALLOWED NULL VARIABLES THOUGH.
Then , just insert NULL
in this column:
INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);
Or, you can make use of the DEFAULT constaints:
...
DateTimeColumn DateTime DEFAULT NULL,
...
Then you can ignore it completely in the INSERT
statement and it will be inserted withe the NULL
value:
INSERT INTO Table(name, ...)
VALUES('foo bar', ..);
Within the view you want to bring to the top... (in swift)
superview?.bringSubviewToFront(self)
HashMap
is an implementation of Map
. Map is just an interface for any type of map.
The Google Play Store doesn't provide this data, so the sites must just be scraping it.
Try to use IF(condition, value1, value2)
SELECT ID, HEADING,
IF(action_type='Income',action_amount,0) as Income,
IF(action_type='Expense',action_amount,0) as Expense
Suppose your drop down list is:
<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>
There are two ways:
<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />
the 2nd way is to use a compare validator:
<asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />
Find: value="([\d]+|[\d])"
Replace: \1
It will really return you
4
403
200
201
116
15
js:
a='value="4"\nvalue="403"\nvalue="200"\nvalue="201"\nvalue="116"\nvalue="15"';
a = a.replace(/value="([\d]+|[\d])"/g, '$1');
console.log(a);
If you specifically want to use an ad hoc wireless network, then Andy's answer seems to be your only option. However, if you just want to share your laptop's internet connection via Wi-fi using any means necessary, then you have at least two more options:
*Some phones with Android 2.3 have proprietary OS extensions that enable Wi-fi Direct (mostly newer Samsung phones), but Android 4 should fully support this (source).
Hi the answer that @anu posted is right, but it wont completely work as required. By making a slight change to child_open() function it works properly.
<html>
<head>
<script type="text/javascript">
var popupWindow=null;
function child_open()
{
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
else
popupWindow =window.open('new.jsp',"_blank","directories=no, status=no, menubar=no, scrollbars=yes, resizable=no,width=600, height=280,top=200,left=200");
}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
</script>
</head>
<body onFocus="parent_disable();" onclick="parent_disable();">
<a href="javascript:child_open()">Click me</a>
</body>
</html>
Create custom helpers’ directory: First create Helpers directory in app directory. Create hlper class definition: Let’s now create a simple helper function that will concatenate two strings. Create a new file MyFuncs.php in /app/Helpers/MyFuncs.php Add the following code
<?php
namespace App\Helpers;
class MyFuncs {
public static function full_name($first_name,$last_name) {
return $first_name . ', '. $last_name;
}
}
namespace App\Helpers; defines the Helpers namespace under App namespace. class MyFuncs {…} defines the helper class MyFuncs. public static function full_name($first_name,$last_name) {…} defines a static function that accepts two string parameters and returns a concatenated string
Helpers service provide class
Service providers are used to auto load classes. We will need to define a service provider that will load all of our helper classes in /app/Helpers directory.
Run the following artisan command:
php artisan make:provider HelperServiceProvider
The file will be created in /app/Providers/HelperServiceProvider.php
Open /app/Providers/HelperServiceProvider.php
Add the following code:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class HelperServiceProvider extends ServiceProvider {
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename){
require_once($filename);
}
}
}
HERE,
namespace App\Providers; defines the namespace provider
use Illuminate\Support\ServiceProvider; imports the ServiceProvider class namespace
class HelperServiceProvider extends ServiceProvider {…} defines a class HelperServiceProvider that extends the ServiceProvider class
public function boot(){…} bootstraps the application service
public function register(){…} is the function that loads the helpers
foreach (glob(app_path().'/Helpers/*.php') as $filename){…} loops through all the files in /app/Helpers directory and loads them.
We now need to register the HelperServiceProvider and create an alias for our helpers.
Open /config/app.php
file
Locate the providers array variable
Add the following line
App\Providers\HelperServiceProvider::class,
Locate the aliases array variable
Add the following line
'MyFuncs' => App\Helpers\MyFuncs::class,
Save the changes Using our custom helper
We will create a route that will call our custom helper function Open /app/routes.php
Add the following route definition
Route::get('/func', function () {
return MyFuncs::full_name("John","Doe");
});
HERE,
return MyFuncs::full_name("John","Doe"); calls the static function full_name in MyFuncs class
Export should be specific about which version of GCC/G++ to use, because if user had multiple compiler version, it would not compile successfully.
export CC=path_of_gcc/gcc-version
export CXX=path_of_g++/g++-version
cmake path_of_project_contain_CMakeList.txt
make
In case project use C++11 this can be handled by using -std=C++-11
flag in CMakeList.txt
Use the SingleOrDefault() instead of FirstOrDefault().
As Wingman said, Google App Engine is a great solution for your scenario.
You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android
And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4
Be careful with jobs
1 - if you have a job based in maven, Jenkins takes your default java configuration and you decide the compilation level in your POM.XML.
2 - if you have a free style job, in the the configuration option of the job you can select the JDK that you want to use.
Hope this help.
public string HtmlAgi(string url, string key)
{
var Webget = new HtmlWeb();
var doc = Webget.Load(url);
HtmlNode ourNode = doc.DocumentNode.SelectSingleNode(string.Format("//meta[@name='{0}']", key));
if (ourNode != null)
{
return ourNode.GetAttributeValue("content", "");
}
else
{
return "not fount";
}
}
I can't believe the accepted answer has so many upvotes -- it's a horrible method.
Here's the correct way to do it, with date_trunc:
SELECT date_trunc('month', txn_date) AS txn_month, sum(amount) as monthly_sum
FROM yourtable
GROUP BY txn_month
It's bad practice but you might be forgiven if you use
GROUP BY 1
in a very simple query.
You can also use
GROUP BY date_trunc('month', txn_date)
if you don't want to select the date.
When you inherit from Super this is what in reality happens:
public class Son extends Super{
// If you dont declare a constructor of any type, adefault one will appear.
public Son(){
// If you dont call any other constructor in the first line a call to super() will be placed instead.
super();
}
}
So, that is the reason, because you have to call your unique constructor, since"Super" doesn't have a default one.
Now, trying to guess why Java doesn't support constructor inheritance, probably because a constructor only makes sense if it's talking about concrete instances, and you shouldn't be able to create an instance of something when you don't know how it's defined (by polymorphism).
Good news everyone, there's an isBetween
function!
Update your library ;)
This line:
setTimeout(startTimer(), startInterval);
You're invoking startTimer()
. Instead, you need to pass it in as a function to be invoked, like so:
setTimeout(startTimer, startInterval);
You could do it in one line (useful for ci-environments):
taskkill /fi "Services eq SERVICE_NAME" /F
Filter -> Services -> ServiceName equals SERVICE_NAMES -> Force
Source: https://technet.microsoft.com/en-us/library/bb491009.aspx
Will the username and password be automatically SSL encrypted? Is the same true for GETs and POSTs
Yes, yes yes.
The entire communication (save for the DNS lookup if the IP for the hostname isn't already cached) is encrypted when SSL is in use.
Security Warning: This class is not secure. It's using Rijndael256-ECB, which is not semantically secure. Just because "it works" doesn't mean "it's secure". Also, it strips tailing spaces afterwards due to not using proper padding.
Found this class recently, it works like a dream!
class Encryption {
var $skey = "yourSecretKey"; // you can change it
public function safe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
public function safe_b64decode($string) {
$data = str_replace(array('-','_'),array('+','/'),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
public function encode($value){
if(!$value){return false;}
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
return trim($this->safe_b64encode($crypttext));
}
public function decode($value){
if(!$value){return false;}
$crypttext = $this->safe_b64decode($value);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
}
And to call it:
$str = "My secret String";
$converter = new Encryption;
$encoded = $converter->encode($str );
$decoded = $converter->decode($encoded);
echo "$encoded<p>$decoded";
In my case it was a problem with a missing init.py file in the module, that I wanted to import in a Python 2.7 environment.
Python 3.3+ has Implicit Namespace Packages that allow it to create a packages without an init.py file.
onmouseover="$('.play-detail').stop().animate({'height': '84px'},'300');"
onmouseout="$('.play-detail').stop().animate({'height': '44px'},'300');"
Just put two stops -- one onmouseover and one onmouseout.
Just add objects = None in your Questions table. That solved the error for me.
Following code uses most efficient way of looping to check if a given number is prime.
function checkPrime(number){
if (number==2 || number==3) {
return true
}
if(number<2 ||number % 2===0){
return false
}
else{
for (let index = 3; index <= Math.sqrt(number); index=index+2) {
if (number%index===0) {
return false
}
}
}
return true
}
Create a struct and set two values inside and return the struct variable.
struct result {
int a;
char *string;
}
You have to allocate space for the char *
in your program.
You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:
Dim MyVar as string = "some text ""hello"" "
This will give the MyVar
variable a value of some text "hello"
.
You can set this programmatically in the controller:-
HttpContext.Current.Server.ScriptTimeout = 300;
Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)