You've missed the id out before the NOT; it needs to be specified.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.
Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.
Incase of string literals(character arrays defined at declaration), they are automatically
appended by \0
.
printf
prints using the format specifier and the address provided. Since, you use %s
it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'
If you are processing in rows with cellIterator....then this worked for me ....
DataFormatter formatter = new DataFormatter();
while(cellIterator.hasNext())
{
cell = cellIterator.next();
String val = "";
switch(cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
val = String.valueOf(formatter.formatCellValue(cell));
break;
case Cell.CELL_TYPE_STRING:
val = formatter.formatCellValue(cell);
break;
}
.....
.....
}
Dawid Ferenczy's answer is pretty complete but after I tried almost all of his options I've found that the Chocolatey’s cyg-get was the best (at least the only one that I could get to work).
I was wanting to install wget
, the steps was this:
choco install cyg-get
Then:
cyg-get wget
You can use Thread.GetHashCode, which returns the managed thread ID. If you think about the purpose of GetHashCode, this makes good sense -- it needs to be a unique identifier (e.g. key in a dictionary) for the object (the thread).
The reference source for the Thread class is instructive here. (Granted, a particular .NET implementation may not be based on this source code, but for debugging purposes I'll take my chances.)
GetHashCode "provides this hash code for algorithms that need quick checks of object equality," so it is well-suited for checking Thread equality -- for example to assert that a particular method is executing on the thread you wanted it called from.
with string GMT/UTC +/-0400 or GMT/UTC +/-1000 based on local timings
Your custom format is just missing O
to give you the timezone offsets from local time.
Difference to Greenwich time (GMT) in hours Example: +0200
date_default_timezone_set('America/La_Paz');
echo date('Y-m-d H:i:s O');
2018-01-12 12:10:11 -0400
However, for maximized portability/interoperability, I would recommend using the ISO8601 date format c
date_default_timezone_set('America/La_Paz');
echo date('c');
2018-01-12T12:10:11-04:00
date_default_timezone_set('Australia/Brisbane');
echo date('c');
2018-01-13T02:10:11+10:00
You can use also gmdate
and the timezone offset string will always be +00:00
date_default_timezone_set('America/La_Paz');
echo gmdate('c');
2018-01-12T16:10:11+00:00
date_default_timezone_set('Australia/Brisbane');
echo gmdate('c');
2018-01-12T16:10:11+00:00
let date = Date()
let units: Set<Calendar.Component> = [.hour, .day, .month, .year]
let comps = Calendar.current.dateComponents(units, from: date)
If you didn't want to sign up for a service, I'd probably go back to the exchanges themselves; most of them aren't CAPTCHAed yet...
The symbol lookup page for:
etc...
It's a very bad idea to directly display any text on an irregular and ever changing background. No matter what you do, some of the time the text will be hard to read.
The best design would be to have the labels on a constant background with the images changing behind that.
You can set the labels background color from clear to white and set the from alpha to 50.0 you get a nice translucent effect. The only problem is that the label's background is a stark rectangle.
To get a label with a background with rounded corners you can use a button with user interaction disabled but the user might mistake that for a button.
The best method would be to create image of the label background you want and then put that in an imageview and put the label with the default transparent background onto of that.
Plain UIViews do not have an image background. Instead, you should make a UIImageView your main view and then rotate the images though its image property. If you set the UIImageView's mode to "Scale to fit" it will scale any image to fit the bounds of the view.
You can use the window.innerHeight
You can use the VS code and install the Graphviz extension or,
C:\Program Files (x86)\Graphviz2.38\bin
(or your_installation_path/ bin) to your system variable
PATHdot music-recommender.dot -Tpng -o image.png
Most easiest way to do it as follow:
var elementPosition = $('#navigation').offset();
$(window).scroll(function(){
if($(window).scrollTop() > elementPosition.top){
$('#navigation').css('position','fixed').css('top','0');
} else {
$('#navigation').css('position','static');
}
});
This works for me on [{"id":"data"},{"id":"data"}]
function getObjects(obj, key, val)
{
var newObj = false;
$.each(obj, function()
{
var testObject = this;
$.each(testObject, function(k,v)
{
//alert(k);
if(val == v && k == key)
{
newObj = testObject;
}
});
});
return newObj;
}
After going through all the answers and executing most of them. Although I resisted to try the Restart magic, eventually, the issue is solved after restart on my macbook(MacOS Catalina Ver. 10.15.7).
It seems like a cache issue indeed but none of the commands that I have executed cleared the cache.
I ended up on this page running Web Apps on Azure.
The page cannot be displayed because an internal server error has occurred.
We ran into this problem because we applicationInitialization in the web.config
<applicationInitialization
doAppInitAfterRestart="true"
skipManagedModules="true">
<add initializationPage="/default.aspx" hostName="myhost"/>
</applicationInitialization>
If running on Azure, have a look at site slots. You should warm up the pages on a staging slot before swapping it to the production slot.
IMHO __call__
method and closures give us a natural way to create STRATEGY design pattern in Python. We define a family of algorithms, encapsulate each one, make them interchangeable and in the end we can execute a common set of steps and, for example, calculate a hash for a file.
btn.titleLabel?.font = .systemFont(ofSize: 12)
It's a conceptual problem.
Stringstream is a stream, so its iterators are forward, cannot return. In an output stringstream, you need a flush() to reinitialize it, as in any other output stream.
You have add this code:
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
And Enabling Allow less secure apps: "will usually solve the problem for PHPMailer, and it does not really make your app significantly less secure. Reportedly, changing this setting may take an hour or more to take effect, so don't expect an immediate fix"
This work for me!
You can change your secret special value to 0, and exploit C's default structure-member semantics
struct foo bar = { .id = 42, .current_route = new_route };
update(&bar);
will then pass 0 as members of bar unspecified in the initializer.
Or you can create a macro that will do the default initialization for you:
#define FOO_INIT(...) { .id = -1, .current_route = -1, .quux = -1, ## __VA_ARGS__ }
struct foo bar = FOO_INIT( .id = 42, .current_route = new_route );
update(&bar);
My interpretation is: I think of YouTube it has a comment-section, and inside the comment-section there are multiple articles (in this case comments).
So a section is like a div-container that holds articles.
As already pointed out in comments by Abhijeet you can just add line like:
/target/**
to exclude file in \.git\info\
folder.
Then if you want to get rid of that target
folder in your remote repo you will need to first manually delete this folder from your local repository, commit and then push it. Thats because git will show you content of a target folder as modified at first.
I know this question is quite old, but I have not seen this solution here before:
If you rewrite the <body>
tag to.
<body oncontextmenu="return false;">
you can prevent the right click without using javascript.
However, you can't prevent keyboard shortcuts with HTML. For this, you must use Javascript.
PL/SQL: numeric or value error: character string buffer too small
is due to the fact that you declare a string to be of a fixed length (say 20), and at some point in your code you assign it a value whose length exceeds what you declared.
for example:
myString VARCHAR2(20);
myString :='abcdefghijklmnopqrstuvwxyz'; --length 26
will fire such an error
matcher.find()
does not find all matches, only the next match.
long matches = matcher.results().count();
You'll have to do the following. (Starting from Java 9, there is a nicer solution)
int count = 0;
while (matcher.find())
count++;
Btw, matcher.groupCount()
is something completely different.
Complete example:
import java.util.regex.*;
class Test {
public static void main(String[] args) {
String hello = "HelloxxxHelloxxxHello";
Pattern pattern = Pattern.compile("Hello");
Matcher matcher = pattern.matcher(hello);
int count = 0;
while (matcher.find())
count++;
System.out.println(count); // prints 3
}
}
When counting matches of aa
in aaaa
the above snippet will give you 2.
aaaa
aa
aa
To get 3 matches, i.e. this behavior:
aaaa
aa
aa
aa
You have to search for a match at index <start of last match> + 1
as follows:
String hello = "aaaa";
Pattern pattern = Pattern.compile("aa");
Matcher matcher = pattern.matcher(hello);
int count = 0;
int i = 0;
while (matcher.find(i)) {
count++;
i = matcher.start() + 1;
}
System.out.println(count); // prints 3
Enter this path in your System environment variable.
C:\Program Files\PostgreSQL\[YOUR PG VERSION]\bin
In this case i'm using version 10. If you check the postgres folder you are going to see your current versions.
In my own case i used the following on separate lines:
C:\Program Files\PostgreSQL\10\bin
C:\Program Files\PostgreSQL\10\lib
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Because Submit
button is inside login_modal
so you need to use loginDialog
view to access button:
Submit = (Button)loginDialog.findViewById(R.id.Submit);
OFFSET
is nothing but a keyword to indicate starting cursor in table
SELECT column FROM table LIMIT 18 OFFSET 8 -- fetch 18 records, begin with record 9 (OFFSET 8)
you would get the same result form
SELECT column FROM table LIMIT 8, 18
visual representation (R
is one record in the table in some order)
OFFSET LIMIT rest of the table
__||__ _______||_______ __||__
/ \ / \ /
RRRRRRRR RRRRRRRRRRRRRRRRRR RRRR...
\________________/
||
your result
strip
only removes characters from the beginning and end of a string. You want to use replace
:
str2 = str.replace("\n", "")
re.sub('\s{2,}', ' ', str) # To remove more than one space
You cannot resize an array in java.
Once the size of array is declared, it remains fixed.
Instead you can use ArrayList
that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.
ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);
String s4 ="Test4";
ar.add(s4);
I know this has already been answered. But I would like to add my solution as it may helpful for others in the future..
A common key error is: Permission denied (publickey)
. You can fix this by using keys:add
to notify Heroku of your new key.
In short follow these steps: https://devcenter.heroku.com/articles/keys
First you have to create a key if you don't have one:
ssh-keygen -t rsa
Second you have to add the key to Heroku:
heroku keys:add
You can run a container setting a shared directory (-v volume), and then run bash in that container. After this, you can interactively use mysql-client to execute the .sql file, from inside the container. obs: /my-host-dir/shared-dir is the .sql location in the host system.
docker run --detach --name=test-mysql -p host-port:container-port --env="MYSQL_ROOT_PASSWORD=my-root-pswd" -v /my-host-dir/shared-dir:/container-dir mysql:latest
docker exec -it test-mysql bash
Inside the container...
mysql -p < /container-dir/file.sql
Custom parameters:
Call make
command this way:
make CFLAGS=-Dvar=42
And be sure to use $(CFLAGS)
in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after the make
command will override the CFLAGS
value already defined the Makefile.
Alternatively you could set -Dvar=42
in another variable than CFLAGS
and then reuse this variable in CFLAGS
to avoid completely overriding CFLAGS
.
Most common AD default design is to have a container, cn=users just after the root of the domain. Thus a DN might be:
cn=admin,cn=users,DC=domain,DC=company,DC=com
Also, you might have sufficient rights in an LDAP bind to connect anonymously, and query for (cn=admin)
. If so, you should get the full DN back in that query.
<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">
window.history.back() does not support reload or refresh of the page. But you can use following if you are okay with an extra refresh
window.history.back()
window.location.reload()
However a real complete solution would be as follows: I wrote a service to keep track of previous page and then navigate to that page with reload:true
Here is how i did it.
'use strict';
angular.module('tryme5App')
.factory('RouterTracker', function RouterTracker($rootScope) {
var routeHistory = [];
var service = {
getRouteHistory: getRouteHistory
};
$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
routeHistory = [];
routeHistory.push({route: from, routeParams: fromParams});
});
function getRouteHistory() {
return routeHistory;
}
return service;
});
Make sure you have included this js file from you index.html
<script src="scripts/components/util/route.service.js"></script>
Now from you stateprovider or controller you can access this service and navigate
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });
or alternatively even perform checks and conditional routing
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
if(routeHistory[0].route.name == 'seat') {
$state.go('seat', null, { reload: true });
} else {
window.history.back()
}
Make sure you have added RouterTracker as an argument in your function in my case it was :
.state('seat.new', {
parent: 'seat',
url: '/new',
data: {
authorities: ['ROLE_USER'],
},
onEnter: ['$stateParams', '$state', '$uibModal', 'RouterTracker', function($stateParams, $state, $uibModal, RouterTracker) {
$uibModal.open({
//....Open dialog.....
}).result.then(function(result) {
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });
}, function() {
$state.go('^');
})
There are some classes in the Java platform libraries that do extend an instantiable class and add a value component. For example, java.sql.Timestamp extends java.util.Date and adds a nanoseconds field. The equals implementation for Timestamp does violate symmetry and can cause erratic behavior if Timestamp and Date objects are used in the same collection or are otherwise intermixed. The Timestamp class has a disclaimer cautioning programmers against mixing dates and timestamps. While you won’t get into trouble as long as you keep them separate, there’s nothing to prevent you from mixing them, and the resulting errors can be hard to debug. This behavior of the Timestamp class was a mistake and should not be emulated.
check out this link
http://blogs.sourceallies.com/2012/02/hibernate-date-vs-timestamp/
Change file AndroidManifest.xml
<uses-sdk android:minSdkVersion="19"/>
<uses-sdk android:minSdkVersion="14"/>
I haven't any personal experience with either of the following, but a simple search for a "Python [memory] profiler" yield:
PySizer, "a memory profiler for Python," found at http://pysizer.8325.org/. However the page seems to indicate that the project hasn't been updated for a while, and refers to...
Heapy, "support[ing] debugging and optimization regarding memory related issues in Python programs," found at http://guppy-pe.sourceforge.net/#Heapy.
Hope that helps.
This is actually the conventional use of the break
statement. If the break
statement wasn't nested in an if
block the for
loop could only ever execute one time.
MSDN lists this as their example for the break
statement.
Along with other issues that you can see in other answers. The way I created this error for myself was that I started a project from scratch and begin by deleting the initial scene of my storyboard and then pasted a scene from another project into my storyboard.
There is no problem in doing that. You only need to add an entry point of your storyboard i.e. check the is initial View Controller
on which ever view controller you like. Otherwise it will be a gray scene and throw you an error.
All type information is erased in JavaScript side and therefore you can't new up T just like @Sohnee states, but I would prefer having typed parameter passed in to constructor:
class A {
}
class B<T> {
Prop: T;
constructor(TCreator: { new (): T; }) {
this.Prop = new TCreator();
}
}
var test = new B<A>(A);
You probably need to declare the code below for height:100%
to work for your divs
html, body {margin:0;padding:0;height:100%;}
fiddle: http://jsfiddle.net/5KYC3/
From http://docs.python-requests.org/en/latest/user/quickstart/
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get
or .post
method.
So more specific to your question:
headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)
If your only requirement in your custom serializer is to skip serializing the name
field of User
, mark it as transient. Jackson will not serialize or deserialize transient fields.
[ see also: Why does Java have transient fields? ]
(For fellow googlers)
There is also Boost::date_time :
#include <boost/date_time/posix_time/posix_time.hpp>
boost::posix_time::ptime date_time = boost::posix_time::microsec_clock::universal_time();
This method does not need to modify dtype or ravel your numpy array.
The core idea is: 1.initialize with one extra row. 2.change the list(which has one more row) to array 3.delete the extra row in the result array e.g.
>>> a = [np.zeros((10,224)), np.zeros((10,))]
>>> np.array(a)
# this will raise error,
ValueError: could not broadcast input array from shape (10,224) into shape (10)
# but below method works
>>> a = [np.zeros((11,224)), np.zeros((10,))]
>>> b = np.array(a)
>>> b[0] = np.delete(b[0],0,0)
>>> print(b.shape,b[0].shape,b[1].shape)
# print result:(2,) (10,224) (10,)
Indeed, it's not necessarily to add one more row, as long as you can escape from the gap stated in @aravk33 and @user707650 's answer and delete the extra item later, it will be fine.
Sometimes a BEFORE
trigger can be replaced with an AFTER
one, but this doesn't appear to be the case in your situation, for you clearly need to provide a value before the insert takes place. So, for that purpose, the closest functionality would seem to be the INSTEAD OF
trigger one, as @marc_s has suggested in his comment.
Note, however, that, as the names of these two trigger types suggest, there's a fundamental difference between a BEFORE
trigger and an INSTEAD OF
one. While in both cases the trigger is executed at the time when the action determined by the statement that's invoked the trigger hasn't taken place, in case of the INSTEAD OF
trigger the action is never supposed to take place at all. The real action that you need to be done must be done by the trigger itself. This is very unlike the BEFORE
trigger functionality, where the statement is always due to execute, unless, of course, you explicitly roll it back.
But there's one other issue to address actually. As your Oracle script reveals, the trigger you need to convert uses another feature unsupported by SQL Server, which is that of FOR EACH ROW
. There are no per-row triggers in SQL Server either, only per-statement ones. That means that you need to always keep in mind that the inserted data are a row set, not just a single row. That adds more complexity, although that'll probably conclude the list of things you need to account for.
So, it's really two things to solve then:
replace the BEFORE
functionality;
replace the FOR EACH ROW
functionality.
My attempt at solving these is below:
CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
DECLARE @new_super TABLE (
super_id int
);
INSERT INTO super (subtype_discriminator)
OUTPUT INSERTED.super_id INTO @new_super (super_id)
SELECT 'SUB1' FROM INSERTED;
INSERT INTO sub (super_id)
SELECT super_id FROM @new_super;
END;
This is how the above works:
The same number of rows as being inserted into sub1
is first added to super
. The generated super_id
values are stored in a temporary storage (a table variable called @new_super
).
The newly inserted super_id
s are now inserted into sub1
.
Nothing too difficult really, but the above will only work if you have no other columns in sub1
than those you've specified in your question. If there are other columns, the above trigger will need to be a bit more complex.
The problem is to assign the new super_id
s to every inserted row individually. One way to implement the mapping could be like below:
CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
DECLARE @new_super TABLE (
rownum int IDENTITY (1, 1),
super_id int
);
INSERT INTO super (subtype_discriminator)
OUTPUT INSERTED.super_id INTO @new_super (super_id)
SELECT 'SUB1' FROM INSERTED;
WITH enumerated AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
FROM inserted
)
INSERT INTO sub1 (super_id, other columns)
SELECT n.super_id, i.other columns
FROM enumerated AS i
INNER JOIN @new_super AS n
ON i.rownum = n.rownum;
END;
As you can see, an IDENTIY(1,1)
column is added to @new_user
, so the temporarily inserted super_id
values will additionally be enumerated starting from 1. To provide the mapping between the new super_id
s and the new data rows, the ROW_NUMBER
function is used to enumerate the INSERTED
rows as well. As a result, every row in the INSERTED
set can now be linked to a single super_id
and thus complemented to a full data row to be inserted into sub1
.
Note that the order in which the new super_id
s are inserted may not match the order in which they are assigned. I considered that a no-issue. All the new super
rows generated are identical save for the IDs. So, all you need here is just to take one new super_id
per new sub1
row.
If, however, the logic of inserting into super
is more complex and for some reason you need to remember precisely which new super_id
has been generated for which new sub
row, you'll probably want to consider the mapping method discussed in this Stack Overflow question:
Use .gitattributes instead, with the following setting:
# Ignore all differences in line endings
* -crlf
.gitattributes would be found in the same directory as your global .gitconfig. If .gitattributes doesn't exist, add it to that directory. After adding/changing .gitattributes you will have to do a hard reset of the repository in order to successfully apply the changes to existing files.
this way we can iterate into table data.
DECLARE @_MinJobID INT
DECLARE @_MaxJobID INT
CREATE TABLE #Temp (JobID INT)
INSERT INTO #Temp SELECT * FROM DBO.STRINGTOTABLE(@JobID,',')
SELECT @_MinJID = MIN(JobID),@_MaxJID = MAX(JobID) FROM #Temp
WHILE @_MinJID <= @_MaxJID
BEGIN
INSERT INTO Mytable
(
JobID,
)
VALUES
(
@_MinJobID,
)
SET @_MinJID = @_MinJID + 1;
END
DROP TABLE #Temp
STRINGTOTABLE is user define function which will parse comma separated data and return table. thanks
Yes. Youtube API is the best resource for this.
There are 3 way to embed a video:
<iframe>
tagsDEPRECATED
I think you are looking for the second one of them:
The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.
<div id="ytplayer"></div>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE'
});
}
</script>
Here are some instructions where you may take a look when starting using the API.
An embed example without using iframe
is to use <object>
tag:
<object width="640" height="360">
<param name="movie" value="http://www.youtube.com/embed/yt-video-id?html5=1&rel=0&hl=en_US&version=3"/
<param name="allowFullScreen" value="true"/>
<param name="allowscriptaccess" value="always"/>
<embed width="640" height="360" src="http://www.youtube.com/embed/yt-video-id?html5=1&rel=0&hl=en_US&version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>
(replace yt-video-id
with your video id)
Is this what you had in mind?
$("document").ready( function() {
// do your stuff
}
The trick is to create subclasses of ViewHolder and then cast them.
public class GroupViewHolder extends RecyclerView.ViewHolder {
TextView mTitle;
TextView mContent;
public GroupViewHolder(View itemView) {
super (itemView);
// init views...
}
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
ImageView mImage;
public ImageViewHolder(View itemView) {
super (itemView);
// init views...
}
}
private static final int TYPE_IMAGE = 1;
private static final int TYPE_GROUP = 2;
And then, at runtime do something like this:
@Override
public int getItemViewType(int position) {
// here your custom logic to choose the view type
return position == 0 ? TYPE_IMAGE : TYPE_GROUP;
}
@Override
public void onBindViewHolder (ViewHolder viewHolder, int i) {
switch (viewHolder.getItemViewType()) {
case TYPE_IMAGE:
ImageViewHolder imageViewHolder = (ImageViewHolder) viewHolder;
imageViewHolder.mImage.setImageResource(...);
break;
case TYPE_GROUP:
GroupViewHolder groupViewHolder = (GroupViewHolder) viewHolder;
groupViewHolder.mContent.setText(...)
groupViewHolder.mTitle.setText(...);
break;
}
}
Hope it helps.
Using C++11:
#include <map>
using namespace std;
map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
Using Boost.Assign:
#include <map>
#include "boost/assign.hpp"
using namespace std;
using namespace boost::assign;
map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');
In my case(my machine is ubuntu 16), I append /etc/resolvconf/resolv.conf.d/base
file by adding below ns lines.
nameserver 8.8.8.8
nameserver 4.2.2.1
nameserver 2001:4860:4860::8844
nameserver 2001:4860:4860::8888
then run the update script,
resolvconf -u
This is what works for me:
watchman watch-del-all && rm -f yarn.lock && rm -rf node_modules && yarn && yarn start --reset-cache
Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash.
HTML:
<input type="file" name="FILENAME" size="20" onchange="check_extension(this.value,"upload");"/>
<input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" />
Javascript:
var hash = {
'xls' : 1,
'xlsx' : 1,
};
function check_extension(filename,submitId) {
var re = /\..+$/;
var ext = filename.match(re);
var submitEl = document.getElementById(submitId);
if (hash[ext]) {
submitEl.disabled = false;
return true;
} else {
alert("Invalid filename, please select another file");
submitEl.disabled = true;
return false;
}
}
You can tell the Java binary version by inspecting the first 8 bytes (or using an app that can).
The compiler itself doesn't, to the best of my knowledge, insert any identifying signature. I can't spot such a thing in the file VM spec class format anyway.
Based on the answers provided, I decided to make a quick plugin to do this:
(function($){
$.fn.moveTo = function(selector){
return this.each(function(){
var cl = $(this).clone();
$(cl).appendTo(selector);
$(this).remove();
});
};
})(jQuery);
Usage:
$('#nodeToMove').moveTo('#newParent');
It seems like you are asking about the difference between the data model and the domain model – the latter is where you can find the business logic and entities as perceived by your end user, the former is where you actually store your data.
Furthermore, I've interpreted the 3rd part of your question as: how to notice failure to keep these models separate.
These are two very different concepts and it's always hard to keep them separate. However, there are some common patterns and tools that can be used for this purpose.
The first thing you need to recognize is that your domain model is not really about data; it is about actions and questions such as "activate this user", "deactivate this user", "which users are currently activated?", and "what is this user's name?". In classical terms: it's about queries and commands.
Let's start by looking at the commands in your example: "activate this user" and "deactivate this user". The nice thing about commands is that they can easily be expressed by small given-when-then scenario's:
given an inactive user
when the admin activates this user
then the user becomes active
and a confirmation e-mail is sent to the user
and an entry is added to the system log
(etc. etc.)
Such scenario's are useful to see how different parts of your infrastructure can be affected by a single command – in this case your database (some kind of 'active' flag), your mail server, your system log, etc.
Such scenario's also really help you in setting up a Test Driven Development environment.
And finally, thinking in commands really helps you create a task-oriented application. Your users will appreciate this :-)
Django provides two easy ways of expressing commands; they are both valid options and it is not unusual to mix the two approaches.
The service module has already been described by @Hedde. Here you define a separate module and each command is represented as a function.
services.py
def activate_user(user_id):
user = User.objects.get(pk=user_id)
# set active flag
user.active = True
user.save()
# mail user
send_mail(...)
# etc etc
The other way is to use a Django Form for each command. I prefer this approach, because it combines multiple closely related aspects:
forms.py
class ActivateUserForm(forms.Form):
user_id = IntegerField(widget = UsernameSelectWidget, verbose_name="Select a user to activate")
# the username select widget is not a standard Django widget, I just made it up
def clean_user_id(self):
user_id = self.cleaned_data['user_id']
if User.objects.get(pk=user_id).active:
raise ValidationError("This user cannot be activated")
# you can also check authorizations etc.
return user_id
def execute(self):
"""
This is not a standard method in the forms API; it is intended to replace the
'extract-data-from-form-in-view-and-do-stuff' pattern by a more testable pattern.
"""
user_id = self.cleaned_data['user_id']
user = User.objects.get(pk=user_id)
# set active flag
user.active = True
user.save()
# mail user
send_mail(...)
# etc etc
You example did not contain any queries, so I took the liberty of making up a few useful queries. I prefer to use the term "question", but queries is the classical terminology. Interesting queries are: "What is the name of this user?", "Can this user log in?", "Show me a list of deactivated users", and "What is the geographical distribution of deactivated users?"
Before embarking on answering these queries, you should always ask yourself this question, is this:
Presentational queries are merely made to improve the user interface. The answers to business logic queries directly affect the execution of your commands. Reporting queries are merely for analytical purposes and have looser time constraints. These categories are not mutually exclusive.
The other question is: "do I have complete control over the answers?" For example, when querying the user's name (in this context) we do not have any control over the outcome, because we rely on an external API.
The most basic query in Django is the use of the Manager object:
User.objects.filter(active=True)
Of course, this only works if the data is actually represented in your data model. This is not always the case. In those cases, you can consider the options below.
The first alternative is useful for queries that are merely presentational: custom tags and template filters.
template.html
<h1>Welcome, {{ user|friendly_name }}</h1>
template_tags.py
@register.filter
def friendly_name(user):
return remote_api.get_cached_name(user.id)
If your query is not merely presentational, you could add queries to your services.py (if you are using that), or introduce a queries.py module:
queries.py
def inactive_users():
return User.objects.filter(active=False)
def users_called_publysher():
for user in User.objects.all():
if remote_api.get_cached_name(user.id) == "publysher":
yield user
Proxy models are very useful in the context of business logic and reporting. You basically define an enhanced subset of your model. You can override a Manager’s base QuerySet by overriding the Manager.get_queryset()
method.
models.py
class InactiveUserManager(models.Manager):
def get_queryset(self):
query_set = super(InactiveUserManager, self).get_queryset()
return query_set.filter(active=False)
class InactiveUser(User):
"""
>>> for user in InactiveUser.objects.all():
… assert user.active is False
"""
objects = InactiveUserManager()
class Meta:
proxy = True
For queries that are inherently complex, but are executed quite often, there is the possibility of query models. A query model is a form of denormalization where relevant data for a single query is stored in a separate model. The trick of course is to keep the denormalized model in sync with the primary model. Query models can only be used if changes are entirely under your control.
models.py
class InactiveUserDistribution(models.Model):
country = CharField(max_length=200)
inactive_user_count = IntegerField(default=0)
The first option is to update these models in your commands. This is very useful if these models are only changed by one or two commands.
forms.py
class ActivateUserForm(forms.Form):
# see above
def execute(self):
# see above
query_model = InactiveUserDistribution.objects.get_or_create(country=user.country)
query_model.inactive_user_count -= 1
query_model.save()
A better option would be to use custom signals. These signals are of course emitted by your commands. Signals have the advantage that you can keep multiple query models in sync with your original model. Furthermore, signal processing can be offloaded to background tasks, using Celery or similar frameworks.
signals.py
user_activated = Signal(providing_args = ['user'])
user_deactivated = Signal(providing_args = ['user'])
forms.py
class ActivateUserForm(forms.Form):
# see above
def execute(self):
# see above
user_activated.send_robust(sender=self, user=user)
models.py
class InactiveUserDistribution(models.Model):
# see above
@receiver(user_activated)
def on_user_activated(sender, **kwargs):
user = kwargs['user']
query_model = InactiveUserDistribution.objects.get_or_create(country=user.country)
query_model.inactive_user_count -= 1
query_model.save()
When using this approach, it becomes ridiculously easy to determine if your code stays clean. Just follow these guidelines:
The same goes for views (because views often suffer from the same problem).
Mirroring a repository
Create a bare clone of the repository.
git clone --bare https://github.com/exampleuser/old-repository.git
Mirror-push to the new repository.
cd old-repository.git
git push --mirror https://github.com/exampleuser/new-repository.git
Remove the temporary local repository you created in step 1.
cd ..
rm -rf old-repository.git
Mirroring a repository that contains Git Large File Storage objects
Create a bare clone of the repository. Replace the example username with the name of the person or organization who owns the repository, and replace the example repository name with the name of the repository you'd like to duplicate.
git clone --bare https://github.com/exampleuser/old-repository.git
Navigate to the repository you just cloned.
cd old-repository.git
Pull in the repository's Git Large File Storage objects.
git lfs fetch --all
Mirror-push to the new repository.
git push --mirror https://github.com/exampleuser/new-repository.git
Push the repository's Git Large File Storage objects to your mirror.
git lfs push --all https://github.com/exampleuser/new-repository.git
Remove the temporary local repository you created in step 1.
cd ..
rm -rf old-repository.git
Above instruction comes from Github Help: https://help.github.com/articles/duplicating-a-repository/
If you want to reverse the calculated binary form , you can use the StringBuffer class and simply use the reverse() method . Here is a sample program that will explain its use and calculate the binary
public class Binary {
public StringBuffer calculateBinary(int number) {
StringBuffer sBuf = new StringBuffer();
int temp = 0;
while (number > 0) {
temp = number % 2;
sBuf.append(temp);
number = number / 2;
}
return sBuf.reverse();
}
}
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("enter the number you want to convert");
BufferedReader bReader = new BufferedReader(newInputStreamReader(System.in));
int number = Integer.parseInt(bReader.readLine());
Binary binaryObject = new Binary();
StringBuffer result = binaryObject.calculateBinary(number);
System.out.println(result);
}
}
Since filter
returns a QuerySet
, you can use count to check how many results were returned. This is assuming you don't actually need the results.
num_results = User.objects.filter(email = cleaned_info['username']).count()
After looking at the documentation though, it's better to just call len on your filter if you are planning on using the results later, as you'll only be making one sql query:
A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).
num_results = len(user_object)
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
An actual JSON request would look like this:
data: '{"command":"on"}',
Where you're sending an actual JSON string. For a more general solution, use JSON.stringify()
to serialize an object to JSON, like this:
data: JSON.stringify({ "command": "on" }),
To support older browsers that don't have the JSON
object, use json2.js which will add it in.
What's currently happening is since you have processData: false
, it's basically sending this: ({"command":"on"}).toString()
which is [object Object]
...what you see in your request.
snippet to retrieve json data, password protected
import requests
username = "my_user_name"
password = "my_super_secret"
url = "https://www.my_base_url.com"
the_page_i_want = "/my_json_data_page"
session = requests.Session()
# retrieve cookie value
resp = session.get(url+'/login')
csrf_token = resp.cookies['csrftoken']
# login, add referer
resp = session.post(url+"/login",
data={
'username': username,
'password': password,
'csrfmiddlewaretoken': csrf_token,
'next': the_page_i_want,
},
headers=dict(Referer=url+"/login"))
print(resp.json())
To read binary ASCII characters with great speed using only your head:
Letters start with leading bits 01. Bit 3 is on (1) for lower case, off (0) for capitals. Scan the following bits 4–8 for the first that is on, and select the starting letter from the same index in this string: “PHDBA” (think P.H.D., Bachelors in Arts). E.g. 1xxxx = P, 01xxx = H, etc. Then convert the remaining bits to an integer value (e.g. 010 = 2), and count that many letters up from your starting letter. E.g. 01001010 => H+2 = J.
I don't think you have to escape the --init-file
parameter:
"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqld.exe" --defaults-file="C:\\Program Files\\MySQL\\MySQL Server 5.6\\my.ini" --init-file=C:\\mysql-init.txt
Should be:
"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqld.exe" --defaults-file="C:\\Program Files\\MySQL\\MySQL Server 5.6\\my.ini" --init-file=C:\mysql-init.txt
If a <script>
has a src
then the text content of the element will be not be executed as JS (although it will appear in the DOM).
You need to use multiple script elements.
<script>
to load the external scripta <script>
to hold your inline code (with the call to the function in the external script)
The Bash Reference Manual is an authoritative source of information about bash.
Here's an example of testing a variable to see if it exists:
if [ -z "$PS1" ]; then
echo This shell is not interactive
else
echo This shell is interactive
fi
(From section 6.3.2.)
Note that the whitespace after the open [
and before the ]
is not optional.
Tips for Vim users
I had a script that had several declarations as follows:
export VARIABLE_NAME="$SOME_OTHER_VARIABLE/path-part"
But I wanted them to defer to any existing values. So I re-wrote them to look like this:
if [ -z "$VARIABLE_NAME" ]; then
export VARIABLE_NAME="$SOME_OTHER_VARIABLE/path-part"
fi
I was able to automate this in vim using a quick regex:
s/\vexport ([A-Z_]+)\=("[^"]+")\n/if [ -z "$\1" ]; then\r export \1=\2\rfi\r/gc
This can be applied by selecting the relevant lines visually, then typing :
. The command bar pre-populates with :'<,'>
. Paste the above command and hit enter.
Tested on this version of Vim:
VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Aug 22 2015 15:38:58)
Compiled by [email protected]
Windows users may want different line endings.
I wrestled with this myself. A nice trick is to use use the current thread to get a ClassLoader when in a static context. This will work in a Hadoop MapReduce as well. Other methods work when running locally, but return a null InputStream when used in a MapReduce.
public static InputStream getResource(String resource) throws Exception {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
InputStream is = cl.getResourceAsStream(resource);
return is;
}
This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(\".navbar.navbar-default\").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}
You can use reorder
:
qplot(reorder(factor(cyl),factor(cyl),length),data=mtcars,geom="bar")
Edit:
To have the tallest bar at the left, you have to use a bit of a kludge:
qplot(reorder(factor(cyl),factor(cyl),function(x) length(x)*-1),
data=mtcars,geom="bar")
I would expect this to also have negative heights, but it doesn't, so it works!
The C++ Standard says it like this:
3.9.1, §2:
There are five signed integer types : "signed char", "short int", "int", "long int", and "long long int". In this list, each type provides at least as much storage as those preceding it in the list. Plain ints have the natural size suggested by the architecture of the execution environment (44); the other signed integer types are provided to meet special needs.
(44) that is, large enough to contain any value in the range of INT_MIN and INT_MAX, as defined in the header
<climits>
.
The conclusion: It depends on which architecture you're working on. Any other assumption is false.
I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.
scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop
The username@remotecomputer
is the same string you used with ssh initially.
I had played a bit with super()
, and had recognized that we can change calling order.
For example, we have next hierarchy structure:
A
/ \
B C
\ /
D
In this case MRO of D will be (only for Python 3):
In [26]: D.__mro__
Out[26]: (__main__.D, __main__.B, __main__.C, __main__.A, object)
Let's create a class where super()
calls after method execution.
In [23]: class A(object): # or with Python 3 can define class A:
...: def __init__(self):
...: print("I'm from A")
...:
...: class B(A):
...: def __init__(self):
...: print("I'm from B")
...: super().__init__()
...:
...: class C(A):
...: def __init__(self):
...: print("I'm from C")
...: super().__init__()
...:
...: class D(B, C):
...: def __init__(self):
...: print("I'm from D")
...: super().__init__()
...: d = D()
...:
I'm from D
I'm from B
I'm from C
I'm from A
A
/ ?
B ? C
? /
D
So we can see that resolution order is same as in MRO. But when we call super()
in the beginning of the method:
In [21]: class A(object): # or class A:
...: def __init__(self):
...: print("I'm from A")
...:
...: class B(A):
...: def __init__(self):
...: super().__init__() # or super(B, self).__init_()
...: print("I'm from B")
...:
...: class C(A):
...: def __init__(self):
...: super().__init__()
...: print("I'm from C")
...:
...: class D(B, C):
...: def __init__(self):
...: super().__init__()
...: print("I'm from D")
...: d = D()
...:
I'm from A
I'm from C
I'm from B
I'm from D
We have a different order it is reversed a order of the MRO tuple.
A
/ ?
B ? C
? /
D
For additional reading I would recommend next answers:
I have seen in unidirectional @ManytoOne, delete don't work as expected. When parent is deleted, ideally child should also be deleted, but only parent is deleted and child is NOT deleted and is left as orphan
Technology used are Spring Boot/Spring Data JPA/Hibernate
Sprint Boot : 2.1.2.RELEASE
Spring Data JPA/Hibernate is used to delete row .eg
parentRepository.delete(parent)
ParentRepository extends standard CRUD repository as shown below
ParentRepository extends CrudRepository<T, ID>
Following are my entity class
@Entity(name = “child”)
public class Child {
@Id
@GeneratedValue
private long id;
@ManyToOne( fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = “parent_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private Parent parent;
}
@Entity(name = “parent”)
public class Parent {
@Id
@GeneratedValue
private long id;
@Column(nullable = false, length = 50)
private String firstName;
}
open key.properties and check your path is correct. (replace from \ to /)
example:-
replace from "storeFile=D:\Projects\Flutter\Key\key.jks" to "storeFile=D:/Projects/Flutter/Key/key.jks"
What you really want to do is use an XML parser and append the new elements with the API provided.
Then simply overwrite the file.
The easiest to use would probably be a DOM parser like the one below:
In array you also can use variables passing to req.params:
app.get(["/:foo", "/:foo/:bar"], /* function */);
This is a method that works based on the text of the option, not the index. Just tested.
var theText = "GOOGLE";
$("#HowYouKnow option:contains(" + theText + ")").attr('selected', 'selected');
Or, if there are similar values (thanks shanabus):
$("#HowYouKnow option").each(function() {
if($(this).text() == theText) {
$(this).attr('selected', 'selected');
}
});
The StartsWith method will be faster, as there is no overhead of interpreting a regular expression, but here is how you do it:
if (Regex.IsMatch(theString, "^(mailto|ftp|joe):")) ...
The ^
mathes the start of the string. You can put any protocols between the parentheses separated by |
characters.
Another approach that is much faster, is to get the start of the string and use in a switch. The switch sets up a hash table with the strings, so it's faster than comparing all the strings:
int index = theString.IndexOf(':');
if (index != -1) {
switch (theString.Substring(0, index)) {
case "mailto":
case "ftp":
case "joe":
// do something
break;
}
}
One other way would be using colorbox
function createConfirm(message, okHandler) {
var confirm = '<p id="confirmMessage">'+message+'</p><div class="clearfix dropbig">'+
'<input type="button" id="confirmYes" class="alignleft ui-button ui-widget ui-state-default" value="Yes" />' +
'<input type="button" id="confirmNo" class="ui-button ui-widget ui-state-default" value="No" /></div>';
$.fn.colorbox({html:confirm,
onComplete: function(){
$("#confirmYes").click(function(){
okHandler();
$.fn.colorbox.close();
});
$("#confirmNo").click(function(){
$.fn.colorbox.close();
});
}});
}
If you have many cases and do not want to write a ton of strcmp()
calls, you could do something like:
switch(my_hash_function(the_string)) {
case HASH_B1: ...
/* ...etc... */
}
You just have to make sure your hash function has no collisions inside the set of possible values for the string.
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]']
instead of myCheckboxes.push
String FILE_NAME = "C:\\Ajay\\TEST\\data_996KB.json";
File file = new File(FILE_NAME);
if((file.length()) <= (1048576)) {
System.out.println("file size is less than 1 mb");
}else {
System.out.println("file size is More than 1 mb");
}
Note: 1048576= (1024*1024)=1MB output : file size is less than 1 mb
Just to add on to the other answers, before i knew my way around git, i was looking for some way to upload existing code to a new github (or other git) repo. Here's the brief that would save time for newbs:-
Assuming you have your NEW empty github or other git repo ready:-
cd "/your/repo/dir"
git clone https://github.com/user_AKA_you/repoName # (creates /your/repo/dir/repoName)
cp "/all/your/existing/code/*" "/your/repo/dir/repoName/"
git add -A
git commit -m "initial commit"
git push origin master
Alternatively if you have an existing local git repo
cd "/your/repo/dir/repoName"
#add your remote github or other git repo
git remote set-url origin https://github.com/user_AKA_you/your_repoName
git commit -m "new origin commit"
git push origin master
Function pointer is usually defined by typedef
, and used as param & return value.
Above answers already explained a lot, I just give a full example:
#include <stdio.h>
#define NUM_A 1
#define NUM_B 2
// define a function pointer type
typedef int (*two_num_operation)(int, int);
// an actual standalone function
static int sum(int a, int b) {
return a + b;
}
// use function pointer as param,
static int sum_via_pointer(int a, int b, two_num_operation funp) {
return (*funp)(a, b);
}
// use function pointer as return value,
static two_num_operation get_sum_fun() {
return ∑
}
// test - use function pointer as variable,
void test_pointer_as_variable() {
// create a pointer to function,
two_num_operation sum_p = ∑
// call function via pointer
printf("pointer as variable:\t %d + %d = %d\n", NUM_A, NUM_B, (*sum_p)(NUM_A, NUM_B));
}
// test - use function pointer as param,
void test_pointer_as_param() {
printf("pointer as param:\t %d + %d = %d\n", NUM_A, NUM_B, sum_via_pointer(NUM_A, NUM_B, &sum));
}
// test - use function pointer as return value,
void test_pointer_as_return_value() {
printf("pointer as return value:\t %d + %d = %d\n", NUM_A, NUM_B, (*get_sum_fun())(NUM_A, NUM_B));
}
int main() {
test_pointer_as_variable();
test_pointer_as_param();
test_pointer_as_return_value();
return 0;
}
and the implicit comment by many posters => Dont use arrays, use vectors. All of the benefits of arrays with none of the downsides. PLus you get lots of other goodies
If you dont know STL, read Josuttis The C++ standard library and meyers effective STL
CAST(QuantityLevel AS NUMERIC(18,2))
You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package
Here are a few options for changing text / label sizes
library(ggplot2)
# Example data using mtcars
a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))
p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=20)
The size
in the geom_text
changes the size of the geom_text
labels.
p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels
p <- p + theme(axis.title = element_text(size = 25)) # change axis titles
p <- p + theme(text = element_text(size = 10)) # this will change all text size
# (except geom_text)
For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?
Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text
sizes to theme
sizes.
So a horrible fix for uniform sizes is to scale by this ratio
geom.text.size = 7
theme.size = (14/5) * geom.text.size
ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=geom.text.size) +
theme(axis.text = element_text(size = theme.size, colour="black"))
This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)
For me what worked was:
rm -rf node_modules && npm install
And then
ng serve
BOOST_VERSION is defined in the boost header file version.hpp.
UTF-8 is a superset of ASCII. Either your UTF-8 file is ASCII, or it can't be converted without loss.
Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()
$.each(json, function (key, data) {
console.log(key)
$.each(data, function (index, data) {
console.log('index', data)
})
})
Demo: Fiddle
An alternative stacking arrangement which works and is perhaps a bit more intuitive is the following:
struct ContentView: View {
var body: some View {
HStack() {
VStack(alignment: .leading) {
Text("Hello World")
.font(.title)
Text("Another")
.font(.body)
Spacer()
}
Spacer()
}.background(Color.red)
}
}
The content can also easily be re-positioned by removing the Spacer()
's if necessary.
You can do the following, when your current directory is parent_directory
:
for d in [0-9][0-9][0-9]
do
( cd "$d" && your-command-here )
done
The (
and )
create a subshell, so the current directory isn't changed in the main script.
Yes you can; it works on Android too:
tel: phone_number
Calls the entered phone number. Valid telephone numbers as defined in the IETF RFC 3966 are accepted. Valid examples include the following:* tel:2125551212 * tel: (212) 555 1212
The Android browser uses the Phone app to handle the “tel” scheme, as defined by RFC 3966.
Clicking a link like:
<a href="tel:2125551212">2125551212</a>
on Android will bring up the Phone app and pre-enter the digits for 2125551212 without autodialing.
Have a look to RFC3966
function convert(str) {
var date = new Date(str),
mnth = ("0" + (date.getMonth()+1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
hours = ("0" + date.getHours()).slice(-2);
minutes = ("0" + date.getMinutes()).slice(-2);
return [ date.getFullYear(), mnth, day, hours, minutes ].join("-");
}
I used this efficiently in angular because i was losing two hours on updating a $scope.STARTevent, and $scope.ENDevent, IN console.log was fine, however saving to mYsql dropped two hours.
var whatSTART = $scope.STARTevent;
whatSTART = convert(whatever);
THIS WILL ALSO work for END
Definitively, for any PHP project, you may want to use GuzzleHTTP for sending requests. Guzzle has very nice documentation you can check here. I just want to say that, you probably want to centralize the usage of the Client class of Guzzle in any component of your Laravel project (for example a trait) instead of being creating Client instances on several controllers and components of Laravel (as many articles and replies suggest).
I created a trait you can try to use, which allows you to send requests from any component of your Laravel project, just using it and calling to makeRequest
.
namespace App\Traits;
use GuzzleHttp\Client;
trait ConsumesExternalServices
{
/**
* Send a request to any service
* @return string
*/
public function makeRequest($method, $requestUrl, $queryParams = [], $formParams = [], $headers = [], $hasFile = false)
{
$client = new Client([
'base_uri' => $this->baseUri,
]);
$bodyType = 'form_params';
if ($hasFile) {
$bodyType = 'multipart';
$multipart = [];
foreach ($formParams as $name => $contents) {
$multipart[] = [
'name' => $name,
'contents' => $contents
];
}
}
$response = $client->request($method, $requestUrl, [
'query' => $queryParams,
$bodyType => $hasFile ? $multipart : $formParams,
'headers' => $headers,
]);
$response = $response->getBody()->getContents();
return $response;
}
}
Notice this trait can even handle files sending.
If you want more details about this trait and some other stuff to integrate this trait to Laravel, check this article. Additionally, if interested in this topic or need major assistance, you can take my course which guides you in the whole process.
I hope it helps all of you.
Best wishes :)
When you run your application this way, the java excecutable read the MANIFEST inside your jar and find the main class you defined. In this class you have a static method called main. In this method you may use the command line arguments.
Try the following and see if it works:
<video width="400" height="300" preload controls>
<source src="video.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
Its working for me...
from selenium import webdriver
PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=http://%s' % PROXY)
chrome = webdriver.Chrome(chrome_options=chrome_options)
chrome.get("http://whatismyipaddress.com")
You can create a 'comment' table, with an id as primary key, then you add a text field to capture the text inserted by the user and you need another field to link the comment table to the article table (foreign key). Plus you need a field to store the user that has entered a comment, this field can be the user's email. Then you capture via GET or POST the user's email and comment and you insert everything in the DB:
"INSERT INTO comment (comment, email, approved) VALUES ('$comment', '$email', '$approved')"
This is a first hint. Of course adding a comment feature it takes a little bit. Then you should think about a form to let the admin to approve the comments and how to publish the comments in the end of articles.
You use input.files
property. It's a collection of File objects and each file has a name
property:
onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"
You didn't mention the fancy indexing capabilities of dataframes, e.g.:
>>> df = pd.DataFrame({"class":[1,1,1,2,2], "value":[1,2,3,4,5]})
>>> df[df["class"]==1].sum()
class 3
value 6
dtype: int64
>>> df[df["class"]==1].sum()["value"]
6
>>> df[df["class"]==1].count()["value"]
3
You could replace df["class"]==1
by another condition.
First, given that you have a complex data retrieval scenario, are you sure even SQLite is overkill?
You'll end up having an ad hoc, informally-specified, bug-ridden, slow implementation of half of SQLite, paraphrasing Greenspun's Tenth Rule.
That said, you are very right in saying that choosing a single data structure will impact one or more of searching, sorting or counting, so if performance is paramount and your data is constant, you could consider having more than one structure for different purposes.
Above all, measure what operations will be more common and decide which structure will end up costing less.
if you just want the number of occurences then you can do this, $ grep -c "string_to_count" file_name
What you should do is create a service to share data between controllers.
Nice tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk
You could return the value using return JsonConvert.SerializeObject(objName); And send it to the front end
This is a global solution, not dependent on particular package or bin.
In my case, I removed Packages folder from my root directory.
Maybe it happens because of your packages are there but compiler is not finding it's reference. so remove older packages first and add new packages.
Steps to Add new packages
This is not proper solution, but I posted it here because I face same issue.
In my case, I wasn't even able to open my solution in visual studio and didn't get any help with other SO answers.
As already stated by Jason Cohen, the Java Language Specification defines what a legal identifier is in section 3.8:
"An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. [...] A 'Java letter' is a character for which the method Character.isJavaIdentifierStart(int) returns true. A 'Java letter-or-digit' is a character for which the method Character.isJavaIdentifierPart(int) returns true."
This hopefully answers your second question. Regarding your first question; I've been taught both by teachers and (as far as I can remember) Java compilers that a Java class name should be an identifier that begins with a capital letter A-Z, but I can't find any reliable source on this. When trying it out with OpenJDK there are no warnings when beginning class names with lower-case letters or even a $-sign. When using a $-sign, you do have to escape it if you compile from a bash shell, however.
Is it because some culture format issue?
Yes. Your user must be in a culture where the time separator is a dot. Both ":" and "/" are interpreted in a culture-sensitive way in custom date and time formats.
How can I make sure the result string is delimited by colon instead of dot?
I'd suggest specifying CultureInfo.InvariantCulture
:
string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",
CultureInfo.InvariantCulture);
Alternatively, you could just quote the time and date separators:
string text = dateTime.ToString("MM'/'dd'/'yyyy HH':'mm':'ss.fff");
... but that will give you "interesting" results that you probably don't expect if you get users running in a culture where the default calendar system isn't the Gregorian calendar. For example, take the following code:
using System;
using System.Globalization;
using System.Threading;
class Test
{
static void Main()
{
DateTime now = DateTime.Now;
CultureInfo culture = new CultureInfo("ar-SA"); // Saudi Arabia
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
}
}
That produces output (on September 18th 2013) of:
11/12/1434 15:04:31.750
My guess is that your web service would be surprised by that!
I'd actually suggest not only using the invariant culture, but also changing to an ISO-8601 date format:
string text = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff");
This is a more globally-accepted format - it's also sortable, and makes the month and day order obvious. (Whereas 06/07/2013 could be interpreted as June 7th or July 6th depending on the reader's culture.)
This is how I am using it. And it is working fantastically -
public enum Button {
REPORT_ISSUES(0),
CANCEL_ORDER(1),
RETURN_ORDER(2);
private int value;
Button(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
And the switch-case
as shown below
@Override
public void onClick(MyOrderDetailDelgate.Button button, int position) {
switch (button) {
case REPORT_ISSUES: {
break;
}
case CANCEL_ORDER: {
break;
}
case RETURN_ORDER: {
break;
}
}
}
Resources in Scala work exactly as they do in Java.
It is best to follow the Java best practices and put all resources in src/main/resources
and src/test/resources
.
Example folder structure:
testing_styles/
+-- build.sbt
+-- src
¦ +-- main
¦ +-- resources
¦ ¦ +-- readme.txt
To read resources the object Source provides the method fromResource.
import scala.io.Source
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines
To read resources you can use getClass.getResource and getClass.getResourceAsStream .
val stream: InputStream = getClass.getResourceAsStream("/readme.txt")
val lines: Iterator[String] = scala.io.Source.fromInputStream( stream ).getLines
To avoid undebuggable Java NPEs, consider:
import scala.util.Try
import scala.io.Source
import java.io.FileNotFoundException
object Example {
def readResourceWithNiceError(resourcePath: String): Try[Iterator[String]] =
Try(Source.fromResource(resourcePath).getLines)
.recover(throw new FileNotFoundException(resourcePath))
}
Keep in mind that getResourceAsStream also works fine when the resources are part of a jar, getResource, which returns a URL which is often used to create a file can lead to problems there.
In production code I suggest to make sure that the source is closed again.
You should use Array.reduce
for this.
var options = [_x000D_
{ name: 'One', assigned: true }, _x000D_
{ name: 'Two', assigned: false }, _x000D_
{ name: 'Three', assigned: true }, _x000D_
];_x000D_
_x000D_
var reduced = options.reduce(function(filtered, option) {_x000D_
if (option.assigned) {_x000D_
var someNewValue = { name: option.name, newProperty: 'Foo' }_x000D_
filtered.push(someNewValue);_x000D_
}_x000D_
return filtered;_x000D_
}, []);_x000D_
_x000D_
document.getElementById('output').innerHTML = JSON.stringify(reduced);
_x000D_
<h1>Only assigned options</h1>_x000D_
<pre id="output"> </pre>
_x000D_
Alternatively, the reducer can be a pure function, like this
var reduced = options.reduce(function(result, option) {
if (option.assigned) {
return result.concat({
name: option.name,
newProperty: 'Foo'
});
}
return result;
}, []);
To have the active
tab also styled, merge the answer from this thread, from Mansukh Khandhar, with this other answer, from lmgonzalves:
.nav-tabs > li.active > a {
background-color: yellow !important;
border: medium none;
border-radius: 0;
}
String str = "abcdef";
char[] ch = str.toCharArray();
for(char c : ch){
int temp = (int)c;
int temp_integer = 96; //for lower case
if(temp<=122 & temp>=97)
System.out.print(temp-temp_integer);
}
Output:
123456
@Shiki for Capital/UpperCase letters use the following code:
String str = "DEFGHI";
char[] ch = str.toCharArray();
for(char c : ch){
int temp = (int)c;
int temp_integer = 64; //for upper case
if(temp<=90 & temp>=65)
System.out.print(temp-temp_integer);
}
Output:
456789
Here's a sample class:
public class Increment
{
public static void main(String [] args)
{
for (int i = 0; i < args.length; ++i)
{
System.out.println(args[i]);
}
}
}
If I disassemble this class using javap.exe I get this:
Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: aload_0
4: arraylength
5: if_icmpge 23
8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
11: aload_0
12: iload_1
13: aaload
14: invokevirtual #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
17: iinc 1, 1
20: goto 2
23: return
}
If I change the loop so it uses i++ and disassemble again I get this:
Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: aload_0
4: arraylength
5: if_icmpge 23
8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
11: aload_0
12: iload_1
13: aaload
14: invokevirtual #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
17: iinc 1, 1
20: goto 2
23: return
}
When I compare the two, TextPad tells me that the two are identical.
What this says is that from the point of view of the generated byte code there's no difference in a loop. In other contexts there is a difference between ++i and i++, but not for loops.
This code seems completely unnecessary:
String serverURLS = getRecipientURL(message);
serverURLS = "https:\\\\abc.my.domain.com:55555\\update";
if (serverURLS != null){
serverURL = new URL(serverURLS);
}
serverURLS
is assigned the result of getRecipientURL(message)
serverURLS
, making the previous statement a dead storeif (serverURLS != null)
evaluates to true
, since you just assigned the variable a value in the preceding statement, you assign a value to serverURL
. It is impossible for if (serverURLS != null)
to evaluate to false
!serverURLS
beyond the previous line of code.You could replace all of this with just:
serverURL = new URL("https:\\\\abc.my.domain.com:55555\\update");
block elements expand to fill their parent.
inline elements contract to be just big enough to hold their children.
If you see this intermittently on wifi or LAN, but your mobile internet connection seems ok, it is most likely your ISP's cheap gateway router is experiencing high traffic load.
You should trap these errors and display a reminder to the user to close any other apps using the network.
Test by running a couple of HD youtube videos on your desktop to reproduce, or just go to a busy Starbucks.
In Scala and Spark 2+, try this (assuming your column name is "s"):
df.select('s).as[String].collect
I would suggest instead of trying to extract the HTML from the WebView, you extract the HTML from the URL. By this, I mean using a third party library such as JSoup to traverse the HTML for you. The following code will get the HTML from a specific URL for you
public static String getHtml(String url) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()
)
);
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
return result;
}
As Sotirios Delimanolis already pointed out in the comments, there are two options:
ResponseEntity
with error messageChange your method like this:
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUser(@RequestHeader(value="Access-key") String accessKey,
@RequestHeader(value="Secret-key") String secretKey) {
try {
// see note 1
return ResponseEntity
.status(HttpStatus.CREATED)
.body(this.userService.chkCredentials(accessKey, secretKey, timestamp));
}
catch(ChekingCredentialsFailedException e) {
e.printStackTrace(); // see note 2
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note 1: You don't have to use the ResponseEntity
builder but I find it helps with keeping the code readable. It also helps remembering, which data a response for a specific HTTP status code should include. For example, a response with the status code 201 should contain a link to the newly created resource in the Location
header (see Status Code Definitions). This is why Spring offers the convenient build method ResponseEntity.created(URI)
.
Note 2: Don't use printStackTrace()
, use a logger instead.
@ExceptionHandler
Remove the try-catch block from your method and let it throw the exception. Then create another method in a class annotated with @ControllerAdvice
like this:
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(ChekingCredentialsFailedException.class)
public ResponseEntity handleException(ChekingCredentialsFailedException e) {
// log exception
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note that methods which are annotated with @ExceptionHandler
are allowed to have very flexible signatures. See the Javadoc for details.
I would probably use an integer as your primary key, and then just have your string (I assume it's some sort of ID) as a separate column.
create table sample (
sample_pk INT NOT NULL AUTO_INCREMENT,
sample_id VARCHAR(100) NOT NULL,
...
PRIMARY KEY(sample_pk)
);
You can always do queries and joins conditionally on the string (ID) column (where sample_id = ...).
Resolved this problem using a Sequence ID defined in Oracle database.
ORACLE_DB_SEQ_ID
is defined as a sequence for the table. Also look at the console to see the Hibernate SQL that is used to verify.
@Id
@Column(name = "MY_ID", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "id_Sequence")
@SequenceGenerator(name = "id_Sequence", sequenceName = "ORACLE_DB_SEQ_ID")
Long myId;
You could do something like this
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:6740/api/Membership/exist");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = 6;
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
And then strReponse should contain the values returned by your webservice
Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.
git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67
Then, abort the rebase again.
For what it's worth, I encountered this when I created an IntelliJ project on a Mac, and then moved the project over to my Windows machine. I had to manually open every file and change the encoding setting at the bottom right of the IntelliJ window. Probably not happening to most if any who read this question but that could have saved me a couple of hours of work...
Java 8 now supports BASE64 Encoding and Decoding. You can use the following classes:
java.util.Base64
, java.util.Base64.Encoder
and java.util.Base64.Decoder
.
Example usage:
// encode with padding
String encoded = Base64.getEncoder().encodeToString(someByteArray);
// encode without padding
String encoded = Base64.getEncoder().withoutPadding().encodeToString(someByteArray);
// decode a String
byte [] barr = Base64.getDecoder().decode(encoded);
Try it:
is_even = lambda x: True if x % 2 == 0 else False
print(is_even(10))
print(is_even(11))
Out:
True
False
I'd like to extend the paulalexandru's answer and put here complete solution that works generally with bootstrap dropdowns and updating main button's content and also the value from selected option.
The bootstrap dropdown is defined this way:
<div class="btn-group" role="group">
<button type="button" data-toggle="dropdown" value="1" class="btn btn-default btn-sm dropdown-toggle">
Option 1 <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#" data-value="1">Option 1</a></li>
<li><a href="#" data-value="2">Option 2</a></li>
<li><a href="#" data-value="3">Option 3</a></li>
</ul>
</div>
Additional to standard bootstrap dropdown code, there is data-value
attribute for storing the values in every dropdown option (in <a>
element).
Now the JS code. I crated function that handle the dropdowns:
function dropdownToggle() {
// select the main dropdown button element
var dropdown = $(this).parent().parent().prev();
// change the CONTENT of the button based on the content of selected option
dropdown.html($(this).html() + ' </i><span class="caret"></span>');
// change the VALUE of the button based on the data-value property of selected option
dropdown.val($(this).prop('data-value'));
}
And of course we need to add event listener:
$(document).ready(function(){
$('.dropdown-menu a').on('click', dropdownToggle);
}
Use of "and" in conditional. I often use this when importing in Jupyter Notebook:
def find_local_py_scripts():
import os # does not cost if already imported
for entry in os.scandir('.'):
# find files ending with .py
if entry.is_file() and entry.name.endswith(".py") :
print("- ", entry.name)
find_local_py_scripts()
- googlenet_custom_layers.py
- GoogLeNet_Inception_v1.py
Others have explained that no, you don't want this in version control. You should configure your version control system to ignore the file (e.g. via a .gitignore
file).
To really understand why, it helps to see what's actually in this file. I wrote a command line tool that lets you see the .suo
file's contents.
Install it on your machine via:
dotnet tool install -g suo
It has two sub-commands, keys
and view
.
suo keys <path-to-suo-file>
This will dump out the key for each value in the file. For example (abridged):
nuget
ProjInfoEx
BookmarkState
DebuggerWatches
HiddenSlnFolders
ObjMgrContentsV8
UnloadedProjects
ClassViewContents
OutliningStateDir
ProjExplorerState
TaskListShortcuts
XmlPackageOptions
BackgroundLoadData
DebuggerExceptions
DebuggerFindSource
DebuggerFindSymbol
ILSpy-234190A6EE66
MRU Solution Files
UnloadedProjectsEx
ApplicationInsights
DebuggerBreakpoints
OutliningStateV1674
...
As you can see, lots of IDE features use this file to store their state.
Use the view
command to see a given key's value. For example:
$ suo view nuget --format=utf8 .suo
nuget
?{"WindowSettings":{"project:MyProject":{"SourceRepository":"nuget.org","ShowPreviewWindow":false,"ShowDeprecatedFrameworkWindow":true,"RemoveDependencies":false,"ForceRemove":false,"IncludePrerelease":false,"SelectedFilter":"UpdatesAvailable","DependencyBehavior":"Lowest","FileConflictAction":"PromptUser","OptionsExpanded":false,"SortPropertyName":"ProjectName","SortDirection":"Ascending"}}}
More information on the tool here: https://github.com/drewnoakes/suo
My solution was to change the "Enable 32-Bit Applications" to True in the advanced settings of the relative app pool in IIS.
If this is from a SQL Server datebase you could issue this kind of query...
Select Top 1 DepartureTime From TrainSchedule where DepartureTime >
GetUTCDate()
Order By DepartureTime ASC
GetDate()
could also be used, not sure how dates are being stored.
I am not sure how the data is being stored and/or read.
To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all')
. It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.
var comment = document.getElementsByClassName("button");_x000D_
_x000D_
function showComment() {_x000D_
var place = document.getElementById('textfield');_x000D_
var commentBox = document.createElement('textarea');_x000D_
place.appendChild(commentBox);_x000D_
}_x000D_
_x000D_
for (var i in comment) {_x000D_
comment[i].onclick = function() {_x000D_
showComment();_x000D_
};_x000D_
}
_x000D_
<input type="button" class="button" value="1">_x000D_
<input type="button" class="button" value="2">_x000D_
<div id="textfield"></div>
_x000D_
As the OP states, TortoiseSVN has a built in changelist, "ignore-on-commit", which is automatically excluded from commits. The command-line client does not have this, so you need to use multiple changelists to accomplish this same behavior (with caveats):
Since there's precedent with TortoiseSVN, I use "ignore-on-commit" in my examples for the files I don't want to commit. I'll use "work" for the files I do, but you could pick any name you wanted.
First, add all files to a changelist named "work". This must be run from the root of your working copy:
svn cl work . -R
This will add all files in the working copy recursively to the changelist named "work". There is a disadvantage to this - as new files are added to the working copy, you'll need to specifically add the new files or they won't be included. Second, if you have to run this again you'll then need to re-add all of your "ignore-on-commit" files again. Not ideal - you could start maintaining your own 'ignore' list in a file as others have done.
Then, for the files you want to exclude:
svn cl ignore-on-commit path\to\file-to-ignore
Because files can only be in one changelist, running this addition after your previous "work" add will remove the file you want to ignore from the "work" changelist and put it in the "ignore-on-commit" changelist.
When you're ready to commit your modified files you do wish to commit, you'd then simply add "--cl work" to your commit:
svn commit --cl work -m "message"
Here's what a simple example looks like on my machine:
D:\workspace\trunk>svn cl work . -R
Skipped '.'
Skipped 'src'
Skipped 'src\conf'
A [work] src\conf\db.properties
Skipped 'src\java'
Skipped 'src\java\com'
Skipped 'src\java\com\corp'
Skipped 'src\java\com\corp\sample'
A [work] src\java\com\corp\sample\Main.java
Skipped 'src\java\com\corp\sample\controller'
A [work] src\java\com\corp\sample\controller\Controller.java
Skipped 'src\java\com\corp\sample\model'
A [work] src\java\com\corp\sample\model\Model.java
Skipped 'src\java\com\corp\sample\view'
A [work] src\java\com\corp\sample\view\View.java
Skipped 'src\resource'
A [work] src\resource\icon.ico
Skipped 'src\test'
D:\workspace\trunk>svn cl ignore-on-commit src\conf\db.properties
D [work] src\conf\db.properties
A [ignore-on-commit] src\conf\db.properties
D:\workspace\trunk>svn status
--- Changelist 'work':
src\java\com\corp\sample\Main.java
src\java\com\corp\sample\controller\Controller.java
src\java\com\corp\sample\model\Model.java
M src\java\com\corp\sample\view\View.java
src\resource\icon.ico
--- Changelist 'ignore-on-commit':
M src\conf\db.properties
D:\workspace\trunk>svn commit --cl work -m "fixed refresh issue"
Sending src\java\com\corp\sample\view\View.java
Transmitting file data .done
Committing transaction...
Committed revision 9.
An alternative would be to simply add every file you wish to commit to a 'work' changelist, and not even maintain an ignore list, but this is a lot of work, too. Really, the only simple, ideal solution is if/when this gets implemented in SVN itself. There's a longstanding issue about this in the Subversion issue tracker, SVN-2858, in the event this changes in the future.
Here is a great resource for detecting browsers in php: http://php.net/manual/en/function.get-browser.php
Here is one of the examples that seems the simplest:
<?php
function get_user_browser()
{
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$ub = '';
if(preg_match('/MSIE/i',$u_agent))
{
$ub = "ie";
}
elseif(preg_match('/Firefox/i',$u_agent))
{
$ub = "firefox";
}
elseif(preg_match('/Safari/i',$u_agent))
{
$ub = "safari";
}
elseif(preg_match('/Chrome/i',$u_agent))
{
$ub = "chrome";
}
elseif(preg_match('/Flock/i',$u_agent))
{
$ub = "flock";
}
elseif(preg_match('/Opera/i',$u_agent))
{
$ub = "opera";
}
return $ub;
}
?>
Then later in your code you could say something like
$browser = get_user_browser();
if($browser == "ie"){
//do stuff
}
AssertJ 1.4+ has specific assertions to compare XML content:
String expectedXml = "<foo />";
String actualXml = "<bar />";
assertThat(actualXml).isXmlEqualTo(expectedXml);
Here is the Documentation
That's correct, initially the ResultSet
's cursor is pointing to before the first row, if the first call to next()
returns false
then there was no data in the ResultSet
.
If you use this method, you may have to call beforeFirst()
immediately after to reset it, since it has positioned itself past the first row now.
It should be noted however, that Seifer's answer below is a more elegant solution to this question.
- (IBAction)logOutButton:(id)sender
{
//show confirmation message to user
CustomAlert* alert = [[CustomAlert alloc] initWithTitle:@"Confirmation" message:@"Do you want to exit?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
alert.style = AlertStyleWhite;
[alert setFontName:@"Helvetica" fontColor:[UIColor blackColor] fontShadowColor:[UIColor clearColor]];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != 0) // 0 == the cancel button
{
//home button press programmatically
UIApplication *app = [UIApplication sharedApplication];
[app performSelector:@selector(suspend)];
//wait 2 seconds while app is going background
[NSThread sleepForTimeInterval:2.0];
//exit app when app is in background
NSLog(@"exit(0)");
exit(0);
}
}
static class Constants
{
public const int MIN_LENGTH = 5;
public const int MIN_WIDTH = 5;
public const int MIN_HEIGHT = 6;
}
// elsewhere
public CBox()
{
length = Constants.MIN_LENGTH;
width = Constants.MIN_WIDTH;
height = Constants.MIN_HEIGHT;
}
Check out mycrypt(): http://us.php.net/manual/en/book.mcrypt.php
And if you're using postgres there's pgcrypto for database level encryption. (makes it easier to search and sort)
scp -r C:/site user@server_ip:path
path
is the place, where site
will be copied into the remote server
EDIT: As I said in my comment, try pscp
, as you want to use scp
using PuTTY
.
The other option is WinSCP
You could use a namedtuple instead of a dict. This is a shorthand for using a data class. Instead of
person = {'name': 'John', 'age': 14}
...do:
from collections import namedtuple
Person = namedtuple('person', ['name', 'age'])
p = Person(name='John', age=14)
p.name # 'John'
This is the same as writing a class that just holds data. In general I would avoid using dicts in django templates because they are awkward.
Most of the answers up there didn't help me..
What helped me was NODE_ENV=production&& nodemon app/app.js
Take note of the space. Good luck.
Ubuntu/Unix && MacOS
My Metro Bundler was stuck and there were lots of node processes running but I didn't have any other development going on besides react-native, so I ran:
$ killall -9 node
The Metro Bundler is running through node on port 8081 by default, and it can encounter issues sometimes whereby it gets stuck (usually due to pressing CTRL+S in rapid succession with hot reloading on). If you press CTRL+C to kill the react-native run-android
process, you will suddenly have a bad time because react-native-run-android
will get stuck on :
Scanning folders for symlinks in /home/poop/dev/some-app/node_modules (41ms)
Fix:
$ killall -9 node
$ react-native run-android
Note: if you are developing other apps at the time, killing all the node proceses may interrupt them or any node-based services you have running, so be mindful of the sweeping nature of killall -9
. If you aren't running a node-based database or app or you don't mind manually restarting them, then you should be good to go.
The reason I leave this detailed answer on this semi-unrelated question is that mine is a solution to a common semi-related problem that sadly requires 2 steps to fix but luckily only takes 2 steps get back to work.
If you want to surgically remove exactly the Metro Bundler garbage on port 8081, do the steps in the answer from RC_02, which are:
$ sudo lsof -i :8081
$ kill -9 23583
(where 23583 is the process ID)
If you want to have LETTERS, SPECIAL CHARACTERS and NUMBERS in your password with at least 8 digit, then use this code, it is working perfectly
public static boolean Password_Validation(String password)
{
if(password.length()>=8)
{
Pattern letter = Pattern.compile("[a-zA-z]");
Pattern digit = Pattern.compile("[0-9]");
Pattern special = Pattern.compile ("[!@#$%&*()_+=|<>?{}\\[\\]~-]");
//Pattern eight = Pattern.compile (".{8}");
Matcher hasLetter = letter.matcher(password);
Matcher hasDigit = digit.matcher(password);
Matcher hasSpecial = special.matcher(password);
return hasLetter.find() && hasDigit.find() && hasSpecial.find();
}
else
return false;
}
Is it not possible in your case to do the AND on several matching results? in pseudocode
regexp_match(pattern1, data) && regexp_match(pattern2, data) && ...
You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.
Gonna give another answer, since the libraries mentioned haven't been actively developed anymore.
Consider using YoutubeExplode. It has a very rich and consistent API and allows you to do a lot of other things with youtube videos beside downloading them.
Use a version GET
variable to prevent browser caching.
Appending ?v=AUTO_INCREMENT_VERSION
to the end of your url prevents browser caching - avoiding any and all cached scripts.
I know this might sound silly, but I recently came across this myself, Make sure the domain controller is not read-only.
For what it is worth, Bjarne Stroustrup, the original author of C++ has his own favorite style, described here: http://www.stroustrup.com/bs_faq2.html
Replace the line in htpasswd file:
Go to: http://www.htaccesstools.com/htpasswd-generator-windows/
(If the link is expired, search another generator from google.com.)
Enter your username and password. The site will generate an encrypted line. Copy that line and replace it with the previous line in the file "repo/htpasswd".
You might also need to Clear the 'Authentication data' from TortoiseSVN ? Settings ? Saved Data.
Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.
I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html
To support both Python 2 and Python 3, use explicit relative imports as below. They are relative to the current module. They have been supported starting from 2.5.
from .sister import foo
from . import brother
from ..aunt import bar
from .. import uncle
MySQL has restrictions about referring to the table you are deleting from. You can work around that with a temporary table, like:
create temporary table tmpTable (id int);
insert into tmpTable
(id)
select id
from YourTable yt
where exists
(
select *
from YourTabe yt2
where yt2.title = yt.title
and yt2.company = yt.company
and yt2.site_id = yt.site_id
and yt2.id > yt.id
);
delete
from YourTable
where ID in (select id from tmpTable);
From Kostanos' suggestion in the comments:
The only slow query above is DELETE, for cases where you have a very large database. This query could be faster:
DELETE FROM YourTable USING YourTable, tmpTable WHERE YourTable.id=tmpTable.id
While working with spark in EMR I was having the same problem and setting maximizeResourceAllocation=true
did the trick; hope it helps someone. You have to set it when you create the cluster. From the EMR docs:
aws emr create-cluster --release-label emr-5.4.0 --applications Name=Spark \
--instance-type m3.xlarge --instance-count 2 --service-role EMR_DefaultRole --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole --configurations https://s3.amazonaws.com/mybucket/myfolder/myConfig.json
Where myConfig.json should say:
[
{
"Classification": "spark",
"Properties": {
"maximizeResourceAllocation": "true"
}
}
]
I had the same problem for different package. I was installing pyinstaller
in conda on Mac Mojave. I did
conda create --name ai37 python=3.7
conda activate ai37
I got the mentioned error when I tried to install pyinstaller using
pip install pyinstaller
I was able to install the pyinstaller with the following command
conda install -c conda-forge pyinstaller
Git rebase is used to make the branching paths in history cleaner and repository structure linear.
It is also used to keep the branches created by you private, as after rebasing and pushing the changes to the server, if you delete your branch, there will be no evidence of branch you have worked on. So your branch is now your local concern.
After doing rebase we also get rid of an extra commit which we used to see if we do a normal merge.
And yes, one still needs to do merge after a successful rebase as the rebase command just puts your work on top of the branch you mentioned during rebase, say master, and makes the first commit of your branch as a direct descendant of the master branch. This means we can now do a fast forward merge to bring changes from this branch to the master branch.
Code bellow allows to play mp3-files and in-memory wave-files too
player.FileName = "123.mp3";
player.Play();
from http://alvas.net/alvas.audio,samples.aspx#sample6 or
Player pl = new Player();
byte[] arr = File.ReadAllBytes(@"in.wav");
pl.Play(arr);
Try Using
string filename = Path.GetFileName(FileUploadControl.FileName);
Then Save the file at specified location using:
FileUploadControl.PostedFile.SaveAs(strpath + filename);
1.find table "dbo._EFMigrationsHistory", then delete the migration record that you want to remove. 2. run "remove-migration" in PM(Package Manager Console). Works for me.
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you can send it to the server side with Ajax.
Maybe you want to use twill. It's quite easy to use and should be able to do what you want.
It will look like the following:
from twill.commands import *
go('http://example.org')
fv("1", "email-email", "blabla.com")
fv("1", "password-clear", "testpass")
submit('0')
You can use showforms()
to list all forms once you used go…
to browse to the site you want to login. Just try it from the python interpreter.
After PHP 5 you can use this: echo date("c");
form ISO 8601 formatted datetime.
Note for comments:
Regarding to this, both of these expressions are valid for timezone, for basic format: ±[hh]:[mm], ±[hh][mm], or ±[hh]
.
But note that, +0X:00 is correct, and +0X00 is incorrect for extended usage. So it's better to use date("c")
. A similar discussion here.
If you are working with your encrypted partition, consider moving the folder to an unencrypted partition, for example a /tmp, running git pull
, and then moving back.
I really like the @mgilson comment, since if you have a two iterables, one that corresponds to the keys and the other the values, you can also do the following.
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))
giving
d = {'a': 1, 'b': 2, 'c': 3}
I think what you are looking for is
Request.QueryString["QueryStringName"]
and you can access it on views by adding @
now look at my example,,, I generated a Url with QueryString
var listURL = '@Url.RouteUrl(new { controller = "Sector", action = "List" , name = Request.QueryString["name"]})';
the listURL value is /Sector/List?name=value'
and when queryString
is empty
listURL value is /Sector/List
This is a sample example you can try this,
var _pageNumber = 2,
_pageSize = 50;
Student.count({},function(err,count){
Student.find({}, null, {
sort: {
Name: 1
}
}).skip(_pageNumber > 0 ? ((_pageNumber - 1) * _pageSize) : 0).limit(_pageSize).exec(function(err, docs) {
if (err)
res.json(err);
else
res.json({
"TotalCount": count,
"_Array": docs
});
});
});
Use the following code:
if(processing == success) {
header("Location:filename");
exit();
}
And you are good to go.
Dictionary can contain values and values can be added by using update() method. You want your system to create variables, so you should know where to keep.
variables = {}
break_condition= True # Dont forget to add break condition to while loop if you dont want your system to go crazy.
name = “variable”
i = 0
name = name + str(i) #this will be your variable name.
while True:
value = 10 #value to assign
variables.update(
{name:value})
if break_condition == True:
break
Select All Occurrences of Find Match editor.action.selectHighlights
.
Ctrl+Shift+L
Cmd+Shift+L or Cmd+Ctrl+G on Mac
You can run ruby commands in one line with the -e
flag:
ruby -e "puts 'hi'"
Check the man page for more information.
You can proceed as follows to check whether a JToken Value is null
JToken token = jObject["key"];
if(token.Type == JTokenType.Null)
{
// Do your logic
}
If total no is: 200 and getting 50 number
then take percentage of 50 in 200 is:
(50/200)*100 = 25%
Works on Mac, Linux, *nix:
This will give you a quoted csv of all files in the current dir:
ls | xargs -I {} echo "$(pwd -P)/{}" | xargs | sed 's/ /","/g'
The output of this can be easily copied into a python list or any similar data structure.
iCalendar was based on a vCalendar and Outlook 2007 handles both formats well so it doesn't really matters which one you choose.
I'm not sure if this stands for Outlook 2003. I guess you should give it a try.
Outlook's default calendar format is iCalendar (*.ics
)
Following OP's edit:
var now = new Date();_x000D_
var start = new Date(now.getFullYear(), 0, 0);_x000D_
var diff = now - start;_x000D_
var oneDay = 1000 * 60 * 60 * 24;_x000D_
var day = Math.floor(diff / oneDay);_x000D_
console.log('Day of year: ' + day);
_x000D_
Edit: The code above will fail when now
is a date in between march 26th and October 29th andnow
's time is before 1AM (eg 00:59:59). This is due to the code not taking daylight savings time into account. You should compensate for this:
var now = new Date();_x000D_
var start = new Date(now.getFullYear(), 0, 0);_x000D_
var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);_x000D_
var oneDay = 1000 * 60 * 60 * 24;_x000D_
var day = Math.floor(diff / oneDay);_x000D_
console.log('Day of year: ' + day);
_x000D_
The builtin copy(dst, src)
copies min(len(dst), len(src))
elements.
So if your dst
is empty (len(dst) == 0
), nothing will be copied.
Try tmp := make([]int, len(arr))
(Go Playground):
arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)
Output (as expected):
[1 2 3]
[1 2 3]
Unfortunately this is not documented in the builtin
package, but it is documented in the Go Language Specification: Appending to and copying slices:
The number of elements copied is the minimum of
len(src)
andlen(dst)
.
Edit:
Finally the documentation of copy()
has been updated and it now contains the fact that the minimum length of source and destination will be copied:
Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).
My hadoopec2cluster.pem
file was the only one in the directory on my local mac, couldn't scp it to aws using scp -i hadoopec2cluster.pem hadoopec2cluster.pem ubuntu@serverip:~
.
Copied hadoopec2cluster.pem to hadoopec2cluster_2.pem and then scp -i hadoopec2cluster.pem hadoopec2cluster_2.pem ubuntu@serverip:~
. Voila!
If it's a table-value function (returns a table set) you simply join it as a Table
this function generates one column table with all the values from passed comma-separated list
SELECT * FROM dbo.udf_generate_inlist_to_table('1,2,3,4')
I have the same problem. but when i add direction: rtl;
in tabs and accordion combo but it crashes my structure.
The way to do it is add div with direction: rtl;
as parent element, and for child div set direction: ltr;
.
I use this first https://api.jquery.com/wrap/
$( ".your selector of child element" ).wrap( "<div class='scroll'></div>" );
then just simply work with css :)
In children div add to css
.your_class {
direction: ltr;
}
And to parent div added by jQuery with class .scroll
.scroll {
unicode-bidi:bidi-override;
direction: rtl;
overflow: scroll;
overflow-x: hidden!important;
}
Works prefect for me
In a batch file, the below works for local files, but fails for files on network hard drives
for %%I in ("test.jpg") do @set filesize=%~z1
However, it's inferior code, because it doesn't work for files saved on a network drive (for example, \\Nas\test.jpg
and \\192.168.2.40\test.jpg
). The below code works for files in any location, and I wrote it myself.
I'm sure there are more efficient ways of doing this using VBScript, or PowerShell or whatever, but I didn't want to do any of that; good ol' batch for me!
set file=C:\Users\Admin\Documents\test.jpg
set /a filesize=
set fileExclPath=%file:*\=%
:onemoretime
set fileExclPath2=%fileExclPath:*\=%
set fileExclPath=%fileExclPath2:*\=%
if /i "%fileExclPath%" NEQ "%fileExclPath2%" goto:onemoretime
dir /s /a-d "%workingdir%">"%temp%\temp.txt"
findstr /C:"%fileExclPath%" "%temp%\temp.txt" >"%temp%\temp2.txt"
set /p filesize= <"%temp%\temp2.txt"
echo set filesize=%%filesize: %fileExclPath%%ext%=%% >"%temp%\temp.bat"
call "%temp%\temp.bat"
:RemoveTrailingSpace
if /i "%filesize:~-1%" EQU " " set filesize=%filesize:~0,-1%
if /i "%filesize:~-1%" EQU " " goto:RemoveTrailingSpace
:onemoretime2
set filesize2=%filesize:* =%
set filesize=%filesize2:* =%
if /i "%filesize%" NEQ "%filesize2%" goto:onemoretime2
set filesize=%filesize:,=%
echo %filesize% bytes
SET /a filesizeMB=%filesize%/1024/1024
echo %filesizeMB% MB
SET /a filesizeGB=%filesize%/1024/1024/1024
echo %filesizeGB% GB
In a Ubuntu/Debian based distro, you could use apt-file
to find the name of the exact package that includes the missing header file.
# do this once
sudo apt-get install apt-file
sudo apt-file update
$ apt-file search lber.h
libldap2-dev: /usr/include/lber.h
As you could see from the output of apt-file search lber.h
, you'd just need to install the package libldap2-dev
.
sudo apt-get install libldap2-dev
check your branch on your repo. maybe someone delete it.
You can use HAVING clause for filter calculated in SELECT fields and aliases
If you use an operating system that uses copy-on-write fork()
semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).
The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy
or array
), place that in shared memory, wrap it with multiprocessing.Array
, and pass that to your functions. This answer shows how to do that.
If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing
provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager
proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).
The Manager
approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.
There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing
is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.
If you backup a table in Oracle Database. You try the statement below.
CREATE TABLE name_table_bk
AS
SELECT *
FROM name_table;
I am using Oracle Database 12c.
Easy way to achieve: (Do this in your Javascript
)
$("selector").dialog({
autoOpen: false,
open: function(event, ui) { // It'll hide Close button
$(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
},
closeOnEscape: false, // Do not close dialog on press Esc button
show: {
effect: "clip",
duration: 500
},
hide: {
effect: "blind",
duration: 200
},
....
});
I solved the issue by following this link
namespace System.Web.Mvc
{
public sealed class JsonDotNetValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
return null;
var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
var bodyText = reader.ReadToEnd();
return String.IsNullOrEmpty(bodyText) ? null : new DictionaryValueProvider<object>(JsonConvert.DeserializeObject<ExpandoObject>(bodyText, new ExpandoObjectConverter()), CultureInfo.CurrentCulture);
}
}
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
//Remove and JsonValueProviderFactory and add JsonDotNetValueProviderFactory
ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());
}
Set equal name
attributes to create a group;
<form>_x000D_
<fieldset id="group1">_x000D_
<input type="radio" value="value1" name="group1">_x000D_
<input type="radio" value="value2" name="group1">_x000D_
</fieldset>_x000D_
_x000D_
<fieldset id="group2">_x000D_
<input type="radio" value="value1" name="group2">_x000D_
<input type="radio" value="value2" name="group2">_x000D_
<input type="radio" value="value3" name="group2">_x000D_
</fieldset>_x000D_
</form>
_x000D_