I had the same error from a different cause: I'd created a starter POM containing our "good practice" dependencies, and built & installed it locally to test it. I could "see" it in the repo, but a project that used it got the above error. What I'd done was set the starter POM to pom, so there was no JAR. Maven was quite correct that it wasn't in Nexus -- but I wasn't expecting it to be, so the error was, ummm, unhelpful. Changing the starter POM to normal packaging & reinstalling fixed the issue.
Simple! You can use size
and from
parameter!
http://localhost:9200/[your index name]/_search?size=1000&from=0
then you change the from
gradually until you get all of the data.
checked
attribute is a boolean value so "checked"
value of other "string"
except boolean false
converts to true
.
Any string value will be true. Also presence of attribute make it true:
<input type="checkbox" checked>
You can make it uncheked only making boolean change in DOM using JS.
So the answer is: they are equal.
Keep in mind that if you want to get exact primary field you need to put TABLE_NAME and TABLE_SCHEMA into the condition.
this solution should work:
select COLUMN_NAME from information_schema.KEY_COLUMN_USAGE
where CONSTRAINT_NAME='PRIMARY' AND TABLE_NAME='TABLENAME'
AND TABLE_SCHEMA='DATABASENAME'
that is referring to the expected dtype of your image
"image".astype('float32') should solve your issue
To avoid explicitly checking for these variants of 'yes' you could use the bash regular expression operator '=~' with a regular expression:
read -p "Are you sure you want to continue? <y/N> " prompt
if [[ $prompt =~ [yY](es)* ]]
then
(etc...)
That tests whether the user input starts with 'y' or 'Y' and is followed by zero or more 'es's.
This is the best .htaccess
I have used in my actual website:
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
##Tweaks##
Header set X-Frame-Options SAMEORIGIN
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##
<IfModule mod_headers.c>
Header set Connection keep-alive
<filesmatch "\.(ico|flv|gif|swf|eot|woff|otf|ttf|svg)$">
Header set Cache-Control "max-age=2592000, public"
</filesmatch>
<filesmatch "\.(jpg|jpeg|png)$">
Header set Cache-Control "max-age=1209600, public"
</filesmatch>
# css and js should use private for proxy caching https://developers.google.com/speed/docs/best-practices/caching#LeverageProxyCaching
<filesmatch "\.(css)$">
Header set Cache-Control "max-age=31536000, private"
</filesmatch>
<filesmatch "\.(js)$">
Header set Cache-Control "max-age=1209600, private"
</filesmatch>
<filesMatch "\.(x?html?|php)$">
Header set Cache-Control "max-age=600, private, must-revalidate"
</filesMatch>
</IfModule>
You can achieve this using Lodash _.merge
function.
var json1 = [{id:1, name: 'xxx'}];_x000D_
var json2 = [{id:2, name: 'xyz'}];_x000D_
var merged = _.merge(_.keyBy(json1, 'id'), _.keyBy(json2, 'id'));_x000D_
var finalObj = _.values(merged);_x000D_
_x000D_
console.log(finalObj);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
I'm using the following, it also correctly detect delete statements that delete nothing:
CREATE TRIGGER dbo.TR_TableName_TriggerName
ON dbo.TableName
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT * FROM INSERTED)
-- DELETE
PRINT 'DELETE';
ELSE
BEGIN
IF NOT EXISTS(SELECT * FROM DELETED)
-- INSERT
PRINT 'INSERT';
ELSE
-- UPDATE
PRINT 'UPDATE';
END
END;
I solved a very similar issue using:
$("#my_form").submit(function(){
$('input[type=submit]').click(function(event){
event.preventDefault();
});
});
When the DLL was created an import lib is usually automatically created and you should use that linked in to your program along with header files to call it but if not then you can manually call windows functions like LoadLibrary and GetProcAddress to get it working.
I will try to explain the results of all the commands you tried.
scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)
First of all, List
is a type alias to scala.collection.immutable.List
(defined in Predef.scala).
Using the List companion object is more straightforward way to instantiate a List
. Ex: List(1.0,5.5)
scala> l
res0: List[Double] = List(1.0, 5.5)
scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)
:::
returns a list resulting from the concatenation of the given list prefix and this list
The original List is NOT modified
scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)
List(l)
is a List[List[Double]]
Definitely not what you want.
:+
returns a new list consisting of all elements of this list followed by elem.
The type is List[Any]
because it is the common superclass between List[Double]
and Double
scala> l
res3: List[Double] = List(1.0, 5.5)
l is left unmodified because no method on immutable.List
modified the List.
Another way to add java docs comment is press : Ctrl + Shift + A >> show a popup >> type : Add javadocs >> Enter .
Ctrl + Shirt + A: Command look-up (autocomplete command name)
strip --strip-unneeded
only operates on the symbol table of your executable. It doesn't actually remove any executable code.
The standard libraries achieve the result you're after by splitting all of their functions into seperate object files, which are combined using ar
. If you then link the resultant archive as a library (ie. give the option -l your_library
to ld) then ld will only include the object files, and therefore the symbols, that are actually used.
You may also find some of the responses to this similar question of use.
I found that in my case this is the only way working: (in my application I want to remove old log entries)
var filterDate = dtRemoveLogs.SelectedDate.Value.Date;
var loadOp = context.Load<ApplicationLog>(context.GetApplicationLogsQuery()
.Where(l => l.DateTime.Year <= filterDate.Year
&& l.DateTime.Month <= filterDate.Month
&& l.DateTime.Day <= filterDate.Day));
I don't understand why the Jon's solution is not working ....
Build an expression that matches, and use !match()... (logical negation) That's probably how grep does anyway...
Try this:
update MasterTbl M,
(select sum(X) as sX,
sum(Y) as sY,
sum(Z) as sZ,
MasterID
from DetailTbl
group by MasterID) A
set
M.TotalX=A.sX,
M.TotalY=A.sY,
M.TotalZ=A.sZ
where
M.ID=A.MasterID
The answer given by deepak goel does not work for me because I always get null from entry.getName()
;
What I do is to set a Tag to the fragment this way:
ft.add(R.id.fragment_container, fragmentIn, FRAGMENT_TAG);
Where ft is my fragment transaction and FRAGMENT_TAG
is the tag. Then I use this code to get the fragment:
Fragment prev_fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);
The most obvious solution to me is to use the key
keyword arg.
>>> X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
>>> Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
>>> keydict = dict(zip(X, Y))
>>> X.sort(key=keydict.get)
>>> X
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
Note that you can shorten this to a one-liner if you care to:
>>> X.sort(key=dict(zip(X, Y)).get)
As Wenmin Mu and Jack Peng have pointed out, this assumes that the values in X
are all distinct. That's easily managed with an index list:
>>> Z = ["A", "A", "C", "C", "C", "F", "G", "H", "I"]
>>> Z_index = list(range(len(Z)))
>>> Z_index.sort(key=keydict.get)
>>> Z = [Z[i] for i in Z_index]
>>> Z
['A', 'C', 'H', 'A', 'C', 'C', 'I', 'F', 'G']
Since the decorate-sort-undecorate approach described by Whatang is a little simpler and works in all cases, it's probably better most of the time. (This is a very old answer!)
The Laravel Hash facade provides secure Bcrypt hashing for storing user passwords.
Basic usage required two things:
First include the Facade in your file
use Illuminate\Support\Facades\Hash;
and use Make
Method to generate password.
$hashedPassword = Hash::make($request->newPassword);
and when you want to match the Hashed string you can use the below code:
Hash::check($request->newPasswordAtLogin, $hashedPassword)
You can learn more with the Laravel document link below for Hashing: https://laravel.com/docs/5.5/hashing
As was mentioned in an older version (2009) of the "Tree Conflict" design document:
XFAIL conflict from merge of add over versioned file
This test does a merge which brings a file addition without history onto an existing versioned file.
This should be a tree conflict on the file of the 'local obstruction, incoming add upon merge
' variety. Fixed expectations in r35341.
(This is also called "evil twins" in ClearCase by the way):
a file is created twice (here "added" twice) in two different branches, creating two different histories for two different elements, but with the same name.
The theoretical solution is to manually merge those files (with an external diff tool) in the destination branch 'B2
'.
If you still are working on the source branch, the ideal scenario would be to remove that file from the source branch B1
, merge back from B2
to B1
in order to make that file visible on B1
(you will then work on the same element).
If a merge back is not possible because merges only occurs from B1
to B2
, then a manual merge will be necessary for each B1->B2
merges.
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
Just to top this up to the new Java 8 API:
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM dd, yyyy").toFormatter();
TemporalAccessor ta = formatter.parse("June 27, 2007");
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
assertThat(d.getYear(), is(107));
assertThat(d.getMonth(), is(5));
A bit more verbose but you also see that the methods of Date used are deprecated ;-) Time to move on.
Okay. The same time I was writing down my question one of my colleagues made me aware this is actually HTML5 behavior. See http://dev.w3.org/html5/spec/Overview.html#the-required-attribute
Seems in HTML5 there is a new attribute "required". And Safari 5 already has an implementation for this attribute.
Consider the Switch Function as an alternative to multiple IIf()
expressions. It will return the value from the first expression/value pair where the expression evaluates as True, and ignore any remaining pairs. The concept is similar to the SELECT ... CASE
approach you referenced but which is not available in Access SQL.
If you want to display a calculated field as commission
:
SELECT
Switch(
OpeningBalance < 5001, 20,
OpeningBalance < 10001, 30,
OpeningBalance < 20001, 40,
OpeningBalance >= 20001, 50
) AS commission
FROM YourTable;
If you want to store that calculated value to a field named commission
:
UPDATE YourTable
SET commission =
Switch(
OpeningBalance < 5001, 20,
OpeningBalance < 10001, 30,
OpeningBalance < 20001, 40,
OpeningBalance >= 20001, 50
);
Either way, see whether you find Switch()
easier to understand and manage. Multiple IIf()s
can become mind-boggling as the number of conditions grows.
After checking catalina.sh (for windows use the .bat versions of everything mentioned below)
# Do not set the variables in this script. Instead put them into a script
# setenv.sh in CATALINA_BASE/bin to keep your customizations separate.
Also this
# CATALINA_OPTS (Optional) Java runtime options used when the "start",
# "run" or "debug" command is executed.
# Include here and not in JAVA_OPTS all options, that should
# only be used by Tomcat itself, not by the stop process,
# the version command etc.
# Examples are heap size, GC logging, JMX ports etc
So create a setenv.sh under CATALINA_BASE/bin (same dir where the catalina.sh resides). Edit the file and set the arguments to CATALINA_OPTS
For e.g. the file would look like this if you wanted to change the heap size
CATALINA_OPTS=-Xmx512m
Or in your case since you're using windows setenv.bat would be
set CATALINA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
To clear the added options later just delete setenv.bat/sh
you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java
What about:
parseFloat(str.replace(' ', '').replace('.', '').replace(',', '.'));
One more little thing, the theme solution does work if you inherit a base theme, so for app compact your theme should be:
<style name="AppTheme.Custom" parent="@style/Theme.AppCompat">
<item name="colorAccent">@color/custom</item>
</style>
And then set this in the progress bar theme
<ProgressBar
android:id="@+id/progressCircle_progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:theme="@style/AppTheme.Custom"
android:indeterminate="true"/>
Here's another way of doing the code above using the openpyxl
module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.
from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')
There is no inherent limit. The maximum number of threads is determined by the amount of physical resources available. See this article by Raymond Chen for specifics.
If you need to ask what the maximum number of threads is, you are probably doing something wrong.
[Update: Just out of interest: .NET Thread Pool default numbers of threads:
(These numbers may vary depending upon the hardware and OS)]
First be sure that your working copy is not modified. Then:
git diff --binary HEAD commit_sha_you_want_to_revert_to | git apply
and then just commit. Don't forget to document what's the reason for revert.
for the future strugglers, in python 3.8.2(and maybe a few versions before that), the syntax is
except Attribute as e:
print(e)
I strongly suspect the problem is to do with namespaces. Try getting rid of the namespace and you'll be fine - but obviously that won't help in your real case, where I'd assume the document is fixed.
I can't remember offhand how to specify a namespace in an XPath expression, but I'm sure that's the problem.
EDIT: Okay, I've remembered how to do it now. It's not terribly pleasant though - you need to create an XmlNamespaceManager
for it. Here's some sample code that works with your sample document:
using System;
using System.Xml;
public class Test
{
static void Main()
{
XmlDocument doc = new XmlDocument();
XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
namespaces.AddNamespace("ns", "urn:hl7-org:v3");
doc.Load("test.xml");
XmlNode idNode = doc.SelectSingleNode("/My_RootNode/ns:id", namespaces);
string msgID = idNode.Attributes["extension"].Value;
Console.WriteLine(msgID);
}
}
You may pass an object to the data
option in $.ajax
. jQuery will send this as regular post data, just like a normal HTML form.
$.ajax({
type: "POST",
url: "TelephoneNumbers.aspx/DeleteNumber",
data: dataO, // same as using {numberId: 1, companyId: 531}
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('In Ajax');
}
});
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
Why can't we make a unique id as below.
We can use DateTime.Now.Ticks and Guid.NewGuid().ToString() to combine together and make a unique id.
As the DateTime.Now.Ticks is added, we can find out the Date and Time in seconds at which the unique id is created.
Please see the code.
var ticks = DateTime.Now.Ticks;
var guid = Guid.NewGuid().ToString();
var uniqueSessionId = ticks.ToString() +'-'+ guid; //guid created by combining ticks and guid
var datetime = new DateTime(ticks);//for checking purpose
var datetimenow = DateTime.Now; //both these date times are different.
We can even take the part of ticks in unique id and check for the date and time later for future reference.
Because all attempts to print the argument I placed in my variable failed, here my 2 bytes for this question:
std::string dump_name;
(stuff..)
if(argc>2)
{
dump_name.assign(argv[2]);
fprintf(stdout, "ARGUMENT %s", dump_name.c_str());
}
Note the use of assign, and also the need for the c_str() function call.
public boolean getcheckboxvalue(String element)
{
WebElement webElement=driver.findElement(By.xpath(element));
return webElement.isSelected();
}
The link of accepted answer is old and can cause warnings with generics use,
You should download latest jar from JSON-java github site
Add jar to Java build Path
In existing project in Order and Export
tab move the new jar, as json-20180813.jar
, as the first (or above other dependencies with JSONObject
)
One other work-around is to use jupyter notebooks and use the markdown mode in cells to render equations.
Basic stuff seems to work perfectly, like centered equations
\begin{equation}
...
\end{equation}
or inline equations
$ \sum_{\forall i}{x_i^{2}} $
Although, one of the functions that I really wanted did not render at all in github was \mbox{}
, which was a bummer. But, all in all this has been the most successful way of rendering equations on github.
This should do it for you - all your files will end up called Part1-Part500.
#!/bin/bash
FILENAME=10000.csv
HDR=$(head -1 $FILENAME) # Pick up CSV header line to apply to each file
split -l 20 $FILENAME xyz # Split the file into chunks of 20 lines each
n=1
for f in xyz* # Go through all newly created chunks
do
echo $HDR > Part${n} # Write out header to new file called "Part(n)"
cat $f >> Part${n} # Add in the 20 lines from the "split" command
rm $f # Remove temporary file
((n++)) # Increment name of output part
done
I turn on .Net Framework 3.5 and 4.5 Advance Service in Control Panel->Programs and Features->Turn Windows features on or off.it work for me.
Try this:
if (strstr($_SERVER['REQUEST_URI'],'index.php')) {
header('HTTP/1.0 404 Not Found');
echo "<head><title>404 Not Found</title></head>";
echo "<h1>Not Found</h1>";
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
echo "<p>The requested URL ".$uri." was not found on this server.</p>";
exit();
}
I like this light weight http request client called `unirest'
gem install unirest
usage:
response = Unirest.post "http://httpbin.org/post",
headers:{ "Accept" => "application/json" },
parameters:{ :age => 23, :foo => "bar" }
response.code # Status code
response.headers # Response headers
response.body # Parsed body
response.raw_body # Unparsed body
Try git add -A
instead of git add .
There is an easy way without the need to use an external tool - it runs fine with Windows 7, 8, 8.1 and 10 and is backwards-compatible too (Windows XP doesn't have any UAC, thus elevation is not needed - in that case the script just proceeds).
Check out this code (I was inspired by the code by NIronwolf posted in the thread Batch File - "Access Denied" On Windows 7?), but I've improved it - in my version there isn't any directory created and removed to check for administrator privileges):
::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
:: see "https://stackoverflow.com/a/12264592/1016343" for description
::::::::::::::::::::::::::::::::::::::::::::
@echo off
CLS
ECHO.
ECHO =============================
ECHO Running Admin shell
ECHO =============================
:init
setlocal DisableDelayedExpansion
set cmdInvoke=1
set winSysFolder=System32
set "batchPath=%~0"
for %%k in (%0) do set batchName=%%~nk
set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
setlocal EnableDelayedExpansion
:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )
:getPrivileges
if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
ECHO.
ECHO **************************************
ECHO Invoking UAC for Privilege Escalation
ECHO **************************************
ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
ECHO args = "ELEV " >> "%vbsGetPrivileges%"
ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
ECHO args = args ^& strArg ^& " " >> "%vbsGetPrivileges%"
ECHO Next >> "%vbsGetPrivileges%"
if '%cmdInvoke%'=='1' goto InvokeCmd
ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
goto ExecElevation
:InvokeCmd
ECHO args = "/c """ + "!batchPath!" + """ " + args >> "%vbsGetPrivileges%"
ECHO UAC.ShellExecute "%SystemRoot%\%winSysFolder%\cmd.exe", args, "", "runas", 1 >> "%vbsGetPrivileges%"
:ExecElevation
"%SystemRoot%\%winSysFolder%\WScript.exe" "%vbsGetPrivileges%" %*
exit /B
:gotPrivileges
setlocal & cd /d %~dp0
if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul & shift /1)
::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
REM Run shell as admin (example) - put here code as you like
ECHO %batchName% Arguments: P1=%1 P2=%2 P3=%3 P4=%4 P5=%5 P6=%6 P7=%7 P8=%8 P9=%9
cmd /k
The script takes advantage of the fact that NET FILE
requires administrator privilege and returns errorlevel 1
if you don't have it. The elevation is achieved by creating a script which re-launches the batch file to obtain privileges. This causes Windows to present the UAC dialog and asks you for the administrator account and password.
I have tested it with Windows 7, 8, 8.1, 10 and with Windows XP - it works fine for all. The advantage is, after the start point you can place anything that requires system administrator privileges, for example, if you intend to re-install and re-run a Windows service for debugging purposes (assumed that mypackage.msi is a service installer package):
msiexec /passive /x mypackage.msi
msiexec /passive /i mypackage.msi
net start myservice
Without this privilege elevating script, UAC would ask you three times for your administrator user and password - now you're asked only once at the beginning, and only if required.
If your script just needs to show an error message and exit if there aren't any administrator privileges instead of auto-elevating, this is even simpler: You can achieve this by adding the following at the beginning of your script:
@ECHO OFF & CLS & ECHO.
NET FILE 1>NUL 2>NUL & IF ERRORLEVEL 1 (ECHO You must right-click and select &
ECHO "RUN AS ADMINISTRATOR" to run this batch. Exiting... & ECHO. &
PAUSE & EXIT /D)
REM ... proceed here with admin rights ...
This way, the user has to right-click and select "Run as administrator". The script will proceed after the REM
statement if it detects administrator rights, otherwise exit with an error. If you don't require the PAUSE
, just remove it.
Important: NET FILE [...] EXIT /D)
must be on the same line. It is displayed here in multiple lines for better readability!
On some machines, I've encountered issues, which are solved in the new version above already. One was due to different double quote handling, and the other issue was due to the fact that UAC was disabled (set to lowest level) on a Windows 7 machine, hence the script calls itself again and again.
I have fixed this now by stripping the quotes in the path and re-adding them later, and I've added an extra parameter which is added when the script re-launches with elevated rights.
The double quotes are removed by the following (details are here):
setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion
You can then access the path by using !batchPath!
. It doesn't contain any double quotes, so it is safe to say "!batchPath!"
later in the script.
The line
if '%1'=='ELEV' (shift & goto gotPrivileges)
checks if the script has already been called by the VBScript script to elevate rights, hence avoiding endless recursions. It removes the parameter using shift
.
Update:
To avoid having to register the .vbs
extension in Windows 10, I have replaced the line
"%temp%\OEgetPrivileges.vbs"
by
"%SystemRoot%\System32\WScript.exe" "%temp%\OEgetPrivileges.vbs"
in the script above; also added cd /d %~dp0
as suggested by Stephen (separate answer) and by Tomáš Zato (comment) to set script directory as default.
Now the script honors command line parameters being passed to it. Thanks to jxmallet, TanisDLJ and Peter Mortensen for observations and inspirations.
According to Artjom B.'s hint, I analyzed it and have replaced SHIFT
by SHIFT /1
, which preserves the file name for the %0
parameter
Added del "%temp%\OEgetPrivileges_%batchName%.vbs"
to the :gotPrivileges
section to clean up (as mlt suggested). Added %batchName%
to avoid impact if you run different batches in parallel. Note that you need to use for
to be able to take advantage of the advanced string functions, such as %%~nk
, which extracts just the filename.
Optimized script structure, improvements (added variable vbsGetPrivileges
which is now referenced everywhere allowing to change the path or name of the file easily, only delete .vbs
file if batch needed to be elevated)
In some cases, a different calling syntax was required for elevation. If the script does not work, check the following parameters:
set cmdInvoke=0
set winSysFolder=System32
Either change the 1st parameter to set cmdInvoke=1
and check if that already fixes the issue. It will add cmd.exe
to the script performing the elevation.
Or try to change the 2nd parameter to winSysFolder=Sysnative
, this might help (but is in most cases not required) on 64 bit systems. (ADBailey has reported this). "Sysnative" is only required for launching 64-bit applications from a 32-bit script host (e.g. a Visual Studio build process, or script invocation from another 32-bit application).
To make it more clear how the parameters are interpreted, I am displaying it now like P1=value1 P2=value2 ... P9=value9
. This is especially useful if you need to enclose parameters like paths in double quotes, e.g. "C:\Program Files"
.
If you want to debug the VBS script, you can add the //X
parameter to WScript.exe as first parameter, as suggested here (it is described for CScript.exe, but works for WScript.exe too).
Useful links:
There is no sure shot trick. You need to explore the reasons why your mails are classified as spam. SpamAssassin hase a page describing Some Tips for Legitimate Senders to Avoid False Positives. See also Coding Horror: So You'd Like to Send Some Email (Through Code)
A POSIX compliant answer. Notice the use of /bin/sh
instead of /bin/bash
. (It does work with bash, but it does not require bash.)
#!/bin/sh
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"
Simple Way:
For Integer:
var number = arrayOf< Int> (10 , 20 , 30 , 40 ,50)
Hold All data types
var number = arrayOf(10 , "string value" , 10.5)
1 ) Copy the initialAdminPassword in Specified path.
2 ) Login with following Credentials
User Name : admin
Password : <da12906084fd405090a9fabfd66342f0>
3 ) Once you login into the jenkins application you can click on admin profile and reset the password.
Another approach is:
git push --prune origin
WARNING: This will delete all remote branches that do not exist locally. Or more comprehensively,
git push --mirror
will effectively make the remote repository look like the local copy of the repository (local heads, remotes and tags are mirrored on remote).
URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.
There are several ways to soften the pain:
JSF EL offers a shorthand to ${pageContext.request}
in flavor of #{request}
:
<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>
You can if necessary use <c:set>
tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:
<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>
JSF 2.x offers the <h:link>
which can take a view ID relative to the context root in outcome
and it will append the context path and FacesServlet
mapping automatically:
<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>
HTML offers the <base>
tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>
.
<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>
(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring()
, see also this answer)
This should end up in the generated HTML something like as
<base href="http://example.com/webname/" />
Note that the <base>
tag has a caveat: it makes all jump anchors in the page like <a href="#top">
relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a>
or <h:link value="top" fragment="top" />
.
You can use this methode to check if a view has children or not .
public static boolean hasChildren(ViewGroup viewGroup) {
return viewGroup.getChildCount() > 0;
}
In case anyone needs a (nearly) ready-to-use PHP function, the following is based on this answer:
/**
* Remove a column from a table.
*
* @param string $tableName The table to remove the column from.
* @param string $columnName The column to remove from the table.
*/
public function DropTableColumn($tableName, $columnName)
{
// --
// Determine all columns except the one to remove.
$columnNames = array();
$statement = $pdo->prepare("PRAGMA table_info($tableName);");
$statement->execute(array());
$rows = $statement->fetchAll(PDO::FETCH_OBJ);
$hasColumn = false;
foreach ($rows as $row)
{
if(strtolower($row->name) !== strtolower($columnName))
{
array_push($columnNames, $row->name);
}
else
{
$hasColumn = true;
}
}
// Column does not exist in table, no need to do anything.
if ( !$hasColumn ) return;
// --
// Actually execute the SQL.
$columns = implode('`,`', $columnNames);
$statement = $pdo->exec(
"CREATE TABLE `t1_backup` AS SELECT `$columns` FROM `$tableName`;
DROP TABLE `$tableName`;
ALTER TABLE `t1_backup` RENAME TO `$tableName`;");
}
In contrast to other answers, the SQL used in this approach seems to preserve the data types of the columns, whereas something like the accepted answer seems to result in all columns to be of type TEXT
.
Update 1:
The SQL used has the drawback that autoincrement
columns are not preserved.
In case if you are not aware of the number and name of columns in dataframe then this method can be handy:
column_list = []
df_column = pd.read_excel(file_name, 'Sheet1').columns
for i in df_column:
column_list.append(i)
converter = {col: str for col in column_list}
df_actual = pd.read_excel(file_name, converters=converter)
where column_list is the list of your column names.
if you fetching it from database then
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<?php $s2="select * from <tablename>";
$q2=mysql_query($s2);
while($rw2=mysql_fetch_array($q2)) {
?>
<option value="<?php echo $rw2['id']; ?>"><?php echo $rw2['carname']; ?></option><?php } ?>
</select>
Import your csv or sql to sqlite with phpLiteAdmin, it is excellent.
"Although I can't isolate SQL as the source of the problem anymore, I still feel like it is."
Fire up SQL Profiler and take a look. Take the resulting queries and check their execution plans to make sure that index is being used.
For pipeline:
pipeline {
environment {
BRANCH_NAME = "${GIT_BRANCH.split("/")[1]}"
}
}
With lodash version 4+, you would remove duplicate objects either by specific property or by the entire object like so:
var users = [
{id:1,name:'ted'},
{id:1,name:'ted'},
{id:1,name:'bob'},
{id:3,name:'sara'}
];
var uniqueUsersByID = _.uniqBy(users,'id'); //removed if had duplicate id
var uniqueUsers = _.uniqWith(users, _.isEqual);//removed complete duplicates
Source:https://www.codegrepper.com/?search_term=Lodash+remove+duplicates+from+array
You can call a stored procedure from another stored procedure by using the EXECUTE command.
Say your procedure is X. Then in X you can use
EXECUTE PROCEDURE Y () RETURNING_VALUES RESULT;"
I too had the same problem in VWD 2010 and, by chance, I had two controls. One was available in code behind and one wasn't accessible. I thought that the order of statements in the controls was causing the issue. I put 'runat' before 'SelectedDate' and that seemed to fix it. When I put 'runat' after 'SelectedDate' it still worked! Unfortunately, I now don't know why it didn't work and haven't got the original that didn't work.
These now all work:-
<asp:Calendar ID="calDateFrom" SelectedDate="08/02/2011" SelectionMode="Day" runat="server"></asp:Calendar>
<asp:Calendar runat="server" SelectionMode="Day" SelectedDate="08/15/2011 12:00:00 AM" ID="Calendar1" VisibleDate="08/03/2011 12:00:00 AM"></asp:Calendar>
<asp:Calendar SelectionMode="Day" SelectedDate="08/31/2011 12:00:00 AM" runat="server" ID="calDateTo"></asp:Calendar>
this could do it:
perl -ne 'if(m/name="(.*?)"/){ print $1 . "\n"; }'
I'm many moons late to the party but for simplicity I use something like this
var fileName = "I.Am.FileName.docx";_x000D_
var nameLen = fileName.length;_x000D_
var lastDotPos = fileName.lastIndexOf(".");_x000D_
var fileNameSub = false;_x000D_
if(lastDotPos === -1)_x000D_
{_x000D_
fileNameSub = false;_x000D_
}_x000D_
else_x000D_
{_x000D_
//Remove +1 if you want the "." left too_x000D_
fileNameSub = fileName.substr(lastDotPos + 1, nameLen);_x000D_
}_x000D_
document.getElementById("showInMe").innerHTML = fileNameSub;
_x000D_
<div id="showInMe"></div>
_x000D_
Run this to find all instances of Xcode in your filesystem:
for i in find / -name Xcode -print
; do echo $i; done
Try this
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
@Override
public void run() {
//your code here that talks with the UI level widgets/ try to access the UI
//elements from this block because this piece of snippet will run in the UI/MainThread.
}
});
You're thinking too complicated. It's actually just $('#'+openaddress)
.
I'm surprised no one has mentioned Google's Closure Compiler. It doesn't just minify/compress, it analyzes to find and remove unused code, and rewrites for maximum minification. It can also do type checking and will warn about syntax errors.
JQuery recently switched from YUI Compresser to Closure Compiler, and saw a "solid improvement"
You should check that what you are passing to foreach
is an array by using the is_array function
If you are not sure it's going to be an array you can always check using the following PHP example code:
if (is_array($variable)) {
foreach ($variable as $item) {
//do something
}
}
You have to use cin.getline()
:
char input[100];
cin.getline(input,sizeof(input));
Using the following ways using only two keys will be the easier:
control + Tab
or
Alt + Left/Right
You can use
timestamp=`date --rfc-3339=seconds`
This delivers in the format 2014-02-01 15:12:35-05:00
The back-tick (`
) characters will cause what is between them to be evaluated and have the result included in the line. date --help
has other options.
My problem was resolved just by adding http://
to my url address.
for example I used http://localhost:3000/movies
instead of localhost:3000/movies
.
YES!! There is a way to detach a busy device immediately - even if it is busy and cannot be unmounted forcefully. You may cleanup all later:
umount -l /PATH/OF/BUSY-DEVICE
umount -f /PATH/OF/BUSY-NFS (NETWORK-FILE-SYSTEM)
NOTE/CAUTION
umount
commands when inside mounted path (Folder/Drive/Device) itself. First, you may use pwd
command to validate your current directory path (which should not be the mounted path), then use cd
command to get out of the mounted path - to unmount it later using above commands.I used this solution to get realtime output on a subprocess. This loop will stop as soon as the process completes leaving out a need for a break statement or possible infinite loop.
sub_process = subprocess.Popen(my_command, close_fds=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while sub_process.poll() is None:
out = sub_process.stdout.read(1)
sys.stdout.write(out)
sys.stdout.flush()
Here is a handy function for Swift 4.2, shows an image with title text:-
override func viewDidLoad() {
super.viewDidLoad()
//Sets the navigation title with text and image
self.navigationItem.titleView = navTitleWithImageAndText(titleText: "Dean Stanley", imageName: "online")
}
func navTitleWithImageAndText(titleText: String, imageName: String) -> UIView {
// Creates a new UIView
let titleView = UIView()
// Creates a new text label
let label = UILabel()
label.text = titleText
label.sizeToFit()
label.center = titleView.center
label.textAlignment = NSTextAlignment.center
// Creates the image view
let image = UIImageView()
image.image = UIImage(named: imageName)
// Maintains the image's aspect ratio:
let imageAspect = image.image!.size.width / image.image!.size.height
// Sets the image frame so that it's immediately before the text:
let imageX = label.frame.origin.x - label.frame.size.height * imageAspect
let imageY = label.frame.origin.y
let imageWidth = label.frame.size.height * imageAspect
let imageHeight = label.frame.size.height
image.frame = CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight)
image.contentMode = UIView.ContentMode.scaleAspectFit
// Adds both the label and image view to the titleView
titleView.addSubview(label)
titleView.addSubview(image)
// Sets the titleView frame to fit within the UINavigation Title
titleView.sizeToFit()
return titleView
}
This is how I make forms full screen.
private void button1_Click(object sender, EventArgs e)
{
int minx, miny, maxx, maxy;
inx = miny = int.MaxValue;
maxx = maxy = int.MinValue;
foreach (Screen screen in Screen.AllScreens)
{
var bounds = screen.Bounds;
minx = Math.Min(minx, bounds.X);
miny = Math.Min(miny, bounds.Y);
maxx = Math.Max(maxx, bounds.Right);
maxy = Math.Max(maxy, bounds.Bottom);
}
Form3 fs = new Form3();
fs.Activate();
Rectangle tempRect = new Rectangle(1, 0, maxx, maxy);
this.DesktopBounds = tempRect;
}
HTTPBuilder is it. Very easy to use.
import groovyx.net.http.HTTPBuilder
def http = new HTTPBuilder('https://google.com')
def html = http.get(path : '/search', query : [q:'waffles'])
It is especially useful if you need error handling and generally more functionality than just fetching content with GET.
Following the idea posted by Andrew Seaford, this is done using sshfs:
echo "SuperHardToGuessPass:P" | sshfs -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no [email protected]:/mypath/ /mnt/source-tmp/ -o workaround=rename -o password_stdin
rsync -a /mnt/source-tmp/ /media/destination/
umount /mnt/source-tmp
There is a better way of checking radios and checkbox; you have to pass an array of values to the val method instead of a raw value
Note: If you simply pass the value by itself (without being inside an array), that will result in all values of "mygroup" being set to the value.
$("input[name=mygroup]").val([5]);
Here is the jQuery doc that explains how it works: http://api.jquery.com/val/#val-value
And .val([...])
also works with form elements like <input type="checkbox">
, <input type="radio">
, and <option>
s inside of a <select>
.
The inputs and the options having a value that matches one of the elements of the array will be checked or selected, while those having a value that don't match one of the elements of the array will be unchecked or unselected
Fiddle demonstrating this working: https://jsfiddle.net/92nekvp3/
Do this to convert safely a PNG to JPG with the transparency in white.
$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);
Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.
If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.
I'm going to try this the following way. I've placed the count variable inside the "onfocus" function so as to keep it from becoming a global variable. The idea is to create a counter for each image in a tumblr blog.
$(document).ready(function() {
$("#image1").onfocus(function() {
var count;
if (count == undefined || count == "" || count == 0) {
var count = 0;
}
count++;
$("#counter1").html("Image Views: " + count);
}
});
Then, outside the script tags and in the desired place in the body I'll add:
<div id="counter1"></div>
For those with spaces in the path, you are going to want something like this: n.b. It expands out to an absolute path, rather than relative, so if your running directory path has spaces in, these count too.
set SOURCE=path\with spaces\to\my.log
FOR /F "usebackq delims=" %%A IN ("%SOURCE%") DO (
ECHO %%A
)
To explain:
(path\with spaces\to\my.log)
Will not parse, because spaces. If it becomes:
("path\with spaces\to\my.log")
It will be handled as a string rather than a file path.
"usebackq delims="
See docs will allow the path to be used as a path (thanks to Stephan).
@Sheridan thx.. if I try your example with "DisplayedImagePath" on both sides, it works with absolute path as you show.
As for the relative paths, this is how I always connect relative paths, I first include the subdirectory (!) and the image file in my project.. then I use ~ character to denote the bin-path..
public string DisplayedImagePath
{
get { return @"~\..\images\osc.png"; }
}
This was tested, see below my Solution Explorer in VS2015..
Note: if you want a Click event, use the Button tag around the image,
<Button Click="image_Click" Width="128" Height="128" Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left">_x000D_
<Image x:Name="image" Source="{Binding DisplayedImagePath}" Margin="0,0,0,0" />_x000D_
</Button>
_x000D_
If you're executing this through PHP, what about this?
$hQuery = mysql_query("SELECT * FROM users");
while($hRow = mysql_fetch_array($hQuery)) {
$hOut .= $hRow['username'] . ", ";
}
$hOut = substr($hOut, 0, strlen($hOut) - 1);
echo $hOut;
Unfortunately, the time zone formats available to SimpleDateFormat (Java 6 and earlier) are not ISO 8601 compliant. SimpleDateFormat understands time zone strings like "GMT+01:00" or "+0100", the latter according to RFC # 822.
Even if Java 7 added support for time zone descriptors according to ISO 8601, SimpleDateFormat is still not able to properly parse a complete date string, as it has no support for optional parts.
Reformatting your input string using regexp is certainly one possibility, but the replacement rules are not as simple as in your question:
The easier solution is possibly to use the data type converter in JAXB, since JAXB must be able to parse ISO8601 date string according to the XML Schema specification. javax.xml.bind.DatatypeConverter.parseDateTime("2010-01-01T12:00:00Z")
will give you a Calendar
object and you can simply use getTime() on it, if you need a Date
object.
You could probably use Joda-Time as well, but I don't know why you should bother with that.
You can use on another class
public ArrayList<Integer> myNumbers = new Foo().myNumbers();
or
Foo myClass = new Foo();
public ArrayList<Integer> myNumbers = myclass.myNumbers();
Path
C:\Program Files\Java\jdk1.7.0_76\bin
Now you're set. Type javac
in cmd. All javac options will be displayed.
Is the first line in your script:
#!/bin/bash
or
#!/bin/sh
the sh shell produces this error messages, not bash
The reason this question still often arises is because, as you mentioned, somewhere somehow someone presumed as important wrote that the RFC states domain names without subdomain in front of them are not valid. If you read the RFC carefully, however, you'll find that this is not exactly what it says. In fact, RFC 1912 states:
Don't go overboard with CNAMEs. Use them when renaming hosts, but plan to get rid of them (and inform your users).
Some DNS hosts provide a way to get CNAME-like functionality at the zone apex (the root domain level, for the naked domain name) using a custom record type. Such records include, for example:
For each provider, the setup is similar: point the ALIAS or ANAME entry for your apex domain to example.domain.com, just as you would with a CNAME record. Depending on the DNS provider, an empty or @ Name value identifies the zone apex.
ALIAS or ANAME or @ example.domain.com.
If your DNS provider does not support such a record-type, and you are unable to switch to one that does, you will need to use subdomain redirection, which is not that hard, depending on the protocol or server software that needs to do it.
I strongly disagree with the statement that it's done only by "amateur admins" or such ideas. It's a simple "What does the name and its service need to do?" deal, and then to adapt your DNS config to serve those wishes; If your main services are web and e-mail, I don' t see any VALID reason why dropping the CNAMEs for-good would be problematic. After all, who would prefer @subdomain.domain.org over @domain.org ? Who needs "www" if you're already set with the protocol itself? It's illogical to assume that use of a root-domainname would be invalid.
Does the screenshot contain only the icon? If so, the L2 distance of the two images might suffice. If the L2 distance doesn't work, the next step is to try something simple and well established, like: Lucas-Kanade. Which I'm sure is available in OpenCV.
There is also a combination, you can use a return value with a recordset:
--Stored Procedure--
CREATE PROCEDURE [TestProc]
AS
BEGIN
DECLARE @Temp TABLE
(
[Name] VARCHAR(50)
)
INSERT INTO @Temp VALUES ('Mark')
INSERT INTO @Temp VALUES ('John')
INSERT INTO @Temp VALUES ('Jane')
INSERT INTO @Temp VALUES ('Mary')
-- Get recordset
SELECT * FROM @Temp
DECLARE @ReturnValue INT
SELECT @ReturnValue = COUNT([Name]) FROM @Temp
-- Return count
RETURN @ReturnValue
END
--Calling Code--
DECLARE @SelectedValue int
EXEC @SelectedValue = [TestProc]
SELECT @SelectedValue
--Results--
I'm using flow with vscode but had the same problem. I solved it with these steps:
Install the extension Flow Language Support
Disable the built-in TypeScript extension:
People run into this error when the Node.js process is still running and they are attempting to start the server again. Try this:
ps aux | grep node
This will print something along the lines of:
user 7668 4.3 1.0 42060 10708 pts/1 Sl+ 20:36 0:00 node server
user 7749 0.0 0.0 4384 832 pts/8 S+ 20:37 0:00 grep --color=auto node
In this case, the process will be the one with the pid 7668. To kill it and restart the server, run kill -9 7668
.
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
echo 'blah' . $_POST['fromPerson'];
}
Use either of these depending how you want backslashes in the shell variables handled (avar
is an awk variable, svar
is a shell variable):
awk -v avar="$svar" '... avar ...' file
awk 'BEGIN{avar=ARGV[1];ARGV[1]=""}... avar ...' "$svar" file
See http://cfajohnson.com/shell/cus-faq-2.html#Q24 for details and other options. The first method above is almost always your best option and has the most obvious semantics.
You can use this javascript
function to check users' OS simply
function getOS() {
var userAgent = window.navigator.userAgent,
platform = window.navigator.platform,
macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
iosPlatforms = ['iPhone', 'iPad', 'iPod'],
os = null;
if (macosPlatforms.indexOf(platform) !== -1) {
os = 'Mac OS';
} else if (iosPlatforms.indexOf(platform) !== -1) {
os = 'iOS';
} else if (windowsPlatforms.indexOf(platform) !== -1) {
os = 'Windows';
} else if (/Android/.test(userAgent)) {
os = 'Android';
} else if (!os && /Linux/.test(platform)) {
os = 'Linux';
}
return os;
}
alert(getOS());
I found a different solution to this issue. Apparently my IIS 7 did not have 32bit mode enabled in my Application Pool by default.
To enable 32bit mode, open IIS and select your Application Pool. Mine was named "ASP.NET v4.0".
Right click, go to "Advanced Settings" and change the section named:
"Enabled 32-bit Applications" to true.
Restart your web server and try again.
I found the fix from this blog reference: http://darrell.mozingo.net/2009/01/17/running-iis-7-in-32-bit-mode/
Additionally, you can change the settings on Visual Studio. In my case, I went to Tools > Options > Projects and Solutions > Web Projects
and checked Use the 64 bit version of IIS Express for web sites and projects
- This was on VS Pro 2015. Nothing else fixed it but this.
If they are separate classes you can do something like the following:
class A
{
private $name;
public function __construct()
{
$this->name = 'Some Name';
}
public function getName()
{
return $this->name;
}
}
class B
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
}
function getNameOfA()
{
return $this->a->getName();
}
}
$a = new A();
$b = new B($a);
$b->getNameOfA();
What I have done in this example is first create a new instance of the A
class. And after that I have created a new instance of the B
class to which I pass the instance of A
into the constructor. Now B
can access all the public members of the A
class using $this->a
.
Also note that I don't instantiate the A
class inside the B
class because that would mean I tighly couple the two classes. This makes it hard to:
B
classA
class for another classObviously you mean the baseurl. If so:
base url: URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash.
Root in codeigniter specifically means that the position where you can append your controller to your url.
For example, if the root is localhost/ci_installation/index.php/
, then to access the mycont
controller you should go to localhost/ci_installation/index.php/mycont
.
So, instead of writing such a long link you can (after loading "url" helper) , replace the term localhost/ci_installation/index.php/
by base_url()
and this function will return the same string url.
NOTE: if you hadn't appended index.php/
to your base_url
in your config.php
, then if you use base_url()
, it will return something like that localhost/ci_installation/mycont
. And that will not work, because you have to access your controllers from index.php
, instead of that you can place a .htaccess
file to your codeigniter installation position. Cope that the below code to it:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /imguplod/index.php/$1 [L]
And it should work :)
In Notepad++, you can use the Mark tab in the Find dialogue to Bookmark all lines matching your query which can be regex or normal (wildcard).
Then use Search > Bookmark > Remove Bookmarked Lines.
<a href="javascript:history.back(1)">Back</a>
this one (by Eiko) is perfect, use css to make a button of <a>
...
eg you can use this css class in <a>
as `
<a class=".back_button" href="javascript:history.back(1)">Back</a>`
.back_button {
display:block;
width:100px;
height:30px;
text-align:center;
background-color:yellow;
border:1px solid #000000;
}
Unfortunately, the Array type in VB6 didn't have all that many razzmatazz features. You are pretty much going to have to just iterate through the arrays and insert them manually into the third
Assuming both arrays are of the same length
Dim arr1() As Variant
Dim arr2() As Variant
Dim arr3() As Variant
arr1() = Array("A", 1, "B", 2)
arr2() = Array("C", 3, "D", 4)
ReDim arr3(UBound(arr1) + UBound(arr2) + 1)
Dim i As Integer
For i = 0 To UBound(arr1)
arr3(i * 2) = arr1(i)
arr3(i * 2 + 1) = arr2(i)
Next i
Updated: Fixed the code. Sorry about the previous buggy version. Took me a few minutes to get access to a VB6 compiler to check it.
Initializing the Canvas like below works for TypeScript/Angular solutions.
const canvas = <HTMLCanvasElement> document.getElementById("htmlElemId");
const context = canvas.getContext("2d");
I have deleted System.Web.dll from Bin frolder of my site.
I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?
You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
array.sort([compareFunction])
Parameters
compareFunction
Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.
In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:
13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return -1.
19. If Result(16) > Result(17), return 1.
20. Return +0.
The tomcat manual says:
Copy the web application archive file into directory $CATALINA_HOME/webapps/. When Tomcat is started, it will automatically expand the web application archive file into its unpacked form, and execute the application that way.
Have you tried Advanced Filter? Using your short list as the 'Criteria' and long list as the 'List Range'. Use the options: 'Filter in Place' and 'Unique Values'.
You should be presented with the list of unique values that only appear in your short list.
Alternatively, you can paste your Unique list to another location (on the same sheet), if you prefer. Choose the option 'Copy to another Location' and in the 'Copy to' box enter the cell reference (say F1) where you want the Unique list.
Note: this will work with the two columns (name/ID) too, if you select the two columns as both 'Criteria' and 'List Range'.
On Windows you can open a command window and type the command
sc qc mysql
Or:
sc qc mariadb
which (depending on your flavor and version) will output something like:
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: mariadb
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : "C:\Program Files\MariaDB 10.4\bin\mysqld.exe" "--defaults-file=C:\Program Files\MariaDB 10.4\data\my.ini" "MariaDB"
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : MariaDB
DEPENDENCIES :
SERVICE_START_NAME : NT AUTHORITY\NetworkService
From this you can see the location of the my.ini file.
You can also change it with the same "sc" command like this:
sc config mysql binPath= <binary path>
Or:
sc config mariadb binPath= <binary path>
For example:
sc config mariadb binpath= "\"C:\Program Files\MariaDB 10.4\bin\mysqld.exe\" \"--defaults-file=M:\data\my.ini\" \"MariaDB\""
For linux, I wrote a script called find_port.py which you can find here: https://github.com/dhylands/usb-ser-mon/blob/master/usb_ser_mon/find_port.py
It uses pyudev to enumerate all tty devices, and can match on various attributes.
Use the --list option to show all of the know USB serial ports and their attributes. You can filter by VID, PID, serial number, or vendor name. Use --help to see the filtering options.
find_port.py prints the /dev/ttyXXX name rather than the /dev/usb/... name.
There are two easy ways:
In your cpanel Go to cpanel/ softaculous/ wordpress, under the current installation, you will see the websites you have installed with the wordpress. Click the "edit detail" of the particular website and you will see your SQL database username and password.
In your server Access your FTP and view the wp-config.php
Linux In current Vscode 1.44.1 version
we could use ctrl+pageup for next editor and ctrl+pagedown for previous editor.
If there is a need to change
ctrl+shift+p > Preferences:Open Keyboard Shortcuts.
search for
nextEditor
change if needed by clicking it.
You've got several options how to do this, either:
urlencode()
or rawurlencode()
- functions designed to encode URLs for http protocolstr_replace()
- "heavy machinery" string replacestrtr()
- would have better performance than str_replace()
when replacing multiple characterspreg_replace()
use regular expressions (perl compatible)strtr()
Assuming that you want to replace "\t"
and " "
with "%20"
:
$replace_pairs = array(
"\t" => '%20',
" " => '%20',
);
return strtr( $text, $replace_pairs)
preg_replace()
You've got few options here, either replacing just space ~ ~
, again replacing space and tab ~[ \t]~
or all kinds of spaces ~\s~
:
return preg_replace( '~\s~', '%20', $text);
Or when you need to replace string like this "\t \t \t \t"
with just one %20
:
return preg_replace( '~\s+~', '%20', $text);
I assumed that you really want to use manual string replacement and handle more types of whitespaces such as non breakable space (
)
Try this:
def word(string, num)
string = 'Smith'
string[0..(num-1)]
end
Warning:
mysql_*
extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
Whenever possible, importing a file to MySQL should be delegated to MySQL client.
the answer from Raj is useful, but (because of file($filename)) it will fail if your mysql-dump not fits in memory
If you are on shared hosting and there are limitations like 30 MB and 12s Script runtime and you have to restore a x00MB mysql dump, you can use this script:
it will walk the dumpfile query for query, if the script execution deadline is near, it saves the current fileposition in a tmp file and a automatic browser reload will continue this process again and again ... If an error occurs, the reload will stop and an the error is shown ...
if you comeback from lunch your db will be restored ;-)
the noLimitDumpRestore.php:
// your config
$filename = 'yourGigaByteDump.sql';
$dbHost = 'localhost';
$dbUser = 'user';
$dbPass = '__pass__';
$dbName = 'dbname';
$maxRuntime = 8; // less then your max script execution limit
$deadline = time()+$maxRuntime;
$progressFilename = $filename.'_filepointer'; // tmp file for progress
$errorFilename = $filename.'_error'; // tmp file for erro
mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());
($fp = fopen($filename, 'r')) OR die('failed to open file:'.$filename);
// check for previous error
if( file_exists($errorFilename) ){
die('<pre> previous error: '.file_get_contents($errorFilename));
}
// activate automatic reload in browser
echo '<html><head> <meta http-equiv="refresh" content="'.($maxRuntime+2).'"><pre>';
// go to previous file position
$filePosition = 0;
if( file_exists($progressFilename) ){
$filePosition = file_get_contents($progressFilename);
fseek($fp, $filePosition);
}
$queryCount = 0;
$query = '';
while( $deadline>time() AND ($line=fgets($fp, 1024000)) ){
if(substr($line,0,2)=='--' OR trim($line)=='' ){
continue;
}
$query .= $line;
if( substr(trim($query),-1)==';' ){
if( !mysql_query($query) ){
$error = 'Error performing query \'<strong>' . $query . '\': ' . mysql_error();
file_put_contents($errorFilename, $error."\n");
exit;
}
$query = '';
file_put_contents($progressFilename, ftell($fp)); // save the current file position for
$queryCount++;
}
}
if( feof($fp) ){
echo 'dump successfully restored!';
}else{
echo ftell($fp).'/'.filesize($filename).' '.(round(ftell($fp)/filesize($filename), 2)*100).'%'."\n";
echo $queryCount.' queries processed! please reload or wait for automatic browser refresh!';
}
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
The first step is figuring out what the error actually is. In order to do this expand your MsBuild output to be diagnostic. This will reveal the actual command executed and hopefully the full error message as well
OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom"
instead of app:showAsAction="ifRoom"
since i am using v7 library.
However the title is coming at center of extended toolbar. How to make it appear at the top?
The quantile()
function will do much of what you probably want, but since the question was ambiguous, I will provide an alternate answer that does something slightly different from quantile()
.
ecdf(infert$age)(infert$age)
will generate a vector of the same length as infert$age
giving the proportion of infert$age
that is below each observation. You can read the ecdf
documentation, but the basic idea is that ecdf()
will give you a function that returns the empirical cumulative distribution. Thus ecdf(X)(Y)
is the value of the cumulative distribution of X at the points in Y. If you wanted to know just the probability of being below 30 (thus what percentile 30 is in the sample), you could say
ecdf(infert$age)(30)
The main difference between this approach and using the quantile()
function is that quantile()
requires that you put in the probabilities to get out the levels, and this requires that you put in the levels to get out the probabilities.
Follow the steps:
More details for each step Click Here
You can do it easily with regex:
string subject = "(913)-444-5555";
string result = Regex.Replace(subject, "[^0-9]", ""); // result = "9134445555"
As an alternative you may want to check out BridgeIt at bridgeit.mobi. Open source, it has resolved the browser performance / consistency issue discussed above in that it leverages the standard browser on the device vs. the web-view browser. It also allows you to access the native features without having to worry about app store deployments and/or native containers.
I've used if for simple camera based access and scanner access and it works well for simple apps. Documentation is a bit light. Not sure how it would do on more complex apps.
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
If you set a different field separator, you can directly use a for
loop:
IFS=","
for v in $variable
do
# things with "$v" ...
done
You can also store the values in an array and then loop through it as indicated in How do I split a string on a delimiter in Bash?:
IFS=, read -ra values <<< "$variable"
for v in "${values[@]}"
do
# things with "$v"
done
$ variable="abc,def,ghij"
$ IFS=","
$ for v in $variable
> do
> echo "var is $v"
> done
var is abc
var is def
var is ghij
You can find a broader approach in this solution to How to iterate through a comma-separated list and execute a command for each entry.
Examples on the second approach:
$ IFS=, read -ra vals <<< "abc,def,ghij"
$ printf "%s\n" "${vals[@]}"
abc
def
ghij
$ for v in "${vals[@]}"; do echo "$v --"; done
abc --
def --
ghij --
You can use the regex
(\s)\1
and
replace it with $1
.
Java code:
str = str.replaceAll("(\\s)\\1","$1");
If the input is "foo\t\tbar "
you'll get "foo\tbar "
as output
But if the input is "foo\t bar"
it will remain unchanged because it does not have any consecutive whitespace characters.
If you treat all the whitespace characters(space, vertical tab, horizontal tab, carriage return, form feed, new line) as space then you can use the following regex to replace any number of consecutive white space with a single space:
str = str.replaceAll("\\s+"," ");
But if you want to replace two consecutive white space with a single space you should do:
str = str.replaceAll("\\s{2}"," ");
Setting the underlying socket ReceiveTimeout
property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout
. You can read the docs for more information.
Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.
I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
var bytes = 0;
client.Client.ReceiveTimeout = 20;
do
{
try
{
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
catch (IOException ex)
{
// if the ReceiveTimeout is reached an IOException will be raised...
// with an InnerException of type SocketException and ErrorCode 10060
var socketExept = ex.InnerException as SocketException;
if (socketExept == null || socketExept.ErrorCode != 10060)
// if it's not the "expected" exception, let's not hide the error
throw ex;
// if it is the receive timeout, then reading ended
bytes = 0;
}
} while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
here is another example and how indexOf
is working.
public int indexOf(Object target) {
for (int i = 0; i < array.length; i++) {
if (equals(target, array[i])) {
return i;
}
}
return -1;
}
That's called SQL INJECTION. The '
tries to open/close a string in your mysql query. You should always escape any string that gets into your queries.
for example,
instead of this:
"VALUES ('$sender_id') "
do this:
"VALUES ('". mysql_real_escape_string($sender_id) ."') "
(or equivalent, of course)
However, it's better to automate this, using PDO, named parameters, prepared statements or many other ways. Research about this and SQL Injection (here you have some techniques).
Hope it helps. Cheers
Use the matplotlib savefig
function with the keyword argument transparent=True
to save the image as a png file.
In [30]: x = np.linspace(0,6,31)
In [31]: y = np.exp(-0.5*x) * np.sin(x)
In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]
In [33]: savefig('demo.png', transparent=True)
Result:
Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display
command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.
One common use is for template-typedef workaround classes like following:
template <class TObj>
class MyLibrariesSmartPointer
{
MyLibrariesSmartPointer();
public:
typedef smart_ptr<TObj> type;
};
Obviously a public non-implemented constructor would work aswell, but a private construtor raises a compile time error instead of a link time error, if anyone tries to instatiate MyLibrariesSmartPointer<SomeType>
instead of MyLibrariesSmartPointer<SomeType>::type
, which is desireable.
I got the same issue. If the app is foreground - it triggers my background service where I can update my database based on the notification type. But, the app goes to the background - the default notification service will be taken care to show the notification to the user.
Here is my solution to identify app in background and trigger your background service,
public class FirebaseBackgroundService extends WakefulBroadcastReceiver {
private static final String TAG = "FirebaseService";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "I'm in!!!");
if (intent.getExtras() != null) {
for (String key : intent.getExtras().keySet()) {
Object value = intent.getExtras().get(key);
Log.e("FirebaseDataReceiver", "Key: " + key + " Value: " + value);
if(key.equalsIgnoreCase("gcm.notification.body") && value != null) {
Bundle bundle = new Bundle();
Intent backgroundIntent = new Intent(context, BackgroundSyncJobService.class);
bundle.putString("push_message", value + "");
backgroundIntent.putExtras(bundle);
context.startService(backgroundIntent);
}
}
}
}
}
In the manifest.xml
<receiver android:exported="true" android:name=".FirebaseBackgroundService" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
Tested this solution in latest android 8.0 version. Thanks
When you call for i in a:
, you are getting the actual elements, not the indexes. When we reach the last element, that is 3
, b.append(a[i+1]-a[i])
looks for a[4]
, doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like
for i in range(0, len(a)-1): Do something
Your current code won't work yet for the do something part though ;)
Horizontal centering is easy: text-align: center;
. Vertical centering of text inside an element can be done by setting line-height
equal to the container height, but this has subtle differences between browsers. On small elements, like a notification badge, these are more pronounced.
Better is to set line-height
equal to font-size
(or slightly smaller) and use padding. You'll have to adjust your height to accomodate.
Here's a CSS-only, single <div>
solution that looks pretty iPhone-like. They expand with content.
Demo: http://jsfiddle.net/ThinkingStiff/mLW47/
Output:
CSS:
.badge {
background: radial-gradient( 5px -9px, circle, white 8%, red 26px );
background-color: red;
border: 2px solid white;
border-radius: 12px; /* one half of ( (border * 2) + height + padding ) */
box-shadow: 1px 1px 1px black;
color: white;
font: bold 15px/13px Helvetica, Verdana, Tahoma;
height: 16px;
min-width: 14px;
padding: 4px 3px 0 3px;
text-align: center;
}
HTML:
<div class="badge">1</div>
<div class="badge">2</div>
<div class="badge">3</div>
<div class="badge">44</div>
<div class="badge">55</div>
<div class="badge">666</div>
<div class="badge">777</div>
<div class="badge">8888</div>
<div class="badge">9999</div>
The easiest solution is to use
Firstly create a class Instance and call the non-static method using that instance. e.g,
class demo {
public static void main(String args[]) {
demo d = new demo();
d.add(10,20); // to call the non-static method
}
public void add(int x ,int y) {
int a = x;
int b = y;
int c = a + b;
System.out.println("addition" + c);
}
}
When using NOT IN you should ensure that none of the values are NULL:
SELECT mac, creation_date
FROM logs
WHERE logs_type_id=11
AND mac NOT IN (
SELECT mac
FROM consols
WHERE mac IS NOT NULL -- add this
)
In XMLHttpRequest
, using XMLHttpRequest.responseText
may raise the exception like below
Failed to read the \'responseText\' property from \'XMLHttpRequest\':
The value is only accessible if the object\'s \'responseType\' is \'\'
or \'text\' (was \'arraybuffer\')
Best way to access the response from XHR as follows
function readBody(xhr) {
var data;
if (!xhr.responseType || xhr.responseType === "text") {
data = xhr.responseText;
} else if (xhr.responseType === "document") {
data = xhr.responseXML;
} else {
data = xhr.response;
}
return data;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(readBody(xhr));
}
}
xhr.open('GET', 'http://www.google.com', true);
xhr.send(null);
Here is an example from my code (for threaded pool, but just change class name and you'll have process pool):
def execute_run(rp):
... do something
pool = ThreadPoolExecutor(6)
for mat in TESTED_MATERIAL:
for en in TESTED_ENERGIES:
for ecut in TESTED_E_CUT:
rp = RunParams(
simulations, DEST_DIR,
PARTICLE, mat, 960, 0.125, ecut, en
)
pool.submit(execute_run, rp)
pool.join()
Basically:
pool = ThreadPoolExecutor(6)
creates a pool for 6 threadspool.submit(execute_run, rp)
adds a task to pool, first arogument is a function called in in a thread/process, rest of the arguments are passed to the called function. pool.join
waits until all tasks are done. for UNIQUEIDENTIFIER datatype in sql server try this
Alter table table_name
add ID UNIQUEIDENTIFIER not null unique default(newid())
If you want to create primary key out of that column use this
ALTER TABLE table_name
ADD CONSTRAINT PK_name PRIMARY KEY (ID);
Below changes worked for me and hope the same works for you.
Change the version of Java from 11 to 8 in pom.xml file
<java.version>1.8</java.version>
Go to, File -> Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler
Here, in Module column you can see your project listed and in Target bytecode version column, Java version for the project is already specified(mostly 11), change it to 8
Go to, File -> Project Structure -> Modules. Here, in Source tab, you can see Language level option, choose 8 - Lambdas, type annotations etc.. Finally, choose Apply and OK, you're good to go.
The easiest is probably to create a PKCS#12 file using OpenSSL:
openssl pkcs12 -export -in abc.crt -inkey abc.key -out abc.p12
You should be able to use the resulting file directly using the PKCS12
keystore type.
If you really need to, you can convert it to JKS using keytool -importkeystore
(available in keytool
from Java 6):
keytool -importkeystore -srckeystore abc.p12 \
-srcstoretype PKCS12 \
-destkeystore abc.jks \
-deststoretype JKS
You don't need to iterate through the DataGrid
rows, you can achieve your goal with a more simple solution.
In order to match your row you can iterate through you collection that was bound to your DataGrid.ItemsSource
property then assign this item to you DataGrid.SelectedItem
property programmatically, alternatively you can add it to your DataGrid.SelectedItems
collection if you want to allow the user to select more than one row. See the code below:
<Window x:Class="ProgGridSelection.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="OnWindowLoaded">
<StackPanel>
<DataGrid Name="empDataGrid" ItemsSource="{Binding}" Height="200"/>
<TextBox Name="empNameTextBox"/>
<Button Content="Click" Click="OnSelectionButtonClick" />
</StackPanel>
public partial class MainWindow : Window
{
public class Employee
{
public string Code { get; set; }
public string Name { get; set; }
}
private ObservableCollection<Employee> _empCollection;
public MainWindow()
{
InitializeComponent();
}
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
// Generate test data
_empCollection =
new ObservableCollection<Employee>
{
new Employee {Code = "E001", Name = "Mohammed A. Fadil"},
new Employee {Code = "E013", Name = "Ahmed Yousif"},
new Employee {Code = "E431", Name = "Jasmin Kamal"},
};
/* Set the Window.DataContext, alternatively you can set your
* DataGrid DataContext property to the employees collection.
* on the other hand, you you have to bind your DataGrid
* DataContext property to the DataContext (see the XAML code)
*/
DataContext = _empCollection;
}
private void OnSelectionButtonClick(object sender, RoutedEventArgs e)
{
/* select the employee that his name matches the
* name on the TextBox
*/
var emp = (from i in _empCollection
where i.Name == empNameTextBox.Text.Trim()
select i).FirstOrDefault();
/* Now, to set the selected item on the DataGrid you just need
* assign the matched employee to your DataGrid SeletedItem
* property, alternatively you can add it to your DataGrid
* SelectedItems collection if you want to allow the user
* to select more than one row, e.g.:
* empDataGrid.SelectedItems.Add(emp);
*/
if (emp != null)
empDataGrid.SelectedItem = emp;
}
}
If 0 is your default value, you can just use a simple assignment:
ddlCustomerNumber.SelectedValue = GetCustomerNumberCookie().ToString();
This automatically selects the proper list item, if the DDL contains the value of the cookie. If it doesn't contain it, this call won't change the selection, so it stays at the default selection. If the latter one is the same as value 0, then it's the perfect solution for you.
I use this mechanism quite a lot and find it very handy.
Just as simple as this:
$("#myElem").show("slow").delay(5000).hide("slow");
This is not the same as using a sequence. When using a sequence, you are not inserting or updating anything. You are simply retrieving the next sequence value. It looks like hibernate does not support it.
In WebApi 2 you can add this to global.asax
protected void Application_PostAuthorizeRequest()
{
System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
Then you could access the session through:
HttpContext.Current.Session
Basically you can’t put an icon inside of a textInput but you can fake it by wrapping it inside a view and setting up some simple styling rules.
Here's how it works:
Code:
<View style={styles.passwordContainer}>
<TextInput
style={styles.inputStyle}
autoCorrect={false}
secureTextEntry
placeholder="Password"
value={this.state.password}
onChangeText={this.onPasswordEntry}
/>
<Icon
name='what_ever_icon_you_want'
color='#000'
size={14}
/>
</View>
Style:
passwordContainer: {
flexDirection: 'row',
borderBottomWidth: 1,
borderColor: '#000',
paddingBottom: 10,
},
inputStyle: {
flex: 1,
},
(Note: the icon is underneath the TextInput so it appears on the far right, if it was above TextInput it would appear on the left.)
A NULL
pointer points to memory that doesn't exist. This may be address 0x00000000
or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The *
operator is the dereferencing operator:
int a, b, c; // some integers
int *pi; // a pointer to an integer
a = 5;
pi = &a; // pi points to a
b = *pi; // b is now 5
pi = NULL;
c = *pi; // this is a NULL pointer dereference
This is exactly the same thing as a NullReferenceException
in C#, except that pointers in C can point to any data object, even elements inside an array.
Here I got the error:
Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
Because you didn't pass a base64-encoded string. Look at your functions: both download
and dataURItoBlob
do expect a data URI for some reason; you however are passing a plain html markup string to download
in your example.
Not only is HTML invalid as base64, you are calling .split(',')[1]
on it which will yield undefined
- and "undefined"
is not a valid base64-encoded string either.
I don't know, but I read that I need to encode my string to base64
That doesn't make much sense to me. You want to encode it somehow, only to decode it then?
What should I call and how?
Change the interface of your download
function back to where it received the filename
and text
arguments.
Notice that the BlobBuilder
does not only support appending whole strings (so you don't need to create those ArrayBuffer
things), but also is deprecated in favor of the Blob
constructor.
Can I put a name on my saved file?
Yes. Don't use the Blob
constructor, but the File
constructor.
function download(filename, text) {
try {
var file = new File([text], filename, {type:"text/plain"});
} catch(e) {
// when File constructor is not supported
file = new Blob([text], {type:"text/plain"});
}
var url = window.URL.createObjectURL(file);
…
}
download('test.html', "<html>" + document.documentElement.innerHTML + "</html>");
See JavaScript blob filename without link on what to do with that object url, just setting the current location to it doesn't work.
If it is a windows form Datagrid, you could use the below code to format the datetime for a column
dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss";
EDIT :
Apart from this, if you need the datetime in AM/PM format, you could use the below code
dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";
with org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users]
, you are trying to select from the users
table. But you are annotating your class with @Table( name = "Users" )
. So either use users
, or Users
.
by creating an absolute-positioned link inside relative-positioned div.. You need set the link width & height as button dimensions, and left&top coordinates for the left-top corner of button within the wrapping div.
<div style="position:relative">
<img src="" width="??" height="??" />
<a href="#" style="display:block; width:247px; height:66px; position:absolute; left: 48px; top: 275px;"></a>
</div>
I have set a php code which can help in case you want to access Instagram images without api on basis of hashtag
Jenkins has a 'Replay' feature, which enables you to quickly replay a job without updating sources:
Try this may work..
<html>
<?php $num = 1; ?>
<div id="Count"><?php echo $num; ?></div>
<input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
<br>
<script>
function Inc() {
i = parseInt(document.getElementById('Count').innerHTML);
document.getElementById('Count').innerHTML = i+1;
}
</script>
</html>
The answer is (almost) ALL
(7-bit ASCII).
If the inclusion rules is "...allowed under some/any/none conditions..."
Just by looking at one of several possible inclusion rules for allowed text in the "domain text" part in RFC 5322 at the top of page 17 we find:
dtext = %d33-90 / ; Printable US-ASCII
%d94-126 / ; characters not including
obs-dtext ; "[", "]", or "\"
the only three missing chars in this description are used in domain-literal []
, to form a quoted-pair \
, and the white space character (%d32). With that the whole range 32-126 (decimal) is used. A similar requirement appear as "qtext" and "ctext". Many control characters are also allowed/used. One list of such control chars appears in page 31 section 4.1 of RFC 5322 as obs-NO-WS-CTL.
obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
%d11 / ; characters that do not
%d12 / ; include the carriage
%d14-31 / ; return, line feed, and
%d127 ; white space characters
All this control characters are allowed as stated at the start of section 3.5:
.... MAY be used, the use of US-ASCII control characters (values
1 through 8, 11, 12, and 14 through 31) is discouraged ....
And such an inclusion rule is therefore "just too wide". Or, in other sense, the expected rule is "too simplistic".
unique_ptr
is the light-weight smart pointer of choice if you just have a dynamic object somewhere for which one consumer has sole (hence "unique") responsibility -- maybe a wrapper class that needs to maintain some dynamically allocated object. unique_ptr
has very little overhead. It is not copyable, but movable. Its type is template <typename D, typename Deleter> class unique_ptr;
, so it depends on two template parameters.
unique_ptr
is also what auto_ptr
wanted to be in the old C++ but couldn't because of that language's limitations.
shared_ptr
on the other hand is a very different animal. The obvious difference is that you can have many consumers sharing responsibility for a dynamic object (hence "shared"), and the object will only be destroyed when all shared pointers have gone away. Additionally you can have observing weak pointers which will intelligently be informed if the shared pointer they're following has disappeared.
Internally, shared_ptr
has a lot more going on: There is a reference count, which is updated atomically to allow the use in concurrent code. Also, there's plenty of allocation going on, one for an internal bookkeeping "reference control block", and another (often) for the actual member object.
But there's another big difference: The shared pointers type is always template <typename T> class shared_ptr;
, and this is despite the fact that you can initialize it with custom deleters and with custom allocators. The deleter and allocator are tracked using type erasure and virtual function dispatch, which adds to the internal weight of the class, but has the enormous advantage that different sorts of shared pointers of type T
are all compatible, no matter the deletion and allocation details. Thus they truly express the concept of "shared responsibility for T
" without burdening the consumer with the details!
Both shared_ptr
and unique_ptr
are designed to be passed by value (with the obvious movability requirement for the unique pointer). Neither should make you worried about the overhead, since their power is truly astounding, but if you have a choice, prefer unique_ptr
, and only use shared_ptr
if you really need shared responsibility.
From the man page, npm start:
runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.
Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.
Anyhow, what really happens is that npm looks in your package.json file, and if you have something like
"scripts": { "start": "coffee server.coffee" }
then it will do that. If npm can't find your start script, it defaults to:
node server.js
localeCompare()
is slow, so if you don't care about the "correct" ordering of non-English-character strings, try your original method or the cleaner-looking:
str1 < str2 ? -1 : +(str1 > str2)
This is an order of magnitude faster than localeCompare()
on my machine.
The +
ensures that the answer is always numeric rather than boolean.
Also add the key "StartingMonthColumn" in App.config that you run application from, for example in the App.config of the test project.
POJO class acts as a bean which is used to set and get the value.
public class Data
{
private int id;
private String deptname;
private String date;
private String name;
private String mdate;
private String mname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMdate() {
return mdate;
}
public void setMdate(String mdate) {
this.mdate = mdate;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
}
Register an event listener for keyup
event:
document.getElementById("input").addEventListener("keyup", function(e){
var someVarName = input.value;
sessionStorage.setItem("someVarKey", someVarName);
input.value = sessionStorage.getItem("someVarKey");
});
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
Convert local time zone string to UTC string.
e.g. New Zealand Time Zone
$datetime = "2016-02-01 00:00:01";
$given = new DateTime($datetime, new DateTimeZone("Pacific/Auckland"));
$given->setTimezone(new DateTimeZone("UTC"));
$output = $given->format("Y-m-d H:i:s");
echo ($output);
Linq equivalents of Map and Reduce: If you’re lucky enough to have linq then you don’t need to write your own map and reduce functions. C# 3.5 and Linq already has it albeit under different names.
Map is Select
:
Enumerable.Range(1, 10).Select(x => x + 2);
Reduce is Aggregate
:
Enumerable.Range(1, 10).Aggregate(0, (acc, x) => acc + x);
Filter is Where
:
Enumerable.Range(1, 10).Where(x => x % 2 == 0);
The easiest way I've seen is to use Google Fonts.
Go to Google Fonts and choose a font, then Google will give you a link to put in your HTML.
Then add this to your custom.css:
h1, h2, h3, h4, h5, h6 {
font-family: 'Your Font' !important;
}
p, div {
font-family: 'Your Font' !important;
}
or
body {
font-family: 'Your Font' !important;
}
The following steps are performed in the Git browser powered by Atlassian (Bitbucket server)
Making {current-branch} as master
master
and name it “master-duplicate”.After reading all the answers, I noticed most didn't work for me. So I did some research and here is what I got. Only try this if step 1 doesn't work.
Open go to C:\Program Files (x86)\Java or C:\Program Files\Java
jdk
folder and then the bin
folder.ii. Copy the path and add it to environment variables. Make sure you separate variables with a semi-colon, ;
. For example, "C:\Yargato\bin;C:\java\bin;". If you don't, it will cause more errors.
iii. Go to the jre
folder and open its bin
folder.
iv. Here search for rt.jar file. Mine is:
C:\Program Files (x86)\Java\jre1.8.0_73\lib\rt.jar Copy and under environment variable and search for the classpath variable and paste it there.
Even though the question is about gaining some space removing the address bar, you can also gain some space by toggling the bookmark bar on and off, using Ctrl + Shift + B, or ? Cmd + Shift + B, in Mac OS.
I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.
I just made two changes and I don't which help.
Go to IIS 6 Manager
Select properties of SMTP server
On tab Access, select Relays
Add your public IP address
Close the dialog and on the same tab click to Authentication button.
Add Integrated Windows Authentication
Maybe some step is not needed, but it works.
You only need to check if response is ok coz the call not returning anything.
var json = {
json: JSON.stringify({
a: 1,
b: 2
}),
delay: 3
};
fetch('/echo/json/', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then((response) => {if(response.ok){alert("the call works ok")}})
.catch (function (error) {
console.log('Request failed', error);
});
There are many ways you can take back of table.
A persistent context represents the entities which hold data and are qualified to be persisted in some persistent storage like a database. Once we commit
a transaction under a session which has these entities attached with, Hibernate flushes the persistent context and changes(insert/save, update or delete) on them are persisted in the persistent storage.
I don't know much about the MySQL command line interface, but assuming you only need help with the bashing, you should try to either swap the commands around like so:
myvariable=$(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p$password)
which echos the string into MySQL. Or, you can be more fancy and use some new bash-features (the here string)
myvariable=$(mysql database -u $user -p$password<<<"SELECT A, B, C FROM table_a")
resulting in the same thing (assuming you're using a recent enough bash version), without involving echo.
Please note that the -p$password is not a typo, but is the way MySQL expects passwords to be entered through the command line (with no space between the option and value).
Note that myvariable will contain everything that MySQL outputs on standard out (usually everything but error messages), including any and all column headers, ASCII-art frames and so on, which may or may not be what you want.
EDIT:
As has been noted, there appears to be a -e
parameter to MySQL, I'd go for that one, definitely.
One of the way to browse your database is to use questoid sqlite manager.
# 1. Download questoid manager from this link .
# 2. Drop this file into your eclipse --> dropins.
# 3. Restart your eclipse.
# 4. Now go to your file explorer and click your database. you can find a blue database icon enabled in the top right corner.
# 5. Double click the icon and you can see ur inserted fields/tables/ in the database
The way I know is easy.
var NSArray_variable = NSArray_Object[n]
var stringVarible = NSArray_variable as String
n
is the inner position in the array
This in SWIFT Language.
It might work in Objective C
Step 1: Implement an interface with your activity class
public class AuthenticatedMainActivity extends Activity implements FragmentManager.OnBackStackChangedListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
.............
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.frame_container,fragment, "First").addToBackStack(null).commit();
}
private void switchFragment(Fragment fragment){
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).addToBackStack("Tag").commit();
}
@Override
public void onBackStackChanged() {
FragmentManager fragmentManager = getFragmentManager();
System.out.println("@Class: SummaryUser : onBackStackChanged "
+ fragmentManager.getBackStackEntryCount());
int count = fragmentManager.getBackStackEntryCount();
// when a fragment come from another the status will be zero
if(count == 0){
System.out.println("again loading user data");
// reload the page if user saved the profile data
if(!objPublicDelegate.checkNetworkStatus()){
objPublicDelegate.showAlertDialog("Warning"
, "Please check your internet connection");
}else {
objLoadingDialog.show("Refreshing data...");
mNetworkMaster.runUserSummaryAsync();
}
// IMPORTANT: remove the current fragment from stack to avoid new instance
fragmentManager.removeOnBackStackChangedListener(this);
}// end if
}
}
Step 2: When you call the another fragment add this method:
String backStateName = this.getClass().getName();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
Fragment fragmentGraph = new GraphFragment();
Bundle bundle = new Bundle();
bundle.putString("graphTag", view.getTag().toString());
fragmentGraph.setArguments(bundle);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragmentGraph)
.addToBackStack(backStateName)
.commit();
Others have commented on the (incorrect) use of 2/11
to specify the desired interval.
I personally however prefer writing things like that using ANSI interval
literals which makes reading the query much easier:
sysdate - interval '2' hour
It also has the advantage of being portable, many DBMS support this. Plus I don't have to fire up a calculator to find out how many hours the expression means - I'm pretty bad with mental arithmetics ;)
The explicit
keyword makes a conversion constructor to non-conversion constructor. As a result, the code is less error prone.
Try:
fs.readFile("test.txt", "utf8", function(err, data) {...});
Basically, you need to specify the encoding.
Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update
).
But unfortunately there is no way to clone
/ mirror / update
the hooks, as I wanted...
I have found this very interesting thread about cloning/mirroring the hooks:
http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread
I learned:
The hooks are not considered part of the repository contents.
There is more data, like the .git/description
folder, which does not get cloned, just as the hooks.
The default hooks that appear in the hooks
dir comes from the TEMPLATE_DIR
There is this interesting template
feature on git.
So, I may either ignore this "clone the hooks thing", or go for a rsync
strategy, given the purposes of my mirror (backup + source for other clones, only).
Well... I will just forget about hooks cloning, and stick to the git remote update
way.
clone
/ update
process, but also stashes, rerere, etc... So, for a strict backup, rsync
or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update
.Thanks! Improved a bit of my own "git-fu"... :-)
Accroding to Thinking in Java by Bruce Eckel, one use case for explicit System.gc() call is when you want to force finalization, i.e. the call to finalize method.
As the error message says, non-default argument til
should not follow default argument hgt
.
Changing order of parameters (function call also be adjusted accordingly) or making hgt
non-default parameter will solve your problem.
def a(len1, hgt=len1, til, col=0):
->
def a(len1, hgt, til, col=0):
UPDATE
Another issue that is hidden by the SyntaxError.
os.system
accepts only one string parameter.
def a(len1, hgt, til, col=0):
system('mode con cols=%s lines=%s' % (len1, hgt))
system('title %s' % til)
system('color %s' % col)
I used this blog post to install it in my machine: http://luminite.wordpress.com/2012/09/06/installing-oracle-database-xe-11g-on-windows-7-64-bit-machine/
The only thing you have to do is replace a registry value during the installation, I've done it about three times already, and every time found a different reference on-line, none here on stackoverflow.
EDIT: as @kc2001 noted, regedit must be run as Administrator, and added this tutorial: (a bit more colorful): http://www.hanmiaojuan.com/2013/03/install-oracle-xe-11g-for-windows7-64bits.html
Will result always be the floor of the division? What is the defined behavior?
Not quite. It rounds toward 0, rather than flooring.
6.5.5 Multiplicative operators
6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
and the corresponding footnote:
- This is often called ‘‘truncation toward zero’’.
Of course two points to note are:
3 The usual arithmetic conversions are performed on the operands.
and:
5 The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
[Note: Emphasis mine]
It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:
http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/
I added the snippet below as a tl;dr
#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
case $OPTION in
h)
usage
exit 1
;;
t)
TEST=$OPTARG
;;
r)
SERVER=$OPTARG
;;
p)
PASSWD=$OPTARG
;;
v)
VERBOSE=1
;;
?)
usage
exit
;;
esac
done
if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
usage
exit 1
fi
./script.sh -t test -r server -p password -v
For Full Page Scrolling Screenshot
If you want to capture a full View screenshot (Which contains a scrollview or so) then have a check at this library
All you have to do is import the Gradel, and create an object of BigScreenshot
BigScreenshot longScreenshot = new BigScreenshot(this, x, y);
A callback will be received with the bitmap of the Screenshots taken while automatically scrolling through the screen view group and at the end assembled together.
@Override public void getScreenshot(Bitmap bitmap) {}
Which can be saved to the gallery or whatsoever usage is necessary their after
The following solution is inspired by the SocketUtils implementation of Spring-core (Apache license).
Compared to other solutions using Socket(...)
it is pretty fast (testing 1000 TCP ports in less than a second):
public static boolean isTcpPortAvailable(int port) {
try (ServerSocket serverSocket = new ServerSocket()) {
// setReuseAddress(false) is required only on OSX,
// otherwise the code will not work correctly on that platform
serverSocket.setReuseAddress(false);
serverSocket.bind(new InetSocketAddress(InetAddress.getByName("localhost"), port), 1);
return true;
} catch (Exception ex) {
return false;
}
}
Seems quite simple these days. This is the Swift version.
let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
view.addGestureRecognizer(tap)
@objc func viewTapped(recognizer: UIGestureRecognizer)
{
//Do what you need to do!
}
You could use overloads:
public static string BuildClause(List<string> l){...}
public static string BuildClause(List<int> l){...}
public static string BuildClause<T>(List<T> l){...}
Or you could inspect the type of the generic parameter:
Type listType = typeof(T);
if(listType == typeof(int)){...}
As of Java 8, you can simply use java.util.Base64 to try and decode the string:
String someString = "...";
Base64.Decoder decoder = Base64.getDecoder();
try {
decoder.decode(someString);
} catch(IllegalArgumentException iae) {
// That string wasn't valid.
}
I have found one related behaviour that may help (sounds like your specific problem runs deeper though):
Flash checks whether a source file needs recompiling by looking at timestamps. If its compiled version is older than the source file, it will recompile. But it doesn't check whether the compiled version was generated from the same source file or not.
Specifically, if you have your actionscript files under version control, and you Revert a change, the reverted file will usually have an older timestamp, and Flash will ignore it.
btn1.setId(1);
addRule()
, check
out the android java docs for this
LayoutParams
object.You need to Override equals
and hashCode
.
equals
will compare the objects for equality according to the properties you need and hashCode
is mandatory in order for your objects to be used correctly in Collections
and Maps