This worked for me. Go to Project->Propertied->Target Frawork->Change frame work like 3.5 to 4.0
The following code
#menu li{
list-style-type: none;
}
_x000D_
<ul id="menu">
<li>Root node 1</li>
<li>Root node 2</li>
</ul>
_x000D_
will produce this output:
step 1 : make a web service on your server
step 2 : make your application make a call to the web service and receive result sets
About looping through a hash:
$Q = @{"ONE"="1";"TWO"="2";"THREE"="3"}
$Q.GETENUMERATOR() | % { $_.VALUE }
1
3
2
$Q.GETENUMERATOR() | % { $_.key }
ONE
THREE
TWO
Alright so after hours of googling and failed attempts at solving this including many of the suggestions above, I found a solution I tried on a whim and worked for me.
Attempt to install the program, then, when it gets "stuck", cancel it, but don't uninstall.
Then, go to the control panel, go to programs, go and attempt to uninstall it, select "Repair" instead of Uninstall.
"Repairing" Visual Studio appears to have completely worked and was very quick, under 5 minutes and everything seems to work fine.
Update
Based on Manipulating the browser history, passing the empty string as second parameter of pushState
method (aka title) should be safe against future changes to the method, so it's better to use pushState
like this:
history.pushState(null, '', '/en/step2');
You can read more about that in mentioned article
Original Answer
Use history.pushState
like this:
history.pushState(null, null, '/en/step2');
Update 2 to answer Idan Dagan's comment:
Why not using
history.replaceState()
?
From MDN
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one
That means if you use replaceState
, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState
doesn't add new entry to history) and it's not recommended and provide bad UX.
Update 3 to add window.onpopstate
So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState
, you can detect the back/forward button navigation by using window.onpopstate
like this:
window.onpopstate = function(e) {
// ...
};
As the first argument of pushState
is an object, if you passed an object
instead of null
, you can access that object in onpopstate
which is very handy, here is how:
window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};
Update 4 to add Reading the current state:
When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate
event using the history.state
property like this:
console.log(history.state);
Bonus: Use following to check history.pushState
support:
if (history.pushState) {
// \o/
}
I keep having this error with WatchKit over and over again and it seems to be when there is a user interface element that isn't tied to an outlet in code. I guess this is required in WatchKit.
class InterfaceController: WKInterfaceController {
@IBOutlet weak var table: WKInterfaceTable!
}
Important note: just connect the outermost element. For instance if you try to also give a connection for something within the table like a label inside a row you will get a compiler error saying the outlet is invalid and cannot be connected to repeating content.
Just another good looking table. I added "table-hover" class because it gives a nice hovering effect.
<h3>NATO Phonetic Alphabet</h3>
<table class="table table-striped table-bordered table-condensed table-hover">
<thead>
<tr>
<th>Letter</th>
<th>Phonetic Letter</th>
</tr>
</thead>
<tr>
<th>A</th>
<th>Alpha</th>
</tr>
<tr>
<td>B</td>
<td>Bravo</td>
</tr>
<tr>
<td>C</td>
<td>Charlie</td>
</tr>
</table>
SELECT LAST(row_name) FROM table_name
This should be noticed if you are new to java, every object has inherited from Object
protected native Object clone() throws CloneNotSupportedException;
While I enjoy using dplyr for interactive use, I find it extraordinarily tricky to do this using dplyr because you have to go through hoops to use lazyeval::interp(), setNames, etc. workarounds.
Here is a simpler version using base R, in which it seems more intuitive, to me at least, to put the loop inside the function, and which extends @MrFlicks's solution.
multipetal <- function(df, n) {
for (i in 1:n){
varname <- paste("petal", i , sep=".")
df[[varname]] <- with(df, Petal.Width * i)
}
df
}
multipetal(iris, 3)
A workaround for this would be to have a variable get the current working directory. Then you can cd out of it to do whatever, then when you need it, you can cd back in.
i.e.
oldpath=`pwd` #do whatever your script does ... ... ... # go back to the dir you wanted to pushd cd $oldpath
Suppose you want to insert a particular line of text (not an empty line):
@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1
@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /p L=
IF %%i==%insertat% ECHO(!TL!
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
I just had to share 'mine'.
Although conceptually the same as Asaph's answer (benefiting from the same cross-browser compatibility, even IE6), it is a lot smaller and comes in handy when size is at a premium and/or when it is not needed so often.
function childOf(/*child node*/c, /*parent node*/p){ //returns boolean
while((c=c.parentNode)&&c!==p);
return !!c;
}
..or as one-liner (just 64 chars!):
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
and jsfiddle here.
Usage:
childOf(child, parent)
returns boolean true
|false
.
Explanation:
while
evaluates as long as the while-condition evaluates to true
.
The &&
(AND) operator returns this boolean true/false after evaluating the left-hand side and the right-hand side, but only if the left-hand side was true (left-hand && right-hand
).
The left-hand side (of &&
) is: (c=c.parentNode)
.
This will first assign the parentNode
of c
to c
and then the AND operator will evaluate the resulting c
as a boolean.
Since parentNode
returns null
if there is no parent left and null
is converted to false
, the while-loop will correctly stop when there are no more parents.
The right-hand side (of &&
) is: c!==p
.
The !==
comparison operator is 'not exactly equal to'. So if the child's parent isn't the parent (you specified) it evaluates to true
, but if the child's parent is the parent then it evaluates to false
.
So if c!==p
evaluates to false, then the &&
operator returns false
as the while-condition and the while-loop stops. (Note there is no need for a while-body and the closing ;
semicolon is required.)
So when the while-loop ends, c
is either a node (not null
) when it found a parent OR it is null
(when the loop ran through to the end without finding a match).
Thus we simply return
that fact (converted as boolean value, instead of the node) with: return !!c;
: the !
(NOT
operator) inverts a boolean value (true
becomes false
and vice-versa).
!c
converts c
(node or null) to a boolean before it can invert that value. So adding a second !
(!!c
) converts this false back to true (which is why a double !!
is often used to 'convert anything to boolean').
Extra:
The function's body/payload is so small that, depending on case (like when it is not used often and appears just once in the code), one could even omit the function (wrapping) and just use the while-loop:
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
c=a; while((c=c.parentNode)&&c!==b); //c=!!c;
if(!!c){ //`if(c)` if `c=!!c;` was used after while-loop above
//do stuff
}
instead of:
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
c=childOf(a, b);
if(c){
//do stuff
}
No need for a custom class. This is all that is needed:
return new JsonResult { Data = Result, MaxJsonLength = Int32.MaxValue };
where Result
is that data you wish to serialize.
In case anyone else ends up as lost as I was... My issues were NOT due to CORS (I have full control of the server(s) and CORS was configured correctly!).
My issue was because I am using Android platform level 28 which disables cleartext network communications by default and I was trying to develop the app which points at my laptop's IP (which is running the API server). The API base URL is something like http://[LAPTOP_IP]:8081. Since it's not https, android webview completely blocks the network xfer between the phone/emulator and the server on my laptop. In order to fix this:
New file in project: resources/android/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<!-- Set application-wide security config -->
<base-config cleartextTrafficPermitted="true"/>
</network-security-config>
NOTE: This should be used carefully as it will allow all cleartext from your app (nothing forced to use https). You can restrict it further if you wish.
<platform name="android">
...
<edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
<application android:networkSecurityConfig="@xml/network_security_config" />
</edit-config>
<resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" />
....
</platform>
That's it! From there I rebuilt the APK and the app was now able to communicate from both the emulator and phone.
More info on network sec: https://developer.android.com/training/articles/security-config.html#CleartextTrafficPermitted
If you installed OpenSSL on Windows together with Git, then add this to your command:
-config "C:\Program Files\Git\usr\ssl\openssl.cnf"
First, you should add from the XML file add android:imeOptions field and change its value to actionUnspecified|actionGo as below
<android.support.design.widget.TextInputEditText
android:id="@+id/edit_text_id"
android:layout_width="fill_parent"
android:layout_height="@dimen/edit_text_height"
android:imeOptions="actionUnspecified|actionGo"
/>
Then In the java class add a setOnEditorActionListener and add InputMethodManager as below
enterOrderNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
return true;
}
return false;
}
});
I'm not sure, what you mean as the 'mobile width'. But in each case, the CSS @media
can be used for hiding elements in the screen width basis. See some example:
<div id="my-content"></div>
...and:
@media screen and (min-width: 0px) and (max-width: 400px) {
#my-content { display: block; } /* show it on small screens */
}
@media screen and (min-width: 401px) and (max-width: 1024px) {
#my-content { display: none; } /* hide it elsewhere */
}
Some truly mobile detection is kind of hard programming and rather difficult. Eventually see the: http://detectmobilebrowsers.com/ or other similar sources.
Thunderbird supports html-body
: mailto:[email protected]?subject=Me&html-body=<b>ME</b>
REST is very abstract. It helps to have some good, simple, real-world examples.
Take for example all major social media apps -- Tumblr, Instagram, Facebook, and Twitter. They all have a forever-scrolling view where the farther you scroll down, the more content you see, further and further back in time. However, we've all experienced that moment where you lose where you were scrolled to, and the app resets you back to the top. Like if you quit the app, then when you reopen it, you're back at the top again.
The reason why, is because the server did not store your session state. Sadly, your scroll position was just stored in RAM on the client.
Fortunately you don't have to log back in when you reconnect, but that's only because your client-side also stored login certificate has not expired. Delete and reinstall the app, and you're going to have to log back in, because the server did not associate your IP address with your session.
You don't have a login session on the server, because they abide by REST.
Now the above examples don't involve a web browser at all, but on the back end, the apps are communicating via HTTPS with their host servers. My point is that REST does not have to involve cookies and browsers etc. There are various means of storing client-side session state.
But lets talk about web browsers for a second, because that brings up another major advantage of REST that nobody here is talking about.
If the server tried to store session state, how is it supposed to identify each individual client?
It could not use their IP address, because many people could be using that same address on a shared router. So how, then?
It can't use MAC address for many reasons, not the least of which because you can be logged into multiple different Facebook accounts simultaneously on different browsers plus the app. One browser can easily pretend to be another one, and MAC addresses are just as easy to spoof.
If the server has to store some client-side state to identify you, it has to store it in RAM longer than just the time it takes to process your requests, or else it has to cache that data. Servers have limited amounts of RAM and cache, not to mention processor speed. Server-side state adds to all three, exponentially. Plus if the server is going to store any state about your sessions then it has to store it separately for each browser and app you're currently logged in with, and also for each different device you use.
So... I hope that you see now why REST is so important for scalability. I hope you can start to see why server-side session state is to server scalability what welded-on anvils are to car acceleration.
Where people get confused is by thinking that "state" refers to, like, information stored in a database. No, it refers to any information that needs to be in the RAM of the server when you're using it.
<h1><a href="/" title="Some title">Name</a></h1>
h1 a{
width: {logo width};
height: {logo height};
display:block;
text-indent:-9999px;
background:url({ logo url});
}
Same problem with Chrome : I had in my html page the following code :
<body>
...
<script src="http://myserver/lib/load.js"></script>
...
</body>
But the load.js
was always in status pending
when looking in the Network pannel.
I found a workaround using asynchronous load of load.js
:
<body>
...
<script>
setTimeout(function(){
var head, script;
head = document.getElementsByTagName("head")[0];
script = document.createElement("script");
script.src = "http://myserver/lib/load.js";
head.appendChild(script);
}, 1);
</script>
...
</body>
Now its working fine.
* {
margin: 0;
}
html, body {
height: 90%;
}
.content {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto ;
}
You should keep a watch on your scope.
Here is how you can do it:
<layout layoutId="myScope"></layout>
Your directive should look like
app.directive('layout', function($http, $compile){
return {
restrict: 'E',
scope: {
layoutId: "=layoutId"
},
link: function(scope, element, attributes) {
var layoutName = (angular.isDefined(attributes.name)) ? attributes.name : 'Default';
$http.get(scope.constants.pathLayouts + layoutName + '.html')
.success(function(layout){
var regexp = /^([\s\S]*?){{content}}([\s\S]*)$/g;
var result = regexp.exec(layout);
var templateWithLayout = result[1] + element.html() + result[2];
element.html($compile(templateWithLayout)(scope));
});
}
}
$scope.$watch('myScope',function(){
//Do Whatever you want
},true)
Similarly you can models in your directive, so if model updates automatically your watch method will update your directive.
Try rewriting your success handler to:
success : handleData
The success property of the ajax method only requires a reference to a function.
In your handleData function you can take up to 3 parameters:
object data
string textStatus
jqXHR jqXHR
jQuery 1.4 also includes a .delay( duration, [ queueName ] ) method if you only need it to trigger once and have already started using that version.
$('#foo').slideUp(300).delay(800).fadeIn(400);
Ooops....my mistake you were looking for an event to continue triggering. I'll leave this here, someone may find it helpful.
I believe it's simply for the sake of clarity, we do not want to clutter the language with too many different symbols. Also a tuple
comprehension is never necessary, a list can just be used instead with negligible speed differences, unlike a dict comprehension as opposed to a list comprehension.
I just tried to call a function in terminal rather then MySQL Query Browser and it works. So, it looks like I'm doing something wrong in that program...
I don't know what since I called some procedures before successfully (but there where no out parameters)...
For this one I had entered
CALL my_sqrt(4,@out_value);
SELECT @out_value;
And it results with an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @out_value' at line 2
Strangely, if I write just:
CALL my_sqrt(4,@out_value);
The result message is: "Query canceled"
I guess, for now I will use only terminal...
Here's an example of how to solve the same problem without having to map the fields manually:
from sqlalchemy import Column, ForeignKey, Integer, String, Date, DateTime, text, create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.attributes import InstrumentedAttribute
engine = create_engine('postgres://postgres@localhost:5432/database')
session = sessionmaker()
session.configure(bind=engine)
Base = declarative_base()
class Media(Base):
__tablename__ = 'media'
id = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
slug = Column(String, nullable=False)
type = Column(String, nullable=False)
def update(self):
s = session()
mapped_values = {}
for item in Media.__dict__.iteritems():
field_name = item[0]
field_type = item[1]
is_column = isinstance(field_type, InstrumentedAttribute)
if is_column:
mapped_values[field_name] = getattr(self, field_name)
s.query(Media).filter(Media.id == self.id).update(mapped_values)
s.commit()
So to update a Media instance, you can do something like this:
media = Media(id=123, title="Titular Line", slug="titular-line", type="movie")
media.update()
Writing an extension method is the most efficient way in my opinion
public static string PeekBody(this HttpRequest request)
{
try
{
request.EnableBuffering();
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
request.Body.Read(buffer, 0, buffer.Length);
return Encoding.UTF8.GetString(buffer);
}
finally
{
request.Body.Position = 0;
}
}
You can use Request.Body.Peeker Nuget Package as well (source code)
//Return string
var request = HttpContext.Request.PeekBody();
//Return in expected type
LoginRequest request = HttpContext.Request.PeekBody<LoginRequest>();
//Return in expected type asynchronously
LoginRequest request = await HttpContext.Request.PeekBodyAsync<LoginRequest>();
Here this the code which slides down the sub menu on hover, and let you redirect to a page if you click on it.
How: strip out class="dropdown-toggle" data-toggle="dropdown"
from a tag, and add css.
Here is the demo at jsfiddle. For demo, please adjust jsfiddle's splitter to see the dropdown due to Bootstrap CSS. jsfiddle won't let you redirect to a new page.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript' src="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
<style type='text/css'>
ul.nav li.dropdown:hover ul.dropdown-menu {
display: block;
}
</style>
</head>
<body>
<nav class="navbar navbar-fixed-top admin-menu" role="navigation">
<div class="navbar-header">...</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown"><a href="http://stackoverflow.com/">Stack Overflow <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="/page2">Page2</a>
</li>
</ul>
</li>
<li><a href="#">I DO WORK</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</nav>
</body>
</html>
select LAST_LOAD_TIME, ELAPSED_TIME, MODULE, SQL_TEXT elapsed from v$sql
order by LAST_LOAD_TIME desc
More complicated example (don't forget to delete or to substitute PATTERN
):
select * from (
select LAST_LOAD_TIME, to_char(ELAPSED_TIME/1000, '999,999,999.000') || ' ms' as TIME,
MODULE, SQL_TEXT from SYS."V_\$SQL"
where SQL_TEXT like '%PATTERN%'
order by LAST_LOAD_TIME desc
) where ROWNUM <= 5;
The following (C# implementation, but similar in Java) allows you to determine if there is an alert without exceptions and without creating the WebDriverWait
object.
boolean isDialogPresent(WebDriver driver) {
IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
return (alert != null);
}
1) Launch Ubuntu Instance on EC2.
2) Open SSH Port in instance security.
3) Do SSH to instance.
4) Execute:
sudo apt-get update sudo apt-get upgrade
5) Because you will be connecting from Windows Remote Desktop, edit the sshd_config file on your Linux instance to allow password authentication.
sudo vim /etc/ssh/sshd_config
6) Change PasswordAuthentication to yes from no, then save and exit.
7) Restart the SSH daemon to make this change take effect.
sudo /etc/init.d/ssh restart
8) Temporarily gain root privileges and change the password for the ubuntu user to a complex password to enhance security. Press the Enter key after typing the command passwd ubuntu, and you will be prompted to enter the new password twice.
sudo –i
passwd ubuntu
9) Switch back to the ubuntu user account and cd to the ubuntu home directory.
su ubuntu
cd
10) Install Ubuntu desktop functionality on your Linux instance, the last command can take up to 15 minutes to complete.
export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get update
sudo -E apt-get install -y ubuntu-desktop
11) Install xrdp
sudo apt-get install xfce4
sudo apt-get install xfce4 xfce4-goodies
12) Make xfce4 the default window manager for RDP connections.
echo xfce4-session > ~/.xsession
13) Copy .xsession to the /etc/skel folder so that xfce4 is set as the default window manager for any new user accounts that are created.
sudo cp /home/ubuntu/.xsession /etc/skel
14) Open the xrdp.ini file to allow changing of the host port you will connect to.
sudo vim /etc/xrdp/xrdp.ini
(xrdp is not installed till now. First Install the xrdp with sudo apt-get install xrdp then edit the above mentioned file)
15) Look for the section [xrdp1] and change the following text (then save and exit [:wq]).
port=-1
- to -
port=ask-1
16) Restart xrdp.
sudo service xrdp restart
17) On Windows, open the Remote Desktop Connection client, paste the fully qualified name of your Amazon EC2 instance for the Computer, and then click Connect.
18) When prompted to Login to xrdp, ensure that the sesman-Xvnc module is selected, and enter the username ubuntu with the new password that you created in step 8. When you start a session, the port number is -1.
19) When the system connects, several status messages are displayed on the Connection Log screen. Pay close attention to these status messages and make note of the VNC port number displayed. If you want to return to a session later, specify this number in the port field of the xrdp login dialog box.
See more details:
https://aws.amazon.com/premiumsupport/knowledge-center/connect-to-linux-desktop-from-windows/
http://c-nergy.be/blog/?p=5305
After 2.10, to solve the scope problem, you can do something like this:
{% set count = namespace(value=0) %}
{% for i in p %}
{{ count.value }}
{% set count.value = count.value + 1 %}
{% endfor %}
Based on cletus's answer you may create new extension.
public static class StringExtensions
{
public static bool IsAlphaNumeric(this string str)
{
if (string.IsNullOrEmpty(str))
return false;
Regex r = new Regex("^[a-zA-Z0-9]*$");
return r.IsMatch(str);
}
}
To print each element of a given list using a single line code
for i in result: print(i)
you can try just add
network_mode: "host"
example :
version: '2'
services:
feedx:
build: web
ports:
- "127.0.0.1:8000:8000"
network_mode: "host"
list option available
network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"
Instead of Windows PowerShell
, find the item in the Start Menu called SharePoint 2013 Management Shell
:
Safari 7.0.5 still does not support notification for validation of input fields.
To overcome it is possible to write fallback script like this: http://codepen.io/ashblue/pen/KyvmA
To see what HTML5 / CSS3 features are supported by browsers check: http://caniuse.com/form-validation
function hasHtml5Validation () {
//Check if validation supported && not safari
return (typeof document.createElement('input').checkValidity === 'function') &&
!(navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0);
}
$('form').submit(function(){
if(!hasHtml5Validation())
{
var isValid = true;
var $inputs = $(this).find('[required]');
$inputs.each(function(){
var $input = $(this);
$input.removeClass('invalid');
if(!$.trim($input.val()).length)
{
isValid = false;
$input.addClass('invalid');
}
});
if(!isValid)
{
return false;
}
}
});
SASS / LESS:
input, select, textarea {
@include appearance(none);
border-radius: 0px;
&.invalid {
border-color: red !important;
}
}
If you want to avoid error cases, don't allow wc -l
to see files with newlines (which it will count as 2+ files)
e.g. Consider a case where we have a single file with a single EOL character in it
> mkdir emptydir && cd emptydir
> touch $'file with EOL(\n) character in it'
> find -type f
./file with EOL(?) character in it
> find -type f | wc -l
2
Since at least gnu wc
does not appear to have an option to read/count a null terminated list (except from a file), the easiest solution would just be to not pass it filenames, but a static output each time a file is found, e.g. in the same directory as above
> find -type f -exec printf '\n' \; | wc -l
1
Or if your find
supports it
> find -type f -printf '\n' | wc -l
1
List only accepts one type parameter. The closest you'll get with List is:
var list = new List<Tuple<string, int>>();
list.Add(Tuple.Create("hello", 1));
When I think of dummy variables I think of using them in the context of OLS regression, and I would do something like this:
import numpy as np
import pandas as pd
import statsmodels.api as sm
my_data = np.array([[5, 'a', 1],
[3, 'b', 3],
[1, 'b', 2],
[3, 'a', 1],
[4, 'b', 2],
[7, 'c', 1],
[7, 'c', 1]])
df = pd.DataFrame(data=my_data, columns=['y', 'dummy', 'x'])
just_dummies = pd.get_dummies(df['dummy'])
step_1 = pd.concat([df, just_dummies], axis=1)
step_1.drop(['dummy', 'c'], inplace=True, axis=1)
# to run the regression we want to get rid of the strings 'a', 'b', 'c' (obviously)
# and we want to get rid of one dummy variable to avoid the dummy variable trap
# arbitrarily chose "c", coefficients on "a" an "b" would show effect of "a" and "b"
# relative to "c"
step_1 = step_1.applymap(np.int)
result = sm.OLS(step_1['y'], sm.add_constant(step_1[['x', 'a', 'b']])).fit()
print result.summary()
Clearing the value of 0th index of input worked for me. Please try the below code, hope this will work (AngularJs).
scope.onClick = function() {
input[0].value = "";
input.click();
};
Oh lord, don't do it this way. HTC files are never a good idea for performance and clarity reasons, and you're using too many vendor-specific parameters for something that can easily be done cross-browser all the way back to IE6.
Apply a background image to your input field with the rounded corners and make the field's background colour transparent with border:none applied instead.
java.sql.Time timeValue = new java.sql.Time(formatter.parse(fajr_prayertime).getTime());
Try this which uses globs rather than regular expressions so it will only pick out the file names that end in .dbf
filenames <- Sys.glob("*.dbf")
I find the fastest loop is a reverse while loop, e.g:
var i = myArray.length;
while(i--){
// Do something
}
Based on Ryan's solution, if you also have lists and nested dictionaries:
For Python 2:
def remove_empty_from_dict(d):
if type(d) is dict:
return dict((k, remove_empty_from_dict(v)) for k, v in d.iteritems() if v and remove_empty_from_dict(v))
elif type(d) is list:
return [remove_empty_from_dict(v) for v in d if v and remove_empty_from_dict(v)]
else:
return d
For Python 3:
def remove_empty_from_dict(d):
if type(d) is dict:
return dict((k, remove_empty_from_dict(v)) for k, v in d.items() if v and remove_empty_from_dict(v))
elif type(d) is list:
return [remove_empty_from_dict(v) for v in d if v and remove_empty_from_dict(v)]
else:
return d
According to docs:
Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.
Update: This phrase in "New Features in Xcode 7" made me to think for a long time that Bitcode is needed for Slicing to reduce app size:
When you archive for submission to the App Store, Xcode will compile your app into an intermediate representation. The App Store will then compile the bitcode down into the 64 or 32 bit executables as necessary.
However that's not true, Bitcode and Slicing work independently: Slicing is about reducing app size and generating app bundle variants, and Bitcode is about certain binary optimizations. I've verified this by checking included architectures in executables of non-bitcode apps and founding that they only include necessary ones.
Bitcode allows other App Thinning component called Slicing to generate app bundle variants with particular executables for particular architectures, e.g. iPhone 5S variant will include only arm64 executable, iPad Mini armv7 and so on.
For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS and tvOS apps, bitcode is required.
From Xcode 7 reference:
Activating this setting indicates that the target or project should generate bitcode during compilation for platforms and architectures which support it. For Archive builds, bitcode will be generated in the linked binary for submission to the app store. For other builds, the compiler and linker will check whether the code complies with the requirements for bitcode generation, but will not generate actual bitcode.
Here's a couple of links that will help in deeper understanding of Bitcode:
Using Helper class you can access SQLite Database and can perform the various operations on it by overriding the onCreate() and onUpgrade() methods.
http://technologyguid.com/android-sqlite-database-app-example/
I'm using Xcode 8.3.3 and Xcode 9.2. The solution for me was to switch my default Xcode from 8 to 9 using Xcode Select:
$ xcode-select --print-path
$ sudo xcode-select -switch /Applications/Xcode-9.2.app
Edit: Actually what seemed to help here was that Xcode 9.2 used the derived data from Xcode 8.3.3. Not a solution but at least it allows me to move forward with my work.
"Session" is the term used to refer to a user's time browsing a web site. It's meant to represent the time between their first arrival at a page in the site until the time they stop using the site. In practice, it's impossible to know when the user is done with the site. In most servers there's a timeout that automatically ends a session unless another page is requested by the same user.
The first time a user connects some kind of session ID is created (how it's done depends on the web server software and the type of authentication/login you're using on the site). Like cookies, this usually doesn't get sent in the URL anymore because it's a security problem. Instead it's stored along with a bunch of other stuff that collectively is also referred to as the session. Session variables are like cookies - they're name-value pairs sent along with a request for a page, and returned with the page from the server - but their names are defined in a web standard.
Some session variables are passed as HTTP headers. They're passed back and forth behind the scenes of every page browse so they don't show up in the browser and tell everybody something that may be private. Among them are the USER_AGENT, or type of browser requesting the page, the REFERRER or the page that linked to the page being requested, etc. Some web server software adds their own headers or transfer additional session data specific to the server software. But the standard ones are pretty well documented.
Hope that helps.
An extension of the answer from Keith Hill (to account for whitespace):
$str = " "
if ($str -and $version.Trim()) { Write-Host "Not Empty" } else { Write-Host "Empty" }
This returns "Empty" for nulls, empty strings, and strings with whitespace, and "Not Empty" for everything else.
The solution below works very well for me.
Only 4 lines and works with most (all?) characters.
:Trim
SetLocal EnableDelayedExpansion
set Params=%*
for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b
exit /b
@echo off
call :Test1 & call :Test2 & call :Test3 & exit /b
:Trim
SetLocal EnableDelayedExpansion
set Params=%*
for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b
exit /b
:Test1
set Value= a b c
set Expected=a b c
call :Trim Actual %Value%
if "%Expected%" == "%Actual%" (echo Test1 passed) else (echo Test1 failed)
exit /b
:Test2
SetLocal EnableDelayedExpansion
set Value= a \ / : * ? " ' < > | ` ~ @ # $ [ ] & ( ) + - _ = z
set Expected=a \ / : * ? " ' < > | ` ~ @ # $ [ ] & ( ) + - _ = z
call :Trim Actual !Value!
if !Expected! == !Actual! (echo Test2 passed) else (echo Test2 failed)
exit /b
:Test3
set /p Value="Enter string to trim: " %=%
echo Before: [%Value%]
call :Trim Value %Value%
echo After : [%Value%]
exit /b
Wait and notify method always called on object so whether it may be Thread object or simple object (which does not extends Thread class) Given Example will clear your all the doubts.
I have called wait and notify on class ObjB and that is the Thread class so we can say that wait and notify are called on any object.
public class ThreadA {
public static void main(String[] args){
ObjB b = new ObjB();
Threadc c = new Threadc(b);
ThreadD d = new ThreadD(b);
d.setPriority(5);
c.setPriority(1);
d.start();
c.start();
}
}
class ObjB {
int total;
int count(){
for(int i=0; i<100 ; i++){
total += i;
}
return total;
}}
class Threadc extends Thread{
ObjB b;
Threadc(ObjB objB){
b= objB;
}
int total;
@Override
public void run(){
System.out.print("Thread C run method");
synchronized(b){
total = b.count();
System.out.print("Thread C notified called ");
b.notify();
}
}
}
class ThreadD extends Thread{
ObjB b;
ThreadD(ObjB objB){
b= objB;
}
int total;
@Override
public void run(){
System.out.print("Thread D run method");
synchronized(b){
System.out.println("Waiting for b to complete...");
try {
b.wait();
System.out.print("Thread C B value is" + b.total);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
EDIT: based on your comment and assuming that this
is the element that is cloned.
$(this).clone()
.attr( 'id', this.id + '_' + new_id )
.attr( 'name', this.name + '_' + new_id )
.val( 'test' )
.appendTo('#someElement');
Full Example
<script type="text/javascript">
var new_id = 0;
$(document).ready( function() {
$('#container > input[type=button]').click( function() {
var oldinp = $('input#inp')[0];
var newinp = $(oldinp).clone()
.attr('id',oldinp.id + new_id )
.attr('name',oldinp.name + new_id )
.val('test')
.appendTo($('#container'));
$('#container').append('<br>');
new_id++;
});
});
</script>
<div id="container">
<input type="button" value="Clone" /><br/>
<input id="inp" name="inp" type="text" value="hmmm" /><br/>
</div>
Another solution to handle this case is creating a customized Seekbar, to get ride of converting the real value and SeekBar progress every time:
import android.content.Context
import android.util.AttributeSet
import android.widget.SeekBar
//
// Require SeekBar with range [Min, Max] and INCREMENT value,
// However, Android Seekbar starts from 0 and increment is 1 by default, Android supports min attr on API 26,
// To make a increment & range Seekbar, we can do the following conversion:
//
// seekbar.setMax((Max - Min) / Increment)
// seekbar.setProgress((actualValue - Min) / Increment)
// seekbar.getProgress = Min + (progress * Increment)
//
// The RangeSeekBar is responsible for handling all these logic inside the class.
data class Range(val min: Int, val max: Int, private val defaultIncrement: Int) {
val increment = if ((max - min) < defaultIncrement) 1 else defaultIncrement
}
internal fun Range.toSeekbarMaximum(): Int = (max - min) / increment
class RangeSeekBar: SeekBar, SeekBar.OnSeekBarChangeListener {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
var range: Range = Range(0, 100, 1)
set(value) {
field = value
max = value.toSeekbarMaximum()
}
var value: Int = 0
get() = range.min + progress * range.increment
set(value) {
progress = (value - range.min) / range.increment
field = value
}
var onSeekBarChangeListenerDelegate: OnSeekBarChangeListener? = this
override fun setOnSeekBarChangeListener(l: OnSeekBarChangeListener?) {
onSeekBarChangeListenerDelegate = l
super.setOnSeekBarChangeListener(this)
}
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
onSeekBarChangeListenerDelegate?.onProgressChanged(seekBar, value, fromUser)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
onSeekBarChangeListenerDelegate?.onStartTrackingTouch(seekBar)
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
onSeekBarChangeListenerDelegate?.onStopTrackingTouch(seekBar)
}
}
Then in your fragment,
// init
range_seekbar.range = Range(10, 110, 10)
range_seekbar.value = 20
// observe value changes
range_seekbar.userChanges().skipInitialValue().subscribe {
println("current value=$it")
}
Keywords: Kotlin, range SeekBar, Rx
Your data.frame mat
is rectangular (n_rows!= n_cols).
Therefore, you cannot make a data.frame
out of the column- and rownames, because each column in a data.frame must be the same length.
Maybe this suffices your needs:
require(reshape2)
mat$id <- rownames(mat)
melt(mat)
Your working tree is what is actually in the files that you are currently working on.
HEAD
is a pointer to the branch or commit that you last checked out, and which will be the parent of a new commit if you make it. For instance, if you're on the master
branch, then HEAD
will point to master
, and when you commit, that new commit will be a descendent of the revision that master
pointed to, and master
will be updated to point to the new commit.
The index is a staging area where the new commit is prepared. Essentially, the contents of the index are what will go into the new commit (though if you do git commit -a
, this will automatically add all changes to files that Git knows about to the index before committing, so it will commit the current contents of your working tree). git add
will add or update files from the working tree into your index.
Just try this line:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
after:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
items is one attribute of dict object.maybe you can try
qs[0].items()
A String is an immutable type. This means that whenever you start concatenating strings with each other you're creating new strings each time. If you do so many times you end up with a lot of heap overhead and the risk of running out of memory.
A StringBuilder instance is used to be able to append strings to the same instance, creating a string when you call the ToString method on it.
Due to the overhead of instantiating a StringBuilder object it's said by Microsoft that it's useful to use when you have more than 5-10 string concatenations.
For sample code I suggest you take a look here:
If you are using this for Angular, then export a function via a named export. Such as:
function someFunc(){}
export { someFunc as someFuncName }
otherwise, Angular will complain that object is not a function.
In:
for i in range(c/10):
You're creating a float as a result - to fix this use the int division operator:
for i in range(c // 10):
There are two types of coding.
(1) hard-coding (2) soft-coding
Hard-coding. Assign values to program during writing source code and make executable file of program.Now, it is very difficult process to change or modify the program source code values. like in block-chain technology, genesis block is hard-code that cannot changed or modified.
Soft-coding: it is process of inserting values from external source into computer program. like insert values through keyboard, command line interface. Soft-coding considered as good programming practice because developers can easily modify programs.
If you'd decide for a solution acting "in place" you could take a look at this one:
>>> d = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]
>>> [dt.update({k: int(v)}) for dt in d for k, v in dt.iteritems()]
[None, None, None, None, None, None]
>>> d
[{'a': 1, 'c': 3, 'b': 2}, {'e': 5, 'd': 4, 'f': 6}]
Btw, key order is not preserved because that's the way standard dictionaries work, ie without the concept of order.
After done trying everything that I found on this issue, in eclipse,
I selected my project --> right click --> Run as --> Maven generate-sources
Then I re-ran my TestNG project and it ran perfectly fine without any issues.Hope that helps :)
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'); });
Try the click library written by the Mozart of Python, Armin Ronacher.
$ pip install click # both 2 and 3 compatible
To create a simple progress bar:
import click
with click.progressbar(range(1000000)) as bar:
for i in bar:
pass
This is what it looks like:
# [###-------------------------------] 9% 00:01:14
Customize to your hearts content:
import click, sys
with click.progressbar(range(100000), file=sys.stderr, show_pos=True, width=70, bar_template='(_(_)=%(bar)sD(_(_| %(info)s', fill_char='=', empty_char=' ') as bar:
for i in bar:
pass
Custom look:
(_(_)===================================D(_(_| 100000/100000 00:00:02
There are even more options, see the API docs:
click.progressbar(iterable=None, length=None, label=None, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None)
try this:
$('form').submit(function(){
// this function will be raised when submit button is clicked.
// perform submit operations here
});
This should do the trick:
pw_bytes.decode("utf-8")
<a href="#anchor">Click me!</a>
<div style="margin-top: -100px; padding-top: 100px;" id="anchor"></div>
<p>I should be 100px below where I currently am!</p>
I think you should use python wheels for distribution instead of egg now.
Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.
For small index values you can implement
my_list.get(index, default)
as
(my_list + [default] * (index + 1))[index]
If you know in advance what index is then this can be simplified, for example if you knew it was 1 then you could do
(my_list + [default, default])[index]
Because lists are forward packed the only fail case we need to worry about is running off the end of the list. This approach pads the end of the list with enough defaults to guarantee that index is covered.
you also use preg_replace_callback
function . and this function is identical to its sibling preg_replace
except for it can take a callback function which gives you more control on how you manipulate your output.
$str = "this is a string";
echo preg_replace_callback(
'/\s+/',
function ($matches) {
return "";
},
$str
);
Yes, I would use explode or you could use:
preg_split
Which is the advised method with PHP 6. preg_split Documentation
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
When you want to edit something in Angular you need to insert an ngModel in your html
try this in your sample:
<input type="text" name="abc" class="color" ng-model="myStyle.color">
You don't need to watch the change at all!
This is by far the best solution I have been able to find on the internet.
I've used the following link https://gist.github.com/mhasby/026f02b33fcc4207b302a60645f6e217,
but it had a single error which I fixed and then it works like a charm.
Here's my code. You can easily use it as it is an independent java class.
public class CopyAssets {
public static void copyAssets(Context context) {
AssetManager assetManager = context.getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
out = new FileOutputStream(Environment.getExternalStorageDirectory()+"/www/resources/" + filename);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
in = null;
} catch (IOException e) {
}
}
if (out != null) {
try {
out.flush();
out.close();
out = null;
} catch (IOException e) {
}
}
}
}
}
public static void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}}
As you can see, just create an instance of CopyAssets
in your java class which has an activity. Now this part is important, as far as my testing and researching on the internet, You cannot use AssetManager if the class has no activity
. It has something to do with the context of the java class.
Now, the c.copyAssets(getApplicationContext())
is an easy way to access the method, where c
is and instance of CopyAssets
class.
As per my requirement, I allowed the program to copy all my resource files inside the asset
folder to the /www/resources/
of my internal directory.
You can easily find out the part where you need to make changes to the directory as per your use.
Feel free to ping me if you need any help.
my problem was that we had this set in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true" />
this means that when debugging in non-SSL (the default), the auth cookie would not get sent back to the server. this would mean that the server would send a new auth cookie (with a new session) for every request back to the client.
the fix is to either set requiressl to false in web.config and true in web.release.config or turn on SSL while debugging:
So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:
r" |(?<![0-9])[.,](?![0-9])"
You can use chmod with the X
mode letter (the capital X) to set the executable flag only for directories.
In the example below the executable flag is cleared and then set for all directories recursively:
~$ mkdir foo
~$ mkdir foo/bar
~$ mkdir foo/baz
~$ touch foo/x
~$ touch foo/y
~$ chmod -R go-X foo
~$ ls -l foo
total 8
drwxrw-r-- 2 wq wq 4096 Nov 14 15:31 bar
drwxrw-r-- 2 wq wq 4096 Nov 14 15:31 baz
-rw-rw-r-- 1 wq wq 0 Nov 14 15:31 x
-rw-rw-r-- 1 wq wq 0 Nov 14 15:31 y
~$ chmod -R go+X foo
~$ ls -l foo
total 8
drwxrwxr-x 2 wq wq 4096 Nov 14 15:31 bar
drwxrwxr-x 2 wq wq 4096 Nov 14 15:31 baz
-rw-rw-r-- 1 wq wq 0 Nov 14 15:31 x
-rw-rw-r-- 1 wq wq 0 Nov 14 15:31 y
A bit of explaination:
chmod -x foo
- clear the eXecutable flag for foo
chmod +x foo
- set the eXecutable flag for foo
chmod go+x foo
- same as above, but set the flag only for Group and Other users, don't touch the User (owner) permissionchmod go+X foo
- same as above, but apply only to directories, don't touch fileschmod -R go+X foo
- same as above, but do this Recursively for all subdirectories of foo
if you found out that the memory settings were not being used and in order to change the memory settings, I used the tomcat7w or tomcat8w in the \bin folder.Then the following should pop up:
Click the Java tab and add the arguments.restart tomcat
By default, when you click on a ListView item it doesn't change its state to "selected". So, when the event fires and you do:
myList.getSelectedItem();
The method doesn't have anything to return. What you have to do is to use the position and obtain the underlying object by doing:
myList.getItemAtPosition(position);
Had such a problem when executing forking in php for command line. In my case from time to time the php killed the child process. To fix this, just wait for the process to complete using the command pcntl_wait($status);
here's a piece of code for a visual example:
#!/bin/php -n
<?php
error_reporting(E_ALL & ~E_NOTICE);
ini_set("log_errors", 1);
ini_set('error_log', '/media/logs/php/fork.log');
$ski = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
error_log(getmypid().' '.$ski.' start my php');
$pid = pcntl_fork();
if($pid) {
error_log(getmypid().' '.$ski.' start 2');
// Wait for children to return. Otherwise they
// would turn into "Zombie" processes
// !!!!!! add this !!!!!!
pcntl_wait($status);
// !!!!!! add this !!!!!!
} else {
error_log(getmypid().' '.$ski.' start 3');
//[03-Apr-2020 12:13:47 UTC] PHP Warning: Error while sending QUERY packet. PID=18048 in /speed/sport/fortest.php on line 22457
mysqli_query($con,$query,MYSQLI_ASYNC);
error_log(getmypid().' '.$ski.' sleep child');
sleep(15);
exit;
}
error_log(getmypid().' '.$ski.'end my php');
exit(0);
?>
You could also use MySQLdb.cursors.DictCursor
. This turns your result set into a python list of python dictionaries, although it uses a special cursor, thus technically less portable than the accepted answer. Not sure about speed. Here's the edited original code that uses this.
#!/usr/bin/python -u
import MySQLdb
import MySQLdb.cursors
#===================================================================
# connect to mysql
#===================================================================
try:
db = MySQLdb.connect(host='myhost', user='myuser', passwd='mypass', db='mydb', cursorclass=MySQLdb.cursors.DictCursor)
except MySQLdb.Error, e:
print 'Error %d: %s' % (e.args[0], e.args[1])
sys.exit(1)
#===================================================================
# query select from table
#===================================================================
cursor = db.cursor()
sql = 'SELECT ext, SUM(size) AS totalsize, COUNT(*) AS filecount FROM fileindex GROUP BY ext ORDER BY totalsize DESC;'
cursor.execute(sql)
all_rows = cursor.fetchall()
print len(all_rows) # How many rows are returned.
for row in all_rows: # While loops always make me shudder!
print '%s %s %s\n' % (row['ext'], row['totalsize'], row['filecount'])
cursor.close()
db.close()
Standard dictionary functions apply, for example, len(row[0])
to count the number of columns for the first row, list(row[0])
for a list of column names (for the first row), etc. Hope this helps!
If you have to check it out manually you can do int a = s.charAt(0)
If the value of a is between 65 to 90 it is upper case.
It is strange that no one had suggested NIO.2 operations (available since Java 7):
import java.nio.file.{Paths, Files}
import java.nio.charset.StandardCharsets
Files.write(Paths.get("file.txt"), "file contents".getBytes(StandardCharsets.UTF_8))
I think this is by far the simplest and easiest and most idiomatic way, and it does not need any dependencies sans Java itself.
Here is my Implementation of Stacks.
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.clear = clear;
this.length = length;
}
function push(element) {
this.dataStore[this.top++] = element;
}
function peek() {
return this.dataStore[this.top-1];
}
function pop() {
return this.dataStore[--this.top];
}
function clear() {
this.top = 0;
}
function length() {
return this.top;
}
var s = new Stack();
s.push("David");
s.push("Raymond");
s.push("Bryan");
console.log("length: " + s.length());
console.log(s.peek());
Please update your php.ini with
default_socket_timeout = 120
You can create your own php.ini if php is installed a CGI instead of a Apache module
You can just do it like this:
#content {
position: relative;
}
#content img {
position: absolute;
top: 0px;
right: 0px;
}
<div id="content">
<img src="images/ribbon.png" class="ribbon"/>
<div>some text...</div>
</div>
If you are working with MVC C#, this is the way to deal with printers and serial ports for dropdowns.
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Drawing.Printing;
public class Miclass
{
private void AllViews()
{
List<PortClass> ports = new List<PortClass>();
List<Printersclass> Printersfor = new List<Printersclass>();
string[] portnames = SerialPort.GetPortNames();
/*PORTS*/
for (int i = 0; i < portnames.Count(); i++)
{
ports.Add(new PortClass() { Name = portnames[i].Trim(), Desc = portnames[i].Trim() });
}
/*PRINTER*/
for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
{
Printersfor.Add(new Printersclass() { Name = PrinterSettings.InstalledPrinters[i].Trim(), Desc = PrinterSettings.InstalledPrinters[i].Trim() });
}
}
}
public class PortClass
{
public string Name { get; set; }
public string Desc { get; set; }
public override string ToString()
{
return string.Format("{0} ({1})", Name, Desc);
}
}
public class Printersclass
{
public string Name { get; set; }
public string Desc { get; set; }
public override string ToString()
{
return string.Format("{0} ({1})", Name, Desc);
}
}
You need a regular expression like "\\s+"
, which means: split whenever at least one whitespace is encountered. The full Java code is:
try {
String[] splitArray = input.split("\\s+");
} catch (PatternSyntaxException ex) {
//
}
you would have to write down some method to create a temporary array and then copy it like
public String[] increaseArray(String[] theArray, int increaseBy)
{
int i = theArray.length;
int n = ++i;
String[] newArray = new String[n];
for(int cnt=0;cnt<theArray.length;cnt++)
{
newArray[cnt] = theArray[cnt];
}
return newArray;
}
or The ArrayList would be helpful to resolve your problem.
You can basically switch the class using [ngClass]
for example
<button [ngClass]="{'active': selectedItem === 'item1'}" (click)="selectedItem = 'item1'">Button One</button>
<button [ngClass]="{'active': selectedItem === 'item2'}" (click)="selectedItem = 'item2'">Button Two</button>
In Excel 2007 you have the option to show empty cells as gaps, zero or connect data points with a line (I assume it's similar for Excel 2010):
If none of these are optimal and you have a "chunk" of data points (or even single ones) missing, you can group-and-hide them, which will remove them from the chart.
Before hiding:
After hiding:
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
Source: http://www.christianschenk.org/blog/php-curl-allow-url-fopen/
To achieve this we need to add few line of Code in both App
App A: Which you want to open from another App. (Source)
App B: From App B you want to open App A (Destination)
Code for App A
Add few tags into the Plist of App A Open Plist Source of App A and Past below XML
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.TestApp</string>
<key>CFBundleURLSchemes</key>
<array>
<string>testApp.linking</string>
</array>
</dict>
</array>
In App delegate of App A - Get Callback here
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
// You we get the call back here when App B will try to Open
// sourceApplication will have the bundle ID of the App B
// [url query] will provide you the whole URL
// [url query] with the help of this you can also pass the value from App B and get that value here
}
Now coming to App B code -
If you just want to open App A without any input parameter
-(IBAction)openApp_A:(id)sender{
if(![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"testApp.linking://?"]]){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"App is not available!" message:nil delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
If you want to pass parameter from App B to App A then use below Code
-(IBAction)openApp_A:(id)sender{
if(![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"testApp.linking://?userName=abe®istered=1&Password=123abc"]]){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"App is not available!" message:nil delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
Note: You can also open App with just type testApp.linking://? on safari browser
I just extended the CanvasRenderingContext2D adding two functions: mlFillText and mlStrokeText.
You can find the last version in GitHub:
With this functions you can fill / stroke miltiline text in a box. You can align the text verticaly and horizontaly. (It takes in account \n's and can also justify the text).
The prototypes are:
function mlFillText(text,x,y,w,h,vAlign,hAlign,lineheight); function mlStrokeText(text,x,y,w,h,vAlign,hAlign,lineheight);
Where vAlign can be: "top", "center" or "button" And hAlign can be: "left", "center", "right" or "justify"
You can test the lib here: http://jsfiddle.net/4WRZj/1/
Here is the code of the library:
// Library: mltext.js
// Desciption: Extends the CanvasRenderingContext2D that adds two functions: mlFillText and mlStrokeText.
//
// The prototypes are:
//
// function mlFillText(text,x,y,w,h,vAlign,hAlign,lineheight);
// function mlStrokeText(text,x,y,w,h,vAlign,hAlign,lineheight);
//
// Where vAlign can be: "top", "center" or "button"
// And hAlign can be: "left", "center", "right" or "justify"
// Author: Jordi Baylina. (baylina at uniclau.com)
// License: GPL
// Date: 2013-02-21
function mlFunction(text, x, y, w, h, hAlign, vAlign, lineheight, fn) {
text = text.replace(/[\n]/g, " \n ");
text = text.replace(/\r/g, "");
var words = text.split(/[ ]+/);
var sp = this.measureText(' ').width;
var lines = [];
var actualline = 0;
var actualsize = 0;
var wo;
lines[actualline] = {};
lines[actualline].Words = [];
i = 0;
while (i < words.length) {
var word = words[i];
if (word == "\n") {
lines[actualline].EndParagraph = true;
actualline++;
actualsize = 0;
lines[actualline] = {};
lines[actualline].Words = [];
i++;
} else {
wo = {};
wo.l = this.measureText(word).width;
if (actualsize === 0) {
while (wo.l > w) {
word = word.slice(0, word.length - 1);
wo.l = this.measureText(word).width;
}
if (word === "") return; // I can't fill a single character
wo.word = word;
lines[actualline].Words.push(wo);
actualsize = wo.l;
if (word != words[i]) {
words[i] = words[i].slice(word.length, words[i].length);
} else {
i++;
}
} else {
if (actualsize + sp + wo.l > w) {
lines[actualline].EndParagraph = false;
actualline++;
actualsize = 0;
lines[actualline] = {};
lines[actualline].Words = [];
} else {
wo.word = word;
lines[actualline].Words.push(wo);
actualsize += sp + wo.l;
i++;
}
}
}
}
if (actualsize === 0) lines[actualline].pop();
lines[actualline].EndParagraph = true;
var totalH = lineheight * lines.length;
while (totalH > h) {
lines.pop();
totalH = lineheight * lines.length;
}
var yy;
if (vAlign == "bottom") {
yy = y + h - totalH + lineheight;
} else if (vAlign == "center") {
yy = y + h / 2 - totalH / 2 + lineheight;
} else {
yy = y + lineheight;
}
var oldTextAlign = this.textAlign;
this.textAlign = "left";
for (var li in lines) {
var totallen = 0;
var xx, usp;
for (wo in lines[li].Words) totallen += lines[li].Words[wo].l;
if (hAlign == "center") {
usp = sp;
xx = x + w / 2 - (totallen + sp * (lines[li].Words.length - 1)) / 2;
} else if ((hAlign == "justify") && (!lines[li].EndParagraph)) {
xx = x;
usp = (w - totallen) / (lines[li].Words.length - 1);
} else if (hAlign == "right") {
xx = x + w - (totallen + sp * (lines[li].Words.length - 1));
usp = sp;
} else { // left
xx = x;
usp = sp;
}
for (wo in lines[li].Words) {
if (fn == "fillText") {
this.fillText(lines[li].Words[wo].word, xx, yy);
} else if (fn == "strokeText") {
this.strokeText(lines[li].Words[wo].word, xx, yy);
}
xx += lines[li].Words[wo].l + usp;
}
yy += lineheight;
}
this.textAlign = oldTextAlign;
}
(function mlInit() {
CanvasRenderingContext2D.prototype.mlFunction = mlFunction;
CanvasRenderingContext2D.prototype.mlFillText = function (text, x, y, w, h, vAlign, hAlign, lineheight) {
this.mlFunction(text, x, y, w, h, hAlign, vAlign, lineheight, "fillText");
};
CanvasRenderingContext2D.prototype.mlStrokeText = function (text, x, y, w, h, vAlign, hAlign, lineheight) {
this.mlFunction(text, x, y, w, h, hAlign, vAlign, lineheight, "strokeText");
};
})();
And here is the use example:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var T = "This is a very long line line with a CR at the end.\n This is the second line.\nAnd this is the last line.";
var lh = 12;
ctx.lineWidth = 1;
ctx.mlFillText(T, 10, 10, 100, 100, 'top', 'left', lh);
ctx.strokeRect(10, 10, 100, 100);
ctx.mlFillText(T, 110, 10, 100, 100, 'top', 'center', lh);
ctx.strokeRect(110, 10, 100, 100);
ctx.mlFillText(T, 210, 10, 100, 100, 'top', 'right', lh);
ctx.strokeRect(210, 10, 100, 100);
ctx.mlFillText(T, 310, 10, 100, 100, 'top', 'justify', lh);
ctx.strokeRect(310, 10, 100, 100);
ctx.mlFillText(T, 10, 110, 100, 100, 'center', 'left', lh);
ctx.strokeRect(10, 110, 100, 100);
ctx.mlFillText(T, 110, 110, 100, 100, 'center', 'center', lh);
ctx.strokeRect(110, 110, 100, 100);
ctx.mlFillText(T, 210, 110, 100, 100, 'center', 'right', lh);
ctx.strokeRect(210, 110, 100, 100);
ctx.mlFillText(T, 310, 110, 100, 100, 'center', 'justify', lh);
ctx.strokeRect(310, 110, 100, 100);
ctx.mlFillText(T, 10, 210, 100, 100, 'bottom', 'left', lh);
ctx.strokeRect(10, 210, 100, 100);
ctx.mlFillText(T, 110, 210, 100, 100, 'bottom', 'center', lh);
ctx.strokeRect(110, 210, 100, 100);
ctx.mlFillText(T, 210, 210, 100, 100, 'bottom', 'right', lh);
ctx.strokeRect(210, 210, 100, 100);
ctx.mlFillText(T, 310, 210, 100, 100, 'bottom', 'justify', lh);
ctx.strokeRect(310, 210, 100, 100);
ctx.mlStrokeText("Yo can also use mlStrokeText!", 0 , 310 , 420, 30, 'center', 'center', lh);
Install bootstrap
npm install bootstrap@next
Add code to .angular-cli.json:
"styles": [
"styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/tether/dist/js/tether.js",
"../node_modules/bootstrap/dist/js/bootstrap.js"
],
Last add bootstrap.css to your code style.scss
@import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
Restart your local server
If you got a html page like this:
<body onbeforecopy = "return false" ondragstart = "return false" onselectstart = "return false" oncontextmenu = "return false" onselect = "document.selection.empty()" oncopy = "document.selection.empty()">
There a simple way to disable all events:
document.write(document.body.innerHTML)
You got the html content and lost other things.
Use CardView for Round Rectangle. CardView give more functionality like cardCornerRadius, cardBackgroundColor, cardElevation & many more. CardView make UI more suitable then Custom Round Rectangle drawable.
It was throwing me this error when I using switch in a function with variables declared in my class:
private void ShowCalendar(final Activity context, Point p, int type)
{
switch (type) {
case type_cat:
break;
case type_region:
break;
case type_city:
break;
default:
//sth
break;
}
}
The problem was solved when I declared final
to the variables in the start of the class:
final int type_cat=1, type_region=2, type_city=3;
Why don't you use PowerShell?
Stop-Process -Name notepad
And if you are in a batch file:
powershell -Command "Stop-Process -Name notepad"
powershell -Command "Stop-Process -Id 4232"
You don't really need to install or use any third party tools.
The drivers located in ...\Android\Sdk\extras\google\usb_driver
work just fine.
Step 1: In Device Manager
, Right click on the malfunctioning Android ADB Interface
driver
Step 2: Select Update Driver Software
Step 3: Select Browse my computer for driver software
Step 4: Select Let me pick from a list of device drivers on my computer
Step 5: Select Have Disk
This window pops up:
Step 6: Copy the location of the Google USB Driver (...\Android\Sdk\extras\google\usb_driver)
or browse to it.
Step 7: Click Ok
This window pops up:
Step 8: Select Android ADB Interface
and click Next
The window below pops up with a warning:
That's it. You driver installation will start and in a few seconds, you should be able to see your device
Call the super method:
Java:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
}
Kotlin:
override fun void onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater)
}
Put log statements in the code to see if the method is not being called or if the menu is not being amended by your code.
Also ensure you are calling setHasOptionsMenu(boolean)
in onCreate(Bundle)
to notify the fragment that it should participate in options menu handling.
This did the trick for me coming from Brackets and being used to ctrl+/ on the numpad.
[
{ "keys": ["ctrl+keypad_divide"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+keypad_divide"], "command": "toggle_comment", "args": { "block": true } }
]
Seems like one of your values, with a property key of 'value' is undefined. Test that i1
, i2
and __i
are defined before executing the if statements:
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if(i1 && i2 && __i.user && __i.pass)
{
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}
You're tired and cant do any more work. You eat food. The energy spent looking for food, getting it and actually eating it consumes energy and is overhead!
Overhead is something wasted in order to accomplish a task. The goal is to make overhead very very small.
In computer science lets say you want to print a number, thats your task. But storing the number, the setting up the display to print it and calling routines to print it, then accessing the number from variable are all overhead.
There are (at least) two types of package dependencies you can indicate in your package.json files:
Those packages that are required in order to use your module are listed under the "dependencies" property. Using npm you can add those dependencies to your package.json file this way:
npm install --save packageName
Those packages required in order to help develop your module are listed under the "devDependencies" property. These packages are not necessary for others to use the module, but if they want to help develop the module, these packages will be needed. Using npm you can add those devDependencies to your package.json file this way:
npm install --save-dev packageName
List anyObject = new ArrayList();
or
List<Object> anyObject = new ArrayList<Object>();
now anyObject
can hold objects of any type
.
use instanceof to know what kind of object it is
.
I like this approach
my_hash = {}
my_hash["goals"] = 3 #to show number
my_hash["penalties"] = "5" #to show string
print("I scored %(goals)d goals and took %(penalties)s penalties" % my_hash)
Note the appended d and s to the brackets respectively.
output will be:
I scored 3 goals and took 5 penalties
If you look at the alternatives on this page, of course the first option looks better and the second one is just more verbose. But if you are looking through a large class that someone else wrote, that verbosity can make the difference between realizing right away what the conditional is testing or not.
One of the reasons I moved away from Perl is because it relies so heavily on punctuation, which is much slower to interpret while reading.
I know I'm outvoted here, but I will almost always side with more explicit code so others can read it more accurately. Then again, I would never use a boolean variable called "status" either. Maybe isSuccess or just success, but "status" being true or false does not mean anything to the casual reader intuitively. As you can tell, I'm very into code readability because I read so much code others have written.
I would change your service layer to:
public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
return Task.Run(() =>
{
return _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}
}
as you have it, you are still running your _service.Process
call synchronously, and gaining very little or no benefit from awaiting it.
With this approach, you are wrapping the potentially slow call in a Task
, starting it, and returning it to be awaited. Now you get the benefit of awaiting the Task
.
Use the following:
driver.findElement(By.id("id")).sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.DELETE), "Your Value");
For those who have this problem with collection of enums here is how to solve it:
@Enumerated(EnumType.STRING)
@Column(name = "OPTION")
@CollectionTable(name = "MY_ENTITY_MY_OPTION")
@ElementCollection(targetClass = MyOptionEnum.class, fetch = EAGER)
Collection<MyOptionEnum> options;
Although I have not worked C++ at a professional level, in my opinion, it is OK to throw exceptions from the constructors. I do that(if needed) in .Net. Check out this and this link. It might be of your interest.
Unitialized variables check. Link 1 and 2 already seem to do this just fine, though.
I can't say I have used any of these intensively, though :)
You can also try \x0d\x0a
in the "Replace with" box with "Use regular Expression" box checked to get carriage return + line feed using Visual Studio Find/Replace.
Using \n
(line feed) is the same as \x0a
Start with:
find . -name '*.log.*.zip' -a -mtime +1
You may not need a regex, try:
find . -name '*.log.*-*-*.zip' -a -mtime +1
You will want the +1 in order to match 1, 2, 3 ...
Decode to Unicode, encode the results to UTF8.
apple.decode('latin1').encode('utf8')
The functionality to name returned aggregate columns has been reintroduced in the master branch and is targeted for pandas 0.25. The new syntax is .agg(new_col_name=('col_name', 'agg_func')
. Detailed example from the PR linked above:
In [2]: df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
...: 'height': [9.1, 6.0, 9.5, 34.0],
...: 'weight': [7.9, 7.5, 9.9, 198.0]})
...:
In [3]: df
Out[3]:
kind height weight
0 cat 9.1 7.9
1 dog 6.0 7.5
2 cat 9.5 9.9
3 dog 34.0 198.0
In [4]: df.groupby('kind').agg(min_height=('height', 'min'),
max_weight=('weight', 'max'))
Out[4]:
min_height max_weight
kind
cat 9.1 9.9
dog 6.0 198.0
It will also be possible to use multiple lambda expressions with this syntax and the two-step rename syntax I suggested earlier (below) as per this PR. Again, copying from the example in the PR:
In [2]: df = pd.DataFrame({"A": ['a', 'a'], 'B': [1, 2], 'C': [3, 4]})
In [3]: df.groupby("A").agg({'B': [lambda x: 0, lambda x: 1]})
Out[3]:
B
<lambda> <lambda 1>
A
a 0 1
and then .rename()
, or in one go:
In [4]: df.groupby("A").agg(b=('B', lambda x: 0), c=('B', lambda x: 1))
Out[4]:
b c
A
a 0 0
The currently accepted answer by unutbu describes are great way of doing this in pandas versions <= 0.20. However, as of pandas 0.20, using this method raises a warning indicating that the syntax will not be available in future versions of pandas.
Series:
FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version
DataFrames:
FutureWarning: using a dict with renaming is deprecated and will be removed in a future version
According to the pandas 0.20 changelog, the recommended way of renaming columns while aggregating is as follows.
# Create a sample data frame
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
'B': range(5),
'C': range(5)})
# ==== SINGLE COLUMN (SERIES) ====
# Syntax soon to be deprecated
df.groupby('A').B.agg({'foo': 'count'})
# Recommended replacement syntax
df.groupby('A').B.agg(['count']).rename(columns={'count': 'foo'})
# ==== MULTI COLUMN ====
# Syntax soon to be deprecated
df.groupby('A').agg({'B': {'foo': 'sum'}, 'C': {'bar': 'min'}})
# Recommended replacement syntax
df.groupby('A').agg({'B': 'sum', 'C': 'min'}).rename(columns={'B': 'foo', 'C': 'bar'})
# As the recommended syntax is more verbose, parentheses can
# be used to introduce line breaks and increase readability
(df.groupby('A')
.agg({'B': 'sum', 'C': 'min'})
.rename(columns={'B': 'foo', 'C': 'bar'})
)
Please see the 0.20 changelog for additional details.
With the old style dictionary syntax, it was possible to pass multiple lambda
functions to .agg
, since these would be renamed with the key in the passed dictionary:
>>> df.groupby('A').agg({'B': {'min': lambda x: x.min(), 'max': lambda x: x.max()}})
B
max min
A
1 2 0
2 4 3
Multiple functions can also be passed to a single column as a list:
>>> df.groupby('A').agg({'B': [np.min, np.max]})
B
amin amax
A
1 0 2
2 3 4
However, this does not work with lambda functions, since they are anonymous and all return <lambda>
, which causes a name collision:
>>> df.groupby('A').agg({'B': [lambda x: x.min(), lambda x: x.max]})
SpecificationError: Function names must be unique, found multiple named <lambda>
To avoid the SpecificationError
, named functions can be defined a priori instead of using lambda
. Suitable function names also avoid calling .rename
on the data frame afterwards. These functions can be passed with the same list syntax as above:
>>> def my_min(x):
>>> return x.min()
>>> def my_max(x):
>>> return x.max()
>>> df.groupby('A').agg({'B': [my_min, my_max]})
B
my_min my_max
A
1 0 2
2 3 4
I found the error: I have a library that it was built using jdk 1.6. The Spring main controller and components are in this library. And how I use jdk 1.7, It does not find the classes built in 1.6.
The solution was built all using "compiler compliance level: 1.7" and "Generated .class files compatibility: 1.6", "Source compatibility: 1.6".
I setup this option in Eclipse: Preferences\Java\Compiler.
Thanks everybody.
My C++ templates were there all along, it was my C# ones that were missing.
Similar to CSharpie, after trying many modify/re-installs, oddly the following finally worked for me :
- run the installer, but un-select 'Desktop development with C++'.
- allow installer to complete
- run the installer again, and select 'Desktop development with C++'.
- allow installer to complete
read() is equivalent to recv() with a flags parameter of 0. Other values for the flags parameter change the behaviour of recv(). Similarly, write() is equivalent to send() with flags == 0.
Well, there's a much easier way of doing this. When you grab embed link for youtube video, scroll down a bit and you will see some options: iFrame Embed, Use old embed, related videos etc. There, select Use old embed link. This solves the issue.
If using a pojo class based on JSON response. If chances are there that json changes frequently declare at pojo class level:
@JsonIgnoreProperties(ignoreUnknown = true)
and at the objectMapper add this if you are converting:
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
So that code will not break.
Create a Custom View Engine and have a method that returns a ViewEngineResult
In this example you just overwrite the _options.ViewLocationFormats
and add your folder directory
:
public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage)
{
var controllerName = context.GetNormalizedRouteValue(CONTROLLER_KEY);
var areaName = context.GetNormalizedRouteValue(AREA_KEY);
var checkedLocations = new List<string>();
foreach (var location in _options.ViewLocationFormats)
{
var view = string.Format(location, viewName, controllerName);
if (File.Exists(view))
{
return ViewEngineResult.Found("Default", new View(view, _ViewRendering));
}
checkedLocations.Add(view);
}
return ViewEngineResult.NotFound(viewName, checkedLocations);
}
You have to use implicitly unwrapped optionals so that Swift can cope with circular dependencies (parent <-> child of the UI components in this case) during the initialization phase.
@IBOutlet var imgBook: UIImageView!
@IBOutlet var titleBook: UILabel!
@IBOutlet var pageBook: UILabel!
Read this doc, they explain it all nicely.
How about:
git branch -D email
git checkout staging
git checkout -b email
git push origin email --force-with-lease
You want rows where that condition is true so you need a comma:
data[data$Ozone > 14, ]
I'm calling powershell from cmd, and passing quotes and neither escapes here worked. The grave accent worked to escape double quotes on this Win 10 surface pro.
>powershell.exe "echo la`"" >> test
>type test
la"
Below are outputs I got for other characters to escape a double quote:
la\
la^
la
la~
Using another quote to escape a quote resulted in no quotes. As you can see, the characters themselves got typed, but didn't escape the double quotes.
It is possible to get your second example (i.e., the one using a scoped enum) to work using the same syntax as unscoped enums. Furthermore, the solution is generic and will work for all scoped enums, versus writing code for each scoped enum (as shown in the answer provided by @ForEveR).
The solution is to write a generic operator<<
function which will work for any scoped enum. The solution employs SFINAE via std::enable_if
and is as follows.
#include <iostream>
#include <type_traits>
// Scoped enum
enum class Color
{
Red,
Green,
Blue
};
// Unscoped enum
enum Orientation
{
Horizontal,
Vertical
};
// Another scoped enum
enum class ExecStatus
{
Idle,
Started,
Running
};
template<typename T>
std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
{
return stream << static_cast<typename std::underlying_type<T>::type>(e);
}
int main()
{
std::cout << Color::Blue << "\n";
std::cout << Vertical << "\n";
std::cout << ExecStatus::Running << "\n";
return 0;
}
use this code:
<iframe width="600" height="450" frameborder="0" style="border:0"
src="https://www.google.com/maps/embed/v1/place?q=place_id:ChIJ5Rw5v9dCXz4R3SUtcL5ZLMk&key=..." allowfullscreen></iframe>
Full process (Unix svn package):
Check files are not in SVN:
> svn st -u folder
? folder
Add all (including ignored files):
> svn add folder
A folder
A folder/file1.txt
A folder/folder2
A folder/folder2/file2.txt
A folder/folderToIgnore
A folder/folderToIgnore/fileToIgnore1.txt
A fileToIgnore2.txt
Remove "Add" Flag to All * Ignore * files:
> cd folder
> svn revert --recursive folderToIgnore
Reverted 'folderToIgnore'
Reverted 'folderToIgnore/fileToIgnore1.txt'
> svn revert fileToIgnore2.txt
Reverted 'fileToIgnore2.txt'
Edit svn ignore on folder
svn propedit svn:ignore .
Add two singles lines with just the following:
folderToIgnore
fileToIgnore2.txt
Check which files will be upload and commit:
> cd ..
> svn st -u
A folder
A folder/file1.txt
A folder/folder2
A folder/folder2/file2.txt
> svn ci -m "Commit message here"
Something simple like this can be done using subqueries in the select
clause:
select ((select sum(hours) from resource) +
(select sum(hours) from projects-time)
) as totalHours
For such a simple query as this, such a subselect is reasonable.
In some databases, you might have to add from dual
for the query to compile.
If you want to output each individually:
select (select sum(hours) from resource) as ResourceHours,
(select sum(hours) from projects-time) as ProjectHours
If you want both and the sum, a subquery is handy:
select ResourceHours, ProjectHours, (ResourceHours+ProjecctHours) as TotalHours
from (select (select sum(hours) from resource) as ResourceHours,
(select sum(hours) from projects-time) as ProjectHours
) t
This is answering a slightly different question, but since I got stuck on this myself, I hope it might be useful for someone else.
If you want to use allow_redirects=False
and get directly to the first redirect object, rather than following a chain of them, and you just want to get the redirect location directly out of the 302 response object, then r.url
won't work. Instead, it's the "Location" header:
r = requests.get('http://github.com/', allow_redirects=False)
r.status_code # 302
r.url # http://github.com, not https.
r.headers['Location'] # https://github.com/ -- the redirect destination
The only way to truly test if a variable is undefined
is to do the following. Remember, undefined is an object in JavaScript.
if (typeof someVar === 'undefined') {
// Your variable is undefined
}
Some of the other solutions in this thread will lead you to believe a variable is undefined even though it has been defined (with a value of NULL or 0, for instance).
first you have to create data directory where MongoDB stores data. MongoDB’s default data directory path is the absolute path \data\db on the drive from which you start MongoDB.
if you have install in C:/ drive then you have to create data\db directory. for doing this run command in cmd
C:\>mkdir data\db
To start MongoDB, run mongod.exe.
"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --dbpath="c:\data\db"
The --dbpath option points to your database directory.
Connect to MongoDB.
"C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe"
to check all work good :
show dbs
My problem was that I had other libraries that my project referenced and those libraries had another version of appcompat referenced. This is what I did to resolve the issue:
(You should back up your project before doing this)
1) I deleted all the appcompat layout folders (ex: /res/layout-v11).
2) Solved the problems that arose from that, usually an error in menu.xml
3) Back to main project and add appcompat library, clean, and everything works!
You can think of the modulus operator as giving you a remainder. count % 6 divides 6 out of count as many times as it can and gives you a remainder from 0 to 5 (These are all the possible remainders because you already divided out 6 as many times as you can). The elements of the array are all printed in the for loop, but every time the remainder is 5 (every 6th element), it outputs a newline character. This gives you 6 elements per line. For 5 elements per line, use
if (count % 5 == 4)
I prefer creating a reverse plug-in eg
jQuery.fn.reverse = function(fn) {
var i = this.length;
while(i--) {
fn.call(this[i], i, this[i])
}
};
Usage eg:
$('#product-panel > div').reverse(function(i, e) {
alert(i);
alert(e);
});
Use this to list Grantee too and remove (PG_monitor and Public) for Postgres PaaS Azure.
SELECT grantee,table_catalog, table_schema, table_name, privilege_type
FROM information_schema.table_privileges
WHERE grantee not in ('pg_monitor','PUBLIC');
File uploader with AngularJs Material and a mime type validation:
Directive:
function apsUploadFile() {
var directive = {
restrict: 'E',
require:['ngModel', 'apsUploadFile'],
transclude: true,
scope: {
label: '@',
mimeType: '@',
},
templateUrl: '/build/html/aps-file-upload.html',
controllerAs: 'ctrl',
controller: function($scope) {
var self = this;
this.model = null;
this.setModel = function(ngModel) {
this.$error = ngModel.$error;
ngModel.$render = function() {
self.model = ngModel.$viewValue;
};
$scope.$watch('ctrl.model', function(newval) {
ngModel.$setViewValue(newval);
});
};
},
link: apsUploadFileLink
};
return directive;
}
function apsUploadFileLink(scope, element, attrs, controllers) {
var ngModelCtrl = controllers[0];
var apsUploadFile = controllers[1];
apsUploadFile.inputname = attrs.name;
apsUploadFile.setModel(ngModelCtrl);
var reg;
attrs.$observe('mimeType', function(value) {
var accept = value.replace(/,/g,'|');
reg = new RegExp(accept, "i");
ngModelCtrl.$validate();
});
ngModelCtrl.$validators.mimetype = function(modelValue, viewValue) {
if(modelValue.data == null){
return apsUploadFile.valid = true;
}
if(modelValue.type.match(reg)){
return apsUploadFile.valid = true;
}else{
return apsUploadFile.valid = false;
}
};
var input = $(element[0].querySelector('#fileInput'));
var button = $(element[0].querySelector('#uploadButton'));
var textInput = $(element[0].querySelector('#textInput'));
if (input.length && button.length && textInput.length) {
button.click(function(e) {
input.click();
});
textInput.click(function(e) {
input.click();
});
}
input.on('change', function(e) {
//scope.fileLoaded(e);
var files = e.target.files;
if (files[0]) {
ngModelCtrl.$viewValue.filename = scope.filename = files[0].name;
ngModelCtrl.$viewValue.type = files[0].type;
ngModelCtrl.$viewValue.size = files[0].size;
var fileReader = new FileReader();
fileReader.onload = function () {
ngModelCtrl.$viewValue.data = fileReader.result;
ngModelCtrl.$validate();
};
fileReader.readAsDataURL(files[0]);
ngModelCtrl.$render();
} else {
ngModelCtrl.$viewValue = null;
}
scope.$apply();
});
}
app.directive('apsUploadFile', apsUploadFile);
html template:
<input id="fileInput" type="file" name="ctrl.inputname" class="ng-hide">
<md-input-container md-is-error="!ctrl.valid">
<label>{@{label}@}</label>
<input id="textInput" ng-model="ctrl.model.filename" type="text" ng-readonly="true">
<div ng-messages="ctrl.$error" ng-transclude></div>
</md-input-container>
<md-button id="uploadButton" class="md-icon-button md-primary" aria-label="attach_file">
<md-icon class="material-icons">cloud_upload</md-icon>
</md-button>
Exemple:
<div layout-gt-sm="row">
<aps-upload-file name="strip" ng-model="cardDesign.strip" label="Strip" mime-type="image/png" class="md-block">
<div ng-message="mimetype" class="md-input-message-animation ng-scope" style="opacity: 1; margin-top: 0px;">Your image must be PNG.</div>
</aps-upload-file>
</div>
Try the google closure compiler:
http://code.google.com/closure/compiler/docs/gettingstarted_ui.html
As others point out, the user name is usually anonymous, and the password is usually your e-mail address, but this is not universally true, and has been found not to work for certain anonymous FTP sites. For example, at least some cPanel sites seem to deviate from the norm, and if given the traditional user name without domain, one of various errors may result:
If the server uses Pure-FTP as the FTP server:
421 Can't change directory to /var/ftp/ error message.
If the server uses ProFTP as the FTP server:
530 Login Authentication Failed error message.
When one of the aforementioned errors occurs when attempting anonymous access, try including a domain with the username. For example, where example.com is the domain used in your e-mail address:
User name: [email protected]
In the specific case of a cPanel site, the password value is unimportant, and may be left blank, but there is no harm in providing a "traditional" anonymous password formatted as an e-mail address.
For reference, this answer is based on content found on a documentation.cpanel.net Anonymous FTP page. At the time of this writing, it stated:
When users log in to FTP anonymously, they must format usernames as
[email protected]
, whereexample.com
represents the user's domain name. This requirement directs your server to the correctpublic_ftp
directory.
Go to the download page and download the Windows x86
version with filename jdk-7-windows-i586.exe
.
We can do it with another approach too, Like first of all get the hash value from js and call the ajax using that parameter and can do whatever we want
Delete you AVD and create another. Maybe isn't the perfect thing to do, but it's the fastest.
I've been stuck with the same issue, and the preceding answer did not help me (albeit well written).
The solution is here : check your /etc/redis/redis.conf
, and make sure to change the default
bind 127.0.0.1
to
bind 0.0.0.0
Then restart your service (service redis-server restart
)
You can then now check that redis is listening on non-local interface with
redis-cli -h 192.168.x.x ping
(replace 192.168.x.x with your IP adress)
Important note : as several users stated, it is not safe to set this on a server which is exposed to the Internet. You should be certain that you redis is protected with any means that fits your needs.
Also be sure to set your JAVA_HOME
environment variable. In fact, I usually set the JAVA_HOME
, then prepend the string "%JAVA_HOME%\bin
" to the system's PATH
environment variable so that if Java ever gets upgraded or changed, only the JAVA_HOME
variable will need to be changed.
And make sure that you close any command prompt windows or open applications that may read your environment variables, as changes to environment variables are normally not noticed until an application is re-launched.
- name: Move the src file to dest
command: mv /path/to/src /path/to/dest
args:
removes: /path/to/src
creates: /path/to/dest
This runs the mv
command only when /path/to/src
exists and /path/to/dest
does not, so it runs once per host, moves the file, then doesn't run again.
I use this method when I need to move a file or directory on several hundred hosts, many of which may be powered off at any given time. It's idempotent and safe to leave in a playbook.
Use a single backspace after each character
printf("hello wor\bl\bd\n");
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
Create an instance of OrientationEventListener
class and enable it.
OrientationEventListener mOrientationEventListener = new OrientationEventListener(YourActivity.this) {
@Override
public void onOrientationChanged(int orientation) {
Log.d(TAG,"orientation = " + orientation);
}
};
if (mOrientationEventListener.canDetectOrientation())
mOrientationEventListener.enable();
The answer is right in the MYSQL manual itself.
"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"
ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
ini_set('max_execution_time', '0'); // for infinite time of execution
Place this at the top of your PHP script and let your script loose!
Taken from Increase PHP Script Execution Time Limit Using ini_set()
You can try ng-file-upload angularjs plugin (instead of ng-upload).
It's fairly easy to setup and deal with angularjs specifics. It also supports progress, cancel, drag and drop and is cross browser.
html
<!-- Note: MUST BE PLACED BEFORE angular.js-->
<script src="ng-file-upload-shim.min.js"></script>
<script src="angular.min.js"></script>
<script src="ng-file-upload.min.js"></script>
<div ng-controller="MyCtrl">
<input type="file" ngf-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: 'server/upload/url', //upload.php script, node.js route, or servlet url
data: {myObj: $scope.myModelObj},
file: file,
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).then(function(response) {
var data = response.data;
// file is uploaded successfully
console.log(data);
});
}
};
}];
That is correct. When you do that you are casting it it into an employee
object, so that means you cannot access anything manager specific.
Downcasting is where you take a base class and then try and turn it into a more specific class. This can be accomplished with using is and an explicit cast like this:
if (employee is Manager)
{
Manager m = (Manager)employee;
//do something with it
}
or with the as
operator like this:
Manager m = (employee as Manager);
if (m != null)
{
//do something with it
}
If anything is unclear I'll be happy to correct it!
iPhone & iPod touch:
<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="../iphone.css" type="text/css" />
iPhone 4 & iPod touch 4G:
<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" type="text/css" href="../iphone4.css" />
iPad:
<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="../ipad.css" type="text/css" />
You can also force the application to open as administrator, if you have an administrator account, of course.
Locate the file, right click > properties > Shortcut > Advanced and check Run as Administrator
Then Click OK.
A cookie key(used to identify a session) and a cookie are the same thing being used in different ways. So the limit would be the same. According to Microsoft its 4096 bytes.
cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50 characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the separate cookies and can save around 200 bytes.
I was getting the below error in my 32 bit application.
Error: Retrieving the COM class factory for component with CLSID {4911BB26-11EE-4182-B66C-64DF2FA6502D} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
And on setting the "Enable32bitApplications
" to true in defaultapplicationpool
in IIS worked for me.
You can do it by following way.
ALTER TABLE tableName drop column if exists columnName;
ALTER TABLE tableName ADD COLUMN columnName character varying(8);
So it will drop the column if it is already exists. And then add the column to particular table.
I spent a day messing with CSS before I found anataliocs tip. Add wmode=transparent
as a parameter to the YouTube URL:
<iframe title=<your frame title goes here>
src="http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent"
scrolling="no"
frameborder="0"
width="640"
height="390"
style="border:none;">
</iframe>
This allows the iframe to inherit the z-index of its container so your opaque <div>
would be in front of the iframe.
if (iv_new_pwd.isSelected()) {
iv_new_pwd.setSelected(false);
Log.d("mytag", "in case 1");
edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT);
} else {
Log.d("mytag", "in case 1");
iv_new_pwd.setSelected(true);
edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
The use of http.createClient
is now deprecated. You can pass Headers in options collection as below.
var options = {
hostname: 'example.com',
path: '/somePath.php',
method: 'GET',
headers: {'Cookie': 'myCookie=myvalue'}
};
var results = '';
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
results = results + chunk;
//TODO
});
res.on('end', function () {
//TODO
});
});
req.on('error', function(e) {
//TODO
});
req.end();
Obviously there is no periodic checking of Scope
whether there is any change in the Objects attached to it. Not all the objects attached to scope are watched . Scope prototypically maintains a $$watchers . Scope
only iterates through this $$watchers
when $digest
is called .
Angular adds a watcher to the $$watchers for each of these
- {{expression}} — In your templates (and anywhere else where there’s an expression) or when we define ng-model.
- $scope.$watch(‘expression/function’) — In your JavaScript we can just attach a scope object for angular to watch.
$watch function takes in three parameters:
First one is a watcher function which just returns the object or we can just add an expression.
Second one is a listener function which will be called when there is a change in the object. All the things like DOM changes will be implemented in this function.
The third being an optional parameter which takes in a boolean . If its true , angular deep watches the object & if its false Angular just does a reference watching on the object. Rough Implementation of $watch looks like this
Scope.prototype.$watch = function(watchFn, listenerFn) {
var watcher = {
watchFn: watchFn,
listenerFn: listenerFn || function() { },
last: initWatchVal // initWatchVal is typically undefined
};
this.$$watchers.push(watcher); // pushing the Watcher Object to Watchers
};
There is an interesting thing in Angular called Digest Cycle. The $digest cycle starts as a result of a call to $scope.$digest(). Assume that you change a $scope model in a handler function through the ng-click directive. In that case AngularJS automatically triggers a $digest cycle by calling $digest().In addition to ng-click, there are several other built-in directives/services that let you change models (e.g. ng-model, $timeout, etc) and automatically trigger a $digest cycle. The rough implementation of $digest looks like this.
Scope.prototype.$digest = function() {
var dirty;
do {
dirty = this.$$digestOnce();
} while (dirty);
}
Scope.prototype.$$digestOnce = function() {
var self = this;
var newValue, oldValue, dirty;
_.forEach(this.$$watchers, function(watcher) {
newValue = watcher.watchFn(self);
oldValue = watcher.last; // It just remembers the last value for dirty checking
if (newValue !== oldValue) { //Dirty checking of References
// For Deep checking the object , code of Value
// based checking of Object should be implemented here
watcher.last = newValue;
watcher.listenerFn(newValue,
(oldValue === initWatchVal ? newValue : oldValue),
self);
dirty = true;
}
});
return dirty;
};
If we use JavaScript’s setTimeout() function to update a scope model, Angular has no way of knowing what you might change. In this case it’s our responsibility to call $apply() manually, which triggers a $digest cycle. Similarly, if you have a directive that sets up a DOM event listener and changes some models inside the handler function, you need to call $apply() to ensure the changes take effect. The big idea of $apply is that we can execute some code that isn't aware of Angular, that code may still change things on the scope. If we wrap that code in $apply , it will take care of calling $digest(). Rough implementation of $apply().
Scope.prototype.$apply = function(expr) {
try {
return this.$eval(expr); //Evaluating code in the context of Scope
} finally {
this.$digest();
}
};
SELECT PKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
PKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O1.SCHEMA_ID)),
PKTABLE_NAME = CONVERT(SYSNAME,O1.NAME),
PKCOLUMN_NAME = CONVERT(SYSNAME,C1.NAME),
FKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
FKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O2.SCHEMA_ID)),
FKTABLE_NAME = CONVERT(SYSNAME,O2.NAME),
FKCOLUMN_NAME = CONVERT(SYSNAME,C2.NAME),
-- Force the column to be non-nullable (see SQL BU 325751)
--KEY_SEQ = isnull(convert(smallint,k.constraint_column_id), sysconv(smallint,0)),
UPDATE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsUpdateCascade')
WHEN 1 THEN 0
ELSE 1
END),
DELETE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsDeleteCascade')
WHEN 1 THEN 0
ELSE 1
END),
FK_NAME = CONVERT(SYSNAME,OBJECT_NAME(F.OBJECT_ID)),
PK_NAME = CONVERT(SYSNAME,I.NAME),
DEFERRABILITY = CONVERT(SMALLINT,7) -- SQL_NOT_DEFERRABLE
FROM SYS.ALL_OBJECTS O1,
SYS.ALL_OBJECTS O2,
SYS.ALL_COLUMNS C1,
SYS.ALL_COLUMNS C2,
SYS.FOREIGN_KEYS F
INNER JOIN SYS.FOREIGN_KEY_COLUMNS K
ON (K.CONSTRAINT_OBJECT_ID = F.OBJECT_ID)
INNER JOIN SYS.INDEXES I
ON (F.REFERENCED_OBJECT_ID = I.OBJECT_ID
AND F.KEY_INDEX_ID = I.INDEX_ID)
WHERE O1.OBJECT_ID = F.REFERENCED_OBJECT_ID
AND O2.OBJECT_ID = F.PARENT_OBJECT_ID
AND C1.OBJECT_ID = F.REFERENCED_OBJECT_ID
AND C2.OBJECT_ID = F.PARENT_OBJECT_ID
AND C1.COLUMN_ID = K.REFERENCED_COLUMN_ID
AND C2.COLUMN_ID = K.PARENT_COLUMN_ID
You can also enable live-logging by setting the following in pytest.ini
or tox.ini
in your project root.
[pytest]
log_cli = True
Or specify it directly on cli
pytest -o log_cli=True
you can use -clean parameter while starting eclipse like
C:\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_24\bin" -clean
char a[]="string";
int toBeRemoved=2;
memmove(&a[toBeRemoved],&a[toBeRemoved+1],strlen(a)-toBeRemoved);
puts(a);
Try this . memmove will overlap it. Tested.
You can't focus on a div. You can only focus on an input element in that div. Also, you need to use element.focus() instead of display()
it's a bit late but...
your code will not work, because of list<FileInfo> lastUpdateFile = null;
and later lastUpdatedFile.Add(file);
so NullReference exception will be thrown.
Working version should be:
private List<FileInfo> GetLastUpdatedFileInDirectory(DirectoryInfo directoryInfo)
{
FileInfo[] files = directoryInfo.GetFiles();
List<FileInfo> lastUpdatedFile = new List<FileInfo>();
DateTime lastUpdate = DateTime.MinValue;
foreach (FileInfo file in files)
{
if (file.LastAccessTime > lastUpdate)
{
lastUpdatedFile.Add(file);
lastUpdate = file.LastAccessTime;
}
}
return lastUpdatedFile;
}
Thanks
use comma separated values in application.yml
ignoreFilenames: .DS_Store, .hg
java code for access
@Value("${ignoreFilenames}")
String[] ignoreFilenames
It is working ;)
Use this:
0?[1-9]|1[012]
To test a pattern as 07/2018 use this:
/^(0?[1-9]|1[012])\/([2-9][0-9]{3})$/
(Date range between 01/2000 to 12/9999 )
Use the response contained within the exception. Here is an example:
import boto3
from botocore.exceptions import ClientError
try:
iam = boto3.client('iam')
user = iam.create_user(UserName='fred')
print("Created user: %s" % user)
except ClientError as e:
if e.response['Error']['Code'] == 'EntityAlreadyExists':
print("User already exists")
else:
print("Unexpected error: %s" % e)
The response dict in the exception will contain the following:
['Error']['Code']
e.g. 'EntityAlreadyExists' or 'ValidationError'['ResponseMetadata']['HTTPStatusCode']
e.g. 400['ResponseMetadata']['RequestId']
e.g. 'd2b06652-88d7-11e5-99d0-812348583a35'['Error']['Message']
e.g. "An error occurred (EntityAlreadyExists) ..."['Error']['Type']
e.g. 'Sender'For more information see:
[Updated: 2018-03-07]
The AWS Python SDK has begun to expose service exceptions on clients (though not on resources) that you can explicitly catch, so it is now possible to write that code like this:
import botocore
import boto3
try:
iam = boto3.client('iam')
user = iam.create_user(UserName='fred')
print("Created user: %s" % user)
except iam.exceptions.EntityAlreadyExistsException:
print("User already exists")
except botocore.exceptions.ParamValidationError as e:
print("Parameter validation error: %s" % e)
except botocore.exceptions.ClientError as e:
print("Unexpected error: %s" % e)
Unfortunately, there is currently no documentation for these exceptions but you can get a list of them as follows:
import botocore
import boto3
dir(botocore.exceptions)
Note that you must import both botocore and boto3. If you only import botocore then you will find that botocore has no attribute named exceptions
. This is because the exceptions are dynamically populated into botocore by boto3.
You don't need to go to 64-bit to see something like this. Consider int32_t
on common 32-bit platforms. It might be typedef
'ed as int
or as a long
, but obviously only one of the two at a time. int
and long
are of course distinct types.
It's not hard to see that there is no workaround which makes int == int32_t == long
on 32-bit systems. For the same reason, there's no way to make long == int64_t == long long
on 64-bit systems.
If you could, the possible consequences would be rather painful for code that overloaded foo(int)
, foo(long)
and foo(long long)
- suddenly they'd have two definitions for the same overload?!
The correct solution is that your template code usually should not be relying on a precise type, but on the properties of that type. The whole same_type
logic could still be OK for specific cases:
long foo(long x);
std::tr1::disable_if(same_type(int64_t, long), int64_t)::type foo(int64_t);
I.e., the overload foo(int64_t)
is not defined when it's exactly the same as foo(long)
.
[edit] With C++11, we now have a standard way to write this:
long foo(long x);
std::enable_if<!std::is_same<int64_t, long>::value, int64_t>::type foo(int64_t);
[edit] Or C++20
long foo(long x);
int64_t foo(int64_t) requires (!std::is_same_v<int64_t, long>);
You can use the moment libraries local data functions.
Code:
moment.localeData().ordinal(1)
//1st
I've used it in the case where something may have gone awry in my @Before method.
public Object obj;
@Before
public void setUp() {
// Do some set up
obj = new Object();
}
@Test
public void testObjectManipulation() {
if(obj == null) {
fail("obj should not be null");
}
// Do some other valuable testing
}
have you tried display:inline-block;
?
You should be able to do this quite easily:
SELECT *
FROM WebPageContent
WHERE data.value('(/PageContent/Text)[1]', 'varchar(100)') LIKE 'XYZ%'
The .value
method gives you the actual value, and you can define that to be returned as a VARCHAR(), which you can then check with a LIKE statement.
Mind you, this isn't going to be awfully fast. So if you have certain fields in your XML that you need to inspect a lot, you could:
With this, you'd basically "extract" a certain portion of the XML into a computed field, make it persisted, and then you can search very efficiently on it (heck: you can even INDEX that field!).
Marc
In JSF 2.2 it's possible to use passthrough elements:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsf="http://xmlns.jcp.org/jsf">
...
<div jsf:id="id1" />
...
</html>
The requirement is to have at least one attribute in the element using jsf namespace.
I think what you are trying to do is to wrap long text without spaces.
look at this :Hyphenator.js and it's demo.
Yeah you can't access your drive folder from you android phone or emulator because your computer and android are two different OS.I would go for res folder of android because it has good resources management methods. Until and unless you have very good reason to put you file in assets folder. Instead You can do this
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.yourfile);
byte[] b = new byte[in_s.available()];
in_s.read(b);
String str = new String(b);
} catch (Exception e) {
Log.e(LOG_TAG, "File Reading Error", e);
}
You can give the background image in css :
#canvas { background:url(example.jpg) }
it will show you canvas back ground image
If you need to load a file that's relative to some directory where you already are (like in the current directory), here's an easy solution:
File f;
if (System.getProperty("sun.arch.data.model").equals("32")) {
// 32-bit JVM
f = new File("mylibfile32.so");
} else {
// 64-bit JVM
f = new File("mylibfile64.so");
}
System.load(f.getAbsolutePath());
SSLHandshakeException can be resolved 2 ways.
Incorporating SSL
Get the SSL (by asking the source system administrator, can also be downloaded by openssl command, or any browsers downloads the certificates)
Add the certificate into truststore (cacerts) located at JRE/lib/security
provide the truststore location in vm arguments as "-Djavax.net.ssl.trustStore="
Ignoring SSL
For this #2, please visit my other answer on another stackoverflow website: How to ingore SSL verification Ignore SSL Certificate Errors with Java
If you want your container to have it's own virtual ethernet socket (with it's own MAC address), iptables, then use the Macvlan driver. This may be necessary to route traffic out to your/ISPs router.
https://docs.docker.com/engine/userguide/networking/get-started-macvlan
Since Redis 2.6, lua is supported, you can get number of wildcard keys like this
eval "return #redis.call('keys', 'prefix-*')" 0
see eval command
You are making sense, but you seem to misunderstand the concept of sending emails.
HTML is parsed on the client side, while the e-mail needs to be sent from the server. You cannot do it in pure HTML. I would suggest writing a PHP script that will deal with the email sending for you.
Basically, instead of the MAILTO, your form's action will need to point to that PHP script. In the script, retrieve the values passed by the form (in PHP, they are available through the $_POST
superglobal) and use the email sending function (mail()
).
Of course, this can be done in other server-side languages as well. I'm giving a PHP solution because PHP is the language I work with.
A simple example code:
form.html:
<form method="post" action="email.php">
<input type="text" name="subject" /><br />
<textarea name="message"></textarea>
</form>
email.php:
<?php
mail('[email protected]', $_POST['subject'], $_POST['message']);
?>
<p>Your email has been sent.</p>
Of course, the script should contain some safety measures, such as checking whether the $_POST valies are at all available, as well as additional email headers (sender's email, for instance), perhaps a way to deal with character encoding - but that's too complex for a quick example ;).
Another scenario where this occurs is when you have a base class and one or more subclasses, where at least one of the subclasses introduce extra properties:
class Folder {
[key]
public string Id { get; set; }
public string Name { get; set; }
}
// Adds no props, but comes from a different view in the db to Folder:
class SomeKindOfFolder: Folder {
}
// Adds some props, but comes from a different view in the db to Folder:
class AnotherKindOfFolder: Folder {
public string FolderAttributes { get; set; }
}
If these are mapped in the DbContext
like below, the "'Invalid column name 'Discriminator'" error occurs when any type based on Folder
base type is accessed:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Folder>().ToTable("All_Folders");
modelBuilder.Entity<SomeKindOfFolder>().ToTable("Some_Kind_Of_Folders");
modelBuilder.Entity<AnotherKindOfFolder>().ToTable("Another_Kind_Of_Folders");
}
I found that to fix the issue, we extract the props of Folder
to a base class (which is not mapped in OnModelCreating()
) like so - OnModelCreating
should be unchanged:
class FolderBase {
[key]
public string Id { get; set; }
public string Name { get; set; }
}
class Folder: FolderBase {
}
class SomeKindOfFolder: FolderBase {
}
class AnotherKindOfFolder: FolderBase {
public string FolderAttributes { get; set; }
}
This eliminates the issue, but I don't know why!
found this:
-- Print contents of `tbl`, with indentation.
-- `indent` sets the initial level of indentation.
function tprint (tbl, indent)
if not indent then indent = 0 end
for k, v in pairs(tbl) do
formatting = string.rep(" ", indent) .. k .. ": "
if type(v) == "table" then
print(formatting)
tprint(v, indent+1)
elseif type(v) == 'boolean' then
print(formatting .. tostring(v))
else
print(formatting .. v)
end
end
end
from here https://gist.github.com/ripter/4270799
works pretty good for me...
Output buffering is used by PHP to improve performance and to perform a few tricks.
You can have PHP store all output into a buffer and output all of it at once improving network performance.
You can access the buffer content without sending it back to browser in certain situations.
Consider this example:
<?php
ob_start( );
phpinfo( );
$output = ob_get_clean( );
?>
The above example captures the output into a variable instead of sending it to the browser. output_buffering is turned off by default.
Consider this example:
<?php
ob_start( );
echo "Hello World";
if ( $some_error )
{
header( "Location: error.php" );
exit( 0 );
}
?>
Consider adding the switch /D_USE_MATH_DEFINES to your compilation command line, or to define the macro in the project settings. This will drag the symbol to all reachable dark corners of include and source files leaving your source clean for multiple platforms. If you set it globally for the whole project, you will not forget it later in a new file(s).
round(number, 1)