Are you sure that you have specified the correct paths?
You need to be in the right directory, i.e.
C:\Program Files\MongoDB\bin
and the path you are installing into needs to be the correct one
i.e.
mongod --dbpath
C:\Users\Name\Documents\myWebsites\nodetest1
A folder named "data" must also exist in your project folder.
I got the same error and this worked for me.
Look here, the operator used is !!
.
I.e. [1,2,3]!!1
gives you 2
, since lists are 0-indexed.
import telnetlib
user = "admin"
password = "\r"
def connect(A):
tnA = telnetlib.Telnet(A)
tnA.read_until('username: ', 3)
tnA.write(user + '\n')
tnA.read_until('password: ', 3)
tnA.write(password + '\n')
return tnA
def quit_telnet(tn)
tn.write("bye\n")
tn.write("quit\n")
If you want to see the contents of RDD then yes collect is one option, but it fetches all the data to driver so there can be a problem
<rdd.name>.take(<num of elements you want to fetch>)
Better if you want to see just a sample
Running foreach and trying to print, I dont recommend this because if you are running this on cluster then the print logs would be local to the executor and it would print for the data accessible to that executor. print statement is not changing the state hence it is not logically wrong. To get all the logs you will have to do something like
**Pseudocode**
collect
foreach print
But this may result in job failure as collecting all the data on driver may crash it. I would suggest using take command or if u want to analyze it then use sample collect on driver or write to file and then analyze it.
These solutions work, but they work for your code ONLY on your machine. I would add a couple of lines to your code that look like this:
import sys
if "C:\\My_Python_Lib" not in sys.path:
sys.path.append("C:\\My_Python_Lib")
That should take care of your problems
Don't run this command on shell, enter this script at a command prompt with your database name, collection name, and file name, all replacing the placeholders..
mongoexport --db (Database name) --collection (Collection Name) --out (File name).json
It works for me.
You can start your container with the flag -P
. This "assigns" a random port to the exposed port of your image.
With docker port <container id>
you can see the randomly choosen port. Access is then possible via localhost:port
.
Since this is for Unix, the executables don't have any extensions.
One thing to note is that root-config
is a utility which provides the right compilation and linking flags; and the right libraries for building applications against root. That's just a detail related to the original audience for this document.
or You Never Forget The First Time You Got Made
An introductory discussion of make, and how to write a simple makefile
What is Make? And Why Should I Care?
The tool called Make is a build dependency manager. That is, it takes care of knowing what commands need to be executed in what order to take your software project from a collection of source files, object files, libraries, headers, etc., etc.---some of which may have changed recently---and turning them into a correct up-to-date version of the program.
Actually, you can use Make for other things too, but I'm not going to talk about that.
A Trivial Makefile
Suppose that you have a directory containing: tool
tool.cc
tool.o
support.cc
support.hh
, and support.o
which depend on root
and are supposed to be compiled into a program called tool
, and suppose that you've been hacking on the source files (which means the existing tool
is now out of date) and want to compile the program.
To do this yourself you could
Check if either support.cc
or support.hh
is newer than support.o
, and if so run a command like
g++ -g -c -pthread -I/sw/include/root support.cc
Check if either support.hh
or tool.cc
are newer than tool.o
, and if so run a command like
g++ -g -c -pthread -I/sw/include/root tool.cc
Check if tool.o
is newer than tool
, and if so run a command like
g++ -g tool.o support.o -L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
-lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz -Wl,-framework,CoreServices \
-Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root -lm -ldl
Phew! What a hassle! There is a lot to remember and several chances to make mistakes. (BTW-- the particulars of the command lines exhibited here depend on our software environment. These ones work on my computer.)
Of course, you could just run all three commands every time. That would work, but it doesn't scale well to a substantial piece of software (like DOGS which takes more than 15 minutes to compile from the ground up on my MacBook).
Instead you could write a file called makefile
like this:
tool: tool.o support.o
g++ -g -o tool tool.o support.o -L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
-lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz -Wl,-framework,CoreServices \
-Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root -lm -ldl
tool.o: tool.cc support.hh
g++ -g -c -pthread -I/sw/include/root tool.cc
support.o: support.hh support.cc
g++ -g -c -pthread -I/sw/include/root support.cc
and just type make
at the command line. Which will perform the three steps shown above automatically.
The unindented lines here have the form "target: dependencies" and tell Make that the associated commands (indented lines) should be run if any of the dependencies are newer than the target. That is, the dependency lines describe the logic of what needs to be rebuilt to accommodate changes in various files. If support.cc
changes that means that support.o
must be rebuilt, but tool.o
can be left alone. When support.o
changes tool
must be rebuilt.
The commands associated with each dependency line are set off with a tab (see below) should modify the target (or at least touch it to update the modification time).
At this point, our makefile is simply remembering the work that needs doing, but we still had to figure out and type each and every needed command in its entirety. It does not have to be that way: Make is a powerful language with variables, text manipulation functions, and a whole slew of built-in rules which can make this much easier for us.
Make Variables
The syntax for accessing a make variable is $(VAR)
.
The syntax for assigning to a Make variable is: VAR = A text value of some kind
(or VAR := A different text value but ignore this for the moment
).
You can use variables in rules like this improved version of our makefile:
CPPFLAGS=-g -pthread -I/sw/include/root
LDFLAGS=-g
LDLIBS=-L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
-lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz \
-Wl,-framework,CoreServices -Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root \
-lm -ldl
tool: tool.o support.o
g++ $(LDFLAGS) -o tool tool.o support.o $(LDLIBS)
tool.o: tool.cc support.hh
g++ $(CPPFLAGS) -c tool.cc
support.o: support.hh support.cc
g++ $(CPPFLAGS) -c support.cc
which is a little more readable, but still requires a lot of typing
Make Functions
GNU make supports a variety of functions for accessing information from the filesystem or other commands on the system. In this case we are interested in $(shell ...)
which expands to the output of the argument(s), and $(subst opat,npat,text)
which replaces all instances of opat
with npat
in text.
Taking advantage of this gives us:
CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)
SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))
tool: $(OBJS)
g++ $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)
tool.o: tool.cc support.hh
g++ $(CPPFLAGS) -c tool.cc
support.o: support.hh support.cc
g++ $(CPPFLAGS) -c support.cc
which is easier to type and much more readable.
Notice that
Implicit and Pattern Rules
We would generally expect that all C++ source files should be treated the same way, and Make provides three ways to state this:
Implicit rules are built in, and a few will be discussed below. Pattern rules are specified in a form like
%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $<
which means that object files are generated from C source files by running the command shown, where the "automatic" variable $<
expands to the name of the first dependency.
Built-in Rules
Make has a whole host of built-in rules that mean that very often, a project can be compile by a very simple makefile, indeed.
The GNU make built in rule for C source files is the one exhibited above. Similarly we create object files from C++ source files with a rule like $(CXX) -c $(CPPFLAGS) $(CFLAGS)
.
Single object files are linked using $(LD) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS)
, but this won't work in our case, because we want to link multiple object files.
Variables Used By Built-in Rules
The built-in rules use a set of standard variables that allow you to specify local environment information (like where to find the ROOT include files) without re-writing all the rules. The ones most likely to be interesting to us are:
CC
-- the C compiler to useCXX
-- the C++ compiler to useLD
-- the linker to useCFLAGS
-- compilation flag for C source filesCXXFLAGS
-- compilation flags for C++ source filesCPPFLAGS
-- flags for the c-preprocessor (typically include file paths and symbols defined on the command line), used by C and C++LDFLAGS
-- linker flagsLDLIBS
-- libraries to linkA Basic Makefile
By taking advantage of the built-in rules we can simplify our makefile to:
CC=gcc
CXX=g++
RM=rm -f
CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)
SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))
all: tool
tool: $(OBJS)
$(CXX) $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)
tool.o: tool.cc support.hh
support.o: support.hh support.cc
clean:
$(RM) $(OBJS)
distclean: clean
$(RM) tool
We have also added several standard targets that perform special actions (like cleaning up the source directory).
Note that when make is invoked without an argument, it uses the first target found in the file (in this case all), but you can also name the target to get which is what makes make clean
remove the object files in this case.
We still have all the dependencies hard-coded.
Some Mysterious Improvements
CC=gcc
CXX=g++
RM=rm -f
CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)
SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))
all: tool
tool: $(OBJS)
$(CXX) $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)
depend: .depend
.depend: $(SRCS)
$(RM) ./.depend
$(CXX) $(CPPFLAGS) -MM $^>>./.depend;
clean:
$(RM) $(OBJS)
distclean: clean
$(RM) *~ .depend
include .depend
Notice that
make
then ls -A
you see a file named .depend
which contains things that look like make dependency linesOther Reading
Know Bugs and Historical Notes
The input language for Make is whitespace sensitive. In particular, the action lines following dependencies must start with a tab. But a series of spaces can look the same (and indeed there are editors that will silently convert tabs to spaces or vice versa), which results in a Make file that looks right and still doesn't work. This was identified as a bug early on, but (the story goes) it was not fixed, because there were already 10 users.
(This was copied from a wiki post I wrote for physics graduate students.)
You can use display: table-cell and vertical-align: bottom, on the 2 columns that you want to be aligned bottom, like so:
.bottom-column
{
float: none;
display: table-cell;
vertical-align: bottom;
}
Working example here.
Also, this might be a possible duplicate question.
I recently encountered this error when I refereneced a project that was initiliazed via a git submodule.
I ended up finding out that the root build.gradle
file of the submodule (a java project) did not have the java plugin applied at the root level.
It only had
apply plugin: 'idea'
I added the java plugin:
apply plugin: 'idea'
apply plugin: 'java'
Once I applied the java plugin the 'default not found' message disappeared and the build succeeded.
In the Hibernate Manual you can see this example
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
for (int i = 0; i < 100000; i++) {
Customer customer = new Customer(...);
session.save(customer);
if (i % 20 == 0) { // 20, same as the JDBC batch size
// flush a batch of inserts and release memory:
session.flush();
session.clear();
}
}
tx.commit();
session.close();
Without the call to the flush method, your first-level cache would throw an OutOfMemoryException
I have a listview which shows the Information about the all clients I am sorting the clients name using this custom comparator class. They are having some extra lerret apart from english letters which i am managing with this setStrength(Collator.SECONDARY)
public class CustomNameComparator implements Comparator<ClientInfo> {
@Override
public int compare(ClientInfo o1, ClientInfo o2) {
Locale locale=Locale.getDefault();
Collator collator = Collator.getInstance(locale);
collator.setStrength(Collator.SECONDARY);
return collator.compare(o1.title, o2.title);
}
}
PRIMARY strength: Typically, this is used to denote differences between base characters (for example, "a" < "b"). It is the strongest difference. For example, dictionaries are divided into different sections by base character.
SECONDARY strength: Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings.
TERTIARY strength: Upper and lower case differences in characters are distinguished at tertiary strength (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary strength (such as "A" and "?"). Another example is the difference between large and small Kana. A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings.
IDENTICAL strength: When all other strengths are equal, the IDENTICAL strength is used as a tiebreaker. The Unicode code point values of the NFD form of each string are compared, just in case there is no difference. For example, Hebrew cantellation marks are only distinguished at this strength. This strength should be used sparingly, as only code point value differences between two strings are an extremely rare occurrence. Using this strength substantially decreases the performance for both comparison and collation key generation APIs. This strength also increases the size of the collation key.
**Here is a another way to make a rule base sorting if u need it just sharing**
/* String rules="< å,Å< ä,Ä< a,A< b,B< c,C< d,D< é< e,E< f,F< g,G< h,H< ï< i,I"+"< j,J< k,K< l,L< m,M< n,N< ö,Ö< o,O< p,P< q,Q< r,R"+"< s,S< t,T< ü< u,U< v,V< w,W< x,X< y,Y< z,Z";
RuleBasedCollator rbc = null;
try {
rbc = new RuleBasedCollator(rules);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String myTitles[]={o1.title,o2.title};
Collections.sort(Arrays.asList(myTitles), rbc);*/
You have to use ':' colon instead of ';' semicolon.
As it stands now you try to execute the jar file which has not the execute bit set, hence the Permission denied.
And the variable must be CLASSPATH not classpath.
Pointers generally have a fixed size, for ex. on a 32-bit executable they're usually 32-bit. There are some exceptions, like on old 16-bit windows when you had to distinguish between 32-bit pointers and 16-bit... It's usually pretty safe to assume they're going to be uniform within a given executable on modern desktop OS's.
Edit: Even so, I would strongly caution against making this assumption in your code. If you're going to write something that absolutely has to have a pointers of a certain size, you'd better check it!
Function pointers are a different story -- see Jens' answer for more info.
var id = $(this).find('option:selected').attr('id');
then you do whatever you want with selectedIndex
I've reedited my answer ... since selectedIndex isn't a good variable to give example...
If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:
# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master
I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.
If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours
merge strategy:
# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master
You can use a dynamic array when you don't know the number of values it will contain until run-time:
Dim Zombies() As Integer
ReDim Zombies(NumberOfZombies)
Or you could do everything with one statement if you're creating an array that's local to a procedure:
ReDim Zombies(NumberOfZombies) As Integer
Fixed-size arrays require the number of elements contained to be known at compile-time. This is why you can't use a variable to set the size of the array—by definition, the values of a variable are variable and only known at run-time.
You could use a constant if you knew the value of the variable was not going to change:
Const NumberOfZombies = 2000
but there's no way to cast between constants and variables. They have distinctly different meanings.
You are missing two closing parentheses...and I am not sure an ampersand works as a string concatenation operator. Try '+'
SELECT dbo.COL_V_Cost_GEMS_Detail.TNG_SYS_NR AS [EHP Code],
dbo.COL_TBL_VCOURSE.TNG_NA AS [Course Title],
LTRIM(RTRIM(FCT_TYP_CD)) + ') AND (' + LTRIM(RTRIM(DEP_TYP_ID)) + ')' AS [Course Owner]
./me casts raise_dead()
I was looking for something like this, but I also needed to reuse the same string minus two parameters so I ended up with something like:
my_exe ()
{
mysql -sN -e "select $1 from heat.stack where heat.stack.name=\"$2\";"
}
This is something I use to monitor openstack heat stack creation. In this case I expect two conditions, an action 'CREATE' and a status 'COMPLETE' on a stack named "Somestack"
To get those variables I can do something like:
ACTION=$(my_exe action Somestack)
STATUS=$(my_exe status Somestack)
if [[ "$ACTION" == "CREATE" ]] && [[ "$STATUS" == "COMPLETE" ]]
...
boolean alltrue = true;
for(int i = 0; alltrue && i<booleanArray.length(); i++)
alltrue &= booleanArray[i];
I think this looks ok and behaves well...
For New way we have registerForActivityResult
In Java :
// You need to create lanucher variable inside onAttach or onCreate or global, i.e, before the activity is displayed
ActivityResultLauncher<Intent> launchSomeActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
// your operation....
}
}
});
public void openYourActivity() {
Intent intent = new Intent(this, SomeActivity.class);
launchSomeActivity.launch(intent);
}
In Kotlin :
var resultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
// your operation...
}
}
fun openYourActivity() {
val intent = Intent(this, SomeActivity::class.java)
resultLauncher.launch(intent)
}
New way is reduce complexity which we faced when we call activity from fragment or from another activity
I kind of got things working by adding auto layout constraints:
But I am not happy with this. Took a lot of trial and error and couldn't understand why this worked.
Also I had to add to use titleLabel.numberOfLines = 0
in my ViewController
Ben Nadel has written a good article about this, he points out the difference in the parameters to these functions:
String.slice( begin [, end ] )
String.substring( from [, to ] )
String.substr( start [, length ] )
He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn't.
Here is his article about this.
For the benefit of anyone reading this later, you need to link against it as Fred said:
gcc fib.c -lm -o fibo
One good way to find out what library you need to link is by checking the man page if one exists. For example, man pow
and man floor
will both tell you:
Link with -lm
.
An explanation for linking math library in C programming - Linking in C
Try to execute
mvn -U clean
or Run > Maven Clean and Maven > Update snapshots from project context menu in eclipse
If you're looking for "update if exists else create" use case, please refer to @Zags excellent answer
Django already has a get_or_create
, https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create
For you it could be :
id = 'some identifier'
person, created = Person.objects.get_or_create(identifier=id)
if created:
# means you have created a new person
else:
# person just refers to the existing one
You just need to cast at least one of the operands to a float:
float z = (float) x / y;
or
float z = x / (float) y;
or (unnecessary)
float z = (float) x / (float) y;
function test(string) {
return ! string.match(/abc|def/);
}
You could do something like this:
#youritem .fade.in {
animation-name: fadeIn;
}
#youritem .fade.out {
animation-name: fadeOut;
}
@keyframes fadeIn {
0% {
opacity: 0;
transform: translateY(startYposition);
}
100% {
opacity: 1;
transform: translateY(endYposition);
}
}
@keyframes fadeOut {
0% {
opacity: 1;
transform: translateY(startYposition);
}
100% {
opacity: 0;
transform: translateY(endYposition);
}
}
Example - Slide and Fade:
This slides and animates the opacity - not based on height of the container, but on the top/coordinate. View example
Example - Auto-height/No Javascript: Here is a live sample, not needing height - dealing with automatic height and no javascript.
View example
The answer of @wmantly is basicly 'the same' as I would go for at this moment.
Don't use <form>
tags at all and prevent 'inappropiate' tag nesting.
Use javascript (in this case jQuery) to do the posting of the data, mostly you will do it with javascript, because only one row had to be updated and feedback must be given without refreshing the whole page (if refreshing the whole page, it's no use to go through all these trobules to only post a single row).
I attach a click handler to a 'update' anchor at each row, that will trigger the collection and 'submit' of the fields on the same row. With an optional data-action
attribute on the anchor tag the target url of the POST can be specified.
Example html
<table>
<tbody>
<tr>
<td><input type="hidden" name="id" value="row1"/><input name="textfield" type="text" value="input1" /></td>
<td><select name="selectfield">
<option selected value="select1-option1">select1-option1</option>
<option value="select1-option2">select1-option2</option>
<option value="select1-option3">select1-option3</option>
</select></td>
<td><a class="submit" href="#" data-action="/exampleurl">Update</a></td>
</tr>
<tr>
<td><input type="hidden" name="id" value="row2"/><input name="textfield" type="text" value="input2" /></td>
<td><select name="selectfield">
<option selected value="select2-option1">select2-option1</option>
<option value="select2-option2">select2-option2</option>
<option value="select2-option3">select2-option3</option>
</select></td>
<td><a class="submit" href="#" data-action="/different-url">Update</a></td>
</tr>
<tr>
<td><input type="hidden" name="id" value="row3"/><input name="textfield" type="text" value="input3" /></td>
<td><select name="selectfield">
<option selected value="select3-option1">select3-option1</option>
<option value="select3-option2">select3-option2</option>
<option value="select3-option3">select3-option3</option>
</select></td>
<td><a class="submit" href="#">Update</a></td>
</tr>
</tbody>
</table>
Example script
$(document).ready(function(){
$(".submit").on("click", function(event){
event.preventDefault();
var url = ($(this).data("action") === "undefined" ? "/" : $(this).data("action"));
var row = $(this).parents("tr").first();
var data = row.find("input, select, radio").serialize();
$.post(url, data, function(result){ console.log(result); });
});
});
A JSFIddle
The FileInputStream
class works directly with the underlying file system. If the file in question is not physically present there, it will fail to open it. The getResourceAsStream()
method works differently. It tries to locate and load the resource using the ClassLoader
of the class it is called on. This enables it to find, for example, resources embedded into jar
files.
You use this signature: (in c#) static void Main(string[] args)
This article may help to explain the role of the main function in programming as well: http://en.wikipedia.org/wiki/Main_function_(programming)
Here is a little example for you:
class Program
{
static void Main(string[] args)
{
bool doSomething = false;
if (args.Length > 0 && args[0].Equals("doSomething"))
doSomething = true;
if (doSomething) Console.WriteLine("Commandline parameter called");
}
}
As per @lvkz comment :
if you are using datatable with uppercase d .DataTable()
( this will return a Datatable API object ) use this :
oTable.search($(this).val()).draw() ;
which is @netbrain answer.
if you are using datatable with lowercase d .dataTable()
( this will return a jquery object ) use this :
oTable.fnFilter($(this).val());
If you are reencoding in your ffmpeg command line, that may be the reason why it is CPU intensive. You need to simply copy the streams to the single container. Since I do not have your command line I cannot suggest a specific improvement here. Your acodec and vcodec should be set to copy is all I can say.
EDIT: On seeing your command line and given you have already tried it, this is for the benefit of others who come across the same question. The command:
ffmpeg -i rtsp://@192.168.241.1:62156 -acodec copy -vcodec copy c:/abc.mp4
will not do transcoding and dump the file for you in an mp4. Of course this is assuming the streamed contents are compatible with an mp4 (which in all probability they are).
Happened the same to me. It turns out that
var data = $("#myObject").data();
gives you a non-writable object. I solved it using:
var data = $.extend({}, $("#myObject").data());
And from then on, data
was a standard, writable JS object.
Check out ALL_TRIGGERS:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2107.htm#i1592586
I am using Android Studio 4 developing a Fluter/Dart application. There does not seem to be a Sync project with gradle button or file menu item, there is no clean or rebuild either.
I fixed the problem by removing the .idea folder. The suggestion included removing .gradle as well, but it did not exist.
I think it also worth to mention that in case the SSH protocol can not be used for some reason and modifying a private repository http(s) URL to provide basic authentication credentials is not an option either, there's an alternative as well.
The basic authentication header can be configured using http.extraHeader
git-config option:
git config --global --unset-all "http.https://github.com/.extraheader"
git config --global --add "http.https://github.com/.extraheader" \
"AUTHORIZATION: Basic $(base64 <<< [access-token-string]:x-oauth-basic)"
Where [access-token-string]
placeholder should be replaced (including square braces) with a generated real token value. You can read more about access tokens here and here.
If the configuration has been applied properly then the configured AUTHORIZATION
header will be included in each HTTPS request to the github.com
IP address accessed by git
command.
The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.
#include <stdio.h>
int main ()
{
printf("Hello ");
goto Cleanup;
Cleanup: ; //This is an empty statement.
char *str = "World\n";
printf("%s\n", str);
}
Depending on some details you might need to do something like this:
r=$(pwd)
case "$TARG" in
/*) p=$r;;
*) p="";;
esac
cd "$SRC" && cp -r . "$p/$TARG"
cd "$r"
... this basically changes to the SRC directory and copies it to the target, then returns back to whence ever you started.
The extra fussing is to handle relative or absolute targets.
(This doesn't rely on subtle semantics of the cp
command itself ... about how it handles source specifications with or without a trailing / ... since I'm not sure those are stable, portable, and reliable beyond just GNU cp
and I don't know if they'll continue to be so in the future).
How many thousands of users?
I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.
Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.
If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.
Edited to add details from the comment below...
If you're already thinking of multiple servers I'd take the following approach.
Use the free tools that I link
to and prove to yourself that you
can create a reasonable number of
connections onto your target OS
(beware of the Windows limits on
dynamic ports which may cause your
client connections to fail, search
for MAX_USER_PORT
).
during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html
This will not problem if we use IE browser. This is for other browsers, save file on another location and use that path.
if (FileUpload1.HasFile)
{
string fileName = FileUpload1.PostedFile.FileName;
string TempfileLocation = @"D:\uploadfiles\";
string FullPath = System.IO.Path.Combine(TempfileLocation, fileName);
FileUpload1.SaveAs(FullPath);
Response.Write(FullPath);
}
Thank you
data.userID = "10";
I totally agree with both the question and Martin's answer :). Even in Java, reading javadoc with generics is much harder than it should be due to the extra noise. This is compounded in Scala where implicit parameters are used as in the questions's example code (while the implicits do very useful collection-morphing stuff).
I don't think its a problem with the language per se - I think its more a tooling issue. And while I agree with what Jörg W Mittag says, I think looking at scaladoc (or the documentation of a type in your IDE) - it should require as little brain power as possible to grok what a method is, what it takes and returns. There shouldn't be a need to hack up a bit of algebra on a bit of paper to get it :)
For sure IDEs need a nice way to show all the methods for any variable/expression/type (which as with Martin's example can have all the generics inlined so its nice and easy to grok). I like Martin's idea of hiding the implicits by default too.
To take the example in scaladoc...
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
When looking at this in scaladoc I'd like the generic block [B, That] to be hidden by default as well as the implicit parameter (maybe they show if you hover a little icon with the mouse) - as its extra stuff to grok reading it which usually isn't that relevant. e.g. imagine if this looked like...
def map(f: A => B): That
nice and clear and obvious what it does. You might wonder what 'That' is, if you mouse over or click it it could expand the [B, That] text highlighting the 'That' for example.
Maybe a little icon could be used for the [] declaration and (implicit...) block so its clear there are little bits of the statement collapsed? Its hard to use a token for it, but I'll use a . for now...
def map.(f: A => B).: That
So by default the 'noise' of the type system is hidden from the main 80% of what folks need to look at - the method name, its parameter types and its return type in nice simple concise way - with little expandable links to the detail if you really care that much.
Mostly folks are reading scaladoc to find out what methods they can call on a type and what parameters they can pass. We're kinda overloading users with way too much detail right how IMHO.
Here's another example...
def orElse[A1 <: A, B1 >: B](that: PartialFunction[A1, B1]): PartialFunction[A1, B1]
Now if we hid the generics declaration its easier to read
def orElse(that: PartialFunction[A1, B1]): PartialFunction[A1, B1]
Then if folks hover over, say, A1 we could show the declaration of A1 being A1 <: A. Covariant and contravariant types in generics add lots of noise too which can be rendered in a much easier to grok way to users I think.
In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.
Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.
This does not work any more - as an exercise, see if you can replace it with the Github API:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: 'callback',
});
});
function photos (data) {
alert(data);
console.log(data);
};
although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing
alert(JSON.stringify(data));
You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery (cross-domain) JSONP Twitter example</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('https://api.github.com/gists?callback=?', function(response){
$.each(response.data, function(i, gist){
$('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" +
(gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
});
});
});
</script>
</head>
<body>
<ul id="gists"></ul>
</body>
</html>
To pass arguments to the jar:
java -jar myjar.jar one two
You can access them in the main() method of "Main-Class" (mentioned in the manifest.mf
file of a JAR).
String one = args[0];
String two = args[1];
The solution of @JarekTkaczyk it is exactly what I was looking for. The only thing I miss is how to do it when you are using
DB::table()
queries. In this case, this is how I do it:
$other = DB::table( DB::raw("({$sub->toSql()}) as sub") )->select(
'something',
DB::raw('sum( qty ) as qty'),
'foo',
'bar'
);
$other->mergeBindings( $sub );
$other->groupBy('something');
$other->groupBy('foo');
$other->groupBy('bar');
print $other->toSql();
$other->get();
Special atention how to make the mergeBindings
without using the getQuery()
method
You can use java split function to split the filename from the extension, if you are sure there is only one dot in the filename which for extension.
File filename = new File('test.txt');
File.getName().split("[.]");
so the split[0]
will return "test" and split[1] will return "txt"
The default value of any Object
, such as Boolean
, is null
.
The default value for a boolean
is false.
Note: Every primitive has a wrapper class. Every wrapper uses a reference which has a default of null
. Primitives have different default values:
boolean -> false
byte, char, short, int, long -> 0
float, double -> 0.0
Note (2): void
has a wrapper Void
which also has a default of null
and is it's only possible value (without using hacks).
As inspiredlife explained, you can figure out whats happening using mail
command.
If you don't want to delete bunch of unrelated / auto-generated messages one by one (like me), simply run the command below to get rid of all messages:
echo -n > /var/mail/yourusername
Reverse one of the strings. Take the FFT of both (treating them as simple sequences of integers). Multiply the results together point-wise. Transform back using inverse FFT. The result will have a single peak if the strings are rotations of each other -- the position of the peak will indicate by how much they are rotated with respect to each other.
As of React Native 0.36, calling focus()
(as suggested in several other answers) on a text input node isn't supported any more. Instead, you can use the TextInputState
module from React Native. I created the following helper module to make this easier:
// TextInputManager
//
// Provides helper functions for managing the focus state of text
// inputs. This is a hack! You are supposed to be able to call
// "focus()" directly on TextInput nodes, but that doesn't seem
// to be working as of ReactNative 0.36
//
import { findNodeHandle } from 'react-native'
import TextInputState from 'react-native/lib/TextInputState'
export function focusTextInput(node) {
try {
TextInputState.focusTextInput(findNodeHandle(node))
} catch(e) {
console.log("Couldn't focus text input: ", e.message)
}
}
You can, then, call the focusTextInput
function on any "ref" of a TextInput
. For example:
...
<TextInput onSubmit={() => focusTextInput(this.refs.inputB)} />
<TextInput ref="inputB" />
...
See the Locale.getLanguage()
, Locale.getCountry()
... Store this combination in the database instead of the "programatic name"
...
When you want to build the Locale back, use public Locale(String language, String country)
Here is a sample code :)
// May contain simple syntax error, I don't have java right now to test..
// but this is a bigger picture for your algo...
public String localeToString(Locale l) {
return l.getLanguage() + "," + l.getCountry();
}
public Locale stringToLocale(String s) {
StringTokenizer tempStringTokenizer = new StringTokenizer(s,",");
if(tempStringTokenizer.hasMoreTokens())
String l = tempStringTokenizer.nextElement();
if(tempStringTokenizer.hasMoreTokens())
String c = tempStringTokenizer.nextElement();
return new Locale(l,c);
}
I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.
scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop
The username@remotecomputer
is the same string you used with ssh initially.
I've got the silimar problem. The solution was to migrate db (manage.py syncdb
or manage.py schemamigration --auto <table name>
if you use south).
using(var client = new System.Net.WebClient()) {
client.UploadData(address,"PUT",data);
}
My own experience has been that it's best to stick to one of two kinds of assembly references:
I've found (much like you've described) other methods to either be too easily broken or have annoying maintenance requirements.
Any assembly I don't want to GAC, has to live in the execution directory. Any assembly that isn't or can't be in the execution directory I GAC (managed by automatic build events).
This hasn't given me any problems so far. While I'm sure there's a situation where it won't work, the usual answer to any problem has been "oh, just GAC it!". 8 D
Hope that helps!
This will get just the revision number of the last changed revision:
<?php
$REV="";
$repo = ""; #url or directory
$REV = svn info $repo --show-item last-changed-revision;
?>
I hope this helps.
Slightly modified answer of @Ty Le:
no changes in files were required for me - I had a branch named 'Feature/...' and while pushing upstream I changed the title to 'feature/...' (the case of the first letter was changed to the lower one).
main() {
double a;
a=3669.0;
int b;
b=a;
printf("b is %d",b);
}
output is :b is 3669
when you write b=a; then its automatically converted in int
see on-line compiler result :
This is called Implicit Type Conversion Read more here https://www.geeksforgeeks.org/implicit-type-conversion-in-c-with-examples/
If you have installed WAMP on your machine, please make sure that it is running. Do not EXIT the WAMP from tray menu since it will stop the MySQL Server.
Ctrl + Enter
%matplotlib inline
Magic Line :D
See: Plotting with Matplotlib.
$(document).height:
if your device height
was bigger. Your page has Not any scroll;
$(document).height:
assume you have not scroll and return this height
;
$(window).height:
return your page height
on your device.
If your classes are in the same package, you won't need to import. To call a method from class B in class A, you should use classB.methodName(arg)
I found one way to access the shared folder without giving the username and password.
We need to change the share folder protect settings in the machine where the folder has been shared.
Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.
By doing the above settings we can access the shared folder without any username/password.
Depending on your needs, here are a couple of ways:
IF EXISTS (SELECT * FROM TABLE WHERE COLUMN = 'SOME VALUE')
--INSERT SOMETHING
ELSE
--INSERT SOMETHING ELSE
Or a bit longer
DECLARE @retVal int
SELECT @retVal = COUNT(*)
FROM TABLE
WHERE COLUMN = 'Some Value'
IF (@retVal > 0)
BEGIN
--INSERT SOMETHING
END
ELSE
BEGIN
--INSERT SOMETHING ELSE
END
It boils down to:
Class<? extends Serializable> c1 = null;
Class<java.util.Date> d1 = null;
c1 = d1; // compiles
d1 = c1; // wont compile - would require cast to Date
You can see the Class reference c1 could contain a Long instance (since the underlying object at a given time could have been List<Long>
), but obviously cannot be cast to a Date since there is no guarantee that the "unknown" class was Date. It is not typsesafe, so the compiler disallows it.
However, if we introduce some other object, say List (in your example this object is Matcher), then the following becomes true:
List<Class<? extends Serializable>> l1 = null;
List<Class<java.util.Date>> l2 = null;
l1 = l2; // wont compile
l2 = l1; // wont compile
...However, if the type of the List becomes ? extends T instead of T....
List<? extends Class<? extends Serializable>> l1 = null;
List<? extends Class<java.util.Date>> l2 = null;
l1 = l2; // compiles
l2 = l1; // won't compile
I think by changing Matcher<T> to Matcher<? extends T>
, you are basically introducing the scenario similar to assigning l1 = l2;
It's still very confusing having nested wildcards, but hopefully that makes sense as to why it helps to understand generics by looking at how you can assign generic references to each other. It's also further confusing since the compiler is inferring the type of T when you make the function call (you are not explicitly telling it was T is).
Since the expiration time is zero (the third argument, the first false
) the cookie is a session cookie, which will expire when the current session ends. (See the setcookie
reference).
Therefore it doesn't need to be saved.
I configured the app.config
with the tool for EntLib configuration and set up my LoggingConfiguration
block. Then I copied this into the DotNetConfig.xsd
. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.
<xs:element name="loggingConfiguration">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:attribute name="fileName" type="xs:string" use="required" />
<xs:attribute name="footer" type="xs:string" use="required" />
<xs:attribute name="formatter" type="xs:string" use="required" />
<xs:attribute name="header" type="xs:string" use="required" />
<xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
<xs:attribute name="rollInterval" type="xs:string" use="required" />
<xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
<xs:attribute name="timeStampPattern" type="xs:string" use="required" />
<xs:attribute name="listenerDataType" type="xs:string" use="required" />
<xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
<xs:attribute name="filter" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="formatters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="template" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="logFilters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="enabled" type="xs:boolean" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="categorySources">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="specialSources">
<xs:complexType>
<xs:sequence>
<xs:element name="allEvents">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="notProcessed">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="errors">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
<xs:attribute name="defaultCategory" type="xs:string" use="required" />
<xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
</xs:complexType>
</xs:element>
In a terminal put these:
cd C:\Program Files (x86)\Google\Chrome\Application
chrome.exe --disable-web-security --user-data-dir="c:/chromedev"
First you need to think off when you want to swap. For example you could switch everytime when its a div tag thats loaded. In my example i just used a extra data field "background" and whenever its set the image is applied as a background image.
Then you just have to load the Data with the created image tag. And not overwrite the img tag instead apply a css background image.
Here is a example of the code change:
if (settings.appear) {
var elements_left = elements.length;
settings.appear.call(self, elements_left, settings);
}
var loadImgUri;
if($self.data("background"))
loadImgUri = $self.data("background");
else
loadImgUri = $self.data(settings.data_attribute);
$("<img />")
.bind("load", function() {
$self
.hide();
if($self.data("background")){
$self.css('backgroundImage', 'url('+$self.data("background")+')');
}else
$self.attr("src", $self.data(settings.data_attribute))
$self[settings.effect](settings.effect_speed);
self.loaded = true;
/* Remove image from array so it is not looped next time. */
var temp = $.grep(elements, function(element) {
return !element.loaded;
});
elements = $(temp);
if (settings.load) {
var elements_left = elements.length;
settings.load.call(self, elements_left, settings);
}
})
.attr("src", loadImgUri );
}
the loading stays the same
$("#divToLoad").lazyload();
and in this example you need to modify the html code like this:
<div data-background="http://apod.nasa.gov/apod/image/9712/orionfull_jcc_big.jpg" id="divToLoad" />?
but it would also work if you change the switch to div tags and then you you could work with the "data-original" attribute.
Here's an fiddle example: http://jsfiddle.net/dtm3k/1/
While I agree with others that direct use of an iterable container is a preferred solution, I want to point out that the C++ standard guarantees enough support for a do-it-yourself solution in case you want it for whatever reason.
Namely, you can inherit from std::queue
and use its protected member Container c;
to access begin() and end() of the underlying container (provided that such methods exist there). Here is an example that works in VS 2010 and tested with ideone:
#include <queue>
#include <deque>
#include <iostream>
template<typename T, typename Container=std::deque<T> >
class iterable_queue : public std::queue<T,Container>
{
public:
typedef typename Container::iterator iterator;
typedef typename Container::const_iterator const_iterator;
iterator begin() { return this->c.begin(); }
iterator end() { return this->c.end(); }
const_iterator begin() const { return this->c.begin(); }
const_iterator end() const { return this->c.end(); }
};
int main() {
iterable_queue<int> int_queue;
for(int i=0; i<10; ++i)
int_queue.push(i);
for(auto it=int_queue.begin(); it!=int_queue.end();++it)
std::cout << *it << "\n";
return 0;
}
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
li = listView1.GetItemAt(e.X, e.Y);
X = e.X;
Y = e.Y;
}
private void listView1_MouseUp(object sender, MouseEventArgs e)
{
int nStart = X;
int spos = 0;
int epos = listView1.Columns[1].Width;
for (int i = 0; i < listView1.Columns.Count; i++)
{
if (nStart > spos && nStart < epos)
{
subItemSelected = i;
break;
}
spos = epos;
epos += listView1.Columns[i].Width;
}
li.SubItems[subItemSelected].Text = "9";
}
I have solved this if you are using array called for 2 tables. Example you have,
$tableA['yellow']
and $tableA['blue']
. You are getting these 2 values and you want to add another element inside them to separate them by their type
.
foreach ($tableA['yellow'] as $value) {
$value->type = 'YELLOW'; //you are adding new element named 'type'
}
foreach ($tableA['blue'] as $value) {
$value->type = 'BLUE'; //you are adding new element named 'type'
}
So, both of the tables value will have new element called type
.
Uninstall the python program using the windows GUI.
Delete the containing folder e.g if it was stored in C:\python36\
make sure to delete that folder
@Chap - you can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:
var data = [
{ "restaurant": { "name": "McDonald's", "food": "burger" } },
{ "restaurant": { "name": "KFC", "food": "chicken" } },
{ "restaurant": { "name": "Pizza Hut", "food": "pizza" } }
].
res = JSON.search( data, '//*[food="pizza"]' );
console.log( res[0].name );
// Pizza Hut
DefiantJS extends the global object with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:
nohup some_command &> nohup2.out &
and voila.
Older syntax for Bash version < 4:
nohup some_command > nohup2.out 2>&1 &
Delegation is a technique where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object. This sounds at first very similar to the proxy pattern, but it serves a much different purpose. Delegation is an abstraction mechanism which centralizes object (method) behavior.
Generally spoken: use delegation as alternative to inheritance. Inheritance is a good strategy, when a close relationship exist in between parent and child object, however, inheritance couples objects very closely. Often, delegation is the more flexible way to express a relationship between classes.
This pattern is also known as "proxy chains". Several other design patterns use delegation - the State, Strategy and Visitor Patterns depend on it.
Here is sample c# code that are sending 2 parameters to a bat/cmd file for answer this question.
Comment: how can I pass parameters and read a result of command execution?
Option 1 : Without hiding the console window, passing arguments and without getting the outputs
using System;
using System.Diagnostics;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Process.Start(@"c:\batchfilename.bat", "\"1st\" \"2nd\"");
}
}
}
Option 2 : Hiding the console window, passing arguments and taking outputs
using System;
using System.Diagnostics;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var process = new Process();
var startinfo = new ProcessStartInfo(@"c:\batchfilename.bat", "\"1st_arg\" \"2nd_arg\" \"3rd_arg\"");
startinfo.RedirectStandardOutput = true;
startinfo.UseShellExecute = false;
process.StartInfo = startinfo;
process.OutputDataReceived += (sender, argsx) => Console.WriteLine(argsx.Data); // do whatever processing you need to do in this handler
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
}
}
}
I think in Postgres you can play with formats for example if you want dd/mm/yyyy
TO_CHAR(submit_time, 'DD/MM/YYYY') as submit_date
here $key will contain the $key associated with $value in $featured. The difference is that now you have that key.
array("thekey"=>array("name"=>"joe"))
here $value is
array("name"=>"joe")
$key is "thekey"
The main point of the differences as pointed out @BizApps is that Load event happens right after the ViewState is populated while PreRender event happens later, right before Rendering phase, and after all individual children controls' action event handlers are already executing. Therefore, any modifications done by the controls' actions event handler should be updated in the control hierarchy during PreRender as it happens after.
To match regexes you need to use the =~
operator.
Try this:
[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
Alternatively, you can use wildcards (instead of regexes) with the ==
operator:
[[ sed-4.2.2.tar.bz2 == *tar.bz2 ]] && echo matched
If portability is not a concern, I recommend using [[
instead of [
or test
as it is safer and more powerful. See What is the difference between test, [ and [[ ? for details.
I found one way to supply credentials for a https connection on the command line. You just need to specify the complete URL to git pull and include the credentials there:
git pull https://username:[email protected]/my/repository
You do not need to have the repository cloned with the credentials before, this means your credentials don't end up in .git/config
. (But make sure your shell doesn't betray you and stores the command line in a history file.)
For the chosen answer version in Swift 3:
var isLoadingTableView = true
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if tableData.count > 0 && isLoadingTableView {
if let indexPathsForVisibleRows = tableView.indexPathsForVisibleRows, let lastIndexPath = indexPathsForVisibleRows.last, lastIndexPath.row == indexPath.row {
isLoadingTableView = false
//do something after table is done loading
}
}
}
I needed the isLoadingTableView variable because I wanted to make sure the table is done loading before I make a default cell selection. If you don't include this then every time you scroll the table it will invoke your code again.
Windows Server 2003 and later (i.e. anything after Windows XP 32 bit) provide the where.exe
program which does some of what which
does, though it matches all types of files, not just executable commands. (It does not match built-in shell commands like cd
.) It will even accept wildcards, so where nt*
finds all files in your %PATH%
and current directory whose names start with nt
.
Try where /?
for help.
Note that Windows PowerShell defines where
as an alias for the Where-Object
cmdlet, so if you want where.exe
, you need to type the full name instead of omitting the .exe
extension.
To figure out what is the difference between before_action and before_filter, we should understand the difference between action and filter.
An action is a method of a controller to which you can route to. For example, your user creation page might be routed to UsersController#new - new is the action in this route.
Filters run in respect to controller actions - before, after or around them. These methods can halt the action processing by redirecting or set up common data to every action in the controller.
Rails 4 –> _action
Rails 3 –> _filter
This should work:
SELECT *
INTO DestinationDB..MyDestinationTable
FROM SourceDB..MySourceTable
It will not copy constraints, defaults or indexes. The table created will not have a clustered index.
Alternatively you could:
INSERT INTO DestinationDB..MyDestinationTable
SELECT * FROM SourceDB..MySourceTable
If your destination table exists and is empty.
Yes, O3 is buggier. I'm a compiler developer and I've identified clear and obvious gcc bugs caused by O3 generating buggy SIMD assembly instructions when building my own software. From what I've seen, most production software ships with O2 which means O3 will get less attention wrt testing and bug fixes.
Think of it this way: O3 adds more transformations on top of O2, which adds more transformations on top of O1. Statistically speaking, more transformations means more bugs. That's true for any compiler.
You can use an anonymous function to pass the matches to your function:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
I do it for beamer presentations,
provide tmp-0.png through tmp-34.png
\usepackage{animate}
\begin{frame}{Torque Generating Mechanism}
\animategraphics[loop,controls,width=\linewidth]{12}{output/tmp-}{0}{34}
\end{frame}
Use : GCM Network Manager
Run this to start a periodic task that will be ran even after re-boot:
PeriodicTask task = new PeriodicTask.Builder()
.setService(MyLocationService.class)
.setTag("periodic")
.setPeriod(30L)
.setPersisted(true)
.build();
mGcmNetworkManager.schedule(task);
then in onRunTask() get current location and use it (in this example, event is submitted at the end to let UI know that location was found):
public void getLastKnownLocation() {
Location lastKnownGPSLocation;
Location lastKnownNetworkLocation;
String gpsLocationProvider = LocationManager.GPS_PROVIDER;
String networkLocationProvider = LocationManager.NETWORK_PROVIDER;
try {
locationManager = (LocationManager) App.get().getSystemService(Context.LOCATION_SERVICE);
lastKnownNetworkLocation = locationManager.getLastKnownLocation(networkLocationProvider);
lastKnownGPSLocation = locationManager.getLastKnownLocation(gpsLocationProvider);
if (lastKnownGPSLocation != null) {
Log.i(TAG, "lastKnownGPSLocation is used.");
this.mCurrentLocation = lastKnownGPSLocation;
} else if (lastKnownNetworkLocation != null) {
Log.i(TAG, "lastKnownNetworkLocation is used.");
this.mCurrentLocation = lastKnownNetworkLocation;
} else {
Log.e(TAG, "lastLocation is not known.");
return;
}
LocationChangedEvent event = new LocationChangedEvent();
event.setLocation(mCurrentLocation);
EventHelper.publishEvent(event);
} catch (SecurityException sex) {
Log.e(TAG, "Location permission is not granted!");
}
return;
}
The MyLocationService in whole:
public class MyLocationService extends GcmTaskService {
private static final String TAG = MyLocationService.class.getSimpleName();
private LocationManager locationManager;
private Location mCurrentLocation;
public static final String TASK_GET_LOCATION_ONCE="location_oneoff_task";
public static final String TASK_GET_LOCATION_PERIODIC="location_periodic_task";
private static final int RC_PLAY_SERVICES = 123;
@Override
public void onInitializeTasks() {
// When your package is removed or updated, all of its network tasks are cleared by
// the GcmNetworkManager. You can override this method to reschedule them in the case of
// an updated package. This is not called when your application is first installed.
//
// This is called on your application's main thread.
startPeriodicLocationTask(TASK_GET_LOCATION_PERIODIC,
30L, null);
}
@Override
public int onRunTask(TaskParams taskParams) {
Log.d(TAG, "onRunTask: " + taskParams.getTag());
String tag = taskParams.getTag();
Bundle extras = taskParams.getExtras();
// Default result is success.
int result = GcmNetworkManager.RESULT_SUCCESS;
switch (tag) {
case TASK_GET_LOCATION_ONCE:
getLastKnownLocation();
break;
case TASK_GET_LOCATION_PERIODIC:
getLastKnownLocation();
break;
}
return result;
}
public void getLastKnownLocation() {
Location lastKnownGPSLocation;
Location lastKnownNetworkLocation;
String gpsLocationProvider = LocationManager.GPS_PROVIDER;
String networkLocationProvider = LocationManager.NETWORK_PROVIDER;
try {
locationManager = (LocationManager) App.get().getSystemService(Context.LOCATION_SERVICE);
lastKnownNetworkLocation = locationManager.getLastKnownLocation(networkLocationProvider);
lastKnownGPSLocation = locationManager.getLastKnownLocation(gpsLocationProvider);
if (lastKnownGPSLocation != null) {
Log.i(TAG, "lastKnownGPSLocation is used.");
this.mCurrentLocation = lastKnownGPSLocation;
} else if (lastKnownNetworkLocation != null) {
Log.i(TAG, "lastKnownNetworkLocation is used.");
this.mCurrentLocation = lastKnownNetworkLocation;
} else {
Log.e(TAG, "lastLocation is not known.");
return;
}
LocationChangedEvent event = new LocationChangedEvent();
event.setLocation(mCurrentLocation);
EventHelper.publishEvent(event);
} catch (SecurityException sex) {
Log.e(TAG, "Location permission is not granted!");
}
return;
}
public static void startOneOffLocationTask(String tag, Bundle extras) {
Log.d(TAG, "startOneOffLocationTask");
GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(App.get());
OneoffTask.Builder taskBuilder = new OneoffTask.Builder()
.setService(MyLocationService.class)
.setTag(tag);
if (extras != null) taskBuilder.setExtras(extras);
OneoffTask task = taskBuilder.build();
mGcmNetworkManager.schedule(task);
}
public static void startPeriodicLocationTask(String tag, Long period, Bundle extras) {
Log.d(TAG, "startPeriodicLocationTask");
GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(App.get());
PeriodicTask.Builder taskBuilder = new PeriodicTask.Builder()
.setService(MyLocationService.class)
.setTag(tag)
.setPeriod(period)
.setPersisted(true)
.setRequiredNetwork(Task.NETWORK_STATE_CONNECTED);
if (extras != null) taskBuilder.setExtras(extras);
PeriodicTask task = taskBuilder.build();
mGcmNetworkManager.schedule(task);
}
public static boolean checkPlayServicesAvailable(Activity activity) {
GoogleApiAvailability availability = GoogleApiAvailability.getInstance();
int resultCode = availability.isGooglePlayServicesAvailable(App.get());
if (resultCode != ConnectionResult.SUCCESS) {
if (availability.isUserResolvableError(resultCode)) {
// Show dialog to resolve the error.
availability.getErrorDialog(activity, resultCode, RC_PLAY_SERVICES).show();
}
return false;
} else {
return true;
}
}
Also add these 2 to the AndroidManifest.xml:
<manifest...
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application...
<service
android:name=".api.location.MyLocationService"
android:exported="true"
android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
<intent-filter>
<action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
</intent-filter>
</service>
Multiple Cookies,Multiple Claims
public class ClaimsCookie
{
private readonly ClaimsPrincipal _user;
private readonly HttpContext _httpContext;
public ClaimsCookie(ClaimsPrincipal user, HttpContext httpContext = null)
{
_user = user;
_httpContext = httpContext;
}
public string GetValue(CookieName cookieName, KeyName keyName)
{
var principal = _user as ClaimsPrincipal;
var cp = principal.Identities.First(i => i.AuthenticationType == ((CookieName)cookieName).ToString());
return cp.FindFirst(((KeyName)keyName).ToString()).Value;
}
public async void SetValue(CookieName cookieName, KeyName[] keyName, string[] value)
{
if (keyName.Length != value.Length)
{
return;
}
var principal = _user as ClaimsPrincipal;
var cp = principal.Identities.First(i => i.AuthenticationType == ((CookieName)cookieName).ToString());
for (int i = 0; i < keyName.Length; i++)
{
if (cp.FindFirst(((KeyName)keyName[i]).ToString()) != null)
{
cp.RemoveClaim(cp.FindFirst(((KeyName)keyName[i]).ToString()));
cp.AddClaim(new Claim(((KeyName)keyName[i]).ToString(), value[i]));
}
}
await _httpContext.SignOutAsync(CookieName.UserProfilCookie.ToString());
await _httpContext.SignInAsync(CookieName.UserProfilCookie.ToString(), new ClaimsPrincipal(cp),
new AuthenticationProperties
{
IsPersistent = bool.Parse(cp.FindFirst(KeyName.IsPersistent.ToString()).Value),
AllowRefresh = true
});
}
public enum CookieName
{
CompanyUserProfilCookie = 0, UserProfilCookie = 1, AdminPanelCookie = 2
}
public enum KeyName
{
Id, Name, Surname, Image, IsPersistent
}
}
This is a self-promotional answer, but I spent a few months researching this and presented the results at jQuery Conference San Francisco 2012.
Here is a free video of the talk:
Actually, I cannot get selected date in aspx. Here is the way to set selected date in codes:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DateTime dt = DateTime.Now.AddDays(-1);
Calendar1.VisibleDate = dt;
Calendar1.SelectedDate = dt;
Calendar1.TodaysDate = dt;
...
}
}
In above example, I need to set the default selected date to yesterday. The key point is to set TodayDate. Otherwise, the selected calendar date is always today.
function helloWorld(name, symbol = '!!!') {
name = name || 'worlds';
console.log('hello ' + name + symbol);
}
helloWorld(); // hello worlds!!!
helloWorld('john'); // hello john!!!
helloWorld('john', '(>.<)'); // hello john(>.<)
helloWorld('john', undefined); // hello john!!!
helloWorld(undefined, undefined); // hello worlds!!!
If you just want the last date for each account, you'd use this:
var q = from n in table
group n by n.AccountId into g
select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};
If you want the whole record:
var q = from n in table
group n by n.AccountId into g
select g.OrderByDescending(t=>t.Date).FirstOrDefault();
Your code is correct. Just put them inside the <VirtualHost *:443>
Example:
<VirtualHost *:443>
SSLEnable
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>
A property, when it has no definition, is undefined. null is an object. It's type is null. undefined is not an object, its type is undefined.
This is a good article explaining the difference and also giving some examples.
First you must test the query list size; here a example:
long count;
if (query.list().size() > 0)
count=(long) criteria.list().get(0);
else
count=0;
return count;
Deleting derived data saved it for me
There is no difference between the two, one is just a shorthand for the second.
The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.
<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>
Source: official documentation.
in build.gradle add Guava
compile group: 'com.google.guava', name: 'guava', version: '27.0-jre'
and then
public static List<String> splitByComma(String str) {
Iterable<String> split = Splitter.on(",")
.omitEmptyStrings()
.trimResults()
.split(str);
return Lists.newArrayList(split);
}
public static String joinWithComma(Set<String> words) {
return Joiner.on(", ").skipNulls().join(words);
}
enjoy :)
It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en
You use a ResultTransformer like that:
public List<Foo> activeObjects() {
Session s = acquireSession();
Query q = s.createQuery("from foo where active");
q.setResultTransformer(Transformers.aliasToBean(Foo.class));
return (List<Foo>) q.list();
}
Using to_char:
select to_char(sysdate, 'YYYY') from dual;
In your example you can use something like:
BETWEEN trunc(sysdate, 'YEAR')
AND add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60;
The comparison values are exactly what you request:
select trunc(sysdate, 'YEAR') begin_year
, add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60 last_second_year
from dual;
BEGIN_YEAR LAST_SECOND_YEAR
----------- ----------------
01/01/2009 31/12/2009
Here is how you would do it with Apache HttpClient (this solution is for those who don't mind using a 3rd party library):
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("file", new FileBody(file))
.build();
HttpPost request = new HttpPost(url);
request.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
It seems all of these answers here just assume you can get that little string out of a bigger object... for people looking to simply deserealize a large object with such a dictionary somewhere inside the mapping, and who are using the System.Runtime.Serialization.Json
DataContract system, here's a solution:
An answer on gis.stackexchange.com had this interesting link. I had to recover it with archive.org, but it offers a pretty much perfect solution: a custom IDataContractSurrogate
class in which you implement exactly your own types. I was able to expand it easily.
I made a bunch of changes in it, though. Since the original source is no longer available, I'll post the entire class here:
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
namespace JsonTools
{
/// <summary>
/// Allows using Dictionary<String,String> and Dictionary<String,Boolean> types, and any others you'd like to add.
/// Source: https://web.archive.org/web/20100317222656/my6solutions.com/post/2009/06/30/DataContractSerializer-DataContractJsonSerializer-JavaScriptSerializer-XmlSerializer-for-serialization.aspx
/// </summary>
public class JsonSurrogate : IDataContractSurrogate
{
/// <summary>
/// Deserialize an object with added support for the types defined in this class.
/// </summary>
/// <typeparam name="T">Contract class</typeparam>
/// <param name="json">JSON String</param>
/// <param name="encoding">Text encoding</param>
/// <returns>The deserialized object of type T</returns>
public static T Deserialize<T>(String json, Encoding encoding)
{
if (encoding == null)
encoding = new UTF8Encoding(false);
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(
typeof(T), new Type[0], int.MaxValue, true, new JsonSurrogate(), false);
using (MemoryStream stream = new MemoryStream(encoding.GetBytes(json)))
{
T result = (T)deserializer.ReadObject(stream);
return result;
}
}
// make sure all values in this are classes implementing JsonSurrogateObject.
private static Dictionary<Type, Type> KnownTypes =
new Dictionary<Type, Type>()
{
{typeof(Dictionary<String, String>), typeof(SSDictionary)},
{typeof(Dictionary<String, Boolean>), typeof(SBDictionary)}
};
#region Implemented surrogate dictionary classes
[Serializable]
public class SSDictionary : SurrogateDictionary<String>
{
public SSDictionary() : base() {}
protected SSDictionary (SerializationInfo info, StreamingContext context) : base(info, context) {}
}
[Serializable]
public class SBDictionary : SurrogateDictionary<Boolean>
{
public SBDictionary() : base() {}
protected SBDictionary (SerializationInfo info, StreamingContext context) : base(info, context) {}
}
#endregion
/// <summary>Small interface to easily extract the final value from the object.</summary>
public interface JsonSurrogateObject
{
Object DeserializedObject { get; }
}
/// <summary>
/// Class for deserializing any simple dictionary types with a string as key.
/// </summary>
/// <typeparam name="T">Any simple type that will be deserialized correctly.</typeparam>
[Serializable]
public abstract class SurrogateDictionary<T> : ISerializable, JsonSurrogateObject
{
public Object DeserializedObject { get { return dict; } }
private Dictionary<String, T> dict;
public SurrogateDictionary()
{
dict = new Dictionary<String, T>();
}
// deserialize
protected SurrogateDictionary(SerializationInfo info, StreamingContext context)
{
dict = new Dictionary<String, T>();
foreach (SerializationEntry entry in info)
{
// This cast will only work for base types, of course.
dict.Add(entry.Name, (T)entry.Value);
}
}
// serialize
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (String key in dict.Keys)
{
info.AddValue(key, dict[key]);
}
}
}
/// <summary>
/// Uses the KnownTypes dictionary to get the surrogate classes.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Type GetDataContractType(Type type)
{
Type returnType;
if (KnownTypes.TryGetValue(type, out returnType))
{
return returnType;
}
return type;
}
public object GetObjectToSerialize(object obj, Type targetType)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the object out of the surrogate datacontract object. This function is the reason all surrogate objects need to implement the JsonSurrogateObject class.
/// </summary>
/// <param name="obj">Result of the deserialization</param>
/// <param name="targetType">Expected target type of the deserialization</param>
/// <returns></returns>
public object GetDeserializedObject(object obj, Type targetType)
{
if (obj is JsonSurrogateObject)
{
return ((JsonSurrogateObject)obj).DeserializedObject;
}
return obj;
}
public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
{
return null;
}
#region not implemented
public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
{
throw new NotImplementedException();
}
public object GetCustomDataToExport(Type clrType, Type dataContractType)
{
throw new NotImplementedException();
}
public void GetKnownCustomDataTypes(Collection<Type> customDataTypes)
{
throw new NotImplementedException();
}
public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit)
{
throw new NotImplementedException();
}
#endregion
}
}
To add new supported types to the class, you just need to add your class, give it the right constructors and functions (look at SurrogateDictionary
for an example), make sure it inherits JsonSurrogateObject
, and add its type mapping to the KnownTypes
dictionary. The included SurrogateDictionary can serve as basis for any Dictionary<String,T>
types where T is any type that does deserialize correctly.
Calling it is really simple:
MyObjtype newObj = JsonSurrogate.Deserialize<MyObjtype>(jsonStr, encoding);
Note that for some reason this thing has trouble using key strings which contain spaces; they were simply not present in the final list. Might just be it's simply against json specs and the api I was calling was poorly implemented, mind you; I dunno. Anyway, I solved this by regex-replacing them with underscores in the raw json data and fixing the dictionary after the deserialization.
Just an update regarding this issue.
Require Drivers:
Linux: Centos 7 64bit, Window 7 64bit
Firefox: 52.0.3
Selenium Webdriver: 3.4.0 (Windows), 3.8.1 (Linux Centos)
GeckoDriver: v0.16.0 (Windows), v0.17.0 (Linux Centos)
Code
System.setProperty("webdriver.gecko.driver", "/home/seleniumproject/geckodrivers/linux/v0.17/geckodriver");
ProfilesIni ini = new ProfilesIni();
// Change the profile name to your own. The profile name can
// be found under .mozilla folder ~/.mozilla/firefox/profile.
// See you profile.ini for the default profile name
FirefoxProfile profile = ini.getProfile("default");
DesiredCapabilities cap = new DesiredCapabilities();
cap.setAcceptInsecureCerts(true);
FirefoxBinary firefoxBinary = new FirefoxBinary();
GeckoDriverService service =new GeckoDriverService.Builder(firefoxBinary)
.usingDriverExecutable(new
File("/home/seleniumproject/geckodrivers/linux/v0.17/geckodriver"))
.usingAnyFreePort()
.usingAnyFreePort()
.build();
try {
service.start();
} catch (IOException e) {
e.printStackTrace();
}
FirefoxOptions options = new FirefoxOptions().setBinary(firefoxBinary).setProfile(profile).addCapabilities(cap);
driver = new FirefoxDriver(options);
driver.get("https://www.google.com");
System.out.println("Life Title -> " + driver.getTitle());
driver.close();
I am posting a complete example which I finally got working. Here I am reading in a file rooms/rooms.txt
from a script rooms/rooms.js
var fs = require('fs');
var path = require('path');
var readStream = fs.createReadStream(path.join(__dirname, '../rooms') + '/rooms.txt', 'utf8');
let data = ''
readStream.on('data', function(chunk) {
data += chunk;
}).on('end', function() {
console.log(data);
});
If you simply open the file for writing with the truncate-option, you'll delete the content.
std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();
If you'd like to use base graphics, you may have a look at this. An extract:
You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.
Don't do it, if you can avoid it. As Devon Sans points out in the comments: This feature will most likely be deprecated.
#Update - Newer Way
From Angular 4.3.0, all piercing css combinators were deprecated. Angular team introduced a new combinator ::ng-deep
(still it is experimental and not the full and final way) as shown below,
DEMO : https://plnkr.co/edit/RBJIszu14o4svHLQt563?p=preview
styles: [
`
:host { color: red; }
:host ::ng-deep parent {
color:blue;
}
:host ::ng-deep child{
color:orange;
}
:host ::ng-deep child.class1 {
color:yellow;
}
:host ::ng-deep child.class2{
color:pink;
}
`
],
template: `
Angular2 //red
<parent> //blue
<child></child> //orange
<child class="class1"></child> //yellow
<child class="class2"></child> //pink
</parent>
`
You can use encapsulation mode
and/or piercing CSS combinators >>>, /deep/ and ::shadow
working example : http://plnkr.co/edit/1RBDGQ?p=preview
styles: [
`
:host { color: red; }
:host >>> parent {
color:blue;
}
:host >>> child{
color:orange;
}
:host >>> child.class1 {
color:yellow;
}
:host >>> child.class2{
color:pink;
}
`
],
template: `
Angular2 //red
<parent> //blue
<child></child> //orange
<child class="class1"></child> //yellow
<child class="class2"></child> //pink
</parent>
`
GitHub have changed their recommendation several times (example).
It appears that they currently recommend HTTPS because it is the easiest to set up on the widest range of networks and platforms, and by users who are new to all this.
There is no inherent flaw in SSH (if there was they would disable it) -- in the links below, you will see that they still provide details about SSH connections too:
HTTPS is less likely to be blocked by a firewall.
https://help.github.com/articles/which-remote-url-should-i-use/
The https:// clone URLs are available on all repositories, public and private. These URLs work everywhere--even if you are behind a firewall or proxy.
An HTTPS connection allows credential.helper
to cache your password.
https://help.github.com/articles/set-up-git
Good to know: The credential helper only works when you clone an HTTPS repo URL. If you use the SSH repo URL instead, SSH keys are used for authentication. While we do not recommend it, if you wish to use this method, check out this guide for help generating and using an SSH key.
import numpy as np
>>> np.shape(a)
(2,2)
Also works if the input is not a numpy array but a list of lists
>>> a = [[1,2],[1,2]]
>>> np.shape(a)
(2,2)
Or a tuple of tuples
>>> a = ((1,2),(1,2))
>>> np.shape(a)
(2,2)
Look at this example:
StringBuilder sb = new StringBuilder();
sb.append("Test String");
File f = new File("d:\\test.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));
ZipEntry e = new ZipEntry("mytext.txt");
out.putNextEntry(e);
byte[] data = sb.toString().getBytes();
out.write(data, 0, data.length);
out.closeEntry();
out.close();
This will create a zip in the root of D:
named test.zip
which will contain one single file called mytext.txt
. Of course you can add more zip entries and also specify a subdirectory like this:
ZipEntry e = new ZipEntry("folderName/mytext.txt");
You can find more information about compression with Java here.
Using your code you can do something like this in plain JavaScript using the cloneNode() method:
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#ddl_1').cloneNode( true );
// Change the id attribute of the newly created element:
clone.setAttribute( 'id', newId );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
Or using jQuery clone() method (not the most efficient):
$('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want
I solved the problem with the following steps:
Open "services.msc" from command / Windows RUN.
Find the service (which is greyed out).
Double click on that service and go to the "Recovery" tab.
Ensure that
and Press OK.
Now, the service will not try to restart and you can able to delete the greyed out service from services list (i.e. greyed out will be gone).
For my Raspberry Pi 3B model it was
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet manual
allow-hotplug wlan0
iface wlan0 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
allow-hotplug wlan1
iface wlan1 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
They serve the actual image inside CSS so there will be less HTTP requests per page.
This is another variant that collects the errors recursively and does not depend on any external library like lodash
(ES6 only):
function isFormGroup(control: AbstractControl): control is FormGroup {
return !!(<FormGroup>control).controls;
}
function collectErrors(control: AbstractControl): any | null {
if (isFormGroup(control)) {
return Object.entries(control.controls)
.reduce(
(acc, [key, childControl]) => {
const childErrors = collectErrors(childControl);
if (childErrors) {
acc = {...acc, [key]: childErrors};
}
return acc;
},
null
);
} else {
return control.errors;
}
}
In this case it is better to use basename
instead of awk
:
$ basename /home/parent/child1/child2/filename
filename
There are some great answers here. But recent changes to how Swift implements weak references should change everyone's weak self vs. unowned self usage decisions. Previously, if you needed the best performance using unowned self was superior to weak self, as long as you could be certain that self would never be nil, because accessing unowned self is much faster than accessing weak self.
But Mike Ash has documented how Swift has updated the implementation of weak vars to use side-tables and how this substantially improves weak self performance.
https://mikeash.com/pyblog/friday-qa-2017-09-22-swift-4-weak-references.html
Now that there isn't a significant performance penalty to weak self, I believe we should default to using it going forward. The benefit of weak self is that it's an optional, which makes it far easier to write more correct code, it's basically the reason Swift is such a great language. You may think you know which situations are safe for the use of unowned self, but my experience reviewing lots of other developers code is, most don't. I've fixed lots of crashes where unowned self was deallocated, usually in situations where a background thread completes after a controller is deallocated.
Bugs and crashes are the most time-consuming, painful and expensive parts of programming. Do your best to write correct code and avoid them. I recommend making it a rule to never force unwrap optionals and never use unowned self instead of weak self. You won't lose anything missing the times force unwrapping and unowned self actually are safe. But you'll gain a lot from eliminating hard to find and debug crashes and bugs.
If you know the extension or pattern of the file you would like, another method is to use --include
option:
grep -r --include "*.txt" texthere .
You can also mention files to exclude with --exclude
.
If you frequently search through code, Ag (The Silver Searcher) is a much faster alternative to grep, that's customized for searching code. For instance, it's recursive by default and automatically ignores files and directories listed in .gitignore
, so you don't have to keep passing the same cumbersome exclude options to grep or find.
I'm just using a predefined directory on the host to persist data for PostgreSQL. Also, this way it is possible to easily migrate existing PostgreSQL installations to Docker containers: https://crondev.com/persistent-postgresql-inside-docker/
This is my way, using location from props. I don't know but history.isActive got undefined for me
export default class Navbar extends React.Component {
render(){
const { location } = this.props;
const homeClass = location.pathname === "/" ? "active" : "";
const aboutClass = location.pathname.match(/^\/about/) ? "active" : "";
const contactClass = location.pathname.match(/^\/contact/) ? "active" : "";
return (
<div>
<ul className="nav navbar-nav navbar-right">
<li className={homeClass}><Link to="/">Home</Link></li>
<li className={aboutClass}><Link to="about" activeClassName="active">About</Link></li>
<li className={contactClass}><Link to="contact" activeClassName="active">Contact</Link></li>
</ul>
</div>
);}}
As a general way to handle error in a loop like your sample code, I would rather use:
on error resume next
for each...
'do something that might raise an error, then
if err.number <> 0 then
...
end if
next ....
you just provide one <folder>
argument to npm install
, argument should point toward the local folder instead of the package name:
npm install /path
The jar file is just an executable java program. If you want to modify the code, you have to open the .java files.
Modification from @veeresh i
var data=[
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
]; //parameter
var para={};
para.datav=data; //datav from View
$.ajax({
traditional: true,
url: "/Conroller/MethodTest",
type: "POST",
contentType: "application/json; charset=utf-8",
data:para,
success: function (data) {
$scope.DisplayError(data.requestStatus);
}
});
In MVC
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
public JsonResult MethodTest(IEnumerable<Thing> datav)
{
//now datav is having all your values
}
Depends on your specific situation, but if the iframe can be deployed after the rest of the page's loading, you can simply use a query string, a la:
<iframe src="some_page.html?somedata=5&more=bacon"></iframe>
And then somewhere in some_page.html:
<script>
var params = location.href.split('?')[1].split('&');
data = {};
for (x in params)
{
data[params[x].split('=')[0]] = params[x].split('=')[1];
}
</script>
The simple approach (gcc -dM -E - < /dev/null
) works fine for gcc but fails for g++. Recently I required a test for a C++11/C++14 feature. Recommendations for their corresponding macro names are published at https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations. But:
g++ -dM -E - < /dev/null | fgrep __cpp_alias_templates
always fails, because it silently invokes the C-drivers (as if invoked by gcc
). You can see this by comparing its output against that of gcc or by adding a g++-specific command line option like (-std=c++11) which emits the error message cc1: warning: command line option ‘-std=c++11’ is valid for C++/ObjC++ but not for C
.
Because (the non C++) gcc will never support "Templates Aliases" (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf) you must add the -x c++
option to force the invocation of the C++ compiler (Credits for using the -x c++
options instead of an empty dummy file go to yuyichao, see below):
g++ -dM -E -x c++ /dev/null | fgrep __cpp_alias_templates
There will be no output because g++ (revision 4.9.1, defaults to -std=gnu++98) does not enable C++11-features by default. To do so, use
g++ -dM -E -x c++ -std=c++11 /dev/null | fgrep __cpp_alias_templates
which finally yields
#define __cpp_alias_templates 200704
noting that g++ 4.9.1 does support "Templates Aliases" when invoked with -std=c++11
.
Just giving a more up to date answer in case someone sees this old post.
Adding "utc=False" when converting to datetime will remove the timezone component and keep only the date in a datetime64[ns] data type.
pd.to_datetime(df['Date'], utc=False)
You will be able to save it in excel without getting the error "ValueError: Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel."
It looks like github has a simple UI for creating branches. I opened the branch drop-down and it prompts me to "Find or create a branch ...". Type the name of your new branch, then click the "create" button that appears.
To retrieve your new branch from github, use the standard git fetch
command.
I'm not sure this will help your underlying problem, though, since the underlying data being pushed to the server (the commit objects) is the same no matter what branch it's being pushed to.
If you are like me and need to change color of text itself also while in the same time filling the background color check my solution.
Steps to create:
Good thing about this solution:
Not so good thing about this solution:
Check the pen ---> https://codepen.io/nikolamitic/pen/vpNoNq
<button class="btn btn--animation-from-right">
<span class="btn__text-static">Cover left</span>
<div class="btn__text-dynamic">
<span class="btn__text-dynamic-inner">Cover left</span>
</div>
</button>
.btn {
padding: 10px 20px;
position: relative;
border: 2px solid #222;
color: #fff;
background-color: #222;
position: relative;
overflow: hidden;
cursor: pointer;
text-transform: uppercase;
font-family: monospace;
letter-spacing: -1px;
[class^="btn__text"] {
font-size: 24px;
}
.btn__text-dynamic,
.btn__text-dynamic-inner {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
z-index: 2;
transition: all ease 0.5s;
}
.btn__text-dynamic {
background-color: #fff;
color: #222;
overflow: hidden;
}
&:hover {
.btn__text-dynamic {
transform: translateX(-100%);
}
.btn__text-dynamic-inner {
transform: translateX(100%);
}
}
}
.btn--animation-from-right {
&:hover {
.btn__text-dynamic {
transform: translateX(100%);
}
.btn__text-dynamic-inner {
transform: translateX(-100%);
}
}
}
You can remove .btn--animation-from-right modifier if you want to animate to the left.
Another way is with Arrays.setAll
, or Arrays.fill
:
String[] v = new String[1000];
Arrays.setAll(v, i -> Integer.toString(i * 30));
//v => ["0", "30", "60", "90"... ]
Arrays.fill(v, "initial value");
//v => ["initial value", "initial value"... ]
This is more usefull for initializing (possibly large) arrays where you can compute each element from its index.
None of these solutions would work for us (other than disabling the schema checking altogether). In the end we had a miss-match in our version of Newtonsoft.json
Our AppConfig did not get updated correctly:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
The solution was to correct the assembly version to the one we were actually deploying
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="10.0.0.0" />
</dependentAssembly>
You can do something like this to read 10 bytes:
char buffer[10];
read(STDIN_FILENO, buffer, 10);
remember read() doesn't add '\0'
to terminate to make it string (just gives raw buffer).
To read 1 byte at a time:
char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
//do stuff
}
and don't forget to #include <unistd.h>
, STDIN_FILENO
defined as macro in this file.
There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:
Integer value Name
0 Standard input (stdin)
1 Standard output (stdout)
2 Standard error (stderr)
So instead STDIN_FILENO
you can use 0.
Edit:
In Linux System you can find this using following command:
$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define STDIN_FILENO 0 /* Standard input. */
Notice the comment /* Standard input. */
If you are using Razor, you cannot access the field directly, but you can manage its value.
The idea is that the first Microsoft approach drive the developers away from Web Development and make it easy for Desktop programmers (for example) to make web applications.
Meanwhile, the web developers, did not understand this tricky strange way of ASP.NET.
Actually this hidden input is rendered on client-side, and the ASP has no access to it (it never had). However, in time you will see its a piratical way and you may rely on it, when you get use with it. The web development differs from the Desktop or Mobile.
The model is your logical unit, and the hidden field (and the whole view page) is just a representative view of the data. So you can dedicate your work on the application or domain logic and the view simply just serves it to the consumer - which means you need no detailed access and "brainstorming" functionality in the view.
The controller actually does work you need for manage the hidden or general setup. The model serves specific logical unit properties and functionality and the view just renders it to the end user, simply said. Read more about MVC.
Model
public class MyClassModel
{
public int Id { get; set; }
public string Name { get; set; }
public string MyPropertyForHidden { get; set; }
}
This is the controller aciton
public ActionResult MyPageView()
{
MyClassModel model = new MyClassModel(); // Single entity, strongly-typed
// IList model = new List<MyClassModel>(); // or List, strongly-typed
// ViewBag.MyHiddenInputValue = "Something to pass"; // ...or using ViewBag
return View(model);
}
The view is below
//This will make a Model property of the View to be of MyClassModel
@model MyNamespace.Models.MyClassModel // strongly-typed view
// @model IList<MyNamespace.Models.MyClassModel> // list, strongly-typed view
// ... Some Other Code ...
@using(Html.BeginForm()) // Creates <form>
{
// Renders hidden field for your model property (strongly-typed)
// The field rendered to server your model property (Address, Phone, etc.)
Html.HiddenFor(model => Model.MyPropertyForHidden);
// For list you may use foreach on Model
// foreach(var item in Model) or foreach(MyClassModel item in Model)
}
// ... Some Other Code ...
The view with ViewBag:
// ... Some Other Code ...
@using(Html.BeginForm()) // Creates <form>
{
Html.Hidden(
"HiddenName",
ViewBag.MyHiddenInputValue,
new { @class = "hiddencss", maxlength = 255 /*, etc... */ }
);
}
// ... Some Other Code ...
We are using Html Helper to render the Hidden field or we could write it by hand - <input name=".." id=".." value="ViewBag.MyHiddenInputValue">
also.
The ViewBag is some sort of data carrier to the view. It does not restrict you with model - you can place whatever you like.
The problem is that /var/www
doesn't exist either, and mkdir
isn't recursive by default -- it expects the immediate parent directory to exist.
Use:
mkdir -p /var/www/app
...or install a package that creates a /var/www
prior to reaching this point in your Dockerfile.
Try System.getProperty( "line.separator" )
writer.write(System.getProperty( "line.separator" ));
A workaround you can do is not use static classes but hide the constructor so the classes static members are the only thing accessible outside the class. The result is an inheritable "static" class essentially:
public class TestClass<T>
{
protected TestClass()
{ }
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public class TestClass : TestClass<double>
{
// Inherited classes will also need to have protected constructors to prevent people from creating instances of them.
protected TestClass()
{ }
}
TestClass.Add(3.0, 4.0)
TestClass<int>.Add(3, 4)
// Creating a class instance is not allowed because the constructors are inaccessible.
// new TestClass();
// new TestClass<int>();
Unfortunately because of the "by-design" language limitation we can't do:
public static class TestClass<T>
{
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public static class TestClass : TestClass<double>
{
}
What
l.onclick();
does is exactly calling the onclick
function of l
, that is, if you have set one with l.onclick = myFunction;
. If you haven't set l.onclick
, it does nothing. In contrast,
l.click();
simulates a click and fires all event handlers, whether added with l.addEventHandler('click', myFunction);
, in HTML, or in any other way.
File file = new File(path, name);
MimeTypeMap mime = MimeTypeMap.getSingleton();
int index = file.getName().lastIndexOf('.')+1;
String ext = file.getName().substring(index).toLowerCase();
String type = mime.getMimeTypeFromExtension(ext);
intent.setDataAndType(Uri.fromFile(file), type);
try
{
context.startActivity(intent);
}
catch(ActivityNotFoundException ex)
{
ex.printStackTrace();
}
Just use substring: "apple".substring(3);
will return le
In the Google Maps API v2 Demo there is a MarkerDemoActivity
class in which you can see how a custom Image is set to a GoogleMap.
// Uses a custom icon.
mSydney = mMap.addMarker(new MarkerOptions()
.position(SYDNEY)
.title("Sydney")
.snippet("Population: 4,627,300")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
As this just replaces the marker with an image you might want to use a Canvas
to draw more complex and fancier stuff:
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(80, 80, conf);
Canvas canvas1 = new Canvas(bmp);
// paint defines the text color, stroke width and size
Paint color = new Paint();
color.setTextSize(35);
color.setColor(Color.BLACK);
// modify canvas
canvas1.drawBitmap(BitmapFactory.decodeResource(getResources(),
R.drawable.user_picture_image), 0,0, color);
canvas1.drawText("User Name!", 30, 40, color);
// add marker to Map
mMap.addMarker(new MarkerOptions()
.position(USER_POSITION)
.icon(BitmapDescriptorFactory.fromBitmap(bmp))
// Specifies the anchor to be at a particular point in the marker image.
.anchor(0.5f, 1));
This draws the Canvas canvas1
onto the GoogleMap mMap
. The code should (mostly) speak for itself, there are many tutorials out there how to draw a Canvas
. You can start by looking at the Canvas and Drawables from the Android Developer page.
Now you also want to download a picture from an URL.
URL url = new URL(user_image_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
You must download the image from an background thread (you could use AsyncTask or Volley or RxJava for that).
After that you can replace the BitmapFactory.decodeResource(getResources(), R.drawable.user_picture_image)
with your downloaded image bmImg
.
Sort of. As Bobby says:
svn co file:///.../trunk/foo file:///.../trunk/bar file:///.../trunk/hum
will get the folders, but you will get separate folders from a subversion perspective. You will have to go separate commits and updates on each subfolder.
I don't believe you can checkout a partial tree and then work with the partial tree as a single entity.
[DataContract] and [DataMember] attribute are found in System.ServiceModel namespace which is in System.ServiceModel.dll .
System.ServiceModel uses the System and System.Runtime.Serialization namespaces to serialize the datamembers.
java.io.NotSerializableException
can occur when you serialize an inner class instance because:
serializing such an inner class instance will result in serialization of its associated outer class instance as well
Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged
You want your if
check to be:
{% if not loop.last %}
,
{% endif %}
Note that you can also shorten the code by using If Expression:
{{ ", " if not loop.last else "" }}
I'd probably change your example to look like this:
<ul ng-repeat="task in tasks">
<li ng-mouseover="enableEdit(task)" ng-mouseleave="disableEdit(task)">{{task.name}}</li>
<span ng-show="task.editable"><a>Edit</a></span>
</ul>
//js
$scope.enableEdit = function(item){
item.editable = true;
};
$scope.disableEdit = function(item){
item.editable = false;
};
I know it's a subtle difference, but makes the domain a little less bound to UI actions. Mentally it makes it easier to think about an item being editable rather than having been moused over.
Example jsFiddle.
If you really wanted to store it in a column and have it queryable a lot of databases support XML now. If not querying you can store them as comma separated values and parse them out with a function when you need them separated. I agree with everyone else though if you are looking to use a relational database a big part of normalization is the separating of data like that. I am not saying that all data fits a relational database though. You could always look into other types of databases if a lot of your data doesn't fit the model.
I like this method,use sind(x)
or cosd(x)
import math
def sind(x):
return math.sin(math.radians(x))
def cosd(x):
return math.cos(math.radians(x))
You can use display:inline-block
.
This property allows a DOM element to have all the attributes of a block element, but keeping it inline. There's some drawbacks, but most of the time it's good enough. Why it's good and why it may not work for you.
EDIT: The only modern browser that has some problems with it is IE7. See Quirksmode.org
Here's how you can do that (quick and dirty solution. If you really need this kind of behavior, you should either reconsider your design or override all IList<T>
members and aggregate the source list):
using System;
using System.Collections.Generic;
namespace ConsoleApplication3
{
public class ModifiableList<T> : List<T>
{
private readonly IList<T> pendingAdditions = new List<T>();
private int activeEnumerators = 0;
public ModifiableList(IEnumerable<T> collection) : base(collection)
{
}
public ModifiableList()
{
}
public new void Add(T t)
{
if(activeEnumerators == 0)
base.Add(t);
else
pendingAdditions.Add(t);
}
public new IEnumerator<T> GetEnumerator()
{
++activeEnumerators;
foreach(T t in ((IList<T>)this))
yield return t;
--activeEnumerators;
AddRange(pendingAdditions);
pendingAdditions.Clear();
}
}
class Program
{
static void Main(string[] args)
{
ModifiableList<int> ints = new ModifiableList<int>(new int[] { 2, 4, 6, 8 });
foreach(int i in ints)
ints.Add(i * 2);
foreach(int i in ints)
Console.WriteLine(i * 2);
}
}
}
Try This one.
function containsSpecialCharacters(str){_x000D_
var regex = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;_x000D_
return regex.test(str);_x000D_
}
_x000D_
Looks for the function glob():
<?php
$files = glob("dir/*.jpg");
foreach($files as $jpg){
echo $jpg, "\n";
}
?>
Sample usage:
SELECT
Getdate=GETDATE()
,SysDateTimeOffset=SYSDATETIMEOFFSET()
,SWITCHOFFSET=SWITCHOFFSET(SYSDATETIMEOFFSET(),0)
,GetutcDate=GETUTCDATE()
GO
Returns:
Getdate SysDateTimeOffset SWITCHOFFSET GetutcDate
2013-12-06 15:54:55.373 2013-12-06 15:54:55.3765498 -08:00 2013-12-06 23:54:55.3765498 +00:00 2013-12-06 23:54:55.373
MainActivity.class
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences.Editor;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
String text;
EditText et;
TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText)findViewById(R.id.editText1);
tts=new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status == TextToSpeech.SUCCESS){
int result=tts.setLanguage(Locale.US);
if(result==TextToSpeech.LANG_MISSING_DATA ||
result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("error", "This Language is not supported");
}
else{
ConvertTextToSpeech();
}
}
else
Log.e("error", "Initilization Failed!");
}
});
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
if(tts != null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
public void onClick(View v){
ConvertTextToSpeech();
}
private void ConvertTextToSpeech() {
// TODO Auto-generated method stub
text = et.getText().toString();
if(text==null||"".equals(text))
{
text = "Content not available";
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}else
tts.speak(text+"is saved", TextToSpeech.QUEUE_FLUSH, null);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="177dp"
android:onClick="onClick"
android:text="Button" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="81dp"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>
I did not found any solution here that show how to pass method with parameters bound to it as a parameter of a method. Bellow is example of how you can pass a method with parameter values already bound to it.
public interface Do {
void run() throws Exception;
}
public interface Return {
R run() throws Exception;
}
//example - when passed method does not return any value
public void tx(final Do func) throws Exception {
connectionScope.beginTransaction();
try {
func.run();
connectionScope.commit();
} catch (Exception e) {
connectionScope.rollback();
throw e;
} finally {
connectionScope.close();
}
}
//Invoke code above by
tx(() -> api.delete(6));
Another example shows how to pass a method that actually returns something
public R tx(final Return func) throws Exception {
R r=null;
connectionScope.beginTransaction();
try {
r=func.run();
connectionScope.commit();
} catch (Exception e) {
connectionScope.rollback();
throw e;
} finally {
connectionScope.close();
}
return r;
}
//Invoke code above by
Object x= tx(() -> api.get(id));
Yes it's possible to change it to gray (no custom colors) but this only works from API 23 and above you only need to add this in your values-v23/styles.xml
<item name="android:windowLightStatusBar">true</item>
If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:
columns = ['Y'+str(i) for year in range(1967, 2011)]
df.groupby('Country')[columns].agg('sum')
If you're using .NET 4, there is a special folder enumeration ProgramFilesX86:
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
Kindly try below on postman :-
In header section example work for me..
Authorization : JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwiZ2V0dGVycyI6e30sIndhc1BvcHVsYXRlZCI6ZmFsc2UsImFjdGl2ZVBhdGhzIjp7InBhdGhzIjp7InBhc3N3b3JkIjoiaW5pdCIsImVtYWlsIjoiaW5pdCIsIl9fdiI6ImluaXQiLCJfaWQiOiJpbml0In0sInN0YXRlcyI6eyJpZ25vcmUiOnt9LCJkZWZhdWx0Ijp7fSwiaW5pdCI6eyJfX3YiOnRydWUsInBhc3N3b3JkIjp0cnVlLCJlbWFpbCI6dHJ1ZSwiX2lkIjp0cnVlfSwibW9kaWZ5Ijp7fSwicmVxdWlyZSI6e319LCJzdGF0ZU5hbWVzIjpbInJlcXVpcmUiLCJtb2RpZnkiLCJpbml0IiwiZGVmYXVsdCIsImlnbm9yZSJdfSwiZW1pdHRlciI6eyJkb21haW4iOm51bGwsIl9ldmVudHMiOnt9LCJfZXZlbnRzQ291bnQiOjAsIl9tYXhMaXN0ZW5lcnMiOjB9fSwiaXNOZXciOmZhbHNlLCJfZG9jIjp7Il9fdiI6MCwicGFzc3dvcmQiOiIkMmEkMTAkdTAybWNnWHFjWVQvdE41MlkzZ2l3dVROd3ZMWW9ZTlFXejlUcThyaDIwR09IMlhHY3haZWUiLCJlbWFpbCI6Im1hZGFuLmRhbGUxQGdtYWlsLmNvbSIsIl9pZCI6IjU5MjEzYzYyYWM2ODZlMGMyNzI2MjgzMiJ9LCJfcHJlcyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbbnVsbCxudWxsLG51bGxdLCIkX19vcmlnaW5hbF92YWxpZGF0ZSI6W251bGxdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltudWxsXX0sIl9wb3N0cyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbXSwiJF9fb3JpZ2luYWxfdmFsaWRhdGUiOltdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltdfSwiaWF0IjoxNDk1MzUwNzA5LCJleHAiOjE0OTUzNjA3ODl9.BkyB0LjKB4FIsCtnM5FcpcBLvKed_j7rCCxZddwiYnU
Try this, at the end of the each loop, ids array will contain all the hexcodes.
var ids = [];
$(document).ready(function($) {
var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
$(".color_cell").each(function() {
code = $(this).attr('id');
ids.push(code);
$div.append(code + "<br />");
});
});
Still better solution could be to follow a design pattern such that the back-button press event gets propagated from active fragment down to host Activity. So, it's like.. if one of the active fragments consume the back-press, the Activity wouldn't get to act upon it, and vice-versa.
One way to do it is to have all your Fragments extend a base fragment that has an abstract 'boolean onBackPressed()' method.
@Override
public boolean onBackPressed() {
if(some_condition)
// Do something
return true; //Back press consumed.
} else {
// Back-press not consumed. Let Activity handle it
return false;
}
}
Keep track of active fragment inside your Activity and inside it's onBackPressed callback write something like this
@Override
public void onBackPressed() {
if(!activeFragment.onBackPressed())
super.onBackPressed();
}
}
This post has this pattern described in detail
You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).
We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)
When using React, you should never mutate the state directly. If an object (or Array
, which is an object too) is changed, you should create a new copy.
Others have suggested using Array.prototype.splice()
, but that method mutates the Array, so it's better not to use splice()
with React.
Easiest to use Array.prototype.filter()
to create a new array:
removePeople(e) {
this.setState({people: this.state.people.filter(function(person) {
return person !== e.target.value
})});
}
The approach recommended by the ASP.Net Core team is to use the new policy design which is fully documented here. The basic idea behind the new approach is to use the new [Authorize] attribute to designate a "policy" (e.g. [Authorize( Policy = "YouNeedToBe18ToDoThis")]
where the policy is registered in the application's Startup.cs to execute some block of code (i.e. ensure the user has an age claim where the age is 18 or older).
The policy design is a great addition to the framework and the ASP.Net Security Core team should be commended for its introduction. That said, it isn't well-suited for all cases. The shortcoming of this approach is that it fails to provide a convenient solution for the most common need of simply asserting that a given controller or action requires a given claim type. In the case where an application may have hundreds of discrete permissions governing CRUD operations on individual REST resources ("CanCreateOrder", "CanReadOrder", "CanUpdateOrder", "CanDeleteOrder", etc.), the new approach either requires repetitive one-to-one mappings between a policy name and a claim name (e.g. options.AddPolicy("CanUpdateOrder", policy => policy.RequireClaim(MyClaimTypes.Permission, "CanUpdateOrder));
), or writing some code to perform these registrations at run time (e.g. read all claim types from a database and perform the aforementioned call in a loop). The problem with this approach for the majority of cases is that it's unnecessary overhead.
While the ASP.Net Core Security team recommends never creating your own solution, in some cases this may be the most prudent option with which to start.
The following is an implementation which uses the IAuthorizationFilter to provide a simple way to express a claim requirement for a given controller or action:
public class ClaimRequirementAttribute : TypeFilterAttribute
{
public ClaimRequirementAttribute(string claimType, string claimValue) : base(typeof(ClaimRequirementFilter))
{
Arguments = new object[] {new Claim(claimType, claimValue) };
}
}
public class ClaimRequirementFilter : IAuthorizationFilter
{
readonly Claim _claim;
public ClaimRequirementFilter(Claim claim)
{
_claim = claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var hasClaim = context.HttpContext.User.Claims.Any(c => c.Type == _claim.Type && c.Value == _claim.Value);
if (!hasClaim)
{
context.Result = new ForbidResult();
}
}
}
[Route("api/resource")]
public class MyController : Controller
{
[ClaimRequirement(MyClaimTypes.Permission, "CanReadResource")]
[HttpGet]
public IActionResult GetResource()
{
return Ok();
}
}
Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting.
pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')
This particular commands worked for me.
sudo apt-get remove --purge nginx nginx-full nginx-common
and
sudo apt-get install nginx
credit to this answer on stackexchnage
Your compile SDK version must match the support library's major version.
Since you are using version 23 of the support library, you need to compile against version 23 of the Android SDK.
Alternatively you can continue compiling against version 22 of the Android SDK by switching to the latest support library v22.
What operating system?
Here on Ubuntu, I have
$ dpkg -S /usr/include/GL/gl.h
mesa-common-dev: /usr/include/GL/gl.h
$
but not the difference in a) capitalization and b) forward/backward slashes. Your example is likely to be wrong in its use of backslashes.
If you want an else
you don't want to filter the list comprehension, you want it to iterate over every value. You can use true-value if cond else false-value
as the statement instead, and remove the filter from the end:
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
Clickatell is a popular SMS gateway. It works in 200+ countries.
Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.
The HTTP/S method is as simple as this:
http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here
The SMTP method consists of sending a plain-text e-mail to: [email protected]
, with the following body:
user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home
You can also test the gateway (incoming and outgoing) for free from your browser
C++ style casts are checked by the compiler. C style casts aren't and can fail at runtime.
Also, c++ style casts can be searched for easily, whereas it's really hard to search for c style casts.
Another big benefit is that the 4 different C++ style casts express the intent of the programmer more clearly.
When writing C++ I'd pretty much always use the C++ ones over the the C style.
You normally use a tool like pip
to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.
For this to work, you do need to install the wheel
package:
pip install wheel
You can then tell pip
to install the project (and it'll download the wheel if available), or the wheel file directly:
pip install project_name # discover, download and install
pip install wheel_file.whl # directly install the wheel
The wheel
module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:
python -m wheel install wheel_file.whl
Also see the wheel
project documentation.
Here is my version:
/**
*
* Insert an element after an index in an array
* @param array $array
* @param string|int $key
* @param mixed $value
* @param string|int $offset
* @return mixed
*/
function array_splice_associative($array, $key, $value, $offset) {
if (!is_array($array)) {
return $array;
}
if (array_key_exists($key, $array)) {
unset($array[$key]);
}
$return = array();
$inserted = false;
foreach ($array as $k => $v) {
$return[$k] = $v;
if ($k == $offset && !$inserted) {
$return[$key] = $value;
$inserted = true;
}
}
if (!$inserted) {
$return[$key] = $value;
}
return $return;
}
I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.
Here is an example:
mysql> PREPARE stmt FROM
-> 'select count(*)
-> from information_schema.schemata
-> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt
-> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
| 2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;
The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.
Here is a good link about this:
Don't forget to deallocate the stmt
using the last line!
Good Luck!
I just wanted to share how I did this find/replace thing with sql database, because I needed to replace links from Chrome's sessionbuddy db file.
Simply to login mysql
in windows
, if you know your username and password.
Open your command prompt, for me the username is root
and password is password
mysql -u root -p
Enter password: ********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.11-log MySQL Community Server (GPL)
Hope it would help many one.
The reason is that modprobe
looks into /lib/modules/$(uname -r)
for the modules and therefore won't work with local file path. That's one of differences between modprobe
and insmod
.
The local Maven repo tracks where artifacts originally came from using a file named "_maven.repositories" in the artifact directory. After removing it, the build worked. This answer fixed the problem for me.
NotificationManager.cancel(id)
is the correct answer. Yet you can remove in Android Oreo and later notifications by deleting the whole notification channel. This should delete all messages in the deleted channel.
Here is the example from the Android documentation:
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String id = "my_channel_01";
mNotificationManager.deleteNotificationChannel(id);
Update: I've since created a downloadable REPL - see my other answer.
With the benefit of hindsight:
rlwrap
, which provides readline support to any command, you can combine it with a simple Perl command to create a usable REPL, and thus make do without third-party REPL solutions.
rlwrap
via Homebrew with brew install rlwrap
.rlwrap
via their respective package managers; e.g., on Ubuntu, use sudo apt-get install rlwrap
.rlwrap
and a Perl command.What you do NOT get with Ján's answer:
The only third-party solution that offers these (with non-trivial installation + additional, non-obvious steps), is psh, but:
it hasn't seen activity in around 2.5 years
its focus is different in that it aims to be a full-fledged shell replacement, and thus works like a traditional shell, which means that it doesn't automatically evaluate a command as a Perl statement, and requires an explicit output command such as print
to print the result of an expression.
Ján Sáreník's answer can be improved in one way:
If you install the Data::Printer
module with [sudo] cpan Data::Printer
as a one-time operation, you can load it into the REPL for use of the p()
function, to which you can pass lists/arrays/hashtables for enumeration.
Here's an alias named iperl
with readline and Data::Printer
support, which can you put in your POSIX-like shell's initialization file (e.g., ~/.bashrc
):
alias iperl='rlwrap -A -S "iperl> " perl -MData::Printer -wnE '\''BEGIN { say "# Use `p @<arrayOrList>` or `p %<hashTable>` to print arrays/lists/hashtables; e.g.: `p %ENV`"; } say eval()//$@'\'
E.g., you can then do the following to print all environment variables via hashtable %ENV
:
$ iperl # start the REPL
iperl> p %ENV # print key-value pairs in hashtable %ENV
As with Ján's answer, the scalar result of an expression is automatically printed; e.g.:
iperl> 22 / 7 # automatically print scalar result of expression: 3.14285714285714
Another solution is using a "while" loop instead a "for" loop:
index=0
while [ ${index} -lt ${#Array[@]} ]
do
echo ${Array[${index}]}
index=$(( $index + 1 ))
done
If you had MyPhoneExplorer installed and connected (not sure this is a must, happened to be my setup already), you could use it to control the screen with your computer mouse. It connects via ADB, for which your normal USB cable is enough.
Another solution I found that even worked without a reboot is updating tables in settings.db and locksettings.db I had to switch to root to open the settings.db though:
adb shell
su
sqlite3 /data/data/com.android.providers.settings/databases/settings.db
update secure set value=1 where name='lockscreen.disabled';
.quit
sqlite3 /data/system/locksettings.db
update locksettings set value=0 where name='lock_pattern_autlock';
update locksettings set value=1 where name='lockscreen.disabled';
.quit
This problem arises due to the administrative share.
Here is the solution :
Set HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System DWORD
value: LocalAccountTokenFilterPolicy
to 1
Go to this link: http://www.snehashish.com/install-oracle-database-12c-software/ Follow 8th point.
It helped me a lot.
After creating the hidden share (c$) it should look like this (you can ignore the description tab)
And let me know if it worked or not.
Use:
int Years(DateTime start, DateTime end)
{
return (end.Year - start.Year - 1) +
(((end.Month > start.Month) ||
((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0);
}
java.net.URLEncoder.encode(finalPartOfString, "utf-8");
This will URL-encode the string.
finalPartOfString
is the part after the last slash - in your case, the name of the song, as it seems.
private Random gen = new Random();
DateTime RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
int range = (DateTime.Today - start).Days;
return start.AddDays(gen.Next(range));
}
For better performance if this will be called repeatedly, create the start
and gen
(and maybe even range
) variables outside of the function.
Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).
Either way works, I like to put that logic in the query so the report has to do less.
My fairly short code to read JSON from an URL. (requires Guava due to usage of CharStreams
).
private static class VersionTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... strings) {
String result = null;
URL url;
HttpURLConnection connection = null;
try {
url = new URL("https://api.github.com/repos/user_name/repo_name/releases/latest");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
result = CharStreams.toString(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8));
} catch (IOException e) {
Log.d("VersionTask", Log.getStackTraceString(e));
} finally {
if (connection != null) {
connection.disconnect();
}
}
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
String version = "";
try {
version = new JSONObject(result).optString("tag_name").trim();
} catch (JSONException e) {
Log.e("VersionTask", Log.getStackTraceString(e));
}
if (version.startsWith("v")) {
//process version
}
}
}
}
PS: This code gets the latest release version (based on tag name) for a given GitHub repo.
The commands are adduser
and addgroup
.
Here's a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):
ENV USER=docker
ENV UID=12345
ENV GID=23456
RUN adduser \
--disabled-password \
--gecos "" \
--home "$(pwd)" \
--ingroup "$USER" \
--no-create-home \
--uid "$UID" \
"$USER"
Note the following:
--disabled-password
prevents prompt for a password--gecos ""
circumvents the prompt for "Full Name" etc. on Debian-based systems--home "$(pwd)"
sets the user's home to the WORKDIR. You may not want this.--no-create-home
prevents cruft getting copied into the directory from /etc/skel
The usage description for these applications is missing the long flags present in the code for adduser and addgroup.
The following long-form flags should work both in alpine as well as debian-derivatives:
BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.
Usage: adduser [OPTIONS] USER [GROUP]
Create new user, or add USER to GROUP
--home DIR Home directory
--gecos GECOS GECOS field
--shell SHELL Login shell
--ingroup GRP Group (by name)
--system Create a system user
--disabled-password Don't assign a password
--no-create-home Don't create home directory
--uid UID User id
One thing to note is that if --ingroup
isn't set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.
BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.
Usage: addgroup [-g GID] [-S] [USER] GROUP
Add a group or add a user to a group
--gid GID Group id
--system Create a system group
I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.
My entrypoint helper script can be found on GitHub.
The intent is to prepend that script as the first argument to ENTRYPOINT
which should cause Docker to infer UID and GID from a relevant bind mount.
An environment variable "TEMPLATE" may be required to determine where the permissions should be inferred from.
(At the time of writing I don't have documentation for my script. It's still on the todo list!!)
You can try this code (requires jQuery):
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#foo').keyup(function(e) {
var v = $('#foo').val();
$('#debug').val(v);
})
});
</script>
</head>
<body>
<form>
<input type="text" id="foo" value="bar"><br>
<textarea id="debug"></textarea>
</form>
</body>
</html>
With the latest Python extension for Visual Studio Code, there is a venvPath Setting:
// Path to folder with a list of Virtual Environments (e.g. ~/.pyenv, ~/Envs, ~/.virtualenvs).
"python.venvPath": "",
On Mac OS X, go to Code ? Preferences ? Settings and scroll down to Python Configuration.
Look for "python.venvPath: "",
and click the pencil on the left-hand side to open up your user settings. Finally, add the path to where you store your virtual environments.
If you are using virtuanenvwrapper, or you have put all your virtual environment setting in one folder, this will be the one for you.
After you have configured "python.venvPath"
, restart Visual Studio Code. Then open the command palette and look for "Python: Select Interpreter". At this point, you should see the interpreter associated with the virtual environment you just added.
One of the important thing is on setting a secure apache web server is to disable directory browsing. By default apache comes with this feature enabled but it is always a good idea to get it disabled unless you really need it. Open httpd.conf file in apache folder and find the line that looks as follows:
Options Includes Indexes FollowSymLinks MultiViews
then remove word Indexes and save the file. Restart apache. That's it
Have you tried using Linux Installer to get a full Debian build on the phone? It's billed as being able to run a full LAMP environment in about 300M and has gotten some good reviews.