Here's some code with a dummy geom_blank
layer,
range_act <- range(range(results$act), range(results$pred))
d <- reshape2::melt(results, id.vars = "pred")
dummy <- data.frame(pred = range_act, value = range_act,
variable = "act", stringsAsFactors=FALSE)
ggplot(d, aes(x = pred, y = value)) +
facet_wrap(~variable, scales = "free") +
geom_point(size = 2.5) +
geom_blank(data=dummy) +
theme_bw()
Using a Messenger is another simple way to communicate between a Service and an Activity.
In the Activity, create a Handler with a corresponding Messenger. This will handle messages from your Service.
class ResponseHandler extends Handler {
@Override public void handleMessage(Message message) {
Toast.makeText(this, "message from service",
Toast.LENGTH_SHORT).show();
}
}
Messenger messenger = new Messenger(new ResponseHandler());
The Messenger can be passed to the service by attaching it to a Message:
Message message = Message.obtain(null, MyService.ADD_RESPONSE_HANDLER);
message.replyTo = messenger;
try {
myService.send(message);
catch (RemoteException e) {
e.printStackTrace();
}
A full example can be found in the API demos: MessengerService and MessengerServiceActivity. Refer to the full example for how MyService works.
flog = open('test.txt', 'r')
flogLines = flog.readlines()
strlist = ['SUCCESS', 'Done','SUCCESSFUL']
res = False
for line in flogLines:
for fstr in strlist:
if line.find(fstr) != -1:
print('found')
res = True
if res:
print('res true')
else:
print('res false')
Use JSON to transfer data types (arrays and objects) between client and server.
In PHP:
In JavaScript:
PHP:
echo json_encode($id_numbers);
JavaScript:
id_numbers = JSON.parse(msg);
As Wolfgang mentioned, you can give a fourth parameter to jQuery to automatically decode JSON for you.
id_numbers = new Array();
$.ajax({
url:"Example.php",
type:"POST",
success:function(msg){
id_numbers = msg;
},
dataType:"json"
});
Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:
str = str.replace(/[^-a-z0-9]+/g, "");
Also, if you need to match upper-case letters along with lower case, you should use:
str = str.replace(/[^-a-zA-Z0-9]+/g, "");
"(SqlConnection)context"
-- This type-casting no longer works. You can do: "SqlConnection context;
".AsSqlServer()"
-- Does not Exist.
"command.ExecuteNonQuery();"
-- Does not return results. reader=command.ExecuteReader()
does work.
With dt.load(reader)... then you have to switch the framework out of 5.0 and back to 4.51, as 5.0 does not support datatables/datasets, yet. Note: This is VS2015 RC.
git log ..otherbranch
git diff ...otherbranch
gitk ...otherbranch
Empty string implies HEAD
, so that's why just ..otherbranch
instead of HEAD..otherbranch
.
The two vs. three dots have slightly different meaning for diff than for the commands that list revisions (log, gitk etc.). For log and others two dots (a..b
) means everything that is in b
but not a
and three dots (a...b
) means everything that is in only one of a
or b
. But diff works with two revisions and there the simpler case represented by two dots (a..b
) is simple difference from a
to b
and three dots (a...b
) mean difference between common ancestor and b
(git diff $(git merge-base a b)..b
).
You could also try this :
function replaceStr(str, find, replace) {
for (var i = 0; i < find.length; i++) {
str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
}
return str;
}
var text = "#here_is_the_one#";
var find = ["#","_"];
var replace = ['',' '];
text = replaceStr(text, find, replace);
console.log(text);
find
refers to the text to be found and replace
to the text to be replaced with
This will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :
new RegExp(find[i], 'g')
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
I've used below command to copy from local linux Centos 7 to AWS EC2.
scp -i user_key.pem file.txt [email protected]:/home/ec2-user
The short answer is: never!
The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher
//Pass results back to the client
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);
If you are entering your credentials into the Visual Studio popup you might see an error that says "Login was not successful". However, this might not be true. Studio will open a browser window saying that it was in fact successful. There is then a dance between the browser and Studio where you need to accept / allow the authentication at certain points.
you have error in your code unexpected token
.use:
$('#purpose').on('change', function () {
if (this.value == '1') {
$("#business").show();
} else {
$("#business").hide();
}
});
Update: You can narrow down the code using .toggle()
$('#purpose').on('change', function () {
$("#business").toggle(this.value == '1');
});
Check for the USB connection type options. You should have one called "Internet pass through". That will let your phone use the same connection as your PC.
Adding break
resolves your issue. You can store more than a record in a cell as markdown doesn't support much features.
You have to make one ajax call to get the required result, in this case you can use Google API to get the same
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false
Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level
Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.
Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:
TableModel datePicker = new DatePickerTable("01011999","12302000");
Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:
datePicker.interval = 15;
Attach your table model into your JTable:
JTable newtable = new JTable (datePicker);
Your Java application now has a drop-down date selection dialog.
To find all types in an assembly that implement IFoo interface:
var results = from type in someAssembly.GetTypes()
where typeof(IFoo).IsAssignableFrom(type)
select type;
Note that Ryan Rinaldi's suggestion was incorrect. It will return 0 types. You cannot write
where type is IFoo
because type is a System.Type instance, and will never be of type IFoo. Instead, you check to see if IFoo is assignable from the type. That will get your expected results.
Also, Adam Wright's suggestion, which is currently marked as the answer, is incorrect as well, and for the same reason. At runtime, you'll see 0 types come back, because all System.Type instances weren't IFoo implementors.
To add an extra layer of control I use the HTML5 storage to detect if it is using mobile storage or desktop storage. If the browser does not support storage I have an array of mobile browser names and I compare the user agent with the browsers in the array.
It is pretty simple. Here is the function:
// Used to detect whether the users browser is an mobile browser
function isMobile() {
///<summary>Detecting whether the browser is a mobile browser or desktop browser</summary>
///<returns>A boolean value indicating whether the browser is a mobile browser or not</returns>
if (sessionStorage.desktop) // desktop storage
return false;
else if (localStorage.mobile) // mobile storage
return true;
// alternative
var mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile'];
for (var i in mobile) if (navigator.userAgent.toLowerCase().indexOf(mobile[i].toLowerCase()) > 0) return true;
// nothing found.. assume desktop
return false;
}
call concat
and pass param axis=1
to concatenate column-wise:
In [5]:
pd.concat([df_a,df_b], axis=1)
Out[5]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
There is a useful guide to the various methods of merging, joining and concatenating online.
For example, as you have no clashing columns you can merge
and use the indices as they have the same number of rows:
In [6]:
df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
And for the same reasons as above a simple join
works too:
In [7]:
df_a.join(df_b)
Out[7]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
A simpler (in my view) solution is to create a new dictionary and update it with the contents of the old one:
my_dict={'a':1}
my_copy = {}
my_copy.update( my_dict )
my_dict['a']=2
my_dict['a']
Out[34]: 2
my_copy['a']
Out[35]: 1
The problem with this approach is it may not be 'deep enough'. i.e. is not recursively deep. good enough for simple objects but not for nested dictionaries. Here is an example where it may not be deep enough:
my_dict1={'b':2}
my_dict2={'c':3}
my_dict3={ 'b': my_dict1, 'c':my_dict2 }
my_copy = {}
my_copy.update( my_dict3 )
my_dict1['b']='z'
my_copy
Out[42]: {'b': {'b': 'z'}, 'c': {'c': 3}}
By using Deepcopy() I can eliminate the semi-shallow behavior, but I think one must decide which approach is right for your application. In most cases you may not care, but should be aware of the possible pitfalls... final example:
import copy
my_copy2 = copy.deepcopy( my_dict3 )
my_dict1['b']='99'
my_copy2
Out[46]: {'b': {'b': 'z'}, 'c': {'c': 3}}
I too had OpenJDK on my Ubuntu machine:
$ java -version
java version "1.7.0_51"
OpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.13.04.2)
OpenJDK 64-Bit Server VM (build 24.45-b08, mixed mode)
Replacing OpenJDK with the HotSpot VM works fine:
sudo apt-get autoremove openjdk-7-jre-headless
After trying the other suggestions to no avail I discovered that this issue was related to styling for me. I don't know a lot about the why but I found that my SVGs were not visible because they were not holding their place in the DOM.
In essence, the containers around my SVGs were at width: 0 and overflow: hidden.
I fixed this by setting a width on the containers but it is possible that there is a more direct solution to that particular issue.
I don't know why you should make it so complicated as the others.
The following code is much simpler to understand and about 25% faster than the other solutions who uses the log function (called the function 20 Mio. times with different parameters)
function formatBytes($bytes, $precision = 2) {
$units = ['Byte', 'Kilobyte', 'Megabyte', 'Gigabyte', 'Terabyte'];
$i = 0;
while($bytes > 1024) {
$bytes /= 1024;
$i++;
}
return round($bytes, $precision) . ' ' . $units[$i];
}
This post already has a checked answer, but the answer doesn't filter for null values. The correct answer should prevent null values by using the Object::nonNull function as a predicate.
BigDecimal result = invoiceList.stream()
.map(Invoice::total)
.filter(Objects::nonNull)
.filter(i -> (i.getUnit_price() != null) && (i.getQuantity != null))
.reduce(BigDecimal.ZERO, BigDecimal::add);
This prevents null values from attempting to be summed as we reduce.
There are many ways to do this but I think one of the easiest options is to link the application to the DLL at link time and then use a definition file to define the symbols to be exported from the DLL.
CAVEAT: The definition file approach works bests for undecorated symbol names. If you want to export decorated symbols then it is probably better to NOT USE the definition file approach.
Here is an simple example on how this is done.
Step 1: Define the function in the export.h file.
int WINAPI IsolatedFunction(const char *title, const char *test);
Step 2: Define the function in the export.cpp file.
#include <windows.h>
int WINAPI IsolatedFunction(const char *title, const char *test)
{
MessageBox(0, title, test, MB_OK);
return 1;
}
Step 3: Define the function as an export in the export.def defintion file.
EXPORTS IsolatedFunction @1
Step 4: Create a DLL project and add the export.cpp and export.def files to this project. Building this project will create an export.dll and an export.lib file.
The following two steps link to the DLL at link time. If you don't want to define the entry points at link time, ignore the next two steps and use the LoadLibrary and GetProcAddress to load the function entry point at runtime.
Step 5: Create a Test application project to use the dll by adding the export.lib file to the project. Copy the export.dll file to ths same location as the Test console executable.
Step 6: Call the IsolatedFunction function from within the Test application as shown below.
#include "stdafx.h"
// get the function prototype of the imported function
#include "../export/export.h"
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// call the imported function found in the dll
int result = IsolatedFunction("hello", "world");
return 0;
}
In Tomcat 7 with these changes, i'm able to access myAPP
at /
and ROOT
at /ROOT
<Context path="" docBase="myAPP"/>
<Context path="ROOT" docBase="ROOT"/>
Add above to the <Host>
section in server.xml
What's happening is Chart.js multiplies the size of the canvas when it is called then attempts to scale it back down using CSS, the purpose being to provide higher resolution graphs for high-dpi devices.
The problem is it doesn't realize it has already done this, so when called successive times, it multiplies the already (doubled or whatever) size AGAIN until things start to break. (What's actually happening is it is checking whether it should add more pixels to the canvas by changing the DOM attribute for width and height, if it should, multiplying it by some factor, usually 2, then changing that, and then changing the css style attribute to maintain the same size on the page.)
For example, when you run it once and your canvas width and height are set to 300, it sets them to 600, then changes the style attribute to 300... but if you run it again, it sees that the DOM width and height are 600 (check the other answer to this question to see why) and then sets it to 1200 and the css width and height to 600.
Not the most elegant solution, but I solved this problem while maintaining the enhanced resolution for retina devices by simply setting the width and height of the canvas manually before each successive call to Chart.js
var ctx = document.getElementById("canvas").getContext("2d");
ctx.canvas.width = 300;
ctx.canvas.height = 300;
var myDoughnut = new Chart(ctx).Doughnut(doughnutData);
If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:
PARAMETERS SomeParam Text(10);
SELECT Field FROM Table
WHERE OtherField=SomeParam
You can also say:
CREATE PROCEDURE ProcedureName
(Parameter1 datatype, Parameter2 datatype) AS
SQLStatement
From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs
Note that the procedure contains only one statement.
This is typically because you have not set the origin alias on your Git repository.
Try
git remote add origin URL_TO_YOUR_REPO
This will add an alias in your .git/config
file for the remote clone/push/pull site URL. This URL can be found on your repository Overview page.
Use this line of code when scanning the second value:
scanf(" %lf", &b);
also replace all %ld with %lf.
It's a problem related with input stream buffer. You can also use fflush(stdin); after the first scanning to clear the input buffer and then the second scanf will work as expected. An alternate way is place a getch(); or getchar(); function after the first scanf line.
File sutest
#!/bin/bash
echo "uid is ${UID}"
echo "user is ${USER}"
echo "username is ${USERNAME}"
run it: `./sutest' gives me
uid is 500
user is stephenp
username is stephenp
but using sudo: sudo ./sutest
gives
uid is 0
user is root
username is stephenp
So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:
#!/bin/bash
sudo -u ${USERNAME} normal_command_1
root_command_1
root_command_2
sudo -u ${USERNAME} normal_command_2
# etc.
Just sudo to invoke your script in the first place, it will prompt for the password once.
I originally wrote this answer on Linux, which does have some differences with OS X
OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER
when you're running sudo, which can be used in place of USERNAME
above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.
Changing the original script for OS X, it becomes...
#!/bin/bash
sudo -u ${SUDO_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${SUDO_USER} normal_command_2
# etc.
A first stab at making it cross-platform could be...
#!/bin/bash
#
# set "THE_USER" to SUDO_USER if that's set,
# else set it to USERNAME if THAT is set,
# else set it to the string "unknown"
# should probably then test to see if it's "unknown"
#
THE_USER=${SUDO_USER:-${USERNAME:-unknown}}
sudo -u ${THE_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${THE_USER} normal_command_2
# etc.
CPU stack and heap are physically related to how CPU and registers works with memory, how machine-assembly language works, not high-level languages themselves, even if these languages can decide little things.
All modern CPUs work with the "same" microprocessor theory: they are all based on what's called "registers" and some are for "stack" to gain performance. All CPUs have stack registers since the beginning and they had been always here, way of talking, as I know. Assembly languages are the same since the beginning, despite variations... up to Microsoft and its Intermediate Language (IL) that changed the paradigm to have a OO virtual machine assembly language. So we'll be able to have some CLI/CIL CPU in the future (one project of MS).
CPUs have stack registers to speed up memories access, but they are limited compared to the use of others registers to get full access to all the available memory for the processus. It why we talked about stack and heap allocations.
In summary, and in general, the heap is hudge and slow and is for "global" instances and objects content, as the stack is little and fast and for "local" variables and references (hidden pointers to forget to manage them).
So when we use the new keyword in a method, the reference (an int) is created in the stack, but the object and all its content (value-types as well as objects) is created in the heap, if I remember. But local elementary value-types and arrays are created in the stack.
The difference in memory access is at the cells referencing level: addressing the heap, the overall memory of the process, requires more complexity in terms of handling CPU registers, than the stack which is "more" locally in terms of addressing because the CPU stack register is used as base address, if I remember.
It is why when we have very long or infinite recurse calls or loops, we got stack overflow quickly, without freezing the system on modern computers...
C# Heap(ing) Vs Stack(ing) In .NET
Stack vs Heap: Know the Difference
Static class memory allocation where it is stored C#
What and where are the stack and heap?
https://en.wikipedia.org/wiki/Memory_management
https://en.wikipedia.org/wiki/Stack_register
Assembly language resources:
Intel® 64 and IA-32 Architectures Software Developer Manuals
The direct cast var ListOfY = (List<Y>)ListOfX
is not possible because it would require co/contravariance of the List<T>
type, and that just can't be guaranteed in every case. Please read on to see the solutions to this casting problem.
While it seems normal to be able to write code like this:
List<Animal> animals = (List<Animal>) mammalList;
because we can guarantee that every mammal will be an animal, this is obviously a mistake:
List<Mammal> mammals = (List<Mammal>) animalList;
since not every animal is a mammal.
However, using C# 3 and above, you can use
IEnumerable<Animal> animals = mammalList.Cast<Animal>();
that eases the casting a little. This is syntactically equivalent to your one-by-one adding code, as it uses an explicit cast to cast each Mammal
in the list to an Animal
, and will fail if the cast is not successfull.
If you like more control over the casting / conversion process, you could use the ConvertAll
method of the List<T>
class, which can use a supplied expression to convert the items. It has the added benifit that it returns a List
, instead of IEnumerable
, so no .ToList()
is necessary.
List<object> o = new List<object>();
o.Add("one");
o.Add("two");
o.Add(3);
IEnumerable<string> s1 = o.Cast<string>(); //fails on the 3rd item
List<string> s2 = o.ConvertAll(x => x.ToString()); //succeeds
What about including the current directory in the search path?
ruby -I. main.rb
The meta cache control tag allows Web publishers to define how pages should be handled by caches. They include directives to declare what should be cacheable, what may be stored by caches, modifications of the expiration mechanism, and revalidation and reload controls.
The allowed values are:
Public - may be cached in public shared caches
Private - may only be cached in private cache
no-Cache - may not be cached
no-Store - may be cached but not archived
Please be careful about case sensitivity. Add the following meta tag in the source of your webpage. The difference in spelling at the end of the tag is either you use " /> = xml or "> = html.
<meta http-equiv="Cache-control" content="public">
<meta http-equiv="Cache-control" content="private">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Cache-control" content="no-store">
Source-> MetaTags
I ended up using label names containing the values for the case expressions as suggested by AjV Jsy. Anyway, I use CALL
instead of GOTO
to jump into the correct case block and GOTO :EOF
to jump back. The following sample code is a complete batch script illustrating the idea.
@ECHO OFF
SET /P COLOR="Choose a background color (type red, blue or black): "
2>NUL CALL :CASE_%COLOR% # jump to :CASE_red, :CASE_blue, etc.
IF ERRORLEVEL 1 CALL :DEFAULT_CASE # If label doesn't exist
ECHO Done.
EXIT /B
:CASE_red
COLOR CF
GOTO END_CASE
:CASE_blue
COLOR 9F
GOTO END_CASE
:CASE_black
COLOR 0F
GOTO END_CASE
:DEFAULT_CASE
ECHO Unknown color "%COLOR%"
GOTO END_CASE
:END_CASE
VER > NUL # reset ERRORLEVEL
GOTO :EOF # return from CALL
The following trick has worked for me:
Add the following property in pom.xml
. Make sure you use the fully qualified class name (i.e. with package name) which contains the main
method:
<properties>
<exec.mainClass>fully-qualified-class-name</exec.mainClass>
</properties>
Now from the terminal, trigger the following command:
mvn clean compile exec:java
NOTE You can pass further arguments via -Dexec.args="xxx"
flag.
I'm surprised nobody has mentioned the Yeoman generator angular-fullstack. It is the number one Yeoman community generator, with currently 1490 stars on the generator page vs Mean.js' 81 stars (admittedly not a fair comparison given how new MEANJS is). It is appears to be actively maintained and is in version 2.05 as I write this. Unlike MEANJS, it doesn't use Swig for templating. It can be scaffolded with passport built in.
Here's the strsplit
solution if s
is a vector:
> s <- c("TGAS_1121", "MGAS_1432")
> s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[2]))
> s1
[1] "1121" "1432"
How do I set up the basic authorization?
All you need to do is use -u, --user USER[:PASSWORD]
. Behind the scenes curl
builds the Authorization
header with base64 encoded credentials for you.
Example:
curl -u username:password -i -H 'Accept:application/json' http://example.com
Using:
SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
...will show you the ctn_no
value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:
SELECT t.ctn_no
FROM YOUR_TABLE t
WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
If you want to see the other column values associated with the duplicate, you'll want to use a self join:
SELECT x.*
FROM YOUR_TABLE x
JOIN (SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no
If you are using dynamic web project then make sure you have added the jar file as commons-logging-1.2.jar in "WebContent > WEB-INF > lib" folder.
Along with you can do few more step as:
Right click on project > Properties > Targeted Runtimes > Choose Apache Tomcat server from list > Apply > Ok.
Go to Servers tab > Right click on server configured > Properties > General > Switch location(eg- /Servers/Tomcat/.....) > Apply > Ok.
That's all!
Why don't you try this
for(int i=0; i < dt.Rows.Count; i++)
{
// u can use here the i
}
Add in numberOfRowsInSection your code [self.tableView setContentInset:UIEdgeInsetsMake(108, 0, 0, 0)];
. So you will set your contentInset always you reload data in your table
I use div instead of tables and am able to target classes within the main class, as below:
.main {
.width: 800px;
.margin: 0 auto;
.text-align: center;
}
.main .table {
width: 80%;
}
.main .row {
/ ***something ***/
}
.main .column {
font-size: 14px;
display: inline-block;
}
.main .left {
width: 140px;
margin-right: 5px;
font-size: 12px;
}
.main .right {
width: auto;
margin-right: 20px;
color: #fff;
font-size: 13px;
font-weight: normal;
}
<div class="main">
<div class="table">
<div class="row">
<div class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:
.main #red { color: red; }
<div class="main">
<div class="table">
<div class="row">
<div id="red" class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
git log -n 1 [branch_name]
branch_name
(may be remote or local branch) is optional. Without branch_name
, it will show the latest commit on the current branch.
For example:
git log -n 1
git log -n 1 origin/master
git log -n 1 some_local_branch
git log -n 1 --pretty=format:"%H" #To get only hash value of commit
the prototype way
<div id="sub1" title="some text on mouse over">some text</div>
<script type="text/javascript">//<![CDATA[
$("sub1").observe("mouseover", function() {
alert(this.readAttribute("title"));
});
//]]></script>
include Prototype Lib for testing
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js"></script>
The opposite of read
is show
.
Prelude> show 3
"3"
Prelude> read $ show 3 :: Int
3
Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.
class Point2D {
double X, Y;
public Point2D(double x, double y) {
init(x, y);
}
public Point2D(Point2D point) {
if (point == null)
throw new ArgumentNullException("point");
init(point.X, point.Y);
}
void init(double x, double y) {
// ... Contracts ...
X = x;
Y = y;
}
}
With a simple JSON object, you don't need jQuery:
for (var i in json) {
for (var j in json[i]) {
console.log(json[i][j]);
}
}
You need to put the .jar file into your classpath when compiling/running your code. Then you just use standard imports of the classes in the .jar.
In my case:
-console.log() // works
-console.error() // works
-app.use(logger('dev')) // Morgan is NOT logging requests that look like "GET /myURL 304 9.072 ms - -"
FIX: I was using Visual Studio code, and I had to add this to my Launch Config
"outputCapture": "std"
Suggestion, in case you are running from an IDE, run directly from the command line to make sure the IDE is not causing the problem.
You can define instance method for js class, via prototype of the constructor.
Following is the sample code:
// BaseClass
var BaseClass = function(name) {
// instance property
this.name = name;
};
// instance method
BaseClass.prototype.getName = function() {
return this.name;
};
BaseClass.prototype.setName = function(name) {
return this.name = name;
};
// test - start
function test() {
var b1 = new BaseClass("b1");
var b2 = new BaseClass("b2");
console.log(b1.getName());
console.log(b2.getName());
b1.setName("b1_new");
console.log(b1.getName());
console.log(b2.getName());
}
test();
// test - end
And, this should work for any browser, you can also simply use nodejs to run this code.
I guess MySQL doesn't believe this to be valid UTF8 text. I tried an insert on a test table with the same column definition (mysql client connection was also UTF8) and although it did the insert, the data I retrieved with the MySQL CLI client as well as JDBC didn't retrieve the values correctly. To be sure UTF8 did work correctly, I inserted an "ö" instead of an "o" for obama:
johan@maiden:~$ mysql -vvv test < insert.sql
--------------
insert into utf8_test values(_utf8 "walmart öbama ")
--------------
Query OK, 1 row affected, 1 warning (0.12 sec)
johan@maiden:~$ file insert.sql
insert.sql: UTF-8 Unicode text
Small java application to test with:
package test.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Test
{
public static void main(String[] args)
{
System.out.println("test string=" + "walmart öbama ");
String url = "jdbc:mysql://hostname/test?useUnicode=true&characterEncoding=UTF-8";
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection c = DriverManager.getConnection(url, "username", "password");
PreparedStatement p = c.prepareStatement("select * from utf8_test");
p.execute();
ResultSet rs = p.getResultSet();
while (!rs.isLast())
{
rs.next();
String retrieved = rs.getString(1);
System.out.println("retrieved=\"" + retrieved + "\"");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output:
johan@appel:~/workspaces/java/javatest/bin$ java test.sql.Test
test string=walmart öbama
retrieved="walmart öbama "
Also, I've tried the same insert with the JDBC connection and it threw the same exception you are getting. I believe this to be a MySQL bug. Maybe there's a bug report about such a situation already..
I needed to exclude an auditing @Aspect @Component from the app context but only for a few test classes. I ended up using @Profile("audit") on the aspect class; including the profile for normal operations but excluding it (don't put it in @ActiveProfiles) on the specific test classes.
You should set your domain for example: www.abi.wapka.mobi
, that is if you are using a wapka site.
Note that if you had a domain with wapka it won't work, so compare wapka with your site provider and text it.
# -*- coding: utf-8 -*-
is a Python 2 thing. In Python 3+, the default encoding of source files is already UTF-8 and that line is useless.
See: Should I use encoding declaration in Python 3?
pyupgrade
is a tool you can run on your code to remove those comments and other no-longer-useful leftovers from Python 2, like having all your classes inherit from object
.
I made a comparison between a ReadAllText and StreamBuffer for a 2Mb csv and it seemed that the difference was quite small but ReadAllText seemed to take the upper hand from the times taken to complete functions.
Spring data has a Pair and can be used like below,
Pair<S, T> pair = Pair.of(S type data, T type data)
Facelets is a XML based view technology. The &
is a special character in XML representing the start of an entity like &
which ends with the ;
character. You'd need to either escape it, which is ugly:
rendered="#{beanA.prompt == true && beanB.currentBase != null}"
or to use the and
keyword instead, which is preferred as to readability and maintainability:
rendered="#{beanA.prompt == true and beanB.currentBase != null}"
Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true
:
rendered="#{beanA.prompt and beanB.currentBase != null}"
If you cannot use RowCounter
for whatever reason, then a combination of these two filters should be an optimal way to get a count:
FirstKeyOnlyFilter() AND KeyOnlyFilter()
The FirstKeyOnlyFilter
will result in the scanner only returning the first column qualifier it finds, as opposed to the scanner returning all of the column qualifiers in the table, which will minimize the network bandwith. What about simply picking one column qualifier to return? This would work if you could guarentee that column qualifier exists for every row, but if that is not true then you would get an inaccurate count.
The KeyOnlyFilter
will result in the scanner only returning the column family, and will not return any value for the column qualifier. This further reduces the network bandwidth, which in the general case wouldn't account for much of a reduction, but there can be an edge case where the first column picked by the previous filter just happens to be an extremely large value.
I tried playing around with scan.setCaching
but the results were all over the place. Perhaps it could help.
I had 16 million rows in between a start and stop that I did the following pseudo-empirical testing:
With FirstKeyOnlyFilter and KeyOnlyFilter activated: With caching not set (i.e., the default value), it took 188 seconds. With caching set to 1, it took 188 seconds With caching set to 10, it took 200 seconds With caching set to 100, it took 187 seconds With caching set to 1000, it took 183 seconds. With caching set to 10000, it took 199 seconds. With caching set to 100000, it took 199 seconds. With FirstKeyOnlyFilter and KeyOnlyFilter disabled: With caching not set, (i.e., the default value), it took 309 seconds
I didn't bother to do proper testing on this, but it seems clear that the FirstKeyOnlyFilter
and KeyOnlyFilter
are good.
Moreover, the cells in this particular table are very small - so I think the filters would have been even better on a different table.
Here is a Java code sample:
import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.filter.RowFilter; import org.apache.hadoop.hbase.filter.KeyOnlyFilter; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp; import org.apache.hadoop.hbase.filter.RegexStringComparator; public class HBaseCount { public static void main(String[] args) throws IOException { Configuration config = HBaseConfiguration.create(); HTable table = new HTable(config, "my_table"); Scan scan = new Scan( Bytes.toBytes("foo"), Bytes.toBytes("foo~") ); if (args.length == 1) { scan.setCaching(Integer.valueOf(args[0])); } System.out.println("scan's caching is " + scan.getCaching()); FilterList allFilters = new FilterList(); allFilters.addFilter(new FirstKeyOnlyFilter()); allFilters.addFilter(new KeyOnlyFilter()); scan.setFilter(allFilters); ResultScanner scanner = table.getScanner(scan); int count = 0; long start = System.currentTimeMillis(); try { for (Result rr = scanner.next(); rr != null; rr = scanner.next()) { count += 1; if (count % 100000 == 0) System.out.println(count); } } finally { scanner.close(); } long end = System.currentTimeMillis(); long elapsedTime = end - start; System.out.println("Elapsed time was " + (elapsedTime/1000F)); } }
Here is a pychbase code sample:
from pychbase import Connection c = Connection() t = c.table('my_table') # Under the hood this applies the FirstKeyOnlyFilter and KeyOnlyFilter # similar to the happybase example below print t.count(row_prefix="foo")
Here is a Happybase code sample:
from happybase import Connection c = Connection(...) t = c.table('my_table') count = 0 for _ in t.scan(filter='FirstKeyOnlyFilter() AND KeyOnlyFilter()'): count += 1 print count
Thanks to @Tuckr and @KennyCason for the tip.
The comp.lang.c FAQ deals with the question
"What's the correct declaration of main()?"in Question 11.12a.
A keystore contains private keys, and the certificates with their corresponding public keys.
A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.
Try
<script>
function toggleTable()
{
var status = document.getElementById("loginTable").style.display;
if (status == 'block') {
document.getElementById("loginTable").style.display="none";
} else {
document.getElementById("loginTable").style.display="block";
}
}
</script>
The calls that you need to make against Nexus are REST api calls.
The maven-nexus-plugin is a Maven plugin that you can use to make these calls. You could create a dummy pom with the necessary properties and make those calls through the Maven plugin.
Something like:
mvn -DserverAuthId=sonatype-nexus-staging -Dauto=true nexus:staging-close
Assumed things:
Ultimately, all this is doing is creating REST calls into Nexus. There is a full Nexus REST api but I have had little luck finding documentation for it that's not behind a paywall. You can turn on the debug mode for the plugin above and figure it out however by using -Dnexus.verboseDebug=true -X
.
You could also theoretically go into the UI, turn on the Firebug Net panel, and watch for /service POSTs and deduce a path there as well.
Like Nathan, I often want to dump the results of a sqlalchemy or sqlsoup Query into a Pandas data frame. My own solution for this is:
query = session.query(tbl.Field1, tbl.Field2)
DataFrame(query.all(), columns=[column['name'] for column in query.column_descriptions])
using varchar is pretty inefficient. use the money type and create a user declared type "phonenumber" out of it, and create a rule to only allow positive numbers.
if you declare it as (19,4) you can even store a 4 digit extension and be big enough for international numbers, and only takes 9 bytes of storage. Also, indexes are speedy.
Dispose()
context create problems if the entities you Add()
rely on other preloaded entities (e.g. navigation properties) in the context
I use similar concept to keep my context small to achieve the same performance
But instead of Dispose()
the context and recreate, I simply detach the entities that already SaveChanges()
public void AddAndSave<TEntity>(List<TEntity> entities) where TEntity : class {
const int CommitCount = 1000; //set your own best performance number here
int currentCount = 0;
while (currentCount < entities.Count())
{
//make sure it don't commit more than the entities you have
int commitCount = CommitCount;
if ((entities.Count - currentCount) < commitCount)
commitCount = entities.Count - currentCount;
//e.g. Add entities [ i = 0 to 999, 1000 to 1999, ... , n to n+999... ] to conext
for (int i = currentCount; i < (currentCount + commitCount); i++)
_context.Entry(entities[i]).State = System.Data.EntityState.Added;
//same as calling _context.Set<TEntity>().Add(entities[i]);
//commit entities[n to n+999] to database
_context.SaveChanges();
//detach all entities in the context that committed to database
//so it won't overload the context
for (int i = currentCount; i < (currentCount + commitCount); i++)
_context.Entry(entities[i]).State = System.Data.EntityState.Detached;
currentCount += commitCount;
} }
wrap it with try catch and TrasactionScope()
if you need,
not showing them here for keeping the code clean
Try this:
SELECT GETDATE(), 'Today'
UNION ALL
SELECT DATEADD(DAY, 10, GETDATE()), '10 Days Later'
UNION ALL
SELECT DATEADD(DAY, –10, GETDATE()), '10 Days Earlier'
UNION ALL
SELECT DATEADD(MONTH, 1, GETDATE()), 'Next Month'
UNION ALL
SELECT DATEADD(MONTH, –1, GETDATE()), 'Previous Month'
UNION ALL
SELECT DATEADD(YEAR, 1, GETDATE()), 'Next Year'
UNION ALL
SELECT DATEADD(YEAR, –1, GETDATE()), 'Previous Year'
Result Set:
———————– —————
2011-05-20 21:11:42.390 Today
2011-05-30 21:11:42.390 10 Days Later
2011-05-10 21:11:42.390 10 Days Earlier
2011-06-20 21:11:42.390 Next Month
2011-04-20 21:11:42.390 Previous Month
2012-05-20 21:11:42.390 Next Year
2010-05-20 21:11:42.390 Previous Year
As of Json.NET 4.0 Release 1, there is native dynamic support:
[Test]
public void DynamicDeserialization()
{
dynamic jsonResponse = JsonConvert.DeserializeObject("{\"message\":\"Hi\"}");
jsonResponse.Works = true;
Console.WriteLine(jsonResponse.message); // Hi
Console.WriteLine(jsonResponse.Works); // True
Console.WriteLine(JsonConvert.SerializeObject(jsonResponse)); // {"message":"Hi","Works":true}
Assert.That(jsonResponse, Is.InstanceOf<dynamic>());
Assert.That(jsonResponse, Is.TypeOf<JObject>());
}
And, of course, the best way to get the current version is via NuGet.
Updated (11/12/2014) to address comments:
This works perfectly fine. If you inspect the type in the debugger you will see that the value is, in fact, dynamic. The underlying type is a JObject
. If you want to control the type (like specifying ExpandoObject
, then do so.
follow the below steps in Intellij (with screenshots for better understanding):
navigate to modules and now select the module, in which your Junit test file present and select "Use module compile output path" radio button.
Mention the respective classes folder path, similar to the screenshot attached.
Referring to the first thread / another possibility VS cant open or find pdb file of the process is when you have your executable running in the background. I was working with mpiexec and ran into this issue. Always check your task manager and kill any exec process that your gonna build in your project. Once I did that, it debugged or built fine.
Also, if you try to continue with the warning , the breakpoints would not be hit and it would not have the current executable
A short answer is NO...
JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
Look at the reason why:
When exchanging data between a browser and a server, the data can only be text.
JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.
We can also convert any JSON received from the server into JavaScript objects.
This way we can work with the data as JavaScript objects, with no complicated parsing and translations.
But wait...
There is still ways to store your function, it's widely not recommended to that, but still possible:
We said, you can save a string
... how about converting your function to a string then?
const data = {func: '()=>"a FUNC"'};
Then you can stringify data using JSON.stringify(data)
and then using JSON.parse
to parse it (if this step needed)...
And eval to execute a string function (before doing that, just let you know using eval widely not recommended):
eval(data.func)(); //return "a FUNC"
If you are using Microsoft Drivers 3.1, 3.0, and 2.0.
Please check your PHP version already install with IIS.
Use this script to check the php version:
<?php echo phpinfo(); ?>
OR
If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.
Then:
If you are using new PHP version (5.6) please download Drivers from here
For PHP version Lower than 5.6 - please download Drivers from here
Then use the PHP Manager to add that downloaded drivers into php config
file.You can do it as shown below (browse the files and press OK).
Then Restart the IIS Server
If this method not work please change the php version and try to run your php script.
Tip:Change the php version
to lower and try to understand what happened.then you can download relevant drivers.
You mentioned that PHP solutions were acceptable, and PHP does offer a way to accomplish this even though it only supports XPath v1.0. You can extend the XPath support to allow PHP function calls.
$xpathObj = new DOMXPath($docObj);
$xpathObj->registerNamespace('php','http://php.net/xpath'); // (required)
$xpathObj->registerPhpFunctions("strtolower"); // (leave empty to allow *any* PHP function)
$xpathObj->query('//CD[php:functionString("strtolower",@title) = "empire burlesque"]');
See the PHP registerPhpFunctions documentation for more examples. It basically demonstrates that "php:function" is for boolean evaluation and "php:functionString" is for string evaluation.
Tried all of the options above. What worked for me was:
Domain
Path=/
Resulting Set-Cookie
header:
Set-Cookie: session_token=74528588-7c48-4546-a3ae-4326e22449e5; Expires=Sun, 16 Aug 2020 04:40:42 GMT; Path=/
You can use map
function
{Object.keys(tifs).map(key => (
<option value={key}>{tifs[key]}</option>
))}
If you don't know the position of the item, you may need to find the index first:
old_index = list1.index(item)
then move it:
list1.insert(new_index, list1.pop(old_index))
or IMHO a cleaner way:
try:
list1.remove(item)
list1.insert(new_index, item)
except ValueError:
pass
You can use:ls -lh
, then you will get a list of file information
Retrieves the full path of a known folder identified by the folder's
KNOWNFOLDERID
.
And, FOLDERID_CommonStartup
:
Default Path
%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp
There are also managed equivalents, but you haven't told us what you're programming in.
I'm surprised that the realpath
command hasn't been mentioned here. My understanding is that it is widely portable / ported.
Your initial solution becomes:
SCRIPT=`realpath $0`
SCRIPTPATH=`dirname $SCRIPT`
And to leave symbolic links unresolved per your preference:
SCRIPT=`realpath -s $0`
SCRIPTPATH=`dirname $SCRIPT`
When doing a clean HTML Structure, you can use this.
//Jquery Code_x000D_
$('a#link_1').click(function(e){_x000D_
e . preventDefault () ;_x000D_
var a = e . target ;_x000D_
window . open ( '_top' , a . getAttribute ('href') ) ;_x000D_
});_x000D_
_x000D_
//Normal Code_x000D_
element = document . getElementById ( 'link_1' ) ;_x000D_
element . onClick = function (e) {_x000D_
e . preventDefault () ;_x000D_
_x000D_
window . open ( '_top' , element . getAttribute ('href') ) ;_x000D_
} ;
_x000D_
<a href="#Foo" id="link_1">Do it!</a>
_x000D_
Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement),
SecondList.OrderBy(sElement => sElement))
If you are using moment.js you can do it easily.
var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");
//Difference in number of days
moment.duration(start.diff(end)).asDays();
//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();
If you want to find difference between a given date and current date in number of days (ignoring time), make sure to remove time from moment object of current date as below
moment().startOf('day')
To find difference between a given date and current date in number of days
var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');
//Difference in number of days
moment.duration(given.diff(current)).asDays();
In WSDL, if you look at the Binding section, you will clearly see that soap binding is explicitly mentioned if the service uses soap 1.2. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="findEmployeeById">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation><operation name="create">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation>
</binding>
if the web service use soap 1.1, it will not explicitly define any soap version in the WSDL file under binding section. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
<operation name="findEmployeeById">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation><operation name="create">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation>
</binding>
How to determine the SOAP version of the SOAP message?
but remember that this is not much recommended way to determine the soap version that your web services uses. the version of the soap message can be determined using one of following ways.
1. checking the namespace of the soap message
SOAP 1.1 namespace : http://schemas.xmlsoap.org/soap/envelope
SOAP 1.2 namespace : http://www.w3.org/2003/05/soap-envelope
2. checking the transport binding information (http header information) of the soap message
SOAP 1.1 : user text/xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: text/xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
SOAP 1.2 : user application/soap+xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: application/soap+xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
3. using SOAP fault information
The structure of a SOAP fault message between the two versions are different.
This error can appear on the client if there is a problem on the server side. For example, if the SOAP server is a PHP script with a parse error, the client will fail with this message.
If you are in control of the server, tail your Apache error_log on the machine that hosts the SOAP server. On CentOS you will find this in /var/log/httpd/error_log, so the command is:
tail -f /var/log/httpd/error_log
Now refresh the client and watch for the error message. Any PHP errors with the server script will be shown.
Hope that helps someone.
Anyone trying to do this in the ESRI GIS Table field calculator interface can do this with the Python parser:
PathToContainingFolder =
"\\".join(!FullFilePathWithFileName!.split("\\")[0:-1])
so that
\Users\me\Desktop\New folder\file.txt
becomes
\Users\me\Desktop\New folder
YourButton.Attributes.Add("onclick", "return false");
or
<asp:button runat="server" ... OnClientClick="return false" />
The following work for me
for the mongoose
version 5.9.16
const mongoose = require('mongoose');
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
mongoose.connect('mongodb://localhost:27017/dbName')
.then(() => console.log('Connect to MongoDB..'))
.catch(err => console.error('Could not connect to MongoDB..', err))
In case you want to sort dates with descending order the minus sign doesn't work with Dates.
out <- DF[rev(order(as.Date(DF$end))),]
However you can have the same effect with a general purpose function: rev(). Therefore, you mix rev and order like:
#init data
DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/09 12:00', '6/1/10 14:20', '1/1/11 11:10')
#change order
out <- DF[rev(order(as.Date(DF$end))),]
Hope it helped.
Like this
DECLARE @date DATETIME
SET @date = '2011-09-28 18:01:00'
select convert(varchar, @date,105) + ' ' + convert(varchar, @date,108)
The minimum requirements are based on the Express edition you're attempting to install:
Express for Web (Web sites and HTML5 applications) - Windows 7 SP1 (With IE 10)
Express for Windows (Windows 8 Apps) - Windows 8.1
Express for Windows Desktop (Windows Programs) - Windows 7 SP1 (With IE 10)
Express for Windows Phone (Windows Phone Apps) - Windows 8
It sounds like you're trying to install the "Express 2013 for Windows" edition, which is for developing Windows 8 "Modern UI" apps, or the Windows Phone edition.
The similarly named version that is compatible with Windows 7 SP1 is "Express 2013 for Windows Desktop"
An optional prefix
!
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
http://schacon.github.com/git/gitignore.html
*.json
!spec/*.json
You can use format strings as well.
string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros
or some shortcuts if the format works for you
string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();
Either should work.
Action Definition
const selectSlice = () => {
return {
type: 'SELECT_SLICE'
}
};
Action Dispatch
store.dispatch({
type:'SELECT_SLICE'
});
Make sure the object structure of action defined is same as action dispatched. In my case, while dispatching action, type was not assigned to property type
.
Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.
If you are using lodash or underscore the _.countBy method will provide an object of aggregate totals keyed by each value in the array. You can turn this into a one-liner if you only need to count one value:
_.countBy(['foo', 'foo', 'bar'])['foo']; // 2
This also works fine on arrays of numbers. The one-liner for your example would be:
_.countBy([1, 2, 3, 5, 2, 8, 9, 2])[2]; // 3
These answers are totally my opinion
Picasso is an easy to use image loader, same goes for Imageloader. Fresco uses a different approach to image loading, i haven't used it yet but it looks too me more like a solution for getting image from network and caching them then showing the images. then the other way around like Picasso/Imageloader/Glide which to me are more Showing image on screen that also does getting images from network and caching them.
Glide tries to be somewhat interchangeable with Picasso.I think when they were created Picasso's mind set was follow HTTP spec's and let the server decide the caching policies and cache full sized and resize on demand. Glide is the same with following the HTTP spec but tries to have a smaller memory footprint by making some different assumptions like cache the resized images instead of the fullsized images, and show images with RGB_565 instead of RGB_8888. Both libraries offer full customization of the default settings.
As to which library is the best to use is really hard to say. Picasso, Glide and Imageloader are well respected and well tested libraries which all are easy to use with the default settings. Both Picasso and Glide require only 1 line of code to load an image and have a placeholder and error image. Customizing the behaviour also doesn't require that much work. Same goes for Imageloader which is also an older library then Picasso and Glide, however I haven't used it so can't say much about performance/memory usage/customizations but looking at the readme on github gives me the impression that it is also relatively easy to use and setup. So in choosing any of these 3 libraries you can't make the wrong decision, its more a matter of personal taste. For fresco my opinion is that its another facebook library so we have to see how that is going to work out for them, so far there track record isn't that good. Like the facebook SDK is still isn't officially released on mavenCentral I have not used to facebook sdk since sept 2014 and it seems they have put the first version online on mavenCentral in oct 2014. So it will take some time before we can get any good opinion about it.
between the 3 big name libraries I think there are no significant differences. The only one that stand out is fresco but that is because it has a different approach and is new and not battle tested.
If you don't have another time interval bigger than days:
int days = (int) (milliseconds / (1000*60*60*24));
If you have weeks too:
int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
int weeks = (int) (milliseconds / (1000*60*60*24*7));
It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.
I recently worked on a project to read the RFID tags. The project used the Devices from manufacturers like Zebra (we were using RFD8500 ) & TSL.
More devices are from Motorola & other vendors as well!
We have to use the native SDK api's provided by the manufacturer, how it works is by pairing the device by the Bluetooth of the phones and so the data transfer between both devices take place! The programming is based on subscribe pattern where the scan should be read by the device trigger(hardware trigger) or soft trigger (from the application).
The Tag read gives us the tagId & the RSSI which is the distance factor from the RFID tags!
This is the sample app:
We get all the device paired to our Android/iOS phones :
There is special method:
a.unshift(value);
But if you want to prepend several elements to array it would be faster to use such a method:
var a = [1, 2, 3],
b = [4, 5];
function prependArray(a, b) {
var args = b;
args.unshift(0);
args.unshift(0);
Array.prototype.splice.apply(a, args);
}
prependArray(a, b);
console.log(a); // -> [4, 5, 1, 2, 3]
Just go to web.config file and add following
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="Path of your Page" />
</files>
</defaultDocument>
</system.webServer>
For Spring Users , Spring Security has a Base64 class in the org.springframework.security.crypto.codec
package that can also be used for encoding and decoding of Base64.
Ex.
public static String base64Encode(String token) {
byte[] encodedBytes = Base64.encode(token.getBytes());
return new String(encodedBytes, Charset.forName("UTF-8"));
}
public static String base64Decode(String token) {
byte[] decodedBytes = Base64.decode(token.getBytes());
return new String(decodedBytes, Charset.forName("UTF-8"));
}
If you are using Chrome you can goto the "Resources" tab and find the item "Cookies" in the left sidebar. From there select the domain you are checking the set cookie for and it will give you a list of cookies associated with that domain, along with their expiration date.
If you need a simple working solution, try using DefaultTableModel.
If you have created your own table model, that extends AbstractTableModel, then you should also implement removeRow() method. The exact implementation depends on the underlying structure, that you have used to store data.
For example, if you have used Vector, then it may be something like this:
public class SimpleTableModel extends AbstractTableModel {
private Vector<String> columnNames = new Vector<String>();
// Each value in the vector is a row; String[] - row data;
private Vector<String[]> data = new Vector<String[]>();
...
public String getValueAt(int row, int col) {
return data.get(row)[col];
}
...
public void removeRow(int row) {
data.removeElementAt(row);
}
}
If you have used List, then it would be very much alike:
// Each item in the list is a row; String[] - row data;
List<String[]> arr = new ArrayList<String[]>();
public void removeRow(int row) {
data.remove(row);
}
HashMap:
//Integer - row number; String[] - row data;
HashMap<Integer, String[]> data = new HashMap<Integer, String[]>();
public void removeRow(Integer row) {
data.remove(row);
}
And if you are using arrays like this one
String[][] data = { { "a", "b" }, { "c", "d" } };
then you're out of luck, because there is no way to dynamically remove elements from arrays. You may try to use arrays by storing separately some flags notifying which rows are deleted and which are not, or by some other devious way, but I would advise against it... That would introduce unnecessary complexity, and would in fact just be solving a problem by creating another. That's a sure-fire way to end up here. Try one of the above ways to store your table data instead.
For better understanding of how this works, and what to do to make your own model work properly, I strongly advise you to refer to Java Tutorial, DefaultTableModel API and it's source code.
Here is an example how to parse JSON response and even how to send a request with a bean in JSON form:
@Autowired
protected MockMvc mvc;
private static final ObjectMapper MAPPER = new ObjectMapper()
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(new JavaTimeModule());
public static String requestBody(Object request) {
try {
return MAPPER.writeValueAsString(request);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static <T> T parseResponse(MvcResult result, Class<T> responseClass) {
try {
String contentAsString = result.getResponse().getContentAsString();
return MAPPER.readValue(contentAsString, responseClass);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
public void testUpdate() {
Book book = new Book();
book.setTitle("1984");
book.setAuthor("Orwell");
MvcResult requestResult = mvc.perform(post("http://example.com/book/")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody(book)))
.andExpect(status().isOk())
.andReturn();
UpdateBookResponse updateBookResponse = parseResponse(requestResult, UpdateBookResponse.class);
assertEquals("1984", updateBookResponse.getTitle());
assertEquals("Orwell", updateBookResponse.getAuthor());
}
As you can see here the Book
is a request DTO and the UpdateBookResponse
is a response object parsed from JSON. You may want to change the Jackson's ObjectMapper
configuration.
I know this thread is old, but since a Google search brought me here, it will also do to other people who may find this useful.
Microsoft recenly launched Visual Studio Online, which is free for projects with up to 5 users:
http://www.visualstudio.com/en-us/products/visual-studio-online-overview-vs.aspx
I have been using it for a while, and it integrates completely with Visual Studio 2013. It claims integration with other IDEs too. Apart from TFS, Git can also be used with it.
I know this thread is old, but since a Google search brought me here
Here is the easiest way that I found after working on this:
string javascript = "alert('Hello');";
// or any combination of your JavaScript commands
// (including function calls, variables... etc)
// WebBrowser webBrowser1 is what you are using for your web browser
webBrowser1.Document.InvokeScript("eval", new object[] { javascript });
What global JavaScript function eval(str)
does is parses and executes whatever is written in str.
Check w3schools ref here.
curl: command not found
is a big hint, you have to install it with :
apt-get update; apt-get install curl
Another way in .Net 2.0
static void Main(string[] args)
{
List<string> alpha = new List<string>();
for(char a = 'a'; a <= 'd'; a++)
{
alpha.Add(a.ToString());
alpha.Add(a.ToString());
}
Console.WriteLine("Data :");
alpha.ForEach(delegate(string t) { Console.WriteLine(t); });
alpha.ForEach(delegate (string v)
{
if (alpha.FindAll(delegate(string t) { return t == v; }).Count > 1)
alpha.Remove(v);
});
Console.WriteLine("Unique Result :");
alpha.ForEach(delegate(string t) { Console.WriteLine(t);});
Console.ReadKey();
}
I've seen this exception before when whatever the JVM considers to be a temp directory is not accessible due to not being there or not having permission to write.
I have found a better way which works on Laravel 5.5 and makes variables accessible by views. And you can retrieve data from the database, do your logic by importing your Model just as you would in your controller.
The "*" means you are referencing all views, if you research more you can choose views to affect.
add in your app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Contracts\View\View;
use Illuminate\Support\ServiceProvider;
use App\Setting;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Fetch the Site Settings object
view()->composer('*', function(View $view) {
$site_settings = Setting::all();
$view->with('site_settings', $site_settings);
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
}
It is kind of screwy, but in a pinch you can use sed
or awk
to make small edits or remove text. Be careful with your regex targets of course and be aware that you're likely root
on your container and might have to re-adjust permissions.
For example, removing a full line that contains text matching a regex:
awk '!/targetText/' file.txt > temp && mv temp file.txt
If you don't need any file further, you can decorate the test method:
@patch('builtins.open', mock_open(read_data="data"))
def test_testme():
result = testeme()
assert result == "data"
You get this exact same error when trying to connect to a MySQL database from MS-Access when the bit version (32 vs 64) of Access doesn't match
For those of you trying to connect MS-Access to MySQL on a 64 bit Windows system, I went through sheer torture trying to get it to work with both MS-Access 2010 and MS-Access 2013. Finally got it working, and here are the lessons I've learned along the way:
I bought a new Windows 7, 64 bit laptop, and I have an app which relies on MS-Access using MySQL tables.
I installed the latest version of MySQL, 5.6, using the All In One package install. This allows you to install both the database and ODBC drivers all at once. That's nice, but the ODBC driver it installs seems to be the 64 bit one, so it will not work with 32 bit MS-Access. It also seems a little buggy - not for sure on that one. When you Add a new DSN in the ODBC Manager, this driver appears as "Microsoft ODBC For Oracle". I could not get this one to work. I had to install the 32 bit one, discussed below.
I had previously installed Office 2013, which I assumed was 64 bit. But upon checking the version (File, Account, About Access), I see that it is 32 bit. Both Access 2010 and 2013 are most commonly sold as 32-bit versions.
My machine is a 64 bit machine. So by default, when you go to set up your DSN's for MS-Access, and go in the usual way into the ODBC Manager via Control Panel, Administrative Options, you get the 64 bit ODBC manager. You have no way of knowing that! You just can't tell. This is a huge gotcha!! It is impossible to set up a DSN from there and have it successfully connect to MS Access 32 bit. You will get the dreaded error:
"the specified dsn contains an architecture mismatch..."
You must download and install the 32 bit ODBC driver from MySQL. I used version 3.5.1
You must tell the ODBC Manager in Control Panel to take a hike and must instead explicitly invoke the 32 bit ODBC Manager with this command executed at the Start, Command prompt:
c:\windows\sysWOW64\odbcad32.exe
I created a shortcut to this on my desktop. From here, build your DSN with this manager. Important point: BUILD THEM AS SYSTEM DSNS, NOT USER DSNS! This tripped me up for awhile.
By the way, the 64 bit version of the ODBC Manager can also be run explicitly as:
c:\windows\system32\odbcad32.exe
Once you've installed the 32-bit ODBC Driver from MySql, when you click Add in the ODBC Manager you will see 2 drivers listed. Choose "MySQL ODBC 5.2 ANSI Driver". I did not try the UNICODE driver.
That does it. Once you have defined your DSN's in the 32 bit ODBC manager, you can connect to MySQL in the usual way from within Access - External Data, ODBC Database, Link to the Database, select Machine Data Source, and the DSN you created to your MySQL database will be there.
You can do this is in many ways like:
1- You can use Wordpress global variable $post
:
<?php
global $post;
$post_slug=$post->post_name;
?>
2- Or you can get use:
$slug = get_post_field( 'post_name', get_post() );
3- Or get full url and then use the PHP function parse_url
:
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url_path = parse_url( $url, PHP_URL_PATH );
$slug = pathinfo( $url_path, PATHINFO_BASENAME );
I hope above methods will help you.
update YourTable
set YourColumn = replace(YourColumn, '@domain2', '@domain1')
where charindex('@domain2', YourColumn) <> 0
Yup, this is possible of course. Here are several examples.
-- one way to do this
DECLARE @Cnt int
SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn
-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)
-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double
SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable
I just changed project facet to 1.7 and it worked.
Yes this does work in PostgreSQL (assuming the column "date" is of datatype date
)
Why don't you just try it?
The standard ANSI SQL format would be:
SELECT Table.date
FROM Table
WHERE date > current_date - interval '10' day;
I prefer that format as it makes things easier to read (but it is the same as current_date - 10
).
For extracting the date from a string in Python; the best module available is the datefinder module.
You can use it in your Python project by following the easy steps given below.
pip install datefinder
import datefinder
input_string = "monkey 2010-07-10 love banana"
# a generator will be returned by the datefinder module. I'm typecasting it to a list. Please read the note of caution provided at the bottom.
matches = list(datefinder.find_dates(input_string))
if len(matches) > 0:
# date returned will be a datetime.datetime object. here we are only using the first match.
date = matches[0]
print date
else:
print 'No dates found'
note: if you are expecting a large number of matches; then typecasting to list won't be a recommended way as it will be having a big performance overhead.
There were a number of suggestions from an earlier similar question "Best way to test for existing string against a large list of comparables".
Regex might be sufficient for your requirement. The expression would be a concatenation of all the candidate substrings, with an OR "|
" operator between them. Of course, you'll have to watch out for unescaped characters when building the expression, or a failure to compile it because of complexity or size limitations.
Another way to do this would be to construct a trie data structure to represent all the candidate substrings (this may somewhat duplicate what the regex matcher is doing). As you step through each character in the test string, you would create a new pointer to the root of the trie, and advance existing pointers to the appropriate child (if any). You get a match when any pointer reaches a leaf.
It depends on what format your image files are in, but for a project here at work I used the tiff2pdf tool in LibTIFF from RemoteSensing.org. Basically just used subprocess to call tiff2pdf.exe with the appropriate argument to read the kind of tiff I had and output the kind of pdf I wanted. If they aren't tiffs you could probably convert them to tiffs using PIL, or maybe find a tool more specific to your image type (or more generic if the images will be diverse) like ReportLab mentioned above.
$ sudo rm -rf /Library/Developer/CommandLineTools
$ xcode-select --install
You can import the text file using the read_table command as so:
import pandas as pd
df=pd.read_table('output_list.txt',header=None)
Preprocessing will need to be done after loading
Created a handy function for this..
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
//Remove from array
array.splice(index, 1);
}
});
}
//Checks countries.result for an object with a property of 'id' whose value is 'AF'
//Then removes it ;p
findAndRemove(countries.results, 'id', 'AF');
A (dirty) possible solution is by using patterns,
here is an example with an inside stroked triangle :
https://jsfiddle.net/qr3p7php/5/
<style>
#triangle1{
fill: #0F0;
fill-opacity: 0.3;
stroke: #000;
stroke-opacity: 0.5;
stroke-width: 20;
}
#triangle2{
stroke: #f00;
stroke-opacity: 1;
stroke-width: 1;
}
</style>
<svg height="210" width="400" >
<pattern id="fagl" patternUnits="objectBoundingBox" width="2" height="1" x="-50%">
<path id="triangle1" d="M150 0 L75 200 L225 200 Z">
</pattern>
<path id="triangle2" d="M150 0 L75 200 L225 200 Z" fill="url(#fagl)"/>
</svg>
The input date value format needs the date specified as per http://tools.ietf.org/html/rfc3339#section-5.6 full-date.
So I've ended up doing:
<input type="date" id="last-start-date" value="@string.Format("{0:yyyy-MM-dd}", Model.LastStartDate)" />
I did try doing it "properly" using:
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime LastStartDate
{
get { return lastStartDate; }
set { lastStartDate = value; }
}
with
@Html.TextBoxFor(model => model.LastStartDate,
new { type = "date" })
Unfortunately that always seemed to set the value attribute of the input to a standard date time so I've ended up applying the formatting directly as above.
Edit:
According to Jorn if you use
@Html.EditorFor(model => model.LastStartDate)
instead of TextBoxFor it all works fine.
Define a behavior in your .config
file:
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="debug">
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
...
</system.serviceModel>
</configuration>
Then apply the behavior to your service along these lines:
<configuration>
<system.serviceModel>
...
<services>
<service name="MyServiceName" behaviorConfiguration="debug" />
</services>
</system.serviceModel>
</configuration>
You can also set it programmatically. See this question.
This is cut and pasted from some sample code I wrote, hopefully it should give the basics. It only supports File data and form-data at the moment.
public class PostData
{
private List<PostDataParam> m_Params;
public List<PostDataParam> Params
{
get { return m_Params; }
set { m_Params = value; }
}
public PostData()
{
m_Params = new List<PostDataParam>();
// Add sample param
m_Params.Add(new PostDataParam("email", "MyEmail", PostDataParamType.Field));
}
/// <summary>
/// Returns the parameters array formatted for multi-part/form data
/// </summary>
/// <returns></returns>
public string GetPostData()
{
// Get boundary, default is --AaB03x
string boundary = ConfigurationManager.AppSettings["ContentBoundary"].ToString();
StringBuilder sb = new StringBuilder();
foreach (PostDataParam p in m_Params)
{
sb.AppendLine(boundary);
if (p.Type == PostDataParamType.File)
{
sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
sb.AppendLine("Content-Type: text/plain");
sb.AppendLine();
sb.AppendLine(p.Value);
}
else
{
sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
sb.AppendLine();
sb.AppendLine(p.Value);
}
}
sb.AppendLine(boundary);
return sb.ToString();
}
}
public enum PostDataParamType
{
Field,
File
}
public class PostDataParam
{
public PostDataParam(string name, string value, PostDataParamType type)
{
Name = name;
Value = value;
Type = type;
}
public string Name;
public string FileName;
public string Value;
public PostDataParamType Type;
}
To send the data you then need to:
HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create(oURL.URL);
oRequest.ContentType = "multipart/form-data";
oRequest.Method = "POST";
PostData pData = new PostData();
byte[] buffer = encoding.GetBytes(pData.GetPostData());
// Set content length of our data
oRequest.ContentLength = buffer.Length;
// Dump our buffered postdata to the stream, booyah
oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();
// get the response
oResponse = (HttpWebResponse)oRequest.GetResponse();
Hope thats clear, i've cut and pasted from a few sources to get that tidier.
Well I had situation when web service returned a color in hex format like "#CC2233" and I wanted to put this color on textView by using setBackGroundColor(), so I used android Color class to get int value of hex string and passed it to mentioned function. Everything worked. This is example:
String myHexColor = "#CC2233";
TextView myView = (TextView) findViewById(R.id.myTextView);
myView.setBackGroundColor(Color.pasrsehexString(myHexColor));
P.S. posted this answer because other solutions didn't work for me. I hope this will help someone:)
The main issue with your example that you can't implicitly convert Task<T>
return types to the base T
type. You need to use the Task.Result property. Note that Task.Result will block async code, and should be used carefully.
Try this instead:
public List<int> TestGetMethod()
{
return GetIdList().Result;
}
I have two Java versions on my Ubuntu server 14.04: java 1.7
and java 1.8
.
I have a project that I need to build using java 1.8
.
If I check my Java version using java -version
I get
java version "1.8.0_144"
But when I did mvn -version
I get:
Java version: 1.7.0_79, vendor: Oracle Corporation
java8
I do this:
export JAVA_HOME=/usr/lib/jvm/java-8-oracle/jre/
Then when I do mvn -version
I get:
Java version: 1.8.0_144, vendor: Oracle Corporation
Open the file in src->router->index.js
At the bottom of this file:
const router = new VueRouter({
mode: "history",
routes,
});
If your matrix is called m
, just use :
R> m[m$three == 11, ]
Python with PHP flavor:
def is_array(var):
return isinstance(var, (list, tuple))
In other words...
IDE Even your notepad is an IDE. Every software you write/compile code with is an IDE.
Library A bunch of code which simplifies functions/methods for quick use.
API A programming interface for functions/configuration which you work with, its usage is often documented.
SDK Extras and/or for development/testing purposes.
ToolKit Tiny apps for quick use, often GUIs.
GUI Apps with a graphical interface, requires no knowledge of programming unlike APIs.
Framework Bunch of APIs/huge Library/Snippets wrapped in a namespace/or encapsulated from outer scope for compact handling without conflicts with other code.
MVC
A design pattern separated in Models, Views and Controllers for huge applications. They are not dependent on each other and can be changed/improved/replaced without to take care of other code.
Example:
Car (Model)
The object that is being presented.
Example in IT: A HTML form.
Camera (View)
Something that is able to see the object(car).
Example in IT: Browser that renders a website with the form.
Driver (Controller)
Someone who drives that car.
Example in IT: Functions which handle form data that's being submitted.
Snippets Small codes of only a few lines, may not be even complete but worth for a quick share.
Plug-ins Exclusive functions for specified frameworks/APIs/libraries only.
Add-ons Additional modules or services for specific GUIs.
The reason you separate the login and non-login shell is because the .bashrc
file is reloaded every time you start a new copy of Bash. The .profile
file is loaded only when you either log in or use the appropriate flag to tell Bash to act as a login shell.
Personally,
PATH
setup into a .profile
file (because I sometimes use other shells);.bashrc
file;I put this
#!/bin/bash
#
# CRM .bash_profile Time-stamp: "2008-12-07 19:42"
#
# echo "Loading ${HOME}/.bash_profile"
source ~/.profile # get my PATH setup
source ~/.bashrc # get my Bash aliases
in my .bash_profile
file.
Oh, and the reason you need to type bash
again to get the new alias is that Bash loads your .bashrc
file when it starts but it doesn't reload it unless you tell it to. You can reload the .bashrc
file (and not need a second shell) by typing
source ~/.bashrc
which loads the .bashrc
file as if you had typed the commands directly to Bash.
Delete your name macro and build again. I did this, and the macro worked.
The command is lowercase: touch filename
.
Keep in mind that touch
will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch
If you always want an empty file, one way to do so would be to use:
echo "" > filename
Here, in this post you will find the detailed code for establishing socket between devices or between two application in the same mobile.
You have to create two application to test below code.
In both application's manifest file, add below permission
<uses-permission android:name="android.permission.INTERNET" />
1st App code: Client Socket
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:id="@+id/tr_send_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="11dp">
<EditText
android:id="@+id/edt_send_message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:hint="Enter message"
android:inputType="text" />
<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="Send" />
</TableRow>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/tr_send_message"
android:layout_marginTop="25dp"
android:id="@+id/scrollView2">
<TextView
android:id="@+id/tv_reply_from_server"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
</RelativeLayout>
MainActivity.java
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
/**
* Created by Girish Bhalerao on 5/4/2017.
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTextViewReplyFromServer;
private EditText mEditTextSendMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonSend = (Button) findViewById(R.id.btn_send);
mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message);
mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server);
buttonSend.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
sendMessage(mEditTextSendMessage.getText().toString());
break;
}
}
private void sendMessage(final String msg) {
final Handler handler = new Handler();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
//Replace below IP with the IP of that device in which server socket open.
//If you change port then change the port number in the server side code also.
Socket s = new Socket("xxx.xxx.xxx.xxx", 9002);
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(msg);
output.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
final String st = input.readLine();
handler.post(new Runnable() {
@Override
public void run() {
String s = mTextViewReplyFromServer.getText().toString();
if (st.trim().length() != 0)
mTextViewReplyFromServer.setText(s + "\nFrom Server : " + st);
}
});
output.close();
out.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
2nd App Code - Server Socket
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_stop_receiving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP Receiving data"
android:layout_alignParentTop="true"
android:enabled="false"
android:layout_centerHorizontal="true"
android:layout_marginTop="89dp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btn_stop_receiving"
android:layout_marginTop="35dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="@+id/tv_data_from_client"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
<Button
android:id="@+id/btn_start_receiving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="START Receiving data"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp" />
</RelativeLayout>
MainActivity.java
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Girish Bhalerao on 5/4/2017.
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
final Handler handler = new Handler();
private Button buttonStartReceiving;
private Button buttonStopReceiving;
private TextView textViewDataFromClient;
private boolean end = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStartReceiving = (Button) findViewById(R.id.btn_start_receiving);
buttonStopReceiving = (Button) findViewById(R.id.btn_stop_receiving);
textViewDataFromClient = (TextView) findViewById(R.id.tv_data_from_client);
buttonStartReceiving.setOnClickListener(this);
buttonStopReceiving.setOnClickListener(this);
}
private void startServerSocket() {
Thread thread = new Thread(new Runnable() {
private String stringData = null;
@Override
public void run() {
try {
ServerSocket ss = new ServerSocket(9002);
while (!end) {
//Server is waiting for client here, if needed
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream());
stringData = input.readLine();
output.println("FROM SERVER - " + stringData.toUpperCase());
output.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
updateUI(stringData);
if (stringData.equalsIgnoreCase("STOP")) {
end = true;
output.close();
s.close();
break;
}
output.close();
s.close();
}
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
private void updateUI(final String stringData) {
handler.post(new Runnable() {
@Override
public void run() {
String s = textViewDataFromClient.getText().toString();
if (stringData.trim().length() != 0)
textViewDataFromClient.setText(s + "\n" + "From Client : " + stringData);
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start_receiving:
startServerSocket();
buttonStartReceiving.setEnabled(false);
buttonStopReceiving.setEnabled(true);
break;
case R.id.btn_stop_receiving:
//stopping server socket logic you can add yourself
buttonStartReceiving.setEnabled(true);
buttonStopReceiving.setEnabled(false);
break;
}
}
}
Use Apache Commons (IO and Lang) for simple/common things like this.
Imports:
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
Code:
String contents = FileUtils.readFileToString(new File("path/to/your/file.txt"));
String[] array = ArrayUtils.toArray(contents.split(" "));
Done.
If the value is between –2147483648 and 2147483647, cast(string_filed as int) will work. else cast(string_filed as bigint) will work
hive> select cast('2147483647' as int);
OK
2147483647
hive> select cast('2147483648' as int);
OK
NULL
hive> select cast('2147483648' as bigint);
OK
2147483648
A lot of the supplied answers require so many lines per property, ie / and / or - what I'd consider an ugly or tedious implementation because of repetitiveness required for multiple properties, etc. I prefer keeping boiling things down / simplifying them until they can't be simplified anymore or until it doesn't serve much purpose to do so.
In short: in completed works, if I repeat 2 lines of code, I typically convert it into a single line helper function, and so on... I simplify math or odd arguments such as ( start_x, start_y, end_x, end_y ) to ( x, y, w, h ) ie x, y, x + w, y + h ( sometimes requiring min / max or if w / h are negative and the implementation doesn't like it, I'll subtract from x / y and abs w / h. etc.. ).
Overriding the internal getters / setters is an ok way to go, but the problem is you need to do that for every class, or parent the class to that base... This doesn't work for me as I'd prefer to be free to choose the children / parents for inheritance, child nodes, etc.
I have created a solution which answers the question without using a Dict data-type to supply the data as I find that to be tedious to enter the data, etc...
My solution requires you to add 2 extra lines above your class to create a base class for the class you want to add the properties to, then 1 line per and you have the option to add callbacks to control the data, inform you when data changes, restrict the data which can be set based on value and / or data-type, and much more.
You also have the option to use _object.x, _object.x = value, _object.GetX( ), _object.SetX( value ) and they are handled equivalently.
Additionally, the values are the only non-static data which are assigned to the class instance, but the actual property is assigned to the class meaning the things you don't want to repeat, don't need to be repeated... You can assign a default value so the getter doesn't need it each time, although there is an option to override the default default value, and there is another option so the getter returns the raw stored value by overriding default returns ( note: this method means the raw value is only assigned when a value is assigned, otherwise it is None - when the value is Reset, then it assigns None, etc.. )
There are many helper functions too - the first property which gets added adds 2 or so helpers to the class for referencing the instance values... They are ResetAccessors( _key, .. ) varargs repeated ( all can be repeated using the first named args ) and SetAccessors( _key, _value ) with the option of more being added to the main class to aide in efficiency - the ones planned are: a way to group accessors together, so if you tend to reset a few at a time, every time, you can assign them to a group and reset the group instead of repeating the named keys each time, and more.
The instance / raw stored value is stored at class., the __class. references the Accessor Class which holds static vars / values / functions for the property. _class. is the property itself which is called when accessed via the instance class during setting / getting, etc.
The Accessor _class.__ points to the class, but because it is internal it needs to be assigned in the class which is why I opted to use __Name = AccessorFunc( ... ) to assign it, a single line per property with many optional arguments to use ( using keyed varargs because they're easier and more efficient to identify and maintain )...
I also create a lot of functions, as mentioned, some of which use accessor function information so it doesn't need to be called ( as it is a bit inconvenient at the moment - right now you need to use _class..FunctionName( _class_instance, args ) - I got around using the stack / trace to grab the instance reference to grab the value by adding the functions which either run this bit marathon, or by adding the accessors to the object and using self ( named this to point out they're for the instance and to retain access to self, the AccessorFunc class reference, and other information from within the function definitions ).
It isn't quite done, but it is a fantastic foot-hold. Note: If you do not use __Name = AccessorFunc( ... ) to create the properties, you won't have access to the __ key even though I define it within the init function. If you do, then there are no issues.
Also: Note that Name and Key are different... Name is 'formal', used in Function Name Creation, and the key is for data storage and access. ie _class.x where lowercase x is key, the name would be uppercase X so that GetX( ) is the function instead of Getx( ) which looks a little odd. this allows self.x to work and look appropriate, but also allow GetX( ) and look appropriate.
I have an example class set up with key / name identical, and different to show. a lot of helper functions created in order to output the data ( Note: Not all of this is complete ) so you can see what is going on.
The current list of functions using key: x, name: X outputs as:
This is by no means a comprehensive list - there are a few which haven't made it on this at the time of posting...
_instance.SetAccessors( _key, _value [ , _key, _value ] .. ) Instance Class Helper Function: Allows assigning many keys / values on a single line - useful for initial setup, or to minimize lines. In short: Calls this.Set<Name>( _value ) for each _key / _value pairing.
_instance.ResetAccessors( _key [ , _key ] .. ) Instance Class Helper Function: Allows resetting many key stored values to None on a single line. In short: Calls this.Reset<Name>() for each name provided.
Note: Functions below may list self.Get / Set / Name( _args ) - self is meant as the class instance reference in the cases below - coded as this in AccessorFuncBase Class.
this.GetX( _default_override = None, _ignore_defaults = False ) GET: Returns IF ISSET: STORED_VALUE .. IF IGNORE_DEFAULTS: None .. IF PROVIDED: DEFAULT_OVERRIDE ELSE: DEFAULT_VALUE 100
this.GetXRaw( ) RAW: Returns STORED_VALUE 100
this.IsXSet( ) ISSET: Returns ( STORED_VALUE != None ) True
this.GetXToString( ) GETSTR: Returns str( GET ) 100
this.GetXLen( _default_override = None, _ignore_defaults = False ) LEN: Returns len( GET ) 3
this.GetXLenToString( _default_override = None, _ignore_defaults = False ) LENSTR: Returns str( len( GET ) ) 3
this.GetXDefaultValue( ) DEFAULT: Returns DEFAULT_VALUE 1111
this.GetXAccessor( ) ACCESSOR: Returns ACCESSOR_REF ( self.__<key> ) [ AccessorFuncBase ] Key: x : Class ID: 2231452344344 : self ID: 2231448283848 Default: 1111 Allowed Types: {"<class 'int'>": "<class 'type'>", "<class 'float'>": "<class 'type'>"} Allowed Values: None
this.GetXAllowedTypes( ) ALLOWED_TYPES: Returns Allowed Data-Types {"<class 'int'>": "<class 'type'>", "<class 'float'>": "<class 'type'>"}
this.GetXAllowedValues( ) ALLOWED_VALUES: Returns Allowed Values None
this.GetXHelpers( ) HELPERS: Returns Helper Functions String List - ie what you're reading now... THESE ROWS OF TEXT
this.GetXKeyOutput( ) Returns information about this Name / Key ROWS OF TEXT
this.GetXGetterOutput( ) Returns information about this Name / Key ROWS OF TEXT
this.SetX( _value ) SET: STORED_VALUE Setter - ie Redirect to __<Key>.Set N / A
this.ResetX( ) RESET: Resets STORED_VALUE to None N / A
this.HasXGetterPrefix( ) Returns Whether or Not this key has a Getter Prefix... True
this.GetXGetterPrefix( ) Returns Getter Prefix... Get
this.GetXName( ) Returns Accessor Name - Typically Formal / Title-Case X
this.GetXKey( ) Returns Accessor Property Key - Typically Lower-Case x
this.GetXAccessorKey( ) Returns Accessor Key - This is to access internal functions, and static data... __x
this.GetXDataKey( ) Returns Accessor Data-Storage Key - This is the location where the class instance value is stored.. _x
Some of the data being output is:
This is for a brand new class created using the Demo class without any data assigned other than the name ( so it can be output ) which is _foo, the variable name I used...
_foo --- MyClass: ---- id( this.__class__ ): 2231452349064 :::: id( this ): 2231448475016
Key Getter Value | Raw Key Raw / Stored Value | Get Default Value Default Value | Get Allowed Types Allowed Types | Get Allowed Values Allowed Values |
Name: _foo | _Name: _foo | __Name.DefaultValue( ): AccessorFuncDemoClass | __Name.GetAllowedTypes( ) <class 'str'> | __Name.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
x: 1111 | _x: None | __x.DefaultValue( ): 1111 | __x.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __x.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
y: 2222 | _y: None | __y.DefaultValue( ): 2222 | __y.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __y.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
z: 3333 | _z: None | __z.DefaultValue( ): 3333 | __z.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __z.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Blah: <class 'int'> | _Blah: None | __Blah.DefaultValue( ): <class 'int'> | __Blah.GetAllowedTypes( ) <class 'str'> | __Blah.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Width: 1 | _Width: None | __Width.DefaultValue( ): 1 | __Width.GetAllowedTypes( ) (<class 'int'>, <class 'bool'>) | __Width.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Height: 0 | _Height: None | __Height.DefaultValue( ): 0 | __Height.GetAllowedTypes( ) <class 'int'> | __Height.GetAllowedValues( ) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) |
Depth: 2 | _Depth: None | __Depth.DefaultValue( ): 2 | __Depth.GetAllowedTypes( ) Saved Value Restricted to Authorized Values ONLY | __Depth.GetAllowedValues( ) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) |
this.IsNameSet( ): True this.GetName( ): _foo this.GetNameRaw( ): _foo this.GetNameDefaultValue( ): AccessorFuncDemoClass this.GetNameLen( ): 4 this.HasNameGetterPrefix( ): <class 'str'> this.GetNameGetterPrefix( ): None
this.IsXSet( ): False this.GetX( ): 1111 this.GetXRaw( ): None this.GetXDefaultValue( ): 1111 this.GetXLen( ): 4 this.HasXGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetXGetterPrefix( ): None
this.IsYSet( ): False this.GetY( ): 2222 this.GetYRaw( ): None this.GetYDefaultValue( ): 2222 this.GetYLen( ): 4 this.HasYGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetYGetterPrefix( ): None
this.IsZSet( ): False this.GetZ( ): 3333 this.GetZRaw( ): None this.GetZDefaultValue( ): 3333 this.GetZLen( ): 4 this.HasZGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetZGetterPrefix( ): None
this.IsBlahSet( ): False this.GetBlah( ): <class 'int'> this.GetBlahRaw( ): None this.GetBlahDefaultValue( ): <class 'int'> this.GetBlahLen( ): 13 this.HasBlahGetterPrefix( ): <class 'str'> this.GetBlahGetterPrefix( ): None
this.IsWidthSet( ): False this.GetWidth( ): 1 this.GetWidthRaw( ): None this.GetWidthDefaultValue( ): 1 this.GetWidthLen( ): 1 this.HasWidthGetterPrefix( ): (<class 'int'>, <class 'bool'>) this.GetWidthGetterPrefix( ): None
this.IsDepthSet( ): False this.GetDepth( ): 2 this.GetDepthRaw( ): None this.GetDepthDefaultValue( ): 2 this.GetDepthLen( ): 1 this.HasDepthGetterPrefix( ): None this.GetDepthGetterPrefix( ): (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
this.IsHeightSet( ): False this.GetHeight( ): 0 this.GetHeightRaw( ): None this.GetHeightDefaultValue( ): 0 this.GetHeightLen( ): 1 this.HasHeightGetterPrefix( ): <class 'int'> this.GetHeightGetterPrefix( ): (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
And this is after assigning all of _foo properties ( except the name ) the following values in the same order: 'string ', 1.0, True, 9, 10, False
this.IsNameSet( ): True this.GetName( ): _foo this.GetNameRaw( ): _foo this.GetNameDefaultValue( ): AccessorFuncDemoClass this.GetNameLen( ): 4 this.HasNameGetterPrefix( ): <class 'str'> this.GetNameGetterPrefix( ): None
this.IsXSet( ): True this.GetX( ): 10 this.GetXRaw( ): 10 this.GetXDefaultValue( ): 1111 this.GetXLen( ): 2 this.HasXGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetXGetterPrefix( ): None
this.IsYSet( ): True this.GetY( ): 10 this.GetYRaw( ): 10 this.GetYDefaultValue( ): 2222 this.GetYLen( ): 2 this.HasYGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetYGetterPrefix( ): None
this.IsZSet( ): True this.GetZ( ): 10 this.GetZRaw( ): 10 this.GetZDefaultValue( ): 3333 this.GetZLen( ): 2 this.HasZGetterPrefix( ): (<class 'int'>, <class 'float'>) this.GetZGetterPrefix( ): None
this.IsBlahSet( ): True this.GetBlah( ): string Blah this.GetBlahRaw( ): string Blah this.GetBlahDefaultValue( ): <class 'int'> this.GetBlahLen( ): 11 this.HasBlahGetterPrefix( ): <class 'str'> this.GetBlahGetterPrefix( ): None
this.IsWidthSet( ): True this.GetWidth( ): False this.GetWidthRaw( ): False this.GetWidthDefaultValue( ): 1 this.GetWidthLen( ): 5 this.HasWidthGetterPrefix( ): (<class 'int'>, <class 'bool'>) this.GetWidthGetterPrefix( ): None
this.IsDepthSet( ): True this.GetDepth( ): 9 this.GetDepthRaw( ): 9 this.GetDepthDefaultValue( ): 2 this.GetDepthLen( ): 1 this.HasDepthGetterPrefix( ): None this.GetDepthGetterPrefix( ): (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
this.IsHeightSet( ): True this.GetHeight( ): 9 this.GetHeightRaw( ): 9 this.GetHeightDefaultValue( ): 0 this.GetHeightLen( ): 1 this.HasHeightGetterPrefix( ): <class 'int'> this.GetHeightGetterPrefix( ): (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
_foo --- MyClass: ---- id( this.__class__ ): 2231452349064 :::: id( this ): 2231448475016
Key Getter Value | Raw Key Raw / Stored Value | Get Default Value Default Value | Get Allowed Types Allowed Types | Get Allowed Values Allowed Values |
Name: _foo | _Name: _foo | __Name.DefaultValue( ): AccessorFuncDemoClass | __Name.GetAllowedTypes( ) <class 'str'> | __Name.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
x: 10 | _x: 10 | __x.DefaultValue( ): 1111 | __x.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __x.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
y: 10 | _y: 10 | __y.DefaultValue( ): 2222 | __y.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __y.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
z: 10 | _z: 10 | __z.DefaultValue( ): 3333 | __z.GetAllowedTypes( ) (<class 'int'>, <class 'float'>) | __z.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Blah: string Blah | _Blah: string Blah | __Blah.DefaultValue( ): <class 'int'> | __Blah.GetAllowedTypes( ) <class 'str'> | __Blah.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Width: False | _Width: False | __Width.DefaultValue( ): 1 | __Width.GetAllowedTypes( ) (<class 'int'>, <class 'bool'>) | __Width.GetAllowedValues( ) Saved Value Restrictions Levied by Data-Type |
Height: 9 | _Height: 9 | __Height.DefaultValue( ): 0 | __Height.GetAllowedTypes( ) <class 'int'> | __Height.GetAllowedValues( ) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) |
Depth: 9 | _Depth: 9 | __Depth.DefaultValue( ): 2 | __Depth.GetAllowedTypes( ) Saved Value Restricted to Authorized Values ONLY | __Depth.GetAllowedValues( ) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) |
Note that because of restricted data-types or value restrictions, some data wasn't assigned - this is by design. The setter prohibits bad data-types or values from being assigned, even from being assigned as a default value ( unless you override the default value protection behavior )
The code hasn't been posted here because I didn't have room after the examples and explanations... Also because it will change.
Please Note: at the time of this posting, the file is messy - this will change. But, if you run it in Sublime Text and compile it, or run it from Python, it will compile and spit out a ton of information - the AccessorDB portion isn't done ( which will be used to update the Print Getters and GetKeyOutput helper functions along with being changed to an Instance function, probably put into a single function and renamed - look for it.. )
Next: Not everything is required for it to run - a lot of the commented stuff at the bottom is for more information used for debugging - it may not be there when you download it. If it is, you should be able to uncomment and recompile to get more information.
I am looking for a work-around to needing MyClassBase: pass, MyClass( MyClassBase ): ... - if you know of a solution - post it.
The only thing necessary in the class are the __ lines - the str is for debugging as is the init - they can be removed from the Demo Class but you will need to comment out or remove some of the lines below ( _foo / 2 / 3 )..
The String, Dict, and Util classes at the top are a part of my Python library - they are not complete. I copied over a few things I needed from the library, and I created a few new ones. The full code will link to the complete library and will include it along with providing updated calls and removing the code ( actually, the only code left will be the Demo Class and the print statements - the AccessorFunc system will be moved to the library )...
Part of file:
##
## MyClass Test AccessorFunc Implementation for Dynamic 1-line Parameters
##
class AccessorFuncDemoClassBase( ):
pass
class AccessorFuncDemoClass( AccessorFuncDemoClassBase ):
__Name = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'Name', default = 'AccessorFuncDemoClass', allowed_types = ( TYPE_STRING ), allowed_values = VALUE_ANY, documentation = 'Name Docs', getter_prefix = 'Get', key = 'Name', allow_erroneous_default = False, options = { } )
__x = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'X', default = 1111, allowed_types = ( TYPE_INTEGER, TYPE_FLOAT ), allowed_values = VALUE_ANY, documentation = 'X Docs', getter_prefix = 'Get', key = 'x', allow_erroneous_default = False, options = { } )
__Height = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'Height', default = 0, allowed_types = TYPE_INTEGER, allowed_values = VALUE_SINGLE_DIGITS, documentation = 'Height Docs', getter_prefix = 'Get', key = 'Height', allow_erroneous_default = False, options = { } )
This beauty makes it incredibly easy to create new classes with dynamically added properties with AccessorFuncs / callbacks / data-type / value enforcement, etc.
For now, the link is at ( This link should reflect changes to the document. ): https://www.dropbox.com/s/6gzi44i7dh58v61/dynamic_properties_accessorfuncs_and_more.py?dl=0
Also: If you don't use Sublime Text, I recommend it over Notepad++, Atom, Visual Code, and others because of proper threading implementations making it much, much faster to use... I am also working on an IDE-like code mapping system for it - take a look at: https://bitbucket.org/Acecool/acecoolcodemappingsystem/src/master/ ( Add Repo in Package Manager first, then Install Plugin - when version 1.0.0 is ready, I'll add it to the main plugin list... )
I hope this solution helps... and, as always:
Just because it works, doesn't make it right - Josh 'Acecool' Moser
shopt -s nocaseglob
There's a much better way to achieve your desired result, using SQL Server's analytic (or windowing) functions.
SELECT DISTINCT Date, MAX(Score) OVER(PARTITION BY Date) FROM ScoresTable
If you need more than just the date and max score combinations, you can use ranking functions, eg:
SELECT *
FROM ScoresTable t
JOIN (
SELECT
ScoreId,
ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Score DESC) AS [Rank]
FROM ScoresTable
) window ON window.ScoreId = p.ScoreId AND window.[Rank] = 1
You may want to use RANK() instead of ROW_NUMBER() if you want multiple records to be returned if they both share the same MAX(Score).
Creating a sum method would work nicely, e.g. you could add the sum function to Array
Array.prototype.sum = function(selector) {
if (typeof selector !== 'function') {
selector = function(item) {
return item;
}
}
var sum = 0;
for (var i = 0; i < this.length; i++) {
sum += parseFloat(selector(this[i]));
}
return sum;
};
then you could do
> [1,2,3].sum()
6
and in your case
> myData.sum(function(item) { return item[1]; });
23
Edit: Extending the builtins can be frowned upon because if everyone did it we would get things unexpectedly overriding each other (namespace collisions). you could add the sum function to some module and accept an array as an argument if you like.
that could mean changing the signature to myModule.sum = function(arr, selector) {
then this
would become arr
If you're like me and came here looking for a way to make sass --watch work with compass, the answer is to use Compass' version of watch, simply:
compass watch
If you're on a Mac and don't yet have the gem installed, you might run into errors when you try to install the Compass gem, due to permission problems that arise on OSX versions later than 10.11. Install ruby with Homebrew to get around this. See this answer for how to do that.
Alternatively you could just use CodeKit, but if you're stubborn like me and want to use Sublime Text and command line, this is the route to go.
I have also used following link as others have suggested you for bluetooth communication.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
The thing is all you need is a class BluetoothChatService.java
this class has following threads:
Now when you call start function of the BluetoothChatService like:
mChatService.start();
It starts accept thread which means it will start looking for connection.
Now when you call
mChatService.connect(<deviceObject>,false/true);
Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.
connect
function will start connecting thread which will look for any device which is running accept thread.
When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:
connected(mmSocket, mmDevice, mSocketType);
this method starts connected thread in both the devices:
Using this socket object connected thread obtains the input and output stream to the other device.
And calls read
function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.
BluetoothChatService also has a write
method which takes byte[]
as input and calls write method on connected thread.
mChatService.write("your message".getByte());
write method in connected thread just write this byte data to outputsream of the other device.
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(
// BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
// buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.
You can only do so during a transaction.
BEGIN;
INSERT INTO xxx ...;
DELETE FROM ...;
Then you can either:
COMMIT; -- will confirm your changes
Or
ROLLBACK -- will undo your previous changes
Not sure if I fully understood your problem, but if it's just about creating export scripts, you should forward engineer to SQL script - Ctrl + Shift + G or File -> Export -> first option.
For a JPA 2.x example usage for the general case of two tables, with a @OneToMany
unidirectional join see https://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Example_of_a_JPA_2.x_unidirectional_OneToMany_relationship_annotations
Screenshot from this WikiBooks JPA article: Example of a JPA 2.x unidirectional OneToMany relationship database
easy but not efficient:
list(df.education).count('9th')
so long as your html content doesn't need to contain a CDATA
element, you can contain the HTML in a CDATA
element, otherwise you'll have to escape the XML entities.
<element><![CDATA[<p>your html here</p>]]></element>
VS
<element><p>your html here</p></element>
I managed to load an application.properties file in external path while using -jar option.
The key was PropertiesLauncher.
To use PropertiesLauncher, pom.xml file must be changed like this:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration> <!-- added -->
<layout>ZIP</layout> <!-- to use PropertiesLaunchar -->
</configuration>
</plugin>
</plugins>
</build>
For this, I referenced the following StackOverflow question: spring boot properties launcher unable to use . BTW, In Spring Boot Maven Plugin document(http://docs.spring.io/spring-boot/docs/1.1.7.RELEASE/maven-plugin/repackage-mojo.html), there is no mention that specifying ZIP triggers that PropertiesLauncher is used. (Perhaps in another document?)
After the jar file had been built, I could see that the PropertiesLauncher is used by inspecting Main-Class property in META-INF/MENIFEST.MF in the jar.
Now, I can run the jar as follows(in Windows):
java -Dloader.path=file:///C:/My/External/Dir,MyApp-0.0.1-SNAPSHOT.jar -jar MyApp-0.0.1-SNAPSHOT.jar
Note that the application jar file is included in loader.path.
Now an application.properties file in C:\My\External\Dir\config is loaded.
As a bonus, any file (for example, static html file) in that directory can also be accessed by the jar since it's in the loader path.
As for the non-jar (expanded) version mentioned in UPDATE 2, maybe there was a classpath order problem.
There is no concept of interface in C++,
You can simulate the behavior using an Abstract class.
Abstract class is a class which has atleast one pure virtual function, One cannot create any instances of an abstract class but You could create pointers and references to it. Also each class inheriting from the abstract class must implement the pure virtual functions in order that it's instances can be created.
Appending to an object in a for loop causes the entire object to be copied on every iteration, which causes a lot of people to say "R is slow", or "R loops should be avoided".
As BrodieG mentioned in the comments: it is much better to pre-allocate a vector of the desired length, then set the element values in the loop.
Here are several ways to append values to a vector. All of them are discouraged.
# one way
for (i in 1:length(values))
vector[i] <- values[i]
# another way
for (i in 1:length(values))
vector <- c(vector, values[i])
# yet another way?!?
for (v in values)
vector <- c(vector, v)
# ... more ways
help("append")
would have answered your question and saved the time it took you to write this question (but would have caused you to develop bad habits). ;-)
Note that vector <- c()
isn't an empty vector; it's NULL
. If you want an empty character vector, use vector <- character()
.
If you absolutely must use a for loop, you should pre-allocate the entire vector before the loop. This will be much faster than appending for larger vectors.
set.seed(21)
values <- sample(letters, 1e4, TRUE)
vector <- character(0)
# slow
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
# user system elapsed
# 0.340 0.000 0.343
vector <- character(length(values))
# fast(er)
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
# user system elapsed
# 0.024 0.000 0.023
Consider this example:
bool isEqual = (23.42f == 23.42);
What is isEqual
? 9 out of 10 people will say "It's true
, of course" and 9 out of 10 people are wrong: https://rextester.com/RVL15906
That's because floating point numbers are no exact numeric representations.
Being binary numbers, they cannot even exactly represent all numbers that can be exact represented as decimal numbers. E.g. while 0.1
can be exactly represented as a decimal number (it is exactly the tenth part of 1
), it cannot be represented using floating point because it is 0.00011001100110011...
periodic as binary. 0.1
is for floating point what 1/3
is for decimal (which is 0.33333...
as decimal)
The consequence is that calculations like 0.3 + 0.6
can result in 0.89999999999999991
, which is not 0.9
, albeit it's close to that. And thus the test 0.1 + 0.2 - 0.3 == 0.0
might fail as the result of the calculation may not be 0
, albeit it will be very close to 0
.
==
is an exact test and performing an exact test on inexact numbers is usually not very meaningful. As many floating point calculations include rounding errors, you usually want your comparisons to also allow small errors and this is what the test code you posted is all about. Instead of testing "Is A equal to B" it tests "Is A very close to B" as very close is quite often the best result you can expect from floating point calculations.
You can use the following css to resize the image for mobile view
object-fit: scale-down; max-width: 100%
PuTTY's plink has a command-line argument for a password. Some other suggestions have been made in the answers to this question: using Expect (which is available for Windows), or writing a launcher in Python with Paramiko.
Reading xml the easy way:
http://www.mkyong.com/java/jaxb-hello-world-example/
package com.mkyong.core;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
.
package com.mkyong.core;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
public static void main(String[] args) {
Customer customer = new Customer();
customer.setId(100);
customer.setName("mkyong");
customer.setAge(29);
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
In MSBuild or Teamcity use command line
MSBuild yourproject.sln /property:Configuration=Release /property:Platform=x64
or use shorter form:
MSBuild yourproject.sln /p:Configuration=Release /p:Platform=x64
However you need to set up platform in your project anyway, see the answer by Julien Hoarau.
You need no sorted list. You need no sorting at all.
I need to add/remove keys from the list when object is added / removed from database.
But not immediately, the removal can wait. Use an ArrayList
containing the ID's all alive objects plus at most some bounded percentage of deleted objects. Use a separate HashSet
to keep track of deleted objects.
private List<ID> mostlyAliveIds = new ArrayList<>();
private Set<ID> deletedIds = new HashSet<>();
I want to randomly select few dozens of element from the whole list.
ID selectOne(Random random) {
checkState(deletedIds.size() < mostlyAliveIds.size());
while (true) {
int index = random.nextInt(mostlyAliveIds.size());
ID id = mostlyAliveIds.get(index);
if (!deletedIds.contains(ID)) return ID;
}
}
Set<ID> selectSome(Random random, int count) {
checkArgument(deletedIds.size() <= mostlyAliveIds.size() - count);
Set<ID> result = new HashSet<>();
while (result.size() < count) result.add(selectOne(random));
}
For maintaining the data, do something like
void insert(ID id) {
if (!deletedIds.remove(id)) mostlyAliveIds.add(ID);
}
void delete(ID id) {
if (!deletedIds.add(id)) {
throw new ImpossibleException("Deleting a deleted element);
}
if (deletedIds.size() > 0.1 * mostlyAliveIds.size()) {
mostlyAliveIds.removeAll(deletedIds);
deletedIds.clear();
}
}
The only tricky part is the insert
which has to check if an already deleted ID was resurrected.
The delete
ensures that no more than 10% of elements in mostlyAliveIds
are deleted IDs. When this happens, they get all removed in one sweep (I didn't check the JDK sources, but I hope, they do it right) and the show goes on.
With no more than 10% of dead IDs, the overhead of selectOne
is no more than 10% on the average.
I'm pretty sure that it's faster than any sorting as the amortized complexity is O(n)
.
Answering your question in this format is quite challenging.
On the other hand you ask about navigation and then about current $state
acting all weird.
For the first I'd say it's too broad question and for the second I'd say... well, you are doing something wrong or missing the obvious :)
Take the following controller:
app.controller('MainCtrl', function($scope, $state) {
$scope.state = $state;
});
Where app
is configured as:
app.config(function($stateProvider) {
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'main.html',
controller: 'MainCtrl'
})
.state('main.thiscontent', {
url: '/thiscontent',
templateUrl: 'this.html',
controller: 'ThisCtrl'
})
.state('main.thatcontent', {
url: '/thatcontent',
templateUrl: 'that.html'
});
});
Then simple HTML template having
<div>
{{ state | json }}
</div>
Would "print out" e.g. the following
{
"params": {},
"current": {
"url": "/thatcontent",
"templateUrl": "that.html",
"name": "main.thatcontent"
},
"transition": null
}
I put up a small example showing this, using ui.router
and pascalprecht.translate
for the menus. I hope you find it useful and figure out what is it you are doing wrong.
Plunker here http://plnkr.co/edit/XIW4ZE
Screencap
You might want to use grep "$(echo -e '\t')"
Only requirement is echo
to be capable of interpretation of backslash escapes.
Following code helped me to hide keyboard
void initState() {
SystemChannels.textInput.invokeMethod('TextInput.hide');
super.initState();
}
As part of htmlAttributes,e.g.
Html.BeginForm(
action, controller, FormMethod.Post, new { enctype="multipart/form-data"})
Or you can pass null
for action and controller to get the same default target as for BeginForm() without any parameters:
Html.BeginForm(
null, null, FormMethod.Post, new { enctype="multipart/form-data"})
It means, the Class reference type can hold any Class object which represents any type. If JVM loads a type, a class object representing that type will be present in JVM. we can get the metadata regarding the type from that class object which is used very much in reflection package.
Suppose you have a a class named "myPackage.MyClass". Assuming that is in classpath, the following statements are equivalent.
Class<?> myClassObject = MyClass.class; //compile time check
Class<?> myClassObject = Class.forname("myPackage.MyClass"); //only runtime check
This works in a similar fashion if the Class<?> reference is in method argument as well.
Please note that the class "Class" does not have a public constructor. So you cannot instantiate "Class" instances with "new" operator.
Replace this:
var cat = $.jqURL.get('category');
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
$(this).select(); // This is where my problem is
});
With this:
$('#cbCategory').val(cat);
Calling val()
on a select list will automatically select the option with that value, if any.
Simply use the logical "OR" operator, that is ||
.
if (A || B)
This happened to me when I started to work with a colleque's project.
He was using jdk 12.0.2 .
If you are suspicious jdk difference might be the case (Your IDE complains about SDK, JDK etc.):
i tried to train unet on voc data set but because of huge image size, memory finishes. i tried all the above tips, even tried with batch size==1, yet to no improvement. sometimes TensorFlow version also causes the memory issues. try by using
pip install tensorflow-gpu==1.8.0
A picture is worth a thousand words.
Main thread-->----->--->-->--block##########continue--->---->
\ | |
sub thread start()\ | join() |
\ | |
---sub thread----->--->--->--finish
Hope to useful, for more detail click here
This should work.
int i = 1;
foreach (ListViewItem lvi in listView.Items) {
...
if(++i == 50) break;
}
I think of two ways to test for the type of a value:
Method 1:
You can use the isNaN
javascript method, which determines if a value is NaN or not. But because in your case you are testing a numerical value converted to string, Javascript is trying to guess the type of the value and converts it to the number 5 which is not NaN
. That's why if you console.log
out the result, you will be surprised that the code:
if (isNaN(i)) {
console.log('This is not number');
}
will not return anything. For this reason a better alternative would be the method 2.
Method 2:
You may use javascript typeof method to test the type of a variable or value
if (typeof i != "number") {
console.log('This is not number');
}
Notice that i'm using double equal operator, because in this case the type of the value is a string but Javascript internally will convert to Number.
A more robust method to force the value to numerical type is to use Number.isNaN which is part of new Ecmascript 6 (Harmony) proposal, hence not widespread and fully supported by different vendors.
some smtp servers (secure ones) requires you to supply both username and email, if its gmail then most chances its the 'Less Secure Sign-In' issue you need to address, otherwise you can try:
public static void SendEmail(string address, string subject,
string message, string email, string username, string password,
string smtp, int port)
{
var loginInfo = new NetworkCredential(username, password);
var msg = new MailMessage();
var smtpClient = new SmtpClient(smtp, port);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress(address));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}
notice that the email from and the username are different unlike some implementation that refers to them as the same.
calling this method can be done like so:
SendEmail("[email protected]", "test", "Hi it worked!!",
"from-mail", "from-username", "from-password", "smtp", 587);
You can write your query like this.
var query = from t1 in myTABLE1List // List<TABLE_1>
join t2 in myTABLE1List
on t1.ColumnA equals t2.ColumnA
and t1.ColumnB equals t2.ColumnA
If you want to compare your column with multiple columns.
This should do it:
<style>
body {
background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>
function inViewport(element) {
let bounds = element.getBoundingClientRect();
let viewWidth = document.documentElement.clientWidth;
let viewHeight = document.documentElement.clientHeight;
if (bounds['left'] < 0) return false;
if (bounds['top'] < 0) return false;
if (bounds['right'] > viewWidth) return false;
if (bounds['bottom'] > viewHeight) return false;
return true;
}
This worked for me!!
SELECT * FROM `users` where `created_at` BETWEEN CURDATE()-7 AND CURDATE()
This could be also the reason. i have come up with following pom.xml
.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
The unresolved issue was due to exclusion of spring-boot-starter-tomcat
. Just remove <exclusions>...</exclusions>
dependency it will ressolve issue, but make sure doing this will also exclude the embedded tomcat server.
If you need embedded tomcat server too you can add same dependency with compile scope
.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>compile</scope>
</dependency>
Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.
The best way is to create a person-component
and watch every person separately inside its own component, as shown below:
<person-component :person="person" v-for="person in people"></person-component>
Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit
to send an event upwards, containing the id
of modified person.
Vue.component('person-component', {_x000D_
props: ["person"],_x000D_
template: `_x000D_
<div class="person">_x000D_
{{person.name}}_x000D_
<input type='text' v-model='person.age'/>_x000D_
</div>`,_x000D_
watch: {_x000D_
person: {_x000D_
handler: function(newValue) {_x000D_
console.log("Person with ID:" + newValue.id + " modified")_x000D_
console.log("New age: " + newValue.age)_x000D_
},_x000D_
deep: true_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
people: [_x000D_
{id: 0, name: 'Bob', age: 27},_x000D_
{id: 1, name: 'Frank', age: 32},_x000D_
{id: 2, name: 'Joe', age: 38}_x000D_
]_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<body>_x000D_
<div id="app">_x000D_
<p>List of people:</p>_x000D_
<person-component :person="person" v-for="person in people"></person-component>_x000D_
</div>_x000D_
</body>
_x000D_
You should add an optional hyphen at the beginning by adding -?
(?
is a quantifier meaning one or zero occurrences):
^-?[0-9]\d*(\.\d+)?$
I verified it in Rubular with these values:
10.00
-10.00
and both matched as expected.
non of the solutions worked well for me. especially when there are many gaps and set is small. this worked very well for me(in php):
$count = $collection->count($search);
$skip = mt_rand(0, $count - 1);
$result = $collection->find($search)->skip($skip)->limit(1)->getNext();
try some thing like blow:
SString otherParametersUrServiceNeed = "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
References :
The grep family of commands (incl egrep, fgrep) is the usual solution for this.
$ grep pattern filename
If you're searching source code, then ack may be a better bet. It'll search subdirectories automatically and avoid files you'd normally not search (objects, SCM directories etc.)
A table out of char array:
char map[256] = { 0 };
map['T'] = 'A';
map['A'] = 'T';
map['C'] = 'G';
map['G'] = 'C';
/* .... */
Most clean technique for both C & C++ is: pass 2D array like a 1D array, then use as 2D inside the function.
#include <stdio.h>
void func(int row, int col, int* matrix){
int i, j;
for(i=0; i<row; i++){
for(j=0; j<col; j++){
printf("%d ", *(matrix + i*col + j)); // or better: printf("%d ", *matrix++);
}
printf("\n");
}
}
int main(){
int matrix[2][3] = { {0, 1, 2}, {3, 4, 5} };
func(2, 3, matrix[0]);
return 0;
}
Internally, no matter how many dimensions an array has, C/C++ always maintains a 1D array. And so, we can pass any multi-dimensional array like this.
You can use javac *.java
command to compile all you java sources. Also you should learn a little about classpath because it seems that you should set appropriate classpath for succesful compilation (because your IDE use some libraries for building WebService clients). Also I can recommend you to check wich command your IDE use to build your project.
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
Others have already posted excellent answers, I just wanted to add that with most languages, frameworks, and use cases you'll be dealing with POST
much, much more often than PUT
. To the point where PUT, DELETE,
etc. are basically trivia questions.
you could also create a class which extends ArrayList
:
public static class MyList extends ArrayList<Myclass> {}
and then use it like:
List<MyClass> list = objectMapper.readValue(json, MyList.class);
There is a easy way of doing this by just using easy_install (A Setuptools to package python librarie).
Assumption. Before doing this check whether you have python installed into your Centos machine (at least 2.x).
Steps to install pip.
So lets do install easy_install,
sudo yum install python-setuptools python-setuptools-devel
Now lets do pip with easy_install,
sudo easy_install pip
That's Great. Now you have pip :)