It's also possible letting a ServletContextListener set the System properties:
import java.util.Enumeration;
import javax.servlet.*;
public class SystemPropertiesHelper implements
javax.servlet.ServletContextListener {
private ServletContext context = null;
public void contextInitialized(ServletContextEvent event) {
context = event.getServletContext();
Enumeration<String> params = context.getInitParameterNames();
while (params.hasMoreElements()) {
String param = (String) params.nextElement();
String value =
context.getInitParameter(param);
if (param.startsWith("customPrefix.")) {
System.setProperty(param, value);
}
}
}
public void contextDestroyed(ServletContextEvent event) {
}
}
And then put this into your web.xml (should be possible for context.xml too)
<context-param>
<param-name>customPrefix.property</param-name>
<param-value>value</param-value>
<param-type>java.lang.String</param-type>
</context-param>
<listener>
<listener-class>servletUtils.SystemPropertiesHelper</listener-class>
</listener>
It worked for me.
What you can do is the following;
Add a file called ROOT.xml
in <catalina_home>/conf/Catalina/localhost/
This ROOT.xml will override the default settings for the root context of the tomcat installation for that engine and host (Catalina and localhost).
Enter the following to the ROOT.xml file;
<Context
docBase="<yourApp>"
path=""
reloadable="true"
/>
Here, <yourApp>
is the name of, well, your app.. :)
And there you go, your application is now the default application and will show up on http://localhost:8080
However, there is one side effect; your application will be loaded twice. Once for localhost:8080
and once for localhost:8080/yourApp
. To fix this you can put your application OUTSIDE <catalina_home>/webapps
and use a relative or absolute path in the ROOT.xml's docBase tag. Something like this;
<Context
docBase="/opt/mywebapps/<yourApp>"
path=""
reloadable="true"
/>
And then it should be all OK!
I think that you are looking for something like this:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
require 'trollop'
opts = Trollop::options do
opt :output, "Output file", :type => String
opt :input, "Input file", :type => String
opt :ss, "String to search", :type => String
opt :rs, "String to replace", :type => String
end
text = File.read(opts.input)
text.gsub!(opts.ss, opts.rs)
File.open(opts.output, 'w') { |f| f.write(text) }
I am able to download it using apple's download website today. https://developer.apple.com/download/
I do not have a paid apple developer account. Before I was only able to see xcode 8.3.3 but somehow today xcode 9 beta also appeared.
Your Fundamentals are wrong, the program won't work, so go through the basics and rewrite the program.
Some of the corrections you must make are:
1) You must make a variable of semaphore type
sem_t semvar;
2) The functions sem_wait()
, sem_post()
require the semaphore variable but you are passing the semaphore id, which makes no sense.
sem_wait(&semvar);
//your critical section code
sem_post(&semvar);
3) You are passing the semaphore to sem_wait()
and sem_post()
without initializing it. You must initialize it to 1 (in your case) before using it, or you will have a deadlock.
ret = semctl( semid, 1, SETVAL, sem);
if (ret == 1)
perror("Semaphore failed to initialize");
Study the semaphore API's from the man page and go through this example.
Make sure you've set your target API (different from the target SDK) in the Project Properties (not the manifest) to be at least 4.0/API 14.
Since the count is the intended final value, in your query pass
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get()->result_array();
return count($query);
The count the retuned value
Just to add on to what @Zaph says in the comments.
I have the same problem as you, as to know, the array of String
is not saved. Even though Apple bridges types such as String and NSString, I wasn't able to save an array of [String]
neither of [AnyObject]
.
However an array of [NSString]
works for me.
So your code could look like that :
var key = "keySave"
var array1: [NSString] = [NSString]()
array1.append("value 1")
array1.append("value 2")
//save
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(array1, forKey: key)
defaults.synchronize()
//read
if let testArray : AnyObject? = defaults.objectForKey(key) {
var readArray : [NSString] = testArray! as [NSString]
}
Note that I created an array of NSString and not a dictionary. I didn't check if it works with a dictionary, but probably you will have to define the things as [NSString : NSString]
to have it working.
EDIT
Re-reading your question and your title, you are talking of array of array
. I think that as long as you stay with NSString
, an array of array will work. However, if you think my answer is irrelevant, just let me know in the comments and I will remove it.
I worked so much, I hope my effort might help you out.
Just paste this into your SSMS and press F5:
Declare @Object as Int;
DECLARE @hr int
Declare @json as table(Json_Table nvarchar(max))
Exec @hr=sp_OACreate 'MSXML2.ServerXMLHTTP.6.0', @Object OUT;
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'open', NULL, 'get',
'http://overpass-api.de/api/interpreter?data=[out:json];area[name=%22Auckland%22]-%3E.a;(node(area.a)[amenity=cinema];way(area.a)[amenity=cinema];rel(area.a)[amenity=cinema];);out;', --Your Web Service Url (invoked)
'false'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'send'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'responseText', @json OUTPUT
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
INSERT into @json (Json_Table) exec sp_OAGetProperty @Object, 'responseText'
-- select the JSON string
select * from @json
-- Parse the JSON string
SELECT * FROM OPENJSON((select * from @json), N'$.elements')
WITH (
[type] nvarchar(max) N'$.type' ,
[id] nvarchar(max) N'$.id',
[lat] nvarchar(max) N'$.lat',
[lon] nvarchar(max) N'$.lon',
[amenity] nvarchar(max) N'$.tags.amenity',
[name] nvarchar(max) N'$.tags.name'
)
EXEC sp_OADestroy @Object
This query will give you 3 results:
1. Catch the error in case something goes wrong (don't panic, it will always show you an error above 4000 characters because NVARCHAR(MAX) can only store till 4000 characters)
2. Put the JSON into a string (which is what we want)
3. BONUS: parse the JSON and nicely store the data into a table (how cool is that?)
The following suggestion let's you test abstract classes without creating a "real" subclass - the Mock is the subclass.
use Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS)
, then mock any abstract methods that are invoked.
Example:
public abstract class My {
public Result methodUnderTest() { ... }
protected abstract void methodIDontCareAbout();
}
public class MyTest {
@Test
public void shouldFailOnNullIdentifiers() {
My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);
Assert.assertSomething(my.methodUnderTest());
}
}
Note: The beauty of this solution is that you do not have to implement the abstract methods, as long as they are never invoked.
In my honest opinion, this is neater than using a spy, since a spy requires an instance, which means you have to create an instantiatable subclass of your abstract class.
var streetaddress= addy.substr(0, addy.indexOf(','));
While it's not the best place for definitive information on what each method does (mozilla developer network is better for that) w3schools.com is good for introducing you to syntax.
If using Maven you can context click and run 'Maven/Update Project...'
This issue is happening because you have installed jre1.8.0_101-1.8.0_101-fcs.i58.rpm as well jdk-1.7.0_80-fcs.x86_64.rpm. so just uninstall your jre rpm & restart your application. It should work out.
Here's a different way to do it, but it's only useful if SecondDate is a variable you're passing in:
DateTime startDate = SecondDate.Date;
DateTime endDate = startDate.AddDays(1).AddTicks(-1);
...
e => e.FirstDate.Value >= startDate && e.FirstDate.Value <= endDate
I think that should work
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
CREATE SCHEMA is a synonym for CREATE DATABASE. CREATE DATABASE Syntax
just click file in your android studio then click Sync Project with Gradle Files..
if it won't work, click Build click Clean Project.
it always work for me
Hope you dont mind Xml.Linq and .net3.5+
XElement ele = XElement.Load("text.xml");
String aXmlString = ele.toString(SaveOptions.DisableFormatting);
Depending on what you are interested in, you can probably skip the whole 'string' var part and just use XLinq objects
Go to your java directory, Copy this path C:\Program Files\Java\jdk1.8.0_40\bin
Right click on my computer , click properties, then go to "Advanced system settings" click , Environment variables. go to "System variables" table, find an entry named "path". Double click it and go to the end, put a semicolon and paste your path, apply and ok. It should run now.
Windows 10 build 15063 "Creators Update" natively supports SVG images (though with some gotchas) to UWP/UAP applications targeting Windows 10.
If your application is a WPF app rather than a UWP/UAP, you can still use this API (after jumping through quite a number of hoops): Windows 10 build 17763 "October 2018 Update" introduced the concept of XAML islands (as a "preview" technology but I believe allowed in the app store; in all cases, with Windows 10 build 18362 "May 2019 Update" XAML islands are no longer a preview feature and are fully supported) allowing you to use UWP APIs and controls in your WPF applications.
You need to first add the references to the WinRT APIs, and to use certain Windows 10 APIs that interact with user data or the system (e.g. loading images from disk in a Windows 10 UWP webview or using the toast notification API to show toasts), you also need to associate your WPF application with a package identity, as shown here (immensely easier in Visual Studio 2019). This shouldn't be necessary to use the Windows.UI.Xaml.Media.Imaging.SvgImageSource
class, though.
Usage (if you're on UWP or you've followed the directions above and added XAML island support under WPF) is as simple as setting the Source
for an <Image />
to the path to the SVG. That is equivalent to using SvgImageSource
, as follows:
<Image>
<Image.Source>
<SvgImageSource UriSource="Assets/svg/icon.svg" />
</Image.Source>
</Image>
However, SVG images loaded in this way (via XAML) may load jagged/aliased. One workaround is to specify a RasterizePixelHeight
or RasterizePixelWidth
value that is double+ your actual height/width:
<SvgImageSource RasterizePixelHeight="300" RasterizePixelWidth="300" UriSource="Assets/svg/icon.svg" /> <!-- presuming actual height or width is under 150 -->
This can be worked around dynamically by creating a new SvgImageSource
in the ImageOpened
event for the base image:
var svgSource = new SvgImageSource(new Uri("ms-appx://" + Icon));
PrayerIcon.ImageOpened += (s, e) =>
{
var newSource = new SvgImageSource(svgSource.UriSource);
newSource.RasterizePixelHeight = PrayerIcon.DesiredSize.Height * 2;
newSource.RasterizePixelWidth = PrayerIcon.DesiredSize.Width * 2;
PrayerIcon2.Source = newSource;
};
PrayerIcon.Source = svgSource;
The aliasing may be hard to see on non high-dpi screens, but here's an attempt to illustrate it.
This is the result of the code above: an Image
that uses the initial SvgImageSource
, and a second Image
below it that uses the SvgImageSource created in the ImageOpened
event:
This is a blown up view of the top image:
Whereas this is a blown-up view of the bottom (antialiased, correct) image:
(you'll need to open the images in a new tab and view at full size to appreciate the difference)
In my case , issue was completely different. I have two classes let's say c1 & c2. Between C1 & C2 dependency is OneToMany. Now if i am saving C1 in DB it was throwing above error.
Resolution of this problem was to get first C2's id from consumer request and find C2 via repository call.Afterwards save c2 into C1 object .Now if i am saving C1, it's working fine.
The descriptor is how Python's property
type is implemented. A descriptor simply implements __get__
, __set__
, etc. and is then added to another class in its definition (as you did above with the Temperature class). For example:
temp=Temperature()
temp.celsius #calls celsius.__get__
Accessing the property you assigned the descriptor to (celsius
in the above example) calls the appropriate descriptor method.
instance
in __get__
is the instance of the class (so above, __get__
would receive temp
, while owner
is the class with the descriptor (so it would be Temperature
).
You need to use a descriptor class to encapsulate the logic that powers it. That way, if the descriptor is used to cache some expensive operation (for example), it could store the value on itself and not its class.
An article about descriptors can be found here.
EDIT: As jchl pointed out in the comments, if you simply try Temperature.celsius
, instance
will be None
.
A bit of a late entry - but hopefully still useful to someone out there:-
Here's a simplified snippet for sending an in-memory string as an email attachment (a CSV file in this particular case).
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream)) // using UTF-8 encoding by default
using (var mailClient = new SmtpClient("localhost", 25))
using (var message = new MailMessage("[email protected]", "[email protected]", "Just testing", "See attachment..."))
{
writer.WriteLine("Comma,Seperated,Values,...");
writer.Flush();
stream.Position = 0; // read from the start of what was written
message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv"));
mailClient.Send(message);
}
The StreamWriter and underlying stream should not be disposed until after the message has been sent (to avoid ObjectDisposedException: Cannot access a closed Stream
).
- Abstract class
is one which can't be instantiated, i.e. its object
cannot be created.
- Abstract method
are method's declaration without its definition.
- A Non-abstract class
can only have Non-abstract methods.
- An Abstract class
can have both the Non-abstract as well as Abstract methods.
- If the Class
has an Abstract method
then the class must also be Abstract.
- An Abstract method
must be implemented by the very first Non-Abstract sub-class.
- Abstract class
in Design patterns
are used to encapsulate the behaviors that keeps changing.
It has nothing to do with jQuery, it's just a handy js method built into modern browsers.
Think of it as a handy alternative to debugging via window.alert()
I'm not really too clear what you are asking, but using the -f
command line option just specifies a file - it doesn't tell make to change directories. If you want to do the work in another directory, you need to cd
to the directory:
clean:
cd gtest-1.4.0 && $(MAKE) clean
Note that each line in Makefile
runs in a separate shell, so there is no need to change the directory back.
I heartily recommended dbVis. The client runs on Mac, Windows and Linux and supports a variety of database servers, including PostgreSQL.
In addition to the other answers here showing you how to git checkout <the-hash-you-want>
it's worth knowing you can switch back to where you were using:
git checkout @{-1}
This is often more convenient than:
git checkout what-was-that-original-branch-called-again-question-mark
As you might anticipate, git checkout @{-2}
will take you back to the branch you were at two git checkout
s ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.
Sadly for productivity, git checkout @{1}
does not take you to the branch you will be on in future, which is a shame.
Understand that .children
is a property of an Element. 1 Only Elements have .children
, and these children are all of type Element. 2
However, .childNodes
is a property of Node. .childNodes
can contain any node. 3
A concrete example would be:
let el = document.createElement("div");
el.textContent = "foo";
el.childNodes.length === 1; // Contains a Text node child.
el.children.length === 0; // No Element children.
Most of the time, you want to use .children
because generally you don't want to loop over Text or Comment nodes in your DOM manipulation.
If you do want to manipulate Text nodes, you probably want .textContent
instead. 4
1. Technically, it is an attribute of ParentNode, a mixin included by Element.
2. They are all elements because .children
is a HTMLCollection, which can only contain elements.
3. Similarly, .childNodes
can hold any node because it is a NodeList.
4. Or .innerText
. See the differences here or here.
The following article perhaps goes into some more detail as to which is a better choice; throw 'An error'
or throw new Error('An error')
:
http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/
It suggests that the latter (new Error()
) is more reliable, since browsers like Internet Explorer and Safari (unsure of versions) don't correctly report the message when using the former.
Doing so will cause an error to be thrown, but not all browsers respond the way you’d expect. Firefox, Opera, and Chrome each display an “uncaught exception” message and then include the message string. Safari and Internet Explorer simply throw an “uncaught exception” error and don’t provide the message string at all. Clearly, this is suboptimal from a debugging point of view.
If you are just looping through 10k rows in column A, then dump the row into a variant array and then loop through that.
You can then either add the elements to a new array (while adding rows when needed) and using Transpose() to put the array onto your range in one move, or you can use your iterator variable to track which row you are on and add rows that way.
Dim i As Long
Dim varray As Variant
varray = Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value
For i = 1 To UBound(varray, 1)
' do stuff to varray(i, 1)
Next
Here is an example of how you could add rows after evaluating each cell. This example just inserts a row after every row that has the word "foo" in column A. Not that the "+2" is added to the variable i during the insert since we are starting on A2. It would be +1 if we were starting our array with A1.
Sub test()
Dim varray As Variant
Dim i As Long
varray = Range("A2:A10").Value
'must step back or it'll be infinite loop
For i = UBound(varray, 1) To LBound(varray, 1) Step -1
'do your logic and evaluation here
If varray(i, 1) = "foo" Then
'not how to offset the i variable
Range("A" & i + 2).EntireRow.Insert
End If
Next
End Sub
when you click div with addproduct class one event is fired for that particular element, not five. you're doing something wrong in you code if event is fired 5 times.
I had the same problem and I solved it by using an absolute import instead of a relative one.
for example in your case, you will write something like this:
from app.mymodule import myclass
You can see in the documentation.
Note that relative imports are based on the name of the current module. Since the name of the main module is always "
__main__
", modules intended for use as the main module of a Python application must always use absolute imports.
A simple example would be
DECLARE @number INTEGER
DECLARE @length INTEGER
DECLARE @char NVARCHAR(10)
SET @number = 1
SET @length = 5
SET @char = '0'
SELECT FORMAT(@number, replicate(@char, @length))
var data = $('<div>').html('[{"Id":1,"Name":"Name}]')[0].textContent;
that should parse all the encoded values you need.
Recursive traverse object or array with array or objects elements:
function traverse(&$objOrArray)
{
foreach ($objOrArray as $key => &$value)
{
if (is_array($value) || is_object($value))
{
traverse($value);
}
else
{
// DO SOMETHING
}
}
}
To add some clarification here, when you create your service, the service class uses the default 'wsdlLocation', which was inserted into it when the class was built from the wsdl. So if you have a service class called SomeService, and you create an instance like this:
SomeService someService = new SomeService();
If you look inside SomeService, you will see that the constructor looks like this:
public SomeService() {
super(__getWsdlLocation(), SOMESERVICE_QNAME);
}
So if you want it to point to another URL, you just use the constructor that takes a URL argument (there are 6 constructors for setting qname and features as well). For example, if you have set up a local TCP/IP monitor that is listening on port 9999, and you want to redirect to that URL:
URL newWsdlLocation = new URL("http://theServerName:9999/somePath");
SomeService someService = new SomeService(newWsdlLocation);
and that will call this constructor inside the service:
public SomeService(URL wsdlLocation) {
super(wsdlLocation, SOMESERVICE_QNAME);
}
If you add this to your meta tags:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
IE8 will render the page like IE7.
URL url = new URL("https://www.google.com");
//if you are using
URLConnection conn =url.openConnection();
//change it to
HttpURLConnection conn =(HttpURLConnection )url.openConnection();
does mail.exampleserver.com exist ??? , if not try the following code (you must have gmail account)
$mail->SMTPSecure = "ssl";
$mail->Host='smtp.gmail.com';
$mail->Port='465';
$mail->Username = '[email protected]'; // SMTP account username
$mail->Password = 'your gmail password';
$mail->SMTPKeepAlive = true;
$mail->Mailer = "smtp";
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->CharSet = 'utf-8';
$mail->SMTPDebug = 0;
You could move the common parts to another configuration file and include
from both server contexts. This should work:
server {
listen 80;
server_name server1.example;
...
include /etc/nginx/include.d/your-common-stuff.conf;
}
server {
listen 80;
server_name another-one.example;
...
include /etc/nginx/include.d/your-common-stuff.conf;
}
Edit: Here's an example that's actually copied from my running server. I configure my basic server settings in /etc/nginx/sites-enabled
(normal stuff for nginx on Ubuntu/Debian). For example, my main server bunkus.org
's configuration file is /etc/nginx/sites-enabled
and it looks like this:
server {
listen 80 default_server;
listen [2a01:4f8:120:3105::101:1]:80 default_server;
include /etc/nginx/include.d/all-common;
include /etc/nginx/include.d/bunkus.org-common;
include /etc/nginx/include.d/bunkus.org-80;
}
server {
listen 443 default_server;
listen [2a01:4f8:120:3105::101:1]:443 default_server;
include /etc/nginx/include.d/all-common;
include /etc/nginx/include.d/ssl-common;
include /etc/nginx/include.d/bunkus.org-common;
include /etc/nginx/include.d/bunkus.org-443;
}
As an example here's the /etc/nginx/include.d/all-common
file that's included from both server
contexts:
index index.html index.htm index.php .dirindex.php;
try_files $uri $uri/ =404;
location ~ /\.ht {
deny all;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
location ~ /(README|ChangeLog)$ {
types { }
default_type text/plain;
}
%02x
means print at least 2 digits, prepend it with 0
's if there's less. In your case it's 7 digits, so you get no extra 0
in front.
Also, %x
is for int, but you have a long. Try %08lx
instead.
Use this
//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text(),'Some text')]
OR
//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(.,'Some text')]
You didn't specify your IDEA version. Before 9.0 use Build | Build Jars, in IDEA 9.0 use Project Structure | Artifacts.
For an example of why it might be desirable to suppress selection, see SIMILE TImeline, which uses drag-and-drop to explore the timeline, during which accidental vertical mouse movement causes the labels to be highlighted unexpectedly, which looks weird.
Or You can use
grep -n . file1 |tail -LineNumberToStartWith|grep regEx
This will take care of numbering the lines in the file
grep -n . file1
This will print the last-LineNumberToStartWith
tail -LineNumberToStartWith
And finally it will grep your desired lines(which will include line number as in orignal file)
grep regEX
This variant -
<a title="Some "text"">Hover me</a>
_x000D_
Is correct and it works as expected - you see normal quotes in rendered page.
Try opening config-db.php, it's inside /etc/phpmyadmin. In my case, the user was phpmyadmin, and my password was correct. Maybe your problem is that you're using the usual 'root' username, and your password could be correct.
Netbeans needs to be able to index the maven repository. Allow it to do that and try again. It was giving me the same error and after it indexed the repository it ran like a charm
The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:
git push origin master
Which will create this new master branch for you. Little things like this are very confusing with git.
If this didn't fix your issue then it's probably a gitolite-related issue:
Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:
repo phonegap
RW+ = myusername otherusername
repo gitolite-admin
RW+ = myusername
Please make sure you're setting your conf file correctly.
Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.
Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.
As another guy described here, all you need to do is add
height: 100vh;
to the style of whatever you need to fill the screen
Helping you further, where Mick Sharpe left you:
It's deriveration is quite simple: see http://en.wikipedia.org/wiki/Logarithm -> Group Theory
log(n!) = log(n * (n-1) * (n-2) * ... * 2 * 1) = log(n) + log(n-1) + ... + log(2) + log(1)
Think of n as infinitly big. What is infinite minus one? or minus two? etc.
log(inf) + log(inf) + log(inf) + ... = inf * log(inf)
And then think of inf as n.
Ok I found out:
You have to put /show
a after the URL you're working on:
http://jsfiddle.net/<your_fiddle_id>/show/
It is the site that shows the results.
And then when you save it as a file. It is all in one HTML-file.
For example:
http://jsfiddle.net/Ua8Cv/show/
for the site http://jsfiddle.net/Ua8Cv
Yes that is valid syntax but it may well not do what you want.
Execution will continue after your RAISERROR
except if you add a RETURN
. So you will need to add a block with BEGIN ... END
to hold the two statements.
Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.
Finally I'd simplify the conditions using IN
CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
@UserType TINYINT,
@UserName NVARCHAR(100),
@Password NVARCHAR(100))
AS
BEGIN
IF ( @TenantId IS NULL
AND @UserType IN ( 0, 1 ) )
BEGIN
RAISERROR('The value for @TenantID should not be null',15,1);
RETURN;
END
END
One more way to do it (if you use form), note that input type is button
<input type="button" onclick="showMessage()" value="submit" />
Complete code is:
<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
But you can do it even without form:
<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
Enter message: <input type="text" id = "message">
<input type="submit" onclick="showMessage()" value="submit" />
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
Here you can use either submit or button:
<input type="submit" onclick="showMessage()" value="submit" />
No need to set
return false;
from JavaScript function for neither of those two examples.
In PHP, you can just put an extra $
in front of a variable to make it a dynamic variable :
$$variableName = $value;
While I wouldn't recommend it, you could even chain this behavior :
$$$$$$$$DoNotTryThisAtHomeKids = $value;
You can but are not forced to put $variableName
between {}
:
${$variableName} = $value;
Using {}
is only mandatory when the name of your variable is itself a composition of multiple values, like this :
${$variableNamePart1 . $variableNamePart2} = $value;
It is nevertheless recommended to always use {}
, because it's more readable.
Another reason to always use {}
, is that PHP5 and PHP7 have a slightly different way of dealing with dynamic variables, which results in a different outcome in some cases.
In PHP7, dynamic variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the mix of special cases in PHP5. The examples below show how the order of evaluation has changed.
$$foo['bar']['baz']
${$foo['bar']['baz']}
${$foo}['bar']['baz']
$foo->$bar['baz']
$foo->{$bar['baz']}
$foo->{$bar}['baz']
$foo->$bar['baz']()
$foo->{$bar['baz']}()
$foo->{$bar}['baz']()
Foo::$bar['baz']()
Foo::{$bar['baz']}()
Foo::{$bar}['baz']()
],\s*
],\n
I came up with another implementation documented at, http://blog.sangupta.com/2010/05/encodeuricomponent-and.html. The implementation can also handle Unicode bytes.
Possible solution with string_view
void do_it_with_string_view( void )
{
std::string a { "12345" };
for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
std::cout << v.substr( 0, 2 ) << " ";
std::cout << std::endl;
}
If class has only one empty constructor (like Activity or Fragment etc, android classes):
Class<?> myClass = Class.forName("com.example.MyClass");
Constructor<?> constructor = myClass.getConstructors()[0];
In python, Suppose you have loaded up the data in some variable train:
train = pandas.read_csv('file_name')
>>> train
train([[ 1., 2., 3.],
[ 5., 1., 2.]],)
I want to check what are the dimensions of the 'file_name'. I have stored the file in train
>>>train.shape
(2,3)
>>>train.shape[0] # will display number of rows
2
>>>train.shape[1] # will display number of columns
3
How about this?
fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2);
In this case spaces in fscanf
match multiple occurrences of any whitespace until the next token in found.
I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:
template <template<class> class H, class S>
void f(const H<S> &value) {
}
Here, H
is a template, but I wanted this function to deal with all specializations of H
.
NOTE: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!).
I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that std::vector
doesn't have a typedef value_type
.
So how would you write a function which can create variables of the right type for the vectors elements? This would work.
template <template<class, class> class V, class T, class A>
void f(V<T, A> &v) {
// This can be "typename V<T, A>::value_type",
// but we are pretending we don't have it
T temp = v.back();
v.pop_back();
// Do some work on temp
std::cout << temp << std::endl;
}
NOTE: std::vector
has two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly.
which you can use like this:
f<std::vector, int>(v); // v is of type std::vector<int> using any allocator
or better yet, we can just use:
f(v); // everything is deduced, f can deal with a vector of any type!
UPDATE: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing auto
. Now the same function can be written as:
template <class Cont>
void f(Cont &v) {
auto temp = v.back();
v.pop_back();
// Do some work on temp
std::cout << temp << std::endl;
}
which is how I'd prefer to write this type of code.
In Swift 3,
let date = Date()
let calendar = Calendar.current()
let hour = calendar.component(.hour, from: date)
//xn=list of parent nodes......
foreach (XmlNode xn in xnList)
{
foreach (XmlNode child in xn.ChildNodes)
{
if (child.Name.Equals("name"))
{
name = child.InnerText;
}
if (child.Name.Equals("age"))
{
age = child.InnerText;
}
}
}
Having two divs,
<div id="div1">The two divs are</div>
<div id="div2">next to each other.</div>
you could also use the display
property:
#div1 {
display: inline-block;
}
#div2 {
display: inline-block;
}
jsFiddle example here.
If div1
exceeds a certain height, div2
will be placed next to div1
at the bottom. To solve this, use vertical-align:top;
on div2
.
jsFiddle example here.
Call() takes comma-separated arguments, ex:
.call(scope, arg1, arg2, arg3)
and apply() takes an array of arguments, ex:
.apply(scope, [arg1, arg2, arg3])
here are few more usage examples: http://blog.i-evaluation.com/2012/08/15/javascript-call-and-apply/
import angularFirebaseStore
in app.module.ts
and set it as a provider like service
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>teste4</groupId>
<artifactId>teste4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>bootstrap</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.Final</version>
</dependency>
</dependencies>
</project>
The "error_page" parameter makes a redirect, converting the request method to "GET", it is not a custom response page.
The easiest solution is
server{
root /var/www/html;
location ~ \.php {
if (!-f $document_root/$fastcgi_script_name){
return 404;
}
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params.default;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
By the way, if you want Nginx to process 404 status returned by PHP scripts, you need to add
[fastcgi_intercept_errors][1] on;
E.g.
location ~ \.php {
#...
error_page 404 404.html;
fastcgi_intercept_errors on;
}
This Python snippet will git mv --force
all files in a directory to be lowercase. For example, foo/Bar.js will become foo/bar.js via git mv foo/Bar.js foo/bar.js --force
.
Modify it to your liking. I just figured I'd share :)
import os
import re
searchDir = 'c:/someRepo'
exclude = ['.git', 'node_modules','bin']
os.chdir(searchDir)
for root, dirs, files in os.walk(searchDir):
dirs[:] = [d for d in dirs if d not in exclude]
for f in files:
if re.match(r'[A-Z]', f):
fullPath = os.path.join(root, f)
fullPathLower = os.path.join(root, f[0].lower() + f[1:])
command = 'git mv --force ' + fullPath + ' ' + fullPathLower
print(command)
os.system(command)
This script below should put you on the right track perhaps?
You can keep this html the same (though I changed the method to POST):
<form method="POST" id="subscribeForm">
<fieldset id="cbgroup">
<div><input name="list" id="list0" type="checkbox" value="newsletter0" >zero</div>
<div><input name="list" id="list1" type="checkbox" value="newsletter1" >one</div>
<div><input name="list" id="list2" type="checkbox" value="newsletter2" >two</div>
</fieldset>
<input name="submit" type="submit" value="submit">
</form>
and this javascript validates
function onSubmit()
{
var fields = $("input[name='list']").serializeArray();
if (fields.length === 0)
{
alert('nothing selected');
// cancel submit
return false;
}
else
{
alert(fields.length + " items selected");
}
}
// register event on form, not submit button
$('#subscribeForm').submit(onSubmit)
and you can find a working example of it here
UPDATE (Oct 2012)
Additionally it should be noted that the checkboxes must have a "name" property, or else they will not be added to the array. Only having "id" will not work.
UPDATE (May 2013)
Moved the submit registration to javascript and registered the submit onto the form (as it should have been originally)
UPDATE (June 2016)
Changes == to ===
You can use array_agg
function for that:
SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";
Result:
MOVIE | ACTOR |
---|---|
A | 1,2,3 |
B | 4 |
See this SQLFiddle
For more See 9.18. Aggregate Functions
The SQLiteDatabase object depends on the type of operation on the database.
More information, visit the official website:
https://developer.android.com/training/basics/data-storage/databases.html#UpdateDbRow
It explains how to manipulate consultations on the SQLite database.
Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);
Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedEntry.TABLE_NAME,
FeedEntry.COLUMN_NAME_NULLABLE,
values);
Define 'where' part of query.
String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
Specify arguments in placeholder order.
String[] selectionArgs = { String.valueOf(rowId) };
SQLiteDatabase db = mDbHelper.getReadableDatabase();
New value for one column
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
Which row to update, based on the ID
String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
int count = db.update(
FeedReaderDbHelper.FeedEntry.TABLE_NAME,
values,
selection,
selectionArgs);
You can also take a look at the built-in .NET tracing facilities too. There's a set of trace listeners that allow you to output to a log file, but you can configure it to log into the Event viewer, or to a database (or all of them simultaneously).
http://www.codeguru.com/csharp/.net/net_debugging/tracing/article.php/c5919/NET-Tracing-Tutorial.htm
subprocess.check_output()
returns a bytestring.
In Python 3, there's no implicit conversion between unicode (str
) objects and bytes
objects. If you know the encoding of the output, you can .decode()
it to get a string, or you can turn the \n
you want to add to bytes
with "\n".encode('ascii')
If, at some point, you only need to export a single result set, just right click "on the data" (any column of any row) there you will find an export option. The wizard exports the complete result set regardless of what you selected
You can replace the values "null" from the original file & field/column.
you can also extract an individual table with the --no-data
option
mysqldump -u user -h localhost --no-data -p database tablename > table.sql
Go to tools
>> nuget
>> console
and type:
Install-Package System.Configuration.ConfigurationManager
If you want a specific version:
Install-Package System.Configuration.ConfigurationManager -Version 4.5.0
Your ConfigurationManager
dll will now be imported and the code will begin to work.
You can use link-rewriting to append a unique identifier to all your URLs when starting at a single page (e.g. index.html/jsp/whatever). The browser will use the same cookies for all your tabs so everything you put in cookies will not be unique.
(Because an ASCII picture is worth a thousand characters.)
An arrow may be a helpful mnemonic, especially since that's almost exactly how it looks in Emacs' dired.
And big picture so you don't get it confused with the Windows' version
Linux:
ln -s target <- linkName
Windows:
mklink linkName -> target
You could also look at these as
ln -s "to-here" <- "from-here"
mklink "from-here" -> "to-here"
The from-here
should not exist yet, it is to be created, while the to-here
should already exist (IIRC).
(I always get mixed up on whether various commands and arguments should involve a pre-existing location, or one to be made.)
EDIT: It's still sinking in slowly for me; I have another way I've written in my notes.
ln -s (target exists) (link is made)
mklink (link is made) (target exists)
The best way to force the use of a number composed of digits only:
<input type="number" onkeydown="javascript: return event.keyCode === 8 ||_x000D_
event.keyCode === 46 ? true : !isNaN(Number(event.key))" />
_x000D_
To allow number keys only:
isNaN(Number(event.key))
but accept "Backspace" (keyCode: 8) and "Delete" (keyCode: 46) ...
create an xml gradient.xml file under drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle" >
<corners android:radius="50dip" />
<stroke android:width="1dip" android:color="#667162" />
<gradient android:angle="-90" android:startColor="#ffffff" android:endColor="#ffffff" />
</shape>
</item>
</selector>
then add this to your TextView
android:background="@drawable/gradient"
Use:
<!-- For Google -->
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<meta name="copyright" content="" />
<meta name="application-name" content="" />
<!-- For Facebook -->
<meta property="og:title" content="" />
<meta property="og:type" content="article" />
<meta property="og:image" content="" />
<meta property="og:url" content="" />
<meta property="og:description" content="" />
<!-- For Twitter -->
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="" />
<meta name="twitter:description" content="" />
<meta name="twitter:image" content="" />
Fill the content =" ... " according to the content of your page.
For more information, visit 18 Meta Tags Every Webpage Should Have in 2013.
Little addition to Jason's answer:
ToShortDateString()
is culture-sensitive.From MSDN:
The string returned by the ToShortDateString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short date pattern is "M/d/yyyy"; for the de-DE culture, it is "dd.MM.yyyy"; for the ja-JP culture, it is "yyyy/M/d". The specific format string on a particular computer can also be customized so that it differs from the standard short date format string.
That's mean it's better to use the ToString()
method and define format explicitly (as Jason said). Although if this string appeas in UI the ToShortDateString()
is a good solution because it returns string which is familiar to a user.
DateTime.Today
.try this
[yourTableView setBounces:NO];
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element? If so here's how you can do it pretty easily:
//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
If you are using Angular 4+ then you can just use titlecase
{{toUppercase | titlecase}}
don't have to write any pipes.
You should try JRebel, which does the hot deploy stuff pretty well. A bit expensive, but worth the money. They have a trial version.
$().ready(function(){_x000D_
_x000D_
$('div.alert').delay(1500);_x000D_
$('div.alert').hide(1000);_x000D_
});
_x000D_
div.alert{_x000D_
color: green;_x000D_
background-color: rgb(50,200,50, .5);_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert"><p>Inserted Successfully . . .</p></div>
_x000D_
4 years after the question got posted, but maybe it will help others who run into this problem. The answer has been posted elsewhere on StackExchange as well, but I lost the link and it's hard to find.
ANSWER: In jQueryTOOLS, the jQuery 'core' is also embedded if you use the default download.
When you load jQuery and jQuery tools, jQuery core gets defined twice and will 'unset' any plugins. 'Draggable' (from jQuery-UI) is such a plug-in.
The solution is to use jQuery tools WITHOUT the jQuery 'core' files and everything will work fine.
In my case the problem was that a method was defined in some Interface A
as default
, while its sub-class overrode it as private. Then when the method was called, the java Runtime realized it was calling a private method.
I am still puzzled as to why the compiler didn't complain about the private override..
public interface A {
default void doStuff() {
// doing stuff
}
}
public class B {
private void doStuff() {
// do other stuff instead
}
}
public static final main(String... args) {
A someB = new B();
someB.doStuff();
}
There's no reason to use set
unless referring to an object reference. It's good practice to only use it in that context. For all other simple data types, just use an assignment operator. It's a good idea to dim
(dimension) ALL variables however:
Examples of simple data types would be integer
, long
, boolean
, string
. These are just data types and do not have their own methods and properties.
Dim i as Integer
i = 5
Dim myWord as String
myWord = "Whatever I want"
An example of an object
would be a Range
, a Worksheet
, or a Workbook
. These have their own methods and properties.
Dim myRange as Range
Set myRange = Sheet1.Range("A1")
If you try to use the last line without Set
, VB will throw an error. Now that you have an object
declared you can access its properties and methods.
myString = myRange.Value
This is because, in the constructor, you declared a local variable with the same name as an attribute.
To allocate an integer array which all elements are initialized to zero, write this in the constructor:
data = new int[3];
To allocate an integer array which has other initial values, put this code in the constructor:
int[] temp = {2, 3, 7};
data = temp;
or:
data = new int[] {2, 3, 7};
try this:
public int getIndexOfMin(List<Float> data) {
float min = Float.MAX_VALUE;
int index = -1;
for (int i = 0; i < data.size(); i++) {
Float f = data.get(i);
if (Float.compare(f.floatValue(), min) < 0) {
min = f.floatValue();
index = i;
}
}
return index;
}
You should use options.addAll(allPoints);
instead of options.add(point);
There are (at least) two different use cases which could be described as "search the bucket":
Search for something inside every object stored at the bucket; this assumes a common format for all the objects in that bucket (say, text files), etc etc. For something like this, you're forced to do what Cody Caughlan just answered. The AWS S3 docs has example code showing how to do this with the AWS SDK for Java: Listing Keys Using the AWS SDK for Java (there you'll also find PHP and C# examples).
List item Search for something in the object keys contained in that bucket; S3 does have partial support for this, in the form of allowing prefix exact matches + collapsing matches after a delimiter. This is explained in more detail at the AWS S3 Developer Guide. This allows, for example, to implement "folders" through using as object keys something like
folder/subfolder/file.txtIf you follow this convention, most of the S3 GUIs (such as the AWS Console) will show you a folder view of your bucket.
There is no such class as DateTime
in the standard Java SE API. Although there is one in joda-time, even that does not have a daysBetween
method.
Using the standard Java API, the easiest way to get seconds between two java.util.Date
objects would be to subtract their timestamps and divide by 1000:
int secondsBetween = (date1.getTime() - date2.getTime()) / 1000;
Apache MPM prefork with modphp is used because it is easy to configure/install. Performance-wise it is fairly inefficient. My preferred way to do the stack, FastCGI/PHP-FPM. That way you can use the much faster MPM Worker. The whole PHP remains non-threaded, but Apache serves threaded (like it should).
So basically, from bottom to top
Linux
Apache + MPM Worker + ModFastCGI (NOT FCGI) |(or)| Cherokee |(or)| Nginx
PHP-FPM + APC
ModFCGI does not correctly support PHP-FPM, or any external FastCGI applications. It only supports non-process managed FastCGI scripts. PHP-FPM is the PHP FastCGI process manager.
One thing you can do is this:
$(this)[0].value = "Something";
This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.
I'm getting the same error on Mac OS X 10.11.6:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
After a lot of agonizing and digging through advice here and in related questions, none of which seemed to fix the problem, I went back and deleted the installed folders, and just did brew install mysql
.
Still getting the same error with most commands, but this works:
/usr/local/bin/mysqld
and returns:
/usr/local/bin/mysqld: ready for connections.
Version: '5.7.12' socket: '/tmp/mysql.sock' port: 3306 Homebrew
Just don't include the columns that you want to use the default value for in your insert statement. For instance:
INSERT INTO table1 (field1, field3) VALUES (5, 10);
...will take the default values for field2
and field4
, and assign 5 to field1
and 10 to field3
.
I found the cleanest way of doing it is this.
Tested on Django 3.1.5
class MyForm(forms.Form):
my_boolean = forms.BooleanField(required=False, initial=True)
I have some code which is similar, but does not rewrite the entire contents each time. This is meant to run periodically and append a JSON entry at the end of an array.
If the file doesn't exist yet, it creates it and dumps the JSON into an array. If the file has already been created, it goes to the end, replaces the ]
with a ,
drops the new JSON object in, and then closes it up again with another ]
# Append JSON object to output file JSON array
fname = "somefile.txt"
if os.path.isfile(fname):
# File exists
with open(fname, 'a+') as outfile:
outfile.seek(-1, os.SEEK_END)
outfile.truncate()
outfile.write(',')
json.dump(data_dict, outfile)
outfile.write(']')
else:
# Create file
with open(fname, 'w') as outfile:
array = []
array.append(data_dict)
json.dump(array, outfile)
If you are accessing a plain HTML form, it has to be submitted to the server via a submit button (or via javascript post). This usually means that your form definition will look like this (I'm going off of memory, make sure you check the html elements are correct):
<form method="POST" action="page.aspx">
<input id="customerName" name="customerName" type="Text" />
<input id="customerPhone" name="customerPhone" type="Text" />
<input value="Save" type="Submit" />
</form>
You should be able to access the customerName and customerPhone data like this:
string n = String.Format("{0}", Request.Form["customerName"]);
If you have method="GET"
in the form (not recommended, it messes up your URL space), you will have to access the form data like this:
string n = String.Format("{0}", Request.QueryString["customerName"]);
This of course will only work if the form was 'Posted', 'Submitted', or done via a 'Postback'. (i.e. somebody clicked the 'Save' button, or this was done programatically via javascript.)
Also, keep in mind that accessing these elements in this manner can only be done when you are not using server controls (i.e. runat="server"
), with server controls the id and name are different.
Have you tried
adb kill-server
adb shell
Sometimes adb gets stuck and first killing adb server and then starting some command forces authorization window to pop-up.
Also please check adb client version on your phone. THis feature is supported from adb 1.0.31 as far as I remember.
Two important notes:
You need to call layoutIfNeeded
within the animation block. Apple actually recommends you call it once before the animation block to ensure that all pending layout operations have been completed
You need to call it specifically on the parent view (e.g. self.view
), not the child view that has the constraints attached to it. Doing so will update all constrained views, including animating other views that might be constrained to the view that you changed the constraint of (e.g. View B is attached to the bottom of View A and you just changed View A's top offset and you want View B to animate with it)
Try this:
Objective-C
- (void)moveBannerOffScreen {
[self.view layoutIfNeeded];
[UIView animateWithDuration:5
animations:^{
self._addBannerDistanceFromBottomConstraint.constant = -32;
[self.view layoutIfNeeded]; // Called on parent view
}];
bannerIsVisible = FALSE;
}
- (void)moveBannerOnScreen {
[self.view layoutIfNeeded];
[UIView animateWithDuration:5
animations:^{
self._addBannerDistanceFromBottomConstraint.constant = 0;
[self.view layoutIfNeeded]; // Called on parent view
}];
bannerIsVisible = TRUE;
}
Swift 3
UIView.animate(withDuration: 5) {
self._addBannerDistanceFromBottomConstraint.constant = 0
self.view.layoutIfNeeded()
}
Had the same issue that the client_max_body_size
directive was ignored.
My silly error was, that I put a file inside /etc/nginx/conf.d
which did not end with .conf
. Nginx will not load these by default.
This way you can set the initial day of the week.
moment.locale('en', {
week: {
dow: 6
}
});
moment.locale('en');
Make sure to use it with moment().weekday(1);
instead of moment.isoWeekday(1)
I had to add blank lines after a table and I manage it adding many divs as I need it with a css style with padding-top set it up, like this. I've used a template engine (underscore) to loop through the number of lines I need to add.
<% var maxRow = 30; var pos = items.models.length; %>
<% for( pos; pos < maxRow; pos++ ){ %>
<div class="blankRow"></div>
<% }; %>
My css file:
.blankRow:{ padding-top: 15px;}
private static readonly ICollection<string> PositiveList = new Collection<string> { "Y", "Yes", "T", "True", "1", "OK" };
public static bool ToBoolean(this string input)
{
return input != null && PositiveList.Any(? => ?.Equals(input, StringComparison.OrdinalIgnoreCase));
}
As of nginx 1.8.0, the correct solution is
sudo nginx -t && sudo service nginx reload
Note that due to a bug, configtest
always returns a zero exit code even if the config file has an error.
UEFA or FIFA don't seem to provide any API to get the information you want. However, there are some third-party services which support that:
OPTA - Both commercial and free. They have incredible database about matches. Whoscored.com currently uses it.
Others: livescoreboards, xmlsoccer, ...
You should use view models and forget about ViewBag
Think of it as if it didn't exist. You will see how easier things will become. So define a view model:
public class MyViewModel
{
public int SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
and then populate this view model from the controller:
public ActionResult NewsEdit(int ID, dms_New dsn)
{
var dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();
var categories = (from b in dc.dms_NewsCategories select b).ToList();
var model = new MyViewModel
{
SelectedCategoryId = dsn.NewsCategoriesID,
Categories = categories.Select(x => new SelectListItem
{
Value = x.NewsCategoriesID.ToString(),
Text = x.NewsCategoriesName
})
};
return View(model);
}
and finally in your view use the strongly typed DropDownListFor
helper:
@model MyViewModel
@Html.DropDownListFor(
x => x.SelectedCategoryId,
Model.Categories
)
You can use jQuery to get text in textbox (work well for me), check in image detail
Code:
$(document.evaluate( "xpath" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()
Example:
$(document.evaluate( "//*[@id='mail']" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()
Inject this above query to your code. Image detail:
The Angular version with no third-party libraries (based on personal_cloud's answer):
import { Component, Renderer2, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit, OnDestroy {
@ViewChild('leftPanel', {static: true})
leftPanelElement: ElementRef;
@ViewChild('rightPanel', {static: true})
rightPanelElement: ElementRef;
@ViewChild('separator', {static: true})
separatorElement: ElementRef;
private separatorMouseDownFunc: Function;
private documentMouseMoveFunc: Function;
private documentMouseUpFunc: Function;
private documentSelectStartFunc: Function;
private mouseDownInfo: any;
constructor(private renderer: Renderer2) {
}
ngAfterViewInit() {
// Init page separator
this.separatorMouseDownFunc = this.renderer.listen(this.separatorElement.nativeElement, 'mousedown', e => {
this.mouseDownInfo = {
e: e,
offsetLeft: this.separatorElement.nativeElement.offsetLeft,
leftWidth: this.leftPanelElement.nativeElement.offsetWidth,
rightWidth: this.rightPanelElement.nativeElement.offsetWidth
};
this.documentMouseMoveFunc = this.renderer.listen('document', 'mousemove', e => {
let deltaX = e.clientX - this.mouseDownInfo.e.x;
// set min and max width for left panel here
const minLeftSize = 30;
const maxLeftSize = (this.mouseDownInfo.leftWidth + this.mouseDownInfo.rightWidth + 5) - 30;
deltaX = Math.min(Math.max(deltaX, minLeftSize - this.mouseDownInfo.leftWidth), maxLeftSize - this.mouseDownInfo.leftWidth);
this.leftPanelElement.nativeElement.style.width = this.mouseDownInfo.leftWidth + deltaX + 'px';
});
this.documentSelectStartFunc = this.renderer.listen('document', 'selectstart', e => {
e.preventDefault();
});
this.documentMouseUpFunc = this.renderer.listen('document', 'mouseup', e => {
this.documentMouseMoveFunc();
this.documentSelectStartFunc();
this.documentMouseUpFunc();
});
});
}
ngOnDestroy() {
if (this.separatorMouseDownFunc) {
this.separatorMouseDownFunc();
}
if (this.documentMouseMoveFunc) {
this.documentMouseMoveFunc();
}
if (this.documentMouseUpFunc) {
this.documentMouseUpFunc();
}
if (this.documentSelectStartFunc()) {
this.documentSelectStartFunc();
}
}
}
_x000D_
.main {
display: flex;
height: 400px;
}
.left {
width: calc(50% - 5px);
background-color: rgba(0, 0, 0, 0.1);
}
.right {
flex: auto;
background-color: rgba(0, 0, 0, 0.2);
}
.separator {
width: 5px;
background-color: red;
cursor: col-resize;
}
_x000D_
<div class="main">
<div class="left" #leftPanel></div>
<div class="separator" #separator></div>
<div class="right" #rightPanel></div>
</div>
_x000D_
The simplest way I found was this: Creates a TextView or LinearLayout and places it along with the Spinner in a RelativeLayout. Initially the textview will have the text as if it were the hint "Select one ...", after the first click this TextView is invisible, disabled and calls the Spinner that is right behind it.
Step 1:
In the activity.xml that finds the spinner put:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Spinner
android:id="@+id/sp_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:spinnerMode="dropdown" />
<LinearLayout
android:id="@+id/ll_hint_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Select..."/>
</LinearLayout>
</RelativeLayout>
Step 2:
In your Activity.java type:
public class MainActivity extends AppCompatActivity {
private LinearLayout ll_hint_spinner;
private Spinner sp_main;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll_hint_spinner = findViewById(R.id.ll_hint_spinner);
sp_main = findViewById(R.id.sp_main);
//Action after clicking LinearLayout / Spinner;
ll_hint_spinner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//By clicking "Select ..." the Spinner is requested;
sp_main.performClick();
//Make LinearLayout invisible
setLinearVisibility(false);
//Disable LinearLayout
ll_hint_spinner.setEnabled(false);
//After LinearLayout is off, Spinner will function normally;
sp_main.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
sp_main.setSelection(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
setLinearVisibility(true);
}
});
}
});
}
//Method to make LinearLayout invisible or visible;
public void setLinearVisibility(boolean visible) {
if (visible) {
ll_hint_spinner.setVisibility(View.VISIBLE);
} else {
ll_hint_spinner.setVisibility(View.INVISIBLE);
}
}
}
Example1 SameExample2 SameExample3
The examples of the images I used a custom Spinner, but the result of the last example will be the same.
Note: I have the example in github: click here!
Personally I use BNC Advanced Feed Parser- i like the template system that is very easy to use
I also get the same error in an ASP.NET application when I saved some unicode data (Hindi) in the Web.config file and saved it with "Unicode" encoding.
It fixed the error for me when I saved the Web.config file with "UTF-8" encoding.
You don't say which shell you're using. If it's a POSIX-compatible one such as Bash, then parameter expansion can do what you want:
Parameter Expansion
...
${parameter#word}
Remove Smallest Prefix Pattern.
Theword
is expanded to produce a pattern. The parameter expansion then results inparameter
, with the smallest portion of the prefix matched by the pattern deleted.
In other words, you can write
$var="${var#*:}"
which will remove anything matching *:
from $var
(i.e. everything up to and including the first :
). If you want to match up to the last :
, then you could use ##
in place of #
.
This is all assuming that the part to remove does not contain :
(true for IPv4 addresses, but not for IPv6 addresses)
Another way of simply telling if an element exists is to check the count()
if (myset.count(x)) {
// x is in the set, count is 1
} else {
// count zero, i.e. x not in the set
}
Most of the times, however, I find myself needing access to the element wherever I check for its existence.
So I'd have to find the iterator anyway. Then, of course, it's better to simply compare it to end
too.
set< X >::iterator it = myset.find(x);
if (it != myset.end()) {
// do something with *it
}
C++ 20
In C++20 set gets a contains
function, so the following becomes possible as mentioned at: https://stackoverflow.com/a/54197839/895245
if (myset.contains(x)) {
// x is in the set
} else {
// no x
}
SQL databases like Oracle, db2 also support Horizontal scaling through Shared disk cluster. For example Oracle RAC, IBM DB2 purescale or Sybase ASE Cluster edition. New node can be added to Oracle RAC system or DB2 purescale system to achieve horizontal scaling.
But the approach is different from noSQL databases (like mongodb, CouchDB or IBM Cloudant) is that the data sharding is not part of Horizontal scaling. In noSQL databases data is shraded during horizontal scaling.
This error generally occurs when the angular project was not configure completely.
This will work
npm install --save-dev @angular-devkit/build-angular
npm install
Checking Count() before the WHERE clause solved my problem. It is cheaper than ToList()
if (authUserList != null && _list.Count() > 0)
_list = _list.Where(l => authUserList.Contains(l.CreateUserId));
I would like to give another example in which multiple (3) joins are used.
DataClasses1DataContext ctx = new DataClasses1DataContext();
var Owners = ctx.OwnerMasters;
var Category = ctx.CategoryMasters;
var Status = ctx.StatusMasters;
var Tasks = ctx.TaskMasters;
var xyz = from t in Tasks
join c in Category
on t.TaskCategory equals c.CategoryID
join s in Status
on t.TaskStatus equals s.StatusID
join o in Owners
on t.TaskOwner equals o.OwnerID
select new
{
t.TaskID,
t.TaskShortDescription,
c.CategoryName,
s.StatusName,
o.OwnerName
};
W3C doc says regarding "border-radius" property: "supported in IE9+, Firefox, Chrome, Safari, and Opera".
Hence I assume you're testing on IE8 or below.
For "regular elements" there is a solution compatible with IE8 & other old/poor browsers. See below.
HTML:
<div class="myWickedClass">
<span class="myCoolItem">Some text</span> <span class="myCoolItem">Some text</span> <span class="myCoolItem"> Some text</span> <span class="myCoolItem">Some text</span>
</div>
CSS:
.myWickedClass{
padding: 0 5px 0 0;
background: #F7D358 url(../img/roundedCorner_right.png) top right no-repeat scroll;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
font: normal 11px Verdana, Helvetica, sans-serif;
color: #A4A4A4;
}
.myWickedClass > .myCoolItem:first-child {
padding-left: 6px;
background: #F7D358 url(../img/roundedCorner_left.png) 0px 0px no-repeat scroll;
}
.myWickedClass > .myCoolItem {
padding-right: 5px;
}
You need to create both roundedCorner_right.png & roundedCorner_left.png. These are work around for IE8 (& below) to fake the rounded corner feature.
So in this example above we apply the left rounded corner to the first span element in the containing div, & we apply the right rounded corner to the containing div. These images overlap the browser-provided "squary corners" & give the illusion of being part of a rounded element.
The idea for inputs would be to do the same logic. However, input is an empty element, " element is empty, it contains attributes only", in other word, you cannot wrap a span into an input such as <input><span class="myCoolItem"></span></input>
to then use background images like in the previous example.
Hence the solution seems to be to do the opposite: wrap the input into another element. see this answer rounded corners of input elements in IE
// number of digits to be compared
public int n = 12
// n+1 because b/a tends to 1 with n leading digits
public double MyEpsilon { get; } = Math.Pow(10, -(n+1));
public bool IsEqual(double a, double b)
{
// Avoiding division by zero
if (Math.Abs(a)<= double.Epsilon || Math.Abs(b) <= double.Epsilon)
return Math.Abs(a - b) <= double.Epsilon;
// Comparison
return Math.Abs(1.0 - a / b) <= MyEpsilon;
}
Explanation
The main comparison function done using division a/b which should go toward 1. But why division? it simply puts one number as reference defines the second one. For example
a = 0.00000012345
b = 0.00000012346
a/b = 0.999919002
b/a = 1.000081004
(a/b)-1 = 8.099789405475458e-5?
1-(b/a) = 8.100445524503848e-5?
or
a=12345*10^8
b=12346*10^8
a/b = 0.999919002
b/a = 1.000081004
(a/b)-1 = 8.099789405475458e-5?
1-(b/a) = 8.100445524503848e-5?
by division we get rid of trailing or leading zeros (or relatively small numbers) that pollute our judgement of number precision. In the example, the comparison is of order 10^-5, and we have 4 number accuracy, because of that in the beginning code I wrote comparison with 10^(n+1) where n is number accuracy.
Here's my workaround:
I created a library with Angular 6. I added a common component commonlib-header
which is used like this in an external application.
Note the serviceReference
which is the class (injected in the component constructor(public serviceReference: MyService)
that uses the commonlib-header
) that holds the stringFunctionName
method:
<commonlib-header
[logo]="{ src: 'assets/img/logo.svg', alt: 'Logo', href: '#' }"
[buttons]="[{ index: 0, innerHtml: 'Button', class: 'btn btn-primary', onClick: [serviceReference, 'stringFunctionName', ['arg1','arg2','arg3']] }]">
</common-header>
The library component is programmed like this. The dynamic event is added in the onClick(fn: any)
method:
export class HeaderComponent implements OnInit {
_buttons: Array<NavItem> = []
@Input()
set buttons(buttons: Array<any>) {
buttons.forEach(navItem => {
let _navItem = new NavItem(navItem.href, navItem.innerHtml)
_navItem.class = navItem.class
_navItem.onClick = navItem.onClick // this is the array from the component @Input properties above
this._buttons[navItem.index] = _navItem
})
}
constructor() {}
ngOnInit() {}
onClick(fn: any){
let ref = fn[0]
let fnName = fn[1]
let args = fn[2]
ref[fnName].apply(ref, args)
}
The reusable header.component.html
:
<div class="topbar-right">
<button *ngFor="let btn of _buttons"
class="{{ btn.class }}"
(click)="onClick(btn.onClick)"
[innerHTML]="btn.innerHtml | keepHtml"></button>
</div>
Simple and not time consuming answer with an example relevant to the question asked Follow this example:
user = [{"name": "Dough", "age": 55},
{"name": "Ben", "age": 44},
{"name": "Citrus", "age": 33},
{"name": "Abdullah", "age":22},
]
print(sorted(user, key=lambda el: el["name"]))
print(sorted(user, key= lambda y: y["age"]))
Look at the names in the list, they starts with D, B, C and A. And if you notice the ages, they are 55, 44, 33 and 22. The first print code
print(sorted(user, key=lambda el: el["name"]))
Results to:
[{'name': 'Abdullah', 'age': 22},
{'name': 'Ben', 'age': 44},
{'name': 'Citrus', 'age': 33},
{'name': 'Dough', 'age': 55}]
sorts the name, because by key=lambda el: el["name"] we are sorting the names and the names return in alphabetical order.
The second print code
print(sorted(user, key= lambda y: y["age"]))
Result:
[{'name': 'Abdullah', 'age': 22},
{'name': 'Citrus', 'age': 33},
{'name': 'Ben', 'age': 44},
{'name': 'Dough', 'age': 55}]
sorts by age, and hence the list returns by ascending order of age.
Try this code for better understanding.
Create and save a java.awt.image.bufferedImage to file:
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
public static void main(String args[]){
try{
BufferedImage img = new BufferedImage(
500, 500, BufferedImage.TYPE_INT_RGB );
File f = new File("MyFile.png");
int r = 5;
int g = 25;
int b = 255;
int col = (r << 16) | (g << 8) | b;
for(int x = 0; x < 500; x++){
for(int y = 20; y < 300; y++){
img.setRGB(x, y, col);
}
}
ImageIO.write(img, "PNG", f);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Notes:
Thanks to @nekno and @ale84 for great answers.
However, I modified @ale84's script it little to increment build numbers for floating point.
the value of incl can be changed according to your floating format requirements. For eg: if incl = .01, output format would be ... 1.19, 1.20, 1.21 ...
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
incl=.01
buildNumber=`echo $buildNumber + $incl|bc`
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
It`s definitely better to use COMPOSITE UNIQUE KEY, as @GranadaCoder offered, a little bit tricky example though:
ALTER IGNORE TABLE table_name ADD UNIQUES INDEX idx_name(some_id, another_id, one_more_id);
I think the OP is asking the wrong question. The code below will show that it not necessary to manually raise the PropertyChanged
EVENT from a dependency property to achieve the desired result. The way to do it is handle the PropertyChanged
CALLBACK on the dependency property and set values for other dependency properties there. The following is a working example.
In the code below, MyControl
has two dependency properties - ActiveTabInt
and ActiveTabString
. When the user clicks the button on the host (MainWindow
), ActiveTabString
is modified. The PropertyChanged
CALLBACK on the dependency property sets the value of ActiveTabInt
. The PropertyChanged
EVENT is not manually raised by MyControl
.
MainWindow.xaml.cs
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
ActiveTabString = "zero";
}
private string _ActiveTabString;
public string ActiveTabString
{
get { return _ActiveTabString; }
set
{
if (_ActiveTabString != value)
{
_ActiveTabString = value;
RaisePropertyChanged("ActiveTabString");
}
}
}
private int _ActiveTabInt;
public int ActiveTabInt
{
get { return _ActiveTabInt; }
set
{
if (_ActiveTabInt != value)
{
_ActiveTabInt = value;
RaisePropertyChanged("ActiveTabInt");
}
}
}
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private void Button_Click(object sender, RoutedEventArgs e)
{
ActiveTabString = (ActiveTabString == "zero") ? "one" : "zero";
}
}
public class MyControl : Control
{
public static List<string> Indexmap = new List<string>(new string[] { "zero", "one" });
public string ActiveTabString
{
get { return (string)GetValue(ActiveTabStringProperty); }
set { SetValue(ActiveTabStringProperty, value); }
}
public static readonly DependencyProperty ActiveTabStringProperty = DependencyProperty.Register(
"ActiveTabString",
typeof(string),
typeof(MyControl), new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
ActiveTabStringChanged));
public int ActiveTabInt
{
get { return (int)GetValue(ActiveTabIntProperty); }
set { SetValue(ActiveTabIntProperty, value); }
}
public static readonly DependencyProperty ActiveTabIntProperty = DependencyProperty.Register(
"ActiveTabInt",
typeof(Int32),
typeof(MyControl), new FrameworkPropertyMetadata(
new Int32(),
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
static MyControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
}
private static void ActiveTabStringChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
MyControl thiscontrol = sender as MyControl;
if (Indexmap[thiscontrol.ActiveTabInt] != thiscontrol.ActiveTabString)
thiscontrol.ActiveTabInt = Indexmap.IndexOf(e.NewValue.ToString());
}
}
MainWindow.xaml
<StackPanel Orientation="Vertical">
<Button Content="Change Tab Index" Click="Button_Click" Width="110" Height="30"></Button>
<local:MyControl x:Name="myControl" ActiveTabInt="{Binding ActiveTabInt, Mode=TwoWay}" ActiveTabString="{Binding ActiveTabString}"></local:MyControl>
</StackPanel>
App.xaml
<Style TargetType="local:MyControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyControl">
<TabControl SelectedIndex="{Binding ActiveTabInt, Mode=TwoWay}">
<TabItem Header="Tab Zero">
<TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
</TabItem>
<TabItem Header="Tab One">
<TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
</TabItem>
</TabControl>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
If you want to avoid the fopen/fputcsv sub-systems here's a snippet that builds an escaped CSV string from an associative array....
$output = '';
foreach ($list as $row) {
$output .= '"' . implode('", "', array_values($row)) . '"' . "\r\n";
}
Or from a list of objects...
foreach ($list as $obj) {
$output .= '"' . implode('", "', array_values((array) $obj)) . '"' . "\r\n";
}
Then you can output the string as desired.
Be carefull when you use derived query for batch delete. It isn't what you expect: DeleteExecution
The simplest way:
ping hostname
e.g.
ping dynlab938.meng.auth.gr
it will print: Pinging dynlab938.meng.auth.gr [155.207.29.38] with 32 bytes of data
You might want to look into the libero FSM generator software. From a state description language and/or a (windows) state diagram editor you may generate code for C, C++, java and many others ... plus nice documentation and diagrams. Source and binaries from iMatix
If you are looking for a solution that works in IE as well, you could float the list elements to the left. However, this will result in a list that snakes around, like this:
item 1 | item 2 | item 3
item 4 | item 5
Instead of neat columns, like:
item 1 | item 4
item 2 |
item 3 |
The code to do that would be:
ul li {
width:10em;
float:left;
}
You could add a border-bottom to the li
s to make the flow of the items from left to right more apparent.
Format your java.util.Date first. Then use the formatted date to get the date in java.sql.Date
java.util.Date utilDate = "Your date"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
final String stringDate= dateFormat.format(utilDate);
final java.sql.Date sqlDate= java.sql.Date.valueOf(stringDate);
The problem is extra 13 byte which server.py receives at the start. To resolve that write "l = c.recv(1024)" twice before the while loop as below.
print "Receiving..."
l = c.recv(1024) #this receives 13 bytes which is corrupting the data
l = c.recv(1024) # Now actual data starts receiving
while (l):
This resolves the issue, tried with different format and sizes of files. If anyone knows what this starting 13 bytes refers to, please reply.
with x as (
select shoppername,count(shoppername)
from sales
having count(shoppername)>1
group by shoppername)
select t.* from x,win_gp_pin1510 t
where x.shoppername=t.shoppername
order by t.shoppername
try this (in CSS
) for preventing line breaks in div
texts:
white-space: nowrap;
str.charAt(str.length - 1)
Some browsers allow (as a non-standard extension) you to shorten this to:
str[str.length - 1];
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
Using callback plugins, you can have the stdout of your commands output in readable form with the play: gist: human_log.py
Edit for example output:
_____________________________________
< TASK: common | install apt packages >
-------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [10.76.71.167] => (item=htop,vim-tiny,curl,git,unzip,update-motd,ssh-askpass,gcc,python-dev,libxml2,libxml2-dev,libxslt-dev,python-lxml,python-pip)
stdout:
Reading package lists...
Building dependency tree...
Reading state information...
libxslt1-dev is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 24 not upgraded.
stderr:
start:
2015-03-27 17:12:22.132237
end:
2015-03-27 17:12:22.136859
Either !=
or ne
will work, but you need to get the accessor syntax and nested quotes sorted out.
<c:if test="${content.contentType.name ne 'MCE'}">
<%-- snip --%>
</c:if>
System.Net.ServicePointManager.Expect100Continue = false;
This issue sometime occurs due the reason of proxy server implemented on web server. To bypass the proxy server by putting this line before calling the send service.
I think those can help for beginner: Naming convention of variables in c
you can do that by xml
:
<TextView
android:id="@+id/textview"
android:maxLines="1" // or any number of lines you want
android:ellipsize="end"
/>
I was missing System.Data.Entity dll reference and problem was solved
Yes you should, As it locks the version of each and every package which you are using in your app and when you run npm install
it install the exact same version in your node_modules folder. This is important becasue let say you are using bootstrap 3 in your application and if there is no package-lock.json file in your project then npm install
will install bootstrap 4 which is the latest and you whole app ui will break due to version mismatch.
private void Test_Click(object sender, System.EventArgs e){
string path;
path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
Console.WriiteLine( path );
}
The reason is that the compiler has to actually see the definition in order to be able to drop it in in place of the call.
Remember that C and C++ use a very simplistic compilation model, where the compiler always only sees one translation unit at a time. (This fails for export, which is the main reason only one vendor actually implemented it.)
Spring beans are classes. Instead of instantiating a class (using new
), you get an instance as a bean
cast to your class type from the application context, where the bean is what you configured in the application context configuration. This way, the whole application maintains singleton-scope instance throughout the application. All beans are initialized following their configuration order right after the application context is instantiated. Even if you don't get any beans in your application, all beans instances are already created the moment after you created the application context.
In my case I had special instruction into nginx configuration file:
location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
try_files $uri =404;
}
All clients have received '404' because nginx nothing known about Flask.
I hope it help someone.
TLS 1.1 and TLS 1.2 are supported since OpenSSL 1.0.1
Forcing TLS 1.1 and 1.2 are only supported since curl 7.34.0
You should consider an upgrade.
There is also a vectorized implementation, which allows to use 4 numpy arrays instead of scalar values for coordinates:
def distance(s_lat, s_lng, e_lat, e_lng):
# approximate radius of earth in km
R = 6373.0
s_lat = s_lat*np.pi/180.0
s_lng = np.deg2rad(s_lng)
e_lat = np.deg2rad(e_lat)
e_lng = np.deg2rad(e_lng)
d = np.sin((e_lat - s_lat)/2)**2 + np.cos(s_lat)*np.cos(e_lat) * np.sin((e_lng - s_lng)/2)**2
return 2 * R * np.arcsin(np.sqrt(d))
Since Python 3.5 this is finally no longer awkward:
>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'
and reverse:
>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'
works also with the mutable bytearray
type.
Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex
Query to join more than two tables:
SELECT ops.field_id, ops.option_id, ops.label
FROM engine4_user_fields_maps AS map
JOIN engine4_user_fields_meta AS meta ON map.`child_id` = meta.field_id
JOIN engine4_user_fields_options AS ops ON map.child_id = ops.field_id
WHERE map.option_id =39 AND meta.type LIKE 'outcomeresult' LIMIT 0 , 30
Here are my "answers" (trying to be unique here, I don't actually recommend either for this particular case :-)
Using ord() and the special a <= b <= c
form:
//starts_with_digit = ord('0') <= ord(mystring[0]) <= ord('9')
//I was thinking too much in C. Strings are perfectly comparable.
starts_with_digit = '0' <= mystring[0] <= '9'
(This a <= b <= c
, like a < b < c
, is a special Python construct and it's kind of neat: compare 1 < 2 < 3
(true) and 1 < 3 < 2
(false) and (1 < 3) < 2
(true). This isn't how it works in most other languages.)
Using a regular expression:
import re
//starts_with_digit = re.match(r"^\d", mystring) is not None
//re.match is already anchored
starts_with_digit = re.match(r"\d", mystring) is not None
Go to the task manager, kill the java processes and turn the server back on. should work fine.
def f(x) -> str:
return x+4
print(f(45))
# will give the result :
49
# or with other words '-> str' has NO effect to return type:
print(f(45).__class__)
<class 'int'>
Maybe we can create a function to do what João proposed? Something like:
def cursor_exec(cursor, query, params):
expansion_params= []
real_params = []
for p in params:
if isinstance(p, (tuple, list)):
real_params.extend(p)
expansion_params.append( ("%s,"*len(p))[:-1] )
else:
real_params.append(p)
expansion_params.append("%s")
real_query = query % expansion_params
cursor.execute(real_query, real_params)
Just add this into your class/component code snippet and Header will be hidden
static navigationOptions = { header: null }
You must remove the entry in .gitmodules
and .git/config
, and remove the directory of the module from the history:
git rm --cached path/to/submodule
If you'll write on git's mailing list probably someone will do a shell script for you.
The query either returned no rows or is erroneus, thus FALSE
is returned. Change it to
if (!$dbc || mysqli_num_rows($dbc) == 0)
mysqli_num_rows
:
Return Values
Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
I needed something along the lines of a simple string reduction function recently. Basically, the code looked something like this (C/C++ code ahead):
size_t ReduceString(char *Dest, size_t DestSize, const char *Src, size_t SrcSize, bool Normalize)
{
size_t x, x2 = 0, z = 0;
memset(Dest, 0, DestSize);
for (x = 0; x < SrcSize; x++)
{
Dest[x2] = (char)(((unsigned int)(unsigned char)Dest[x2]) * 37 + ((unsigned int)(unsigned char)Src[x]));
x2++;
if (x2 == DestSize - 1)
{
x2 = 0;
z++;
}
}
// Normalize the alphabet if it looped.
if (z && Normalize)
{
unsigned char TempChr;
y = (z > 1 ? DestSize - 1 : x2);
for (x = 1; x < y; x++)
{
TempChr = ((unsigned char)Dest[x]) & 0x3F;
if (TempChr < 10) TempChr += '0';
else if (TempChr < 36) TempChr = TempChr - 10 + 'A';
else if (TempChr < 62) TempChr = TempChr - 36 + 'a';
else if (TempChr == 62) TempChr = '_';
else TempChr = '-';
Dest[x] = (char)TempChr;
}
}
return (SrcSize < DestSize ? SrcSize : DestSize);
}
It probably has more collisions than might be desired but it isn't intended for use as a cryptographic hash function. You might try various multipliers (i.e. change the 37 to another prime number) if you get too many collisions. One of the interesting features of this snippet is that when Src is shorter than Dest, Dest ends up with the input string as-is (0 * 37 + value = value). If you want something "readable" at the end of the process, Normalize will adjust the transformed bytes at the cost of increasing collisions.
Source:
https://github.com/cubiclesoft/cross-platform-cpp/blob/master/sync/sync_util.cpp
The following query will get the current datetime and convert into string. with the following format yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar(25), getdate(), 120)
echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
You should try console_runner gem. This gem makes your pure Ruby code executable from command-line. All you need is to add YARD annotations to your code:
# @runnable This tool can talk to you. Run it when you are lonely.
# Written in Ruby.
class MyClass
def initialize
@hello_msg = 'Hello'
@bye_msg = 'Good Bye'
end
# @runnable Say 'Hello' to you.
# @param [String] name Your name
# @param [Hash] options options
# @option options [Boolean] :second_meet Have you met before?
# @option options [String] :prefix Your custom prefix
def say_hello(name, options = {})
second_meet = nil
second_meet = 'Nice to see you again!' if options['second_meet']
prefix = options['prefix']
message = @hello_msg + ', '
message += "#{prefix} " if prefix
message += "#{name}. "
message += second_meet if second_meet
puts message
end
end
Then run it from console:
$ c_run /projects/example/my_class.rb say_hello -n John --second-meet --prefix Mr.
-> Hello, Mr. John. Nice to see you again!
There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that are defined in the List interface. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.
Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).
That's called polymorphism. You can read up on it.
int day=0,month=0,year=0;
DateTime smallDate = Convert.ToDateTime(string.Format("{0}", "01.01.1900"));
DateTime bigDate = Convert.ToDateTime(string.Format("{0}", "05.06.2019"));
TimeSpan timeSpan = new TimeSpan();
//timeSpan is diff between bigDate and smallDate as days
timeSpan = bigDate - smallDate;
//year is totalDays / 365 as int
year = timeSpan.Days / 365;
//smallDate.AddYears(year) is closing the difference for year because we found the year variable
smallDate = smallDate.AddYears(year);
//again subtraction because we don't need the year now
timeSpan = bigDate - smallDate;
//month is totalDays / 30 as int
month = timeSpan.Days / 30;
//smallDate.AddMonths(month) is closing the difference for month because we found the month variable
smallDate = smallDate.AddMonths(month);
if (bigDate > smallDate)
{
timeSpan = bigDate - smallDate;
day = timeSpan.Days;
}
//else it is mean already day is 0
For Scala >= 2.12, use Source.fromResource
:
scala.io.Source.fromResource("located_in_resouces.any")
Two options:
Firstly, you can escape it using a backslash -- \(
Alternatively, since it's a single character, you can put it in a character class, where it doesn't need to be escaped -- [(]
I suggest you use CSS instead, seems like you're going to repeat those lines later on. But to answer your question:
<html>
<head>
<style type="text/css">
td.randname {
padding-left: 5px;
padding-bottom:3px;
font-size:35px;
}
</style>
</head>
<body>
<table>
<tr>
<td class="randname"> <b>Datum:</b><br/>
November 2010 </td></tr>
</table>
</body>
</html>
Please be carefull with the usage of autoSizeColumn()
. It can be used without problems on small files but please take care that the method is called only once (at the end) for each column and not called inside a loop which would make no sense.
Please avoid using autoSizeColumn()
on large Excel files. The method generates a performance problem.
We used it on a 110k rows/11 columns file. The method took ~6m to autosize all columns.
For more details have a look at: How to speed up autosizing columns in apache POI?
Try moving the button styling to the TouchableHighlight
itself:
Styles:
submit:{
marginRight:40,
marginLeft:40,
marginTop:10,
paddingTop:20,
paddingBottom:20,
backgroundColor:'#68a0cf',
borderRadius:10,
borderWidth: 1,
borderColor: '#fff'
},
submitText:{
color:'#fff',
textAlign:'center',
}
Button (same):
<TouchableHighlight
style={styles.submit}
onPress={() => this.submitSuggestion(this.props)}
underlayColor='#fff'>
<Text style={[this.getFontSize(),styles.submitText]}>Submit</Text>
</TouchableHighlight>
In JavaScript it has no special significance (no more than a
or Q
anyway). It is just an uninformative variable name.
In jQuery the variable is assigned a copy of the jQuery
function. This function is heavily overloaded and means half a dozen different things depending on what arguments it is passed. In this particular example you are passing it a string that contains a selector, so the function means "Create a jQuery object containing the element with the id Text".
In order to apply a style on your string, you can use a command like:
echo -e '\033[1mYOUR_STRING\033[0m'
Explanation:
-e
option means that escaped (backslashed) strings will be interpretedThe possible integers are:
The syntax error is just due to a missing alias for the subquery:
select COUNT(*) from
(
select m.Company_id
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5) mySubQuery /* Alias */
The first line of a paragraph is indented by default, thus whether or not you have \indent
there won't make a difference. \indent
and \noindent
can be used to override default behavior. You can see this by replacing your line with the following:
Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented
\noindent override default indentation (not indented)\\
asdf
SELECT sc.name +'.'+ ta.name TableName
,SUM(pa.rows) RowCnt
FROM sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC
See this:
If you would like to 'add' additional items to a page, you may want to create an array of maps. This is how I created an array of maps and then added results to it:
import { Product } from '../models/product';
products: Array<Product>; // Initialize the array.
[...]
let i = 0;
this.service.products( i , (result) => {
if ( i == 0 ) {
// Create the first element of the array.
this.products = Array(result);
} else {
// Add to the array of maps.
this.products.push(result);
}
});
Where product.ts look like...
export class Product {
id: number;
[...]
}
You can also use git diff HEAD file
to show the diff for a specific file.
See the EXAMPLE
section under git-diff(1)
This happens when you have 1 name for the Java class on hard disk and another name of Java class in the code!!
For example, I renamed my MainActivity
class to MainnActivity
only (!) in the code. I got this error immediately.
There is also a visual indicator in the Project tab of Android Studio - a class inside a class, like you have nested classed, but with an error indicator.
The solution is to simply rename class name in the Project tab (SHIFT
+ F6
) to match the name in the Java code.
There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...
You can also check the .Any()
method:
if (!YourResult.Any())
Just a note that .Any
will still retrieve the records from the database; doing a .FirstOrDefault()/.Where()
will be just as much overhead but you would then be able to catch the object(s) returned from the query
Another solution is to use AngularJS. The AngularUI module has a directive called ng-grid
which supports a feature called column pinning. It is not 100% pure CSS but neither are the other solutions.
Using max(date) didn't solve my problem as there is no assurance that other columns will be from the same row as the max(date) is. Instead of that this one solved my problem and sorted group by in a correct order and values of other columns are from the same row as the max date is:
SELECT model, date
FROM (SELECT * FROM doc ORDER BY date DESC) as sortedTable
GROUP BY model
The error is coming from $userRecord->email
. You need to use the ->get()
or ->first()
methods when calling from the database otherwise you're only getting the Eloquent\Builder
object rather than an Eloquent\Collection
The ->first()
method is pretty self-explanatory, it will return the first row found. ->get()
returns all the rows found
$userRecord = Model::where('email', '=', $email)->where('password', '=', $password)->get();
echo "First name: " . $userRecord->email;
It's better to cast it to HttpContextBase
, this way you can mock and test it more easily
public string GetUserIp(HttpRequestMessage request)
{
if (request.Properties.ContainsKey("MS_HttpContext"))
{
var ctx = request.Properties["MS_HttpContext"] as HttpContextBase;
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
return null;
}
I found this difference which forced me to use a mixed bag of phonegap and cordova cli commands when building my app:
'phonegap plugin add' couldn't handle command line parameters correctly, whereas 'cordova platform add' works flawlessly
The command I use is:
'cordova plugin add https://github.com/crittercism/PhoneGap.git --variable IOS_APP_ID="[my_license_key]"
Note I am using phonegap 3.5
This is key answer to this post "bLengthChange": false,
will hide the Entries Dropdown
git log --no-walk --tags --pretty="%h %d %s" --decorate=full
This version will print the commit message as well:
$ git log --no-walk --tags --pretty="%h %d %s" --decorate=full
3713f3f (tag: refs/tags/1.0.0, tag: refs/tags/0.6.0, refs/remotes/origin/master, refs/heads/master) SP-144/ISP-177: Updating the package.json with 0.6.0 version and the README.md.
00a3762 (tag: refs/tags/0.5.0) ISP-144/ISP-205: Update logger to save files with optional port number if defined/passed: Version 0.5.0
d8db998 (tag: refs/tags/0.4.2) ISP-141/ISP-184/ISP-187: Fixing the bug when loading the app with Gulp and Grunt for 0.4.2
3652484 (tag: refs/tags/0.4.1) ISP-141/ISP-184: Missing the package.json and README.md updates with the 0.4.1 version
c55eee7 (tag: refs/tags/0.4.0) ISP-141/ISP-184/ISP-187: Updating the README.md file with the latest 1.3.0 version.
6963d0b (tag: refs/tags/0.3.0) ISP-141/ISP-184: Add support for custom serializers: README update
4afdbbe (tag: refs/tags/0.2.0) ISP-141/ISP-143/ISP-144: Fixing a bug with the creation of the logs
e1513f1 (tag: refs/tags/0.1.0) ISP-141/ISP-143: Betterr refactoring of the Loggers, no dependencies, self-configuration for missing settings.
Here is slightly modified version. Changes are noted as code commentary.
BEGIN TRANSACTION
declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500)
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'pct%'
AND TABLE_NAME LIKE 'TestData%'
open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
-- And then fetch
fetch next from Tests into @test, @tableName
-- And then, if no row is fetched, exit the loop
if @@fetch_status <> 0
begin
break
end
-- Quotename is needed if you ever use special characters
-- in table/column names. Spaces, reserved words etc.
-- Other changes add apostrophes at right places.
set @cmd = N'exec sp_rename '''
+ quotename(@tableName)
+ '.'
+ quotename(@test)
+ N''','''
+ RIGHT(@test,LEN(@test)-3)
+ '_Pct'''
+ N', ''column'''
print @cmd
EXEC sp_executeSQL @cmd
END
close Tests
deallocate Tests
ROLLBACK TRANSACTION
--COMMIT TRANSACTION
Your first example is effectively what you need:
<TextBlock Text="{Binding CelsiusTemp, StringFormat={}{0}°C}" />
Just add this code snippet in your script:
$(function () {
$('[data-toggle="tooltip"]').tooltip()
});
and ofcourse as mentioned in above answers the data-html
should be "true"
. This will allow you to use html tags and formatting inside the value of title
attribute.