first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
I opened XCode -> Preferences -> Accounts and clicked on Download certificate. That fixed my problem
I got this error: "Source option 5 is no longer supported. Use 6 or later" after I changed the pom.xml
<java.version>7</java.version>
to
<java.version>11</java.version>
Later to realise the property was used with a dash insteal of a dot:
<source>${java-version}</source>
<target>${java-version}</target>
(swearings), I replaced the dot with a dash and the error went away:
<java-version>11</javaversion>
.list-inline class in bootstrap is a Inline Unordered List.
If you want to create a horizontal menu using ordered or unordered list you need to place all list items in a single line i.e. side by side. You can do this by simply applying the class
<div class="list-inline">
<a href="#" class="list-inline-item">First item</a>
<a href="#" class="list-inline-item">Secound item</a>
<a href="#" class="list-inline-item">Third item</a>
</div>
I was also facing the same problem. Nothing like changing theme from Layout preview window helped me.
What helped me was adding this to Apptheme
in styles.xml
:
dependencies {
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'
}
Still it was giving me the error: "cannot resolve symbol widget...coordinatorLayout". Then I updated my build.gradle(app)
with:
dependencies {
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'
}
One more thing:
compileSdkVersion 27
targetSdkVersion 27
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
Download the developer edition. There you can choose Express as license when installing.
You have to modify the viewBox
property to change the height and the width correctly with a svg. It is in the <svg>
tag of the svg.
https://developer.mozilla.org/en/docs/Web/SVG/Attribute/viewBox
In case this helps anyone else, this started happening for me on an older site when "Valid OAuth Redirect URIs" became mandatory. The site was still using the V4 PHP SDK and the problem was resolved for me by upgrading to the V5 SDK.
I am using AWS sdk for uploads, after spending some time searching online i stumbled upon this thread. thanks to @lsimoneau 45581857 it turns out the exact same thing was happening. I simply pointed my request Url to the region on my bucket by attaching the region option and it worked.
const s3 = new AWS.S3({
accessKeyId: config.awsAccessKeyID,
secretAccessKey: config.awsSecretAccessKey,
region: 'eu-west-2' // add region here });
I'v got a same issue. but Now I'm fixed.
You should delete a line apply plugin: 'com.google.gms.google-services'
because "com.android.application" package already has same package.
It is compile time error. You can get it in a lot of case:
.xcodeproj
was opened instead of .xcworkspace
module.modulemap
Objective-C, Library/Framework Target.
If you host your own library or framework please make sure that it has module.modulemap
file and the headers from it are located in Build Phases -> Headers section
Framework Search Paths
consumer -> framework
If you try to build an app without setting the Framework Search Paths
. After setting the Framework Search Path
to point to the framework resources, Xcode will build the project successfully. However, when you run the app in the Simulator, there is a crash for reason: Image not found
about
It can be an absolute path or a relative path like $(SRCROOT)
or $(SRCROOT)/..
for workspace
Import Paths
Swift consumer -> Swift static library
The Import Paths
should point to .swiftmodule
Linked Frameworks and Libraries
consumer -> static framework
Add a Static framework
to this section
Find Implicit Dependencies
When you have an implicit dependency but Find Implicit Dependencies
was turned off
CocoaPods
pod deintegrate
pod install
UI Test Bundle
for App Target
where used additional dependency from CocoaPods. To solve it use inherit!
[About] in Podfile
please close the android studio and remove the file
.gradle
and
.idea
file form your project .Hope so it is helpful
Location:Go to Android studio projects->your project ->see both file remove (.gradle
& .idea
)
Add produces = "application/json"
in @RequestMapping
Please use Like below.
<a style="cursor: pointer" **(click)="yourFunctionComponent()"** >
<i class="fa fa-dribbble fa-4x"></i>
</a>
The above can be used so that the fa icon will be shown and also on the click function you could write your logic.
class func uuid(completionHandler: @escaping (String) -> ()) {
if let uuid = UIDevice.current.identifierForVendor?.uuidString {
completionHandler(uuid)
}
else {
// If the value is nil, wait and get the value again later. This happens, for example, after the device has been restarted but before the user has unlocked the device.
// https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor?language=objc
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
uuid(completionHandler: completionHandler)
}
}
}
Answering your question in this format is quite challenging.
On the other hand you ask about navigation and then about current $state
acting all weird.
For the first I'd say it's too broad question and for the second I'd say... well, you are doing something wrong or missing the obvious :)
Take the following controller:
app.controller('MainCtrl', function($scope, $state) {
$scope.state = $state;
});
Where app
is configured as:
app.config(function($stateProvider) {
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'main.html',
controller: 'MainCtrl'
})
.state('main.thiscontent', {
url: '/thiscontent',
templateUrl: 'this.html',
controller: 'ThisCtrl'
})
.state('main.thatcontent', {
url: '/thatcontent',
templateUrl: 'that.html'
});
});
Then simple HTML template having
<div>
{{ state | json }}
</div>
Would "print out" e.g. the following
{
"params": {},
"current": {
"url": "/thatcontent",
"templateUrl": "that.html",
"name": "main.thatcontent"
},
"transition": null
}
I put up a small example showing this, using ui.router
and pascalprecht.translate
for the menus. I hope you find it useful and figure out what is it you are doing wrong.
Plunker here http://plnkr.co/edit/XIW4ZE
Screencap
Another way of viewing the full content of the cells in a pandas dataframe is to use IPython's display functions:
from IPython.display import HTML
HTML(df.to_html())
I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.
In parent window use:
<head>
<style>
.disableWin{
pointer-events: none;
}
</style>
<script type="text/javascript">
function openPopUp(url) {
disableParentWin();
var win = window.open(url);
win.focus();
checkPopUpClosed(win);
}
/*Function to detect pop up is closed and take action to enable parent window*/
function checkPopUpClosed(win) {
var timer = setInterval(function() {
if(win.closed) {
clearInterval(timer);
enableParentWin();
}
}, 1000);
}
/*Function to enable parent window*/
function enableParentWin() {
window.document.getElementById('mainDiv').class="";
}
/*Function to enable parent window*/
function disableParentWin() {
window.document.getElementById('mainDiv').class="disableWin";
}
</script>
</head>
<body>
<div id="mainDiv class="">
</div>
</body>
I know I am late, but if you want to know the easiest way, you could do a code like this:
number = 100
right_questions = 1
control = 100
c = control / number
cc = right_questions * c
print float(cc)
You can change up the number score, and right_questions. It will tell you the percent.
Building on what deb2fast said I would also pass in a couple of extra parameters to JSON.stringify() to get it to pretty format:
fs.writeFileSync('./data.json', JSON.stringify(obj, null, 2) , 'utf-8');
The second param is an optional replacer function which you don't need in this case so null
works.
The third param is the number of spaces to use for indentation. 2 and 4 seem to be popular choices.
I know this is an "older" post. This question and the provided answers helped me get ideas for my own problem. I think this solution addresses the OP question (intersecting borders with 4 and 2 columns depending on display)
Fiddle: https://jsfiddle.net/tqmfpwhv/1/
css based on OP information, media query at end is for med & lg view.
.vr-all {
padding:0px;
border-right:1px solid #CC0000;
}
.vr-xs {
padding:0px;
}
.vr-md {
padding:0px;
}
.hrspacing { padding:0px; }
.hrcolor {
border-color: #CC0000;
border-style: solid;
border-bottom: 1px;
margin:0px;
padding:0px;
}
/* for medium and up */
@media(min-width:992px){
.vr-xs {
border-right:1px solid #CC0000;
}
}
html adjustments to OP provided code. Red border and Img links for example.
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="one">
<h5>Rich Media Ad Production</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" />
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="two">
<h5>Web Design & Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="three">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="four">
<h5>Creative Design</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for for all viewports -->
<div class="col-xs-12 hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="five">
<h5>Web Analytics</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="six">
<h5>Search Engine Marketing</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="seven">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="eight">
<h5>Quality Assurance</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
</div>
</div>
You can copy-paste data from en excel-sheet to an SQL-table by doing so:
Note: Often tables have a first column which is an ID-column with an auto generated/incremented ID. When you paste your data it will start inserting the leftmost selected column in Excel into the leftmost column in SSMS thus inserting data into the ID-column. To avoid that keep an empty column at the leftmost part of your selection in order to skip that column in SSMS. That will result in SSMS inserting the default data which is the auto generated ID.
Furthermore you can skip other columns by having empty columns at the same ordinal positions in the Excel sheet selection as those columns to be skipped. That will make SSMS insert the default value (or NULL where no default value is specified).
In BOOTSTRAP 4 you can use
<div class="row m-0">
my fullwidth div
</div>
... if you just use a .row without the .m-0 as a top level div, you will have unwanted margin, which makes the page wider than the browser window and cause a horizontal scrollbar.
It seemed that a lot of dependencies were incorrect.
A good place to look for the correct dependencies is the Maven Repository website.
Scenario / Solution 1:
Ensure your Folder
/ Sub-folder
is not in the .gitignore
file, by any chance.
Scenario / Solution 2:
By default, git add .
works recursively.
Scenario / Solution 3:
git add --all :/
works smoothly, where git add .
doesn't (work).
(@JasonHartley's comment)
Scenario / Solution 4:
The issue I personally faced was adding Subfolders or Files
, which were common between multiple Folders
.
For example:
Folder/Subfolder-L1/Subfolder-L2/...file12.txt
Folder/Subfolder-L1/Subfolder-L2/Subfolder-L3/...file123.txt
Folder/Subfolder-L1/...file1.txt
So Git
was recommending me to add git submodule
, which I tried but was a pain.
Finally what worked for me was:
1. git add
one file that's at the last end / level of a Folder
.
For example:
git add Folder/Subfolder-L1/Subfolder-L2/Subfolder-L3/...file123.txt
2. git add --all :/
now.
It'll very swiftly add all the Folders
, Subfolders
and files
.
Just try this code.
img:hover
{
box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset;
-webkit-box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset;
-moz-box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset;
-o-box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset;
}
I ended up getting the answer from AngularJS forum. See this thread for details
The link is to a Google Groups thread, which is difficult to read and doesn't provide a clear answer. To remove URL parameters use
$location.url($location.path());
Actually, if you do not want to delete your local .m2/repository/... and you are have a downloaded copy of Maven from Apache, you can have Eclipse /STS use that external Maven and you can edit the {maven}\conf\settings.xml to point your localRepository to a new empty location.
<localRepository>C:\java\repository</localRepository>
Of course, you will have a new repository with all of the maven source downloads in addition to your previous .m2 location.
This is my solution for my scenario:
<div class="btn-group btn-group-justified">
<a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
{{ song.name }}
</a>
<a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
{{ match.name }}
</a>
</div>
default state:
on hover:
background: rgba(0,0,0,.5);
you can use rgba for opacity, will only work in ie9+ and better browsers
Here is an alternative way if the data frame just contains numbers.
apply(as.matrix.noquote(SFI),2,as.numeric)
_x000D_
but the most reliable way of converting a data frame to a matrix is using data.matrix()
function.
Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.
Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.
How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.
How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.
Use a dot or a pipe as the field separator:
awk -v FS='[.|]' '{
printf "%s%s %s.%s\n", toupper(substr($4,1,1)), substr($4,2), $1, $2
}' << END
[email protected]|com.emailclient.account
[email protected]|com.socialsite.auth.account
END
gives:
Emailclient [email protected]
Socialsite [email protected]
For me, the problem was a ContextRefreshedEvent handler. I was doing some data initilization but at that point in the application the Authentication had not been set. It was a catch 22 since the system needed an authentication to authorize and it needed authorization to get the authentication details :). I ended up loosening the authorization from a class level to a method level.
If you are constrained to using an <img>
tag:
I've found it much easier to set a <div>
or any other element of your choice with a background-image
, width: 100%
and background-size: 100%
.
This isn't the end all be all to responsive images, but it's a start. Also, try messing around with background-size: cover
and maybe some positioning with background-position: center
.
CSS:
.image-container{
height: 100%; /* It doesn't have to be '%'. It can also use 'px'. */
width: 100%;
margin: 0 auto;
padding: 0;
background-image: url(../img/exampleImage.jpg);
background-position: top center;
background-repeat: no-repeat;
background-size: 100%;
}
HMTL:
<div class="image-container"></div>
The <ul>
element has browser inherent padding & margin by default. In your case, Use
#footer ul {
margin: 0; /* To remove default bottom margin */
padding: 0; /* To remove default left padding */
}
or a CSS browser reset ( https://cssreset.com/ ) to deal with this.
You might have 10,000 users total, but that's not the same as concurrent users. In this context, concurrent scripts being run.
For example, if your visitor visits index.php, and it makes a database query to get some user details, that request might live for 250ms. You can limit how long those MySQL connections live even further by opening and closing them only when you are querying, instead of leaving it open for the duration of the script.
While it is hard to make any type of formula to predict how many connections would be open at a time, I'd venture the following:
You probably won't have more than 500 active users at any given time with a user base of 10,000 users. Of those 500 concurrent users, there will probably at most be 10-20 concurrent requests being made at a time.
That means, you are really only establishing about 10-20 concurrent requests.
As others mentioned, you have nothing to worry about in that department.
I would like to add a new pure javascript
way to do this, which in my opinion is much cleaner, by using the fetch()
API. This a modern way to implements network requests. In your case, since you already have a form element
we can simply use it to build our request.
const formInputs = oForm.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(oForm.action,
{
method: oForm.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
As you can see it is very clean and much less verbose to use than XMLHttpRequest
.
You cannot do this on multiple fields. You can also look for this.
I was getting a consistent 15 second delay on the first request after 4 minutes of inactivity. My problem was that my app was using Windows Integrated Authentication to SQL Server and the service profile was in a different domain than the server. This caused a cross-domain authentication from IIS to SQL upon app initialization - and this was the real source of my delay. I changed to using a SQL login instead of windows authentication. The delay was immediately gone. I still have all the app initialization settings in place to help improve performance but they may have not been needed at all in my case.
To do links, you can do
.social h2 a:link {
color: pink;
font-size: 14px;
}
You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.
Does GitHub have this social feature?
If the commit email is kept private, GitHub now (July 2020) proposes:
Users and organizations can now add Twitter usernames to their GitHub profiles
You can now add your Twitter username to your GitHub profile directly from your profile page, via profile settings, and also the REST API.
We've also added the latest changes:
- Organization admins can now add Twitter usernames to their profile via organization profile settings and the REST API.
- All users are now able to see Twitter usernames on user and organization profiles, as well as via the REST and GraphQL APIs.
- When sponsorable maintainers and organizations add Twitter usernames to their profiles, we'll encourage new sponsors to include that Twitter username when they share their sponsorships on Twitter.
That could be a workaround to leave a message to a GitHub user.
I find a nice and tidy Wave game engine few days ago. It uses C# and have Windows Phone and Windows Store converters as well which makes it a great replacement of XNA for me
In my case, I was using InstallUtil.exe
which was causing an error. To install the .Net Core
service in window best way to use sc
command.
More information here Exe installation throwing error The module was expected to contain an assembly manifest .Net Core
Remember that you can apply multiple classes to an element by separating each class with a space within its class attribute. For example:
<img class="class1 class2">
What is your project type? If it's a "Win32 project", your entry point should be (w)WinMain
. If it's a "Win32 Console Project", then it should be (w)main
. The name _tmain
is #defined to be either main
or wmain
depending on whether UNICODE is defined or not.
If it's a DLL, then DllMain
.
The project type can be seen under project properties, Linker, System, Subsystem. It would say either "Console" or "Windows".
Note that the entry point name varies depending on whether UNICODE is defined or not. In VS2008, it's defined by default.
The proper prototype for main is either
int _tmain(int argc, _TCHAR* argv[])
or
int _tmain()
Make sure it's one of those.
EDIT:
If you're getting an error on _TCHAR, place an
#include <tchar.h>
If you think the issue is with one of the headers, go to the properties of the file with main(), and under Preprocessor, enable generating of the preprocessed file. Then compile. You'll get a file with the same name a .i extension. Open it, and see if anything unsavory happened to the main() function. There can be rogue #defines in theory...
EDIT2:
With UNICODE defined (which is the default), the linker expects the entry point to be wmain(), not main(). _tmain has the advantage of being UNICODE-agnostic - it translates to either main or wmain.
Some time ago, there was a reason to maintain both an ANSI build and a Unicode build. Unicode support was sorely incomplete in Windows 95/98/Me. The primary APIs were ANSI, and Unicode versions existed here and there, but not pervasively. Also, the VS debugger had trouble displaying Unicode strings. In the NT kernel OSes (that's Windows 2000/XP/Vista/7/8/10), Unicode support is primary, and ANSI functions are added on top. So ever since VS2005, the default upon project creation is Unicode. That means - wmain. They could not keep the same entry point name because the parameter types are different. _TCHAR is #defined to be either char or wchar_t. So _tmain is either main(int argc, char **argv) or wmain(int argc, wchar_t **argv).
The reason you were getting an error at _tmain
at some point was probably because you did not change the type of argv
to _TCHAR**
.
If you're not planning to ever support ANSI (probably not), you can reformulate your entry point as
int wmain(int argc, wchar_t *argv[])
and remove the tchar.h
include line.
INSERT INTO wp_bp_activity
(
user_id,
component,
`type`,
`action`,
content,
primary_link,
item_id,
secondary_item_id,
date_recorded,
hide_sitewide,
mptt_left,
mptt_right
)
VALUES(
1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
)
https://github.com/dualface/cocos2d-x-extensions/blob/master/TODO.tasks , he is developing nice features on cocos2d-x
The standard Pinterest button code (which you can generate here), is an <a>
tag wrapping an <img>
of the Pinterest button.
If you don't include the pinit.js
script on your page, this <a>
tag will work "as-is". You could improve the experience by registering your own click handler on these tags that opens a new window with appropriate dimensions, or at least adding target="_blank"
to the tag to make it open clicks in a new window.
The tag syntax would look like:
<a href="http://pinterest.com/pin/create/button/?url={URI-encoded URL of the page to pin}&media={URI-encoded URL of the image to pin}&description={optional URI-encoded description}" class="pin-it-button" count-layout="horizontal">
<img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" />
</a>
If using the JavaScript versions of sharing buttons are ruining your page load times, you can improve your site by using asynchronous loading methods. For an example of doing this with the Pinterest button, check out my GitHub Pinterest button project with an improved HTML5 syntax.
I've installed and use VB6 for legacy projects many times on Windows 7.
What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.
Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721
Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm
I had this issue when my main project was in the same folder as the solution, then I had a separate project in the same solution located in a sub folder, and that separate project used the main project as a reference. This caused the main project to detect the sub folder bin & obj folders which created duplicate references.
All previous answers have since been deprecated. This method works as of Aug 2016:
To get the like count of any URL:
GET request: https://graph.facebook.com/[url]/access_token=[access_token]
Then grab shares->share_count from the returned JSON object.
Fan count for a Facebook page:
GET request: https://graph.facebook.com/[url]/?fields=fan_count&access_token=[access_token]
Then grab the 'fan_count' field from the returned JSON object.
You can test this out and get your access token using the Graph API Explorer
I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:
We can enable TCP/IP protocol with WMI:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocol " _
& "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")
if tcpProtocols.Count = 1 then
' set tcpProtocol = tcpProtocols(0)
' I wish this worked, but unfortunately
' there's no int-indexed Item property in this type
' Doing this instead
for each tcpProtocol in tcpProtocols
dim setEnableResult
setEnableResult = tcpProtocol.SetEnable()
if setEnableResult <> 0 then
Wscript.Echo "Failed!"
end if
next
end if
I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)
We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456
:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocolProperty " _
& "where InstanceName='SQLEXPRESS' and " _
& "ProtocolName='Tcp' and IPAddressName='IPAll'")
for each tcpProperty in tcpProperties
dim setValueResult, requestedValue
if tcpProperty.PropertyName = "TcpPort" then
requestedValue = "3456"
elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
requestedValue = ""
end if
setValueResult = tcpProperty.SetStringValue(requestedValue)
if setValueResult = 0 then
Wscript.Echo "" & tcpProperty.PropertyName & " set."
else
Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
end if
next
Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.
Just a reminder that when working with WMI, WBEMTest.exe is your best friend!
I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:
Use LoginMode
property of Microsoft.SqlServer.Management.Smo.Server
class, as described here.
Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS
, so for my SQL Server 2008 R2 Express instance the right registry key was
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer
.
You got this one covered.
Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.
SQLCMD -U sa -P newPassword -S 192.168.0.120,3456
Please let me know if this works for you (fingers crossed!).
trying to access the /s2/profile/photo url works for most users but not all.
The only full proof method is to use the Google+ API. You don't need user authentication to request public profile data so it's a rather simple method:
Get a Google+ API key on https://cloud.google.com/console
Make a simple GET request to: https://www.googleapis.com/plus/v1/people/+< username >?key=
Note the + before the username. If you use user ids instead (the long string of digits), you don't need the +
Have you tried using the fb:// protocol?
To have them like your page when they scan the qr code, it goes like this:
fb://page/(pageID)/addfan
If you need to get the pageID, replace "www" with "graph" in the Facebook url when you visit your page in a desktop browser and it will display the ID and other data.
Not only does this add them automatically, but it opens up the page in the FB app instead of the mobile browser.
As far as legality, I would assume as long as you put something like "Scan to like our page", you're in the clear. They know what they're getting into.
$(window).scroll(() => {
const footerToTop = $('.your-footer').position().top;
const scrollTop = $(document).scrollTop() + $(window).height();
const difference = scrollTop - footerToTop;
const bottomValue = scrollTop > footerToTop ? difference : 0;
$('.your-fixed-element').css('bottom', bottomValue);
});
The most comfortable way to preview HTML files on GitHub is to go to https://htmlpreview.github.io/ or just prepend it to the original URL, i.e.: https://htmlpreview.github.io/?https://github.com/bartaz/impress.js/blob/master/index.html
You can make like this:
<center>
<form action="" method="POST">
<input type="text" class="emailField" placeholder="[email protected]" style="text-align: center" name="email" />
<input type="submit" value="submit" />
</form>
</center>
I would prefer (RHEL) - pip download package==version --no-deps --no-binary=:all:
Here is a way to detect Zombie transaction
SqlTransaction trans = connection.BeginTransaction();
//some db calls here
if (trans.Connection != null) //Detecting zombie transaction
{
trans.Commit();
}
Decompiling the SqlTransaction class, you will see the following
public SqlConnection Connection
{
get
{
if (this.IsZombied)
return (SqlConnection) null;
return this._connection;
}
}
I notice if the connection is closed, the transOP will become zombie, thus cannot Commit
.
For my case, it is because I have the Commit()
inside a finally
block, while the connection was in the try
block. This arrangement is causing the connection to be disposed and garbage collected. The solution was to put Commit
inside the try
block instead.
Try to use classpath*:
prefix instead.
Also please try to deploy exploded war, to ensure that all files are there.
This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.
Here is the complete example for previewing image before it gets upload.
HTML :
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://goo.gl/r57ze"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>
JavaScript :
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
The definitive answer to this is from Facebook themselves. In post today at https://developers.facebook.com/bugs/335452696581712 a Facebook dev says
The ability to pass in an e-mail address into the "user" search type was
removed on July 10, 2013. This search type only returns results that match
a user's name (including alternate name).
So, alas, the simple answer is you can no longer search for users by their email address. This sucks, but that's Facebook's new rules.
Surprised no one mentioned this:
public Task<int> BlahAsync()
{
// ...
}
int result = BlahAsync().GetAwaiter().GetResult();
Not as pretty as some of the other methods here, but it has the following benefits:
Wait
)AggregateException
(like Result
)Task
and Task<T>
(try it out yourself!)Also, since GetAwaiter
is duck-typed, this should work for any object that is returned from an async method (like ConfiguredAwaitable
or YieldAwaitable
), not just Tasks.
edit: Please note that it's possible for this approach (or using .Result
) to deadlock, unless you make sure to add .ConfigureAwait(false)
every time you await, for all async methods that can possibly be reached from BlahAsync()
(not just ones it calls directly). Explanation.
// In BlahAsync() body
await FooAsync(); // BAD!
await FooAsync().ConfigureAwait(false); // Good... but make sure FooAsync() and
// all its descendants use ConfigureAwait(false)
// too. Then you can be sure that
// BlahAsync().GetAwaiter().GetResult()
// won't deadlock.
If you're too lazy to add .ConfigureAwait(false)
everywhere, and you don't care about performance you can alternatively do
Task.Run(() => BlahAsync()).GetAwaiter().GetResult()
The file msrdo20.dll is missing from the installation.
According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.
I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:
regsvr32 c:\windows\system32\msrdo20.dll
In an ideal world you would package this up with the redistributable.
What is oAuth?
OAuth is simply a secure authorization protocol that deals with the authorization of third party application to access the user data without exposing their password. eg. (Login with fb, gPlus, twitter in many websites..) all work under this protocol.
Parties involved
The Protocol becomes easier when you know the involved parties. Basically there are three parties involved: oAuth Provider, oAuth Client and Owner.
How It Works?
I have supposed a scenario where a website(stackoverflow) needs to add login with facebook feature. Thus facebook is oAuth Provider and the stackoverflow is oAuth Client.
This step is done by app's developer. At the very beginning facebook (oAuth Provider) has no idea about the stackoverflow(oAuth Client) because there is no link between them. So the very first step is to register stackoverflow with facebook developers site. This is done manually where developers need to give app's information to facebook like app's name, website, logo, redirect Url(important one). Then stackoverflow is successfully registered, has got client Id, client secret etc from facebook and is up and running with OAUTH.
2.Now when stackoverflow's user clicks login with fb button. Stackoverflow requests facebook with ClientId(fb use it to recognize the client) and redirectUrl(fb will return back to this url after success).Thus the user gets redirected to facebook login page. This is the best part user(owner) is not giving thier facebook credential to stackoverflow.
For More:
Facebook's FQL documentation here tells you how to do it. Run the example SELECT name, fan_count FROM page WHERE page_id = 19292868552
and replace the page_id number with your page's id number and it will return the page name and the fan count.
When requesting paginated data, you know (by explicit page size parameter value or default page size value) the page size, so you know if you got all data in response or not. When there is less data in response than is a page size, then you got whole data. When a full page is returned, you have to ask again for another page.
I prefer have separate endpoint for count (or same endpoint with parameter countOnly). Because you could prepare end user for long/time consuming process by showing properly initiated progressbar.
If you want to return datasize in each response, there should be pageSize, offset mentionded as well. To be honest the best way is to repeat a request filters too. But the response became very complex. So, I prefer dedicated endpoint to return count.
<data>
<originalRequest>
<filter/>
<filter/>
</originalReqeust>
<totalRecordCount/>
<pageSize/>
<offset/>
<list>
<item/>
<item/>
</list>
</data>
Couleage of mine, prefer a countOnly parameter to existing endpoint. So, when specified the response contains metadata only.
endpoint?filter=value
<data>
<count/>
<list>
<item/>
...
</list>
</data>
endpoint?filter=value&countOnly=true
<data>
<count/>
<!-- empty list -->
<list/>
</data>
Facebook uses the LAMP stack, so if you want to get a career with them you're going to want to focus on that. In addition they often have C++ and/or Java listed in their requirements as well.
One of the postings includes the following requirements:
Another:
Another:
http://www.facebook.com/careers/#!/careers/department.php?dept=engineering
Also, do any other social networking sites use the same language?
Some other companys that use PHP/LAMP Stack:
Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like
Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.
Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.
Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.
HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.
If we go into more detail, then answer to this question go longer. We can understand more from following posts:
You need to set the value of $title
before echoing it.
Also, you should really sanitize any data before using it in queries as this is a security risk
In my fairly complex scenario the accepted answer for how to do this in Chrome doesn't work for me. You may want to try the Firefox debugger instead (part of the Firefox developer tools), which shows all of the 'Sources', including those that are part of an iFrame
You can check out this blog post. It had solved my problem.
http://dotnetguts.blogspot.com/2010/06/restore-failed-for-server-restore.html
Select @@Version
It had given me following output Microsoft SQL Server 2005 - 9.00.4053.00 (Intel X86) May 26 2009 14:24:20 Copyright (c) 1988-2005 Microsoft Corporation Express Edition on Windows NT 6.0 (Build 6002: Service Pack 2)
You will need to re-install to a new named instance to ensure that you are using the new SQL Server version.
Just git commit
it.
Optionally git abort
it:
I ran into a merge conflict. How can I abort the merge?
To make life easier with on merges install kdiff3 and configure it as a mergetool. Instructions: http://doodkin.com/2016/05/29/git-merge-easy-github-this-branch-has-conflicts-that-must-be-resolved-use-the-command-line/
That page contains this video: https://www.youtube.com/watch?v=Cc4xPp7Iuzo
I found the fix you were looking for:
context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");
For some reason Android makes a bad cache of the url which it keeps returning by accident instead of the new data you need. Sure, you could just delete the entries from the DB but in my case I am only trying to access one URL so blowing away the whole DB is easier.
And don't worry, these DBs are just associated with your app so you aren't clearing the cache of the whole phone.
Numbers from 987-65-4320 to 987-65-4329 are reserved for use in advertisements.
This is what finally worked for me:
<xsd:element name="bar">
<xsd:complexType>
<xsd:sequence>
<!-- Permit any of these tags in any order in any number -->
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element name="child1" type="xsd:string" />
<xsd:element name="child2" type="xsd:string" />
<xsd:element name="child3" type="xsd:string" />
</xsd:choice>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
If you want downloads number for each customer, use:
select ssn
, sum(time)
from downloads
group by ssn
If you want just one record -- for a customer with highest number of downloads -- use:
select *
from (
select ssn
, sum(time)
from downloads
group by ssn
order by sum(time) desc
)
where rownum = 1
However if you want to see all customers with the same number of downloads, which share the highest position, use:
select *
from (
select ssn
, sum(time)
, dense_rank() over (order by sum(time) desc) r
from downloads
group by ssn
)
where r = 1
No there is no such extension method overload for this. I've found this frustrating myself in the past and as such I usually write a helper class to deal with this problem. The goal is to convert a Func<T,T,bool>
to IEqualityComparer<T,T>
.
Example
public class EqualityFactory {
private sealed class Impl<T> : IEqualityComparer<T,T> {
private Func<T,T,bool> m_del;
private IEqualityComparer<T> m_comp;
public Impl(Func<T,T,bool> del) {
m_del = del;
m_comp = EqualityComparer<T>.Default;
}
public bool Equals(T left, T right) {
return m_del(left, right);
}
public int GetHashCode(T value) {
return m_comp.GetHashCode(value);
}
}
public static IEqualityComparer<T,T> Create<T>(Func<T,T,bool> del) {
return new Impl<T>(del);
}
}
This allows you to write the following
var distinctValues = myCustomerList
.Distinct(EqualityFactory.Create((c1, c2) => c1.CustomerId == c2.CustomerId));
There is easy way of doing this. I don't know why people are giving complicated answers.
Double click SSIS package. Then go to connection manager, select DestinationConnectionOLDB and then add password next to login field.
Example: Data Source=SysproDB1;User ID=test;password=test;Initial Catalog=ASBuiltDW;Provider=SQLNCLI11;Auto Translate=false;
Do same for SourceConnectionOLDB.
if it is 64bit them - C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell**3.0**
and version could be different
The ToString
function has many overloads - the method group would be the group consisting of all the different overloads for that function.
There is no way you could do this 100% (i would say maybe 1-5% would be plausible) with nowdays knowledge. You would get much better result (than those 1-5%) just checking the image-names for sex-related-words :).
@SO Troll: So true.
We just released pako https://github.com/nodeca/pako , port of zlib to javascript. I think that's now the fastest js implementation of deflate / inflate / gzip / ungzip. Also, it has democratic MIT licence. Pako supports all zlib options and it's results are binary equal.
Example:
var inflate = require('pako/lib/inflate').inflate;
var text = inflate(zipped, {to: 'string'});
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.
When deciding to use Array or ArrayList, your first instinct really shouldn't be worrying about performance, though they do perform differently. You first concern should be whether or not you know the size of the Array before hand. If you don't, naturally you would go with an array list, just for functionality.
May be useful for java and jstl.
In JSP
1.
<fmt:message key="some.key" var="item"/>
2.
<div class="content">
<a href="#">${fn:toLowerCase(item)}</a>
</div>
In CSS
3.
.content {
text-transform:capitalize;
}
I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.
Solution:
First of all find the application which is causing heavy memory usage.
You can find this in the Details section of the Task Manager.
Next.
If this solution works for you please add a comment so that I can know.
There is an easy workaround for this problem
What you need to do, is format your dates as DD/MM/YYYY (or whichever way around you like)
Insert a column next to the time and date columns, put a formula in this column that adds them together. e.g. =A5+B5.
Format this inserted column into DD/MM/YYYY hh:mm:ss which can be found in the custom category on the formatting section
Plot a scatter graph
Badabing badaboom
If you are unhappy with this workaround, learn to use GNUplot :)
Use jQuery and CSS
jQuery(document).ready(function() {_x000D_
jQuery("[required]").after("<span class='required'>*</span>");_x000D_
});
_x000D_
.required {_x000D_
position: absolute;_x000D_
margin-left: -10px;_x000D_
color: #FB0000;_x000D_
font-size: 15px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" value="xxx" required>
_x000D_
You can overwrite your default activity animation and it perform better than overridePendingTransition. I use this solution that work for every android version. Just copy paste 4 files and add a 4 lines style as below:
Create a "CustomActivityAnimation" and add this to your base Theme by "windowAnimationStyle".
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorPrimary</item>
<item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>
</style>
<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">
<item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>
<item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>
<item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>
<item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>
</style>
Then Create anim folder under res folder and then create this four animation files into anim folder:
slide_in_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="100%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_out_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-100%p"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_in_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="-100%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_out_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="100%p"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
If you face any problem then you can download my sample project from github.
Thanks
That's because there was an error in your query. MySQli->query()
will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
O.K. I neither have rep to comment on previous answer (of Philippe De Muyter) nor raise it's score, hence a new example using his define for SIGNED_MAX trivially extended for unsigned types:
// We can use it to define limits based on actual compiler built-in types also:
#define INT_MAX SIGNED_MAX(int)
// based on the above, we can extend it for unsigned types also:
#define UNSIGNED_MAX(x) ( (SIGNED_MAX(x)<<1) | 1 ) // We reuse SIGNED_MAX
#define UINT_MAX UNSIGNED_MAX(unsigned int) // on ARM: 4294967295
// then we can have:
unsigned int width = UINT_MAX;
Unlike using this or that header, here we use the real type from the compiler.
This might help someone:
I am installing the latest Java on my system for development, and currently it's Java SE 7. Now, let's dive into this "madness", as you put it...
All of these are the same (when developers are talking about Java for development):
Starting with Java v1.5:
And we can assume this will remain for future versions.
Next, for developers, download JDK, not JRE.
JDK will contain JRE. If you need JDK and JRE, get JDK. Both will be installed from the single JDK install, as you will see below.
As someone above mentioned:
Here's the step by step links I followed (one step leads to the next, this is all for a single download) to download Java for development (JDK):
Keep in mind the above links are for reference purposes only, to show you the step by step method of what it takes to download the JDK.
And install with default settings to:
Remember from above that JDK contains JRE, which makes sense if you know what they both are. Again, see above.
After your install, double check “C:\Program Files\Java” to see both these folders. Now you know what they are and why they are there.
I know I wrote this for newbies, but I enjoy knowing things in full detail, so I hope this helps.
The equivalent command in svn is:
svn log --diff -r revision
Flask-JsonTools package has an implementation of JsonSerializableBase Base class for your models.
Usage:
from sqlalchemy.ext.declarative import declarative_base
from flask.ext.jsontools import JsonSerializableBase
Base = declarative_base(cls=(JsonSerializableBase,))
class User(Base):
#...
Now the User
model is magically serializable.
If your framework is not Flask, you can just grab the code
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
If your using vS2k8, you can use an extension method to add it to the String class:
public static string FirstLetterToUpper(this String input)
{
return input = input.Substring(0, 1).ToUpper() +
input.Substring(1, input.Length - 1);
}
The packages you installed introduced dependencies to version 5.2.3.0 dll's as user Bracher showed above. Microsoft.AspNet.WebApi.Cors is an example package. The path I take is to update the MVC project proir to any package installs:
Install-Package Microsoft.AspNet.Mvc -Version 5.2.3
You can import svg and it use it like a image
import chatSVG from '../assets/images/undraw_typing_jie3.svg'
And ise it in img tag
<img src={chatSVG} className='iconChat' alt="Icon chat"/>
sed
is the stream editor, in that you can use |
(pipe) to send standard streams (STDIN and STDOUT specifically) through sed
and alter them programmatically on the fly, making it a handy tool in the Unix philosophy tradition; but can edit files directly, too, using the -i
parameter mentioned below.
Consider the following:
sed -i -e 's/few/asd/g' hello.txt
s/
is used to substitute the found expression few
with asd
:
The few, the brave.
The asd, the brave.
/g
stands for "global", meaning to do this for the whole line. If you leave off the /g
(with s/few/asd/
, there always needs to be three slashes no matter what) and few
appears twice on the same line, only the first few
is changed to asd
:
The few men, the few women, the brave.
The asd men, the few women, the brave.
This is useful in some circumstances, like altering special characters at the beginnings of lines (for instance, replacing the greater-than symbols some people use to quote previous material in email threads with a horizontal tab while leaving a quoted algebraic inequality later in the line untouched), but in your example where you specify that anywhere few
occurs it should be replaced, make sure you have that /g
.
The following two options (flags) are combined into one, -ie
:
-i
option is used to edit in place on the file hello.txt
.
-e
option indicates the expression/command to run, in this case s/
.
Note: It's important that you use -i -e
to search/replace. If you do -ie
, you create a backup of every file with the letter 'e' appended.
You could also extend Array
to have this function and make it part of every array.
Array.prototype.max = function(){return Math.max.apply( Math, this )};
myArray = [1,2,3];
console.log( myArray.max() );
im attach my vb.net code based on brian reference
Imports System.ComponentModel
Imports System.Runtime.InteropServices
Public Class PinvokeWindowsNetworking
Const NO_ERROR As Integer = 0
Private Structure ErrorClass
Public num As Integer
Public message As String
Public Sub New(ByVal num As Integer, ByVal message As String)
Me.num = num
Me.message = message
End Sub
End Structure
Private Shared ERROR_LIST As ErrorClass() = New ErrorClass() {
New ErrorClass(5, "Error: Access Denied"),
New ErrorClass(85, "Error: Already Assigned"),
New ErrorClass(1200, "Error: Bad Device"),
New ErrorClass(67, "Error: Bad Net Name"),
New ErrorClass(1204, "Error: Bad Provider"),
New ErrorClass(1223, "Error: Cancelled"),
New ErrorClass(1208, "Error: Extended Error"),
New ErrorClass(487, "Error: Invalid Address"),
New ErrorClass(87, "Error: Invalid Parameter"),
New ErrorClass(1216, "Error: Invalid Password"),
New ErrorClass(234, "Error: More Data"),
New ErrorClass(259, "Error: No More Items"),
New ErrorClass(1203, "Error: No Net Or Bad Path"),
New ErrorClass(1222, "Error: No Network"),
New ErrorClass(1206, "Error: Bad Profile"),
New ErrorClass(1205, "Error: Cannot Open Profile"),
New ErrorClass(2404, "Error: Device In Use"),
New ErrorClass(2250, "Error: Not Connected"),
New ErrorClass(2401, "Error: Open Files")}
Private Shared Function getErrorForNumber(ByVal errNum As Integer) As String
For Each er As ErrorClass In ERROR_LIST
If er.num = errNum Then Return er.message
Next
Try
Throw New Win32Exception(errNum)
Catch ex As Exception
Return "Error: Unknown, " & errNum & " " & ex.Message
End Try
Return "Error: Unknown, " & errNum
End Function
<DllImport("Mpr.dll")>
Private Shared Function WNetUseConnection(ByVal hwndOwner As IntPtr, ByVal lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUserID As String, ByVal dwFlags As Integer, ByVal lpAccessName As String, ByVal lpBufferSize As String, ByVal lpResult As String) As Integer
End Function
<DllImport("Mpr.dll")>
Private Shared Function WNetCancelConnection2(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Boolean) As Integer
End Function
<StructLayout(LayoutKind.Sequential)>
Private Class NETRESOURCE
Public dwScope As Integer = 0
Public dwType As Integer = 0
Public dwDisplayType As Integer = 0
Public dwUsage As Integer = 0
Public lpLocalName As String = ""
Public lpRemoteName As String = ""
Public lpComment As String = ""
Public lpProvider As String = ""
End Class
Public Shared Function connectToRemote(ByVal remoteUNC As String, ByVal username As String, ByVal password As String) As String
Return connectToRemote(remoteUNC, username, password, False)
End Function
Public Shared Function connectToRemote(ByVal remoteUNC As String, ByVal username As String, ByVal password As String, ByVal promptUser As Boolean) As String
Dim nr As NETRESOURCE = New NETRESOURCE()
nr.dwType = ResourceTypes.Disk
nr.lpRemoteName = remoteUNC
Dim ret As Integer
If promptUser Then
ret = WNetUseConnection(IntPtr.Zero, nr, "", "", Connects.Interactive Or Connects.Prompt, Nothing, Nothing, Nothing)
Else
ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, Nothing, Nothing, Nothing)
End If
If ret = NO_ERROR Then Return Nothing
Return getErrorForNumber(ret)
End Function
Public Shared Function disconnectRemote(ByVal remoteUNC As String) As String
Dim ret As Integer = WNetCancelConnection2(remoteUNC, Connects.UpdateProfile, False)
If ret = NO_ERROR Then Return Nothing
Return getErrorForNumber(ret)
End Function
Enum Resources As Integer
Connected = &H1
GlobalNet = &H2
Remembered = &H3
End Enum
Enum ResourceTypes As Integer
Any = &H0
Disk = &H1
Print = &H2
End Enum
Enum ResourceDisplayTypes As Integer
Generic = &H0
Domain = &H1
Server = &H2
Share = &H3
File = &H4
Group = &H5
End Enum
Enum ResourceUsages As Integer
Connectable = &H1
Container = &H2
End Enum
Enum Connects As Integer
Interactive = &H8
Prompt = &H10
Redirect = &H80
UpdateProfile = &H1
CommandLine = &H800
CmdSaveCred = &H1000
LocalDrive = &H100
End Enum
End Class
how to use it
Dim login = PinvokeWindowsNetworking.connectToRemote("\\ComputerName", "ComputerName\UserName", "Password")
If IsNothing(login) Then
'do your thing on the shared folder
PinvokeWindowsNetworking.disconnectRemote("\\ComputerName")
End If
General rule: If following a rule requires you to do something more awkward and difficult to read then breaking the rule, then break the rule.
In the case of looping until you find something, you run into the problem of distinguishing found versus not found when you get out. That is:
for (int x=0;x<fooCount;++x)
{
Foo foo=getFooSomehow(x);
if (foo.bar==42)
break;
}
// So when we get here, did we find one, or did we fall out the bottom?
So okay, you can set a flag, or initialize a "found" value to null. But
That's why in general I prefer to push my searches into functions:
Foo findFoo(int wantBar)
{
for (int x=0;x<fooCount;++x)
{
Foo foo=getFooSomehow(x);
if (foo.bar==wantBar)
return foo;
}
// Not found
return null;
}
This also helps to unclutter the code. In the main line, "find" becomes a single statement, and when the conditions are complex, they're only written once.
this might help someone who had similar issue like me , i followed all naming and interface standards., But i was still facing issue.
My param name was --> update_datetime
I wanted to fetch my entities based on the update_datetime in the descending order, and i was getting the error
org.springframework.data.mapping.PropertyReferenceException: No property update found for type Release!
Somehow it was not reading the Underscore character --> ( _ )
so for workaround i changed the property name as --> updateDatetime
and then used the same for using JpaRepository methods.
It Worked !
Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:
DateTime dt = DateTime.MinValue;
DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);
This would work too.
List<string> names = Enum.GetNames(typeof(MyEnum)).ToList();
If your code is placed in a class you could use a decorator for that. You have such decorator in the utils-decorators (npm install --save utils-decorators
). It will cancel the previous invocation of the decorated method if before the resolving of the previous call there was made another call for that specific method.
import {cancelPrevious} from 'utils-decorators';
class SomeService {
@cancelPrevious()
doSomeAsync(): Promise<any> {
....
}
}
or you could use a wrapper function:
import {cancelPreviousify} from 'utils-decorators';
const cancelable = cancelPreviousify(originalMethod)
https://github.com/vlio20/utils-decorators#cancelprevious-method
The first way is "more correct", what intention could there be to express? If the code ends, it ends. That's pretty clear, in my opinion.
I don't understand what could possibly be confusing and need clarification. If there's no looping construct being used, then what could possibly happen other than that the function stops executing?
I would be severly annoyed by such a pointless extra return
statement at the end of a void
function, since it clearly serves no purpose and just makes me feel the original programmer said "I was confused about this, and now you can be too!" which is not very nice.
No of directory we can find using below command
ls -l | grep "^d" | wc -l
In my case, the mistake was that the animation was set to a parent div of the animated element (an SVG). The parent div had some crazy width, like 466.667px. Setting that to an odd number wouldn't help. But: targetting the SVG itself with the animation (instead of the parent container did).
My grep-a-like program ack
has a -1
option that stops at the first match found anywhere. It supports the -m 1
that @mvp refers to as well. I put it in there because if I'm searching a big tree of source code to find something that I know exists in only one file, it's unnecessary to find it and have to hit Ctrl-C.
An easier way of doing the same:
Type cast integer to character, let int n
be the integer,
then:
Char c=(char)n;
System.out.print(c)//char c will store the converted value.
The third row you expect (the one with Powerpoint) is filtered out by the Computer.ID = 1
condition (try running the query with the Computer.ID = 1 or Computer.ID is null
it to see what happens).
However, dropping that condition would not make sense, because after all, we want the list for a given Computer.
The only solution I see is performing a UNION between your original query and a new query that retrieves the list of application that are not found on that Computer.
The query might look like this:
DECLARE @ComputerId int
SET @ComputerId = 1
-- your original query
SELECT Computer.ComputerName, Application.Name, Software.Version
FROM Computer
JOIN dbo.Software_Computer
ON Computer.ID = Software_Computer.ComputerID
JOIN dbo.Software
ON Software_Computer.SoftwareID = Software.ID
RIGHT JOIN dbo.Application
ON Application.ID = Software.ApplicationID
WHERE Computer.ID = @ComputerId
UNION
-- query that retrieves the applications not installed on the given computer
SELECT Computer.ComputerName, Application.Name, NULL as Version
FROM Computer, Application
WHERE Application.ID not in
(
SELECT s.ApplicationId
FROM Software_Computer sc
LEFT JOIN Software s on s.ID = sc.SoftwareId
WHERE sc.ComputerId = @ComputerId
)
AND Computer.id = @ComputerId
if(c is TFrom)
{
// Do Stuff
}
or if you plan on using c
as a TForm
, use the following example:
var tForm = c as TForm;
if(tForm != null)
{
// c is of type TForm
}
The second example only needs to check to see if c
is of type TForm
once. Whereis if you check if see if c
is of type TForm
then cast it, the CLR undergoes an extra check.
Here is a reference.
Edit: Stolen from Jon Skeet
If you want to make sure c
is of TForm
and not any class inheriting from TForm
, then use
if(c.GetType() == typeof(TForm))
{
// Do stuff cause c is of type TForm and nothing else
}
Try this
#movie_item {
display: block;
margin-top: 10px;
height: 175px;
}
.movie_item_poster {
float: left;
height: 150px;
width: 100px;
background: red;
}
#movie_item_content {
float: left;
background: gold;
}
.movie_item_content_title {
display: block;
}
.movie_item_content_year {
float: right;
}
.movie_item_content_plot {
display: block;
}
.movie_item_toolbar {
clear: both;
vertical-align: bottom;
width: 100%;
height: 25px;
}
In Html
<div id="movie_item">
<div class="movie_item_poster">
<img src="..." style="max-width: 100%; max-height: 100%;">
</div>
<div id="movie_item_content">
<div class="movie_item_content_year">(1890-)</div>
<div class="movie_item_content_title">title my film is a long word</div>
<div class="movie_item_content_plot">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia, ratione, aliquam, earum, quibusdam libero rerum iusto exercitationem reiciendis illo corporis nulla ducimus suscipit nisi dolore explicabo. Accusantium porro reprehenderit ad!</div>
</div>
<div class="movie_item_toolbar">
Lorem Ipsum...
</div>
</div>
I change position div year.
In general, I break lines before operators, and indent the subsequent lines:
Map<long parameterization> longMap
= new HashMap<ditto>();
String longString = "some long text"
+ " some more long text";
To me, the leading operator clearly conveys that "this line was continued from something else, it doesn't stand on its own." Other people, of course, have different preferences.
Generally this problem occurs when you are modifying the keys very oftenly. Based on the server it might take some time to update the new key that you have generated and pasted in the server. So after generating the key and pasting in the server, wait for 3 to 4 hours and then try. The problem should be solved. It happened with me.
Its working for me in rating bar xml style="?android:attr/ratingBarStyleSmall" add this.it will work.
For future readers.
I wanted specific control over this issue, so this is what I did:
From a fragment or activity, hide your other views (that aren't needed while the keyboard is up), then restore them to solve this problem:
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
int heightDiff = rootView.getRootView().getHeight() - (r.bottom - r.top);
if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
//ok now we know the keyboard is up...
view_one.setVisibility(View.GONE);
view_two.setVisibility(View.GONE);
} else {
//ok now we know the keyboard is down...
view_one.setVisibility(View.VISIBLE);
view_two.setVisibility(View.VISIBLE);
}
}
});
Although this may be more complicated/heavier-weight than you want, one very flexible way to do it is using something like Expect (or one of the derivatives in another programming language).
Expect is a language designed specifically to control text-based applications, which is exactly what you are looking to do. If you end up needing to do something more complicated (like with logic to actually decide what to do/answer next), Expect is the way to go.
To connect Excel to Access using VBA is very useful I use it in my profession everyday. The connection string I use is according to the program found in the link below. The program can be automated to do multiple connections or tasks in on shot but the basic connection code looks the same. Good luck!
I had a similar issue, I found the reason for this is because you need to calculate the dp
. Android studio is calculating the ImageView
when you load it from the drawable
, but when you are using another method, like loading from bitmap the dp
is not automatically accounted for,
Here is my xml
<ImageView
android:id="@+id/imageViewer"
android:layout_width="match_parent"
android:layout_height="match_parent"//dp is not automaticly updated, when loading from a other source
android:scaleType="fitCenter"
tools:srcCompat="@drawable/a8" />
I'm using Kotlin, and loading drawable from an asset file, here's how I calculate this
val d = Drawable.createFromStream(assets.open("imageData/${imageName}.png"), null)
bitHeight = d.minimumHeight//get the image height
imageViewer.layoutParams.height = (bitHeight * resources.displayMetrics.density).toInt()//set the height
imageViewer.setImageDrawable(d)//set the image from the drawable
imageViewer.requestLayout()//here I apply it to the layout
DELIMITER ;;
CREATE TRIGGER `my_table_bi` BEFORE INSERT ON `my_table` FOR EACH ROW
BEGIN
SET NEW.created_date = NOW();
END;;
DELIMITER ;
I got a solution for downloading from angular 2 without getting corrupt, using spring mvc and angular 2
1st- my return type is :-ResponseEntity from java end. Here I am sending byte[] array has return type from the controller.
2nd- to include the filesaver in your workspace-in the index page as:
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
3rd- at component ts write this code:
import {ResponseContentType} from '@angular.core';
let headers = new Headers({ 'Content-Type': 'application/json', 'MyApp-Application' : 'AppName', 'Accept': 'application/pdf' });
let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob });
this.http
.post('/project/test/export',
somevalue,options)
.subscribe(data => {
var mediaType = 'application/vnd.ms-excel';
let blob: Blob = data.blob();
window['saveAs'](blob, 'sample.xls');
});
This will give you xls file format. If you want other formats change the mediatype and file name with right extension.
So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.
Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.
Waiting for all images to load...
I found the anwser to my problem with jfriend00 here jquery: how to listen to the image loaded event of one container div? .. and "if (this.complete)"
Waiting for the all thing to load and some possibly in cache !.. and i have added the "error" event...
it's robust across all browsers
$(function() { // Wait dom ready
var $img = $('img'), // images collection
totalImg = $img.length,
waitImgDone = function() {
totalImg--;
if (!totalImg) {
console.log($img.length+" image(s) chargée(s) !");
}
};
$img.each(function() {
if (this.complete) waitImgDone(); // already here..
else $(this).load(waitImgDone).error(waitImgDone); // completed...
});
});
If you are a Windows user, you may either remove or update your credentials in Credential Manager.
In Windows 10, go to the below path:
Control Panel → All Control Panel Items → Credential Manager
Or search for "credential manager" in your "Search Windows" section in the Start menu.
Then from the Credential Manager, select "Windows Credentials".
Credential Manager will show many items including your outlook and GitHub repository under "Generic credentials"
You click on the drop down arrow on the right side of your Git: and it will show options to edit and remove. If you remove, the credential popup will come next time when you fetch or pull. Or you can directly edit the credentials there.
patrick dw's answer is right on.
For kicks and giggles I thought I would post a simple way to return an array of all the IDs.
var arrayOfIds = $.map($(".myClassName"), function(n, i){
return n.id;
});
alert(arrayOfIds);
use the variable, Oracle does not support SQL in that context without an INTO. With a properly named variable your code will be more legible anyway.
I don't want to have to enable a reference library as I need my scripts to be portable. The Dim foo As New VBScript_RegExp_55.RegExp
line caused User Defined Type Not Defined
errors, but I found a solution that worked for me.
Update RE comments w/ @chrisneilsen :
I was under the impression that enabling a reference library was tied to the local computers settings, but it is in fact, tied directly to the workbook. So, you can enable a reference library, share a macro enabled workbook and the end user wouldn't have to enable the library as well. Caveat: The advantage to Late Binding is that the developer does not have to worry about the wrong version of an object library being installed on the user's computer. This likely would not be an issue w/ the VBScript_RegExp_55.RegExp
library, but I'm not sold that the "performance" benifit is worth it for me at this time, as we are talking imperceptible milliseconds in my code. I felt this deserved an update to help others understand. If you enable the reference library, you can use "early bind", but if you don't, as far as I can tell, the code will work fine, but you need to "late bind" and loose on some performance/debugging features.
Source: https://peltiertech.com/Excel/EarlyLateBinding.html
What you'll want to do is put an example string in cell A1
, then test your strPattern
. Once that's working adjust then rng
as desired.
Public Sub RegExSearch()
'https://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops
'https://wellsr.com/vba/2018/excel/vba-regex-regular-expressions-guide/
'https://www.vitoshacademy.com/vba-regex-in-excel/
Dim regexp As Object
'Dim regex As New VBScript_RegExp_55.regexp 'Caused "User Defined Type Not Defined" Error
Dim rng As Range, rcell As Range
Dim strInput As String, strPattern As String
Set regexp = CreateObject("vbscript.regexp")
Set rng = ActiveSheet.Range("A1:A1")
strPattern = "([a-z]{2})([0-9]{8})"
'Search for 2 Letters then 8 Digits Eg: XY12345678 = Matched
With regexp
.Global = False
.MultiLine = False
.ignoreCase = True
.Pattern = strPattern
End With
For Each rcell In rng.Cells
If strPattern <> "" Then
strInput = rcell.Value
If regexp.test(strInput) Then
MsgBox rcell & " Matched in Cell " & rcell.Address
Else
MsgBox "No Matches!"
End If
End If
Next
End Sub
A MySQL MyISAM table is the combination of three files:
You should be able to restore by copying them in your database folder (In linux, the default location is /var/lib/mysql/
)
You should do it while the server is not running.
In addition to perfect Riceball LEE's example of adding a new element-directive
newElement = $compile("<div my-directive='n'></div>")($scope)
$element.parent().append(newElement)
Adding a new attribute-directive to existed element could be done using this way:
Let's say you wish to add on-the-fly my-directive
to the span
element.
template: '<div>Hello <span>World</span></div>'
link: ($scope, $element, $attrs) ->
span = $element.find('span').clone()
span.attr('my-directive', 'my-directive')
span = $compile(span)($scope)
$element.find('span').replaceWith span
Hope that helps.
Turn on Regex Search and Replace (icon most to the left in search and replace bar or shortcut Alt + R)
Find What: \\n
Replace with: \n
Cheers
Another alternative to Loganathan Mohanraj's solution (which effectively does the same, but from the GUI):
Just write:
date("Y") // A full numeric representation of a year, 4 digits
// Examples: 1999 or 2003
Or:
date("y"); // A two digit representation of a year Examples: 99 or 03
And 'echo' this value...
$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);
Note: only work for your example.
for (var i in a) {
console.log(a[i],i)
}
The accepted answer needs an Option 3
ALSO Option 2 is TERRIBLE. It should NEVER be used (esp. in production) since it provides a FALSE sense of security. Just use HTTP instead of Option 2.
OPTION 3
Use the self-signed certificate to make the Https connection.
Here is an example:
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.KeyStore;
/*
* Use a SSLSocket to send a HTTP GET request and read the response from an HTTPS server.
* It assumes that the client is not behind a proxy/firewall
*/
public class SSLSocketClientCert
{
private static final String[] useProtocols = new String[] {"TLSv1.2"};
public static void main(String[] args) throws Exception
{
URL inputUrl = null;
String certFile = null;
if(args.length < 1)
{
System.out.println("Usage: " + SSLSocketClient.class.getName() + " <url>");
System.exit(1);
}
if(args.length == 1)
{
inputUrl = new URL(args[0]);
}
else
{
inputUrl = new URL(args[0]);
certFile = args[1];
}
SSLSocket sslSocket = null;
PrintWriter outWriter = null;
BufferedReader inReader = null;
try
{
SSLSocketFactory sslSocketFactory = getSSLSocketFactory(certFile);
sslSocket = (SSLSocket) sslSocketFactory.createSocket(inputUrl.getHost(), inputUrl.getPort() == -1 ? inputUrl.getDefaultPort() : inputUrl.getPort());
String[] enabledProtocols = sslSocket.getEnabledProtocols();
System.out.println("Enabled Protocols: ");
for(String enabledProtocol : enabledProtocols) System.out.println("\t" + enabledProtocol);
String[] supportedProtocols = sslSocket.getSupportedProtocols();
System.out.println("Supported Protocols: ");
for(String supportedProtocol : supportedProtocols) System.out.println("\t" + supportedProtocol + ", ");
sslSocket.setEnabledProtocols(useProtocols);
/*
* Before any data transmission, the SSL socket needs to do an SSL handshake.
* We manually initiate the handshake so that we can see/catch any SSLExceptions.
* The handshake would automatically be initiated by writing & flushing data but
* then the PrintWriter would catch all IOExceptions (including SSLExceptions),
* set an internal error flag, and then return without rethrowing the exception.
*
* This means any error messages are lost, which causes problems here because
* the only way to tell there was an error is to call PrintWriter.checkError().
*/
sslSocket.startHandshake();
outWriter = sendRequest(sslSocket, inputUrl);
readResponse(sslSocket);
closeAll(sslSocket, outWriter, inReader);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
closeAll(sslSocket, outWriter, inReader);
}
}
private static PrintWriter sendRequest(SSLSocket sslSocket, URL inputUrl) throws IOException
{
PrintWriter outWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream())));
outWriter.println("GET " + inputUrl.getPath() + " HTTP/1.1");
outWriter.println("Host: " + inputUrl.getHost());
outWriter.println("Connection: Close");
outWriter.println();
outWriter.flush();
if(outWriter.checkError()) // Check for any PrintWriter errors
System.out.println("SSLSocketClient: PrintWriter error");
return outWriter;
}
private static void readResponse(SSLSocket sslSocket) throws IOException
{
BufferedReader inReader = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
String inputLine;
while((inputLine = inReader.readLine()) != null)
System.out.println(inputLine);
}
// Terminate all streams
private static void closeAll(SSLSocket sslSocket, PrintWriter outWriter, BufferedReader inReader) throws IOException
{
if(sslSocket != null) sslSocket.close();
if(outWriter != null) outWriter.close();
if(inReader != null) inReader.close();
}
// Create an SSLSocketFactory based on the certificate if it is available, otherwise use the JVM default certs
public static SSLSocketFactory getSSLSocketFactory(String certFile)
throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException
{
if (certFile == null) return (SSLSocketFactory) SSLSocketFactory.getDefault();
Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(new File(certFile)));
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("server", certificate);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
return sslContext.getSocketFactory();
}
}
just remove the alignItems: 'center'
in the container styles and add textAlign: "center"
to the line1
style like given below.
It will work well
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#F5FCFF',
borderWidth: 1,
}
line1: {
backgroundColor: '#FDD7E4',
textAlign:'center'
},
If it is windows 10 then open the powershell as admin and run the following command:
dism /online /enable-feature /all /featurename:IIS-ASPNET45
Try converting your boolean to an integer?
echo (int)$bool_val;
I guess it's a matter of taste, although (mistakenly) mixing them up might cause some undesired behaviors:
true && false || false; // returns false
true and false || false; // returns true
Hence, using && and || is safer for they have the highest precedence. In what regards to readability, I'd say these operators are universal enough.
UPDATE: About the comments saying that both operations return false ... well, in fact the code above does not return anything, I'm sorry for the ambiguity. To clarify: the behavior in the second case depends on how the result of the operation is used. Observe how the precedence of operators comes into play here:
var_dump(true and false || false); // bool(false)
$a = true and false || false; var_dump($a); // bool(true)
The reason why $a === true
is because the assignment operator has precedence over any logical operator, as already very well explained in other answers.
If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...
For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.
Modified Alec McGail's answer to support JSON with lists inside
def flattenjson(self, mp, delim="|"):
ret = []
if isinstance(mp, dict):
for k in mp.keys():
csvs = self.flattenjson(mp[k], delim)
for csv in csvs:
ret.append(k + delim + csv)
elif isinstance(mp, list):
for k in mp:
csvs = self.flattenjson(k, delim)
for csv in csvs:
ret.append(csv)
else:
ret.append(mp)
return ret
Thanks!
try
Calendar c = Calendar.getInstance(); // this takes current date
c.set(Calendar.DAY_OF_MONTH, 1);
System.out.println(c.getTime()); // this returns java.util.Date
Updated (Since Java 8):
import java.time.LocalDate;
LocalDate todaydate = LocalDate.now();
System.out.println("Months first date in yyyy-mm-dd: " +todaydate.withDayOfMonth(1));
Use select setval('payments_id_seq', 21, true);
setval
contains 3 parameters:
sequence_name
nextval
The use of true or false in 3rd parameter of setval is as follows:
SELECT setval('payments_id_seq', 21); // Next nextval will return 22
SELECT setval('payments_id_seq', 21, true); // Same as above
SELECT setval('payments_id_seq', 21, false); // Next nextval will return 21
The better way to avoid hard-coding of sequence name, next sequence value and to handle empty column table correctly, you can use the below way:
SELECT setval(pg_get_serial_sequence('table_name', 'id'), coalesce(max(id), 0)+1 , false) FROM table_name;
where table_name
is the name of the table, id
is the primary key
of the table
i had this problem before , i am using yii2 and i solved it this way
$.fn.modal.Constructor.prototype.enforceFocus = $.noop;
Table Name
sp_rename 'db_name.old_table_name', 'new_table_name'
Column
sp_rename 'db_name.old_table_name.name' 'userName', 'COLUMN'
Index
sp_rename 'db_name.old_table_name.id', 'product_ID', 'INDEX'
also available for statics and datatypes
How about this
$.validate.addMethod(cb_selectone,
function(value,element){
if(element.length>0){
for(var i=0;i<element.length;i++){
if($(element[i]).val('checked')) return true;
}
return false;
}
return false;
},
'Please select a least one')
Now you ca do
$.validate({rules:{checklist:"cb_selectone"}});
You can even go further a specify the minimum number to select with a third param in the callback function.I have not tested it yet so tell me if it works.
To make a translation in the controller you could use $translate
service:
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope
event: $translateChangeSuccess
and do the same translation there:
$rootScope.$on('$translateChangeSuccess', function () {
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
});
Of course, you could encapsulate the $translate
service in a method and call it in the controller and in the $translateChangeSucess
listener.
Edit your AndroidManifest.xml
android:windowSoftInputMode="adjustResize"
Add this to your root view of Layout file.
android:fitsSystemWindows="true"
That's all.
You may have real characters "\" in the string (the single quote strings, as said @Robik).
If you are quite sure the '\r' or '\n' strings should be replaced as well, I'm not talking of special characters here but a sequence of two chars '\' and 'r', then escape the '\' in the replace string and it will work:
str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),"<br/>",$description);
Check out the boost NumericConversion library. It will allow to explicitly control how you want to deal with issues like overflow handling and truncation.
The --trace-ascii
option to curl will show the request headers, as well as the response headers and response body.
For example, the command
curl --trace-ascii curl.trace http://www.google.com/
produces a file curl.trace
that starts as follows:
== Info: About to connect() to www.google.com port 80 (#0)
== Info: Trying 209.85.229.104... == Info: connected
== Info: Connected to www.google.com (209.85.229.104) port 80 (#0)
=> Send header, 145 bytes (0x91)
0000: GET / HTTP/1.1
0010: User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3
0050: OpenSSL/0.9.7l zlib/1.2.3
006c: Host: www.google.com
0082: Accept: */*
008f:
It also got a response (a 302 response, to be precise but irrelevant) which was logged.
If you only want to save the response headers, use the --dump-header
option:
curl -D file url
curl --dump-header file url
If you need more information about the options available, use curl --help | less
(it produces a couple hundred lines of output but mentions a lot of options). Or find the manual page where there is more explanation of what the options mean.
I created this function, for rounding a number. The value can be a string (ex. '1.005') or a number 1.005 that will be 1 by default and if you specify the decimal to be 2, the result will be 1.01
round(value: string | number, decimals: number | string = "0"): number | null {
return +( Math.round(Number(value + "e+"+decimals)) + "e-" + decimals);
}
Usage: round(1.005, 2) // 1.01 or Usage: round('1.005', 2) //1.01
You'll have to set it to zero. Zero means the script can run forever. Add the following at the start of your script:
ini_set('max_execution_time', 0);
Refer to the PHP documentation of max_execution_time
Note that:
set_time_limit(0);
will have the same effect.
To Use Jquery in Angular2(4)
Follow these setps
install the Jquery and Juqry type defination
For Jquery Installation npm install jquery --save
For Jquery Type defination Installation npm install @types/jquery --save-dev
and then simply import the jquery
import { Component } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
console.log($(window)); // jquery is accessible
}
Also if you want to get most frequent value(positive or negative) without loading any modules you can use the following code:
lVals = [1,2,3,1,2,1,1,1,3,2,2,1]
print max(map(lambda val: (lVals.count(val), val), set(lVals)))
The VS equivalent of a makefile is a "Solution" (over-simplified, I know).
Simple, Elegant, and Powerful:
A generator expression in conjuction with a builtin… (python 2.5+)
any(x for x in mylist if x.n == 10)
Uses the Python any()
builtin, which is defined as follows:
any(iterable)
->
Return True if any element of the iterable is true. Equivalent to:
def any(iterable):
for element in iterable:
if element:
return True
return False
In C# These ways you can Solve the problem, In UIkit these methods are available.
Label.Font = Label.Font.WithSize(5.0f);
Or
Label.Font = UIFont.FromName("Copperplate", 10.0f);
Or
Label.Font = UIFont.WithSize(5.0f);
Here simple example to create pandas dataframe by using numpy array.
import numpy as np
import pandas as pd
# create an array
var1 = np.arange(start=1, stop=21, step=1).reshape(-1)
var2 = np.random.rand(20,1).reshape(-1)
print(var1.shape)
print(var2.shape)
dataset = pd.DataFrame()
dataset['col1'] = var1
dataset['col2'] = var2
dataset.head()
Relation objects can be converted to arrays. This negates being able to use any ActiveRecord methods on them afterwards, but I didn't need to. I did this:
name_relation = first_name_relation + last_name_relation
Ruby 1.9, rails 3.2
The process is greatly simplified for VS2017 / VS2019 (maybe even earlier, but I have not tested) in conjunction with GitHub:
Create an empty repository in GitHub => https://github.com//.git
Follow these instructions: (optionally add to source control to git initialize) -> Team explorer -> Sync -> Publish to GitHub -> https://github.com//.git
If you need minimal value for particular column
min(data[,2])
Note: R considers NA
both the minimum and maximum value so if you have NA's in your column, they return: NA
. To remedy, use:
min(data[,2], na.rm=T)
For me Run->Attach debugger to Android process was working, but I had to do it every time app was launched.
Fix: There may be a problem with your 'App launch configuration'(To verify this create new project to see if it's working fine). Just delete app configuration, open MainActivity file and Run->Debug (new conffiguration will be created)
With a .rdl, .rdlc or similar file selected, you can either:
To check input type
<!DOCTYPE html>
<html>
<body>
<input type=number id="txtinp">
<button onclick=checktype()>Try it</button>
<script>
function checktype()
{
alert(document.getElementById("txtinp").type);
}
</script>
</body>
</html>
the pom.xml for the project I have doesn't have this "http://repo1.maven.org/myurlhere" anywhere in it
All projects have http://repo1.maven.org/ declared as <repository>
(and <pluginRepository>
) by default. This repository, which is called the central repository, is inherited like others default settings from the "Super POM" (all projects inherit from the Super POM). So a POM is actually a combination of the Super POM, any parent POMs and the current POM. This combination is called the "effective POM" and can be printed using the effective-pom
goal of the Maven Help plugin (useful for debugging).
And indeed, if you run:
mvn help:effective-pom
You'll see at least the following:
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Repository Switchboard</name>
<url>http://repo1.maven.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Plugin Repository</name>
<url>http://repo1.maven.org/maven2</url>
</pluginRepository>
</pluginRepositories>
it has the absolute url where the maven repo is for the project but maven is still trying to download from the general maven repo
Maven will try to find dependencies in all repositories declared, including in the central one which is there by default as we saw. But, according to the trace you are showing, you only have one repository defined (the central repository) or maven would print something like this:
Reason: Unable to download the artifact from any repository
url.project:project:pom:x.x
from the specified remote repositories:
central (http://repo1.maven.org/),
another-repository (http://another/repository)
So, basically, maven is unable to find the url.project:project:pom:x.x
because it is not available in central.
But without knowing which project you've checked out (it has maybe specific instructions) or which dependency is missing (it can maybe be found in another repository), it's impossible to help you further.
your google-services.json package name must match your build.gradle applicationId (applicationId "your package name")
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
This is my simple solution, adapted from Microsoft (https://code.msdn.microsoft.com/windowsapps/How-to-add-a-hint-text-to-ed66a3c6)
<Grid Background="White" HorizontalAlignment="Right" VerticalAlignment="Top" >
<!-- overlay with hint text -->
<TextBlock Margin="5,2" MinWidth="50" Text="Suche..."
Foreground="LightSteelBlue" Visibility="{Binding ElementName=txtSearchBox, Path=Text.IsEmpty, Converter={StaticResource MyBoolToVisibilityConverter}}" IsHitTestVisible="False"/>
<!-- enter term here -->
<TextBox MinWidth="50" Name="txtSearchBox" Background="Transparent" />
</Grid>
Use the below code in your rounded_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#FFFFFF" />
<stroke
android:width="1dp"
android:color="#2f6699" />
<corners
android:radius="10dp"
/>
</shape>
This should work
I think the fastest way to do this is:
GradientDrawable gradientDrawable = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM, //set a gradient direction
new int[] {0xFF757775,0xFF151515}); //set the color of gradient
gradientDrawable.setCornerRadius(10f); //set corner radius
//Apply background to your view
View view = (RelativeLayout) findViewById( R.id.my_view );
if(Build.VERSION.SDK_INT>=16)
view.setBackground(gradientDrawable);
else view.setBackgroundDrawable(gradientDrawable);
No, I don't think there is. Unfortunately, you're stuck calling getApplicationContext()
from Activity
or one of the other subclasses of Context
. Also, this question is somewhat related.
SimpleDateFormat
stores intermediate results in instance fields. So if one instance is used by two threads they can mess each other's results.
Looking at the source code reveals that there is a Calendar
instance field, which is used by operations on DateFormat
/ SimpleDateFormat
.
For example parse(..)
calls calendar.clear()
initially and then calendar.add(..)
. If another thread invokes parse(..)
before the completion of the first invocation, it will clear the calendar, but the other invocation will expect it to be populated with intermediate results of the calculation.
One way to reuse date formats without trading thread-safety is to put them in a ThreadLocal
- some libraries do that. That's if you need to use the same format multiple times within one thread. But in case you are using a servlet container (that has a thread pool), remember to clean the thread-local after you finish.
To be honest, I don't understand why they need the instance field, but that's the way it is. You can also use joda-time DateTimeFormat
which is threadsafe.
Also with dict
a = []
b = {1:'one'}
a.append(dict(b))
print a
b[1]='iuqsdgf'
print a
result
[{1: 'one'}]
[{1: 'one'}]
Try this:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:toolbar="http://schemas.android.com/apk/res-auto"
android:id="@+id/tool_drawer"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
toolbar:navigationIcon="@drawable/ic_navigation">
</android.support.v7.widget.Toolbar>
You are not using a .NET control for your text area. Either add runat="server"
to the HTML TextArea control or use a .NET control:
Try this:
<asp:TextBox id="TextArea1" TextMode="multiline" Columns="50" Rows="5" runat="server" />
Then reference it in your codebehind:
message.Body = TextArea1.Text;
FROM ubuntu:14.04
RUN rm /bin/sh && ln -s /bin/bash /bin/sh
This should work for every Ubuntu docker base image. I generally add this line for every Dockerfile I write.
If you want to get the effect of "use bash
instead of sh
throughout this entire Dockerfile", without altering and possibly damaging* the OS inside the container, you can just tell Docker your intention. That is done like so:
SHELL ["/bin/bash", "-c"]
* The possible damage is that many scripts in Linux (on a fresh Ubuntu install
grep -rHInE '/bin/sh' /
returns over 2700 results) expect a fully POSIX shell at/bin/sh
. The bash shell isn't just POSIX plus extra builtins. There are builtins (and more) that behave entirely different than those in POSIX. I FULLY support avoiding POSIX (and the fallacy that any script that you didn't test on another shell is going to work because you think you avoided basmisms) and just using bashism. But you do that with a proper shebang in your script. Not by pulling the POSIX shell out from under the entire OS. (Unless you have time to verify all 2700 plus scripts that come with Linux plus all those in any packages you install.)
More detail in this answer below. https://stackoverflow.com/a/45087082/117471
// copy /tmp/abc.txt to /tmp/abc.txt (target path)
// username and password of 10.1.1.2 is "username" and "password"
sshpass -p "password" scp /tmp/abc.txt [email protected]:/tmp/abc.txt
// install sshpass (ubuntu)
sudo apt-get install sshpass
C:\Users\xyz>adb shell pm list packages -f | findstr whatsapp
package:/data/app/com.whatsapp-1/base.apk=com.whatsapp
C:\Users\xyz>adb pull /data/app/com.whatsapp-1/base.apk Desktop
/data/app/com.whatsapp-1/base.apk: 1 f.... 13.8 MB/s (32803925 bytes in
2.269s)
Have you instaled the J2EE? If you installed just de standard (J2SE) it won´t find.
I don't know if this is exactly what you want, but did you know you can use the CSS overflow
property to create scrollbars?
CSS:
div.box{
width: 200px;
height: 200px;
overflow: scroll;
}
HTML:
<div class="box">
All your text content...
</div>
I think the easiest (and best) way to do this is to subclass your global view and use hitTest:withEvent
method to listen to any touch. Touches on keyboard aren't registered, so hitTest:withEvent is only called when you touch/scroll/swipe/pinch... somewhere else, then call [self endEditing:YES]
.
This is better than using touchesBegan
because touchesBegan
are not called if you click on a button on top of the view. It is better than UITapGestureRecognizer
which can't recognize a scrolling gesture for example. It is also better than using a dim screen because in a complexe and dynamic user interface, you can't put dim screen everywhere. Moreover, it doesn't block other actions, you don't need to tap twice to select a button outside (like in the case of a UIPopover
).
Also, it's better than calling [textField resignFirstResponder]
, because you may have many text fields on screen, so this works for all of them.
We can separate out section of which we need to convert in PDF
For example, if table is in class "pdf-table-wrap"
After this, we need to call html2canvas function combined with jsPDF
following is sample code
var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
onrendered: function(canvas) {
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var imgData = canvas.toDataURL("image/png", 1.0);
var width = canvas.width;
var height = canvas.clientHeight;
pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));
}
});
setTimeout(function() {
//jsPDF code to save file
pdf.save('sample.pdf');
}, 0);
Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/
Typically this would be handled by your Subversion server administrator. If that's you and you are using the built-in authentication, then edit your [repository]\conf\passwd
file on your Subversion server machine.
Follow these steps:
Next time you attempt an action that requires credentials you'll be asked for them.
If you're using the command-line svn.exe
use the --no-auth-cache
option so that you can specify alternate credentials without having them cached against your Windows user.
Similar to the top answer, we were getting this incredibly unhelpful exception because of a missing IIS CORS module. It was the exact same error with Error Code (0x8007000d) and Config Source (-1: 0:), but installing the URL Rewriting module didn't fix it.
We had recently updated the web.config to enable CORS for some developers that needed it, but did not expect it would be required for all developers to install the IIS CORS module. Unfortunately it looks like it is required.
To fix it, install the IIS CORS module from here.
You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t
below) and alias the columns as well.
The DISTINCT
can also be safely removed as the internal GROUP BY
makes it redundant:
SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
SELECT MIN(`date`) AS `date`, `player_name`
FROM `player_playtime`
GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;
Since the COUNT
is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*)
and further simplify the query:
SELECT t.date , COUNT(*) AS player_count
FROM (
SELECT DATE(MIN(`date`)) AS date
FROM player_playtime
GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;
Working Solution in Java:
import java.awt.event.*;
import java.awt.Robot;
public class CircleMouse {
/* circle stuff */
final static int RADIUS = 100;
final static int XSTART = 500;
final static int YSTART = 500;
final static int DELAYMS = 1;
final static int ROUNDS = 5;
public static void main(String args[]) {
long startT = System.currentTimeMillis();
Robot bot = null;
try {
bot = new Robot();
} catch (Exception failed) {
System.err.println("Failed instantiating Robot: " + failed);
}
int mask = InputEvent.BUTTON1_DOWN_MASK;
int howMany = 360 * ROUNDS;
while (howMany > 0) {
int x = getX(howMany);
int y = getY(howMany);
bot.mouseMove(x, y);
bot.delay(DELAYMS);
System.out.println("x:" + x + " y:" + y);
howMany--;
}
long endT = System.currentTimeMillis();
System.out.println("Duration: " + (endT - startT));
}
/**
*
* @param angle
* in degree
* @return
*/
private static int getX(int angle) {
double radians = Math.toRadians(angle);
Double x = RADIUS * Math.cos(radians) + XSTART;
int result = x.intValue();
return result;
}
/**
*
* @param angle
* in degree
* @return
*/
private static int getY(int angle) {
double radians = Math.toRadians(angle);
Double y = RADIUS * Math.sin(radians) + YSTART;
int result = y.intValue();
return result;
}
}
For static text:
For long text that needs to be updated once in a while:
For a number (formatted 00.0):
In your onDraw event only update the value variable sent to the shader.
precision highp float;
precision highp sampler2D;
uniform float uTime;
uniform float uValue;
uniform vec3 iResolution;
varying vec4 v_Color;
varying vec2 vTextureCoord;
uniform sampler2D s_texture;
void main() {
vec4 fragColor = vec4(1.0, 0.5, 0.2, 0.5);
vec2 uv = vTextureCoord;
float devisor = 10.75;
float digit;
float i;
float uCol;
float uRow;
if (uv.y < 0.45) {
if (uv.x > 0.75) {
digit = floor(uValue*10.0);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.5) / devisor, uRow / devisor) );
} else if (uv.x > 0.5) {
uCol = 4.0;
uRow = 1.0;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.0) / devisor, uRow / devisor) );
} else if (uv.x > 0.25) {
digit = floor(uValue);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.5) / devisor, uRow / devisor) );
} else if (uValue >= 10.0) {
digit = floor(uValue/10.0);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.0) / devisor, uRow / devisor) );
} else {
fragColor = vec4(0.0, 0.0, 0.0, 0.0);
}
} else {
fragColor = vec4(0.0, 0.0, 0.0, 0.0);
}
gl_FragColor = fragColor;
}
Above code works for a texture atlas where numbers start from 0 at the 7th column of the 2nd row of the font atlas (texture).
Refer to https://www.shadertoy.com/view/Xl23Dw for demonstration (with wrong texture though)
First, add a pom.xml and make it a maven project and then build it. It will create a War file for you in the target folder after that you can deploy it wherever you want.
pom.xml http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 it.megadix create-react-app-servlet 0.0.1-SNAPSHOT war
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<npm.output.directory>build</npm.output.directory>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- Standard plugin to generate WAR -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<webResources>
<resource>
<directory>${npm.output.directory}</directory>
</resource>
</webResources>
<webXml>${basedir}/web.xml</webXml>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<!-- Required: The following will ensure `npm install` is called
before anything else during the 'Default Lifecycle' -->
<execution>
<id>npm install (initialize)</id>
<goals>
<goal>exec</goal>
</goals>
<phase>initialize</phase>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<!-- Required: The following will ensure `npm install` is called
before anything else during the 'Clean Lifecycle' -->
<execution>
<id>npm install (clean)</id>
<goals>
<goal>exec</goal>
</goals>
<phase>pre-clean</phase>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<!-- Required: This following calls `npm run build` where 'build' is
the script name I used in my project, change this if yours is
different -->
<execution>
<id>npm run build (compile)</id>
<goals>
<goal>exec</goal>
</goals>
<phase>compile</phase>
<configuration>
<executable>npm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
</configuration>
</execution>
</executions>
<configuration>
<environmentVariables>
<CI>true</CI>
<!-- The following parameters create an NPM sandbox for CI -->
<NPM_CONFIG_PREFIX>${basedir}/npm</NPM_CONFIG_PREFIX>
<NPM_CONFIG_CACHE>${NPM_CONFIG_PREFIX}/cache</NPM_CONFIG_CACHE>
<NPM_CONFIG_TMP>${project.build.directory}/npmtmp</NPM_CONFIG_TMP>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>local</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<environmentVariables>
<PUBLIC_URL>http://localhost:8080/${project.artifactId}</PUBLIC_URL>
<REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>prod</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<environmentVariables>
<PUBLIC_URL>http://my-awesome-production-host/${project.artifactId}</PUBLIC_URL>
<REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
Note:- If you find a blank page after running your project then clear your cache or restart your IDE.
Regarding WMI and Registry:
There are three WMI event classes concerning registry:
But you need to be aware of these limitations:
With RegistryTreeChangeEvent and RegistryKeyChangeEvent there is no way of directly telling which values or keys actually changed. To do this, you would need to save the registry state before the event and compare it to the state after the event.
You can't use these classes with HKEY_CLASSES_ROOT or HKEY_CURRENT_USER hives. You can overcome this by creating a WMI class to represent the registry key to monitor:
Defining a Registry Class With Qualifiers
and use it with __InstanceOperationEvent derived classes.
So using WMI to monitor the Registry is possible, but less then perfect. The advantage is that it is possible to monitor the changes in 'real time'. Another advantage could be WMI permanent event subscription:
a method to monitor the Registry 'at all times', ie. event if your application is not running.
You can press ok and it will continue the insallation.
Otherwise, see Trying to reinstall XAMPP on windows 7, getting error messag...
functionReturningTwoValues <- function() {
results <- list()
results$first <- 1
results$second <-2
return(results)
}
a <- functionReturningTwoValues()
I think this works.
I fixed it adding these lines in the build.grandle (App Module)
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar']) //it was there
compile "com.android.support:support-v4:21.0.+" //Added
compile "com.android.support:appcompat-v7:21.0.+" //Added
}
Cleaning up : Since the post section of a Pipeline is guaranteed to run at the end of a Pipeline’s execution, we can add some notification or other steps to perform finalization, notification, or other end-of-Pipeline tasks.
pipeline {
agent any
stages {
stage('No-op') {
steps {
sh 'ls'
}
}
}
post {
cleanup {
echo 'One way or another, I have finished'
deleteDir() /* clean up our workspace */
}
}
}
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
To be perfectly precise, Darwin is enough. No need to import the whole Cocoa framework.
import Darwin
Of course, if you need elements from Cocoa or Foundation or other higher level frameworks, you can import them instead
Assuming you are on 10g, you can also use the MERGE statement. This allows you to insert the row if it doesn't exist and ignore the row if it does exist. People tend to think of MERGE when they want to do an "upsert" (INSERT if the row doesn't exist and UPDATE if the row does exist) but the UPDATE part is optional now so it can also be used here.
SQL> create table foo (
2 name varchar2(10) primary key,
3 age number
4 );
Table created.
SQL> ed
Wrote file afiedt.buf
1 merge into foo a
2 using (select 'johnny' name, null age from dual) b
3 on (a.name = b.name)
4 when not matched then
5 insert( name, age)
6* values( b.name, b.age)
SQL> /
1 row merged.
SQL> /
0 rows merged.
SQL> select * from foo;
NAME AGE
---------- ----------
johnny
Not sure what you are asking, but... Class.forname, maybe?
It will work.
long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));
I'm not sure there's a way to hide that information. No matter what you do to obfuscate or hide whatever you're doing in JavaScript, it still comes down to the fact that your browser needs to load it in order to use it. Modern browsers have web debugging/analysis tools out of the box that make extracting and viewing scripts trivial (just hit F12 in Chrome, for example).
If you're worried about exposing some kind of trade secret or algorithm, then your only recourse is to encapsulate that logic in a web service call and have your page invoke that functionality via AJAX.
AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8
in the content type. It failed with a generic "Server Error"
and it took hours to figure out what it didn't like:
request.ContentType = "text/xml; encoding=utf-8";
Basing my answer on assumption that user just wanted to literaaly convert an int
to char
, for example
Input:
int i = 5;
Output:
char c = '5'
This has been already answered above, however if the integer value i > 10
, then need to use char array
.
char[] c = String.valueOf(i).toCharArray();
Pease note @Phrogz's solution doesn't work in IE 8 while @nickf's works in all major browsers. Another approach is:
$.each(myOptions, function(val, text) {
$("#mySelect").append($("<option/>").attr("value", val).text(text));
});
webView.setDownloadListener(new DownloadListener()
{
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading File...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}});
In addition to dplyr::rename
in newer versions of dplyr
is rename_with()
rename_with() renames columns using a function.
You can apply a function over a tidy-select set of columns using the .cols
argument:
iris %>%
dplyr::rename_with(.fn = ~ gsub("^S", "s", .), .cols = where(is.numeric))
sepal.Length sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
Your connection URL should look like the below,
jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false
This will disable SSL and also suppress the SSL errors.
Classifiers are just objects that can be pickled and dumped like any other. To continue your example:
import cPickle
# save the classifier
with open('my_dumped_classifier.pkl', 'wb') as fid:
cPickle.dump(gnb, fid)
# load it again
with open('my_dumped_classifier.pkl', 'rb') as fid:
gnb_loaded = cPickle.load(fid)
Edit: if you are using a sklearn Pipeline in which you have custom transformers that cannot be serialized by pickle (nor by joblib), then using Neuraxle's custom ML Pipeline saving is a solution where you can define your own custom step savers on a per-step basis. The savers are called for each step if defined upon saving, and otherwise joblib is used as default for steps without a saver.
A method that is relatively fast on long vectors and gives a convenient output is to use lengths(split(numbers, numbers))
(note the S at the end of lengths
):
# Make some integer vectors of different sizes
set.seed(123)
x <- sample.int(1e3, 1e4, replace = TRUE)
xl <- sample.int(1e3, 1e6, replace = TRUE)
xxl <-sample.int(1e3, 1e7, replace = TRUE)
# Number of times each value appears in x:
a <- lengths(split(x,x))
# Number of times the value 64 appears:
a["64"]
#~ 64
#~ 15
# Occurences of the first 10 values
a[1:10]
#~ 1 2 3 4 5 6 7 8 9 10
#~ 13 12 6 14 12 5 13 14 11 14
The output is simply a named vector.
The speed appears comparable to rle
proposed by JBecker and even a bit faster on very long vectors. Here is a microbenchmark in R 3.6.2 with some of the functions proposed:
library(microbenchmark)
f1 <- function(vec) lengths(split(vec,vec))
f2 <- function(vec) table(vec)
f3 <- function(vec) rle(sort(vec))
f4 <- function(vec) plyr::count(vec)
microbenchmark(split = f1(x),
table = f2(x),
rle = f3(x),
plyr = f4(x))
#~ Unit: microseconds
#~ expr min lq mean median uq max neval cld
#~ split 402.024 423.2445 492.3400 446.7695 484.3560 2970.107 100 b
#~ table 1234.888 1290.0150 1378.8902 1333.2445 1382.2005 3203.332 100 d
#~ rle 227.685 238.3845 264.2269 245.7935 279.5435 378.514 100 a
#~ plyr 758.866 793.0020 866.9325 843.2290 894.5620 2346.407 100 c
microbenchmark(split = f1(xl),
table = f2(xl),
rle = f3(xl),
plyr = f4(xl))
#~ Unit: milliseconds
#~ expr min lq mean median uq max neval cld
#~ split 21.96075 22.42355 26.39247 23.24847 24.60674 82.88853 100 ab
#~ table 100.30543 104.05397 111.62963 105.54308 110.28732 168.27695 100 c
#~ rle 19.07365 20.64686 23.71367 21.30467 23.22815 78.67523 100 a
#~ plyr 24.33968 25.21049 29.71205 26.50363 27.75960 92.02273 100 b
microbenchmark(split = f1(xxl),
table = f2(xxl),
rle = f3(xxl),
plyr = f4(xxl))
#~ Unit: milliseconds
#~ expr min lq mean median uq max neval cld
#~ split 296.4496 310.9702 342.6766 332.5098 374.6485 421.1348 100 a
#~ table 1151.4551 1239.9688 1283.8998 1288.0994 1323.1833 1385.3040 100 d
#~ rle 399.9442 430.8396 464.2605 471.4376 483.2439 555.9278 100 c
#~ plyr 350.0607 373.1603 414.3596 425.1436 437.8395 506.0169 100 b
Importantly, the only function that also counts the number of missing values NA
is plyr::count
. These can also be obtained separately using sum(is.na(vec))
You might be interested in somethinkg like this:
select * from (
select * from table
) as Subquery
Use string for shorter field, like names, address, phone, company
Use Text for larger content, comments, content, paragraphs.
My general rule, if it's something that is more than one line, I typically go for text, if it's a short 2-6 words, I go for string.
The official rule is 255 for a string. So, if your string is more than 255 characters, go for text.
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(isset($_GET['i'])){unset($_GET['i']); header('location:/');} ?>
This will remove the 'i' parameter from the URL. Change the 'i's to whatever you need.
This answer seems good.
however, it lead me towards an error as it resulted with
Configuration 'xyz' could not be found in project ...
error in build.
It is requierd not only to updated build configurations, but also serve
ones.
So just to leave no confusions:
--env
is not supported in angular 6
--env
got changed into --configuration
|| -c
(and is now more powerful)angular.json
file:
{ ... "build": "configurations": ...
propertyfileReplacements
part, (but more options are available){ ... "serve": "configurations": ...
propertybrowserTarget="your-project-name:build:staging"
You can use this code to send CSV file data into an array:
import numpy as np
csv = np.genfromtxt('test.csv', delimiter=",")
print(csv)
The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:
// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z
// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z
// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z
//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z
Try to enter the full-path of the dll. If it doesn't work, try to copy the dll into the system32 folder.
I have had a similar issue recently and realised that it's not due to background-size:cover
but background-attachment:fixed
.
I solved the issue by using a media query for iPhone and setting background-attachment
property to scroll
.
For my case:
.cover {
background-size: cover;
background-attachment: fixed;
background-position: center center;
@media (max-width: @iphone-screen) {
background-attachment: scroll;
}
}
Edit: The code block is in LESS and assumes a pre-defined variable for @iphone-screen
. Thanks for the notice @stephband.
I have a Nexus 4 and own a Thinkpad L430 Windows 8.1
My errors: "Waiting for device. USB device not found"
I went to: Device Manager > View > Drop to "Acer Device" > Right click on Acer Composite ADB Interface > Update it
Afterward, Reboot/Restart your computer. Once it turned on Plug Your USB Device onto the computer.
Go to: Setting > Enable "Developer options" > Check the "USB debugging" option > Check "Allow mock locations" > Check "Verify apps over USB".
Swipe down from the drop down menu of your phone where it Shows the USB Connection Icon. Tap on USB Computer Connection > Select the Check box "Camera (PTP)"
Run your Android Studio App and it should work
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
The pack
method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize
or setBounds
(which also sets the frame location). In general, using pack is preferable to calling setSize
, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.
From Java tutorial
You should also refer to Javadocs any time you need additional information on any Java API
var module = angular.module("example", []);
module.controller("orderByController", function ($scope) {
$scope.orderByValue = function (value) {
return value;
};
$scope.items = ["c", "b", "a"];
$scope.objList = [
{
"name": "c"
}, {
"name": "b"
}, {
"name": "a"
}];
$scope.item = "b";
});
I was porting one application from Visual C to gcc over Linux and I had the same problem with
malloc.c:3096: sYSMALLOc: Assertion using gcc on UBUNTU 11.
I moved the same code to a Suse distribution (on other computer ) and I don't have any problem.
I suspect that the problems are not in our programs but in the own libc.
The HTML
<a href="#" id="btn">click</a>
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
Based on the above suggestions, the following data.table
solution worked very fast for me:
library(data.table)
set.seed(45)
DT <- data.table(matrix(sample(10, 10^7, TRUE), ncol=10))
system.time(
DT[, col_max := colnames(.SD)[max.col(.SD, ties.method = "first")]]
)
#> user system elapsed
#> 0.15 0.06 0.21
DT[]
#> V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 col_max
#> 1: 7 4 1 2 3 7 6 6 6 1 V1
#> 2: 4 6 9 10 6 2 7 7 1 3 V4
#> 3: 3 4 9 8 9 9 8 8 6 7 V3
#> 4: 4 8 8 9 7 5 9 2 7 1 V4
#> 5: 4 3 9 10 2 7 9 6 6 9 V4
#> ---
#> 999996: 4 6 10 5 4 7 3 8 2 8 V3
#> 999997: 8 7 6 6 3 10 2 3 10 1 V6
#> 999998: 2 3 2 7 4 7 5 2 7 3 V4
#> 999999: 8 10 3 2 3 4 5 1 1 4 V2
#> 1000000: 10 4 2 6 6 2 8 4 7 4 V1
And also comes with the advantage that can always specify what columns .SD
should consider by mentioning them in .SDcols
:
DT[, MAX2 := colnames(.SD)[max.col(.SD, ties.method="first")], .SDcols = c("V9", "V10")]
In case we need the column name of the smallest value, as suggested by @lwshang, one just needs to use -.SD
:
DT[, col_min := colnames(.SD)[max.col(-.SD, ties.method = "first")]]
toISOString()
will give current UTC Date. So to get the current local time we have to get getTimezoneOffset()
and subtract it from current time
document.getElementById('dt').max = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString().split("T")[0];
_x000D_
<input type="date" min='1899-01-01' id="dt" />
_x000D_
There is package called rimraf that is very handy. It is the UNIX command rm -rf for node.
Nevertheless, it can be too powerful too because you can delete folders very easily using it. The following commands will delete the files inside the folder. If you remove the *, you will remove the log folder.
const rimraf = require('rimraf');
rimraf('./log/*', function () { console.log('done'); });
You can change the index as explained already using set_index
.
You don't need to manually swap rows with columns, there is a transpose (data.T
) method in pandas that does it for you:
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> newdf = df.set_index('Locality').T
> newdf
Locality ABBOTSFORD ABERFELDIE
2005 427000 534000
2006 448000 600000
then you can fetch the dataframe column values and transform them to a list:
> newdf['ABBOTSFORD'].values.tolist()
[427000, 448000]
A rather common solution to the two click problem is putting
e.stopPropagation()
at the end of your function (assuming you use function(e)
that is). This prevents the event from bubbling up which could lead to a second execution of the function.
For me it happened because I had 2 versions of python installed - python 27 and python 3.3. Both these folder had path variable set, and hence there was this issue. To fix, this, I moved python27 to temp folder, as I was ok with python 3.3. So do check environment variables like PATH,PYTHONHOME as it may be a issue. Thanks.
Use:
git remote prune <remote>
Where <remote>
is a remote source name like origin or upstream.
Example: git remote prune origin
If it doesn't have to be writeable you can create such an array with np.broadcast_to
:
>>> import numpy as np
>>> np.broadcast_to(True, (2, 5))
array([[ True, True, True, True, True],
[ True, True, True, True, True]], dtype=bool)
If you need it writable you can also create an empty array and fill
it yourself:
>>> arr = np.empty((2, 5), dtype=bool)
>>> arr.fill(1)
>>> arr
array([[ True, True, True, True, True],
[ True, True, True, True, True]], dtype=bool)
These approaches are only alternative suggestions. In general you should stick with np.full
, np.zeros
or np.ones
like the other answers suggest.
Access can always use the Excel procedure as long as the project has the Microsoft Excel XX.X object reference included:
Call Excel.Application.Wait(DateAdd("s",10,Now()))
There are a lot of ways to do this. Below is a few simple steps:
Suppose you have one Map like:
Map<String, Integer> m = new HashMap<String, Integer>();
Then you can do something like the below to iterate over map elements.
// ********** Using an iterator ****************
Iterator<Entry<String, Integer>> me = m.entrySet().iterator();
while(me.hasNext()){
Entry<String, Integer> pair = me.next();
System.out.println(pair.getKey() + ":" + pair.getValue());
}
// *********** Using foreach ************************
for(Entry<String, Integer> me : m.entrySet()){
System.out.println(me.getKey() + " : " + me.getValue());
}
// *********** Using keySet *****************************
for(String s : m.keySet()){
System.out.println(s + " : " + m.get(s));
}
// *********** Using keySet and iterator *****************
Iterator<String> me = m.keySet().iterator();
while(me.hasNext()){
String key = me.next();
System.out.println(key + " : " + m.get(key));
}
ul {
text-align: center;
list-style: inside;
}
string.isNullOrWhiteSpace(text) should be used in most cases as it also includes a blank string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
var str = "";
Console.WriteLine(string.IsNullOrWhiteSpace(str));
}
}
}
It returns True!
You can use the centos-sclo-rh-testing repo to install GCC v7 without having to compile it forever, also enable V7 by default and let you switch between different versions if required.
sudo yum install -y yum-utils centos-release-scl;
sudo yum -y --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc;
echo "source /opt/rh/devtoolset-7/enable" | sudo tee -a /etc/profile;
source /opt/rh/devtoolset-7/enable;
gcc --version;
There are many ways mentioned above. But I use rather simple way (well not simple as SELECT @@SERVERNAME). When you start SQL server management studio you will prompt below GUI
In there Server name is your server name (There may have multiple servers according to you dev environment choose correct one). Hope this helps :)
Another quick test for a string to have something in it but space.
if [[ -n "${str// /}" ]]; then
echo "It is not empty!"
fi
"-n" means non-zero length string.
Then the first two slashes mean match all of the following, in our case space(s). Then the third slash is followed with the replacement (empty) string and closed with "}". Note the difference from the usual regular expression syntax.
You can read more about string manipulation in bash shell scripting here.
if using homebrew you can update sim links using
brew link --overwrite git
Java 8
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
List<List<String>> stringListList = new ArrayList<>();
stringListList.add(Arrays.asList(new String[] {"(0,0)", "(0,1)"} ));
stringListList.add(Arrays.asList(new String[] {"(1,0)", "(1,1)", "(1,2)"} ));
stringListList.add(Arrays.asList(new String[] {"(2,0)", "(2,1)"} ));
int count=stringListList.stream().mapToInt(i -> i.size()).sum();
System.out.println("stringListList count: "+count);
}
}
Convert using Jackson :
JSONObject obj = new JSONObject().put("abc", "pqr").put("xyz", 5);
Map<String, Object> map = new ObjectMapper().readValue(obj.toString(), new TypeReference<Map<String, Object>>() {});
Of the existing IDEs, Ted Neward ranks them this way:
Best: IntelliJ IDEA
Second: Netbeans
Third: Eclipse
He seems to think that Eclipse throws up a lot of "friction"; hard to say what that means.
Edit, years later: After attempting to use Eclipse/Aptana for node development and using JetBrains products for node and ruby development I would absolutely start with IntelliJ IDEA and give that a try for the 30 day trial.
Using JSON.stringify(data);
:
$.ajax({
url: ...
success:function(data){
JSON.stringify(data); //to string
alert(data.you_value); //to view you pop up
}
});
A simplest way that i have tried
You can also create an array in your component file and you can call it with *ngFor directive by returning as an array .
Something like this ....
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-morning',
templateUrl: './morning.component.html',
styleUrls: ['./morning.component.css']
})
export class MorningComponent implements OnInit {
arr = [];
i: number = 0;
arra() {
for (this.i = 0; this.i < 20; this.i++) {
this.arr[this.i]=this.i;
}
return this.arr;
}
constructor() { }
ngOnInit() {
}
}
And this function can be used in your html template file
<p *ngFor="let a of arra(); let i= index">
value:{{a}} position:{{i}}
</p>
On my machine:
C:\Program Files\PostgreSQL\8.4\data\postgresql.conf
Have a look at https://wiki.debian.org/JavaPackage At the bottom of this page an other method is descibed using a command from the java-common package
You need remove path.moveTo after first initial.
Path path = new Path();
path.moveTo(point1_returned.x, point1_returned.y);
path.lineTo(point2_returned.x, point2_returned.y);
path.lineTo(point3_returned.x, point3_returned.y);
path.lineTo(point1_returned.x, point1_returned.y);
path.close();
In case the above does not work for you (i.e.: you are working with new SQL or Azure) try the following:
1) drop existing column constraint (if any):
ALTER TABLE [table_name] DROP CONSTRAINT DF_my_constraint
2) create a new one:
ALTER TABLE [table_name] ADD CONSTRAINT DF_my_constraint DEFAULT getdate() FOR column_name;
Most of the MVC helper methods have a XXXFor variant. They are intended to be used in conjunction with a concrete model class. The idea is to allow the helper to derive the appropriate "name" attribute for the form-input control based on the property you specify in the lambda. This means that you get to eliminate "magic strings" that you would otherwise have to employ to correlate the model properties with your views. For example:
Html.Hidden("Name", "Value")
Will result in:
<input id="Name" name="Name" type="hidden" value="Value">
In your controller, you might have an action like:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
}
And a model like:
public class MyModel
{
public string Name { get; set; }
}
The raw Html.Hidden
we used above will get correlated to the Name
property in the model. However, it's somewhat distasteful that the value "Name" for the property must be specified using a string ("Name"). If you rename the Name
property on the Model, your code will break and the error will be somewhat difficult to figure out. On the other hand, if you use HiddenFor
, you get protected from that:
Html.HiddenFor(x => x.Name, "Value");
Now, if you rename the Name
property, you will get an explicit runtime error indicating that the property can't be found. In addition, you get other benefits of static analysis, such as getting a drop-down of the members after typing x.
.
In VS 2015
MVC
, you may need to add the reference in the reference manager.import urllib
import urllib.request
from bs4 import BeautifulSoup
with urllib.request.urlopen("http://www.newegg.com/") as url:
s = url.read()
print(s)
soup = BeautifulSoup(s, "html.parser")
all_tag_a = soup.find_all("a", limit=10)
for links in all_tag_a:
#print(links.get('href'))
print(links)
This is a clean utility tool for the above answer :
@GetMapping(value = "/my-url")
public @ResponseBody
MappingJacksonValue getMyBean() {
List<MyBean> myBeans = Service.findAll();
MappingJacksonValue mappingValue = MappingFilterUtils.applyFilter(myBeans, MappingFilterUtils.JsonFilterMode.EXCLUDE_FIELD_MODE, "MyFilterName", "myBiggerObject.mySmallerObject.mySmallestObject");
return mappingValue;
}
//AND THE UTILITY CLASS
public class MappingFilterUtils {
public enum JsonFilterMode {
INCLUDE_FIELD_MODE, EXCLUDE_FIELD_MODE
}
public static MappingJacksonValue applyFilter(Object object, final JsonFilterMode mode, final String filterName, final String... fields) {
if (fields == null || fields.length == 0) {
throw new IllegalArgumentException("You should pass at least one field");
}
return applyFilter(object, mode, filterName, new HashSet<>(Arrays.asList(fields)));
}
public static MappingJacksonValue applyFilter(Object object, final JsonFilterMode mode, final String filterName, final Set<String> fields) {
if (fields == null || fields.isEmpty()) {
throw new IllegalArgumentException("You should pass at least one field");
}
SimpleBeanPropertyFilter filter = null;
switch (mode) {
case EXCLUDE_FIELD_MODE:
filter = SimpleBeanPropertyFilter.serializeAllExcept(fields);
break;
case INCLUDE_FIELD_MODE:
filter = SimpleBeanPropertyFilter.filterOutAllExcept(fields);
break;
}
FilterProvider filters = new SimpleFilterProvider().addFilter(filterName, filter);
MappingJacksonValue mapping = new MappingJacksonValue(object);
mapping.setFilters(filters);
return mapping;
}
}
It is also possible to declare it the following way. It's not good design, but it works.
int[] twoDimIntArray[] = new int[5][10];
There are methods in the String class; toUppercase()
and toLowerCase()
.
i.e.
String input = "Cricket!";
String upper = input.toUpperCase(); //stores "CRICKET!"
String lower = input.toLowerCase(); //stores "cricket!"
This will clarify your doubt
I wasted hours on this stupid issue. None of the above solutions worked for me on their own.
I'm running Windows 10. I had an old manual install of the Android SDK as well as Android Studio's SDK. I deleted my manually installed SDK and all my devices stopped working. These were the symptoms:
$ adb usb
error: device unauthorized.
This adb server's $ADB_VENDOR_KEYS is not set
Try 'adb kill-server' if that seems wrong.
Otherwise check for a confirmation dialog on your device.
as well as
$ adb devices
List of devices attached
id1 unauthorized
id2 unauthorized
id3 unauthorized
To be honest I'm not sure which of these steps got me my Allow USB debugging? prompts back so I listed EVERYTHING for completeness. Goes in order from easiest to hardest. Most people seem to be back on their feet after the first two sections.
I would perform this after each of the sections below.
adb kill-server
adb usb
~/.android
folder. Sometimes this folder can have the wrong permissions which can cause issues. You might want to back this folder up first.%ANDROID_HOME%
if you have it set%ANDROID_SDK_HOME%
if you have it setAt this point all my devices magically came to life and started displaying the Allow USB debugging? prompts and connecting properly through ADB. If you've made it this far and haven't found a solution, I am truly sorry you're in this predicament. Make sure you've restarted all devices and your dev machine at the end of all of these steps and connect to a fresh USB port using a new cable.
If that still doesn't work try some of these other SO posts on the subject:
I'm not with computer,so I write a draft. You might be clear of what I say.
func main(){
const dir = "/etc/"
filesInfo, e := ioutil.ReadDir(dir)
var fileNames = make([]string, 0, 10)
for i,v:=range filesInfo{
if !v.IsDir() {
fileNames = append(fileNames, v.Name())
}
}
var fileNumber = len(fileNames)
var contents = make([]string, fileNumber, 10)
wg := sync.WaitGroup{}
wg.Add(fileNumber)
for i,_:=range content {
go func(i int){
defer wg.Done()
buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
defer file.Close()
content[i] = string(buf)
}(i)
}
wg.Wait()
}
C:\Documents and Settings\Scripter>echo %cd%
C:\Documents and Settings\Scripter
C:\Documents and Settings\Scripter>
for Unix use pwd
command
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
}
This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:
var abc = 1; // we want to use this variable in embedded functions
function xyz(){
console.log(abc); // it is available here!
function qwe(){
console.log(abc); // it is available here too!
}
...
};
This technique relies on using a closure. But it doesn't work with this
because this
is a pseudo variable that may change from scope to scope dynamically:
// we want to use "this" variable in embedded functions
function xyz(){
// "this" is different here!
console.log(this); // not what we wanted!
function qwe(){
// "this" is different here too!
console.log(this); // not what we wanted!
}
...
};
What can we do? Assign it to some variable and use it through the alias:
var abc = this; // we want to use this variable in embedded functions
function xyz(){
// "this" is different here! --- but we don't care!
console.log(abc); // now it is the right object!
function qwe(){
// "this" is different here too! --- but we don't care!
console.log(abc); // it is the right object here too!
}
...
};
this
is not unique in this respect: arguments
is the other pseudo variable that should be treated the same way — by aliasing.
Another basic example:
NOT working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
};
img.src = reader.result;
Working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
}.bind(this);
img.src = reader.result;
So basically: just add .bind(this) to your function
Its specifically told that you need to reboot after you set the environmental variables in windows for migwin.
Like Query would be as shown below
db.movies.find({title: /.*Twelve Monkeys.*/}).sort({regularizedCorRelation : 1}).limit(10);
for scala ReactiveMongo api,
val query = BSONDocument("title" -> BSONRegex(".*"+name+".*", "")) //like
val sortQ = BSONDocument("regularizedCorRelation" -> BSONInteger(1))
val cursor = collection.find(query).sort(sortQ).options(QueryOpts().batchSize(10)).cursor[BSONDocument]
You could do:
SELECT
Orders.OrderNumber,
LineItems.Quantity,
LineItems.Description
FROM
Orders INNER JOIN LineItems
ON Orders.OrderID = LineItems.OrderID
WHERE
LineItems.LineItemID = (
SELECT MIN(LineItemID)
FROM LineItems
WHERE OrderID = Orders.OrderID
)
This requires an index (or primary key) on LineItems.LineItemID
and an index on LineItems.OrderID
or it will be slow.
You can only use await
in an async
method, and Main
cannot be async
.
You'll have to use your own async
-compatible context, call Wait
on the returned Task
in the Main
method, or just ignore the returned Task
and just block on the call to Read
. Note that Wait
will wrap any exceptions in an AggregateException
.
If you want a good intro, see my async
/await
intro post.
File file = new File("Path");
FileReader reader = new FileReader(file);
while((ch=reader.read())!=-1)
{
System.out.print((char)ch);
}
This worked for me
The above answers are good, except they don't have proper tick placement on the colorbar. I like having the ticks in the middle of the color so that the number -> color mapping is more clear. You can solve this problem by changing the limits of the matshow call:
import matplotlib.pyplot as plt
import numpy as np
def discrete_matshow(data):
#get discrete colormap
cmap = plt.get_cmap('RdBu', np.max(data)-np.min(data)+1)
# set limits .5 outside true range
mat = plt.matshow(data,cmap=cmap,vmin = np.min(data)-.5, vmax = np.max(data)+.5)
#tell the colorbar to tick at integers
cax = plt.colorbar(mat, ticks=np.arange(np.min(data),np.max(data)+1))
#generate data
a=np.random.randint(1, 9, size=(10, 10))
discrete_matshow(a)
You can use something like this :
SELECT
Books.BookTitle,
Books.Edition,
Books.Year,
Books.Pages,
Books.Rating,
Categories.Category,
Publishers.Publisher,
Writers.LastName
FROM Books
INNER JOIN Categories_Books ON Categories_Books._Books_ISBN = Books._ISBN
INNER JOIN Categories ON Categories._CategoryID = Categories_Books._Categories_Category_ID
INNER JOIN Publishers ON Publishers._Publisherid = Books.PublisherID
INNER JOIN Writers_Books ON Writers_Books._Books_ISBN = Books._ISBN
INNER JOIN Writers ON Writers.Writers_Books = _Writers_WriterID.
I used SSH.Net in a project a while ago and was very happy with it. It also comes with a good documentation with lots of samples on how to use it.
The original package website can be still found here, including the documentation (which currently isn't available on GitHub).
For your case the code would be something like this.
using (var client = new SshClient("hostnameOrIp", "username", "password"))
{
client.Connect();
client.RunCommand("etc/init.d/networking restart");
client.Disconnect();
}
HTML Code
<div class="rCol">
<div id ="prv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div>
</div>
<div class="rCol" style="clear:both;">
<label > Upload Photo : </label>
<input type="file" id="file" name='file' onChange=" return submitForm();">
<input type="hidden" id="filecount" value='0'>
Here is Ajax Code:
function submitForm() {
var fcnt = $('#filecount').val();
var fname = $('#filename').val();
var imgclean = $('#file');
if(fcnt<=5)
{
data = new FormData();
data.append('file', $('#file')[0].files[0]);
var imgname = $('input[type=file]').val();
var size = $('#file')[0].files[0].size;
var ext = imgname.substr( (imgname.lastIndexOf('.') +1) );
if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG')
{
if(size<=1000000)
{
$.ajax({
url: "<?php echo base_url() ?>/upload.php",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' )
{
fcnt = parseInt(fcnt)+1;
$('#filecount').val(fcnt);
var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="<?php echo base_url() ?>/local_cdn/'+data+'"><a href="#" id="rmv_'+fcnt+'" onclick="return removeit('+fcnt+')" class="close-classic"></a></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">';
$('#prv').append(img);
if(fname!=='')
{
fname = fname+','+data;
}else
{
fname = data;
}
$('#filename').val(fname);
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
}
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('SORRY SIZE AND TYPE ISSUE');
}
});
return false;
}//end size
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type
alert('Sorry File size exceeding from 1 Mb');
}
}//end FILETYPE
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
}
}//end filecount
else
{ imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('You Can not Upload more than 6 Photos');
}
}
Here is PHP code :
$filetype = array('jpeg','jpg','png','gif','PNG','JPEG','JPG');
foreach ($_FILES as $key )
{
$name =time().$key['name'];
$path='local_cdn/'.$name;
$file_ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array(strtolower($file_ext), $filetype))
{
if($key['name']<1000000)
{
@move_uploaded_file($key['tmp_name'],$path);
echo $name;
}
else
{
echo "FILE_SIZE_ERROR";
}
}
else
{
echo "FILE_TYPE_ERROR";
}// Its simple code.Its not with proper validation.
Here upload and preview part done.Now if you want to delete and remove image from page and folder both then code is here for deletion. Ajax Part:
function removeit (arg) {
var id = arg;
// GET FILE VALUE
var fname = $('#filename').val();
var fcnt = $('#filecount').val();
// GET FILE VALUE
$('#img_'+id).remove();
$('#rmv_'+id).remove();
$('#img_'+id).css('display','none');
var dname = $('#name_'+id).val();
fcnt = parseInt(fcnt)-1;
$('#filecount').val(fcnt);
var fname = fname.replace(dname, "");
var fname = fname.replace(",,", "");
$('#filename').val(fname);
$.ajax({
url: 'delete.php',
type: 'POST',
data:{'name':dname},
success:function(a){
console.log(a);
}
});
}
Here is PHP part(delete.php):
$path='local_cdn/'.$_POST['name'];
if(@unlink($path))
{
echo "Success";
}
else
{
echo "Failed";
}
You can also just access $s1 like an array, if you only need to access it:
$s1 = "hello world";
echo $s1[0]; // -> h
<xsl:if test="xpath-expression">...</xsl:if>
so for example
<xsl:if test="/html/body">body node exists</xsl:if>
<xsl:if test="not(/html/body)">body node missing</xsl:if>
This is a maven specific problem I think. Maven does not copy the files form /src/main/resources
to the target-test folder. You will have to do this yourself by configuring the resources plugin, if you absolutely want to go this way.
An easier way is to instead put a test specific context definition in the /src/test/resources
directory and load via:
@ContextConfiguration(locations = { "classpath:mycontext.xml" })
Add this line to dependencies in build.gradle
:
dependencies {
compile 'com.android.support:appcompat-v7:18.0.+'
}
Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:
big = 1e5;
tic;
x = rand(big,1);
toc
x = zeros(big,1);
tic;
for ii = 1:big
x(ii) = rand;
end
toc
x = [];
tic;
for ii = 1:big
x(end+1) = rand;
end;
toc
x = [];
tic;
for ii = 1:big
x = [x rand];
end;
toc
Elapsed time is 0.004611 seconds.
Elapsed time is 0.016448 seconds.
Elapsed time is 0.034107 seconds.
Elapsed time is 12.341434 seconds.
I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get
Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.
So I guess the speed advantage only applies to more recent versions of Matlab
There's a very nice and concise answer to your question here. (It struck me as such a nicely straightforward way of explaining it that I want to link it from here.)
A quick way to do the thing now (previous ones haven't worked for me):
sudo wget https://github.com/mikefarah/yq/releases/download/v4.4.1/yq_linux_amd64 -O /usr/bin/yq &&\
sudo chmod +x /usr/bin/yq
Example asd.yaml:
a_list:
- key1: value1
key2: value2
key3: value3
parsing root:
user@vm:~$ yq e '.' asd.yaml
a_list:
- key1: value1
key2: value2
key3: value3
parsing key3:
user@vm:~$ yq e '.a_list[0].key3' asd.yaml
value3
Best way to pass multiple complex object to webapi services is by using tuple other than dynamic, json string, custom class.
HttpClient.PostAsJsonAsync("http://Server/WebService/Controller/ServiceMethod?number=" + number + "&name" + name, Tuple.Create(args1, args2, args3, args4));
[HttpPost]
[Route("ServiceMethod")]
[ResponseType(typeof(void))]
public IHttpActionResult ServiceMethod(int number, string name, Tuple<Class1, Class2, Class3, Class4> args)
{
Class1 c1 = (Class1)args.Item1;
Class2 c2 = (Class2)args.Item2;
Class3 c3 = (Class3)args.Item3;
Class4 c4 = (Class4)args.Item4;
/* do your actions */
return Ok();
}
No need to serialize and deserialize passing object while using tuple. If you want to send more than seven complex object create internal tuple object for last tuple argument.
Quite and old question but I had the same issue today. Cleanest solution I found is to use the concept of currying.
The code for that:
someObj.addEventListener('click', some_function(someVar));
var some_function = function(someVar) {
return function curried_func(e) {
// do something here
}
}
By naming the curried function it allows you to call Object.removeEventListener to unregister the eventListener at a later execution time.