On redhat7 :
yum install gtk2 libXtst xorg-x11-fonts-Type1
did the job, because of a swt dependency.
found here
Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
So, you can add your parameters as BasicNameValuePair
.
An alternative is to use (Http)URLConnection
. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection
javadoc.
You could use AsyncTask
, you'll have to customize to fit your needs, but something like the following
Async task has three primary methods:
onPreExecute()
- most commonly used for setting up and starting a progress dialog
doInBackground()
- Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).
onPostExecute()
- Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.First we will start the class, initialize a String
to hold the results outside of the methods but inside the class, then run the onPreExecute()
method setting up a simple progress dialog.
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
Then we need to set up the connection and how we want to handle the response:
@Override
protected Void doInBackground(String... params) {
String url_select = "http://yoururlhere.com";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
} // protected Void doInBackground(String... params)
Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
for(i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String name = jObject.getString("name");
String tab1_text = jObject.getString("tab1_text");
int active = jObject.getInt("active");
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
I just ran across the need to close .dialog(s) with an out of element click. I have a page with a lot of info dialogs, so I needed something to handle them all. This is how I handled it:
$(document).ready(function () {
$(window).click(function (e) {
$(".dialogGroup").each(function () {
$(this).dialog('close');
})
});
$("#lostEffClick").click(function () {
event.stopPropagation();
$("#lostEffDialog").dialog("open");
};
});
On a Mac you can can select the text that you are after then press: cmd + ctrl + G
This will select every instance of your selected text within the same document. If you now start typing to replace your original highlighted text, you will replace all of the other occurrences at the same time.
Directly using scanf(3)
and its variants poses a number of problems. Typically, users and non-interactive use cases are defined in terms of lines of input. It's rare to see a case where, if enough objects are not found, more lines will solve the problem, yet that's the default mode for scanf. (If a user didn't know to enter a number on the first line, a second and third line will probably not help.)
At least if you fgets(3)
you know how many input lines your program will need, and you won't have any buffer overflows...
Assuming that you have a data frame called students
, you can select individual rows or columns using the bracket syntax, like this:
students[1,2]
would select row 1 and column 2, the result here would be a single cell.students[1,]
would select all of row 1, students[,2]
would select all of column 2.If you'd like to select multiple rows or columns, use a list of values, like this:
students[c(1,3,4),]
would select rows 1, 3 and 4, students[c("stu1", "stu2"),]
would select rows named stu1
and stu2
.Hope I could help.
Check for already existing primary key with different column. If yes, drop the primary key using:
ALTER TABLE Table1
DROP CONSTRAINT PK_Table1_Col1
GO
and then write your query as it is.
The answer to your original question
How to read a string one char at the time, and stop when you reach end of line?
is, in C++, very simply, namely: use getline. The link shows a simple example:
#include <iostream>
#include <string>
int main () {
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
Do you really want to do this in C? I wouldn't! The thing is, in C, you have to allocate the memory in which to place the characters you read in? How many characters? You don't know ahead of time. If you allocate too few characters, you will have to allocate a new buffer every time to realize you reading more characters than you made room for. If you over-allocate, you are wasting space.
C is a language for low-level programming. If you are new to programming and writing simple applications for reading files line-by-line, just use C++. It does all that memory allocation for you.
Your later questions regarding "\0"
and end-of-lines in general were answered by others and do apply to C as well as C++. But if you are using C, please remember that it's not just the end-of-line that matters, but memory allocation as well. And you will have to be careful not to overrun your buffer.
Here is how I resolved it.
It is not the most secure way however it solved my problem as security was not an issue on internal servers.
Create a new file say password.txt
and store the password for the server where the file will be pasted. Save this to a location on the host server.
scp -W location/password.txt copy_file_location paste_file_location
Cheers!
You can use Math.Round:
decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229
Or you can use ToString with the N3 numeric format.
string roundedNumber = number.ToString("N3");
EDIT: Since you don't want rounding, you can easily use Math.Truncate:
Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229
Jwt is a strict set of instructions for the issuing and validating of signed access tokens. The tokens contain claims that are used by an app to limit access to a user
OAuth2 on the other hand is not a protocol, its a delegated authorization framework. think very detailed guideline, for letting users and applications authorize specific permissions to other applications in both private and public settings. OpenID Connect which sits on top of OAUTH2 gives you Authentication and Authorization.it details how multiple different roles, users in your system, server side apps like an API, and clients such as websites or native mobile apps, can authenticate with each othe
Note oauth2 can work with jwt , flexible implementation, extandable to different applications
employees.ToList().Foreach(u=> { u.SomeProperty = null; u.OtherProperty = null; });
Notice that I used semicolons after each set statement
that is -->
u.SomeProperty = null;
u.OtherProperty = null;
I hope this will definitely solve your problem.
sed
can perform text transformations on input stream from a file or from a pipeline. Example:
echo 'C:\foo\bar.xml' | sed 's/\\/\//g'
gets
C:/foo/bar.xml
from collections import Counter
most_common,num_most_common = Counter(L).most_common(1)[0] # 4, 6 times
For older Python versions (< 2.7), you can use this recipe to create the Counter
class.
For some reason the responsive table in particular doesn't behave as it should. You can patch it by getting rid of display:block;
.table-responsive {
display: table;
}
I may file a bug report.
Edit:
I use Hibernate 5.2 and @Temporal
is not required anymore.
java.util.date, sql.date, time.LocalDate are stored into DB with appropriate datatype as Date/timestamp.
You should be using Maven, as the structure is standardized. To do that (Once you have created your Maven project in Netbeans, just
As long as the project has no errors, I usually get none transferring to eclipse. This works for Maven web projects and regular projects.
Promises and Observables both handle the asynchronous call only.
Here are the differences between them:
Observable
Promise
Emits only a single value at a time
Calls the services without .then and .catch
Cannot be canceled
Does not provide any operators
Use this query:
SELECT object_definition(object_id) AS [Proc Definition]
FROM sys.objects
WHERE type='P'
The way to determine the coordinates depends on what element you're working with. For circle
s for example, the cx
and cy
attributes determine the center position. In addition, you may have a translation
applied through the transform
attribute which changes the reference point of any coordinates.
Most of the ways used in general to get screen coordinates won't work for SVGs. In addition, you may not want absolute coordinates if the line you want to draw is in the same container as the elements it connects.
Edit:
In your particular code, it's quite difficult to get the position of the node because its determined by a translation of the parent element. So you need to get the transform attribute of the parent node and extract the translation from that.
d3.transform(d3.select(this.parentNode).attr("transform")).translate
Working jsfiddle here.
Eliminate discovery exceptions from your inquiries; go to the output Window (Ctrl-Alt-O), then switch the show output from dropdown (Shift-Alt-S) to Tests and make sure there are no discovery exceptions
Test|Test settings|Default processor architecture can help if your tests are x86/x64 specific and discovery is triggering bittedness-related exceptions, i.e. not AnyCpu
As suggested in this answer(upvote it if the technique helps) running the desktop console runner (instructions) can be a good cross check to eliminate other possibilities, e.g. mangled config files:-
packages\xunit.runner.console.2.2.0\tools\xunit.console <tests.dll>
NOTE The xunit.runner.console
package is deprecated - when you get stuff working in VS, you'll be able to have dotnet test
run them in CI contexts too
Go read the documentation - it's comprehensive, up to date, includes troubleshooting info and takes PRs:-
Important note: If you've previously installed the xUnit.net Visual Studio Runner VSIX (Extension), you must uninstall it first. The Visual Studio runner is only distributed via NuGet now. To remove it, to go Tools > Extensions and Updates. Scroll to the bottom of the list, and if xUnit.net is installed, uninstall it. This will force you to restart Visual Studio.
If you're having problems discovering or running tests, you may be a victim of a corrupted runner cache inside Visual Studio. To clear this cache, shut down all instances of Visual Studio, then delete the folder
%TEMP%\VisualStudioTestExplorerExtensions
. Also make sure your project is only linked against a single version of the Visual Studio runner NuGet package (xunit.runner.visualstudio
).
The following steps worked for me:
(Only if you suspect there is a serious mess on your machine - in general the more common case is that the visual studio integration is simply not installed yet)
Do the DEL %TEMP%\VisualStudioTestExplorerExtensions
as advised :-
PS> del $env:TEMP\VisualStudioTestExplorerExtensions
Install the NuGet Package xunit.runner.visualstudio
in all test projects
Paket:
.paket\paket add nuget xunit.runner.visualstudio -i
You need to end up with the following in your paket.dependencies
:
nuget xunit.runner.visualstudio version_in_path: true
Note the version_in_path: true
bit is important
Nuget: Go to Package Manager Console (Alt-T,N,O) and
Install-Package xunit.runner.visualstudio)
Rebuild to make sure xunit.runner
ends up in the output dir
Close Test Explorer <- this was the missing bit for me
Re-open Test Explorer (Alt-S,W,T)
Run All tests (Ctrl R, A)
I finally solve this issue. These are the detail of my env:
Version of Python to install: 3.6.8
OS: Ubuntu 16.04.6 LTS
Root access: No
Some people suggest to install libssl-dev
, but it did not work for me. I follow this link and I fixed it!
In short, I download, extract, build, and install OpenSSL (openssl-1.1.1b.tar.gz). Then, I modify .bashrc
file follow this link.
Next, I download and extract Python-3.6.8.tgz. I edit Modules/Setup.dist to modify SSL path (lines around #211). I did ./configure --prefix=$HOME/opt/python-3.6.8
, make
and make install
. Last, I modify my .bashrc
. Notice that I do not include --enable-optimizations
in ./configure
.
JavaScript is case-sensitive. The b
in getElementbyId
should be capitalized.
var content = document.getElementById("edit").innerHTML;
try something like this
#vote_links a
will catch all ids inside vote links div id ...
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(\'#vote_links a\').click(function() {// alert(\'vote clicked\');
var det = jQuery(this).get(0).id.split("-");// alert(jQuery(this).get(0).id);
var votes_id = det[0];
$("#about-button").css({
opacity: 0.3
});
$("#contact-button").css({
opacity: 0.3
});
$("#page-wrap div.button").click(function(){
Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.
One way to switch frames in tkinter
is to destroy the old frame then replace it with your new frame.
I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container
object and allows you to use any generic Frame
class.
# Multi-frame tkinter application v2.3
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Open page one",
command=lambda: master.switch_frame(PageOne)).pack()
tk.Button(self, text="Open page two",
command=lambda: master.switch_frame(PageTwo)).pack()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
class PageTwo(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
switch_frame()
works by accepting any Class object that implements Frame
. The function then creates a new frame to replace the old one.
_frame
if it exists, then replaces it with the new frame..pack()
, such as menubars, will be unaffected.tkinter.Frame
.v2.3
- Pack buttons and labels as they are initialized
v2.2
- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.
v2.1.1
- Remove type-hinting for backwards compatibility with Python 3.4.
v2.1
- Add type-hinting for `frame_class`.
v2.0
- Remove extraneous `container` frame.
- Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
- Frame switching is now done with `master.switch_frame()`.
v1.6
- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.
v1.5
- Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
- Initializing the frame before calling `.destroy()` results
in a smoother visual transition.
v1.4
- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
- Remove `new_frame` variable.
v1.3
- Rename `parent` to `master` for consistency with base `Frame` class.
v1.2
- Remove `main()` function.
v1.1
- Rename `frame` to `_frame`.
- Naming implies variable should be private.
- Create new frame before destroying old frame.
v1.0
- Initial version.
I went with a modification of @user1097431 's answer:
function menuPosition(){
// distance from top of footer to top of document
var footertotop = ($('.footer').position().top);
// distance user has scrolled from top, adjusted to take in height of bar (42 pixels inc. padding)
var scrolltop = $(document).scrollTop() + window.innerHeight;
// difference between the two
var difference = scrolltop-footertotop;
// if user has scrolled further than footer,
// pull sidebar up using a negative margin
if (scrolltop > footertotop) {
$('#categories-wrapper').css({
'bottom' : difference
});
}else{
$('#categories-wrapper').css({
'bottom' : 0
});
};
};
If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped. So what you can do is, send broadcast from onTaskRemoved
method of your service as follows:
Intent intent = new Intent("com.android.ServiceStopped");
sendBroadcast(intent);
and have an broadcast receiver which will again start a service. I have tried it. service restarts from all type of kills.
you can also use rdd
it can dump & restore a running redis server and allow filter/match/rename dumps keys
I have this function for this case ..
Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean
c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
Select Case Mid(c, x, 1)
Case ":": bNum = True
Case " ": Exit For
Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
End Select
Next
GetValue = val(nRet)
End Function
To fill cell BC .. (assumed that you check cell A1)
Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")
// dict is Dictionary<string, Foo>
Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);
// or in C# 3.0:
var foos = dict.Values.ToArray();
To anyone who came across this question who are using SQL Server Database and still having an exception thrown even after adding the following annotation on the int primary key
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
Please check your SQL, make sure your the primary key has 'IDENTITY(startValue, increment)' next to it,
CREATE TABLE [dbo].[User]
(
[Id] INT IDENTITY(1,1) NOT NULL PRIMARY KEY
)
This will make the database increments the id every time a new row is added, with a starting value of 1 and increments of 1.
I accidentally overlooked that in my SQL which cost me an hour of my life, so hopefully this helps someone!!!
I was struggling to get this right using the scripts provided above and some other scripts especially when files and folder names had newline or spaces.
Finally stumbled on tmpreaper and it has been worked pretty well for us so far.
tmpreaper -t 5d ~/Downloads
tmpreaper --protect '*.c' -t 5h ~/my_prg
Original Source link
Has features like test, which checks the directories recursively and lists them. Ability to delete symlinks, files or directories and also the protection mode for a certain pattern while deleting
For me / had to be in a new line.
For example
create type emp_t;/
didn't work
but
create type emp_t;
/
worked.
You could also do it via jQuery:
$('#x_Created').addClass(date);
Just install the latest version from nondefault repository:
$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-4.7-dev
What about the official JDBC 4.0 compatible JDBC driver from Microsoft?
Use glutStrokeCharacter(GLUT_STROKE_ROMAN, myCharString)
.
An example: A STAR WARS SCROLLER.
#include <windows.h>
#include <string.h>
#include <GL\glut.h>
#include <iostream.h>
#include <fstream.h>
GLfloat UpwardsScrollVelocity = -10.0;
float view=20.0;
char quote[6][80];
int numberOfQuotes=0,i;
//*********************************************
//* glutIdleFunc(timeTick); *
//*********************************************
void timeTick(void)
{
if (UpwardsScrollVelocity< -600)
view-=0.000011;
if(view < 0) {view=20; UpwardsScrollVelocity = -10.0;}
// exit(0);
UpwardsScrollVelocity -= 0.015;
glutPostRedisplay();
}
//*********************************************
//* printToConsoleWindow() *
//*********************************************
void printToConsoleWindow()
{
int l,lenghOfQuote, i;
for( l=0;l<numberOfQuotes;l++)
{
lenghOfQuote = (int)strlen(quote[l]);
for (i = 0; i < lenghOfQuote; i++)
{
//cout<<quote[l][i];
}
//out<<endl;
}
}
//*********************************************
//* RenderToDisplay() *
//*********************************************
void RenderToDisplay()
{
int l,lenghOfQuote, i;
glTranslatef(0.0, -100, UpwardsScrollVelocity);
glRotatef(-20, 1.0, 0.0, 0.0);
glScalef(0.1, 0.1, 0.1);
for( l=0;l<numberOfQuotes;l++)
{
lenghOfQuote = (int)strlen(quote[l]);
glPushMatrix();
glTranslatef(-(lenghOfQuote*37), -(l*200), 0.0);
for (i = 0; i < lenghOfQuote; i++)
{
glColor3f((UpwardsScrollVelocity/10)+300+(l*10),(UpwardsScrollVelocity/10)+300+(l*10),0.0);
glutStrokeCharacter(GLUT_STROKE_ROMAN, quote[l][i]);
}
glPopMatrix();
}
}
//*********************************************
//* glutDisplayFunc(myDisplayFunction); *
//*********************************************
void myDisplayFunction(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluLookAt(0.0, 30.0, 100.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
RenderToDisplay();
glutSwapBuffers();
}
//*********************************************
//* glutReshapeFunc(reshape); *
//*********************************************
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, 1.0, 1.0, 3200);
glMatrixMode(GL_MODELVIEW);
}
//*********************************************
//* int main() *
//*********************************************
int main()
{
strcpy(quote[0],"Luke, I am your father!.");
strcpy(quote[1],"Obi-Wan has taught you well. ");
strcpy(quote[2],"The force is strong with this one. ");
strcpy(quote[3],"Alert all commands. Calculate every possible destination along their last known trajectory. ");
strcpy(quote[4],"The force is with you, young Skywalker, but you are not a Jedi yet.");
numberOfQuotes=5;
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 400);
glutCreateWindow("StarWars scroller");
glClearColor(0.0, 0.0, 0.0, 1.0);
glLineWidth(3);
glutDisplayFunc(myDisplayFunction);
glutReshapeFunc(reshape);
glutIdleFunc(timeTick);
glutMainLoop();
return 0;
}
You can use the following command to update the DATA PUMP DIRECTORY path,
create or replace directory DATA_PUMP_DIR as '/u01/app/oracle/admin/MYDB/dpdump/';
For me data path correction was required as I have restored the my database from production to test environment.
Same command can be used to create a new DATA PUMP DIRECTORY
name
and path
.
I don't think this would be possible to do across all browsers.
W3Schools reports that the option events exist in all browsers, but after setting up this test demo. I can only get it to work for Firefox (not Chrome or IE), I haven't tested it on other browsers.
Firefox also allows mouseenter and mouseleave but this is not reported on the w3schools page.
Update: Honestly, from looking at the example code you provided, I wouldn't even use a select box. I think it would look nicer with a slider. I've updated your demo. I had to make a few minor changes to your ratings object (adding a level number) and the safesurf tab. But I left pretty much everything else intact.
For simple code, may be i think
import os
os.system('youtube-dl [OPTIONS] URL [URL...]')
Above is just running command line inside python.
Other is mentioned in the documentation Using youtube-dl on python Here is the way
from __future__ import unicode_literals
import youtube_dl
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])
The solution in UIKeyboardTypeNumberPad and missing return key works great but only if there are no other non-number pad text fields on the screen.
I took that code and turned it into an UIViewController that you can simply subclass to make number pads work. You will need to get the icons from the above link.
NumberPadViewController.h:
#import <UIKit/UIKit.h>
@interface NumberPadViewController : UIViewController {
UIImage *numberPadDoneImageNormal;
UIImage *numberPadDoneImageHighlighted;
UIButton *numberPadDoneButton;
}
@property (nonatomic, retain) UIImage *numberPadDoneImageNormal;
@property (nonatomic, retain) UIImage *numberPadDoneImageHighlighted;
@property (nonatomic, retain) UIButton *numberPadDoneButton;
- (IBAction)numberPadDoneButton:(id)sender;
@end
and NumberPadViewController.m:
#import "NumberPadViewController.h"
@implementation NumberPadViewController
@synthesize numberPadDoneImageNormal;
@synthesize numberPadDoneImageHighlighted;
@synthesize numberPadDoneButton;
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
if ([super initWithNibName:nibName bundle:nibBundle] == nil)
return nil;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
self.numberPadDoneImageNormal = [UIImage imageNamed:@"DoneUp3.png"];
self.numberPadDoneImageHighlighted = [UIImage imageNamed:@"DoneDown3.png"];
} else {
self.numberPadDoneImageNormal = [UIImage imageNamed:@"DoneUp.png"];
self.numberPadDoneImageHighlighted = [UIImage imageNamed:@"DoneDown.png"];
}
return self;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Add listener for keyboard display events
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
} else {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
}
// Add listener for all text fields starting to be edited
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textFieldDidBeginEditing:)
name:UITextFieldTextDidBeginEditingNotification
object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardDidShowNotification
object:nil];
} else {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
}
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UITextFieldTextDidBeginEditingNotification
object:nil];
[super viewWillDisappear:animated];
}
- (UIView *)findFirstResponderUnder:(UIView *)root {
if (root.isFirstResponder)
return root;
for (UIView *subView in root.subviews) {
UIView *firstResponder = [self findFirstResponderUnder:subView];
if (firstResponder != nil)
return firstResponder;
}
return nil;
}
- (UITextField *)findFirstResponderTextField {
UIResponder *firstResponder = [self findFirstResponderUnder:[self.view window]];
if (![firstResponder isKindOfClass:[UITextField class]])
return nil;
return (UITextField *)firstResponder;
}
- (void)updateKeyboardButtonFor:(UITextField *)textField {
// Remove any previous button
[self.numberPadDoneButton removeFromSuperview];
self.numberPadDoneButton = nil;
// Does the text field use a number pad?
if (textField.keyboardType != UIKeyboardTypeNumberPad)
return;
// If there's no keyboard yet, don't do anything
if ([[[UIApplication sharedApplication] windows] count] < 2)
return;
UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
// Create new custom button
self.numberPadDoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.numberPadDoneButton.frame = CGRectMake(0, 163, 106, 53);
self.numberPadDoneButton.adjustsImageWhenHighlighted = FALSE;
[self.numberPadDoneButton setImage:self.numberPadDoneImageNormal forState:UIControlStateNormal];
[self.numberPadDoneButton setImage:self.numberPadDoneImageHighlighted forState:UIControlStateHighlighted];
[self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];
// Locate keyboard view and add button
NSString *keyboardPrefix = [[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2 ? @"<UIPeripheralHost" : @"<UIKeyboard";
for (UIView *subView in keyboardWindow.subviews) {
if ([[subView description] hasPrefix:keyboardPrefix]) {
[subView addSubview:self.numberPadDoneButton];
[self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];
break;
}
}
}
- (void)textFieldDidBeginEditing:(NSNotification *)note {
[self updateKeyboardButtonFor:[note object]];
}
- (void)keyboardWillShow:(NSNotification *)note {
[self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}
- (void)keyboardDidShow:(NSNotification *)note {
[self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}
- (IBAction)numberPadDoneButton:(id)sender {
UITextField *textField = [self findFirstResponderTextField];
[textField resignFirstResponder];
}
- (void)dealloc {
[numberPadDoneImageNormal release];
[numberPadDoneImageHighlighted release];
[numberPadDoneButton release];
[super dealloc];
}
@end
Enjoy.
You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
SELECT TOP 25 amount,
(SELECT SUM(amount)
FROM time_detail b
WHERE b.time_detail_id <= a.time_detail_id) AS Total FROM time_detail a
You can also use the ROW_NUMBER() function and a temp table to create an arbitrary column to use in the comparison on the inner SELECT statement.
You can use fetch optionally with await-try-catch
let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});
async function SavePhoto(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
const ctrl = new AbortController() // timeout
setTimeout(() => ctrl.abort(), 5000);
try {
let r = await fetch('/upload/image',
{method: "POST", body: formData, signal: ctrl.signal});
console.log('HTTP response code:',r.status);
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
_x000D_
Old school approach - xhr
let photo = document.getElementById("image-file").files[0]; // file from input
let req = new XMLHttpRequest();
let formData = new FormData();
formData.append("photo", photo);
req.open("POST", '/upload/image');
req.send(formData);
function SavePhoto(e)
{
let user = { name:'john', age:34 };
let xhr = new XMLHttpRequest();
let formData = new FormData();
let photo = e.files[0];
formData.append("user", JSON.stringify(user));
formData.append("photo", photo);
xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
xhr.timeout = 5000;
xhr.open("POST", '/upload/image');
xhr.send(formData);
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
_x000D_
SUMMARY
filename
formData parameter.Content-Type
to multipart/form-data
- this will be set automatically by browser./upload/image
you can use full address like http://.../upload/image
.multiple
attribute: <input multiple type=... />
, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];
... formData.append("photo2", photo2);
)let user = {name:'john', age:34}
in this way: formData.append("user", JSON.stringify(user));
fetch
using AbortController
, for old approach by xhr.timeout= milisec
Are you getting this value from a database? If so, consider formatting it in the database (use date_format
in mysql, for example). If not, exploding the value may be the best bet, since strtotime just doesn't seem to appreciate dd/mm/yyyy values.
user: root
password: [blank]
XAMPP v3.2.2
I have updated macOS to 10.13.4 and it works.
I had this issue. The security settings in the ControlPanel seem to be user specific. Try running it as the user you are actually running your browser as (you are not browsing as root!??) and setting the security level to Medium there. - For me, that did it.
For Angular 1.2.0rc1+ you need to add a resourceUrlWhitelist.
1.2: release version they added a escapeForRegexp function so you no longer have to escape the strings. You can just add the url directly
'http://sub*.assets.example.com/**'
make sure to add ** for sub folders. Here is a working jsbin for 1.2: http://jsbin.com/olavok/145/edit
1.2.0rc: If you are still on a rc version, the Angular 1.2.0rc1 the solution looks like:
.config(['$sceDelegateProvider', function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist(['self', /^https?:\/\/(cdn\.)?yourdomain.com/]);
}])
Here is a jsbin example where it works for 1.2.0rc1: http://jsbin.com/olavok/144/edit
Pre 1.2: For older versions (ref http://better-inter.net/enabling-cors-in-angular-js/) you need to add the following 2 lines to your config:
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
Here is a jsbin example where it works for pre 1.2 versions: http://jsbin.com/olavok/11/edit
I was running into the same issue but was able to package all dependencies into my jar file using the Maven Shade Plugin
$('input[type="submit"]').click(function(){
$(this).css('color','red');
});
Use class, Demo:- http://jsfiddle.net/BX6Df/
$('input[type="submit"]').click(function(){
$(this).addClass('red');
});
if you want to toggle the color each click, you can try this:- http://jsfiddle.net/SMNks/
$('input[type="submit"]').click(function(){
$(this).toggleClass('red');
});
.red
{
background-color:red;
}
Updated answer for your comment.
$('input[type="submit"]').click(function(){
$('input[type="submit"].red').removeClass('red')
$(this).addClass('red');
});
In case it helps, this seems to be easier in the latest Chrome (47.0.2526.106):
Inspect element and then click on the three white dots in the left gutter:
I found a solution for this problem. The issue I described in my question occured basically due to the incompatibility of the Microsoft.Jet.OLEDB.4.0 driver in 64 bit OS.
So if we are using Microsoft.Jet.OLEDB.4.0 driver in a 64 bit server, we have to force our application to build in in 32 bit mode (This is the answer I found when I did an extensive search for this known issue) and that causes other part of my code to break.
Fortunately, now Microsoft has released a 64 bit compatible 2010 Office System Driver which can be used as replacement for the traditional Microsoft.Jet.OLEDB.4.0 driver. It works both in 32 bit as well as 64 bit servers. I have used it for Excel file manipulation and it worked fine for me in both the environments. But this driver is in BETA.
You can download this driver from Microsoft Access Database Engine 2010 Redistributable
In my case the problem was I was using Virtual environment
which didn't have access to global site-packages. Thus, the interpreter was not aware of the newly installed packages.
To resolve the issue, just edit or recreate your virtual interpreter and tick the Inherit global site-packages
option.
You could do this using SUMIF
. This allows you to SUM a value in a cell IF a value in another cell meets the specified criteria. Here's an example:
- A B
1 100 YES
2 100 YES
3 100 NO
Using the formula: =SUMIF(B1:B3, "YES", A1:A3)
, you will get the result of 200
.
Here's a screenshot of a working example I just did in Excel:
interface
with a Singleton class, but a class's static methods (or e.g. a C# static class
) cannot.You've just published that private key, so now the whole world knows what it is. Hopefully that was just for testing.
EDIT: Others have noted that the openssl text header of the published key, -----BEGIN RSA PRIVATE KEY-----, indicates that it is PKCS#1. However, the actual Base64 contents of the key in question is PKCS#8. Evidently the OP copy and pasted the header and trailer of a PKCS#1 key onto the PKCS#8 key for some unknown reason. The sample code I've provided below works with PKCS#8 private keys.
Here is some code that will create the private key from that data. You'll have to replace the Base64 decoding with your IBM Base64 decoder.
public class RSAToy {
private static final String BEGIN_RSA_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n"
+ "MIIEuwIBADAN ...skipped the rest\n"
// + ...
// + ... skipped the rest
// + ...
+ "-----END RSA PRIVATE KEY-----";
public static void main(String[] args) throws Exception {
// Remove the first and last lines
String privKeyPEM = BEGIN_RSA_PRIVATE_KEY.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
System.out.println(privKeyPEM);
// Base64 decode the data
byte [] encoded = Base64.decode(privKeyPEM);
// PKCS8 decode the encoded RSA private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
// Display the results
System.out.println(privKey);
}
}
The top answers are correct. Please check them direct in MySQL CLI first. If this fixes the problem there, you may want to have it working in Python3 just pass it to the MySQLdb.connect
as parameter
self.connection = MySQLdb.connect(
host=host, user=settings_DB.db_config['USER'],
port=port, passwd=settings_DB.db_config['PASSWORD'],
db=settings_DB.db_config['NAME'],
local_infile=True)
Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder
Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row
Events -> Action -> actionPerformed
You should see code like the following auto-generated
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
The jTable1
will have a DefaultTableModel
. You can add rows to the model with your data
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
String data1 = something1.getSomething();
String data2 = something2.getSomething();
String data3 = something3.getSomething();
String data4 = something4.getSomething();
Object[] row = { data1, data2, data3, data4 };
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
// clear the entries.
}
So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.
df[df['Value']==df['Value'].max()]
This will return the entire row with max value
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
There is a better solution in pandas 0.24:
with pd.ExcelWriter(path, mode='a') as writer:
s.to_excel(writer, sheet_name='another sheet', index=False)
before:
after:
so upgrade your pandas now:
pip install --upgrade pandas
You can use a lambda:
Collectors.toMap(p -> p.getLast(), Function.identity())
or, more concisely, you can use a method reference using ::
:
Collectors.toMap(Person::getLast, Function.identity())
and instead of Function.identity
, you can simply use the equivalent lambda:
Collectors.toMap(Person::getLast, p -> p)
If you use Netbeans you should get hints whenever an anonymous class can be replaced by a lambda.
I have joined the answer from Lucas and "ASP.NET MVC Helpers, Merging two object htmlAttributes together" and plus controllerName to following code:
// Sample usage in CSHTML
@Html.ActionImage("Edit",
"EditController"
new { id = MyId },
"~/Content/Images/Image.bmp",
new { width=108, height=129, alt="Edit" })
And the extension class for the code above:
using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;
namespace MVC.Extensions
{
public static class MvcHtmlStringExt
{
// Extension method
public static MvcHtmlString ActionImage(
this HtmlHelper html,
string action,
string controllerName,
object routeValues,
string imagePath,
object htmlAttributes)
{
//https://stackoverflow.com/questions/4896439/action-image-mvc3-razor
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
var dictAttributes = htmlAttributes.ToDictionary();
if (dictAttributes != null)
{
foreach (var attribute in dictAttributes)
{
imgBuilder.MergeAttribute(attribute.Key, attribute.Value.ToString(), true);
}
}
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
public static IDictionary<string, object> ToDictionary(this object data)
{
//https://stackoverflow.com/questions/6038255/asp-net-mvc-helpers-merging-two-object-htmlattributes-together
if (data == null) return null; // Or throw an ArgumentNullException if you want
BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (PropertyInfo property in
data.GetType().GetProperties(publicAttributes))
{
if (property.CanRead)
{
dictionary.Add(property.Name, property.GetValue(data, null));
}
}
return dictionary;
}
}
}
If you are using a mac and sublime text 3, this is what you do.
Go to your /Packages/User/
and create a file called Python.sublime-settings
.
Typically /Packages/User
is inside your ~/Library/Application Support/Sublime Text 3/Packages/User/Python.sublime-settings
if you are using mac os x.
Then you put this in the Python.sublime-settings
.
{
"tab_size": 4,
"translate_tabs_to_spaces": false
}
Credit goes to Mark Byer's answer, sublime text 3 docs and python style guide.
This answer is mostly for readers who had the same issue and stumble upon this and are using sublime text 3 on Mac OS X.
There isn't any reliable way to get the minimum/maximum without testing every value. You don't want to try a sort or anything like that, walking through the array is O(n), which is better than any sort algorithm can do in the general case.
Enqueue means to add an element, dequeue to remove an element.
var stackInput= []; // First stack
var stackOutput= []; // Second stack
// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
return stackInput.push(item);
}
function dequeue(stackInput, stackOutput) {
// Reverse the stack such that the first element of the output stack is the
// last element of the input stack. After that, pop the top of the output to
// get the first element that was ever pushed into the input stack
if (stackOutput.length <= 0) {
while(stackInput.length > 0) {
var elementToOutput = stackInput.pop();
stackOutput.push(elementToOutput);
}
}
return stackOutput.pop();
}
You can simply traverse the array in three nested loops and write their values to your file. For reading, you simply use the same exact loop construction. You will get the values in exactly the right order to fill your arrays correctly again.
Perhaps something like this for the first problem, you can simply access the columns by their names:
>>> df = pd.DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df[df['c']>.5][['b','e']]
b e
1 0.071146 0.132145
2 0.495152 0.420219
For the second problem:
>>> df[df['c']>.5][['b','e']].values
array([[ 0.07114556, 0.13214495],
[ 0.49515157, 0.42021946]])
var dict = File.ReadLines("test.txt")
.Where(line => !string.IsNullOrWhitespace(line))
.Select(line => line.Split(new char[] { '=' }, 2, 0))
.ToDictionary(parts => parts[0], parts => parts[1]);
or
enter code here
line="[email protected][email protected]";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);
ans:
tokens[0]=to
token[1][email protected][email protected]
The second sample assigns a unique ID to the element in question. This element can then be manipulated or accessed using DHTML.
The first one, on the other hand, sets a named location within the document, akin to a bookmark. Attached to an "anchor", it makes perfect sense.
There are a lot of very nice answers on this page and I googled for some more, but none of the answers ticked all the checkboxes on my wish list:
So I mixed the code of several examples, fixed the things that I needed and here is the result:
I used the following CSS and HTML:
/* Progress Tracker v2 */_x000D_
ol.progress[data-steps="2"] li { width: 49%; }_x000D_
ol.progress[data-steps="3"] li { width: 33%; }_x000D_
ol.progress[data-steps="4"] li { width: 24%; }_x000D_
ol.progress[data-steps="5"] li { width: 19%; }_x000D_
ol.progress[data-steps="6"] li { width: 16%; }_x000D_
ol.progress[data-steps="7"] li { width: 14%; }_x000D_
ol.progress[data-steps="8"] li { width: 12%; }_x000D_
ol.progress[data-steps="9"] li { width: 11%; }_x000D_
_x000D_
.progress {_x000D_
width: 100%;_x000D_
list-style: none;_x000D_
list-style-image: none;_x000D_
margin: 20px 0 20px 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.progress li {_x000D_
float: left;_x000D_
text-align: center;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.progress .name {_x000D_
display: block;_x000D_
vertical-align: bottom;_x000D_
text-align: center;_x000D_
margin-bottom: 1em;_x000D_
color: black;_x000D_
opacity: 0.3;_x000D_
}_x000D_
_x000D_
.progress .step {_x000D_
color: black;_x000D_
border: 3px solid silver;_x000D_
background-color: silver;_x000D_
border-radius: 50%;_x000D_
line-height: 1.2;_x000D_
width: 1.2em;_x000D_
height: 1.2em;_x000D_
display: inline-block;_x000D_
z-index: 0;_x000D_
}_x000D_
_x000D_
.progress .step span {_x000D_
opacity: 0.3;_x000D_
}_x000D_
_x000D_
.progress .active .name,_x000D_
.progress .active .step span {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.progress .step:before {_x000D_
content: "";_x000D_
display: block;_x000D_
background-color: silver;_x000D_
height: 0.4em;_x000D_
width: 50%;_x000D_
position: absolute;_x000D_
bottom: 0.6em;_x000D_
left: 0;_x000D_
z-index: -1;_x000D_
}_x000D_
_x000D_
.progress .step:after {_x000D_
content: "";_x000D_
display: block;_x000D_
background-color: silver;_x000D_
height: 0.4em;_x000D_
width: 50%;_x000D_
position: absolute;_x000D_
bottom: 0.6em;_x000D_
right: 0;_x000D_
z-index: -1;_x000D_
}_x000D_
_x000D_
.progress li:first-of-type .step:before {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.progress li:last-of-type .step:after {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.progress .done .step,_x000D_
.progress .done .step:before,_x000D_
.progress .done .step:after,_x000D_
.progress .active .step,_x000D_
.progress .active .step:before {_x000D_
background-color: yellowgreen;_x000D_
}_x000D_
_x000D_
.progress .done .step,_x000D_
.progress .active .step {_x000D_
border: 3px solid yellowgreen;_x000D_
}
_x000D_
<!-- Progress Tracker v2 -->_x000D_
<ol class="progress" data-steps="4">_x000D_
<li class="done">_x000D_
<span class="name">Foo</span>_x000D_
<span class="step"><span>1</span></span>_x000D_
</li>_x000D_
<li class="done">_x000D_
<span class="name">Bar</span>_x000D_
<span class="step"><span>2</span></span>_x000D_
</li>_x000D_
<li class="active">_x000D_
<span class="name">Baz</span>_x000D_
<span class="step"><span>3</span></span>_x000D_
</li>_x000D_
<li>_x000D_
<span class="name">Quux</span>_x000D_
<span class="step"><span>4</span></span>_x000D_
</li>_x000D_
</ol>
_x000D_
As can be seen in the example above, there are now two list item classes to take note of: active
and done
. Use class="active"
for the current step, use class="done"
for all steps before it.
Also note the data-steps="4"
in the ol
tag; set this to the total number of steps to apply the correct size to all list items.
Feel free to play around with the JSFiddle. Enjoy!
I copy the file "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5.1\Facades\system.runtime.dll" to bin folder of production server, this solve the problem.
if the other div is sibling/child, or any combination of, of the parent yes
.showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .hideme{_x000D_
display : none;_x000D_
}_x000D_
.showhim:hover ~ .hideme2{ _x000D_
display:none;_x000D_
}
_x000D_
<div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div> _x000D_
<div class="hideme">bye</div>_x000D_
</div>_x000D_
<div class="hideme2">bye bye</div>
_x000D_
Put your default.png in a UIImageView full screen as a subview on the top of your main view thus covering your other UI. Set a timer to remove it after x seconds (possibly with effects) now showing your application.
In my case I got this message because the branch was marked as 'Protected' in GitLab.
I tried many of the answers here, but none of them worked for me. Then I found an article about my problem here. I thought of sharing it here too.
Below are the steps taken in brief.
Just before your "Content of the letter" line, add \thispagestyle{fancy}
and it should show the headers you defined. (It worked for me.)
Here's the full document that I used to test:
\documentclass[12pt]{letter}
\usepackage{fontspec}% font selecting commands
\usepackage{xunicode}% unicode character macros
\usepackage{xltxtra} % some fixes/extras
% page counting, header/footer
\usepackage{fancyhdr}
\usepackage{lastpage}
\pagestyle{fancy}
\lhead{\footnotesize \parbox{11cm}{Draft 1} }
\lfoot{\footnotesize \parbox{11cm}{\textit{2}}}
\cfoot{}
\rhead{\footnotesize 3}
\rfoot{\footnotesize Page \thepage\ of \pageref{LastPage}}
\renewcommand{\headheight}{24pt}
\renewcommand{\footrulewidth}{0.4pt}
\usepackage{lipsum}% provides filler text
\begin{document}
\name{ Joe Laroo }
\signature{ Joe Laroo }
\begin{letter}{ To-Address }
\renewcommand{\today}{ February 16, 2009 }
\opening{ Opening }
\thispagestyle{fancy}% sets the current page style to 'fancy' -- must occur *after* \opening
\lipsum[1-10]% just dumps ten paragraphs of filler text
\closing{ Yours truly, }
\end{letter}
\end{document}
The \opening
command sets the page style to firstpage
or empty
, so you have to use \thispagestyle
after that command.
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
It does, in that a high-level functional PL (like OCaml, with classes, modules, etc.) certainly supersedes OOP imperative languages in type versatility and power of expression. The abstractions do not leak, you can express most of your ideas directly in the program. Therefore, yes, it does replace design patterns, most of which are ridiculously simplistic compared to functional patterns anyhow.
The global variable should be declare in config/initializers
directory
COLOURS = %w(white blue black red green)
If you want to handle IPV6 in standard notation there are 8 groups of 4 hex digits:
2001:0dc5:72a3:0000:0000:802e:3370:73E4
32 hex digits + 7 separators = 39 characters.
CAUTION: If you also want to hold IPV4 addresses mapped as IPV6 addresses, use 45 characters as @Deepak suggests.
You should run:
pip install protobuf
That will install Google protobuf and after that you can run that Python script.
As per this link.
I have another solution that makes this possible. It requires the client be running Javascript (which I think is a fair requirement these days).
Simply use an AJAX request on Page A to go and generate your invoice number and customer details in the background (your previous Page B), then once the request gets returned successfully with the correct information - simply complete the form submission over to your payment gateway (Page C).
This will achieve your result of the user only clicking one button and proceeding to the payment gateway. Below is some pseudocode
HTML:
<form id="paymentForm" method="post" action="https://example.com">
<input type="hidden" id="customInvoiceId" .... />
<input type="hidden" .... />
<input type="submit" id="submitButton" />
</form>
JS (using jQuery for convenience but trivial to make pure Javascript):
$('#submitButton').click(function(e) {
e.preventDefault(); //This will prevent form from submitting
//Do some stuff like build a list of things being purchased and customer details
$.getJSON('setupOrder.php', {listOfProducts: products, customerDetails: details }, function(data) {
if (!data.error) {
$('#paymentForm #customInvoiceID').val(data.id);
$('#paymentForm').submit(); //Send client to the payment processor
}
});
I have the solution to this problem enters (Start -> Run -> services.msc) are looking for the postgresql service once you localizas le das Properties---> login and you disable the account you have and what you leave as the local system account , save and restart the programs pgadmin3 and ready should operate.
Greeting from Colombia
I was able to achieve this using an immediately-invoked function and require statement.
const something = (() => (
condition ? require('something') : null
))();
if(something) {
something.doStuff();
}
Assume you want to replace symbols which are not digits or letters (and _ character as @Guffa correctly pointed):
string input = "Hello@Hello&Hello(Hello)";
string result = Regex.Replace(input, @"[^\w\d]", ",");
// Hello,Hello,Hello,Hello,
You can add another symbols which should not be replaced. E.g. if you want white space symbols to stay, then just add \s
to pattern: \[^\w\d\s]
You can use enumerate
and remove the values whose index matches the indices you want to remove:
indices = 0, 2
somelist = [i for j, i in enumerate(somelist) if j not in indices]
I had the same error in Laravel 5.2, turns out the namespace is incorrect in the model class definition.
I created my model using the command:
php artisan make:model myModel
By default, Laravel 5 creates the model under App
folder, but if you were to move the model to another folder like I did, you must change the the namespace inside the model definition too:
namespace App\ModelFolder;
To include the folder name when creating the model you could use (don't forget to use double back slashes):
php artisan make:model ModelFolder\\myModel
Also ran into this error message, but the root cause was of a different flavor from those referenced in the other answers here.
Generic answer: Make sure that once hibernate loads an entity, no code changes the primary key value in that object in any way. When hibernate flushes all changes back to the database, it throws this exception because the primary key changed. If you don't do it explicitly, look for places where this may happen unintentionally, perhaps on related entities that only have LAZY loading configured.
In my case, I am using a mapping framework (MapStruct) to update an entity. In the process, also other referenced entities were being updates as mapping frameworks tend to do that by default. I was later replacing the original entity with new one (in DB terms, changed the value of the foreign key to reference a different row in the related table), the primary key of the previously-referenced entity was already updated, and hibernate attempted to persist this update on flush.
So, weirdly excel imports a csv date in different ways. And, displays them differently depending on the format used in the csv file. Unfortunately the ISO 8061 format comes in as a string. Which prevents you from possibly reformatting the date yourself.
All the ones the do come in as a date... contain the entire information... but they format differently... if you don't like it you can choose a new format for the column in excel and it will work. (Note: you can tell it came in as a valid date/time as it will right justify... if it comes in as a string it will left justify)
Here are formats I tested:
"yyyy-MM-dd" shows up as a date of course when opened in excel. (also "MM/dd/yyyy" works)
"yyyy-MM-dd HH:mm:ss" default display format is "MM/dd/yyyy HH:mm" (date and time w/out seconds)
"yyyy-MM-dd HH:mm:ss.fff" default display format is "HH:mm:ss" (time only w/ seconds)
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
Sounds like you should have two copies on your server. A bare copy, that you can push/pull from, which your would push your changes when you're done, and then you would clone this into you web directory and set up a cronjob to update git pull from your web directory every day or so.
Right click on JSON file, select open, navigate to program you want open with(notepad). Consecutive opens automatically use notepad.
import torch.nn as nn
# a simple network
rand_net = nn.Sequential(nn.Linear(in_features, h_size),
nn.BatchNorm1d(h_size),
nn.ReLU(),
nn.Linear(h_size, h_size),
nn.BatchNorm1d(h_size),
nn.ReLU(),
nn.Linear(h_size, 1),
nn.ReLU())
# initialization function, first checks the module type,
# then applies the desired changes to the weights
def init_normal(m):
if type(m) == nn.Linear:
nn.init.uniform_(m.weight)
# use the modules apply function to recursively apply the initialization
rand_net.apply(init_normal)
Something no one seems to have noted yet is readability. Having…
CONVERT(SomeType,
SomeReallyLongExpression
+ ThatMayEvenSpan
+ MultipleLines
)
…may be easier to understand than…
CAST(SomeReallyLongExpression
+ ThatMayEvenSpan
+ MultipleLines
AS SomeType
)
I don't suggest you to use syntax like you did. AngularJs lets you to have different functionalities as you want (run
, config
, service
, factory
, etc..), which are more professional.In this function you don't even have to inject that by yourself like
MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
you can use it, as you know.
This is the best solution I could come up with, NOT using CSS 3. And it works great on Firefox, Chrome, and Internet Explorer as far as I can see.
Put a container div
and two children div
s at the same level, one for content, one for the background.
And using CSS, auto-size the background to fit the content and put the background actually in the back using z-index.
.container {_x000D_
position: relative;_x000D_
}_x000D_
.content {_x000D_
position: relative;_x000D_
color: White;_x000D_
z-index: 5;_x000D_
}_x000D_
.background {_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: Black;_x000D_
z-index: 1;_x000D_
/* These three lines are for transparency in all browsers. */_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";_x000D_
filter: alpha(opacity=50);_x000D_
opacity: .5;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="content">_x000D_
Here is the content._x000D_
<br/>Background should grow to fit._x000D_
</div>_x000D_
<div class="background"></div>_x000D_
</div>
_x000D_
Google has announced support for tensorflow on Windows. Please follow instructions at https://developers.googleblog.com/2016/11/tensorflow-0-12-adds-support-for-windows.html. Please note CUDA8.0 is needed for GPU installation.
If you have installed the 64-bit version of Python 3.5 (either from Python.org or Anaconda), you can install TensorFlow with a single command: C:> pip install tensorflow
For GPU support, if you have CUDA 8.0 installed, you can install the following package instead: C:> pip install tensorflow-gpu
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
Simple fix for me was
You don't need jQuery for that. Use regular javascript
var arr = new Array();
// or var arr = [];
arr.push('value1');
arr.push('value2');
Note: In javascript, you can also use Objects as Arrays, but still have access to the Array prototypes. This makes the object behave like an array:
var obj = new Object();
Array.prototype.push.call(obj, 'value');
will create an object that looks like:
{
0: 'value',
length: 1
}
You can access the vaules just like a normal array f.ex obj[0]
.
Pushing to the limits corner radius up to get a circle:
self.btnFoldButton.layer.cornerRadius = self.btnFoldButton.frame.height/2.0;
If button frame is an square it does not matter frame.height or frame.width. Otherwise use the largest of both ones.
Use
python python_script.py filename
and in your Python script
import sys
print sys.argv[1]
solution for swift 3 -
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
titleLabel.text = "change to red color"
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.red
This function will return the results of a query as an array of powershell objects so you can use them in filters and access columns easily:
function sql($sqlText, $database = "master", $server = ".")
{
$connection = new-object System.Data.SqlClient.SQLConnection("Data Source=$server;Integrated Security=SSPI;Initial Catalog=$database");
$cmd = new-object System.Data.SqlClient.SqlCommand($sqlText, $connection);
$connection.Open();
$reader = $cmd.ExecuteReader()
$results = @()
while ($reader.Read())
{
$row = @{}
for ($i = 0; $i -lt $reader.FieldCount; $i++)
{
$row[$reader.GetName($i)] = $reader.GetValue($i)
}
$results += new-object psobject -property $row
}
$connection.Close();
$results
}
Another problem, in the presence of a NAMESPACE, is that you are trying to run an unexported function from package foo.
For example (contrived, I know, but):
> mod <- prcomp(USArrests, scale = TRUE)
> plot.prcomp(mod)
Error: could not find function "plot.prcomp"
Firstly, you shouldn't be calling S3 methods directly, but lets assume plot.prcomp
was actually some useful internal function in package foo. To call such function if you know what you are doing requires the use of :::
. You also need to know the namespace in which the function is found. Using getAnywhere()
we find that the function is in package stats:
> getAnywhere(plot.prcomp)
A single object matching ‘plot.prcomp’ was found
It was found in the following places
registered S3 method for plot from namespace stats
namespace:stats
with value
function (x, main = deparse(substitute(x)), ...)
screeplot.default(x, main = main, ...)
<environment: namespace:stats>
So we can now call it directly using:
> stats:::plot.prcomp(mod)
I've used plot.prcomp
just as an example to illustrate the purpose. In normal use you shouldn't be calling S3 methods like this. But as I said, if the function you want to call exists (it might be a hidden utility function for example), but is in a namespace
, R will report that it can't find the function unless you tell it which namespace to look in.
Compare this to the following:
stats::plot.prcomp
The above fails because while stats
uses plot.prcomp
, it is not exported from stats
as the error rightly tells us:
Error: 'plot.prcomp' is not an exported object from 'namespace:stats'
This is documented as follows:
pkg::name returns the value of the exported variable name in namespace pkg, whereas pkg:::name returns the value of the internal variable name.
Use Dictionary<string, DateTime>
to store token with timestamp:
static Dictionary<string, DateTime> dic = new Dictionary<string, DateTime>();
Add token with timestamp whenever you create new token:
dic.Add("yourToken", DateTime.Now);
There is a timer running to remove any expired tokens out of dic:
timer = new Timer(1000*60); //assume run in 1 minute
timer.Elapsed += timer_Elapsed;
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
var expiredTokens = dic.Where(p => p.Value.AddDays(1) <= DateTime.Now)
.Select(p => p.Key);
foreach (var key in expiredTokens)
dic.Remove(key);
}
So, when you authenticate token, just check whether token exists in dic or not.
Here's another two-div solution. Tried to keep it concise and not hardcoded. First, the expectable html:
<div id="outer">
<div id="inner">
content
</div>
</div>
The principle behind the following css is to position some side of "outer", then use the fact that it assumes the size of "inner" to relatively shift the latter.
#outer {
position: fixed;
left: 50%; // % of window
}
#inner {
position: relative;
left: -50%; // % of outer (which auto-matches inner width)
}
This approach is similar to Quentin's, but inner can be of variable size.
[Twitter Bootstrap v3]
To create a n-level dropdown menu (touch device friendly) in Twitter Bootstrap v3,
CSS:
.dropdown-menu>li /* To prevent selection of text */
{ position:relative;
-webkit-user-select: none; /* Chrome/Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+ */
/* Rules below not implemented in browsers yet */
-o-user-select: none;
user-select: none;
cursor:pointer;
}
.dropdown-menu .sub-menu
{
left: 100%;
position: absolute;
top: 0;
display:none;
margin-top: -1px;
border-top-left-radius:0;
border-bottom-left-radius:0;
border-left-color:#fff;
box-shadow:none;
}
.right-caret:after,.left-caret:after
{ content:"";
border-bottom: 5px solid transparent;
border-top: 5px solid transparent;
display: inline-block;
height: 0;
vertical-align: middle;
width: 0;
margin-left:5px;
}
.right-caret:after
{ border-left: 5px solid #ffaf46;
}
.left-caret:after
{ border-right: 5px solid #ffaf46;
}
JQuery:
$(function(){
$(".dropdown-menu > li > a.trigger").on("click",function(e){
var current=$(this).next();
var grandparent=$(this).parent().parent();
if($(this).hasClass('left-caret')||$(this).hasClass('right-caret'))
$(this).toggleClass('right-caret left-caret');
grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
grandparent.find(".sub-menu:visible").not(current).hide();
current.toggle();
e.stopPropagation();
});
$(".dropdown-menu > li > a:not(.trigger)").on("click",function(){
var root=$(this).closest('.dropdown');
root.find('.left-caret').toggleClass('right-caret left-caret');
root.find('.sub-menu:visible').hide();
});
});
HTML:
<div class="dropdown" style="position:relative">
<a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Click Here <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>
<a class="trigger right-caret">Level 1</a>
<ul class="dropdown-menu sub-menu">
<li><a href="#">Level 2</a></li>
<li>
<a class="trigger right-caret">Level 2</a>
<ul class="dropdown-menu sub-menu">
<li><a href="#">Level 3</a></li>
<li><a href="#">Level 3</a></li>
<li>
<a class="trigger right-caret">Level 3</a>
<ul class="dropdown-menu sub-menu">
<li><a href="#">Level 4</a></li>
<li><a href="#">Level 4</a></li>
<li><a href="#">Level 4</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Level 2</a></li>
</ul>
</li>
<li><a href="#">Level 1</a></li>
<li><a href="#">Level 1</a></li>
</ul>
</div>
Some versions of libc contain functions that deal with stack traces; you might be able to use them:
http://www.gnu.org/software/libc/manual/html_node/Backtraces.html
I remember using libunwind a long time ago to get stack traces, but it may not be supported on your platform.
I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics
If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.
Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.
What is the difference between c++ and visaul c++?
Visual C++ is an IDE. There's also C++Builder from Embarcadero. (Used to be Borland.) There are also a few other C++ IDE's.
I know that c++ has the portability and all so if you know c++ how is it related to visual c++?
C++ is as portable as the libraries that you use in your C++ application. VC++ has some specialized libraries to use with Windows, so if you use those libraries in your C++ application, you're stuck with Windows. But a simple "Hello, World" application that just uses the console as output can be compiled on Windows, Linux, VMS, AS/400, Smartphones, FreeBSD, MS-DOS, CP80 and almost any other system for which you can find a C++ compiler. Injteresting fact: at http://nethack.org/ you can download the C sourcecode for an almost antique game, where you have to walk through a bunch of mazes, kick some monsters around, find treasures and steal some valuable amulet and bring that amulet back out. (It's also a game where you can encounter your characters from previous, failed attempts to get that amulet. :-) The sourcecode of NetHack is a fine example of how portable C (C++) code can be.
Is visual c++ mostly for online apps?
No. But it can be used for online apps. Actually, C# is used more often for server-side web applications while C++ (VC++) is used for all kinds of (server) components that your application will be depending upon.
Would visual basic be better for desktop applications?
Or Embarcadero Delphi. Delphi and Basic are languages that are easier to learn than C++ and both have very good IDE's to develop GUI applications with. Unfortunately, Visual Basic is now running on .NET only, while there are still many developers who need to create WIN32 applications. Those developers often have to choose between Delphi or C++ or else convince management to move to .NET development.
There are two prerequisite requirements need to install MySql Workbench as follows.
When .Net Framework 4.0
does not exist your computer installation will be corrupted. But if Microsoft Visual C++ 2010
does not exist your computer then you will continue the installation but cannot open MySql Workbench program. Sometimes you will need Microsoft Visual C++ 2013
instead of Microsoft Visual C++ 2010
. So I recommend to install Microsoft Visual C++ 2013
.
You can use it like this in template without any filters
{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}
If your SVG includes sprites, here's a component you can use. We have three or four groups of sprites... obviously you can pull that bit out if you only have one sprite file.
The Sprite component:
import React from 'react'
import PropTypes from 'prop-types';
export default class Sprite extends React.Component {
static propTypes = {
label: PropTypes.string,
group: PropTypes.string,
sprite: PropTypes.string.isRequired
}
filepath(spriteGroup)
{
if(spriteGroup == undefined) { spriteGroup = 'base' }
return "/asset_path/sprite_" + spriteGroup + ".svg";
}
render()
{
return(
<svg aria-hidden="true" title={this.props.label}>
<use xlinkHref={`${this.filepath(this.props.group)}#${this.props.sprite}`}></use>
</svg>
)
}
}
And elsewhere in React you would:
import Sprite from './Sprite';
render()
{
...
<Sprite label="No Current Value" group='base' sprite='clock' />
}
Example from our 'base' sprite file, sprite_base.svg:
<svg xmlns="http://www.w3.org/2000/svg">
<defs>
<symbol id="clock" viewBox="0 0 512 512">
<path fill="currentColor" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm216 248c0 118.7-96.1 216-216 216-118.7 0-216-96.1-216-216 0-118.7 96.1-216 216-216 118.7 0 216 96.1 216 216zm-148.9 88.3l-81.2-59c-3.1-2.3-4.9-5.9-4.9-9.7V116c0-6.6 5.4-12 12-12h14c6.6 0 12 5.4 12 12v146.3l70.5 51.3c5.4 3.9 6.5 11.4 2.6 16.8l-8.2 11.3c-3.9 5.3-11.4 6.5-16.8 2.6z" class="">
</path>
</symbol>
<symbol id="arrow-up" viewBox="0 0 16 16">
<polygon points="1.3,6.7 2.7,8.1 7,3.8 7,16 9,16 9,3.8 13.3,8.1 14.7,6.7 8,0 "> </polygon>
</symbol>
<symbol id="arrow-down" viewBox="0 0 16 16">
<polygon points="14.7,9.3 13.3,7.9 9,12.2 9,0 7,0 7,12.2 2.7,7.9 1.3,9.3 8,16 "> </polygon>
</symbol>
<symbol id="download" viewBox="0 0 48 48">
<line data-cap="butt" fill="none" stroke-width="3" stroke-miterlimit="10" x1="24" y1="3" x2="24" y2="36" stroke-linejoin="miter" stroke-linecap="butt"></line>
<polyline fill="none" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" points="11,23 24,36 37,23 " stroke-linejoin="miter"></polyline>
<line data-color="color-2" fill="none" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="2" y1="45" x2="46" y2="45" stroke-linejoin="miter"></line>
</symbol>
</devs>
</svg>
head:
head - output the first part of files
head [OPTION]... [FILE]...
Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input.
Mandatory arguments to long options are mandatory for short options too.
-c, --bytes=[-]N
print the first N bytes of each file; with the leading '-', print all but the last N bytes of each file
Adding the correct locale to ~/.bashrc
, ~/.bash_profile
, /etc/environment
and the like will solve the problem, however it is not recommended, as it overrides the settings from /etc/default/locale
, which is confusing at best and may lead to the locales not being applied consistently at worst.
Instead, one should edit /etc/default/locale
directly, which may look something like this:
LANG=en_US.UTF-8
LANGUAGE=en_US:en
LC_CTYPE=en_US
The change will take effect the next time you log in. You can get the new locale in an existing shell by sourcing /etc/default/locale
like this:
$ . /etc/default/locale
Regular solution, that does not work always:
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli
Other more drastic solution:
Angular CLI
globallynpm uninstall -g @angular/cli
Node.js
& npm
with uninstallerNode.js
& npm
C:\Users\<user>\AppData\Roaming\npm
and C:\Users\<user>\AppData\Roaming\npm-cache
ng version
npm -v
node -v
Node.js
& npm
with installer: https://nodejs.org/en/download/ Angular CLI
npm install -g @angular/cli
ng version
In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.
For QtCreator and Examples and API Docs:
sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `
sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`
sudo apt-get install build-essential qtcreator qt5-default
If something is also missing, then:
sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `
Hope to be helpful.
Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing
TL;DR you should just update the existing remote:
$ git remote set-url origin [email protected]:ppreyer/first_app.git
Long version:
As the error message indicates, there is already a remote configured with the same name. So you can either add the new remote with a different name or update the existing one if you don't need it:
To add a new remote, called for example github
instead of origin
(which obviously already exists in your system), do the following:
$ git remote add github [email protected]:ppreyer/first_app.git
Remember though, everywhere in the tutorial you see "origin" you should replace it with "github". For example $ git push origin master
should now be $ git push github master
.
However, if you want to see what that origin
which already exists is, you can do a $ git remote -v
. If you think this is there by some error, you can update it like so:
$ git remote set-url origin [email protected]:ppreyer/first_app.git
>>> format(3735928559, 'x')
'deadbeef'
The short version is: The efficient way to use readlines()
is to not use it. Ever.
I read some doc notes on
readlines()
, where people has claimed that thisreadlines()
reads whole file content into memory and hence generally consumes more memory compared to readline() or read().
The documentation for readlines()
explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list
full of str
ings out of those lines.
But the documentation for read()
likewise guarantees that it reads the whole file into memory, and builds a str
ing, so that doesn't help.
On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.
You can work around this in three ways:
readlines(sizehint)
, read(size)
, or readline()
.mmap
the file, which allows you to treat it as a giant string without first reading it in.For example, this has to read all of foo
at once:
with open('foo') as f:
lines = f.readlines()
for line in lines:
pass
But this only reads about 8K at a time:
with open('foo') as f:
while True:
lines = f.readlines(8192)
if not lines:
break
for line in lines:
pass
And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.
with open('foo') as f:
while True:
line = f.readline()
if not line:
break
pass
And this will do the exact same thing as the previous:
with open('foo') as f:
for line in f:
pass
Meanwhile:
but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?
Python doesn't make any such guarantees about garbage collection.
The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content
gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.
However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.
On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.
Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of malloc
s to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).
Putting it all together, here's how I'd write your program:
for filename in os.listdir(input_dir):
with open(filename, 'rb') as f:
if filename.endswith(".gz"):
f = gzip.open(fileobj=f)
words = (line.split(delimiter) for line in f)
... my logic ...
Or, maybe:
for filename in os.listdir(input_dir):
if filename.endswith(".gz"):
f = gzip.open(filename, 'rb')
else:
f = open(filename, 'rb')
with contextlib.closing(f):
words = (line.split(delimiter) for line in f)
... my logic ...
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
I was getting these errors when trying to load my test environment (via rake test or autotest) and the IRB suggestions didn't help. I ended up wrapping my entire test/test_helper.rb in a begin/rescue block and that fixed things up.
begin
class ActiveSupport::TestCase
#awesome stuff
end
rescue => e
puts e.backtrace
end
Here is the a quick solution for multiple checkbox validation using jquery validation plugin:
jQuery.validator.addMethod('atLeastOneChecked', function(value, element) {
return ($('.cbgroup input:checked').length > 0);
});
$('#subscribeForm').validate({
rules: {
list0: { atLeastOneChecked: true }
},
messages: {
list0: { 'Please check at least one option' }
}
});
$('.cbgroup input').click(function() {
$('#list0').valid();
});
If you have a datetime.timedelta
value td
, td.days
already gives you the "days" you want. timedelta
values keep fraction-of-day as seconds (not directly hours or minutes) so you'll indeed have to perform "nauseatingly simple mathematics", e.g.:
def days_hours_minutes(td):
return td.days, td.seconds//3600, (td.seconds//60)%60
The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).
If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:
Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.
You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).
As an aside, the login properties for sa
would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.
I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM
account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):
And some other resources:
There are none (at least in the standard Java library). Character sets vary from platform to platform so there isn't a standard list of them in Java.
There are some 3rd party libraries which contain these constants though. One of these is Guava (Google core libraries): http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Charsets.html
Yes, we can do this way.
import java.util.Scanner;
public class Collection_Basic {
private static Scanner sc;
public static void main(String[] args) {
Object[] obj=new Object[4];
sc = new Scanner(System.in);
//Storing element
System.out.println("enter your element");
for(int i=0;i<4;i++){
obj[i]=sc.nextInt();
}
/*
* here, size reaches with its maximum capacity so u can not store more element,
*
* for storing more element we have to create new array Object with required size
*/
Object[] tempObj=new Object[10];
//copying old array to new Array
int oldArraySize=obj.length;
int i=0;
for(;i<oldArraySize;i++){
tempObj[i]=obj[i];
}
/*
* storing new element to the end of new Array objebt
*/
tempObj[i]=90;
//assigning new array Object refeence to the old one
obj=tempObj;
for(int j=0;j<obj.length;j++){
System.out.println("obj["+j+"] -"+obj[j]);
}
}
}
Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.
In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]:
x y a b
0 3 -1 1 2
1 6 -2 2 4
2 9 -3 3 6
3 12 -4 4 8
The keys are maintained with the removed key missing but they can be rearranged by doing this:
$array = array(1,2,3,4,5);
unset($array[2]);
$arranged = array_values($array);
print_r($arranged);
Outputs:
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 5
)
Notice that if we do the following without rearranging:
unset($array[2]);
$array[]=3;
The index of the value 3 will be 5 because it will be pushed to the end of the array and will not try to check or replace missing index. This is important to remember when using FOR LOOP with index access.
There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List
Here some basics points about scenarios and functions:
Try this
DataSet ds = new DataSet("TimeRanges");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("Procedure1", conn);
sqlComm.Parameters.AddWithValue("@Start", StartTime);
sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
$apply
should be called?TL;DR:
$apply
should be called whenever you want to apply changes made outside of Angular world.
Just to update @Dustin's answer, here is an explanation of what $apply exactly does and why it works.
$apply()
is used to execute an expression in AngularJS from outside of the AngularJS framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the AngularJS framework we need to perform proper scope life cycle of exception handling, executing watches.
Angular allows any value to be used as a binding target. Then at the end of any JavaScript code turn, it checks to see if the value has changed.
That step that checks to see if any binding values have changed actually has a method, $scope.$digest()
1. We almost never call it directly, as we use $scope.$apply()
instead (which will call $scope.$digest
).
Angular only monitors variables used in expressions and anything inside of a $watch
living inside the scope. So if you are changing the model outside of the Angular context, you will need to call $scope.$apply()
for those changes to be propagated, otherwise Angular will not know that they have been changed thus the binding will not be updated2.
You can do it on a per file basis. Use the path attribute to include the filename
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<location path="YourFileNameHere.xml">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
</configuration>
The below code helps me to return a JSON object for JavaScript on the front end
My template code
template_file.json
{
"name": "{{name}}"
}
Python backed code
def download_json(request):
print("Downloading JSON")
# Response render a template as JSON object
return HttpResponse(render_to_response("template_file.json",dict(name="Alex Vera")),content_type="application/json")
File url.py
url(r'^download_as_json/$', views.download_json, name='download_json-url')
jQuery code for the front end
$.ajax({
url:'{% url 'download_json-url' %}'
}).done(function(data){
console.log('json ', data);
console.log('Name', data.name);
alert('hello ' + data.name);
});
Linux users (tested on ubuntu 14.04)
by default (on linux and mac) pycharm uses the OS's password manager. To access the passwords on ubuntu open the program "Passwords and Keys".
Once open filter on "idea" and edit the relevant passwords.
No need to restart pycharm for me.
Using pycharm 17.2
You cannot do that, see this question's answers.
You may use std:vector
instead.
I checked all my settings according to this list: http://msdn.microsoft.com/en-us/library/ts7eyw4s.aspx#feedback . It is helpful to me and for my situation, I find out that Link Dependency of projects' properties has double-quote, which should not be there.
From the docs:
To uninstall Anaconda open a terminal window and remove the entire anaconda install directory:
rm -rf ~/anaconda
. You may also edit~/.bash_profile
and remove the anaconda directory from yourPATH
environment variable, and remove the hidden.condarc
file and.conda
and.continuum
directories which may have been created in the home directory withrm -rf ~/.condarc ~/.conda ~/.continuum
.
Further notes:
~/anaconda3
dir instead of ~/anaconda
.~/.anaconda
hidden directory that may be removed.PATH
is modified in one of your runcom files, and not in your shell profile. So, for example if you are using bash, be sure to check your ~/.bashrc
if you don't find the PATH
modified in ~/.bash_profile
.ul, li {_x000D_
list-style: none;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
ul {_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
width: calc(100% / 3);_x000D_
}_x000D_
_x000D_
img {_x000D_
width: 100%;_x000D_
height: auto;_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
<img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">_x000D_
<br> Line 1_x000D_
<br> Line 2_x000D_
</li>_x000D_
<li>_x000D_
<img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">_x000D_
<br> Line 1_x000D_
<br> Line 2_x000D_
<br> Line 3_x000D_
<br> Line 4_x000D_
</li>_x000D_
<li>_x000D_
<img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">_x000D_
<br> Line 1_x000D_
</li>_x000D_
<li>_x000D_
<img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">_x000D_
<br> Line 1_x000D_
<br> Line 2_x000D_
</li>_x000D_
</ul>
_x000D_
using d3.js v3:
ages = d3.set(
array.map(function (d) { return d.age; })
).values();
Try this. It worked for me.
{{ html_entity_decode($text) }}
In Laravel Blade template, {{ }} wil escape html. If you want to display html from controller in view, decode html from string.
=COUNTIFS(1:1,FALSE)=0
This will return TRUE or FALSE (Looks for FALSE, if count isn't 0 (all True) it will be false
Have a look at the content by type web part - http://codeplex.com/eoffice - probably the most flexible viewing web part.
You are missing a step. You need to log / store the values on your server (mailgun is a client). Then you need to retrieve those values on your server (your pc with your web browser will be a client). These will be two totally different aspx files (or the same one with different parameters).
aspx page 1 (the one that mailgun has):
var val = Request.Form["recipient"];
var file = new File(filename);
file.write(val);
close(file);
aspx page 2:
var contents = "";
if (File.exists(filename))
var file = File.open(filename);
contents = file.readtoend();
file.close()
Request.write(contents);
This css script might be useful to all - It is not for syntax highlighting but works well for presenting the source code in original format :
<pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace;
color: #000000; background-color: #eee;
font-size: 12px; border: 1px dashed #999999;
line-height: 14px; padding: 5px;
overflow: auto; width: 100%">
<code style="color:#000000;word-wrap:normal;">
<<<<<<<YOUR CODE HERE>>>>>>>
</code>
</pre>
How to use :
BENEFITS : Simple and easy to use, less configuration, easy to reconfigure, no extra software
I had the same error message so I went googling a bit I managed to fix it with the following code.
df<-data.frame(words = unlist(words))
words is a character list.
This just in case somebody else needs the output to be a data frame.
PLEASE NOTE: The documentation says:
filter
is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of filter in ECMA-262 implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming that fn.call evaluates to the original value of Function.prototype.call, and that Array.prototype.push has its original value.
So, to avoid some heartache, you may have to add this code to your script At the beginning.
if (!Array.prototype.filter) {
Array.prototype.filter = function (fn, context) {
var i,
value,
result = [],
length;
if (!this || typeof fn !== 'function' || (fn instanceof RegExp)) {
throw new TypeError();
}
length = this.length;
for (i = 0; i < length; i++) {
if (this.hasOwnProperty(i)) {
value = this[i];
if (fn.call(context, value, i, this)) {
result.push(value);
}
}
}
return result;
};
}
@@IDENTITY
Is a system function that returns the last-inserted identity value.
In my case, The issue was that for UAT environment, API URL will start with Http instead of https. Also, the backend assigns different ports for both Http and https.
for example,
http://10.12.12.31:2001/api/example. - is correct for me
https://10.12.12.31:2002/api/example. - is wrong for me
Because I was using https and 2002 port for hitting the UAT environment. So I am getting could not get any response error in postman.
document.getElementById('id1').bgColor = '#00FF00';
seems to work. I don't think .style.backgroundColor
does.
I've been using the same approach of saving the hidden TabPages in a private list, but the problem is that when I want to show the TabPage again, they doesn't appears in the original position (order). So, finally, I wrote a class in VB to add the TabControl with two methods: HideTabPageByName and ShowTabPageByName. You can just call the methods passing the name (not the TabPage instance).
Public Class CS_Control_TabControl
Inherits System.Windows.Forms.TabControl
Private mTabPagesHidden As New Dictionary(Of String, System.Windows.Forms.TabPage)
Private mTabPagesOrder As List(Of String)
Public Sub HideTabPageByName(ByVal TabPageName As String)
If mTabPagesOrder Is Nothing Then
' The first time the Hide method is called, save the original order of the TabPages
mTabPagesOrder = New List(Of String)
For Each TabPageCurrent As TabPage In Me.TabPages
mTabPagesOrder.Add(TabPageCurrent.Name)
Next
End If
If Me.TabPages.ContainsKey(TabPageName) Then
Dim TabPageToHide As TabPage
' Get the TabPage object
TabPageToHide = TabPages(TabPageName)
' Add the TabPage to the internal List
mTabPagesHidden.Add(TabPageName, TabPageToHide)
' Remove the TabPage from the TabPages collection of the TabControl
Me.TabPages.Remove(TabPageToHide)
End If
End Sub
Public Sub ShowTabPageByName(ByVal TabPageName As String)
If mTabPagesHidden.ContainsKey(TabPageName) Then
Dim TabPageToShow As TabPage
' Get the TabPage object
TabPageToShow = mTabPagesHidden(TabPageName)
' Add the TabPage to the TabPages collection of the TabControl
Me.TabPages.Insert(GetTabPageInsertionPoint(TabPageName), TabPageToShow)
' Remove the TabPage from the internal List
mTabPagesHidden.Remove(TabPageName)
End If
End Sub
Private Function GetTabPageInsertionPoint(ByVal TabPageName As String) As Integer
Dim TabPageIndex As Integer
Dim TabPageCurrent As TabPage
Dim TabNameIndex As Integer
Dim TabNameCurrent As String
For TabPageIndex = 0 To Me.TabPages.Count - 1
TabPageCurrent = Me.TabPages(TabPageIndex)
For TabNameIndex = TabPageIndex To mTabPagesOrder.Count - 1
TabNameCurrent = mTabPagesOrder(TabNameIndex)
If TabNameCurrent = TabPageCurrent.Name Then
Exit For
End If
If TabNameCurrent = TabPageName Then
Return TabPageIndex
End If
Next
Next
Return TabPageIndex
End Function
Protected Overrides Sub Finalize()
mTabPagesHidden = Nothing
mTabPagesOrder = Nothing
MyBase.Finalize()
End Sub
End Class
Depending on your environment, you could use Rhino to do this, see Rhino website. This gives you access to all of the Java libraries from within JavaScript.
if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
alert('hello world');
}
This is the only one solution that worked for me (it's not a onepage website). It's working with Chrome, Firefox and Safari.
Please read the $.ajax
documentation, this is a covered topic.
$.ajax({
url: "test.html",
error: function(){
// will fire when timeout is reached
},
success: function(){
//do something
},
timeout: 3000 // sets timeout to 3 seconds
});
You can get see what type of error was thrown by accessing the textStatus parameter of the error: function(jqXHR, textStatus, errorThrown)
option. The options are "timeout", "error", "abort", and "parsererror".
Try pulling out the NVIDIA graphics card and reinserting it.
I prefer to use an IF statement in the FOR loop that checks to make sure the current iteration isn't the last value in the array. If not, add a comma
$fruit = array("apple", "banana", "pear", "grape");
for($i = 0; $i < count($fruit); $i++){
echo "$fruit[$i]";
if($i < (count($fruit) -1)){
echo ", ";
}
}
It means three things.
First public
means that any other object can access it.
static
means that the class in which it resides doesn't have to be instantiated first before the function can be called.
void
means that the function does not return a value.
Since you are just learning, don't worry about the first two too much until you learn about classes, and the third won't matter much until you start writing functions (other than main that is).
Best piece of advice I got when learning to program, and which I pass along to you, is don't worry about the little details you don't understand right away. Get a broad overview of the fundamentals, then go back and worry about the details. The reason is that you have to use some things (like public static void
) in your first programs which can't really be explained well without teaching you about a bunch of other stuff first. So, for the moment, just accept that that's the way it's done, and move on. You will understand them shortly.
My answer is basically the same as @pi-k. In my case my program worked locally but failed to build on QA servers. (I suspect devops had older versions of the package blocked and my version must have been too out-of-date) I just decided to upgrade everything
$ pip install pip-review
$ pip-review --local --interactive
The error MethodNotAllowedHttpException means the route exists, but the HTTP method (GET) is wrong. You have to change it to POST:
Route::post('test/register', array('uses'=>'TestController@create'));
Also, you need to hash your passwords:
public function create()
{
$user = new User;
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::back();
}
And I removed the line:
$user= Input::all();
Because in the next command you replace its contents with
$user = new User;
To debug your Input, you can, in the first line of your controller:
dd( Input::all() );
It will display all fields in the input.
This can be done just using Copy-Item. No need to use Get-Childitem. I think you are just overthinking it.
Copy-Item -Path C:\MyFolder -Destination \\Server\MyFolder -recurse -Force
I just tested it and it worked for me.
edit: included suggestion from the comments
# Add wildcard to source folder to ensure consistent behavior
Copy-Item -Path $sourceFolder\* -Destination $targetFolder -Recurse
OK, so first of all the http://angular-ui.github.io/bootstrap/ has a <modal>
directive and the $dialog
service and both of those can be used to open modal windows.
The difference is that with the <modal>
directive content of a modal is embedded in a hosting template (one that triggers modal window opening). The $dialog
service is far more flexible and allow you to load modal's content from a separate file as well as trigger modal windows from any place in AngularJS code (this being a controller, a service or another directive).
Not sure what you mean exactly by "using JavaScript code" but assuming that you mean any place in AngularJS code the $dialog
service is probably a way to go.
It is very easy to use and in its simplest form you could just write:
$dialog.dialog({}).open('modalContent.html');
To illustrate that it can be really triggered by any JavaScript code here is a version that triggers modal with a timer, 3 seconds after a controller was instantiated:
function DialogDemoCtrl($scope, $timeout, $dialog){
$timeout(function(){
$dialog.dialog({}).open('modalContent.html');
}, 3000);
}
This can be seen in action in this plunk: http://plnkr.co/edit/u9HHaRlHnko492WDtmRU?p=preview
Finally, here is the full reference documentation to the $dialog
service described here:
https://github.com/angular-ui/bootstrap/blob/master/src/dialog/README.md
In simple words, dereferencing means accessing the value from a certain memory location against which that pointer is pointing.
@vnr you can retrieve all the sort keys associated with a partition key by just using the query using partion key. No need of scan. The point here is partition key is compulsory in a query . Sort key are used only to get range of data
There's no built-in command for it, so I usually just do something like this:
#!/bin/bash
# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs. The first revision of the file is emitted as
# full text since there's not previous version to compare it to.
function history_of_file() {
url=$1 # current url of file
svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {
# first revision as full text
echo
read r
svn log -r$r $url@HEAD
svn cat -r$r $url@HEAD
echo
# remaining revisions as differences to previous revision
while read r
do
echo
svn log -r$r $url@HEAD
svn diff -c$r $url@HEAD
echo
done
}
}
Then, you can call it with:
history_of_file $1
document.cookie = valuename + "=" + value + "; " + expires + ";domain=;path=/";
this "domain=;path=/"; will take dynamic domain as its cookie will work in subdomain. if u want to test in localhost it will work
If you are using Angular, go like this:
<select>_x000D_
<option [ngValue]="undefined" disabled selected>Select your option</option>_x000D_
<option [ngValue]="hurr">Durr</option>_x000D_
</select>
_x000D_
Very simple verison of the rebase solution:
Go to the folder where git is installed, such as:
C:\Program Files (x86)\Git\bin
By holding shift and right clicking in the folder, you should be able to open a command prompt as administrator from there (thanks to https://stackoverflow.com/users/355389/darren-lewis for that comment),
Then run:
rebase.exe -b 0x50000000 msys-1.0.dll
This fixed it for me when the restart approach didn't work.
Hope it helps.
The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr)
instead of 1fr
as your track size.
If you need to be checking external pages, you won't be able to get away with a pure javascript solution, since any requests to external URLs are blocked. You can get away with it by using JSONP, but that won't work unless the page you're requesting only serves up JSON.
You need to have a proxy on your own server to get the external links for you. This is actually rather simple with any server-side language.
<?php
$contents = file_get_contents($_GET['url']); // please do some sanitation here...
// i'm just showing an example.
echo $contents;
?>
If you needed to check server response codes (eg: 404, 301, etc), then using a library such as cURL in your server-side script could retrieve that information and then pass it onto your javascript app.
Thinking about it now, there probably could be JSONP-enabled proxies out there for you to use, should the "setting up my own proxy" option not be viable.
Believe it or not, in my system this ugly function performs better than G Mastros elegant one.
CREATE FUNCTION dbo.RemoveSpecialChar (@s VARCHAR(256))
RETURNS VARCHAR(256)
WITH SCHEMABINDING
BEGIN
IF @s IS NULL
RETURN NULL
DECLARE @s2 VARCHAR(256) = '',
@l INT = LEN(@s),
@p INT = 1
WHILE @p <= @l
BEGIN
DECLARE @c INT
SET @c = ASCII(SUBSTRING(@s, @p, 1))
IF @c BETWEEN 48 AND 57
OR @c BETWEEN 65 AND 90
OR @c BETWEEN 97 AND 122
SET @s2 = @s2 + CHAR(@c)
SET @p = @p + 1
END
IF LEN(@s2) = 0
RETURN NULL
RETURN @s2
You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.
To fix this, restart your interpreter.
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168
If you shadow the sum
builtin, you can get the error you are seeing
>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Also, note that sum
will work fine on the set
there is no need to convert it to a list
plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')
('0' * 7 + bin(6)[2:])[-8:]
or
right_side = bin(6)[2:]
'0' * ( 8 - len( right_side )) + right_side
This problem is usually caused by one of the following
Try running your query natively and look at the results, if the resultset is not too large. If you've eliminated null values, then my guess is that the primary key columns is being duplicated.
Or, to see the exact error, you can manually add a Try/Catch block to the generated code like so and then breaking when the exception is raised:
Then within the command window, call GetErrors
method on the table getting the error.
For C#, the command would be ? dataTable.GetErrors()
For VB, the command is ? dataTable.GetErrors
This will show you all datarows which have an error. You can get then look at the RowError
for each of these, which should tell you the column that's invalid along with the problem. So, to see the error of the first datarow in error the command is:
? dataTable.GetErrors(0).RowError
or in C# it would be ? dataTable.GetErrors()[0].RowError
I'm late to the party, but hopefully this is a useful addition to the other answers here...
I need to know how I can determine what "too much work" my application may be doing as all my processing is done in AsyncTasks.
The following are all candidates:
Uri
's on ImageView
's all constitute IO on the main thread)View
hierarchiesView
hierarchyonDraw
methods in custom View
'sAsyncTask
's are "background" by default, java.lang.Thread
is not)To actually determine the specific cause you'll need to profile your app.
I've been trying to understand Choreographer by experimenting and looking at the code.
The documentation of Choreographer opens with "Coordinates the timing of animations, input and drawing." which is actually a good description, but the rest goes on to over-emphasize animations.
The Choreographer is actually responsible for executing 3 types of callbacks, which run in this order:
The aim is to match the rate at which invalidated views are re-drawn (and animations tweened) with the screen vsync - typically 60fps.
The warning about skipped frames looks like an afterthought: The message is logged if a single pass through the 3 steps takes more than 30x the expected frame duration, so the smallest number you can expect to see in the log messages is "skipped 30 frames"; If each pass takes 50% longer than it should you will still skip 30 frames (naughty!) but you won't be warned about it.
From the 3 steps involved its clear that it isn't only animations that can trigger the warning: Invalidating a significant portion of a large View
hierarchy or a View
with a complicated onDraw method might be enough.
For example this will trigger the warning repeatedly:
public class AnnoyTheChoreographerActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_linear_layout);
ViewGroup root = (ViewGroup) findViewById(R.id.root);
root.addView(new TextView(this){
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
long sleep = (long)(Math.random() * 1000L);
setText("" + sleep);
try {
Thread.sleep(sleep);
} catch (Exception exc) {}
}
});
}
}
... which produces logging like this:
11-06 09:35:15.865 13721-13721/example I/Choreographer? Skipped 42 frames! The application may be doing too much work on its main thread.
11-06 09:35:17.395 13721-13721/example I/Choreographer? Skipped 59 frames! The application may be doing too much work on its main thread.
11-06 09:35:18.030 13721-13721/example I/Choreographer? Skipped 37 frames! The application may be doing too much work on its main thread.
You can see from the stack during onDraw
that the choreographer is involved regardless of whether you are animating:
at example.AnnoyTheChoreographerActivity$1.onDraw(AnnoyTheChoreographerActivity.java:25) at android.view.View.draw(View.java:13759)
... quite a bit of repetition ...
at android.view.ViewGroup.drawChild(ViewGroup.java:3169) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3039) at android.view.View.draw(View.java:13762) at android.widget.FrameLayout.draw(FrameLayout.java:467) at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2396) at android.view.View.getDisplayList(View.java:12710) at android.view.View.getDisplayList(View.java:12754) at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1144) at android.view.ViewRootImpl.draw(ViewRootImpl.java:2273) at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2145) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1956) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1112) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4472) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725) at android.view.Choreographer.doCallbacks(Choreographer.java:555) at android.view.Choreographer.doFrame(Choreographer.java:525) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4898)
Finally, if there is contention from other threads that reduce the amount of work the main thread can get done, the chance of skipping frames increases dramatically even though you aren't actually doing the work on the main thread.
In this situation it might be considered misleading to suggest that the app is doing too much on the main thread, but Android really wants worker threads to run at low priority so that they are prevented from starving the main thread. If your worker threads are low priority the only way to trigger the Choreographer warning really is to do too much on the main thread.
There is a simple solution, So when you run Object.keys(Enum)
that gonna give you a Array of Values and Keys, in first slice Values and in the second one keys, so why we don't just return the second slice, this code below works for me.
enum Enum {
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN
}
const keys = Object.keys(Enum);
console.log(keys.slice(keys.length / 2));
Like CodeHater said you are accessing the variable before it is set.
To fix this move the ng-init directive to the first div.
<body ng-app>
<div ng-controller="testController" ng-init="testInput='value'">
<input type="hidden" id="testInput" ng-model="testInput" />
{{ testInput }}
</div>
</body>
That should work!
replace it with index of the array.
array[index] = new_value;
Selects a subset of the array to return based on the specified condition. Returns an array with only those elements that match the condition. The returned elements are in the original order.
db.test.aggregate([
{$match: {"list.a": {$gt:3}}}, // <-- match only the document which have a matching element
{$project: {
list: {$filter: {
input: "$list",
as: "list",
cond: {$gt: ["$$list.a", 3]} //<-- filter sub-array based on condition
}}
}}
]);
Quote from the Spring reference doc:
Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there...
Your servlet is called spring-dispatcher
, so it looks for /WEB-INF/spring-dispatcher-servlet.xml
. You need to have this servlet configuration, and define web related beans in there (like controllers, view resolvers, etc). See the linked documentation for clarification on the relation of servlet contexts to the global application context (which is the app-config.xml
in your case).
One more thing, if you don't like the naming convention of the servlet config xml, you can specify your config explicitly:
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
This is a well-known nuisance when posting multiline commands in R. (You can get different behavior when you source()
a script to when you copy-and-paste the lines, both with multiline and comments)
ggplot(...) + geom_whatever1(...) +
geom_whatever2(...) +
stat_whatever3(...) +
geom_title(...) + scale_y_log10(...)
Error in "+ geom_whatever2(...) invalid argument to unary operator"
cf. answer to "Split code over multiple lines in an R script"
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
According to the select_list Oracle select documentation the AS is optional.
As a personal note I think it is easier to read with the AS
After you malloc
a node
make sure to set node->next = NULL
.
int addNodeBottom(int val, node *head)
{
node *current = head;
node *newNode = (node *) malloc(sizeof(node));
if (newNode == NULL) {
printf("malloc failed\n");
exit(-1);
}
newNode->value = val;
newNode->next = NULL;
while (current->next) {
current = current->next;
}
current->next = newNode;
return 0;
}
I should point out that with this version the head
is still used as a dummy, not used for storing a value. This lets you represent an empty list by having just a head
node.
Ok...so first you need to import the image into your project.
1) Select the PictureBox in the Form Design View
2) Open PictureBox Tasks
(it's the little arrow printed to right on the edge of the PictureBox)
3) Click on "Choose image..."
4) Select the second option "Project resource file:"
(this option will create a folder called "Resources" which you can access with Properties.Resources)
5) Click on "Import..." and select your image from your computer
(now a copy of the image will be saved in "Resources" folder created at step 4)
6) Click on "OK"
Now the image is in your project and you can use it with the Properties command. Just type this code when you want to change the picture in the PictureBox:
pictureBox1.Image = Properties.Resources.MyImage;
Note:
MyImage represent the name of the image...
After typing "Properties.Resources.", all imported image files are displayed...
The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):
Greedy quantifiers
X? X, once or not at all
X* X, zero or more times
X+ X, one or more times
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}? X, exactly n times
X{n,}? X, at least n times
X{n,m}? X, at least n but not more than m times
Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+ X, exactly n times
X{n,}+ X, at least n times
X{n,m}+ X, at least n but not more than m times
You can achieve this using a meta tag
as follows:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
I can answer this question only for Ubuntu users:
The root directory of docker can be found when you run the command docker info
Docker directory will be given in this line: "Docker Root Dir: /var/lib/docker
"
About the docker images, they are stored inside the docker directory:
/var/lib/docker/aufs/diff/
Remember these things are not same in all version of docker. Currently, I am using 1.12.3.
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
Use the Moment.js library http://momentjs.com/ It will save you a LOT of trouble.
moment().format('DD-MMM-YYYY');
If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:
You can also click the 'n commits' link below their name on the repo's "contributors" page:
Alternatively, you can directly append ?author=<theusername>
or ?author=<emailaddress>
to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:
For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress>
to the URL - the author's name will not be clickable from the commits list.
You can also get the list of commits by a particular author from the command line using
git log --author=[your git name]
Example:
git log --author=Prem
You can get the id of clicked one by this code
$("span").on("click",function(e){
console.log(e.target.Id);
});
Use .on()
event for future compatibility
just replace JFrame
to JDialog
in class
public class MyDialog extends JFrame // delete JFrame and write JDialog
and then write setModal(true);
in constructor
After that you will be able to construct your Form in netbeans and the form becomes modal
This is a working example of consuming SOAP web services in android.
**Note ::***DON'T FORGET TO ADD ksoap2.jar in your project and also add the INTERNET permission in AndroidManifest file*
public final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
public final String METHOD_NAME = "FahrenheitToCelsius";
public final String PROPERTY_NAME = "Fahrenheit";
public final String SOAP_ACTION = "http://tempuri.org/FahrenheitToCelsius";
public final String SOAP_ADDRESS = "http://www.w3schools.com/webservices/tempconvert.asmx";
private class TestAsynk extends AsyncTask<String, Void, String> {
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),
String.format("%.2f", Float.parseFloat(result)),
Toast.LENGTH_SHORT).show();
}
@Override
protected String doInBackground(String... params) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
METHOD_NAME);
request.addProperty(PROPERTY_NAME, params[0]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
SOAP_ADDRESS);
Object response = null;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
response = envelope.getResponse();
Log.e("Object response", response.toString());
} catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
}
Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.
{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li> {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}