The answer is YES, but shouldn't use 'Background Fetch' or 'Remote notification'. PushKit is the answer you desire.
In summary, PushKit, the new framework in ios 8, is the new push notification mechanism which can silently launch your app into the background with no visual alert prompt even your app was killed by swiping out from app switcher, amazingly you even cannot see it from app switcher.
PushKit reference from Apple:
The PushKit framework provides the classes for your iOS apps to receive pushes from remote servers. Pushes can be of one of two types: standard and VoIP. Standard pushes can deliver notifications just as in previous versions of iOS. VoIP pushes provide additional functionality on top of the standard push that is needed to VoIP apps to perform on-demand processing of the push before displaying a notification to the user.
To deploy this new feature, please refer to this tutorial: https://zeropush.com/guide/guide-to-pushkit-and-voip - I've tested it on my device and it works as expected.
If you do not want to use angular-ui-router, but would like to have your controllers lazy loaded via RequireJS, there are couple of problems with event $routeChangeStart
when using your controllers as RequireJS modules (lazy loaded).
You cannot be sure the controller will be loaded before $routeChangeStart
gets triggered -- in fact it wont be loaded. That means you cannot access properties of next
route like locals
or $$route
because they are not yet setup.
Example:
app.config(["$routeProvider", function($routeProvider) {
$routeProvider.when("/foo", {
controller: "Foo",
resolve: {
controller: ["$q", function($q) {
var deferred = $q.defer();
require(["path/to/controller/Foo"], function(Foo) {
// now controller is loaded
deferred.resolve();
});
return deferred.promise;
}]
}
});
}]);
app.run(["$rootScope", function($rootScope) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log(next.$$route, next.locals); // undefined, undefined
});
}]);
This means you cannot check access rights in there.
Solution:
As loading of controller is done via resolve, you can do the same with your access control check:
app.config(["$routeProvider", function($routeProvider) {
$routeProvider.when("/foo", {
controller: "Foo",
resolve: {
controller: ["$q", function($q) {
var deferred = $q.defer();
require(["path/to/controller/Foo"], function(Foo) {
// now controller is loaded
deferred.resolve();
});
return deferred.promise;
}],
access: ["$q", function($q) {
var deferred = $q.defer();
if (/* some logic to determine access is granted */) {
deferred.resolve();
} else {
deferred.reject("You have no access rights to go there");
}
return deferred.promise;
}],
}
});
}]);
app.run(["$rootScope", function($rootScope) {
$rootScope.$on("$routeChangeError", function(event, next, current, error) {
console.log("Error: " + error); // "Error: You have no access rights to go there"
});
}]);
Note here that instead of using event $routeChangeStart
I'm using $routeChangeError
Following document published by W3C also describes the differences between SOAP 1.1 and 1.2:
Update for Django 1.10+:
is_authenticated
is now an attribute in Django 1.10.
The method was removed in Django 2.0.
For Django 1.9 and older:
is_authenticated
is a function. You should call it like
if request.user.is_authenticated():
# do something if the user is authenticated
As Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may have seen something like this in template code:
{% if user.is_authenticated %}
However, in Python code, it is indeed a method in the User
class.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//private void Form1_Load(object sender, EventArgs e)
//{
// // Instantiate a new instance of Form1.
// Form1 f1 = new Form1();
// f1.Text = "zzzzzzz";
//}
}
class MainApplication
{
public static void Main()
{
// Instantiate a new instance of Form1.
Form1 f1 = new Form1();
// Display a messagebox. This shows the application
// is running, yet there is nothing shown to the user.
// This is the point at which you customize your form.
System.Windows.Forms.MessageBox.Show("The application "
+ "is running now, but no forms have been shown.");
// Customize the form.
f1.Text = "Running Form";
// Show the instance of the form modally.
f1.ShowDialog();
}
}
}
In Jsp:
action="profile/proffiesional"
In Controller
@RequestMapping(value = "proffessional", method = RequestMethod.POST)
Spelling MisMatch !
It is possible to do (in the deployed repository)
git fetch
git checkout origin/master -- path/to/file
The fetch will download all the recent changes, but it will not put it in your current checked out code (working area).
The checkout will update the working tree with the particular file from the downloaded changes (origin/master
).
At least this works for me for those little small typo fixes, where it feels weird to create a branch etc just to change one word in a file.
You forget the @ID above the userId
What about using eventlet? If you want to timeout the request after 10 seconds, even if data is being received, this snippet will work for you:
import requests
import eventlet
eventlet.monkey_patch()
with eventlet.Timeout(10):
requests.get("http://ipv4.download.thinkbroadband.com/1GB.zip", verify=False)
You can use contains
(this works with an arbitrary sequence):
df.filter($"foo".contains("bar"))
like
(SQL like with SQL simple regular expression whith _
matching an arbitrary character and %
matching an arbitrary sequence):
df.filter($"foo".like("bar"))
or rlike
(like with Java regular expressions):
df.filter($"foo".rlike("bar"))
depending on your requirements. LIKE
and RLIKE
should work with SQL expressions as well.
You have to add Button to excel sheet(say sheet1
) from which you can go to another sheet(say sheet2
).
Button can be added from Developer tab in excel. If developer tab is not there follow below steps to enable.
GOTO file -> options -> Customize Ribbon -> enable checkbox of developer on right panel -> Done.
To Add button :-
Developer Tab -> Insert -> choose first item button -> choose location of button-> Done.
To give name for button :-
Right click on button -> edit text.
To add code for going to sheet2 :-
Right click on button -> Assign Macro -> New -> (microsoft visual basic will open to code for button) -> paste below code
Worksheets("Sheet2").Visible = True
Worksheets("Sheet2").Activate
Save the file using 'Excel Macro Enable Template(*.xltm)' By which the code is appended with excel sheet.
Since the answers deviate I decided to test this and post the result - including the test example.
The server here just writes data to a client and does not expect any input.
The server:
ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
out.println("output");
if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
System.out.println(clientSocket.isConnected());
System.out.println(clientSocket.getInputStream().read());
// thread sleep ...
// break condition , close sockets and the like ...
}
Please try this:
DELETE FROM `table` WHERE id >=163 and id<= 265
The problem is with your line
x=np.array ([x0*n])
Here you define x as a single-item array of -200.0. You could do this:
x=np.array ([x0,]*n)
or this:
x=np.zeros((n,)) + x0
Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single
from pylab import *
line in the top you could use all the modules you need.
Microsoft recommends to use the "InstallShield Limited Edition for Visual Studio" as replacement for the discontinued "Deployment and Setup Project" - but it is not so nice and nobody else recommends to use it. But for simple setups, and if it is not a problem to relay on commercial third party products, you can use it.
The alternative is to use Windows Installer XML (WiX), but you have to do many things manually that did the Setup-Project by itself.
In Laravel 4 & 5 (up to 5.7), you can use str_limit, which limits the number of characters in a string.
While in Laravel 7 up, you can use the Str::limit helper.
//For Laravel to Laravel 7
{{ Illuminate\Support\Str::limit($post->title, 20, $end='...') }}
.NET 5 will be a unified version of all .NET variants coming in November 2020, so there will be no need to choose between variants anymore.
where are you trying to return the value? to console in dev tools is better for debugging
<script type = 'text/javascript'>
var ask = confirm('".$message."');
function answer(){
if(ask==false){
return false;
} else {
return true;
}
}
console.log("ask : ", ask);
console.log("answer : ", answer());
</script>
ShieldUI's export to excel functionality should already support all special chars.
It's an implicit conversion to bool
. I.e. wherever implicit conversions are allowed, your class can be converted to bool
by calling that method.
I know its Too late But I hope it will work new comers Try This Its Working ... :D
select
case
when isnumeric(my_NvarcharColumn) = 1 then
cast(my_NvarcharColumn AS int)
else
NULL
end
AS 'my_NvarcharColumnmitter'
from A
Try installing via :app:installDebug
. If it works then it is related to Android Studio's caches. I removed .gradle/
folder inside my project and it works.
/usr/bin/hive --version worked for me.
[qa@ip-10-241-1-222 ~]$ /usr/bin/hive --version
Hive 0.13.1-cdh5.3.1
Subversion file:///data/1/jenkins/workspace/generic-package-rhel64-6-0/topdir/BUILD/hive-0.13.1-cdh5.3.1 -r Unknown
Compiled by jenkins on Tue Jan 27 16:38:55 PST 2015
From source with checksum 1bb86e4899928ce29cbcaec8cf43c9b6
[qa@ip-10-241-1-222 ~]$
For Python 3, you have to decode the data you get back from the web server. For instance I decode the data as utf8 then deal with it:
# example of json data object group with two values of key id
jsonstufftest = '{'group':{'id':'2','id':'3'}}
# always set your headers
headers = {'User-Agent': 'Moz & Woz'}
# the url you are trying to load and get json from
url = 'http://www.cooljson.com/cooljson.json'
# in python 3 you can build the request using request.Request
req = urllib.request.Request(url,None,headers)
# try to connect or fail gracefully
try:
response = urllib.request.urlopen(req) # new python 3 code -jc
except:
exit('could not load page, check connection')
# read the response and DECODE
html=response.read().decode('utf8') # new python3 code
# now convert the decoded string into real JSON
loadedjson = json.loads(html)
# print to make sure it worked
print (loadedjson) # works like a charm
# iterate through each key value
for testdata in loadedjson['group']:
print (accesscount['id']) # should print 2 then 3 if using test json
If you don't decode you will get bytes vs string errors in Python 3.
Not able to understand your actual problem but your case statement is incorrect
CASE
WHEN
TABLE3.COL3 IS NULL
THEN TABLE2.COL3
ELSE
TABLE3.COL3
END
AS
COL4
variable.isnumeric
checks if a value is an integer:
if myVariable.isnumeric:
print('this varibale is numeric')
else:
print('not numeric')
My computer had the wrong locale set.
I first did
>>> import locale
>>> locale.getpreferredencoding(False)
'ANSI_X3.4-1968'
locale.getpreferredencoding(False)
is the function called by open()
when you don't provide an encoding. The output should be 'UTF-8'
, but in this case it's some variant of ASCII.
Then I ran the bash command locale
and got this output
$ locale
LANG=
LANGUAGE=
LC_CTYPE="POSIX"
LC_NUMERIC="POSIX"
LC_TIME="POSIX"
LC_COLLATE="POSIX"
LC_MONETARY="POSIX"
LC_MESSAGES="POSIX"
LC_PAPER="POSIX"
LC_NAME="POSIX"
LC_ADDRESS="POSIX"
LC_TELEPHONE="POSIX"
LC_MEASUREMENT="POSIX"
LC_IDENTIFICATION="POSIX"
LC_ALL=
So, I was using the default Ubuntu locale, which causes Python to open files as ASCII instead of UTF-8. I had to set my locale to en_US.UTF-8
sudo apt install locales
sudo locale-gen en_US en_US.UTF-8
sudo dpkg-reconfigure locales
If you can't change the locale system wide, you can invoke all your Python code like this:
PYTHONIOENCODING="UTF-8" python3 ./path/to/your/script.py
or do
export PYTHONIOENCODING="UTF-8"
to set it in the shell you run that in.
Process Spawning Manager
Sure, technically these are processes, and this program should really be called a process spawning manager, but this is only due to the way that BASH works when it forks using the ampersand, it uses the fork() or perhaps clone() system call which clones into a separate memory space, rather than something like pthread_create() which would share memory. If BASH supported the latter, each "sequence of execution" would operate just the same and could be termed to be traditional threads whilst gaining a more efficient memory footprint. Functionally however it works the same, though a bit more difficult since GLOBAL variables are not available in each worker clone hence the use of the inter-process communication file and the rudimentary flock semaphore to manage critical sections. Forking from BASH of course is the basic answer here but I feel as if people know that but are really looking to manage what is spawned rather than just fork it and forget it. This demonstrates a way to manage up to 200 instances of forked processes all accessing a single resource. Clearly this is overkill but I enjoyed writing it so I kept on. Increase the size of your terminal accordingly. I hope you find this useful.
ME=$(basename $0)
IPC="/tmp/$ME.ipc" #interprocess communication file (global thread accounting stats)
DBG=/tmp/$ME.log
echo 0 > $IPC #initalize counter
F1=thread
SPAWNED=0
COMPLETE=0
SPAWN=1000 #number of jobs to process
SPEEDFACTOR=1 #dynamically compensates for execution time
THREADLIMIT=50 #maximum concurrent threads
TPS=1 #threads per second delay
THREADCOUNT=0 #number of running threads
SCALE="scale=5" #controls bc's precision
START=$(date +%s) #whence we began
MAXTHREADDUR=6 #maximum thread life span - demo mode
LOWER=$[$THREADLIMIT*100*90/10000] #90% worker utilization threshold
UPPER=$[$THREADLIMIT*100*95/10000] #95% worker utilization threshold
DELTA=10 #initial percent speed change
threadspeed() #dynamically adjust spawn rate based on worker utilization
{
#vaguely assumes thread execution average will be consistent
THREADCOUNT=$(threadcount)
if [ $THREADCOUNT -ge $LOWER ] && [ $THREADCOUNT -le $UPPER ] ;then
echo SPEED HOLD >> $DBG
return
elif [ $THREADCOUNT -lt $LOWER ] ;then
#if maxthread is free speed up
SPEEDFACTOR=$(echo "$SCALE;$SPEEDFACTOR*(1-($DELTA/100))"|bc)
echo SPEED UP $DELTA%>> $DBG
elif [ $THREADCOUNT -gt $UPPER ];then
#if maxthread is active then slow down
SPEEDFACTOR=$(echo "$SCALE;$SPEEDFACTOR*(1+($DELTA/100))"|bc)
DELTA=1 #begin fine grain control
echo SLOW DOWN $DELTA%>> $DBG
fi
echo SPEEDFACTOR $SPEEDFACTOR >> $DBG
#average thread duration (total elapsed time / number of threads completed)
#if threads completed is zero (less than 100), default to maxdelay/2 maxthreads
COMPLETE=$(cat $IPC)
if [ -z $COMPLETE ];then
echo BAD IPC READ ============================================== >> $DBG
return
fi
#echo Threads COMPLETE $COMPLETE >> $DBG
if [ $COMPLETE -lt 100 ];then
AVGTHREAD=$(echo "$SCALE;$MAXTHREADDUR/2"|bc)
else
ELAPSED=$[$(date +%s)-$START]
#echo Elapsed Time $ELAPSED >> $DBG
AVGTHREAD=$(echo "$SCALE;$ELAPSED/$COMPLETE*$THREADLIMIT"|bc)
fi
echo AVGTHREAD Duration is $AVGTHREAD >> $DBG
#calculate timing to achieve spawning each workers fast enough
# to utilize threadlimit - average time it takes to complete one thread / max number of threads
TPS=$(echo "$SCALE;($AVGTHREAD/$THREADLIMIT)*$SPEEDFACTOR"|bc)
#TPS=$(echo "$SCALE;$AVGTHREAD/$THREADLIMIT"|bc) # maintains pretty good
#echo TPS $TPS >> $DBG
}
function plot()
{
echo -en \\033[${2}\;${1}H
if [ -n "$3" ];then
if [[ $4 = "good" ]];then
echo -en "\\033[1;32m"
elif [[ $4 = "warn" ]];then
echo -en "\\033[1;33m"
elif [[ $4 = "fail" ]];then
echo -en "\\033[1;31m"
elif [[ $4 = "crit" ]];then
echo -en "\\033[1;31;4m"
fi
fi
echo -n "$3"
echo -en "\\033[0;39m"
}
trackthread() #displays thread status
{
WORKERID=$1
THREADID=$2
ACTION=$3 #setactive | setfree | update
AGE=$4
TS=$(date +%s)
COL=$[(($WORKERID-1)/50)*40]
ROW=$[(($WORKERID-1)%50)+1]
case $ACTION in
"setactive" )
touch /tmp/$ME.$F1$WORKERID #redundant - see main loop
#echo created file $ME.$F1$WORKERID >> $DBG
plot $COL $ROW "Worker$WORKERID: ACTIVE-TID:$THREADID INIT " good
;;
"update" )
plot $COL $ROW "Worker$WORKERID: ACTIVE-TID:$THREADID AGE:$AGE" warn
;;
"setfree" )
plot $COL $ROW "Worker$WORKERID: FREE " fail
rm /tmp/$ME.$F1$WORKERID
;;
* )
;;
esac
}
getfreeworkerid()
{
for i in $(seq 1 $[$THREADLIMIT+1])
do
if [ ! -e /tmp/$ME.$F1$i ];then
#echo "getfreeworkerid returned $i" >> $DBG
break
fi
done
if [ $i -eq $[$THREADLIMIT+1] ];then
#echo "no free threads" >> $DBG
echo 0
#exit
else
echo $i
fi
}
updateIPC()
{
COMPLETE=$(cat $IPC) #read IPC
COMPLETE=$[$COMPLETE+1] #increment IPC
echo $COMPLETE > $IPC #write back to IPC
}
worker()
{
WORKERID=$1
THREADID=$2
#echo "new worker WORKERID:$WORKERID THREADID:$THREADID" >> $DBG
#accessing common terminal requires critical blocking section
(flock -x -w 10 201
trackthread $WORKERID $THREADID setactive
)201>/tmp/$ME.lock
let "RND = $RANDOM % $MAXTHREADDUR +1"
for s in $(seq 1 $RND) #simulate random lifespan
do
sleep 1;
(flock -x -w 10 201
trackthread $WORKERID $THREADID update $s
)201>/tmp/$ME.lock
done
(flock -x -w 10 201
trackthread $WORKERID $THREADID setfree
)201>/tmp/$ME.lock
(flock -x -w 10 201
updateIPC
)201>/tmp/$ME.lock
}
threadcount()
{
TC=$(ls /tmp/$ME.$F1* 2> /dev/null | wc -l)
#echo threadcount is $TC >> $DBG
THREADCOUNT=$TC
echo $TC
}
status()
{
#summary status line
COMPLETE=$(cat $IPC)
plot 1 $[$THREADLIMIT+2] "WORKERS $(threadcount)/$THREADLIMIT SPAWNED $SPAWNED/$SPAWN COMPLETE $COMPLETE/$SPAWN SF=$SPEEDFACTOR TIMING=$TPS"
echo -en '\033[K' #clear to end of line
}
function main()
{
while [ $SPAWNED -lt $SPAWN ]
do
while [ $(threadcount) -lt $THREADLIMIT ] && [ $SPAWNED -lt $SPAWN ]
do
WID=$(getfreeworkerid)
worker $WID $SPAWNED &
touch /tmp/$ME.$F1$WID #if this loops faster than file creation in the worker thread it steps on itself, thread tracking is best in main loop
SPAWNED=$[$SPAWNED+1]
(flock -x -w 10 201
status
)201>/tmp/$ME.lock
sleep $TPS
if ((! $[$SPAWNED%100]));then
#rethink thread timing every 100 threads
threadspeed
fi
done
sleep $TPS
done
while [ "$(threadcount)" -gt 0 ]
do
(flock -x -w 10 201
status
)201>/tmp/$ME.lock
sleep 1;
done
status
}
clear
threadspeed
main
wait
status
echo
Ideone supports Python 2.6 and Python 3
@The MYYN
wow, nice awk! But what about suid, sgid and sticky bit?
You have to extend your filter with s and t, otherwise they will not count and you get the wrong result. To calculate the octal number for this special flags, the procedure is the same but the index is at 4 7 and 10. the possible flags for files with execute bit set are ---s--s--t
amd for files with no execute bit set are ---S--S--T
ls -l | awk '{
k = 0
s = 0
for( i = 0; i <= 8; i++ )
{
k += ( ( substr( $1, i+2, 1 ) ~ /[rwxst]/ ) * 2 ^( 8 - i ) )
}
j = 4
for( i = 4; i <= 10; i += 3 )
{
s += ( ( substr( $1, i, 1 ) ~ /[stST]/ ) * j )
j/=2
}
if ( k )
{
printf( "%0o%0o ", s, k )
}
print
}'
For test:
touch blah
chmod 7444 blah
will result in:
7444 -r-Sr-Sr-T 1 cheko cheko 0 2009-12-05 01:03 blah
and
touch blah
chmod 7555 blah
will give:
7555 -r-sr-sr-t 1 cheko cheko 0 2009-12-05 01:03 blah
This error occur when you don't correctly write blocks. Forgetting a ":", or not using "Tab" button for blocks and use spaces. When you are transporting a code from one editor to another editor,it can happen. And never forget this: errors aren't always on that line. I came here for this, but I've forgotten an except after a try. because of my unstandard editor, it happend. But it's possible in normal editor.
After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.
Dim intChoice As Integer
Dim strPath As String
' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show
' Get back the user option
If intChoice <> 0 Then
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
Exit Sub
End If
Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String
Set fsoStream = FSO.OpenTextFile(strPath)
Do Until fsoStream.AtEndOfStream = True
strLine = fsoStream.ReadLine
' ... do your work ...
Loop
fsoStream.Close
Set FSO = Nothing
Hope it help!
Best regards
Fabio
Since XCode 4.3 the location has changed, the simulator can now be found at:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/
If you are hosting your Laravel app on Heroku, you can create custom_php.ini
in the root of your project and simply add max_execution_time = 60
You could try:
UIView *firstViewUIView = [[[NSBundle mainBundle] loadNibNamed:@"firstView" owner:self options:nil] firstObject];
[self.view.containerView addSubview:firstViewUIView];
Just replace following line
exec -a "$0" "$HERE/chrome" "$@"
with
exec -a "$0" "$HERE/chrome" "$@" --user-data-dir
all things will be right.
This code will not work (throw an error when clicked):
$timeout(function() {
angular.element('#btn2').triggerHandler('click');
});
You need to use the querySelector as follows:
$timeout(function() {
angular.element(document.querySelector('#btn2')).triggerHandler('click');
});
It appears to be relate to the graphics driver. In the emulator configuration, changing Emulated Graphics to Software - GLES 2.0
caused the crashes to stop.
BufferedReader#read
reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.
String s= inp.readLine();
int[] m= new int[2];
String[] s1 = inp.readLine().split(" ");
m[0]=Integer.parseInt(s1[0]);
m[1]=Integer.parseInt(s1[1]);
// Checking whether I am taking the inputs correctly
System.out.println(s);
System.out.println(m[0]);
System.out.println(m[1]);
You can check also Scanner vs. BufferedReader.
I'm not sure what your problem is (since you haven't told us), but I'm guessing at
a = Console.Read();
This will only read one character from your Console.
You can change your program to this. To make it more robust, accept more than 1 char input, and validate that the input is actually a number:
double a, b;
Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
if (double.TryParse(Console.ReadLine(), out a)) {
b = a * Math.PI;
Console.WriteLine("Sonuç " + b);
} else {
//user gave an illegal input. Handle it here.
}
The issue was fixed by doing the following steps.
Eclipse finds the JAVA executables from 'C:\ProgramData\Oracle\Java\javapath'
The folder structure will contain shortcuts to the below executables,
i. java.exe
ii. javaw.exe
iii. javaws.exe
For me the executable paths were pointing to my Program Files(x86) (home for 32 bit applications) folder location
I corrected it to Program Files (which homes 64-bit applications) and the issue got resolved
Please find the screenshot for the same.
No, Static member function can't be virtual .since virtual concept is resolved at run time with the help of vptr, and vptr is non static member of a class.due to that static member function can't acess vptr so static member can't be virtual.
Clearly HttpContext.Current
is not null
only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".
It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.
Overall, don't use Application["Setting"]
to store global stuffs, as they are not global as you discovered.
If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext
or Application["Settings"]
, as that violates the principles of isolation and decoupling.
Update:
Due to the introduction of async/await
it is more often that such issues happen, so you might consider the following tip,
In general, you should only call HttpContext.Current
in only a few scenarios (within an HTTP module for example). In all other cases, you should use
Page.Context
https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.page.context?view=netframework-4.7.2 Controller.HttpContext
https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.httpcontext?view=aspnet-mvc-5.2instead of HttpContext.Current
.
I've tried a some of the solutions in this thread, and unfortunately, I found some of them to be cumbersome (i.e. requiring excessive effort when doing something non-trivial) and inelegant. Consequently, I thought I'd throw my preferred solution, web2py HTML helper objects, into the mix.
First, install the the standalone web2py module:
pip install web2py
Unfortunately, the above installs an extremely antiquated version of web2py, but it'll be good enough for this example. The updated source is here.
Import web2py HTML helper objects documented here.
from gluon.html import *
Now, you can use web2py helpers to generate XML/HTML.
words = ['this', 'is', 'my', 'item', 'list']
# helper function
create_item = lambda idx, word: LI(word, _id = 'item_%s' % idx, _class = 'item')
# create the HTML
items = [create_item(idx, word) for idx,word in enumerate(words)]
ul = UL(items, _id = 'my_item_list', _class = 'item_list')
my_div = DIV(ul, _class = 'container')
>>> my_div
<gluon.html.DIV object at 0x00000000039DEAC8>
>>> my_div.xml()
# I added the line breaks for clarity
<div class="container">
<ul class="item_list" id="my_item_list">
<li class="item" id="item_0">this</li>
<li class="item" id="item_1">is</li>
<li class="item" id="item_2">my</li>
<li class="item" id="item_3">item</li>
<li class="item" id="item_4">list</li>
</ul>
</div>
There isn't any direct equivalent to the goto
concept in Java. There are a few constructs that allow you to do some of the things you can do with a classic goto
.
break
and continue
statements allow you to jump out of a block in a loop or switch statement.break <label>
allow you to jump out of an arbitrary compound statement to any level within a given method (or initializer block).continue <label>
to continue with the next iteration of an outer loop from an inner loop.return
.None of these Java constructs allow you to branch backwards or to a point in the code at the same level of nesting as the current statement. They all jump out one or more nesting (scope) levels and they all (apart from continue
) jump downwards. This restriction helps to avoid the goto "spaghetti code" syndrome inherent in old BASIC, FORTRAN and COBOL code2.
1- The most expensive part of exceptions is the actual creation of the exception object and its stacktrace. If you really, really need to use exception handling for "normal" flow control, you can either preallocate / reuse the exception object, or create a custom exception class that overrides the fillInStackTrace()
method. The downside is that the exception's printStackTrace()
methods won't give you useful information ... should you ever need to call them.
2 - The spaghetti code syndrome spawned the structured programming approach, where you limited in your use of the available language constructs. This could be applied to BASIC, Fortran and COBOL, but it required care and discipline. Getting rid of goto
entirely was a pragmatically better solution. If you keep it in a language, there is always some clown who will abuse it.
you can download printThis lib from this source https://github.com/jasonday/printThis/blob/0a7f799693af8a8303bf0b8df0efc80c2694af81/printThis.js and include it into your html page
Call the following jquery to print all the content including the content that is not viewable. You may include your css files in an array if you have multiple css files.
$("#modalDiv").printThis({
debug: false,
importCSS: true,
importStyle: true,
printContainer: true,
loadCSS: "../css/style.css",
pageTitle: "My Modal",
removeInline: false,
printDelay: 333,
header: null,
formValues: true
});
As of RC6 you can do the following to change URL without change state and thereby keeping your route history
import {OnInit} from '@angular/core';
import {Location} from '@angular/common';
// If you dont import this angular will import the wrong "Location"
@Component({
selector: 'example-component',
templateUrl: 'xxx.html'
})
export class ExampleComponent implements OnInit {
constructor( private location: Location )
{}
ngOnInit() {
this.location.replaceState("/some/newstate/");
}
}
Doing this solution by calling function and modularized
def userInput():
number = int(input('Please enter the number between 1 - 40 to find out the
fibonacci :'))
return number
def findFibonacci(number):
if number == 0:
return 0
elif number == 1:
return 1
else:
return findFibonacci(number - 1) + findFibonacci (number - 2)
def main():
userNumber = userInput()
print(findFibonacci(userNumber))
main()
Doing row=1
won't change anything, because you'll just overwrite that with the results of the loop.
You want to do next(reader)
to skip one row.
This could also be an issue of building the code using a 64 bit
configuration. You can try to select x86
as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager
From there you can change the Platform
of the project using the 32-bit .dll to x86
Here's how I did it:
var leftKey = 37, upKey = 38, rightKey = 39, downKey = 40;
var keystate;
document.addEventListener("keydown", function (e) {
keystate[e.keyCode] = true;
});
document.addEventListener("keyup", function (e) {
delete keystate[e.keyCode];
});
if (keystate[leftKey]) {
//code to be executed when left arrow key is pushed.
}
if (keystate[upKey]) {
//code to be executed when up arrow key is pushed.
}
if (keystate[rightKey]) {
//code to be executed when right arrow key is pushed.
}
if (keystate[downKey]) {
//code to be executed when down arrow key is pushed.
}
Years late but here's the simplest for others in case.
String connectionString = @"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";
SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);
DataTable data = new DataTable();
sda.Fill(data);
DataGridView1.DataSource = data;
Using DataSet
is not necessary and DataTable
should be good enough. SQLCommandBuilder
is unnecessary either.
None of the current answers worked for me. I'm using Bootstrap 3.
I liked what Rob Vermeer was doing and started from his response.
For a fade in and then fade out effect, I just used wrote the following function and used jQuery:
Html on my page to add the alert(s) to:
<div class="alert-messages text-center">
</div>
Javascript function to show and dismiss the alert.
function showAndDismissAlert(type, message) {
var htmlAlert = '<div class="alert alert-' + type + '">' + message + '</div>';
// Prepend so that alert is on top, could also append if we want new alerts to show below instead of on top.
$(".alert-messages").prepend(htmlAlert);
// Since we are prepending, take the first alert and tell it to fade in and then fade out.
// Note: if we were appending, then should use last() instead of first()
$(".alert-messages .alert").first().hide().fadeIn(200).delay(2000).fadeOut(1000, function () { $(this).remove(); });
}
Then, to show and dismiss the alert, just call the function like this:
showAndDismissAlert('success', 'Saved Successfully!');
showAndDismissAlert('danger', 'Error Encountered');
showAndDismissAlert('info', 'Message Received');
As a side note, I styled the div.alert-messages fixed on top:
<style>
div.alert-messages {
position: fixed;
top: 50px;
left: 25%;
right: 25%;
z-index: 7000;
}
</style>
Why not use: CopyOnWriteArraySet from java.util.concurrent?
new Date().getTime() is bugged.
Date date = new Date();
System.out.println(date);
System.out.println(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
long t1 = date.getTime();
System.out.println((t1 / 1000 / 60 / 60) % 24 + ":" + (t1 / 1000 / 60) % 60 + ":" + (t1 / 1000) % 60);
long t2 = System.currentTimeMillis();
System.out.println((t2 / 1000 / 60 / 60) % 24 + ":" + (t2 / 1000 / 60) % 60 + ":" + (t2 / 1000) % 60);
It returns me the wrong time millis. System.currentTimeMillis()
too. Since I ask the Date instance to tell me the corresponding time millis it must return the matching ones not others from a different time zone. Funny how deprecated methods are the only ones which return correct values.
This may help you!
$latlng='{"lat":29.5345741,"lng":75.0342196}';
$latlng=json_decode($latlng,TRUE); // array
echo "Lat=".$latlng['lat'];
echo '<br/>';
echo "Lng=".$latlng['lng'];
echo '<br/>';
$latlng2='{"lat":29.5345741,"lng":75.0342196}';
$latlng2=json_decode($latlng2); // object
echo "Lat=".$latlng2->lat;
echo '<br/>';
echo "Lng=".$latlng2->lng;
echo '<br/>';
this query runs perfectly in my case
select xmltype(t.axi_content).extract('//Lexis-NexisFlag/text()').getStringVal() from ax_bib_entity t
One way I managed to fix this (in a Kotlin app with architecture components) was by setting if (recyclerView.adapter == null) recyclerView.adapter = MyAdapter(datasource)
after I fetched the data from the Repository. Apparently it might have something to do with async issues with the suspend functions in the repository because when I fetch data for the first time when starting the activity, it calls the REST API since there is no data in the db, and everything goes smoothly, but after that, that same query cannot be made again, causing a crash.
Just use this:
<a title='Tool
Tip
On
New
Line'>link with tip</a>
You can add new line on title by using this 

.
Please refer to my answer on this post.
There is no need to iterate over the List
just overwrite the equals
method.
Use equals
instead of ==
@Override
public boolean equals (Object object) {
boolean result = false;
if (object == null || object.getClass() != getClass()) {
result = false;
} else {
EmployeeModel employee = (EmployeeModel) object;
if (this.name.equals(employee.getName()) && this.designation.equals(employee.getDesignation()) && this.age == employee.getAge()) {
result = true;
}
}
return result;
}
Call it like this:
public static void main(String args[]) {
EmployeeModel first = new EmployeeModel("Sameer", "Developer", 25);
EmployeeModel second = new EmployeeModel("Jon", "Manager", 30);
EmployeeModel third = new EmployeeModel("Priyanka", "Tester", 24);
List<EmployeeModel> employeeList = new ArrayList<EmployeeModel>();
employeeList.add(first);
employeeList.add(second);
employeeList.add(third);
EmployeeModel checkUserOne = new EmployeeModel("Sameer", "Developer", 25);
System.out.println("Check checkUserOne is in list or not");
System.out.println("Is checkUserOne Preasent = ? " + employeeList.contains(checkUserOne));
EmployeeModel checkUserTwo = new EmployeeModel("Tim", "Tester", 24);
System.out.println("Check checkUserTwo is in list or not");
System.out.println("Is checkUserTwo Preasent = ? " + employeeList.contains(checkUserTwo));
}
to center a a position:absolute attribute you need to set left:50% and margin-left: -50% of the width of the div.
<!-- for horizontal -->
<style>
div.center{
width:200px;
left:50%;
margin-left:-100px;
position:absolute;
}
</style>
<body>
<div class='center'>
should be centered horizontaly
</div>
</body>
for vertical center absolute you need to do the same thing bud not with left just with top. ( NOTE: html and body must have min-height 100%; )
<!-- for vertical -->
<style>
body,html{
min-height:100%;
}
div.center{
height:200px;
top:50%;
margin-top:-100px;
position:absolute;
}
</style>
<body>
<div class='center'>
should be centered verticaly
</div>
</body>
and can be combined for both
<!-- for both -->
<style>
body,html{
min-height:100%;
}
div.center{
width:200px;
height:50px
left:50%;
top:50%;
margin-left:-100px;
margin-top:-25px;
position:absolute;
}
</style>
<body>
<div class='center'>
should be centered
</div>
</body>
JFrame.dispose()
public void dispose()
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable. The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).
Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.
System.exit()
public static void exit(int status)
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.
The call System.exit(n)
is effectively equivalent to the call:
Runtime.getRuntime().exit(n)
There's a super() in Python too. It's a bit wonky, because of Python's old- and new-style classes, but is quite commonly used e.g. in constructors:
class Foo(Bar):
def __init__(self):
super(Foo, self).__init__()
self.baz = 5
You'll probably want to try textContent
instead of innerHTML
.
Given innerHTML
will return DOM content as a String
and not exclusively the "text" in the div
. It's fine if you know that your div
contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent
instead of innerHTML
For example, considering the following markup:
<div id="test">
Some <span class="foo">sample</span> text.
</div>
You'll get the following result:
var node = document.getElementById('test'),
htmlContent = node.innerHTML,
// htmlContent = "Some <span class="foo">sample</span> text."
textContent = node.textContent;
// textContent = "Some sample text."
See MDN for more details:
char[] characters;
...
string s = new string(characters);
Just want to add my two cents on this old post:
In my opinion, almost all of relational database engines include a commit transaction execution automatically after execute a DDL command even when you have autocommit=false, So you don't need to start a transaction to avoid a potential truncated object creation because It is completely unnecessary.
DECLARE @start [datetime] = 2010/4/1;
Should be...
DECLARE @start [datetime] = '2010-04-01';
The one you have is dividing 2010 by 4, then by 1, then converting to a date. Which is the 57.5th day from 1900-01-01.
Try SELECT @start
after your initialisation to check if this is correct.
As the error clearly states, OffenceBox.Text()
is not a function and therefore doesn't make sense.
Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:
"temp" environment variable setting - then it would be:
%temp%\Temporary ASP.NET Files
Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:
c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files
There are also cases where the temp folder can be set via config for a machine or site specific using this:
<compilation tempDirectory="d:\MyTempPlace" />
I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.
Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.
Aaron's approach above worked perfectly for me. My update statement was slightly different because I needed to join based on two fields concatenated in one table to match a field in another table.
--update clients table cell field from custom table containing mobile numbers
update clients
set cell = m.Phone
from clients as c
inner join [dbo].[COSStaffMobileNumbers] as m
on c.Last_Name + c.First_Name = m.Name
A StringBuffer
or its younger and faster brother StringBuilder
is preferred whenever you're going do to a lot of string concatenations in flavor of
string += newString;
or equivalently
string = string + newString;
because the above constructs implicitly creates new string everytime which will be a huge performance and drop. A StringBuffer
/ StringBuilder
is under the hoods best to be compared with a dynamically expansible List<Character>
.
start "" ExeToExecute
method does not work for me in the case of Xilinx xsdk, because as pointed out by @jeb in the comments below it is actaully a bat file.
so what does not work de-facto is
start "" BatToExecute
I am trying to open xsdk like that and it opens a separate cmd that needs to be closed and xsdk can run on its own
Before launching xsdk I run (source) the Env / Paths (with settings64.bat) so that xsdk.bat command gets recognized (simply as xsdk, withoitu the .bat)
what works with .bat
call BatToExecute
Yes there is possible to close TCP or UDP port there is a command in DOS
TASKKILL /f /pid 1234
I hope this will work for You
In vim column visual mode is Ctrl + v. If that is what you meant?
When you're working with strings in PHP you'll need to pay special attention to the formation, using "
or '
$string = 'Hello, world!';
$string = "Hello, world!";
Both of these are valid, the following is not:
$string = "Hello, world';
You must also note that '
inside of a literal started with "
will not end the string, and vice versa. So when you have a string which contains '
, it is generally best practice to use double quotation marks.
$string = "It's ok here";
Escaping the string is also an option
$string = 'It\'s ok here too';
More information on this can be found within the documentation
You can toggle the class of the i
element within the clicked anchor like
<i class="fa fa-plus-circle"></i>
then
$('#category-tabs li a').click(function(){
$(this).next('ul').slideToggle('500');
$(this).find('i').toggleClass('fa-plus-circle fa-minus-circle')
});
Demo: Fiddle
You could try this simple approach
var array1 = [4,8,9,10];_x000D_
var array2 = [4,8,9,10];_x000D_
_x000D_
console.log(array1.join('|'));_x000D_
console.log(array2.join('|'));_x000D_
_x000D_
if (array1.join('|') === array2.join('|')) {_x000D_
console.log('The arrays are equal.');_x000D_
} else {_x000D_
console.log('The arrays are NOT equal.');_x000D_
}_x000D_
_x000D_
array1 = [[1,2],[3,4],[5,6],[7,8]];_x000D_
array2 = [[1,2],[3,4],[5,6],[7,8]];_x000D_
_x000D_
console.log(array1.join('|'));_x000D_
console.log(array2.join('|'));_x000D_
_x000D_
if (array1.join('|') === array2.join('|')) {_x000D_
console.log('The arrays are equal.');_x000D_
} else {_x000D_
console.log('The arrays are NOT equal.');_x000D_
}
_x000D_
If the position of the values are not important you could sort the arrays first.
if (array1.sort().join('|') === array2.sort().join('|')) {
console.log('The arrays are equal.');
} else {
console.log('The arrays are NOT equal.');
}
Copied over from comment by @sloth
Instead of YourCollection.FirstOrDefault()
, you could use YourCollection.DefaultIfEmpty(YourDefault).First()
for example.
Example:
var viewModel = new CustomerDetailsViewModel
{
MainResidenceAddressSection = (MainResidenceAddressSection)addresses.DefaultIfEmpty(new MainResidenceAddressSection()).FirstOrDefault( o => o is MainResidenceAddressSection),
RiskAddressSection = addresses.DefaultIfEmpty(new RiskAddressSection()).FirstOrDefault(o => !(o is MainResidenceAddressSection)),
};
with open(fname, 'rb') as fh:
first = next(fh).decode()
fh.seek(-1024, 2)
last = fh.readlines()[-1].decode()
The variable value here is 1024: it represents the average string length. I choose 1024 only for example. If you have an estimate of average line length you could just use that value times 2.
Since you have no idea whatsoever about the possible upper bound for the line length, the obvious solution would be to loop over the file:
for line in fh:
pass
last = line
You don't need to bother with the binary flag you could just use open(fname)
.
ETA: Since you have many files to work on, you could create a sample of couple of dozens of files using random.sample
and run this code on them to determine length of last line. With an a priori large value of the position shift (let say 1 MB). This will help you to estimate the value for the full run.
There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:
It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.
I create a block to reset all my sequences:
DECLARE
I_val number;
BEGIN
FOR US IN
(SELECT US.SEQUENCE_NAME FROM USER_SEQUENCES US)
LOOP
execute immediate 'select ' || US.SEQUENCE_NAME || '.nextval from dual' INTO l_val;
execute immediate 'alter sequence ' || US.SEQUENCE_NAME || ' increment by -' || l_val || ' minvalue 0';
execute immediate 'select ' || US.SEQUENCE_NAME || '.nextval from dual' INTO l_val;
execute immediate 'alter sequence ' || US.SEQUENCE_NAME || ' increment by 1 minvalue 0';
END LOOP;
END;
I was looking to use the print statement to debug some dynamic sql as I imagin most of you are using print for simliar reasons.
I tried a few of the solutions listed and found that Kelsey's solution works with minor tweeks (@sql is my @script) n.b. LENGTH isn't a valid function:
--http://stackoverflow.com/questions/7850477/how-to-print-varcharmax-using-print-statement
--Kelsey
DECLARE @Counter INT
SET @Counter = 0
DECLARE @TotalPrints INT
SET @TotalPrints = (LEN(@sql) / 4000) + 1
WHILE @Counter < @TotalPrints
BEGIN
PRINT SUBSTRING(@sql, @Counter * 4000, 4000)
SET @Counter = @Counter + 1
END
PRINT LEN(@sql)
This code does as commented add a new line into the output, but for debugging this isn't a problem for me.
Ben B's solution is perfect and is the most elegent, although for debugging is a lot of lines of code so I choose to use my slight modification of Kelsey's. It might be worth creating a system like stored procedure in msdb for Ben B's code which could be reused and called in one line?
Alfoks' code doesn't work unfortunately because that would have been easier.
This: "\0"
is a string, not a character. A character uses single quotes, like '\0'
.
Another workaround:
Sometimes this happens to me because of network problems. I don't understand the root problem fully, but switching to a different sub-network or using VPN solves it
i got solution what you are getting as per imp help=y
it is mentioned that imp is only valid for TRANSPORT_TABLESPACE
as below:
Keyword Description (Default) Keyword Description (Default)
--------------------------------------------------------------------------
USERID username/password FULL import entire file (N)
BUFFER size of data buffer FROMUSER list of owner usernames
FILE input files (EXPDAT.DMP) TOUSER list of usernames
SHOW just list file contents (N) TABLES list of table names
IGNORE ignore create errors (N) RECORDLENGTH length of IO record
GRANTS import grants (Y) INCTYPE incremental import type
INDEXES import indexes (Y) COMMIT commit array insert (N)
ROWS import data rows (Y) PARFILE parameter filename
LOG log file of screen output CONSTRAINTS import constraints (Y)
DESTROY overwrite tablespace data file (N)
INDEXFILE write table/index info to specified file
SKIP_UNUSABLE_INDEXES skip maintenance of unusable indexes (N)
FEEDBACK display progress every x rows(0)
TOID_NOVALIDATE skip validation of specified type ids
FILESIZE maximum size of each dump file
STATISTICS import precomputed statistics (always)
RESUMABLE suspend when a space related error is encountered(N)
RESUMABLE_NAME text string used to identify resumable statement
RESUMABLE_TIMEOUT wait time for RESUMABLE
COMPILE compile procedures, packages, and functions (Y)
STREAMS_CONFIGURATION import streams general metadata (Y)
STREAMS_INSTANTIATION import streams instantiation metadata (N)
DATA_ONLY import only data (N)
The following keywords only apply to transportable tablespaces
TRANSPORT_TABLESPACE import transportable tablespace metadata (N)
TABLESPACES tablespaces to be transported into database
DATAFILES datafiles to be transported into database
TTS_OWNERS users that own data in the transportable tablespace set
So, Please create table space for your user:
CREATE TABLESPACE <tablespace name> DATAFILE <path to save, example: 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\ABC.dbf'> SIZE 100M AUTOEXTEND ON NEXT 100M MAXSIZE 10G EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;
You can do this with dynamic objects:
var dynamicKeyValueArray = new[] { new {Key = "K1", Value = 10}, new {Key = "K2", Value = 5} };
foreach(var keyvalue in dynamicKeyValueArray)
{
Console.Log(keyvalue.Key);
Console.Log(keyvalue.Value);
}
I'm posting this because (to my surprise) there was no other place I could find that recommended this.
There's a really easy way to do this, without restricting you to browser-defined input dimensions. Just use the <label>
tag around a hidden file upload button. This allows for even more freedom in styling than the styling allowed via webkit's built-in styling[1].
The label tag was made for the exact purpose of directing any click events on it to the child inputs[2], so using that, you won't require any JavaScript to direct the click event to the input button for you anymore. You'd to use something like the following:
label.myLabel input[type="file"] {_x000D_
position:absolute;_x000D_
top: -1000px;_x000D_
}_x000D_
_x000D_
/***** Example custom styling *****/_x000D_
.myLabel {_x000D_
border: 2px solid #AAA;_x000D_
border-radius: 4px;_x000D_
padding: 2px 5px;_x000D_
margin: 2px;_x000D_
background: #DDD;_x000D_
display: inline-block;_x000D_
}_x000D_
.myLabel:hover {_x000D_
background: #CCC;_x000D_
}_x000D_
.myLabel:active {_x000D_
background: #CCF;_x000D_
}_x000D_
.myLabel :invalid + span {_x000D_
color: #A44;_x000D_
}_x000D_
.myLabel :valid + span {_x000D_
color: #4A4;_x000D_
}
_x000D_
<label class="myLabel">_x000D_
<input type="file" required/>_x000D_
<span>My Label</span>_x000D_
</label>
_x000D_
I've used a fixed position to hide the input, to make it work even in ancient versions of Internet Explorer (emulated IE8- refused to work on a visibility:hidden
or display:none
file-input). I've tested in emulated IE7 and up, and it worked perfectly.
<button>
s inside <label>
tags unfortunately, so you'll have to define the styles for the buttons yourself. To me, this is the only downside to this approach.for
attribute is defined, its value is used to trigger the input with the same id
as the for
attribute on the <label>
.To stash your working directory including untracked files (especially those that are in the .gitignore) then you probably want to use this cmd:
git stash --include-untracked
(Alternatively, you can use the shorthand -u
instead of --include-untracked
)
Update 17 May 2018:
New versions of git now have git stash --all
which stashes all files, including untracked and ignored files.
git stash --include-untracked
no longer touches ignored files (tested on git 2.16.2).
Original answer below:
As of version 1.7.7 you can use git stash --include-untracked
or git stash save -u
to stash untracked files without staging them.
Add (git add
) the file and start tracking it. Then stash. Since the entire contents of the file are new, they will be stashed, and you can manipulate it as necessary.
I resolved this problem by renaming the DLL. The DLL had been manually renamed when it was uploaded to its shared location (a version number was appended to the file name). Removing the version number from the downloaded file resolved the issue.
On Submit form
public ActionResult ExportXls()
{
var filePath="";
CommonHelper.WriteXls(filePath, "Text.xls");
}
public static void WriteXls(string filePath, string targetFileName)
{
if (!String.IsNullOrEmpty(filePath))
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "utf-8";
response.ContentType = "text/xls";
response.AddHeader("content-disposition", string.Format("attachment; filename={0}", targetFileName));
response.BinaryWrite(File.ReadAllBytes(filePath));
response.End();
}
}
I found there was another solution for this problem rather than creating a symbolic link.
You set the path to your directory, where libmysqlclient.18.dylib resides, to DYLD_LIBRARY_PATH environment variable. What I did is to put following line in my .bash_profile:
export DYLD_LIBRARY_PATH=/usr/local/mysql-5.5.15-osx10.6-x86/lib/:$DYLD_LIBRARY_PATH
That's it.
You cannot use the syntax you have suggested. If you have a C99 compiler, though, you can do this:
int *p;
p = malloc(3 * sizeof p[0]);
memcpy(p, (int []){ 0, 1, 2 }, 3 * sizeof p[0]);
If your compiler does not support C99 compound literals, you need to use a named template to copy from:
int *p;
p = malloc(3 * sizeof p[0]);
{
static const int p_init[] = { 0, 1, 2 };
memcpy(p, p_init, 3 * sizeof p[0]);
}
Assuming that you are using mvn and cloudera distribution of hadoop. I'm using cdh4.6 and adding these dependencies worked for me.I think you should check the versions of hadoop and mvn dependencies.
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
<version>2.0.0-mr1-cdh4.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.0.0-cdh4.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.0.0-cdh4.6.0</version>
</dependency>
don't forget to add cloudera mvn repository.
<repository>
<id>cloudera</id>
<url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
</repository>
This will not expand the last column of the xaml grid to take the remaining space if
AutoGeneratedColumns="True"
.
setTimeout() function it's use to delay a process in JavaScript.
w3schools has an easy tutorial about this function.
::
is the scope resolution operator. It's used to specify the scope of something.
For example, ::
alone is the global scope, outside all other namespaces.
some::thing
can be interpreted in any of the following ways:
some
is a namespace (in the global scope, or an outer scope than the current one) and thing
is a type, a function, an object or a nested namespace;some
is a class available in the current scope and thing
is a member object, function or type of the some
class;some
can be a base type of the current type (or the current type itself) and thing
is then one member of this class, a type, function or object.You can also have nested scope, as in some::thing::bad
. Here each name could be a type, an object or a namespace. In addition, the last one, bad
, could also be a function. The others could not, since functions can't expose anything within their internal scope.
So, back to your example, ::thing
can be only something in the global scope: a type, a function, an object or a namespace.
The way you use it suggests (used in a pointer declaration) that it's a type in the global scope.
I hope this answer is complete and correct enough to help you understand scope resolution.
Thanks to an answer to Stack Overflow quesion Creating a file name as a timestamp in a batch job, I found that it was a space terminating the filename.
Just to clarify the answer given by JScoobyCed, the scp command cannot copy files to directories that require administrative permission. However, you can use the scp command to copy to directories that belong to the remote user.
So, to copy to a directory that requires root privileges, you must first copy that file to a directory belonging to the remote user using the scp command. Next, you must login to the remote account using ssh. Once logged in, you can then move the file to the directory of your choosing by using the sudo mv command. In short, the commands to use are as follows:
Using scp, copy file to a directory in the remote user's account, for example the Documents directory:
scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents
Next, login to the remote user's account using ssh and then move the file to a restricted directory using sudo:
ssh remoteUser@some_address
sudo mv /home/remoteUser/Documents/file /var/www
[
stands for single dimension array
Ljava.lang.String
stands for the string class (L followed by class/interface name)
Few Examples:
Class.forName("[D")
-> Array of primitive doubleClass.forName("[[Ljava.lang.String")
-> Two dimensional array of strings.List of notations:
Element Type : Notation
boolean : Z
byte : B
char : C
class or interface : Lclassname
double : D
float : F
int : I
long : J
short : S
The way you have synchronized is correct. But there is a catch
However in real world you would generally query the map before putting in the value. Hence you would need to do two operations and hence a synchronized block is needed. So the way you have used it is correct. However.
a. It has a API 'putIfAbsent' which would do the same stuff but in a more efficient manner.
b. Its Efficient: dThe CocurrentMap just locks keys hence its not blocking the whole map's world. Where as you have blocked keys as well as values.
c. You could have passed the reference of your map object somewhere else in your codebase where you/other dev in your tean may end up using it incorrectly. I.e he may just all add() or get() without locking on the map's object. Hence his call won't run mutually exclusive to your sync block. But using a concurrent implementation gives you a peace of mind that it can never be used/implemented incorrectly.
With Angular CLI 6 you need to use builders as ng eject is deprecated and will soon be removed in 8.0. That's what it says when I try to do an ng eject
You can use angular-builders package (https://github.com/meltedspark/angular-builders) to provide your custom webpack config.
I have tried to summarize all in a single blog post on my blog - How to customize build configuration with custom webpack config in Angular CLI 6
but essentially you add following dependencies -
"devDependencies": {
"@angular-builders/custom-webpack": "^7.0.0",
"@angular-builders/dev-server": "^7.0.0",
"@angular-devkit/build-angular": "~0.11.0",
In angular.json make following changes -
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {"path": "./custom-webpack.config.js"},
Notice change in builder and new option customWebpackConfig. Also change
"serve": {
"builder": "@angular-builders/dev-server:generic",
Notice the change in builder again for serve target. Post these changes you can create a file called custom-webpack.config.js in your same root directory and add your webpack config there.
However, unlike ng eject configuration provided here will be merged with default config so just add stuff you want to edit/add.
To retrieve the position relative to the page efficiently, and without using a recursive function: (includes IE also)
var element = document.getElementById('elementId'); //replace elementId with your element's Id.
var rect = element.getBoundingClientRect();
var elementLeft,elementTop; //x and y
var scrollTop = document.documentElement.scrollTop?
document.documentElement.scrollTop:document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft?
document.documentElement.scrollLeft:document.body.scrollLeft;
elementTop = rect.top+scrollTop;
elementLeft = rect.left+scrollLeft;
If you are getting the error
Attempt by security transparent method ‘WebMatrix.WebData.PreApplicationStartCode.Start()’ to access security critical method ‘System.Web.WebPages.Razor.WebPageRazorHost.AddGlobalImport(System.String)’ failed.
In order to fix this install this package using NuGet package manager.
Install-Package Microsoft.AspNet.WebHelpers
After that , probably you will get another error
Cannot load WebMatrix.Data version 3.0.0.0 assembly
to fix this install this package using NuGet package manager.
Install-Package Microsoft.AspNet.WebPages.Data
I like the approach from Fusion, but there's a small error in it. Like that it is correct:
function closest(array, number) {
var num = 0;
for (var i = array.length - 1; i >= 0; i--) {
if(Math.abs(number - array[i]) < Math.abs(number - array[num])){
num = i;
}
}
return array[num];
}
It it also a bit faster because it uses the improved for
loop.
At the end I wrote my function like this:
var getClosest = function(number, array) {
var current = array[0];
var difference = Math.abs(number - current);
var index = array.length;
while (index--) {
var newDifference = Math.abs(number - array[index]);
if (newDifference < difference) {
difference = newDifference;
current = array[index];
}
}
return current;
};
I tested it with console.time()
and it is slightly faster than the other function.
Things that might work against beginner scrapers:
Things that will help in general:
Things that will help but will make your users hate you:
Although an old question all the contributions helped me a lot so here's my solution, which works within my own DbContext
class. The $rows
parameter is simply an array of associative arrays representing rows or models: field name => insert value
.
If you use a pattern that uses models this fits in nicely when passed model data as an array, say from a ToRowArray
method within the model class.
Note: It should go without saying but never allow the arguments passed to this method to be exposed to the user or reliant on any user input, other than the insert values, which have been validated and sanitised. The
$tableName
argument and the column names should be defined by the calling logic; for instance aUser
model could be mapped to the user table, which has its column list mapped to the model's member fields.
public function InsertRange($tableName, $rows)
{
// Get column list
$columnList = array_keys($rows[0]);
$numColumns = count($columnList);
$columnListString = implode(",", $columnList);
// Generate pdo param placeholders
$placeHolders = array();
foreach($rows as $row)
{
$temp = array();
for($i = 0; $i < count($row); $i++)
$temp[] = "?";
$placeHolders[] = "(" . implode(",", $temp) . ")";
}
$placeHolders = implode(",", $placeHolders);
// Construct the query
$sql = "insert into $tableName ($columnListString) values $placeHolders";
$stmt = $this->pdo->prepare($sql);
$j = 1;
foreach($rows as $row)
{
for($i = 0; $i < $numColumns; $i++)
{
$stmt->bindParam($j, $row[$columnList[$i]]);
$j++;
}
}
$stmt->execute();
}
we can be submit multiple updates together in JDBC to submit batch updates.
we can use Statement, PreparedStatement, and CallableStatement objects for bacth update with disable autocommit
addBatch() and executeBatch() functions are available with all statement objects to have BatchUpdate
here addBatch() method adds a set of statements or parameters to the current batch.
I had the same problem. But just restarting my computer after setting up the Maven path resolved the issue.
Variable Name: M2_Home Variable Value:C:\Apache\apache-maven-3.3.9
Variable Name: Path Variable Value:C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%JAVA_HOME%\bin\;%M2_HOME%\bin\
require 'uri'
class Hash
def to_query_hash(key)
reduce({}) do |h, (k, v)|
new_key = key.nil? ? k : "#{key}[#{k}]"
v = Hash[v.each_with_index.to_a.map(&:reverse)] if v.is_a?(Array)
if v.is_a?(Hash)
h.merge!(v.to_query_hash(new_key))
else
h[new_key] = v
end
h
end
end
def to_query(key = nil)
URI.encode_www_form(to_query_hash(key))
end
end
2.4.2 :019 > {:a => "a", :b => "b"}.to_query_hash(nil)
=> {:a=>"a", :b=>"b"}
2.4.2 :020 > {:a => "a", :b => "b"}.to_query
=> "a=a&b=b"
2.4.2 :021 > {:a => "a", :b => ["c", "d", "e"]}.to_query_hash(nil)
=> {:a=>"a", "b[0]"=>"c", "b[1]"=>"d", "b[2]"=>"e"}
2.4.2 :022 > {:a => "a", :b => ["c", "d", "e"]}.to_query
=> "a=a&b%5B0%5D=c&b%5B1%5D=d&b%5B2%5D=e"
Create a public integer in the General Declaration.
Then in your function you can increase its value each time. See example (function to save attachements of an email as CSV).
Public Numerator As Integer
Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim FileName As String
saveFolder = "c:\temp\"
For Each objAtt In itm.Attachments
FileName = objAtt.DisplayName & "_" & Numerator & "_" & Format(Now, "yyyy-mm-dd H-mm-ss") & ".CSV"
objAtt.SaveAsFile saveFolder & "\" & FileName
Numerator = Numerator + 1
Set objAtt = Nothing
Next
End Sub
You can use dateutil.parser.parse
(install with python -m pip install python-dateutil
) to parse strings into datetime objects.
dateutil.parser.parse
will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime
which you supply a format string to (see Brent Washburne's answer).
from dateutil.parser import parse
a = "2012-10-09T19:00:55Z"
b = parse(a)
print(b.weekday())
# 1 (equal to a Tuesday)
Right now (August 2014) You could use RStudio for converting R Markdown to PDF. Basically, RStudio use pandoc to convert Rmd to PDF.
You could change metadata to:
For more details - http://rmarkdown.rstudio.com/pdf_document_format.html
I'm not sure that i know exactly what you mean.
But to get the length of an initialized array,
doesn't strlen(string) work ??
Depending on the hibernate flush mode that you are using (AUTO
is the default) save
may or may not write your changes to the DB straight away. When you call saveAndFlush
you are enforcing the synchronization of your model state with the DB.
If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save()
and saveAndFlush()
because the select triggers a flush first. See the documention.
You don't need any tool. Only a few clicks.
Windows 10 can handle ttc files with no problem.
You can double click the file and install it like any ttf. Then if you nead the individual ttf files you can go to C:\Windows\Fonts\Font Name and there you will findit. If you cant do this i suspect you have a corupt file.
You can make use of getSizeof() as mentioned below to determine the size of an object
import sys
str1 = "one"
int_element=5
print("Memory size of '"+str1+"' = "+str(sys.getsizeof(str1))+ " bytes")
print("Memory size of '"+ str(int_element)+"' = "+str(sys.getsizeof(int_element))+ " bytes")
I used Abdurrahim's suggestion. However, it seemed to give a weird time format and also added the abbreviation for the day as part of the build date; example: Sun 12/24/2017 13:21:05.43. I only needed just the date so I had to eliminate the rest using substring.
After adding the echo %date% %time% > "$(ProjectDir)\Resources\BuildDate.txt"
to the pre-build event, I just did the following:
string strBuildDate = YourNamespace.Properties.Resources.BuildDate;
string strTrimBuildDate = strBuildDate.Substring(4).Remove(10);
The good news here is that it worked.
GitHub recently introduced a new feature called Projects. This provides a visual board that is typical of many Project Management tools:
A Repository as documented on GitHub:
A repository is the most basic element of GitHub. They're easiest to imagine as a project's folder. A repository contains all of the project files (including documentation), and stores each file's revision history. Repositories can have multiple collaborators and can be either public or private.
A Project as documented on GitHub:
Project boards on GitHub help you organize and prioritize your work. You can create project boards for specific feature work, comprehensive roadmaps, or even release checklists. With project boards, you have the flexibility to create customized workflows that suit your needs.
Part of the confusion is that the new feature, Projects, conflicts with the overloaded usage of the term project in the documentation above.
I ended up writing a function that has worked for me well so far:
// pretty print data
function out($data, $label = NULL) {
$CLI = (php_sapi_name() === 'cli') ? 'cli' : '';
$gettype = gettype($data);
if (isset($label)) {
if ($CLI) { $label = $label . ': '; }
else { $label = '<b>'.$label.'</b>: '; }
}
if ($gettype == 'string' || $gettype == 'integer' || $gettype == 'double' || $gettype == 'boolean') {
if ($CLI) { echo $label . $data . "\n"; }
else { echo $label . $data . "<br/>"; }
}
else {
if ($CLI) { echo $label . print_r($data,1) . "\n"; }
else { echo $label . "<pre>".print_r($data,1)."</pre>"; }
}
}
// Usage
out('Hello world!');
$var = 'Hello Stackoverflow!';
out($var, 'Label');
I don't know about elegance, but this works:
import glob
import os
for f in glob.glob("file*.txt"):
os.system("cat "+f+" >> OutFile.txt")
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
Option 1
Open a different console and run
jupyter notebook stop [PORT]
The default [PORT] is 8888, so, assuming that Jupyter Notebooks is running on port 8888, just run
jupyter notebook stop
If it is on port 9000, then
jupyter notebook stop 9000
Option 2 (Source)
Check runtime folder location
jupyter --paths
Remove all files in the runtime folder
rm -r [RUNTIME FOLDER PATH]/*
Use top
to find any Jupyter Notebook running processes left and if so kill their PID.
top | grep jupyter &
kill [PID]
One can boilt it down to
TARGET_PORT=8888
kill -9 $(lsof -n -i4TCP:$TARGET_PORT | cut -f 2 -d " ")
Note: If one wants to launch one's Notebook on a specific IP/Port
jupyter notebook --ip=[ADD_IP] --port=[ADD_PORT] --allow-root &
There are essentially three different ways how to express something like if-then-else in Prolog. To compare them consider char_class/2
. For a
and b
the class should be ab
and other
for all other terms. One could write this clumsily like so:
char_class(a, ab).
char_class(b, ab).
char_class(X, other) :-
dif(X, a),
dif(X, b).
?- char_class(Ch, Class).
Ch = a, Class = ab
; Ch = b, Class = ab
; Class = other,
dif(Ch, a), dif(Ch, b).
To write things more compactly, an if-then-else construct is needed. Prolog has a built-in one:
?- ( ( Ch = a ; Ch = b ) -> Class = ab ; Class = other ).
Ch = a, Class = ab.
While this answer is sound, it is incomplete. Just the first answer from ( Ch = a ; Ch = b )
is given. The other answers are chopped away. Not very relational, indeed.
A better construct, often called a "soft cut" (don't believe the name, a cut is a cut is a cut), gives slightly better results (this is in YAP):
?- ( ( Ch = a ; Ch = b ) *-> Class = ab ; Class = other ).
Ch = a, Class = ab
; Ch = b, Class = ab.
Alternatively, SICStus has if/3
with very similar semantics:
?- if( ( Ch = a ; Ch = b ), Class = ab , Class = other ).
Ch = a, Class = ab
; Ch = b, Class = ab.
So the last answer is still suppressed. Now enter library(reif)
for SICStus, YAP, and SWI. Install it and say:
?- use_module(library(reif)).
?- if_( ( Ch = a ; Ch = b ), Class = ab , Class = other ).
Ch = a, Class = ab
; Ch = b, Class = ab
; Class = other,
dif(Ch, a), dif(Ch, b).
Note that all the if_/3
is compiled away to a wildly nested if-then-else for
char_class(Ch, Class) :-
if_( ( Ch = a ; Ch = b ), Class = ab , Class = other ).
which expands in YAP 6.3.4 to:
char_class(A,B) :-
( A\=a
->
( A\=b
->
B=other
;
( A==b
->
B=ab
)
;
A=b,
B=ab
;
dif(A,b),
B=other
)
;
( A==a
->
B=ab
)
;
A=a,
B=ab
;
dif(A,a),
( A\=b
->
B=other
;
( A==b
->
B=ab
)
;
A=b,
B=ab
;
dif(A,b),
B=other
)
).
We're using Kafka 2.11 and make use of this tool - kafka-consumer-groups
.
$ rpm -qf /bin/kafka-consumer-groups
confluent-kafka-2.11-1.1.1-1.noarch
For example:
$ kafka-consumer-groups --describe --group logstash | grep -E "TOPIC|filebeat"
Note: This will not show information about old Zookeeper-based consumers.
TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST CLIENT-ID
beats_filebeat 0 20003914484 20003914888 404 logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1 logstash-0
beats_filebeat 1 19992522286 19992522709 423 logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1 logstash-0
beats_filebeat 2 19990597254 19990597637 383 logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1 logstash-0
beats_filebeat 7 19991718707 19991719268 561 logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2 logstash-0
beats_filebeat 8 20015611981 20015612509 528 logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2 logstash-0
beats_filebeat 5 19990536340 19990541331 4991 logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3 logstash-0
beats_filebeat 6 19990728038 19990733086 5048 logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3 logstash-0
beats_filebeat 3 19994613945 19994616297 2352 logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4 logstash-0
beats_filebeat 4 19990681602 19990684038 2436 logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4 logstash-0
NOTE: We use an alias that overloads kafka-consumer-groups
like so in our /etc/profile.d/kafka.sh
:
alias kafka-consumer-groups="KAFKA_JVM_PERFORMANCE_OPTS=\"-Djava.security.auth.login.config=$HOME/.kafka_client_jaas.conf\" kafka-consumer-groups --bootstrap-server ${KAFKA_HOSTS} --command-config /etc/kafka/security-enabler.properties"
Maybe you can try this one:
if (isset($_POST['mail']) && ($_POST['mail'] !=0)) { echo "Yes, mail is set"; } else { echo "No, mail is not set"; }
Just adding to the answers already given, the solution using the string "nunique"
seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M
%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s
%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s
%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s
It normally represents a parameter to be supplied by client.
An oblique answer to the question is to write all the code as classes, apart from the index.php files, which are then the only points of entry. PHP files that contain classes will not cause anything to happen, even if they are invoked directly through Apache.
A direct answer is to include the following in .htaccess:
<FilesMatch "\.php$">
Order Allow,Deny
Deny from all
</FilesMatch>
<FilesMatch "index[0-9]?\.php$">
Order Allow,Deny
Allow from all
</FilesMatch>
This will allow any file like index.php, index2.php etc to be accessed, but will refuse access of any kind to other .php files. It will not affect other file types.
To run this in later versions of pip (tested on pip==10.0.1
) use the following:
from pip._internal.operations.freeze import freeze
for requirement in freeze(local_only=True):
print(requirement)
to get total seconds
var i = TimeSpan.FromTicks(startDate.Ticks).TotalSeconds;
and to get datetime from seconds
var thatDateTime = new DateTime().AddSeconds(i)
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
You need to keep an array of the google.maps.Marker
objects to hide (or remove or run other operations on them).
In the global scope:
var gmarkers = [];
Then push the markers on that array as you create them:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
title: locations[i].title,
icon: icon,
map:map
});
// Push your newly created marker into the array:
gmarkers.push(marker);
Then to remove them:
function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
working example (toggles the markers)
code snippet:
var gmarkers = [];_x000D_
var RoseHulman = new google.maps.LatLng(39.483558, -87.324593);_x000D_
var styles = [{_x000D_
stylers: [{_x000D_
hue: "black"_x000D_
}, {_x000D_
saturation: -90_x000D_
}]_x000D_
}, {_x000D_
featureType: "road",_x000D_
elementType: "geometry",_x000D_
stylers: [{_x000D_
lightness: 100_x000D_
}, {_x000D_
visibility: "simplified"_x000D_
}]_x000D_
}, {_x000D_
featureType: "road",_x000D_
elementType: "labels",_x000D_
stylers: [{_x000D_
visibility: "on"_x000D_
}]_x000D_
}];_x000D_
_x000D_
var styledMap = new google.maps.StyledMapType(styles, {_x000D_
name: "Campus"_x000D_
});_x000D_
var mapOptions = {_x000D_
center: RoseHulman,_x000D_
zoom: 15,_x000D_
mapTypeControl: true,_x000D_
zoomControl: true,_x000D_
zoomControlOptions: {_x000D_
style: google.maps.ZoomControlStyle.SMALL_x000D_
},_x000D_
mapTypeControlOptions: {_x000D_
mapTypeIds: ['map_style', google.maps.MapTypeId.HYBRID],_x000D_
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU_x000D_
},_x000D_
scrollwheel: false,_x000D_
streetViewControl: true,_x000D_
_x000D_
};_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map'), mapOptions);_x000D_
map.mapTypes.set('map_style', styledMap);_x000D_
map.setMapTypeId('map_style');_x000D_
_x000D_
var infowindow = new google.maps.InfoWindow({_x000D_
maxWidth: 300,_x000D_
infoBoxClearance: new google.maps.Size(1, 1),_x000D_
disableAutoPan: false_x000D_
});_x000D_
_x000D_
var marker, i, icon, image;_x000D_
_x000D_
var locations = [{_x000D_
"id": "1",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Alpha Tau Omega Fraternity",_x000D_
"description": "<p>Alpha Tau Omega house</p>",_x000D_
"longitude": "-87.321133",_x000D_
"latitude": "39.484092"_x000D_
}, {_x000D_
"id": "2",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Apartment Commons",_x000D_
"description": "<p>The commons area of the apartment-style residential complex</p>",_x000D_
"longitude": "-87.329282",_x000D_
"latitude": "39.483599"_x000D_
}, {_x000D_
"id": "3",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Apartment East",_x000D_
"description": "<p>Apartment East</p>",_x000D_
"longitude": "-87.328809",_x000D_
"latitude": "39.483748"_x000D_
}, {_x000D_
"id": "4",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Apartment West",_x000D_
"description": "<p>Apartment West</p>",_x000D_
"longitude": "-87.329732",_x000D_
"latitude": "39.483429"_x000D_
}, {_x000D_
"id": "5",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Baur-Sames-Bogart (BSB) Hall",_x000D_
"description": "<p>Baur-Sames-Bogart Hall</p>",_x000D_
"longitude": "-87.325714",_x000D_
"latitude": "39.482382"_x000D_
}, {_x000D_
"id": "6",_x000D_
"category": "6",_x000D_
"campus_location": "D3",_x000D_
"title": "Blumberg Hall",_x000D_
"description": "<p>Blumberg Hall</p>",_x000D_
"longitude": "-87.328321",_x000D_
"latitude": "39.483388"_x000D_
}, {_x000D_
"id": "7",_x000D_
"category": "1",_x000D_
"campus_location": "E1",_x000D_
"title": "The Branam Innovation Center",_x000D_
"description": "<p>The Branam Innovation Center</p>",_x000D_
"longitude": "-87.322614",_x000D_
"latitude": "39.48494"_x000D_
}, {_x000D_
"id": "8",_x000D_
"category": "6",_x000D_
"campus_location": "G3",_x000D_
"title": "Chi Omega Sorority",_x000D_
"description": "<p>Chi Omega house</p>",_x000D_
"longitude": "-87.319905",_x000D_
"latitude": "39.482071"_x000D_
}, {_x000D_
"id": "9",_x000D_
"category": "3",_x000D_
"campus_location": "D1",_x000D_
"title": "Cook Stadium/Phil Brown Field",_x000D_
"description": "<p>Cook Stadium at Phil Brown Field</p>",_x000D_
"longitude": "-87.325258",_x000D_
"latitude": "39.485007"_x000D_
}, {_x000D_
"id": "10",_x000D_
"category": "1",_x000D_
"campus_location": "D2",_x000D_
"title": "Crapo Hall",_x000D_
"description": "<p>Crapo Hall</p>",_x000D_
"longitude": "-87.324368",_x000D_
"latitude": "39.483709"_x000D_
}, {_x000D_
"id": "11",_x000D_
"category": "6",_x000D_
"campus_location": "G3",_x000D_
"title": "Delta Delta Delta Sorority",_x000D_
"description": "<p>Delta Delta Delta</p>",_x000D_
"longitude": "-87.317477",_x000D_
"latitude": "39.482951"_x000D_
}, {_x000D_
"id": "12",_x000D_
"category": "6",_x000D_
"campus_location": "D2",_x000D_
"title": "Deming Hall",_x000D_
"description": "<p>Deming Hall</p>",_x000D_
"longitude": "-87.325822",_x000D_
"latitude": "39.483421"_x000D_
}, {_x000D_
"id": "13",_x000D_
"category": "5",_x000D_
"campus_location": "F1",_x000D_
"title": "Facilities Operations",_x000D_
"description": "<p>Facilities Operations</p>",_x000D_
"longitude": "-87.321782",_x000D_
"latitude": "39.484916"_x000D_
}, {_x000D_
"id": "14",_x000D_
"category": "2",_x000D_
"campus_location": "E3",_x000D_
"title": "Flame of the Millennium",_x000D_
"description": "<p>Flame of Millennium sculpture</p>",_x000D_
"longitude": "-87.323306",_x000D_
"latitude": "39.481978"_x000D_
}, {_x000D_
"id": "15",_x000D_
"category": "5",_x000D_
"campus_location": "E2",_x000D_
"title": "Hadley Hall",_x000D_
"description": "<p>Hadley Hall</p>",_x000D_
"longitude": "-87.324046",_x000D_
"latitude": "39.482887"_x000D_
}, {_x000D_
"id": "16",_x000D_
"category": "2",_x000D_
"campus_location": "F2",_x000D_
"title": "Hatfield Hall",_x000D_
"description": "<p>Hatfield Hall</p>",_x000D_
"longitude": "-87.322340",_x000D_
"latitude": "39.482146"_x000D_
}, {_x000D_
"id": "17",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Hulman Memorial Union",_x000D_
"description": "<p>Hulman Memorial Union</p>",_x000D_
"longitude": "-87.32698",_x000D_
"latitude": "39.483574"_x000D_
}, {_x000D_
"id": "18",_x000D_
"category": "1",_x000D_
"campus_location": "E2",_x000D_
"title": "John T. Myers Center for Technological Research with Industry",_x000D_
"description": "<p>John T. Myers Center for Technological Research With Industry</p>",_x000D_
"longitude": "-87.322984",_x000D_
"latitude": "39.484063"_x000D_
}, {_x000D_
"id": "19",_x000D_
"category": "6",_x000D_
"campus_location": "A2",_x000D_
"title": "Lakeside Hall",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.330612",_x000D_
"latitude": "39.482804"_x000D_
}, {_x000D_
"id": "20",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Lambda Chi Alpha Fraternity",_x000D_
"description": "<p>Lambda Chi Alpha</p>",_x000D_
"longitude": "-87.320999",_x000D_
"latitude": "39.48305"_x000D_
}, {_x000D_
"id": "21",_x000D_
"category": "1",_x000D_
"campus_location": "D2",_x000D_
"title": "Logan Library",_x000D_
"description": "<p>Logan Library</p>",_x000D_
"longitude": "-87.324851",_x000D_
"latitude": "39.483408"_x000D_
}, {_x000D_
"id": "22",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Mees Hall",_x000D_
"description": "<p>Mees Hall</p>",_x000D_
"longitude": "-87.32778",_x000D_
"latitude": "39.483533"_x000D_
}, {_x000D_
"id": "23",_x000D_
"category": "1",_x000D_
"campus_location": "E2",_x000D_
"title": "Moench Hall",_x000D_
"description": "<p>Moench Hall</p>",_x000D_
"longitude": "-87.323695",_x000D_
"latitude": "39.483471"_x000D_
}, {_x000D_
"id": "24",_x000D_
"category": "1",_x000D_
"campus_location": "G4",_x000D_
"title": "Oakley Observatory",_x000D_
"description": "<p>Oakley Observatory</p>",_x000D_
"longitude": "-87.31616",_x000D_
"latitude": "39.483789"_x000D_
}, {_x000D_
"id": "25",_x000D_
"category": "1",_x000D_
"campus_location": "D2",_x000D_
"title": "Olin Hall and Olin Advanced Learning Center",_x000D_
"description": "<p>Olin Hall</p>",_x000D_
"longitude": "-87.324550",_x000D_
"latitude": "39.482796"_x000D_
}, {_x000D_
"id": "26",_x000D_
"category": "6",_x000D_
"campus_location": "C3",_x000D_
"title": "Percopo Hall",_x000D_
"description": "<p>Percopo Hall</p>",_x000D_
"longitude": "-87.328182",_x000D_
"latitude": "39.482121"_x000D_
}, {_x000D_
"id": "27",_x000D_
"category": "6",_x000D_
"campus_location": "G3",_x000D_
"title": "Public Safety Office",_x000D_
"description": "<p>The Office of Public Safety</p>",_x000D_
"longitude": "-87.320377",_x000D_
"latitude": "39.48191"_x000D_
}, {_x000D_
"id": "28",_x000D_
"category": "1",_x000D_
"campus_location": "E2",_x000D_
"title": "Rotz Mechanical Engineering Lab",_x000D_
"description": "<p>Rotz Lab</p>",_x000D_
"longitude": "-87.323247",_x000D_
"latitude": "39.483711"_x000D_
}, {_x000D_
"id": "28",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Scharpenberg Hall",_x000D_
"description": "<p>Scharpenberg Hall</p>",_x000D_
"longitude": "-87.328139",_x000D_
"latitude": "39.483582"_x000D_
}, {_x000D_
"id": "29",_x000D_
"category": "6",_x000D_
"campus_location": "G2",_x000D_
"title": "Sigma Nu Fraternity",_x000D_
"description": "<p>The Sigma Nu house</p>",_x000D_
"longitude": "-87.31999",_x000D_
"latitude": "39.48374"_x000D_
}, {_x000D_
"id": "30",_x000D_
"category": "6",_x000D_
"campus_location": "E4",_x000D_
"title": "South Campus / Rose-Hulman Ventures",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.330623",_x000D_
"latitude": "39.417646"_x000D_
}, {_x000D_
"id": "31",_x000D_
"category": "6",_x000D_
"campus_location": "C3",_x000D_
"title": "Speed Hall",_x000D_
"description": "<p>Speed Hall</p>",_x000D_
"longitude": "-87.326632",_x000D_
"latitude": "39.482121"_x000D_
}, {_x000D_
"id": "32",_x000D_
"category": "3",_x000D_
"campus_location": "C1",_x000D_
"title": "Sports and Recreation Center",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.3272",_x000D_
"latitude": "39.484874"_x000D_
}, {_x000D_
"id": "33",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Triangle Fraternity",_x000D_
"description": "<p>Triangle fraternity</p>",_x000D_
"longitude": "-87.32113",_x000D_
"latitude": "39.483659"_x000D_
}, {_x000D_
"id": "34",_x000D_
"category": "6",_x000D_
"campus_location": "B3",_x000D_
"title": "White Chapel",_x000D_
"description": "<p>The White Chapel</p>",_x000D_
"longitude": "-87.329367",_x000D_
"latitude": "39.482481"_x000D_
}, {_x000D_
"id": "35",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Women's Fraternity Housing",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.320753",_x000D_
"latitude": "39.482401"_x000D_
}, {_x000D_
"id": "36",_x000D_
"category": "3",_x000D_
"campus_location": "E1",_x000D_
"title": "Intramural Fields",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.321267",_x000D_
"latitude": "39.485934"_x000D_
}, {_x000D_
"id": "37",_x000D_
"category": "3",_x000D_
"campus_location": "A3",_x000D_
"title": "James Rendel Soccer Field",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.332135",_x000D_
"latitude": "39.480933"_x000D_
}, {_x000D_
"id": "38",_x000D_
"category": "3",_x000D_
"campus_location": "B2",_x000D_
"title": "Art Nehf Field",_x000D_
"description": "<p>Art Nehf Field</p>",_x000D_
"longitude": "-87.330923",_x000D_
"latitude": "39.48022"_x000D_
}, {_x000D_
"id": "39",_x000D_
"category": "3",_x000D_
"campus_location": "B2",_x000D_
"title": "Women's Softball Field",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.329904",_x000D_
"latitude": "39.480278"_x000D_
}, {_x000D_
"id": "40",_x000D_
"category": "3",_x000D_
"campus_location": "D1",_x000D_
"title": "Joy Hulbert Tennis Courts",_x000D_
"description": "<p>The Joy Hulbert Outdoor Tennis Courts</p>",_x000D_
"longitude": "-87.323767",_x000D_
"latitude": "39.485595"_x000D_
}, {_x000D_
"id": "41",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Speed Lake",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.328134",_x000D_
"latitude": "39.482779"_x000D_
}, {_x000D_
"id": "42",_x000D_
"category": "5",_x000D_
"campus_location": "F1",_x000D_
"title": "Recycling Center",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.320098",_x000D_
"latitude": "39.484593"_x000D_
}, {_x000D_
"id": "43",_x000D_
"category": "1",_x000D_
"campus_location": "F3",_x000D_
"title": "Army ROTC",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.321342",_x000D_
"latitude": "39.481992"_x000D_
}, {_x000D_
"id": "44",_x000D_
"category": "2",_x000D_
"campus_location": " ",_x000D_
"title": "Self Made Man",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.326272",_x000D_
"latitude": "39.484481"_x000D_
}, {_x000D_
"id": "P1",_x000D_
"category": "4",_x000D_
"title": "Percopo Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.328756",_x000D_
"latitude": "39.481587"_x000D_
}, {_x000D_
"id": "P2",_x000D_
"category": "4",_x000D_
"title": "Speed Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.327361",_x000D_
"latitude": "39.481694"_x000D_
}, {_x000D_
"id": "P3",_x000D_
"category": "4",_x000D_
"title": "Main Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.326245",_x000D_
"latitude": "39.481446"_x000D_
}, {_x000D_
"id": "P4",_x000D_
"category": "4",_x000D_
"title": "Lakeside Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.330848",_x000D_
"latitude": "39.483284"_x000D_
}, {_x000D_
"id": "P5",_x000D_
"category": "4",_x000D_
"title": "Hatfield Hall Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.321417",_x000D_
"latitude": "39.482398"_x000D_
}, {_x000D_
"id": "P6",_x000D_
"category": "4",_x000D_
"title": "Women's Fraternity Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.320977",_x000D_
"latitude": "39.482315"_x000D_
}, {_x000D_
"id": "P7",_x000D_
"category": "4",_x000D_
"title": "Myers and Facilities Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.322243",_x000D_
"latitude": "39.48417"_x000D_
}, {_x000D_
"id": "P8",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.323241",_x000D_
"latitude": "39.484758"_x000D_
}, {_x000D_
"id": "P9",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.323617",_x000D_
"latitude": "39.484311"_x000D_
}, {_x000D_
"id": "P10",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.325714",_x000D_
"latitude": "39.484584"_x000D_
}, {_x000D_
"id": "P11",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.32778",_x000D_
"latitude": "39.484145"_x000D_
}, {_x000D_
"id": "P12",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.329035",_x000D_
"latitude": "39.4848"_x000D_
}];_x000D_
_x000D_
for (i = 0; i < locations.length; i++) {_x000D_
_x000D_
var marker = new google.maps.Marker({_x000D_
position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),_x000D_
title: locations[i].title,_x000D_
map: map_x000D_
});_x000D_
gmarkers.push(marker);_x000D_
google.maps.event.addListener(marker, 'click', (function(marker, i) {_x000D_
return function() {_x000D_
if (locations[i].description !== "" || locations[i].title !== "") {_x000D_
infowindow.setContent('<div class="content" id="content-' + locations[i].id +_x000D_
'" style="max-height:300px; font-size:12px;"><h3>' + locations[i].title + '</h3>' +_x000D_
'<hr class="grey" />' +_x000D_
hasImage(locations[i]) +_x000D_
locations[i].description) + '</div>';_x000D_
infowindow.open(map, marker);_x000D_
}_x000D_
}_x000D_
})(marker, i));_x000D_
}_x000D_
_x000D_
function toggleMarkers() {_x000D_
for (i = 0; i < gmarkers.length; i++) {_x000D_
if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);_x000D_
else gmarkers[i].setMap(map);_x000D_
}_x000D_
}_x000D_
_x000D_
function hasImage(location) {_x000D_
return '';_x000D_
}
_x000D_
html,_x000D_
body,_x000D_
#map {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>_x000D_
<div id="controls">_x000D_
<input type="button" value="Toggle All Markers" onClick="toggleMarkers()" />_x000D_
</div>_x000D_
<div id="map"></div>
_x000D_
You can use something like this :
SELECT
Books.BookTitle,
Books.Edition,
Books.Year,
Books.Pages,
Books.Rating,
Categories.Category,
Publishers.Publisher,
Writers.LastName
FROM Books
INNER JOIN Categories_Books ON Categories_Books._Books_ISBN = Books._ISBN
INNER JOIN Categories ON Categories._CategoryID = Categories_Books._Categories_Category_ID
INNER JOIN Publishers ON Publishers._Publisherid = Books.PublisherID
INNER JOIN Writers_Books ON Writers_Books._Books_ISBN = Books._ISBN
INNER JOIN Writers ON Writers.Writers_Books = _Writers_WriterID.
As of jQuery 1.7, the .live()
method is deprecated. Use .on()
to attach event handlers.
Example -
$( document ).on( events, selector, data, handler );
using (var context = new DataDb())
{
var ctx = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)context).ObjectContext;
ctx.ExecuteStoreCommand("DELETE FROM [TableName] WHERE Name= {0}", Name);
}
or
using (var context = new DataDb())
{
context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]");
}
The question revolves around how this
keyword behaves in javascript. this
behaves differently as below,
this
is usually determined by a function execution context.this
refers to the global object (the window
object).this
will be undefined
as in strict mode, global object refers to undefined
in place of the window
object.call()
, bind()
, and apply()
new
keyword is used (a constructor), this is bound to the new object being created.this
— instead, this
is bound lexically (i.e. based on the original context)As most of the answers suggest, we can use Arrow function or bind()
Method or Self var. I would quote a point about lambdas (Arrow function) from Google JavaScript Style Guide
Prefer using arrow functions over f.bind(this), and especially over goog.bind(f, this). Avoid writing const self = this. Arrow functions are particularly useful for callbacks, which sometimes pass unexpectedly additional arguments.
Google clearly recommends using lambdas rather than bind or const self = this
So the best solution would be to use lambdas as below,
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', () => {
alert(this.data);
});
}
References:
I'm sorry, I still yet cant comment, so to answer Tom's answer... In javascript (undefined != null) == false In fact that function wont work with "null", you should use "undefined"
"Add a reference to MySql.Data.dll" means you need to add a library reference to the downloaded connector. The IDE will link the database connection library with your application when it compiles.
I downloaded the binary (no installer) zip package from the MySQL web site, extracted onto the desktop, and did the following:
using MySql.Data.MySqlClient;
. If you've added the reference correctly, IntelliSense should offer to complete this for you.Interestingly enough I tried both of these in LinqPad and the variant using group from Dmitry Gribkov by appears to be quicker. (also the final distinct is not required as the result is already distinct.
My (somewhat simple) code was:
public class Pair
{
public int id {get;set;}
public string Arb {get;set;}
}
void Main()
{
var theList = new List<Pair>();
var randomiser = new Random();
for (int count = 1; count < 10000; count++)
{
theList.Add(new Pair
{
id = randomiser.Next(1, 50),
Arb = "not used"
});
}
var timer = new Stopwatch();
timer.Start();
var distinct = theList.GroupBy(c => c.id).Select(p => p.First().id);
timer.Stop();
Debug.WriteLine(timer.Elapsed);
timer.Start();
var otherDistinct = theList.Select(p => p.id).Distinct();
timer.Stop();
Debug.WriteLine(timer.Elapsed);
}
If you want to return from an outer function with an error without exit
ing you can use this trick:
do-something-complex() {
# Using `return` here would only return from `fail`, not from `do-something-complex`.
# Using `exit` would close the entire shell.
# So we (ab)use a different feature. :)
fail() { : "${__fail_fast:?$1}"; }
nested-func() {
try-this || fail "This didn't work"
try-that || fail "That didn't work"
}
nested-func
}
Trying it out:
$ do-something-complex
try-this: command not found
bash: __fail_fast: This didn't work
This has the added benefit/drawback that you can optionally turn off this feature: __fail_fast=x do-something-complex
.
Note that this causes the outermost function to return 1.
As said here and i quote:
just change this line on config.inc.php
$cfg['Servers'][$i]['auth_type'] = 'config';
to
$cfg['Servers'][$i]['auth_type'] = 'cookie';
then you will be prompted to login when you refreshed the page. Afterwards, the log out icon will appear next to home icon.
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
You can load the content from the file. Consider the file is present in asset folder.
public static InputStream loadInputStreamFromAssetFile(Context context, String fileName){
AssetManager am = context.getAssets();
try {
InputStream is = am.open(fileName);
return is;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String loadContentFromFile(Context context, String path){
String content = null;
try {
InputStream is = loadInputStreamFromAssetFile(context, path);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return content;
}
Now you can get the content by calling the function as follow
String json= FileUtil.loadContentFromFile(context, "data.json");
Considering the data.json is stored at Application\app\src\main\assets\data.json
If you don't mind the dictionary values being tuples, you can use itertuples:
>>> {x[0]: x[1:] for x in df.itertuples(index=False)}
{'p': (1, 3, 2), 'q': (4, 3, 2), 'r': (4, 0, 9)}
this.setState(
{
originId: input.originId,
destinationId: input.destinationId,
radius: input.radius,
search: input.search
},
function() { console.log("setState completed", this.state) }
)
this might be helpful
String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());
Reflection can help you.
var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
This question has a lot of answers but all they looks not very useful in case if you really want to use backgroundColor to style your buttons. UIButton has nice option to set different images for different control states but there is not same feature for background colors. So one of solutions is to add extension which will generate images from color and apply them to button.
extension UIButton {
private func image(withColor color: UIColor) -> UIImage? {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
self.setBackgroundImage(image(withColor: color), for: state)
}
}
Only one issue with this solution -- this change won't be applied to buttons created in storyboard. As for me it's not an issue because I prefer to style UI from code. If you want to use storyboards then some additional magic with @IBInspectable
needed.
Second option is subclassing but I prefer to avoid this.
The another workaround is to call
Hibernate.initialize(extractedObject.getSubojbectToUnproxy());
Just before closing the session.
Actually, this is the proper way to get what you want, unless you can use MS SQL 2014 (which finally enables custom format strings for date times).
To get yyyymm
instead of yyyym
, you can use this little trick:
select
right('0000' + cast(datepart(year, getdate()) as varchar(4)), 4)
+ right('00' + cast(datepart(month, getdate()) as varchar(2)), 2)
It's faster and more reliable than gettings parts of convert(..., 112)
.
You use jarsigner to sign APK's. You don't have to sign with the original keystore, just generate a new one. Read up on the details: http://developer.android.com/guide/publishing/app-signing.html
Let's start from keeping in mind that data is stored as bytes; Unicode is a character set where characters are mapped to code points (unique integers), and we need something to translate these code points data into bytes. That's where UTF-8 comes in so called encoding – simple!
"Casting" is different than conversion. In this case, window.location.hash
will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:
window.location.hash = ""+page_number;
window.location.hash = String(page_number);
These conversions are ideal if you don't want an error to be thrown when page_number
is null
or undefined
. Whereas page_number.toString()
and page_number.toLocaleString()
will throw when page_number
is null
or undefined
.
When you only need to cast, not convert, this is how to cast to a string in TypeScript:
window.location.hash = <string>page_number;
// or
window.location.hash = page_number as string;
The <string>
or as string
cast annotations tell the TypeScript compiler to treat page_number
as a string at compile time; it doesn't convert at run time.
However, the compiler will complain that you can't assign a number to a string. You would have to first cast to <any>
, then to <string>
:
window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;
So it's easier to just convert, which handles the type at run time and compile time:
window.location.hash = String(page_number);
(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)
hi firstly there seems to be many 'errors' in your html where you are missing closing tags, you could try wrapping the contents of your <body>
in a fixed width <div style="margin: 0 auto; width: 900px>
to achieve what you have done with the body {margin: 0 10% 0 10%}
You have to repeat your expression everywhere you want to use it:
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
or you can make it a subquery
select P
from (
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
) t
WHERE P LIKE 'NW101%'
It is because you have to write
s="hello"
type(s) == type("")
type accepts an instance and returns its type. In this case you have to compare two instances' types.
If you need to do preemptive checking, it is better if you check for a supported interface than the type.
The type does not really tell you much, apart of the fact that your code want an instance of a specific type, regardless of the fact that you could have another instance of a completely different type which would be perfectly fine because it implements the same interface.
For example, suppose you have this code
def firstElement(parameter):
return parameter[0]
Now, suppose you say: I want this code to accept only a tuple.
import types
def firstElement(parameter):
if type(parameter) != types.TupleType:
raise TypeError("function accepts only a tuple")
return parameter[0]
This is reducing the reusability of this routine. It won't work if you pass a list, or a string, or a numpy.array. Something better would be
def firstElement(parameter):
if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
raise TypeError("interface violation")
return parameter[0]
but there's no point in doing it: parameter[0] will raise an exception if the protocol is not satisfied anyway... this of course unless you want to prevent side effects or having to recover from calls that you could invoke before failing. (Stupid) example, just to make the point:
def firstElement(parameter):
if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
raise TypeError("interface violation")
os.system("rm file")
return parameter[0]
in this case, your code will raise an exception before running the system() call. Without interface checks, you would have removed the file, and then raised the exception.
Winand, Quality was also an issue for me so I did this:
For Each ws In ActiveWorkbook.Worksheets
If ws.PageSetup.PrintArea <> "" Then
'Reverse the effects of page zoom on the exported image
zoom_coef = 100 / ws.Parent.Windows(1).Zoom
areas = Split(ws.PageSetup.PrintArea, ",")
areaNo = 0
For Each a In areas
Set area = ws.Range(a)
' Change xlPrinter to xlScreen to see zooming white space
area.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
Set chartobj = ws.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
chartobj.Chart.Paste
'scale the image before export
ws.Shapes(chartobj.Index).ScaleHeight 3, msoFalse, msoScaleFromTopLeft
ws.Shapes(chartobj.Index).ScaleWidth 3, msoFalse, msoScaleFromTopLeft
chartobj.Chart.Export ws.Name & "-" & areaNo & ".png", "png"
chartobj.delete
areaNo = areaNo + 1
Next
End If
Next
See here:https://robp30.wordpress.com/2012/01/11/improving-the-quality-of-excel-image-export/
git checkout master
master is the tip, or the last commit. gitk will only show you up to where you are in the tree at the time. git reflog will show all the commits, but in this case, you just want the tip, so git checkout master.
I'm not a huge fan of the #if stuff, especially if you spread it all around your code base as it will give you problems where Debug builds pass but Release builds fail if you're not careful.
So here's what I have come up with (inspired by #ifdef in C#):
public interface IDebuggingService
{
bool RunningInDebugMode();
}
public class DebuggingService : IDebuggingService
{
private bool debugging;
public bool RunningInDebugMode()
{
//#if DEBUG
//return true;
//#else
//return false;
//#endif
WellAreWe();
return debugging;
}
[Conditional("DEBUG")]
private void WellAreWe()
{
debugging = true;
}
}
set <ORACLE_HOME> path variable
example
path ORACLE_HOME
value is C:\oraclexe\app\oracle\product\10.2.0\server
Add:
allow_url_fopen=1
in your php.ini
file. If you are using shared hosting, create one first.
The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:
var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
The code above depends on the nuget package RestSharp, which you can easily install.
2^(x+y) = 2^x * 2^y
2^10 ~ 1,000
2^20 ~ 1,000,000
2^30 ~ 1,000,000,000
2^40 ~ 1,000,000,000,000
(etc.)
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
2^5 = 32
2^6 = 64
2^7 = 128
2^8 = 256
2^9 = 512
So, 2^31 (signed int max) is 2^30 (about 1 billion) times 2^1 (2), or about 2 billion. And 2^32 is 2^30 * 2^2 or about 4 billion. This method of approximation is accurate enough even out to around 2^64 (where the error grows to about 15%).
If you need an exact answer then you should pull up a calculator.
Handy word-aligned capacity approximations:
Though this is not directly related to the OP's exact question but I just found out that using a Oracle reserved word in your query (in my case the alias IN
) can cause the same error.
Example:
SELECT * FROM TBL_INDEPENTS IN
JOIN TBL_VOTERS VO on IN.VOTERID = VO.VOTERID
Or if its in the query itself as a field name
SELECT ..., ...., IN, ..., .... FROM SOMETABLE
That would also throw that error. I hope this helps someone.
You need to open the file in binary b
mode to take care of blank lines in Python 2. This isn't required in Python 3.
So, change open('test.csv', 'w')
to open('test.csv', 'wb')
.
You can even abbreviate this a bit by simply using part of the user name:
git log --author=mr #if you're looking for mrfoobar's commits
I do:
int hex = 10;
std::string hexstring = stringFormat("%X", hex);
Take a look at SO answer from iFreilicht and the required template header-file from here GIST!
For people wondering about a Servlet/JSP implementation here's how you go about doing it... I will be explaining uploadimage below also.
1) First make sure you have added the filebrowser and uploadimage variable to your config.js file. Make you also have the uploadimage and filebrowser folder inside the plugins folder too.
2) This part is where it tripped me up:
The Ckeditor website documentation says you need to use these two methods:
function getUrlParam( paramName ) {
var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
var match = window.location.search.match( reParam );
return ( match && match.length > 1 ) ? match[1] : null;
}
function returnFileUrl() {
var funcNum = getUrlParam( 'CKEditorFuncNum' );
var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
window.close();
}
What they don't mention is that these methods have to be on a different page and not the page where you are clicking the browse server button from.
So if you have ckeditor initialized in page editor.jsp then you need to create a file browser (with basic html/css/javascript) in page filebrowser.jsp.
editor.jsp (all you need is this in your script tag) This page will open filebrowser.jsp in a mini window when you click on the browse server button.
CKEDITOR.replace( 'editor', {
filebrowserBrowseUrl: '../filebrowser.jsp', //jsp page with jquery to call servlet and get image files to view
filebrowserUploadUrl: '../UploadImage', //servlet
});
filebrowser.jsp (is the custom file browser you built which will contain the methods mentioned above)
<head>
<script src="../../ckeditor/ckeditor.js"></script>
</head>
<body>
<script>
function getUrlParam( paramName ) {
var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
var match = window.location.search.match( reParam );
return ( match && match.length > 1 ) ? match[1] : null;
}
function returnFileUrl() {
var funcNum = getUrlParam( 'CKEditorFuncNum' );
var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
window.close();
}
//when this window opens it will load all the images which you send from the FileBrowser Servlet.
getImages();
function getImages(){
$.get("../FileBrowser", function(responseJson) {
//do something with responseJson (like create <img> tags and update the src attributes)
});
}
//you call this function and pass 'fileUrl' when user clicks on an image that you loaded into this window from a servlet
returnFileUrl();
</script>
</body>
3) The FileBrowser Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Images i = new Images();
List<ImageObject> images = i.getImages(); //get images from your database or some cloud service or whatever (easier if they are in a url ready format)
String json = new Gson().toJson(images);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
4) UploadImage Servlet
Go back to your config.js file for ckeditor and add the following line:
//https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
config.uploadUrl = '/UploadImage';
Then you can drag and drop files also:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Images i = new Images();
//do whatever you usually do to upload your image to your server (in my case i uploaded to google cloud storage and saved the url in a database.
//Now this part is important. You need to return the response in json format. And it has to look like this:
// https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
// response must be in this format:
// {
// "uploaded": 1,
// "fileName": "example.png",
// "url": "https://www.cats.com/example.png"
// }
String image = "https://www.cats.com/example.png";
ImageObject objResponse = i.getCkEditorObjectResponse(image);
String json = new Gson().toJson(objResponse);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
And that's all folks. Hope it helps someone.
I have written comments below to understand code sample. Some one if using, they can follow it , as I named the files accordingly.
IF server is sending blob in the response, then our client should be able to produce it.
As my purpose is solved by using these. I can able to download files, as I have used type: 'application/*' for all files.
Created "downloadLink" variable is just technique used in response so that, it would fill like some clicked on link, then response comes and then its href would be triggered.
controller.js_x000D_
//this function is in controller, which will be trigered on download button hit. _x000D_
_x000D_
$scope.downloadSampleFile = function() {_x000D_
//create sample hidden link in document, to accept Blob returned in the response from back end_x000D_
_x000D_
var downloadLink = document.createElement("a");_x000D_
_x000D_
document.body.appendChild(downloadLink);_x000D_
downloadLink.style = "display: none";_x000D_
_x000D_
//This service is written Below how does it work, by aceepting necessary params_x000D_
downloadFile.downloadfile(data).then(function (result) {_x000D_
_x000D_
var fName = result.filename;_x000D_
var file = new Blob([result.data], {type: 'application/*'});_x000D_
var fileURL = (window.URL || window.webkitURL).createObjectURL(file);_x000D_
_x000D_
_x000D_
//Blob, client side object created to with holding browser specific download popup, on the URL created with the help of window obj._x000D_
_x000D_
downloadLink.href = fileURL;_x000D_
downloadLink.download = fName;_x000D_
downloadLink.click();_x000D_
});_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
services.js_x000D_
_x000D_
.factory('downloadFile', ["$http", function ($http) {_x000D_
return {_x000D_
downloadfile : function () {_x000D_
return $http.get(//here server endpoint to which you want to hit the request_x000D_
, {_x000D_
responseType: 'arraybuffer',_x000D_
params: {_x000D_
//Required params_x000D_
},_x000D_
}).then(function (response, status, headers, config) {_x000D_
return response;_x000D_
});_x000D_
},_x000D_
};_x000D_
}])
_x000D_
In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime()
gives you the mentioned milliseconds).
In your solution:
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();
long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);
you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.
Another possible solution would be to utilise the static fields of the Calendar
class:
//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);
Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.
Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?
No, it means that if no data arrives within 2000ms a SocketTimeoutException
will be thrown.
What does it mean timeout expire?
It means the 2000ms (in your case) elapses without any data arriving.
What is the option which must be enabled prior to blocking operation?
There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.
Infinite Timeout menas that the socket does't read anymore?
What a strange suggestion. It means that if no data ever arrives you will block in the read forever.
What you have is a valid ADO.NET connection string - but it's NOT a valid Entity Framework connection string.
The EF connection string would look something like this:
<connectionStrings>
<add name="NorthwindEntities" connectionString=
"metadata=.\Northwind.csdl|.\Northwind.ssdl|.\Northwind.msl;
provider=System.Data.SqlClient;
provider connection string="Data Source=SERVER\SQL2000;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=False""
providerName="System.Data.EntityClient" />
</connectionStrings>
You're missing all the metadata=
and providerName=
elements in your EF connection string...... you basically only have what's contained in the provider connection string
part.
Using the EDMX designer should create a valid EF connection string for you, in your web.config or app.config.
Marc
UPDATE: OK, I understand what you're trying to do: you need a second "ADO.NET" connection string just for ASP.NET user / membership database. Your string is OK, but the providerName is wrong - it would have to be "System.Data.SqlClient" - this connection doesn't use ENtity Framework - don't specify the "EntityClient" for it then!
<add name="ASPNETMembership"
connectionString="Data Source=MONTGOMERY-DEV\SQLEXPRESS;Initial Catalog=ASPNETDB;Integrated Security=True;"
providerName="System.Data.SqlClient" />
If you specify providerName=System.Data.EntityClient
==> Entity Framework connection string (with the metadata= and everything).
If you need and specify providerName=System.Data.SqlClient
==> straight ADO.NET SQL Server connection string without all the EF additions
Go to your respective git repo, then run the below command:
git diff filename
It will open the file with the changes marked, press return/enter key to scroll down the file.
P.S. filename should include the full path of the file or else you can run without the full file path by going in the respective directory/folder of the file
The merge()
method on the Collection
does not modify the collection on which it was called. It returns a new collection with the new data merged in. You would need:
$related = $related->merge($tag->questions);
However, I think you're tackling the problem from the wrong angle.
Since you're looking for questions that meet a certain criteria, it would probably be easier to query in that manner. The has()
and whereHas()
methods are used to generate a query based on the existence of a related record.
If you were just looking for questions that have any tag, you would use the has()
method. Since you're looking for questions with a specific tag, you would use the whereHas()
to add the condition.
So, if you want all the questions that have at least one tag with either 'Travel', 'Trains', or 'Culture', your query would look like:
$questions = Question::whereHas('tags', function($q) {
$q->whereIn('name', ['Travel', 'Trains', 'Culture']);
})->get();
If you wanted all questions that had all three of those tags, your query would look like:
$questions = Question::whereHas('tags', function($q) {
$q->where('name', 'Travel');
})->whereHas('tags', function($q) {
$q->where('name', 'Trains');
})->whereHas('tags', function($q) {
$q->where('name', 'Culture');
})->get();
You can use append
(to add at last position of parent) or prepend
(to add at fist position of parent):
$('#parent').append('<div>hello</div>');
// or
$('<div>hello</div>').appendTo('#parent');
Alternatively, you can use the .html()
or .add()
as mentioned in a different answer.
I tried the following and it works for me better
Code:
.unstyled-link{
color: inherit;
text-decoration: inherit;
&:link,
&:hover {
color: inherit;
text-decoration: inherit;
}
}
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
Here is a complete answer from hmkcode.com
If we have such JSON data
// JSON Data
var articles = [
{
"title":"Title 1",
"url":"URL 1",
"categories":["jQuery"],
"tags":["jquery","json","$.each"]
},
{
"title":"Title 2",
"url":"URL 2",
"categories":["Java"],
"tags":["java","json","jquery"]
}
];
And we want to view in this Table structure
<table id="added-articles" class="table">
<tr>
<th>Title</th>
<th>Categories</th>
<th>Tags</th>
</tr>
</table>
The following JS code will fill create a row for each JSON element
// 1. remove all existing rows
$("tr:has(td)").remove();
// 2. get each article
$.each(articles, function (index, article) {
// 2.2 Create table column for categories
var td_categories = $("<td/>");
// 2.3 get each category of this article
$.each(article.categories, function (i, category) {
var span = $("<span/>");
span.text(category);
td_categories.append(span);
});
// 2.4 Create table column for tags
var td_tags = $("<td/>");
// 2.5 get each tag of this article
$.each(article.tags, function (i, tag) {
var span = $("<span/>");
span.text(tag);
td_tags.append(span);
});
// 2.6 Create a new row and append 3 columns (title+url, categories, tags)
$("#added-articles").append($('<tr/>')
.append($('<td/>').html("<a href='"+article.url+"'>"+article.title+"</a>"))
.append(td_categories)
.append(td_tags)
);
});
Note that the default when you make a class is not public as far as packages are considered. Make sure that you actually write public class [MyClass] {
when defining your class. I've made this mistake more times than I care to admit.
Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.
If the gif is displayed but not animating, see reference links at very bottom of this answer.
Displaying the gif + overlay, however, is easier than you might think.
All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.
So, when the button is pressed, just unhide those two divs. That's it!
$("#button").click(function() {_x000D_
$('#myOverlay').show();_x000D_
$('#loadingGIF').show();_x000D_
setTimeout(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
},2500);_x000D_
});_x000D_
/* Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
You might enjoy playing with the new backdrop-filter:blur(_px)
css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)
References:
http://www.paulirish.com/2007/animated-gif-not-animating/
Animated GIF while loading page does not animate
https://wordpress.org/support/topic/animated-gif-not-working
For People, looking for answers w.r.t to 'map' function and dynamic data, here is a working example.
<img src={"http://examole.com/randomview/images" + each_actor['logo']} />
This gives the URL as "http://examole.com/randomview/images/2/dp_pics/182328.jpg" (random example)
Get the selected item with Kotlin:
spinner.selectedItem.toString()
var arr1 = [_x000D_
{name: 'a', Val: 1}, _x000D_
{name: 'b', Val: 2}, _x000D_
{name: 'c', Val: 3}_x000D_
];_x000D_
_x000D_
var arr2 = [_x000D_
{name: 'c', Val: 3},_x000D_
{name: 'x', Val: 4}, _x000D_
{name: 'y', Val: 5}, _x000D_
{name: 'z', Val: 6}_x000D_
];_x000D_
var _isEqual = _.intersectionWith(arr1, arr2, _.isEqual);// common in both array_x000D_
var _difference1 = _.differenceWith(arr1, arr2, _.isEqual);//difference from array1 _x000D_
var _difference2 = _.differenceWith(arr2, arr1, _.isEqual);//difference from array2 _x000D_
console.log(_isEqual);// common in both array_x000D_
console.log(_difference1);//difference from array1 _x000D_
console.log(_difference2);//difference from array2
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
_x000D_
OPTIONS
method returns info about API (methods/content type)
HEAD
method returns info about resource (version/length/type)
Server response
OPTIONS
HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0
HEAD
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
OPTIONS
Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?HEAD
Checking whether a resource has changed. This is useful when maintaining a cached version of a resourceHEAD
Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrievalHEAD, OPTIONS
Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application
Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.
Not really solve your question but it's an important alternative.
If you want to add custom html to the beginning of the page (inside <body>
element), you may use Page.ClientScript.RegisterClientScriptBlock()
.
Although the method is called "script", but you can add arbitary string, including html.
If you are using the LaunchScreen.storyboard you can obtain the same view controller and present it: (remember to set the storyboard id, for example "LaunchScreen")
func applicationDidBecomeActive(application: UIApplication) {
let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("LaunchScreen")
self.window!.rootViewController!.presentViewController(vc, animated: false, completion: nil)
}
SWIFT 4
let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "LaunchScreen")
self.window!.rootViewController!.present(vc, animated: false, completion: nil)
<style type="text/css">
p {margin-bottom: -1em; margin-top: 0em;}
</style>
This completely worked for me. Paragraphs were right below each other. When I used 0em for both the margins, there was still some space left in between the lines. I went for Developer tools in my browser, tried with -1em and it worked.
Download and install Eclipse, and you're good to go.
http://www.eclipse.org/downloads/
Apple provides its own version of Java, so make sure it's up-to-date.
http://developer.apple.com/java/download/
Eclipse is an integrated development environment. It has many features, but the ones that are relevant for you at this stage is:
As you gain more experience, you'll start to appreciate the rest of its rich set of features.
I suspect you're getting text/html encoding in response to your request so I believe the issue is:
dataType : 'json',
try changing it to
dataType : 'html',
From http://api.jquery.com/jQuery.get/:
dataType Type: String The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
Neither a ":" nor a "." will show up in valid Base64, so I think you can unambiguously throw away the http://www.stackoverflow.com
line. In Perl, say, something like
my $sanitized_str = join q{}, grep {!/[^A-Za-z0-9+\/=]/} split /\n/, $str;
say decode_base64($sanitized_str);
might be what you want. It produces
This is simple ASCII Base64 for StackOverflow exmaple.
Assuming $foo
is an integer:
$answer = (int) (floor(($foo + 5) / 6) * 6)
Avoid any?
for large arrays.
any?
is O(n)
empty?
is O(1)
any?
does not check the length but actually scans the whole array for truthy elements.
static VALUE
rb_ary_any_p(VALUE ary)
{
long i, len = RARRAY_LEN(ary);
const VALUE *ptr = RARRAY_CONST_PTR(ary);
if (!len) return Qfalse;
if (!rb_block_given_p()) {
for (i = 0; i < len; ++i) if (RTEST(ptr[i])) return Qtrue;
}
else {
for (i = 0; i < RARRAY_LEN(ary); ++i) {
if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qtrue;
}
}
return Qfalse;
}
empty?
on the other hand checks the length of the array only.
static VALUE
rb_ary_empty_p(VALUE ary)
{
if (RARRAY_LEN(ary) == 0)
return Qtrue;
return Qfalse;
}
The difference is relevant if you have "sparse" arrays that start with lots of nil
values, like for example an array that was just created.
This was the only way I could get this to work
add_action('init','add_query_args');
function add_query_args()
{
add_query_arg( 'var1', 'val1' );
}
I ran across this problem while automating a restore proccess in SQL Server 2008. My (successfull) approach was a mix of two of the answers provided.
First, I run across all the connections of said database, and kill them.
DECLARE @SPID int = (SELECT TOP 1 SPID FROM sys.sysprocess WHERE dbid = db_id('dbName'))
While @spid Is Not Null
Begin
Execute ('Kill ' + @spid)
Select @spid = top 1 spid from master.dbo.sysprocesses
where dbid = db_id('dbName')
End
Then, I set the database to a single_user mode
ALTER DATABASE dbName SET SINGLE_USER
Then, I run the restore...
RESTORE DATABASE and whatnot
Kill the connections again
(same query as above)
And set the database back to multi_user.
ALTER DATABASE dbName SET MULTI_USER
This way, I ensure that there are no connections holding up the database before setting to single mode, since the former will freeze if there are.
I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).
Solution is: First Update ADT to 22.0.4 and then Update SDK Tool to 22.0.4
The above link says,
ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so
What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).
How to Update your ADT to Latest Version
In Eclipse go to Help
Install New Software
---> Add
inside Add Repository write the Name: ADT
(or whatever you want)
Location: https://dl-ssl.google.com/android/eclipse/
after loading you should get Developer Tools and NDK Plugins
check both if you want to use the Native Developer Kit (NDK) in the future or check
Developer Tool only
click Next
Finish
Imagine you have have a Book model and a Page model,
1:N means:
One book can have **many** pages. One page can only be in **one** book.
N:N means:
One book can have **many** pages. And one page can be in **many** books.
While this doesn't directly answer you question, I think it might be a good solution for you in the future. I saw a part of my code, which was bad. Didn't know who wrote it or when. I could see all changes from the file, but it was clear that the code had been moved from some other file to this one. I wanted to find who actually added it in the first place.
To do this, I used Git bisect, which quickly let me find the sinner.
I ran git bisect start
and then git bisect bad
, because the revision checked out had the issue. Since I didn't know when the problem occured, I targetted the first commit for the "good", git bisect good <initial sha>
.
Then I just kept searching the repo for the bad code. When I found it, I ran git bisect bad
, and when it wasn't there: git bisect good
.
In ~11 steps, I had covered ~1000 commits and found the exact commit, where the issue was introduced. Pretty great.
The String#replaceAll()
interprets the argument as a regular expression. The \
is an escape character in both String
and regex
. You need to double-escape it for regex:
string.replaceAll("\\\\", "\\\\\\\\");
But you don't necessarily need regex for this, simply because you want an exact character-by-character replacement and you don't need patterns here. So String#replace()
should suffice:
string.replace("\\", "\\\\");
Update: as per the comments, you appear to want to use the string in JavaScript context. You'd perhaps better use StringEscapeUtils#escapeEcmaScript()
instead to cover more characters.
The accepted answer is correct, but there is a more clever/efficient way to do this if you need to convert a whole bunch of ASCII characters to their ASCII codes at once. Instead of doing:
for ch in mystr:
code = ord(ch)
or the slightly faster:
for code in map(ord, mystr):
you convert to Python native types that iterate the codes directly. On Python 3, it's trivial:
for code in mystr.encode('ascii'):
and on Python 2.6/2.7, it's only slightly more involved because it doesn't have a Py3 style bytes
object (bytes
is an alias for str
, which iterates by character), but they do have bytearray
:
# If mystr is definitely str, not unicode
for code in bytearray(mystr):
# If mystr could be either str or unicode
for code in bytearray(mystr, 'ascii'):
Encoding as a type that natively iterates by ordinal means the conversion goes much faster; in local tests on both Py2.7 and Py3.5, iterating a str
to get its ASCII codes using map(ord, mystr)
starts off taking about twice as long for a len
10 str
than using bytearray(mystr)
on Py2 or mystr.encode('ascii')
on Py3, and as the str
gets longer, the multiplier paid for map(ord, mystr)
rises to ~6.5x-7x.
The only downside is that the conversion is all at once, so your first result might take a little longer, and a truly enormous str
would have a proportionately large temporary bytes
/bytearray
, but unless this forces you into page thrashing, this isn't likely to matter.
PHP Code
<?php
error_reporting(0);
session_start();
include('config.php');
//define session id
$session_id='1';
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//set the image extentions
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //image upload directory
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats))
{
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$time=time();
//insert in database
mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>';
}
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
}
}
?>
Jquery Code
<script>
$(document).ready(function() {
$('#photoimg').die('click').live('change', function() {
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
console.log('ttest');
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
console.log('test');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
console.log('xtest');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
});
});
</script>