you have a lot of answers in the post
var d1 = new Date (),
d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 20 );
alert ( d2 );
Arrow function could have make your life more easier to avoid binding this keyword. Like so:
delta = () => {
this.setState({
count : this.state.count++
});
}
Try this
function DisplayLocalSites
{
try{
Set-ExecutionPolicy unrestricted
$list = @()
foreach ($webapp in get-childitem IIS:\Sites\)
{
$name = "IIS:\Sites\" + $webapp.name
$item = @{}
$item.WebAppName = $webapp.name
foreach($Bind in $webapp.Bindings.collection)
{
$item.SiteUrl = $Bind.Protocol +'://'+ $Bind.BindingInformation.Split(":")[-1]
}
$obj = New-Object PSObject -Property $item
$list += $obj
}
$list | Format-Table -a -Property "WebAppName","SiteUrl"
$list | Out-File -filepath C:\websites.txt
Set-ExecutionPolicy restricted
}
catch
{
$ExceptionMessage = "Error in Line: " + $_.Exception.Line + ". " + $_.Exception.GetType().FullName + ": " + $_.Exception.Message + " Stacktrace: " + $_.Exception.StackTrace
$ExceptionMessage
}
}
From Dockerfile reference:
The
ARG
instruction defines a variable that users can pass at build-time to the builder with the docker build command using the--build-arg <varname>=<value>
flag.The
ENV
instruction sets the environment variable<key>
to the value<value>
.
The environment variables set usingENV
will persist when a container is run from the resulting image.
So if you need build-time customization, ARG
is your best choice.
If you need run-time customization (to run the same image with different settings), ENV
is well-suited.
If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable
Given the number of combinations involved, using ENV
to set those features at runtime is best here.
But you can combine both by:
ARG
ARG
as an ENV
That is, with a Dockerfile including:
ARG var
ENV var=${var}
You can then either build an image with a specific var
value at build-time (docker build --build-arg var=xxx
), or run a container with a specific runtime value (docker run -e var=yyy
)
You can write a custom UICollectionView
layout to achieve this, here is demo image of my implementation:
Here's code repository: KSTCollectionViewPageHorizontalLayout
@iPhoneDev (this maybe help you too)
This should help -
var json = "{'@STARTDATE': '2016-02-17 00:00:00.000', '@ENDDATE': '2016-02-18 23:59:00.000' }";
var fdate = JObject.Parse(json)["@STARTDATE"];
Overloading methods is tricky in Python. However, there could be usage of passing the dict, list or primitive variables.
I have tried something for my use cases, and this could help here to understand people to overload the methods.
Let's take your example:
A class overload method with call the methods from different class.
def add_bullet(sprite=None, start=None, headto=None, spead=None, acceleration=None):
Pass the arguments from the remote class:
add_bullet(sprite = 'test', start=Yes,headto={'lat':10.6666,'long':10.6666},accelaration=10.6}
Or
add_bullet(sprite = 'test', start=Yes, headto={'lat':10.6666,'long':10.6666},speed=['10','20,'30']}
So, handling is being achieved for list, Dictionary or primitive variables from method overloading.
Try it out for your code.
Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.
var data = { 'venue[]' : []};
$("input:checked").each(function() {
data['venue[]'].push($(this).val());
});
In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this
needing to be enclosed as $(this)
A large number of unwanted NUL characters, say one every other byte, indicates that the file is encoded in UTF-16 and that you should use iconv
to convert it to UTF-8.
We were receiving the same. The exception was
Stacktrace: at Microsoft.Office.Interop.Excel._Workbook.SaveAs(Object Filename, Object FileFormat, Object Password, Object WriteResPassword, Object ReadOnlyRecommended, Object CreateBackup, XlSaveAsAccessMode AccessMode, Object ConflictResolution, Object AddToMru, Object TextCodepage, Object Text VisualLayout, Object Local)`
with an inner exception of
Exception from HRESULT: 0x800A03EC 2012-11-01 10:37:59`
We were able to resolve the problem with information from this post, which I quote here for convenience...
this should work also with different predicate
myFunction(strings.find( _ == mystring ).isDefined)
It all depends on what you want to do, and what you want the derived classes to be able to see.
class A
{
private:
int _privInt = 0;
int privFunc(){return 0;}
virtual int privVirtFunc(){return 0;}
protected:
int _protInt = 0;
int protFunc(){return 0;}
public:
int _publInt = 0;
int publFunc()
{
return privVirtFunc();
}
};
class B : public A
{
private:
virtual int privVirtFunc(){return 1;}
public:
void func()
{
_privInt = 1; // wont work
_protInt = 1; // will work
_publInt = 1; // will work
privFunc(); // wont work
privVirtFunc(); // wont work
protFunc(); // will work
publFunc(); // will return 1 since it's overridden in this class
}
}
TL;DR
Long Version
Jenkins Pipeline testing becomes more and more of a pain. Unlike the classic declarative job configuration approach where the user was limited to what the UI exposed the new Jenkins Pipeline is a full fledged programming language for the build process where you mix the declarative part with your own code. As good developers we want to have some unit tests for this kind of code as well.
There are three steps you should follow when developing Jenkins Pipelines. The step 1. should cover 80% of the uses cases.
Examples
The pipelineUnit GitHub repo contains some Spock examples on how to use Jenkins Pipeline Unit testing framework
You can simply subtract two dates. You have to cast it first, using to_date
:
select to_date('2000-01-01', 'yyyy-MM-dd')
- to_date('2000-01-02', 'yyyy-MM-dd')
datediff
from dual
;
The result is in days, to the difference of these two dates is -1
(you could swap the two dates if you like). If you like to have it in hours, just multiply the result with 24.
Apply proper charset and collation to database, table and columns/fields.
I creates database and table structure using sql queries from one server to another. it creates database structure as follows:
I change collation of table and column to utf8_general_ci
, and it resolves the error.
If you're using bindings you can do
val headerView = binding.navView.getHeaderView(0)
val headerBinding = NavDrawerHeaderBinding.bind(headerView)
headerBinding.textView.text = "Your text here"
def wordCount(mystring):
tempcount = 0
count = 1
try:
for character in mystring:
if character == " ":
tempcount +=1
if tempcount ==1:
count +=1
else:
tempcount +=1
else:
tempcount=0
return count
except Exception:
error = "Not a string"
return error
mystring = "I am having a very nice 23!@$ day."
print(wordCount(mystring))
output is 8
@Alex Martelli
's answer is great!
But it work only for one element at time (WHERE name = 'Joan'
)
If you take out the WHERE
clause, the query will return all the root rows together...
I changed a little bit for my situation, so it can show the entire tree for a table.
table definition:
CREATE TABLE [dbo].[mar_categories] (
[category] int IDENTITY(1,1) NOT NULL,
[name] varchar(50) NOT NULL,
[level] int NOT NULL,
[action] int NOT NULL,
[parent] int NULL,
CONSTRAINT [XPK_mar_categories] PRIMARY KEY([category])
)
(level
is literally the level of a category 0: root, 1: first level after root, ...)
and the query:
WITH n(category, name, level, parent, concatenador) AS
(
SELECT category, name, level, parent, '('+CONVERT(VARCHAR (MAX), category)+' - '+CONVERT(VARCHAR (MAX), level)+')' as concatenador
FROM mar_categories
WHERE parent is null
UNION ALL
SELECT m.category, m.name, m.level, m.parent, n.concatenador+' * ('+CONVERT (VARCHAR (MAX), case when ISNULL(m.parent, 0) = 0 then 0 else m.category END)+' - '+CONVERT(VARCHAR (MAX), m.level)+')' as concatenador
FROM mar_categories as m, n
WHERE n.category = m.parent
)
SELECT distinct * FROM n ORDER BY concatenador asc
(You don't need to concatenate the level
field, I did just to make more readable)
the answer for this query should be something like:
I hope it helps someone!
now, I'm wondering how to do this on MySQL... ^^
Like this?
public static void Test()
{
using (var image = Image.FromFile(@"c:\logo.png"))
using (var newImage = ScaleImage(image, 300, 400))
{
newImage.Save(@"c:\test.png", ImageFormat.Png);
}
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
2020 answer
CSS Filter works on all current browsers
<img>
tag.<img src="dotted-arrow.svg" class="filter-green"/>
For example, output for #00EE00
is
filter: invert(42%) sepia(93%) saturate(1352%) hue-rotate(87deg) brightness(119%) contrast(119%);
filter
into this class. .filter-green{
filter: invert(48%) sepia(79%) saturate(2476%) hue-rotate(86deg) brightness(118%) contrast(119%);
}
I found hitting ctrl+break while the macro wasn't running fixed the problem.
You don't need to reset all your user data to switch users. Try clicking on your name in the upper right corner then click on "Account settings". There you will get an option to sign out of the IDE. Once signed out you can sign back in as another Microsoft account.
There's a difference between additive colors (http://en.wikipedia.org/wiki/Additive_color) and subtractive colors (http://en.wikipedia.org/wiki/Subtractive_color).
With additive colors, the more you add, the brighter the colors become. This is because they are emitting light. This is why the day light is (more or less) white, since the Sun is emitting in almost all the visible wavelength spectrum.
On the other hand, with subtractive colors the more colors you mix, the darker the resulting color. This is because they are reflecting light. This is also why the black colors get hotter quickly, because it absorbs (almost) all light energy and reflects (almost) none.
Specifically to your question, it depends what medium you are working on. Traditionally, additive colors (RGB) are used because the canon for computer graphics was the computer monitor, and since it's emitting light, it makes sense to use the same structure for the graphic card (the colors are shown without conversions). However, if you are used to graphic arts and press, subtractive color model is used (CMYK). In programs such as Photoshop, you can choose to work in CMYK space although it doesn't matter what color model you use: the primary colors of one group are the secondary colors of the second one and viceversa.
P.D.: my father worked at graphic arts, this is why i know this... :-P
Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.
Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.
Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html
if namespace is provided on the given xml, its better to use this.
(/*[local-name() ='bookstore']/*[local-name()='book'][@location='US'])[1]
Javadoc to the rescue :
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace
nextLine
is probably the method you should use.
With the usual caveats about C's behaviour with shifts, this ought to work for unsigned quantities regardless of the native size of an int...
static unsigned int udiv(unsigned int a, unsigned int b) {
unsigned int c = 1, result = 0;
if (b == 0) return (unsigned int)-1 /*infinity*/;
while (((int)b > 0) && (b < a)) { b = b<<1; c = c<<1; }
do {
if (a >= b) { a -= b; result += c; }
b = b>>1; c = c>>1;
} while (c);
return result;
}
You can index into a string in C# like an array, and you get the character at that index.
Example:
In Java, you would say
str.charAt(8);
In C#, you would say
str[8];
This is not the correct usage of the System.Threading.Timer. When you instantiate the Timer, you should almost always do the following:
_timer = new Timer( Callback, null, TIME_INTERVAL_IN_MILLISECONDS, Timeout.Infinite );
This will instruct the timer to tick only once when the interval has elapsed. Then in your Callback function you Change the timer once the work has completed, not before. Example:
private void Callback( Object state )
{
// Long running operation
_timer.Change( TIME_INTERVAL_IN_MILLISECONDS, Timeout.Infinite );
}
Thus there is no need for locking mechanisms because there is no concurrency. The timer will fire the next callback after the next interval has elapsed + the time of the long running operation.
If you need to run your timer at exactly N milliseconds, then I suggest you measure the time of the long running operation using Stopwatch and then call the Change method appropriately:
private void Callback( Object state )
{
Stopwatch watch = new Stopwatch();
watch.Start();
// Long running operation
_timer.Change( Math.Max( 0, TIME_INTERVAL_IN_MILLISECONDS - watch.ElapsedMilliseconds ), Timeout.Infinite );
}
I strongly encourage anyone doing .NET and is using the CLR who hasn't read Jeffrey Richter's book - CLR via C#, to read is as soon as possible. Timers and thread pools are explained in great details there.
Example:
You want to see all the items that are (round AND (red OR blue)):
{
"query": {
"bool": {
"must": [
{
"term": {"shape": "round"}
},
{
"bool": {
"should": [
{"term": {"color": "red"}},
{"term": {"color": "blue"}}
]
}
}
]
}
}
}
You can also do more complex versions of OR, for example if you want to match at least 3 out of 5, you can specify 5 options under "should" and set a "minimum_should" of 3.
Thanks to Glen Thompson and Sebastialonso for finding where my nesting wasn't quite right before.
Thanks also to Fatmajk for pointing out that "term" becomes "match" in ElasticSearch 6.
Just noting that if you wish to redirect both stderr and stdout to a file while you have noclobber set (i.e. set -o noclobber
), you can use the code:
cmd >| file.txt 2>&1
More information about this can be seen at https://stackoverflow.com/a/876242.
Also this answer's @TuBui's question on the answer @BrDaHa provided above at Aug 9 '18 at 9:34.
Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).
jQuery Cycle is one of my favourite light weight libraries.
What you want to achieve could be done in just
jQuery("#slideshow").cycle({
timeout:0, // no autoplay
fx: 'fade', //fade effect, although there are heaps
next: '#next',
prev: '#prev'
});
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
OK, if that's what you want, here's what I would do to fix your existing code:
from collections import Counter
def count_letters(words):
counter = Counter()
for word in words.split():
counter.update(word)
return sum(counter.itervalues())
words = "The grey old fox is an idiot"
print count_letters(words) # 22
If you don't want to count certain non-whitespace characters, then you'll need to remove them -- inside the for
loop if not sooner.
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
Perhaps you should check NLS_DATE_FORMAT
and use the date string conforming the format.
Or you can use to_date
function within the INSERT
statement, like the following:
insert into visit
values(123456,
to_date('19-JUN-13', 'dd-mon-yy'),
to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));
Additionally, Oracle DATE
stores date and time information together.
I'd say it depends upon the size of your project... Personnally, I would use Maven for simple projects that need straightforward compiling, packaging and deployment. As soon as you need to do some more complicated things (many dependencies, creating mapping files...), I would switch to Ant...
In Laravel 5.5 is very simple, if you are using CRUD route system.
Go to app/http/controllers/RegisterController
there is namespace: Illuminate\Foundation\Auth\RegistersUser
You need to go to the RegistersUser: Illuminate\Foundation\Auth\RegistersUser
There is the method call showRegistrationForm
change this: return view('auth.login');
for this: return redirect()->route('auth.login');
and remove from you blade page route call register. It may look like that:
<li role="presentation">
<a class="nav-link" href="{{ route('register') }}">Register</a>
</li>
Attributes are class components that can be accessed from outside the object. They are known as properties in many other programming languages. Their values are accessible by using the "dot notation", as in object_name.attribute_name. Unlike Python and a few other languages, Ruby does not allow instance variables to be accessed directly from outside the object.
class Car
def initialize
@wheels = 4 # This is an instance variable
end
end
c = Car.new
c.wheels # Output: NoMethodError: undefined method `wheels' for #<Car:0x00000000d43500>
In the above example, c is an instance (object) of the Car class. We tried unsuccessfully to read the value of the wheels instance variable from outside the object. What happened is that Ruby attempted to call a method named wheels within the c object, but no such method was defined. In short, object_name.attribute_name tries to call a method named attribute_name within the object. To access the value of the wheels variable from the outside, we need to implement an instance method by that name, which will return the value of that variable when called. That's called an accessor method. In the general programming context, the usual way to access an instance variable from outside the object is to implement accessor methods, also known as getter and setter methods. A getter allows the value of a variable defined within a class to be read from the outside and a setter allows it to be written from the outside.
In the following example, we have added getter and setter methods to the Car class to access the wheels variable from outside the object. This is not the "Ruby way" of defining getters and setters; it serves only to illustrate what getter and setter methods do.
class Car
def wheels # getter method
@wheels
end
def wheels=(val) # setter method
@wheels = val
end
end
f = Car.new
f.wheels = 4 # The setter method was invoked
f.wheels # The getter method was invoked
# Output: => 4
The above example works and similar code is commonly used to create getter and setter methods in other languages. However, Ruby provides a simpler way to do this: three built-in methods called attr_reader, attr_writer and attr_acessor. The attr_reader method makes an instance variable readable from the outside, attr_writer makes it writeable, and attr_acessor makes it readable and writeable.
The above example can be rewritten like this.
class Car
attr_accessor :wheels
end
f = Car.new
f.wheels = 4
f.wheels # Output: => 4
In the above example, the wheels attribute will be readable and writable from outside the object. If instead of attr_accessor, we used attr_reader, it would be read-only. If we used attr_writer, it would be write-only. Those three methods are not getters and setters in themselves but, when called, they create getter and setter methods for us. They are methods that dynamically (programmatically) generate other methods; that's called metaprogramming.
The first (longer) example, which does not employ Ruby's built-in methods, should only be used when additional code is required in the getter and setter methods. For instance, a setter method may need to validate data or do some calculation before assigning a value to an instance variable.
It is possible to access (read and write) instance variables from outside the object, by using the instance_variable_get and instance_variable_set built-in methods. However, this is rarely justifiable and usually a bad idea, as bypassing encapsulation tends to wreak all sorts of havoc.
There is a single quote in $submitsubject
or $submit_message
Why is this a problem?
The single quote char terminates the string in MySQL and everything past that is treated as a sql command. You REALLY don't want to write your sql like that. At best, your application will break intermittently (as you're observing) and at worst, you have just introduced a huge security vulnerability.
Imagine if someone submitted '); DROP TABLE private_messages;
in submit message.
Your SQL Command would be:
INSERT INTO private_messages (to_id, from_id, time_sent, subject, message)
VALUES('sender_id', 'id', now(),'subjet','');
DROP TABLE private_messages;
Instead you need to properly sanitize your values.
AT A MINIMUM you must run each value through mysql_real_escape_string()
but you should really be using prepared statements.
If you were using mysql_real_escape_string()
your code would look like this:
if($_POST['submit_message']){
if($_POST['form_subject']==""){
$submit_subject="(no subject)";
}else{
$submit_subject=mysql_real_escape_string($_POST['form_subject']);
}
$submit_message=mysql_real_escape_string($_POST['form_message']);
$sender_id = mysql_real_escape_string($_POST['sender_id']);
Here is a great article on prepared statements and PDO.
var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));
Make sure you don't have any undefined classpath variables (like M2_REPO).
An <hr> inside a display:flex will make it display vertically.
JSFiddle: https://jsfiddle.net/w6y5t1kL/
Example:
<div style="display:flex;">
<div>
Content
<ul>
<li>Continued content...</li>
</ul>
</div>
<hr>
<div>
Content
<ul>
<li>Continued content...</li>
</ul>
</div>
</div>
Hashes are a sequence of bits (128 bits, 160 bits, 256 bits, etc., depending on the algorithm). Your column should be binary-typed, not text/character-typed, if MySQL allows it (SQL Server datatype is binary(n)
or varbinary(n)
). You should also salt the hashes. Salts may be text or binary, and you will need a corresponding column.
The real question is: whether to use interfaces or base classes. This has been covered before.
In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.
Bar
is guaranteed not to change the object it is being invoked on. See the section about const correctness in the C++ FAQ, for example.
I just created some directories, shared them and mapped using:
net use y: "\\mycomputername\folder with spaces"
So this solution gets "works on my machine" certificate. What error code do you get?
This might come a little late...
I wrote this KalmanLocationManager for Android, which wraps the two most common location providers, Network and GPS, kalman-filters the data, and delivers updates to a LocationListener
(like the two 'real' providers).
I use it mostly to "interpolate" between readings - to receive updates (position predictions) every 100 millis for instance (instead of the maximum gps rate of one second), which gives me a better frame rate when animating my position.
Actually, it uses three kalman filters, on for each dimension: latitude, longitude and altitude. They're independent, anyway.
This makes the matrix math much easier: instead of using one 6x6 state transition matrix, I use 3 different 2x2 matrices. Actually in the code, I don't use matrices at all. Solved all equations and all values are primitives (double).
The source code is working, and there's a demo activity. Sorry for the lack of javadoc in some places, I'll catch up.
According to Flexbugs:
In IE 10-11,
min-height
declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.
Here are a couple of workarounds:
<aside>
and <section>
:html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1;
display: flex;
}
aside, section {
overflow: auto;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1 0 auto;
display: flex;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
You may use Apache Commons IO:
try (OutputStream outputStream = ...) {
IOUtils.write("data", outputStream, "UTF-8");
}
The problem might be with your firewall or antivirus.
Make sure they all disabled.
Run your script in Eclipse. If it works, then 2 and 3 might be the culprit. For me, it was comodo firewall. I created a filter for Adb.exe
There are in fact multiples things you need to know about indentation in Python:
In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / end
or { }
and is therefore necessary.
This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won't work.
1. "IndentationError: expected an indented block"
They are two main reasons why you could have such an error:
- You have a ":" without an indented block behind.
Here are two examples:
Example 1, no indented block:
Input:
if 3 != 4:
print("usual")
else:
Output:
File "<stdin>", line 4
^
IndentationError: expected an indented block
The output states that you need to have an indented block on line 4, after the else:
statement
Example 2, unindented block:
Input:
if 3 != 4:
print("usual")
Output
File "<stdin>", line 2
print("usual")
^
IndentationError: expected an indented block
The output states that you need to have an indented block line 2, after the if 3 != 4:
statement
- You are using Python2.x and have a mix of tabs and spaces:
Input
def foo():
if 1:
print 1
Please note that before if, there is a tab, and before print there is 8 spaces.
Output:
File "<stdin>", line 3
print 1
^
IndentationError: expected an indented block
It's quite hard to understand what is happening here, it seems that there is an indent block... But as I said, I've used tabs and spaces, and you should never do that.
2. "IndentationError: unexpected indent"
It is important to indent blocks, but only blocks that should be indent. So basically this error says:
- You have an indented block without a ":" before it.
Example:
Input:
a = 3
a += 3
Output:
File "<stdin>", line 2
a += 3
^
IndentationError: unexpected indent
The output states that he wasn't expecting an indent block line 2, then you should remove it.
3. "TabError: inconsistent use of tabs and spaces in indentation" (python3.x only)
Just look at the line number of the error, and fix it using the previous information.
You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.
Are you sure you need a list in this case? If you are populating the list with many items, performance will suffer with myList.Contains
or myList.Any
; the run-time will be quadratic. You might want to consider using a better data structure. For example,
public class MyClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
public class MyClassComparer : EqualityComparer<MyClass>
{
public override bool Equals(MyClass x, MyClass y)
{
if(x == null || y == null)
return x == y;
return x.Property1 == y.Property1 && x.Property2 == y.Property2;
}
public override int GetHashCode(MyClass obj)
{
return obj == null ? 0 : (obj.Property1.GetHashCode() ^ obj.Property2.GetHashCode());
}
}
You could use a HashSet in the following manner:
var set = new HashSet<MyClass>(new MyClassComparer());
foreach(var myClass in ...)
set.Add(myClass);
Of course, if this definition of equality for MyClass
is 'universal', you needn't write an IEqualityComparer
implementation; you could just override GetHashCode
and Equals
in the class itself.
It doesn't appear that iframes display and scroll properly. You can use an object tag to replace an iframe and the contents will be scrollable with 2 fingers. Here's a simple example:
<html>
<head>
<meta name="viewport" content="minimum-scale=1.0; maximum-scale=1.0; user-scalable=false; initial-scale=1.0;"/>
</head>
<body>
<div>HEADER - use 2 fingers to scroll contents:</div>
<div id="scrollee" style="height:75%;" >
<object id="object" height="90%" width="100%" type="text/html" data="http://en.wikipedia.org/"></object>
</div>
<div>FOOTER</div>
</body>
</html>
For using DOSBox with SDL, you will need to set or change the following:
[sdl]
windowresolution=1280x960
output=opengl
Here is three options to put those settings:
Edit user's default configuration, for example, using vi
:
$ dosbox -printconf
/home/USERNAME/.dosbox/dosbox-0.74.conf
$ vi "$(dosbox -printconf)"
$ dosbox
For temporary resize, create a new configuration with the three lines above, say newsize.conf
:
$ dosbox -conf newsize.conf
You can use -conf
to load multiple configuration and/or with -userconf
for default configuration, for example:
$ dosbox -userconf -conf newsize.conf
[snip]
---
CONFIG:Loading primary settings from config file /home/USERNAME/.dosbox/dosbox-0.74.conf
CONFIG:Loading additional settings from config file newsize.conf
[snip]
Create a dosbox.conf
under current directory, DOSBox loads it as default.
DOSBox should start up and resize to 1280x960 in this case.
Note that you probably would not get any size you desired, for instance, I set 1280x720 and I got 1152x720.
This bug seem to have resurfaced (Noticed it November 2010)
I think the WebKit bug reports involved are this one and this. Essentially it boils down to incorrect cache handling when doing an If-Modified-Since
which get a 304
response.
The message means that both the packages have functions with the same names. In this particular case, the testthat
and assertive
packages contain five functions with the same name.
R will look through the search
path to find functions, and will use the first one that it finds.
search()
## [1] ".GlobalEnv" "package:assertive" "package:testthat"
## [4] "tools:rstudio" "package:stats" "package:graphics"
## [7] "package:grDevices" "package:utils" "package:datasets"
## [10] "package:methods" "Autoloads" "package:base"
In this case, since assertive
was loaded after testthat
, it appears earlier in the search path, so the functions in that package will be used.
is_true
## function (x, .xname = get_name_in_parent(x))
## {
## x <- coerce_to(x, "logical", .xname)
## call_and_name(function(x) {
## ok <- x & !is.na(x)
## set_cause(ok, ifelse(is.na(x), "missing", "false"))
## }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>
The functions in testthat
are not accessible in the usual way; that is, they have been masked.
You can explicitly provide a package name when you call a function, using the double colon operator, ::
. For example:
testthat::is_true
## function ()
## {
## function(x) expect_true(x)
## }
## <environment: namespace:testthat>
If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE
to library
.
library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time
Alternatively, suppress the message with suppressPackageStartupMessages
:
library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output
If you have altered some of R's startup configuration options (see ?Startup
) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup
should solve most mysteries.
For example, the documentation there says:
Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.
Which implies that when 3rd party packages are loaded via files like .Rprofile
you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.
First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.
library(dplyr)
envs <- search() %>% setNames(., .)
For each environment, get the exported functions (and other variables).
fns <- lapply(envs, ls)
Turn this into a data frame, for easy use with dplyr.
fns_by_env <- data_frame(
env = rep.int(names(fns), lengths(fns)),
fn = unlist(fns)
)
Find cases where the object appears more than once.
fns_by_env %>%
group_by(fn) %>%
tally() %>%
filter(n > 1) %>%
inner_join(fns_by_env)
To test this, try loading some packages with known conflicts (e.g., Hmisc
, AnnotationDbi
).
The conflicted
package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.
library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
## * Hmisc::units
## * base::units
There are several different pieces of information relating to processors that you could get:
These can all be different; in the case of a machine with 2 dual-core hyper-threading-enabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.
The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems):
Make sure to add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.
Physical Processors:
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
}
Cores:
int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
coreCount += int.Parse(item["NumberOfCores"].ToString());
}
Console.WriteLine("Number Of Cores: {0}", coreCount);
Logical Processors:
Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);
OR
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}
Processors excluded from Windows:
You can also use Windows API calls in setupapi.dll to discover processors that have been excluded from Windows (e.g. through boot settings) and aren't detectable using the above means. The code below gives the total number of logical processors (I haven't been able to figure out how to differentiate physical from logical processors) that exist, including those that have been excluded from Windows:
static void Main(string[] args)
{
int deviceCount = 0;
IntPtr deviceList = IntPtr.Zero;
// GUID for processor classid
Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");
try
{
// get a list of all processor devices
deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);
// attempt to process each item in the list
for (int deviceNumber = 0; ; deviceNumber++)
{
SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA();
deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);
// attempt to read the device info from the list, if this fails, we're at the end of the list
if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))
{
deviceCount = deviceNumber;
break;
}
}
}
finally
{
if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }
}
Console.WriteLine("Number of cores: {0}", deviceCount);
}
[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
[MarshalAs(UnmanagedType.LPStr)]String enumerator,
IntPtr hwndParent,
Int32 Flags);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
Int32 MemberIndex,
ref SP_DEVINFO_DATA DeviceInterfaceData);
[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
public int cbSize;
public Guid ClassGuid;
public uint DevInst;
public IntPtr Reserved;
}
private enum DIGCF
{
DEFAULT = 0x1,
PRESENT = 0x2,
ALLCLASSES = 0x4,
PROFILE = 0x8,
DEVICEINTERFACE = 0x10,
}
The catch all for me is taking an object, encoding it, and then passing the string into a javascript script
tag. To do this you have to do some replacements.
First replace every \
with a double slash \\
and then every quote"
with a \"
.
$payload = json_encode($payload);
$payload = preg_replace("_\\\_", "\\\\\\", $payload);
$payload = preg_replace("/\"/", "\\\"", $payload);
return View::make('pages.javascript')
->with('payload', $payload)
Then in the blade template
@if(isset($payload))
<script>
window.__payload = JSON.parse("{!!$payload!!}");
</script>
@endif
This basically allows you to take an object on the php side, and then have an object on the javascript side.
This is what I have been using successfully:
...
<div class="custom-file">
<input type="file" class="custom-file-input image-gallery" id="image-gallery" name="image-gallery[]" multiple accept="image/*">
<label class="custom-file-label" for="image-gallery">Upload Image(s)</label>
</div>
...
It is always a good idea to check for the actual file type on the server-side as well.
There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.
Imports are pretty straightforward really. Just remember the following:
'import' and 'from xxx import yyy' are executable statements. They execute when the running program reaches that line.
If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module. It does not return control to the calling module until the execution has completed.
If a module does exist in sys.modules then an import simply returns that module whether or not it has completed executing. That is the reason why cyclic imports may return modules which appear to be partly empty.
Finally, the executing script runs in a module named __main__, importing the script under its own name will create a new module unrelated to __main__.
Take that lot together and you shouldn't get any surprises when importing modules.
let str = "\(INT_VALUE), \(FLOAT_VALUE), \(DOUBLE_VALUE), \(STRING_VALUE)"
Update: I wrote this answer before Swift had String(format:)
added to it's API. Use the method given by the top answer.
Your code has a few things wrong with it.
It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:
<?php
if (isset($_POST['hidden1'])) {
echo "You submitted {$_POST['hidden1']}";
die;
}
echo <<<HTML
<form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
<input type="submit" name="submit" value="Test this mess!" />
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<script type="text/javascript">
document.getElementById("hidden1").value = "This is an example";
</script>
HTML;
?>
Something that I tried and work for me is simply you create a new virtual machine and you use the existing virtual hard disk file and everything is like you left it.
Yet another reason may be that your entity class has several properties named somhow /.*id/i
- so ending with ID case insensitive AND elementary type AND there is no [Key]
attribute.
EF will namely try to figure out the PK by itself by looking for elementary typed properties ending in ID.
See my case:
public class MyTest, IMustHaveTenant
{
public long Id { get; set; }
public int TenantId { get; set; }
[MaxLength(32)]
public virtual string Signum{ get; set; }
public virtual string ID { get; set; }
public virtual string ID_Other { get; set; }
}
don't ask - lecacy code. The Id
was even inherited, so I could not use [Key]
(just simplifying the code here)
But here EF is totally confused.
What helped was using modelbuilder this in DBContext class.
modelBuilder.Entity<MyTest>(f =>
{
f.HasKey(e => e.Id);
f.HasIndex(e => new { e.TenantId });
f.HasIndex(e => new { e.TenantId, e.ID_Other });
});
the index on PK is implicit.
You can't do it directly. There are a number of ways to do it:
Use a std::stringstream
:
std::ostringstream s;
s << "(" << c1 << ", " << c2 << ")";
storedCorrect[count] = s.str()
Use boost::lexical_cast
:
storedCorrect[count] = "(" + boost::lexical_cast<std::string>(c1) + ", " + boost::lexical_cast<std::string>(c2) + ")";
Use std::snprintf
:
char buffer[256]; // make sure this is big enough!!!
snprintf(buffer, sizeof(buffer), "(%g, %g)", c1, c2);
storedCorrect[count] = buffer;
There are a number of other ways, using various double-to-string conversion functions, but these are the main ways you'll see it done.
You can also configure your component like this :
package mypackage;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConstructorClassConfig {
@Bean
public MyConstructorClass myConstructorClass(){
return new myConstructorClass("foobar");
}
}
}
With the Bean
annotation, you are telling Spring to register the returned bean in the BeanFactory
.
So you can autowire it as you wish.
I have given a brief description of steps to follow, and parameters to pass while generating an ipa using terrminal below:
Go to the folder which contains the MyApp.xcodeproject file in terminal
By using the command given below you will get all the Targets of the application
/usr/bin/xcodebuild -list
After the above command is executed, you will get a list of targets of which you should select a specific target you need to generate .ipa
/usr/bin/xcodebuild -target $TARGET -sdk iphoneos -configuration Release
The above command builds the project and creates a .app file.The path to locate the .app file is ./build/Release-iphoneos/MyApp.app
After Build gets succeeded then execute the following command to generate .ipa of the application using Developer Name and Provisioning Profile using the syntax below:
/usr/bin/xcrun -sdk iphoneos PackageApplication -v “${TARGET}.app” -o “${OUTDIR}/${TARGET}.ipa” –sign “${IDENTITY}” –embed “${PROVISONING_PROFILE}”
Explanation of each Parameter in the above syntax:
${TARGET}.app == Target path (ex :/Users/XXXXXX/desktop/Application/build/Release-iphoneos/MyApp.app)
${OUTDIR} == Select the output directory(Where you want to save .ipa file)
${IDENTITY} == iPhone Developer: XXXXXXX (XXXXXXXXXX)(which can be obtained from Keychain access)
${PROVISONING_PROFILE} == Path to the provisioning profile(/Users/XXXXXX/Library/MobileDevice/Provisioning Profiles/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.mobileprovision”)
The only thing that worked for me:
g.drawOval((getWidth()-200)/2,(getHeight()-200)/2, 200, 200);
In Windows 8 & 10, you have to right-click devenv.exe
and select "Troubleshoot compatibility".
If, when you open Visual Studio it asks to save changes to devenv.sln, see this answer to disable it:
Disable Visual Studio devenv solution save dialog
If you change your mind and wish to undo the "Run As Administrator" Compatibility setting, see the answer here: How to Fix Unrecognized Guid format in Visual Studio 2015
The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';
Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.
In neither case is the "syntax malformed". It's the semantics that are wrong. Hence, IMHO a 400 is inappropriate. Instead, it would be appropriate to return a 200 along with some kind of error object such as { "error": { "message": "Unknown request keyword" } }
or whatever.
Consider the client processing path(s). An error in syntax (e.g. invalid JSON) is an error in the logic of the program, in other words a bug of some sort, and should be handled accordingly, in a way similar to a 403, say; in other words, something bad has gone wrong.
An error in a parameter value, on the other hand, is an error of semantics, perhaps due to say poorly validated user input. It is not an HTTP error (although I suppose it could be a 422). The processing path would be different.
For instance, in jQuery, I would prefer not to have to write a single error handler that deals with both things like 500 and some app-specific semantic error. Other frameworks, Ember for one, also treat HTTP errors like 400s and 500s identically as big fat failures, requiring the programmer to detect what's going on and branch depending on whether it's a "real" error or not.
I found the answer!! Taking a screenshot interrupts any touches that are on the screen. This is why snapchat requires holding to see the picture. Reference: http://tumblr.jeremyjohnstone.com/post/38503925370/how-to-detect-screenshots-on-ios-like-snapchat
You can check if an object is nil (null) by calling present? or blank? .
@object.present?
this will return false if the project is an empty string or nil .
or you can use
@object.blank?
this is the same as present? with a bang and you can use it if you don't like 'unless'. this will return true for an empty string or nil .
You cannot include style directives in GFM.
The most complete documentation/example is "Markdown Cheatsheet", and it illustrates that this element <style>
is missing.
If you manage to include your text in one of the GFM elements, then you can play with a github.css stylesheet in order to colors that way, meaning to color using inline CSS style directives, referring to said css stylesheet.
make sure your app is live on developer.facebook.com
This green circle is indicating the app is live
If it is not then follow this two steps for make your app live
Step 1 Go to your application -> setting => and add Contact Email and apply save Changes
Setp 2 Then goto App Review option and make sure this toggle is Yes i added a screen shot
You can use the ternary operator notation:
<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">
Just to expand on my answer a neater way of doing this multiple times would probably be:
PopulateByteArray(UserCode, 0x20);
which calls:
public static void PopulateByteArray(byte[] byteArray, byte value)
{
for (int i = 0; i < byteArray.Length; i++)
{
byteArray[i] = value;
}
}
This has the advantage of a nice efficient for loop (mention to gwiazdorrr's answer) as well as a nice neat looking call if it is being used a lot. And a lot mroe at a glance readable than the enumeration one I personally think. :)
<?php
header('Location: http://www.google.com'); //Send browser to http://www.google.com
?>
For My Mac OS mountain Lion device :
Works perfect !
fileinput
already supports inplace editing. It redirects stdout
to the file in this case:
#!/usr/bin/env python3
import fileinput
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_to_search, replacement_text), end='')
There are shorter ways of doing it like others have said, but you can also check each character until you encounter a second space yourself, then return the corresponding substring.
static string Extract(string str)
{
bool end = false;
int length = 0 ;
foreach (char c in str)
{
if (c == ' ' && end == false)
{
end = true;
}
else if (c == ' ' && end == true)
{
break;
}
length++;
}
return str.Substring(0, length);
}
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
/stop([a-zA-Z])+/
Will match any stop word (stop, stopped, stopping, etc)
However, if you just want to match "stop" at the start of a string
/^stop/
will do :D
Looks like this behavior is how Ansible currently works, although there is a lot of interest in fixing it to work as desired. There's currently a pull request with the desired functionality so hopefully this will get incorporated into Ansible eventually.
I believe that by now the above answers are outdated (or at least unclear) so here's my little go at it.
I tried compiling ffmpeg with the option --enable-encoders=libx264
and it will give no error but it won't enable anything (I can't seem to find where I found that suggestion).
Anyways step-by-step, first you must compile libx264 yourself because repository version is outdated:
wget ftp://ftp.videolan.org/pub/x264/snapshots/last_x264.tar.bz2
tar --bzip2 -xvf last_x264.tar.bz2
cd x264-snapshot-XXXXXXXX-XXXX/
./configure
make
sudo make install
And then get and compile ffmpeg with libx264 enabled. I'm using the latest release which is "Happiness":
wget http://ffmpeg.org/releases/ffmpeg-0.11.2.tar.bz2
tar --bzip2 -xvf ffmpeg-0.11.2.tar.bz2
cd ffmpeg-0.11.2/
./configure --enable-libx264 --enable-gpl
make
sudo install
Now finally you have the libx264 codec to encode, to check it you may run
ffmpeg -codecs | grep h264
and you'll see the options you have were the first D means decoding and the first E means encoding
<iframe src="http://docs.google.com/gview?url=http://domain.com/pdf.pdf&embedded=true"
style="width:600px; height:500px;" frameborder="0"></iframe>
Google docs allows you to embed PDFs, Microsoft Office Docs, and other applications by just linking to their services with an iframe. Its user-friendly, versatile, and attractive.
<span style="color:#ffffff; font-size:18px; line-height:35px; font-family: Calibri;">Our Activities </span>
This works for me well:) As it has been already mentioned above "The font tag has been deprecated, at least in XHTML. It always safe to use span tag. font may not give you desire results, at least in my case it didn't.
- (IBAction)toggleSpinner:(id)sender
{
if (self.spinner.isAnimating)
{
[self.spinner stopAnimating];
((UIButton *)sender).titleLabel.text = @"Start spinning";
[self.controlState setValue:[NSNumber numberWithBool:NO] forKey:@"SpinnerAnimatingState"];
}
else
{
[self.spinner startAnimating];
((UIButton *)sender).titleLabel.text = @"Stop spinning";
[self.controlState setValue:[NSNumber numberWithBool:YES] forKey:@"SpinnerAnimatingState"];
}
}
I need to select every production with a category that doesn't contain "Business"
Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as
//production[category[not(contains(., 'Business'))]]
rather than
//production[not(contains(category, 'Business'))]
The latter selects every production whose first category
child doesn't contain "Business". The two XPath expressions will behave differently when a production
has no category
children, or more than one.
It doesn't make any difference in practice as long as every <production>
has exactly one <category>
child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').
Another option is to use modal segue
STEP 1: Go to the storyboard, and give the View Controller a Storyboard ID. You can find where to change the storyboard ID in the Identity Inspector on the right.
Lets call the storyboard ID ModalViewController
STEP 2: Open up the 'sender' view controller (let's call it ViewController
) and add this code to it
public class ViewController {
override func viewDidLoad() {
showModalView()
}
func showModalView() {
if let mvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ModalViewController") as? ModalViewController {
self.present(mvc, animated: true, completion: nil)
}
}
}
Note that the View Controller we want to open is also called ModalViewController
STEP 3: To close ModalViewController, add this to it
public class ModalViewController {
@IBAction func closeThisViewController(_ sender: Any?) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
}
A simple example for copy-pasting into Chrome console:
fetch('https://example.com/path', {method:'GET',
headers: {'Authorization': 'Basic ' + btoa('login:password')}})
.then(response => response.json())
.then(json => console.log(json));
Get all the checked checkbox value in an array - one liner
const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);_x000D_
console.log(data);
_x000D_
<div class="row">_x000D_
<input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option1</label>_x000D_
<input class="custom-control-input inp" type="checkbox" id="inlineCheckbox1" value="option2"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option2</label>_x000D_
<input class="custom-control-input inp" Checked type="checkbox" id="inlineCheckbox1" value="option3"> _x000D_
<label class="custom-control-label" for="inlineCheckbox1">Option3</label>_x000D_
</div>
_x000D_
Here's the cleaned up ARC version, based on @elsurudo's code:
- (id)fetchSSIDInfo {
NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
NSLog(@"Supported interfaces: %@", ifs);
NSDictionary *info;
for (NSString *ifnam in ifs) {
info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
NSLog(@"%@ => %@", ifnam, info);
if (info && [info count]) { break; }
}
return info;
}
As pointed out, you cannot set arbitrary inline styles for hover, but you can change the style of the hover cursor in CSS using the following in the appropriate tag:
style="cursor: pointer;"
Personally I would use the Maven surefire JUnit runner to do that.
Try this, note that you don't need to specify the end index in substring
.
var characters = member.substr(member.length -2);
Do you have an activity set up the be the launched activity when the application starts?
This is done in your Manifest.xml file, something like:
<activity android:name=".Main" android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You can easily install it by writing
Install-Package AjaxControlToolkit
in package manager console.
for more information you can check this link
I am using Visual Studio Code 1.52.1 on windows 10 machine.'cls' or 'Clear' doesn't clear the terminal.
just write
exit
It will close the terminal and press
ctrl+shift+`
to open new terminal.
StringUtils.abbreviate
from Apache Commons Lang library could be your friend:
StringUtils.abbreviate("abcdefg", 6) = "abc..."
StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
StringUtils.abbreviate("abcdefg", 4) = "a..."
Commons Lang3 even allow to set a custom String as replacement marker. With this you can for example set a single character ellipsis.
StringUtils.abbreviate("abcdefg", "\u2026", 6) = "abcde…"
Try this,
// prepare json data
let json: [String: Any] = ["title": "ABC",
"dict": ["1":"First", "2":"Second"]]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = URL(string: "http://httpbin.org/post")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()
or try a convenient way Alamofire
You are missing a comma in your statement.
Try this:
data[data[, "Var1"]>10, ]
Or:
data[data$Var1>10, ]
Or:
subset(data, Var1>10)
As an example, try it on the built-in dataset, mtcars
data(mtcars)
mtcars[mtcars[, "mpg"]>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
mtcars[mtcars$mpg>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
subset(mtcars, mpg>25)
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
xmllint --format yourxmlfile.xml
xmllint is a command line XML tool and is included in libxml2
(http://xmlsoft.org/).
================================================
Note: If you don't have libxml2
installed you can install it by doing the following:
CentOS
cd /tmp
wget ftp://xmlsoft.org/libxml2/libxml2-2.8.0.tar.gz
tar xzf libxml2-2.8.0.tar.gz
cd libxml2-2.8.0/
./configure
make
sudo make install
cd
Ubuntu
sudo apt-get install libxml2-utils
Cygwin
apt-cyg install libxml2
MacOS
To install this on MacOS with Homebrew just do:
brew install libxml2
Git
Also available on Git if you want the code:
git clone git://git.gnome.org/libxml2
This worked for me.
using System.IO;
//
string readStr = File.ReadAllText(file.FullName);
string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);
The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.
You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.
You can configure individual ObjectMappers like this:
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
If you want it set globally, I usually access a configured mapper through a wrapper class.
When cin
gets input it can't use, it sets failbit
:
int n;
cin >> n;
if(!cin) // or if(cin.fail())
{
// user didn't input a number
cin.clear(); // reset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
// next, request user reinput
}
When cin
's failbit
is set, use cin.clear()
to reset the state of the stream, then cin.ignore()
to expunge the remaining input, and then request that the user re-input. The stream will misbehave so long as the failure state is set and the stream contains bad input.
main()
{
int *arr[5];
int i=31, j=5, k=19, l=71, m;
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;
arr[4]=&m;
for(m=0; m<=4; m++)
{
printf("%d",*(arr[m]));
}
return 0;
}
You have not joined TableD, merely selected the TableD FIELD (dID
) from one of the tables.
It is possible to save a "list" of labels in keras model directly. This way the user who uses the model for predictions and does not have any other sources of information can perform the lookup himself. Here is a dummy example of how one can perform an "injection" of labels
# assume we get labels as list
labels = ["cat","dog","horse","tomato"]
# here we start building our model with input image 299x299 and one output layer
xx = Input(shape=(299,299,3))
flat = Flatten()(xx)
output = Dense(shape=(4))(flat)
# here we perform injection of labels
tf_labels = tf.constant([labels],dtype="string")
tf_labels = tf.tile(labels,[tf.shape(xx)[0],1])
output_labels = Lambda(lambda x: tf_labels,name="label_injection")(xx)
#and finaly creating a model
model=tf.keras.Model(xx,[output,output_labels])
When used for prediction, this model returns tensor of scores and tensot of string labels. Model like this can be saved to h5. In this case the file contains the labels. This model can also be exported to saved_model and used for serving in the cloud.
SQL is the actual language that as defined by the ISO and ANSI. Here is a link to the Wikipedia article. MySQL is a specific implementation of this standard. I believe Oracle bought the company that originally developed MySQL. Other companies also have their own implementations of the SQL standard.
With Jenkins 1.494, I was able to send a file to a job parameter on Ubuntu Linux 12.10 using curl
with --form
parameters:
curl --form name=myfileparam --form file=@/local/path/to/your/file.xml \
-Fjson='{"parameter": {"name": "myfileparam", "file": "file"}}' \
-Fsubmit=Build \
http://user:password@jenkinsserver/job/jobname/build
On the Jenkins server, I configured a job that accepts a single parameter: a file upload parameter named myfileparam
.
The first line of that curl call constructs a web form with a parameter named myfileparam
(same as in the job); its value will be the contents of a file on the local file system named /local/path/to/your/file.txt
. The @
symbol prefix tells curl to send a local file instead of the given filename.
The second line defines a JSON request that matches the form parameters on line one: a file parameter named myfileparam
.
The third line activates the form's Build button. The forth line is the job URL with the "/build" suffix.
If this call is successful, curl returns 0
. If it is unsuccessful, the error or exception from the service is printed to the console. This answer takes a lot from an old blog post relating to Hudson, which I deconstructed and re-worked for my own needs.
I like the approach and implemented it on server-side without doing any authentication related thing on front-end
My 'technique' on my latest app is.. the client doesn't care about Auth. Every single thing in the app requires a login first, so the server just always serves a login page unless an existing user is detected in the session. If session.user is found, the server just sends index.html. Bam :-o
Look for the comment by "Andrew Joslin".
Use an "Or"
Select SUM(CAmount) as PaymentAmount
from TableOrderPayment
where (CPaymentType='Check' Or CPaymentType='Cash')
and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
and CStatus='" & "Active" & "'"
or an "IN"
Select SUM(CAmount) as PaymentAmount
from TableOrderPayment
where CPaymentType IN ('Check', 'Cash')
and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
and CStatus='" & "Active" & "'"
If your code has add(0)
and remove(0)
, use a LinkedList
and it's prettier addFirst()
and removeFirst()
methods. Otherwise, use ArrayList
.
And of course, Guava's ImmutableList is your best friend.
Just run graphics.off()
before plotting your data.
This instruction solved my error. So, it's harmless to try it before taking a more complex solution.
I. In your build.gradle add latest appcompat library, at the time 24.2.1
dependencies {
compile 'com.android.support:appcompat-v7:X.X.X'
// where X.X.X version
}
II. Make your activity extend android.support.v7.app.AppCompatActivity
and implement the DatePickerDialog.OnDateSetListener
interface.
public class MainActivity extends AppCompatActivity
implements DatePickerDialog.OnDateSetListener {
III. Create your DatePickerDialog
setting a context, the implementation of the listener and the start year, month and day of the date picker.
DatePickerDialog datePickerDialog = new DatePickerDialog(
context, MainActivity.this, startYear, starthMonth, startDay);
IV. Show your dialog on the click event listener of your button
((Button) findViewById(R.id.myButton))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
datePickerDialog.show();
}
});
This may be what you want. Settings -> Appearance & Behavior -> System Settings > Project Opening > Default Directory
It worked for me. I tried Android Studio 3.5.
Assuming there will be no errors thrown, and you want to work on the top stash item in the list of available stashes:
git stash pop
= git stash apply
+ git stash drop
You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.
There's a good howto here:
https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/
Basically:
If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).
Here's another one-liner approach to throw out there:
next((some_list.pop(i) for i, l in enumerate(some_list) if l == thing), None)
It doesn't create a list copy, doesn't make multiple passes through the list, doesn't require additional exception handling, and returns the matched object or None if there isn't a match. Only issue is that it makes for a long statement.
In general, when looking for a one-liner solution that doesn't throw exceptions, next() is the way to go, since it's one of the few Python functions that supports a default argument.
From your example, it seems to me you want to use a static method.
class mystuff:
@staticmethod
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
print mystuff.average(9,18,27)
Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.
<select>
<option value="1" <?php if ($myVar==1) echo 'selected="selected"';?>>Yes</options>
<option value="2" <?php if ($myVar==2) echo 'selected="selected"';?>>No</options>
<option value="3" <?php if ($myVar==3) echo 'selected="selected"';?>>Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
This is a very simple and straightforward way, if I understand your question correctly.
var timestamp = DateTime.Now.ToFileTime();
//output: 132260149842749745
This is an alternative way to individuate distinct transactions. It's not unix time, but windows filetime.
From the docs:
A Windows file time is a 64-bit value that represents the number of 100-
nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601
A.D. (C.E.) Coordinated Universal Time (UTC).
You could run jconsole
(included with Java 6's SDK) then connect to your Java application. It will show you every Thread running and its stack trace.
The best way, and it converts to a String as bonus ;)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//Dates to compare
String CurrentDate= "09/24/2015";
String FinalDate= "09/26/2015";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");
//Setting dates
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
Log.e("HERE","HERE: " + dayDifference);
}
catch (Exception exception) {
Log.e("DIDN'T WORK", "exception " + exception);
}
}
This is how I did it:
$str = file_get_contents("my-code-file.php");
echo "<textarea disabled='true' style='border: none;background-color:white;'>";
echo $str;
echo "</textarea>";
Included page:
<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>
Including page:
<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
ui:composition
as shown above.ui:include
in the including xhtml file as also shown above.It sounds like you have a form tag in a Master Page and in the Page that is throwing the error.
You can have only one.
Go to your folder path in cmd where your angular is installed and type
ng --version
it will show your angular version. Thanks.
You have to declare the function before you use it. If the function name appears before its declaration, C compiler will follow certain rules and makes the declaration itself. If it is wrong, you will get that error.
You have two options: (1) define it before you use it, or (2) use forward declaration without implementation. For example:
char *do_something(char *dest, const char *src);
Note the semicolon at the end.
If you are using Java 8 then try this using lambda expression and org.apache.commons.lang.StringUtils, that will also clear null
and blank
values from array
input
public static String[] cleanArray(String[] array) {
return Arrays.stream(array).filter(x -> !StringUtils.isBlank(x)).toArray(String[]::new);
}
You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/
(very rough example)
#!/usr/bin/expect
set pass "mysecret"
spawn /usr/bin/passwd
expect "password: "
send "$pass"
expect "password: "
send "$pass"
If upload_file
is meant to be the file, use:
files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}
r = requests.post(url, files=files, data=values)
and requests
will send a multi-part form POST body with the upload_file
field set to the contents of the file.txt
file.
The filename will be included in the mime header for the specific field:
>>> import requests
>>> open('file.txt', 'wb') # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', 'http://example.com', files=files).prepare().body.decode('ascii'))
--c226ce13d09842658ffbd31e0563c6bd
Content-Disposition: form-data; name="upload_file"; filename="file.txt"
--c226ce13d09842658ffbd31e0563c6bd--
Note the filename="file.txt"
parameter.
You can use a tuple for the files
mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:
files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}
This sets an alternative filename and content type, leaving out the optional headers.
If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files
parameter, just post the file directly as data
. You then may want to set a Content-Type
header too, as none will be set otherwise. See Python requests - POST data from a file.
In order to access the files, the permissions must be given in the manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Try this:
String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
string
is synonym for System.String
type, They are identical.
Values are also identical: string.Empty == String.Empty == ""
I would not use character constant "" in code, rather string.Empty
or String.Empty
- easier to see what programmer meant.
Between string
and String
I like lower case string
more just because I used to work with Delphi for lot of years and Delphi style is lowercase string
.
So, if I was your boss, you would be writing string.Empty
I know this thread is old now but I am answering it to keep things a bit updated.
With Angular 1.4 and above you can directly use limitTo filter which apart from accepting the limit
parameter also accepts a begin
parameter.
Usage: {{ limitTo_expression | limitTo : limit : begin}}
So now you may not need to use any third party library to achieve something like pagination. I have created a fiddle to illustrate the same.
I noticed I was using the incorrect HTTP request url while making it, later which i changed that it resolved my problem. my upload url was : http://192.168.0.31:5000/uploader while i was using http://192.168.0.31:5000. that was a get call. and got a java.net.SocketException: Broken pipe? exception.
That was my reason. might lead you to check one more point when this issue
public void postRequest() {
Security.insertProviderAt(Conscrypt.newProvider(), 1);
System.out.println("mediafilename-->>" + mediaFileName);
String[] dirarray = mediaFileName.split("/");
String file_name = dirarray[6];
//Thread.sleep(10000);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file",file_name, RequestBody.create(MediaType.parse("video/mp4"), new File(mediaFileName))).build();
OkHttpClient okHttpClient = new OkHttpClient();
// ExecutorService executor = newFixedThreadPool(20);
// Request request = new Request.Builder().post(requestBody).url("https://192.168.0.31:5000/uploader").build();
Request request = new Request.Builder().url("http://192.168.0.31:5000/uploader").post(requestBody).build();
// Request request = new Request.Builder().url("http://192.168.0.31:5000").build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
//
call.cancel();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"Something went wrong:" + " ", Toast.LENGTH_SHORT).show();
}
});
e.printStackTrace();
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
System.out.println("Response ; " + response.body().toString());
// Toast.makeText(getApplicationContext(), response.body().toString(),Toast.LENGTH_LONG).show();
System.out.println(response);
}
});
Safari 7.0.5 still does not support notification for validation of input fields.
To overcome it is possible to write fallback script like this: http://codepen.io/ashblue/pen/KyvmA
To see what HTML5 / CSS3 features are supported by browsers check: http://caniuse.com/form-validation
function hasHtml5Validation () {
//Check if validation supported && not safari
return (typeof document.createElement('input').checkValidity === 'function') &&
!(navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0);
}
$('form').submit(function(){
if(!hasHtml5Validation())
{
var isValid = true;
var $inputs = $(this).find('[required]');
$inputs.each(function(){
var $input = $(this);
$input.removeClass('invalid');
if(!$.trim($input.val()).length)
{
isValid = false;
$input.addClass('invalid');
}
});
if(!isValid)
{
return false;
}
}
});
SASS / LESS:
input, select, textarea {
@include appearance(none);
border-radius: 0px;
&.invalid {
border-color: red !important;
}
}
points
or lines
comes handy if
y2
is generated later, orx
but still should go into the same coordinate system.As your y
s share the same x
, you can also use matplot
:
matplot (x, cbind (y1, y2), pch = 19)
(without the pch
matplopt
will plot the column numbers of the y
matrix instead of dots).
Accepted answer is not the best in all cases because sometimes you want to perserve classes of options and different arguments (for example data-foo).
My solution is:
var sel = $('#select_id');
var selected = sel.val(); // cache selected value, before reordering
var opts_list = sel.find('option');
opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
sel.html('').append(opts_list);
sel.val(selected); // set cached selected value
//For ie11 or those who get a blank options, replace html('') empty()
To manually sign an Android APK file run these three commands:
Generate Keystore file
keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000
Sign Your APK file using jarsigner
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME
Align Signed APK using zipalign tool
zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH
Generate Keystore file
keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000
keytool -genkey -v -keystore id.keystore -alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000
keystore password : yourApp@123 key password : yourApp@123
D:\ru\SignedBuilds\MySignedApp>keytool -genkey -v -keystore id.keystore
-alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]: MySignedApp Sample
What is the name of your organizational unit?
[Unknown]: Information Technology
What is the name of your organization?
[Unknown]: MySignedApp Demo
What is the name of your City or Locality?
[Unknown]: Mumbai
What is the name of your State or Province?
[Unknown]: Maharashtra
What is the two-letter country code for this unit?
[Unknown]: IN
Is CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra, C=IN corr
ect?
[no]: y
Generating 2,048 bit RSA key pair and self-signed certificate (SHA256withRSA) with a validity of 10,
000 days
for: CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra,
C=IN
Enter key password for <MySignedApp>
(RETURN if same as keystore password):
Re-enter new password:
[Storing id.keystore]
D:\ru\SignedBuilds\MySignedApp>
Sign your app with your private keystore using jarsigner
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id
D:\ru\SignedBuilds\MySignedApp>jarsigner -verbose -sigalg SHA1withRSA -
digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id ---
ect
Enter Passphrase for keystore:
adding: META-INF/MANIFEST.MF
adding: META-INF/---.SF
adding: META-INF/---.RSA
signing: AndroidManifest.xml
.....
signing: classes.dex
signing: lib/commons-codec-1.6.jar
signing: lib/armeabi/libkonyjsvm.so
jar signed.
Warning:
No -tsa or -tsacert is provided and this jar is not timestamped. Without a timestamp, users may not
be able to validate this jar after the signer certificate's expiration date (2044-02-07) or after an
y future revocation date.
D:\ru\SignedBuilds\MySignedApp>
Verify that your APK is signed
jarsigner -verify -verbose -certs JARSIGNED_APK_FILE_PATH
jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk
D:\ru\SignedBuilds\MySignedApp>jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk
s = signature was verified
m = entry is listed in manifest
k = at least one certificate was found in keystore
i = at least one certificate was found in identity scope
jar verified.
Warning:
This jar contains entries whose certificate chain is not validated.
This jar contains signatures that does not include a timestamp. Without a timestamp, users may not b
e able to validate this jar after the signer certificate's expiration date (2044-02-09) or after any
future revocation date.
D:\ru\SignedBuilds\MySignedApp>
zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH_WITH_NAME_ofSignedAPK
zipalign -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
D:\Android\android-sdk\build-tools\19.1.0>zipalign -v 4 D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16
_prod_playstore\MySignedAppS1-release-unsigned.apk D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16_prod
_playstore\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...
4528613 classes.dex (OK - compressed)
5656594 lib/commons-codec-1.6.jar (OK - compressed)
5841869 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful
D:\Android\android-sdk\build-tools\19.1.0>
Verify that your APK is Aligned successfully
zipalign -c -v 4 YOUR_APK_PATH
zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
D:\Android\android-sdk\build-tools\19.1.0>zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...
4453984 res/drawable/zoomout.png (OK)
4454772 res/layout/tabview.xml (OK - compressed)
4455243 res/layout/wheel_item.xml (OK - compressed)
4455608 resources.arsc (OK)
4470161 classes.dex (OK - compressed)
5597923 lib/commons-codec-1.6.jar (OK - compressed)
5783198 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful
D:\Android\android-sdk\build-tools\19.1.0>
The verify command is just to check whether APK is built and signed correctly!
I hope this will help one and all :)
State machines can be very complex for a complex problem. They are also subject to unexpected bugs. They can turn into a nightmare if someone runs into a bug or needs to change the logic in the future. They are also difficult to follow and debug without the state diagram. Structured programming is much better (for example you would probably not use a state machine at mainline level). You can use structured programming even in interrupt context (which is where state machines are usually used). See this article "Macros to simulate multi-tasking/blocking code at interrupt level" found at codeproject.com.
the Grade class must also implement Serializable
public class Grade implements Serializable {
.....your content....
}
Consider this array:
$arr = array("key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value4");
To remove an element using the array key
:
// To unset an element from array using Key:
unset($arr["key2"]);
var_dump($arr);
// output: array(3) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
To remove element by value
:
// remove an element by value:
$arr = array_diff($arr, ["value1"]);
var_dump($arr);
// output: array(2) { ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
read more about array_diff: http://php.net/manual/en/function.array-diff.php
To remove an element by using index
:
array_splice($arr, 1, 1);
var_dump($arr);
// array(1) { ["key3"]=> string(6) "value3" }
read more about array_splice: http://php.net/manual/en/function.array-splice.php
The chosen solution doesn't actually work for me because I get a
"Unexpected Token <"
error in Chrome. This is because the error is thrown as soon as the parse comes across and unknown character. However, there is a way around this if you are returning only string values through ajax (which can be fairly useful if you are using PHP or ASPX to process ajax requests and might or might not return JSON depending on conditions)
The solution is quite simple, you can do the following to check if it was a valid JSON return
var IS_JSON = true;
try
{
var json = $.parseJSON(msg);
}
catch(err)
{
IS_JSON = false;
}
As I have said before, this is the solution for if you are either returning string type stuff from your AJAX request or if you are returning mixed type.
I was using View.INVISIBLE
and View.VISIBLE
and the ProgressBar
would slowly flash instead of constantly being visible, switched to View.GONE
and View.VISIBLE
and it works perfectly
a solution To preserve,both methods and properties from merged onjects is to create a combinator class that can
class combinator{
function __construct(){
$this->melt = array_reverse(func_get_args());
// array_reverse is to replicate natural overide
}
public function __call($method,$args){
forEach($this->melt as $o){
if(method_exists($o, $method)){
return call_user_func_array([$o,$method], $args);
//return $o->$method($args);
}
}
}
public function __get($prop){
foreach($this->melt as $o){
if(isset($o->$prop))return $o->$prop;
}
return 'undefined';
}
}
simple use
class c1{
public $pc1='pc1';
function mc1($a,$b){echo __METHOD__." ".($a+$b);}
}
class c2{
public $pc2='pc2';
function mc2(){echo __CLASS__." ".__METHOD__;}
}
$comb=new combinator(new c1, new c2);
$comb->mc1(1,2);
$comb->non_existing_method(); // silent
echo $comb->pc2;
On my Linux I see an error with
adb shell "su -c '[your command goes here]'"
su: invalid uid/gid '-c'
The solution is on Linux
adb shell su 0 '[your command goes here]'
Regex to the rescue!
import re
s = re.sub('[^0-9a-zA-Z]+', '*', s)
Example:
>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'
I was able to figure it out. In case someone wants to know below the code that worked for me:
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);
Let me know if there is a simpler way o doing it.
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()
resp.read()
is the straight html of the page you want to open, and you can use opener
to view any page using your session cookie.
As many of the answer suggesting better solution is to use ArrayList. ArrayList size is not fixed and it is easily manageable.
It is resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.
Note that this implementation is not synchronized.
ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test1");
scripts.add("test2");
scripts.add("test3");
Lazy loading - is good when handling with pagination like on page load list of users appear which contains 10 users and as the user scrolls down the page an api call brings next 10 users.Its good when you don't want to load enitire data at once as it would take more time and would give bad user experience.
Eager loading - is good as other people suggested when there are not much relations and fetch entire data at once in single call to database
This happened to me when I was debugging my C# WinForms application in Visual Studio. My application makes calls to Win32 stuff via DllImport, e.g.
[DllImport("Secur32.dll", SetLastError = false)]
private static extern uint LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList);
Running Visual Studio "as Administrator" solved the problem for me.
Use async/await :
async function firstFunction(){
for(i=0;i<x;i++){
// do something
}
return;
};
then use await in your other function to wait for it to return:
async function secondFunction(){
await firstFunction();
// now wait for firstFunction to finish...
// do something else
};
The widely-used PCRE library can handle such situations (you won't achieve the the same with POSIX-compliant regex engines, though):
(\b\w+\b)\W+\1
I use Eclipse Java EE edition
Create a "Dynamic Web Project"
Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.
When I deploy I export the project to a war file.
I would also suggest using some kind of build tool (Ant or Maven, Ant is already suggested and is easier to start with) or an IDE that handles the compilation (Eclipse uses incremental compilation with reconciling strategy, and you don't even have to care to press any "Compile" buttons).
If you need to try something out for a larger project and don't have any proper build tools nearby, you can always use a small trick that javac
offers: the classnames to compile can be specified in a file. You simply have to pass the name of the file to javac
with the @
prefix.
If you can create a list of all the *.java
files in your project, it's easy:
# Linux / MacOS
$ find -name "*.java" > sources.txt
$ javac @sources.txt
:: Windows
> dir /s /B *.java > sources.txt
> javac @sources.txt
sources.txt
file each time you create a new source or rename an existing one file which is an easy to forget (thus error-prone) and tiresome task.On the long run it is better to use a tool that was designed to build software.
If you create a simple build.xml
file that describes how to build the software:
<project default="compile">
<target name="compile">
<mkdir dir="bin"/>
<javac srcdir="src" destdir="bin"/>
</target>
</project>
you can compile the whole software by running the following command:
$ ant
Maven is not that trivial to set up and work with, but learning it pays well. Here's a great tutorial to start a project within 5 minutes.
Now that what could boost your development productivity. There are a few open source alternatives (like Eclipse and NetBeans, I prefer the former) and even commercial ones (like IntelliJ) which are quite popular and powerful.
They can manage the project building in the background so you don't have to deal with all the command line stuff. However, it always comes handy if you know what actually happens in the background so you can hunt down occasional errors like a ClassNotFoundException
.
For larger projects, it is always advised to use an IDE and a build tool. The former boosts your productivity, while the latter makes it possible to use different IDEs with the project (e.g., Maven can generate Eclipse project descriptors with a simple mvn eclipse:eclipse
command). Moreover, having a project that can be tested/built with a single line command is easy to introduce to new colleagues and into a continuous integration server for example. Piece of cake :-)
Just write
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
Order by name
the order by is applied to the complete resultset
-You can use any free address in the network 127.0.0.0/8 , in my case needed this for python flask and this is what I have done : add this line in the hosts file (you can find it is windows under : C:\Windows\System32\drivers\etc ) :
127.0.0.5 flask.dev
Make sure the port is the default port "80" in my case this is what in the python flask: app.run("127.0.0.5","80")
now run your code and browse flask.dev
Usually I prefer to use this extension:
Swift 3.x and Swift 4.0:
extension FileManager {
class func documentsDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String]
return paths[0]
}
class func cachesDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
return paths[0]
}
}
Swift 2.x:
extension NSFileManager {
class func documentsDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
return paths[0]
}
class func cachesDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as [String]
return paths[0]
}
}
Material Design styling alert dialogs: Custom Font, Button, Color & shape,..
MaterialAlertDialogBuilder(requireContext(),
R.style.MyAlertDialogTheme
)
.setIcon(R.drawable.ic_dialogs_24px)
.setTitle("Feedback")
//.setView(R.layout.edit_text)
.setMessage("Do you have any additional comments?")
.setPositiveButton("Send") { dialog, _ ->
val input =
(dialog as AlertDialog).findViewById<TextView>(
android.R.id.text1
)
Toast.makeText(context, input!!.text, Toast.LENGTH_LONG).show()
}
.setNegativeButton("Cancel") { _, _ ->
Toast.makeText(requireContext(), "Clicked cancel", Toast.LENGTH_SHORT).show()
}
.show()
Style:
<style name="MyAlertDialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog.Alert">
<item name="android:textAppearanceSmall">@style/MyTextAppearance</item>
<item name="android:textAppearanceMedium">@style/MyTextAppearance</item>
<item name="android:textAppearanceLarge">@style/MyTextAppearance</item>
<item name="buttonBarPositiveButtonStyle">@style/Alert.Button.Positive</item>
<item name="buttonBarNegativeButtonStyle">@style/Alert.Button.Neutral</item>
<item name="buttonBarNeutralButtonStyle">@style/Alert.Button.Neutral</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Dialog.Rounded
</item>
</style>
<style name="MyTextAppearance" parent="TextAppearance.AppCompat">
<item name="android:fontFamily">@font/rosarivo</item>
</style>
<style name="Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
<!-- <item name="backgroundTint">@color/colorPrimaryDark</item>-->
<item name="backgroundTint">@android:color/transparent</item>
<item name="rippleColor">@color/colorAccent</item>
<item name="android:textColor">@color/colorPrimary</item>
<!-- <item name="android:textColor">@android:color/white</item>-->
<item name="android:textSize">14sp</item>
<item name="android:textAllCaps">false</item>
</style>
<style name="Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
<item name="backgroundTint">@android:color/transparent</item>
<item name="rippleColor">@color/colorAccent</item>
<item name="android:textColor">@color/colorPrimary</item>
<!--<item name="android:textColor">@android:color/darker_gray</item>-->
<item name="android:textSize">14sp</item>
<item name="android:textAllCaps">false</item>
</style>
<style name="ShapeAppearanceOverlay.MyApp.Dialog.Rounded" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">8dp</item>
</style>
Note the potential for an out-of-range index with "i+3". You could do something like:
with open("file.txt", "r") as f:
searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
if "searchphrase" in line:
k=min(i+3,j)
for l in searchlines[i:k]: print l,
print
Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.
I tried to use awk
to print lines between two patterns while pattern2 also match pattern1. And the pattern1 line should also be printed.
e.g. source
package AAA
aaa
bbb
ccc
package BBB
ddd
eee
package CCC
fff
ggg
hhh
iii
package DDD
jjj
should has an ouput of
package BBB
ddd
eee
Where pattern1 is package BBB
, pattern2 is package \w*
. Note that CCC
isn't a known value so can't be literally matched.
In this case, neither @scai 's awk '/abc/{a=1}/mno/{print;a=0}a' file
nor @fedorqui 's awk '/abc/{a=1} a; /mno/{a=0}' file
works for me.
Finally, I managed to solve it by awk '/package BBB/{flag=1;print;next}/package \w*/{flag=0}flag' file
, haha
A little more effort result in awk '/package BBB/{flag=1;print;next}flag;/package \w*/{flag=0}' file
, to print pattern2 line also, that is,
package BBB
ddd
eee
package CCC
The detailed steps are as follow.
Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security
console.log = function(){};
Override it like any other thing.
I've always kept the tags in a separate table and then had a mapping table. Of course I've never done anything on a really large scale either.
Having a "tags" table and a map table makes it pretty trivial to generate tag clouds & such since you can easily put together SQL to get a list of tags with counts of how often each tag is used.
Steps:
7 . now open your xampp dir ( c:/xampp ) --> 8 . to phpMyadmin dir [C:\xampp\phpMyAdmin]
10 .find [ $cfg['Servers'][$i]['auth_type'] = 'config';
]line and replace 'config' to ‘cookie’
$cfg['Servers'][$i]['AllowNoPassword'] = true;
] this line change ‘true’ to ‘false’
.last : save the file .
here is a video link in case you want to see it in Action [ click Here ]
Setting the time zone by location for a spring boot application inside the application.properties
file to
spring.datasource.url=jdbc:mysql://localhost:3306/db?serverTimezone=Europe/Berlin
resolved the problem for the CET
/ CEST
time zone. The pom.xml
uses the maven artifact
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.
For background, see the Understanding ASP.NET dynamic compilation article on MSDN.
In html page for pc is easy to implement
<embed src="study/sample.pdf" type="application/pdf" height="300px" width="100%">
but pdf show in mobile by this code is not possible you must need a plugin
if you have not responsive your site. Then above code pdf not show in mobile but you can put download option after the code
<embed src="study/sample.pdf" type="application/pdf" height="300px" width="100%" class="responsive">
<a href="study/sample.pdf">download</a>
For anyone who make it in bigger scale, you might have also check how many file descriptors you have. It will throw this error if you ran out at bad moment.
This function converts a Blob
into a File
and it works great for me.
Vanilla JavaScript
function blobToFile(theBlob, fileName){
//A Blob() is almost a File() - it's just missing the two properties below which we will add
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
TypeScript (with proper typings)
public blobToFile = (theBlob: Blob, fileName:string): File => {
var b: any = theBlob;
//A Blob() is almost a File() - it's just missing the two properties below which we will add
b.lastModifiedDate = new Date();
b.name = fileName;
//Cast to a File() type
return <File>theBlob;
}
Usage
var myBlob = new Blob();
//do stuff here to give the blob some data...
var myFile = blobToFile(myBlob, "my-image.png");
I've been using vi and vim also for some 20 years, and I'm still learning new things.
David Rayner's Best of Vim Tips site is an excellent list, though it's probably more useful once you have some familiarity with vim.
I also want to mention the ViEmu site which has some great info on vi/vim tips and especially the article Why, oh WHY, do those nutheads use vi? (archived version)
I needed to rotate an object but have a call back function. Inspired by John Kern's answer I created this.
function animateRotate (object,fromDeg,toDeg,duration,callback){
var dummy = $('<span style="margin-left:'+fromDeg+'px;">')
$(dummy).animate({
"margin-left":toDeg+"px"
},
{
duration:duration,
step: function(now,fx){
$(object).css('transform','rotate(' + now + 'deg)');
if(now == toDeg){
if(typeof callback == "function"){
callback();
}
}
}
}
)};
Doing this you can simply call the rotate on the object like so... (in my case I'm doing it on a disclosure triangle icon that has already been rotated by default to 270 degress and I'm rotating it another 90 degrees to 360 degrees at 1000 milliseconds. The final argument is the callback after the animation has finished.
animateRotate($(".disclosure_icon"),270,360,1000,function(){
alert('finished rotate');
});
Replacing spaces is fine, but I might suggest going a little further to handle other URL-hostile characters like question marks, apostrophes, exclamation points, etc.
Also note that the general consensus among SEO experts is that dashes are preferred to underscores in URLs.
import re
def urlify(s):
# Remove all non-word characters (everything except numbers and letters)
s = re.sub(r"[^\w\s]", '', s)
# Replace all runs of whitespace with a single dash
s = re.sub(r"\s+", '-', s)
return s
# Prints: I-cant-get-no-satisfaction"
print(urlify("I can't get no satisfaction!"))
Which would you rather write and maintain?
ASP.NET MVC
public class TweetsController : Controller {
// GET: /Tweets/
[HttpGet]
public ActionResult Index() {
return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
}
}
ASP.NET Web API
public class TweetsController : ApiController {
// GET: /Api/Tweets/
public List<Tweet> Get() {
return Twitter.GetTweets();
}
}
Like this:
<?php
$option = $_POST['taskOption'];
?>
The index of the $_POST
array is always based on the value of the name
attribute of any HTML input.
You could use XDocument:
new XDocument(
new XElement("root",
new XElement("someNode", "someValue")
)
)
.Save("foo.xml");
If the file you want to create is very big and cannot fit into memory you might use XmlWriter.
JSONObject typically uses HashMap
internally to store the data. So, you can use it as Map in your code.
Example,
JSONObject obj = JSONObject.fromObject(strRepresentation);
Iterator i = obj.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry)i.next();
System.out.println("Key: " + e.getKey());
System.out.println("Value: " + e.getValue());
}
When you imported the WSDL, you should have an ObjectFactory
class which should have bunch of methods for creating various input parameters.
ObjectFactory factory = new ObjectFactory();
JAXBElement<String> createMessageDescription = factory.createMessageDescription("description");
message.setDescription(createMessageDescription);
Simple solution
Hit below commend only to fix this error
npm install --save-dev @angular-devkit/build-angular
This happens where a column is explicitly set to a different collation or the default collation is different in the table queried.
if you have many tables you want to change collation on run this query:
select concat('ALTER TABLE ', t.table_name , ' CONVERT TO CHARACTER
SET utf8 COLLATE utf8_unicode_ci;') from (SELECT table_name FROM
information_schema.tables where table_schema='SCHRMA') t;
this will output the queries needed to convert all the tables to use the correct collation per column
Here is the batch file which should work for you:
@echo off
Title HOST: Installing updates on %computername%
echo %computername%
set Server=\\SERVERNAME or PATH\msifolder
:select
cls
echo Select one of the following MSI install folders for installation task.
echo.
dir "%Server%" /AD /ON /B
echo.
set /P "MSI=Please enter the MSI folder to install: "
set "Package=%Server%\%MSI%\%MSI%.msi"
if not exist "%Package%" (
echo.
echo The entered folder/MSI file does not exist ^(typing mistake^).
echo.
setlocal EnableDelayedExpansion
set /P "Retry=Try again [Y/N]: "
if /I "!Retry!"=="Y" endlocal & goto select
endlocal
goto :EOF
)
echo.
echo Selected installation: %MSI%
echo.
echo.
:verify
echo Is This Correct?
echo.
echo.
echo 0: ABORT INSTALL
echo 1: YES
echo 2: NO, RE-SELECT
echo.
set /p "choice=Select YES, NO or ABORT? [0,1,2]: "
if [%choice%]==[0] goto :EOF
if [%choice%]==[1] goto yes
goto select
:yes
echo.
echo Running %MSI% installation ...
start "Install MSI" /wait "%SystemRoot%\system32\msiexec.exe" /i /quiet "%Package%"
The characters listed on last page output on entering in a command prompt window either help cmd
or cmd /?
have special meanings in batch files. Here are used parentheses and square brackets also in strings where those characters should be interpreted literally. Therefore it is necessary to either enclose the string in double quotes or escape those characters with character ^
as it can be seen in code above, otherwise command line interpreter exits batch execution because of a syntax error.
And it is not possible to call a file with extension MSI. A *.msi file is not an executable. On double clicking on a MSI file, Windows looks in registry which application is associated with this file extension for opening action. And the application to use is msiexec
with the command line option /i
to install the application inside MSI package.
Run msiexec.exe /?
to get in a GUI window the available options or look at Msiexec (command-line options).
I have added already /quiet
additionally to required option /i
for a silent installation.
In batch code above command start
is used with option /wait
to start Windows application msiexec.exe
and hold execution of batch file until installation finished (or aborted).
Actually, as far as I know, dynamically created inline event-handlers DO work perfectly within Internet Explorer 8 when created with the x.setAttribute()
command; you just have to position them properly within your JavaScript code. I stumbled across the solution to your problem (and mine) here.
When I moved all of my statements containing x.appendChild()
to their correct positions (i.e., immediately following the last setAttribute command within their groups), I found that EVERY single setAttribute worked in IE8 as it was supposed to, including all form input attributes (including "name" and "type" attributes, as well as my "onclick" event-handlers).
I found this quite remarkable, since all I got in IE before I did this was garbage rendered across the screen, and one error after another. In addition, I found that every setAttribute still worked within the other browsers as well, so if you just remember this simple coding-practice, you'll be good to go in most cases.
However, this solution won't work if you have to change any attributes on the fly, since they cannot be changed in IE once their HTML element has been appended to the DOM; in this case, I would imagine that one would have to delete the element from the DOM, and then recreate it and its attributes (in the correct order, of course!) for them to work properly, and not throw any errors.
mkdirs()
also creates parent directories in the path this File
represents.
javadocs for mkdirs()
:
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
javadocs for mkdir()
:
Creates the directory named by this abstract pathname.
Example:
File f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());
will yield false
for the first [and no dir will be created], and true
for the second, and you will have created non_existing_dir/someDir
Thanks to yojimbo for his answer. To add to his sample, I wanted to use the jquery method $.getJSON which puts a random callback in the query string so I also wanted to parse that out in the Node.js. I also wanted to pass an object back and use the stringify function.
This is my Client Side code.
$.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
function(data){
alert(data);
},
function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
});
This is my Server side Node.js
var http = require('http');
var querystring = require('querystring');
var url = require('url');
http.createServer(function (req, res) {
//grab the callback from the query string
var pquery = querystring.parse(url.parse(req.url).query);
var callback = (pquery.callback ? pquery.callback : '');
//we probably want to send an object back in response to the request
var returnObject = {message: "Hello World!"};
var returnObjectString = JSON.stringify(returnObject);
//push back the response including the callback shenanigans
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(callback + '(\'' + returnObjectString + '\')');
}).listen(8124);
This is worked for me successfully.
"C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe" -exportcert -alias sociallisting -keystore "D:\keystore\SocialListing" | "C:\cygwin\bin\openssl.exe" sha1 -binary | "C:\cygwin\bin\openssl.exe" base64
Be careful with below path :
If command successfully work then you will see this command :
Enter keystore password : typeyourpassword
Encryptedhashkey**
(reposting this answer)
You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types
package main
import "fmt"
import "encoding/binary"
func main() {
var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
data := binary.BigEndian.Uint64(mySlice)
fmt.Println(data)
}
My problem was similar but with the inconvenience that sometimes the string contains letters (sometimes empty).
string sNumbers = "1,2,hh,3,4,x,5";
Trying to follow Pcode Xonos Extension Method:
public static List<int> SplitToIntList(this string list, char separator = ',')
{
int result = 0;
return (from s in list.Split(',')
let isint = int.TryParse(s, out result)
let val = result
where isint
select val).ToList();
}
SELECT *
FROM tbl
WHERE myDate BETWEEN #date one# AND #date two#;
MySQLi stands for MySQL improved. It's an object-oriented interface to the MySQL bindings which makes things easier to use. It also offers support for prepared statements (which are very useful). If you're on PHP 5 use MySQLi.
Let us understand some key limitations & features on Angular’s component inheritance system.
The component only inherits the class logic:
These features are very important to have in mind so let us examine each one independently.
The Component only inherits the class logic
When you inherit a Component, all logic inside is equally inherited. It is worth noting that only public members are inherited as private members are only accessible in the class that implements them.
All meta-data in the @Component decorator is not inherited
The fact that no meta-data is inherited might seem counter-intuitive at first but, if you think about this it actually makes perfect sense. If you inherit from a Component say (componentA), you would not want the selector of ComponentA, which you are inheriting from to replace the selector of ComponentB which is the class that is inheriting. The same can be said for the template/templateUrl as well as the style/styleUrls.
Component @Input and @Output properties are inherited
This is another feature that I really love about component Inheritance in Angular. In a simple sentence, whenever you have a custom @Input and @Output property, these properties get inherited.
Component lifecycle is not inherited
This part is the one that is not so obvious especially to people who have not extensively worked with OOP principles. For example, say you have ComponentA which implements one of Angular’s many lifecycle hooks like OnInit. If you create ComponentB and inherit ComponentA, the OnInit lifecycle from ComponentA won't fire until you explicitly call it even if you do have this OnInit lifecycle for ComponentB.
Calling Super/Base Component Methods
In order to have the ngOnInit() method from ComponentA fire, we need to use the super keyword and then call the method we need which in this case is ngOnInit. The super keyword refers to the instance of the component that is being inherited from which in this case will be ComponentA.
Another way
@Html.TextAreaFor(model => model.Comments[0].Comment)
And in your css do this
textarea
{
font-family: inherit;
width: 650px;
height: 65px;
}
That DataType dealie allows carriage returns in the data, not everybody likes those.