Install the package python-tk
like
sudo apt-get install python-tk
That is described (with apt-cache search python-tk
as)
Tkinter - Writing Tk applications with Python
If you hit = and expect to see line numbers, but only see byte counts, then line numbers are turned off. Hit -n to turn them on, and make sure $LESS
doesn't include 'n'.
Turning off line numbers by default (for example, setting LESS=n
) speeds up searches in very large files. It is handy if you frequently search through big files, but don't usually care which line you're on.
I typically run with LESS=RSXin
(escape codes enabled, long lines chopped, don't clear the screen on exit, ignore case on all lower case searches, and no line number counting by default) and only use -n or -S from inside less
as needed.
Are you resizing larger, or smaller? By a small % or by a larger factor like 2x, 3x? What do you mean by quality for your application? And what type of images - photographs, hard-edged line drawings, or what? Writing your own low-level pixel grinding code or trying to do it as much as possible with existing libraries (.net or whatever)?
There is a large body of knowledge on this topic. The key concept is interpolation.
Browsing recommendations:
* http://www.all-in-one.ee/~dersch/interpolator/interpolator.html
* http://www.cambridgeincolour.com/tutorials/image-interpolation.htm
* for C#: https://secure.codeproject.com/KB/GDI-plus/imageprocessing4.aspx?display=PrintAll&fid=3657&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26&select=629945
* this is java-specific but might be educational - http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
I just needed to set the size of one textbox on one page. Coding attributes on the model and creating custom editor templates were overkill, so I just wrapped the @Html.EditorFor call with a span tag that called a class which specifies the size of the textbox.
.SpaceAvailableSearch input
{
width:25px;
}
<span class="SpaceAvailableSearch">@Html.EditorFor(model => model.SearchForm.SpaceAvailable)</span>
1.) Create a sequence of numbers 'seq' from 1 to 1000, and fix the width '-w' (width is determined by length of ending number, in this case 4 digits for 1000).
2.) Also, select which numbers you want using 'sed -n' (in this case, we select numbers 1-100).
3.) 'echo' out each number. Numbers are stored in the variable 'i', accessed using the '$'.
Pros: This code is pretty clean.
Cons: 'seq' isn't native to all Linux systems (as I understand)
for i in `seq -w 1 1000 | sed -n '1,100p'`;
do
echo $i;
done
You can use Java Pluggable Annotation Processing API to write annotation processor which will be executed during the compilation process and will collect all annotated classes and build the index file for runtime use.
This is the fastest way possible to do annotated class discovery because you don't need to scan your classpath at runtime, which is usually very slow operation. Also this approach works with any classloader and not only with URLClassLoaders usually supported by runtime scanners.
The above mechanism is already implemented in ClassIndex library.
To use it annotate your custom annotation with @IndexAnnotated meta-annotation. This will create at compile time an index file: META-INF/annotations/com/test/YourCustomAnnotation listing all annotated classes. You can acccess the index at runtime by executing:
ClassIndex.getAnnotated(com.test.YourCustomAnnotation.class)
<<
operations of the final four swaps are incorrect, they should be shift-right >>
operations and their shift values would also need to be corrected.// Swap endian (big to little) or (little to big)
uint32_t num = 0x12345678;
uint32_t res =
((num & 0x000000FF) << 24) |
((num & 0x0000FF00) << 8) |
((num & 0x00FF0000) >> 8) |
((num & 0xFF000000) >> 24);
printf("%0x\n", res);
The result is represented here in both binary and hex, notice how the bytes have swapped:
?0111 1000 0101 0110 0011 0100 0001 0010?
78563412
In terms of performance, leave it to the compiler to optimize your code when possible. You should avoid unnecessary data structures like arrays for simple algorithms like this, doing so will usually cause different instruction behavior such as accessing RAM instead of using CPU registers.
// mutiple image retrieve
File folPath = new File(getIntent().getStringExtra("folder_path"));
File[] imagep = folPath.listFiles();
for (int i = 0; i < imagep.length ; i++) {
imageModelList.add(new ImageModel(imagep[i].getAbsolutePath(), Uri.parse(imagep[i].getAbsolutePath())));
}
imagesAdapter.notifyDataSetChanged();
I think you are getting confused with your site Authentication and SSL.
If you need to get your site into SSL, then you would need to install a SSL certificate into your web server. You can buy a certificate for yourself from one of the places like Symantec etc. The certificate would contain your public/private key pair, along with other things.
You wont need to do anything in your source code, and you can still continue to use your Form Authntication (or any other) in your site. Its just that, any data communication that takes place between the web server and the client will encrypted and signed using your certificate. People would use secure-HTTP (https://) to access your site.
View this for more info --> http://en.wikipedia.org/wiki/Transport_Layer_Security
SET collation_connection = 'utf8_general_ci';
then for your databases
ALTER DATABASE your_database_name CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
MySQL sneaks swedish in there sometimes for no sensible reason.
you can use this code .may be solve the problem
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);
I've been using Typescript in my current angular project for about a year and a half and while there are a few issues with definitions every now and then the DefinitelyTyped project does an amazing job at keeping up with the latest versions of most popular libraries.
Having said that there is a definite learning curve when transitioning from vanilla JavaScript to TS and you should take into account the ability of you and your team to make that transition. Also if you are going to be using angular 1.x most of the examples you will find online will require you to translate them from JS to TS and overall there are not a lot of resources on using TS and angular 1.x together right now.
If you plan on using angular 2 there are a lot of examples using TS and I think the team will continue to provide most of the documentation in TS, but you certainly don't have to use TS to use angular 2.
ES6 does have some nice features and I personally plan on getting more familiar with it but I would not consider it a production-ready language at this point. Mainly due to a lack of support by current browsers. Of course, you can write your code in ES6 and use a transpiler to get it to ES5, which seems to be the popular thing to do right now.
Overall I think the answer would come down to what you and your team are comfortable learning. I personally think both TS and ES6 will have good support and long futures, I prefer TS though because you tend to get language features quicker and right now the tooling support (in my opinion) is a little better.
If you want to get everything after |
excluding set character use this code.
[^|]*$
Others solutions \|.*$
Results : | mypcworld
This one [^|]*$
Results : mypcworld
The relevel()
command is a shorthand method to your question. What it does is reorder the factor so that whatever is the ref level is first. Therefore, reordering your factor levels will also have the same effect but gives you more control. Perhaps you wanted to have levels 3,4,0,1,2. In that case...
bFactor <- factor(b, levels = c(3,4,0,1,2))
I prefer this method because it's easier for me to see in my code not only what the reference was but the position of the other values as well (rather than having to look at the results for that).
NOTE: DO NOT make it an ordered factor. A factor with a specified order and an ordered factor are not the same thing. lm()
may start to think you want polynomial contrasts if you do that.
You can tell EF which properties have to be updated in this way:
public void ChangePassword(int userId, string password)
{
var user = new User { Id = userId, Password = password };
using (var context = new ObjectContext(ConnectionString))
{
var users = context.CreateObjectSet<User>();
users.Attach(user);
context.ObjectStateManager.GetObjectStateEntry(user)
.SetModifiedProperty("Password");
context.SaveChanges();
}
}
You can enable whitespace trimming at file save time from settings:
"files.trimTrailingWhitespace": true
setting to the User Settings document if it's not already there. This is so you aren't editing the Default Setting directly, but instead adding to it.We also added a new command to trigger this manually (Trim Trailing Whitespace from the command palette).
If you already have package-lock.json
file just delete it and try again.
Not pretty good solution, but you can try the hjson tool. It allows you to write text multi-lined in editor and then converts it to the proper valid JSON format.
Note: it adds '\n' characters for the new lines, but you can simply delete them in any text editor with the "Replace all.." function.
Use requests.packages.urllib3.disable_warnings()
and verify=False
on requests
methods.
import requests
from urllib3.exceptions import InsecureRequestWarning
# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
# Set `verify=False` on `requests.post`.
requests.post(url='https://example.com', data={'bar':'baz'}, verify=False)
What i found...when i got 'EntityValidationErrors' error is that....i have a field in my database 'db1' in table 'tbladdress' as 'address1' which has size of 100 (i.e address varchar(100) null) and i was passing value more than 100 characters..and this leading to error while saving data to database....
So you must Check the data you are passing to the field.
You probably want pop
:
a = ['a', 'b', 'c', 'd']
a.pop(1)
# now a is ['a', 'c', 'd']
By default, pop
without any arguments removes the last item:
a = ['a', 'b', 'c', 'd']
a.pop()
# now a is ['a', 'b', 'c']
Kind of an old topic, but this one might be useful for someone:
As someone mentioned above - you can use a dummy form. I had to overcome this issue some time ago. At first, I totally forgot about this HTML restriction and just added the nested forms. The result was interesting - I lost my first form from the nested. Then it turned out to be some kind of a "trick" to simply add a dummy form (that will be removed from the browser) before the actual nested forms.
In my case it looks like this:
<form id="Main">
<form></form> <!--this is the dummy one-->
<input...><form id="Nested 1> ... </form>
<input...><form id="Nested 1> ... </form>
<input...><form id="Nested 1> ... </form>
<input...><form id="Nested 1> ... </form>
......
</form>
Works fine with Chrome, Firefox, and Safari. IE up to 9 (not sure about 10) and Opera does not detect parameters in the main form. The $_REQUEST global is empty, regardless of the inputs. Inner forms seem to work fine everywhere.
Haven't tested another suggestion described here - fieldset around nested forms.
EDIT: Frameset didn't work! I simply added the Main form after the others (no more nested forms) and used jQuery's "clone" to duplicate inputs in the form on button click. Added .hide() to each of the cloned inputs to keep layout unchanged and now it works like a charm.
Floats don't have a height so the containing div has a height of zero.
<div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>
overflow:hidden clears the float for most browsers.
zoom:1 clears the float for IE.
You should be able to create a query with this filter here:
(&(objectClass=user)(sAMAccountName=yourUserName)
(memberof=CN=YourGroup,OU=Users,DC=YourDomain,DC=com))
and when you run that against your LDAP server, if you get a result, your user "yourUserName" is indeed a member of the group "CN=YourGroup,OU=Users,DC=YourDomain,DC=com
Try and see if this works!
If you use C# / VB.Net and System.DirectoryServices, this snippet should do the trick:
DirectoryEntry rootEntry = new DirectoryEntry("LDAP://dc=yourcompany,dc=com");
DirectorySearcher srch = new DirectorySearcher(rootEntry);
srch.SearchScope = SearchScope.Subtree;
srch.Filter = "(&(objectClass=user)(sAMAccountName=yourusername)(memberOf=CN=yourgroup,OU=yourOU,DC=yourcompany,DC=com))";
SearchResultCollection res = srch.FindAll();
if(res == null || res.Count <= 0) {
Console.WriteLine("This user is *NOT* member of that group");
} else {
Console.WriteLine("This user is INDEED a member of that group");
}
Word of caution: this will only test for immediate group memberships, and it will not test for membership in what is called the "primary group" (usually "cn=Users") in your domain. It does not handle nested memberships, e.g. User A is member of Group A which is member of Group B - that fact that User A is really a member of Group B as well doesn't get reflected here.
Marc
Here is the code
<html>
<body>
<input type="text" name="name" id="name" required="required" aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
<script>
function func()
{
var namdata=document.form1.name.value;
if(namdata.match("[a-z]{1,5}"))
{
document.getElementById("but1").disabled=false;
}
}
</script>
</body>
</html>
Using Javascript
How I solved my problem.
I had
?useUnicode=true&characterEncoding=UTF-8
In my hibernate jdbc connection url and I changed the string datatype to longtext in database, which was varchar before.
The method is to use another byte along with a bitwise AND to mask out the target bit.
I used convention from my classes here where "0" is the most significant bit and "7" is the least.
public static class ByteExtensions
{
// Assume 0 is the MSB andd 7 is the LSB.
public static bool GetBit(this byte byt, int index)
{
if (index < 0 || index > 7)
throw new ArgumentOutOfRangeException();
int shift = 7 - index;
// Get a single bit in the proper position.
byte bitMask = (byte)(1 << shift);
// Mask out the appropriate bit.
byte masked = (byte)(byt & bitMask);
// If masked != 0, then the masked out bit is 1.
// Otherwise, masked will be 0.
return masked != 0;
}
}
dayStart.bat
start "startOfficialSoftwares" /min cmd /k call startOfficialSoftwares.bat
start "initCodingEnvironment" /min cmd /k call initCodingEnvironment.bat
start "updateProjectSource" /min cmd /k call updateProjectSource.bat
start "runCoffeeMachine" /min cmd /k call runCoffeeMachine.bat
release.bat
call updateDevelVersion.bat
call mergeDevelIntoMaster.bat
call publishProject.bat
I would check to see if the SqlDataReader has rows returned first:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.HasRows)
{
...
}
HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use
HttpContext.Current.Request.Url.Port
In my case I just added
window.scroll(0,0);
in ngOnInit()
and its working fine.
As you know the answer is to use the ObjectFactory(). Here is a sample of the code that worked for me :)
ObjectFactory myRootFactory = new ObjectFactory();
MyRootType myRootType = myRootFactory.createMyRootType();
try {
File file = new File("./file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(MyRoot.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
JABXElement<MyRootType> myRootElement = myRootFactory.createMyRoot(myRootType);
jaxbMarshaller.marshal(myRootElement, file);
jaxbMarshaller.marshal(myRootElement, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
No. If you don't have access to the php.ini, you can't guarantee that changes would have any effect.
I doubt you need to extend your sessions time though.
It has pretty sensible timeout at the moment and there are no reasons to extend it.
I suggest you to use ArgueJS this way:
function myFunc(){
arguments = __({requiredArg: undefined, optionalArg: [undefined: 'defaultValue'})
//do stuff, using arguments.requiredArg and arguments.optionalArg
// to access your arguments
}
You can also replace undefined
by the type of the argument you expect to receive, like this:
function myFunc(){
arguments = __({requiredArg: Number, optionalArg: [String: 'defaultValue'})
//do stuff, using arguments.requiredArg and arguments.optionalArg
// to access your arguments
}
Don't need the wrap it in a div...
CSS:
tr {
width: 100%;
display: inline-table;
table-layout: fixed;
}
table{
height:300px; // <-- Select the height of the table
display: -moz-groupbox; // Firefox Bad Effect
}
tbody{
overflow-y: scroll;
height: 200px; // <-- Select the height of the body
width: 100%;
position: absolute;
}
Bootply : http://www.bootply.com/AgI8LpDugl
You need selector like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- State when a row is being pressed, but hasn't yet been activated (finger down) -->
<item android:drawable="@color/app_primary_color_light" android:state_pressed="true" />
<!-- Used when the view is "activated". -->
<item android:drawable="@color/app_primary_color" android:state_activated="true" />
<!-- Default, "just hangin' out" state. -->
<item android:drawable="@android:color/transparent" /></selector>
And then set android:choiceMode="singleChoice"
to your ListView.
3.2 introduced $sample to the aggregation pipeline.
There's also a good blog post on putting it into practice.
This was actually a feature request: http://jira.mongodb.org/browse/SERVER-533 but it was filed under "Won't fix."
The cookbook has a very good recipe to select a random document out of a collection: http://cookbook.mongodb.org/patterns/random-attribute/
To paraphrase the recipe, you assign random numbers to your documents:
db.docs.save( { key : 1, ..., random : Math.random() } )
Then select a random document:
rand = Math.random()
result = db.docs.findOne( { key : 2, random : { $gte : rand } } )
if ( result == null ) {
result = db.docs.findOne( { key : 2, random : { $lte : rand } } )
}
Querying with both $gte
and $lte
is necessary to find the document with a random number nearest rand
.
And of course you'll want to index on the random field:
db.docs.ensureIndex( { key : 1, random :1 } )
If you're already querying against an index, simply drop it, append random: 1
to it, and add it again.
Firefox 3 will display %20
s in URLs as spaces in the address bar.
In my case the error got resolved by migrating to OpenCV 4.0 (or higher).
I was looking for a resolution to this issue in Windows, and it seems to be that if you don't have the environments vars ok, you need to put the complete directory. For eg. with a file in the same directory than PHP:
F:\myfolder\php\php.exe -f F:\myfolder\php\script.php
Despite that this question has already an accepted answer, I think that the exact details of why this is happening are still missing. So I think there might be a place for one more answer.
If you add the required hadoop-aws dependency, your code should work.
Starting Hadoop 2.6.0, s3 FS connector has been moved to a separate library called hadoop-aws. There is also a Jira for that: Move s3-related FS connector code to hadoop-aws.
This means that any version of spark, that has been built against Hadoop 2.6.0 or newer will have to use another external dependency to be able to connect to the S3 File System.
Here is an sbt example that I have tried and is working as expected using Apache Spark 1.6.2 built against Hadoop 2.6.0:
libraryDependencies += "org.apache.hadoop" % "hadoop-aws" % "2.6.0"
In my case, I encountered some dependencies issues, so I resolved by adding exclusion:
libraryDependencies += "org.apache.hadoop" % "hadoop-aws" % "2.6.0" exclude("tomcat", "jasper-compiler") excludeAll ExclusionRule(organization = "javax.servlet")
On other related note, I have yet to try it, but that it is recommended to use "s3a" and not "s3n" filesystem starting Hadoop 2.6.0.
The third generation, s3a: filesystem. Designed to be a switch in replacement for s3n:, this filesystem binding supports larger files and promises higher performance.
Another way to use OVER is to have a result column in your select operate on another "partition", so to say.
This:
SELECT
name,
ssn,
case
when ( count(*) over (partition by ssn) ) > 1
then 1
else 0
end AS hasDuplicateSsn
FROM table;
returns 1 in hasDuplicateSsn for each row whose ssn is shared by another row. Great for making "tags" for data for different error reports and such.
can you try if.else
> col2=ifelse(df1$col=="true",1,0)
> df1
$col
[1] "true" "false"
> cbind(df1$col)
[,1]
[1,] "true"
[2,] "false"
> cbind(df1$col,col2)
col2
[1,] "true" "1"
[2,] "false" "0"
try this:
<div ng-if="$scope.length == 0" ? true : false></div>
and show or hide
<div ng-show="$scope.length == 0"></div>
else it will be hide
-----------------or--------------------------
if you are using $ctrl than code will be like this:
try this:
<div ng-if="$ctrl.length == 0" ? true : false></div>
and show or hide
<div ng-show="$ctrl.length == 0"></div>
else it will be hide
The []-operator is resolved to the access property this[sometype index]
, with implementation depending upon the Element-Collection.
An Enumerable-Interface declares a blueprint of what a Collection should look like in the first place.
Take this example to demonstrate the usefulness of clean Interface separation:
var ienu = "13;37".Split(';').Select(int.Parse);
//provides an WhereSelectArrayIterator
var inta = "13;37".Split(';').Select(int.Parse).ToArray()[0];
//>13
//inta.GetType(): System.Int32
Also look at the syntax of the []-operator:
//example
public class SomeCollection{
public SomeCollection(){}
private bool[] bools;
public bool this[int index] {
get {
if ( index < 0 || index >= bools.Length ){
//... Out of range index Exception
}
return bools[index];
}
set {
bools[index] = value;
}
}
//...
}
You could use this PHP, hope it helps.
<?php if(basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>
So a list would be like the below.
<ul>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="home"><i class="fa fa-dashboard"></i> <span>Home</span></a></li>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'listings' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="other"><i class="fa fa-th-list"></i> <span>Other</span></a></li>
</ul>
If you want to create a typed list with values, here's the syntax.
Assuming a class of Student like
public class Student {
public int StudentID { get; set; }
public string StudentName { get; set; }
}
You can make a list like this:
IList<Student> studentList = new List<Student>() {
new Student(){ StudentID=1, StudentName="Bill"},
new Student(){ StudentID=2, StudentName="Steve"},
new Student(){ StudentID=3, StudentName="Ram"},
new Student(){ StudentID=1, StudentName="Moin"}
};
In phpMyAdmin, navigate to the table in question and click the "Operations" tab. On the left under Table Options you will be allowed to set the current AUTO_INCREMENT value.
On windows, you can use PuttyGen to load the private key file, remove the passphrase and then overwrite the existing private key file.
you can use the postrgesql chr(int) function:
insert into test values (2,'|| chr(39)||'my users'||chr(39)||');
increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin
heap size can be changed based on Requirements.
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m
in eclipse right click on your project-> select build path and then select configure build path. from the window select the jar file that you want and refresh your project
The visible width of an element is width + padding + border + outline
, so it seems that you are forgetting about the border on the input element. That is, to say, that the default border width for an input element on most (some?) browsers is actually calculated as 2px, not one. Hence your input is appearing as 2px wider. Try explicitly setting the border-width
on the input, or making your div wider.
Had the same problem, I worked around it by changing ${java.home}/../bin/javafxpackager to ${java.home}/bin/javafxpackager
If you are looking to get the names of functions or lambdas or other function-like objects that are defined in the interpreter, you can use dill.source.getname
from dill
. It pretty much looks for the __name__
method, but in certain cases it knows other magic for how to find the name... or a name for the object. I don't want to get into an argument about finding the one true name for a python object, whatever that means.
>>> from dill.source import getname
>>>
>>> def add(x,y):
... return x+y
...
>>> squared = lambda x:x**2
>>>
>>> print getname(add)
'add'
>>> print getname(squared)
'squared'
>>>
>>> class Foo(object):
... def bar(self, x):
... return x*x+x
...
>>> f = Foo()
>>>
>>> print getname(f.bar)
'bar'
>>>
>>> woohoo = squared
>>> plus = add
>>> getname(woohoo)
'squared'
>>> getname(plus)
'add'
For my answer, it is worth remembering that the TPL (Task-Parallel-Library), Task
class and TaskStatus
enumeration were introduced prior to the async-await keywords and the async-await keywords were not the original motivation of the TPL.
In the context of methods marked as async
, the resulting Task
is not a Task
representing the execution of the method, but a Task
for the continuation of the method.
This is only able to make use of a few possible states:
I understand that Running
could appear to have been a better default than WaitingForActivation
, however this could be misleading, as the majority of the time, an async method being executed is not actually running (i.e. it may be await
-ing something else). The other option may have been to add a new value to TaskStatus
, however this could have been a breaking change for existing applications and libraries.
All of this is very different to when making use of Task.Run
which is a part of the original TPL, this is able to make use of all the possible values of the TaskStatus
enumeration.
If you wish to keep track of the status of an async method, take a look at the IProgress(T)
interface, this will allow you to report the ongoing progress. This blog post, Async in 4.5: Enabling Progress and Cancellation in Async APIs will provide further information on the use of the IProgress(T)
interface.
resize:none; This property fix your text area and bound it. you use this css property id your textarea.gave text area an id and on the behalf of that id you can use this css property.
According to Android Sqlite get last insert row id there is another query:
SELECT rowid from your_table_name order by ROWID DESC limit 1
Try Portable UTF-8:
$str = utf8_chr( 0x1000 );
$str = utf8_chr( '\u1000' );
$str = utf8_chr( 4096 );
All work exactly the same way. You can get the codepoint of a character with utf8_ord()
. Read more about Portable UTF-8.
hello bro this is a way to read the string in the exact line using this code
hope this could help you !
#include <iostream>
#include <fstream>
using namespace std;
int main (){
string text[1];
int lineno ;
ifstream file("text.txt");
cout << "tell me which line of the file you want : " ;
cin >> lineno ;
for (int i = 0; i < lineno ; i++)
{
getline(file , text[0]);
}
cout << "\nthis is the text in which line you want befor :: " << text[0] << endl ;
system("pause");
return 0;
}
Good luck !
Yes, there are negative effects from this:
If you script out a change blocked by this flag you get something like the script below (all i am turning the ID column in Contact into an autonumbered IDENTITY column, but the table has dependencies). Note potential errors that can occur while the following is running:
--
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
DROP CONSTRAINT fk_Contact_AddressType
GO
ALTER TABLE ref.ContactpointType SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
DROP CONSTRAINT fk_contact_profile
GO
ALTER TABLE raw.Profile SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE raw.Tmp_Contact
(
ContactID int NOT NULL IDENTITY (1, 1),
ProfileID int NOT NULL,
AddressType char(2) NOT NULL,
ContactText varchar(250) NULL
) ON [PRIMARY]
GO
ALTER TABLE raw.Tmp_Contact SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT raw.Tmp_Contact ON
GO
IF EXISTS(SELECT * FROM raw.Contact)
EXEC('INSERT INTO raw.Tmp_Contact (ContactID, ProfileID, AddressType, ContactText)
SELECT ContactID, ProfileID, AddressType, ContactText FROM raw.Contact WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT raw.Tmp_Contact OFF
GO
ALTER TABLE raw.PostalAddress
DROP CONSTRAINT fk_AddressProfile
GO
ALTER TABLE raw.MarketingFlag
DROP CONSTRAINT fk_marketingflag_contact
GO
ALTER TABLE raw.Phones
DROP CONSTRAINT fk_phones_contact
GO
DROP TABLE raw.Contact
GO
EXECUTE sp_rename N'raw.Tmp_Contact', N'Contact', 'OBJECT'
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
Idx_Contact_1 PRIMARY KEY CLUSTERED
(
ProfileID,
ContactID
)
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
Idx_Contact UNIQUE NONCLUSTERED
(
ProfileID,
ContactID
)
GO
CREATE NONCLUSTERED INDEX idx_Contact_0 ON raw.Contact
(
AddressType
)
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
fk_contact_profile FOREIGN KEY
(
ProfileID
) REFERENCES raw.Profile
(
ProfileID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
fk_Contact_AddressType FOREIGN KEY
(
AddressType
) REFERENCES ref.ContactpointType
(
ContactPointTypeCode
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Phones ADD CONSTRAINT
fk_phones_contact FOREIGN KEY
(
ProfileID,
PhoneID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.Phones SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.MarketingFlag ADD CONSTRAINT
fk_marketingflag_contact FOREIGN KEY
(
ProfileID,
ContactID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.MarketingFlag SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.PostalAddress ADD CONSTRAINT
fk_AddressProfile FOREIGN KEY
(
ProfileID,
AddressID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.PostalAddress SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
Unfortunately , JSONArray
doesn't support foreach
statements, like:
for(JSONObject someObj : someJsonArray) {_x000D_
// do something about someObj_x000D_
...._x000D_
...._x000D_
}
_x000D_
There are some dedicated classes for this:
import java.text.*;
final CharacterIterator it = new StringCharacterIterator(s);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
// process c
...
}
This one is in my opinion the best one for online (offline however dreamweaver is best): http://www.maschek.hu/imagemap/imgmap
There is a prebuilt bootstrap bower package called bootstrap-css. I think this is what you (and I) were hoping to find.
bower install bootstrap-css
Thanks Nico.
colrm x
For example, if you need the first 100 characters:
cat file |colrm 101
It's been around for years and is in most linux's and bsd's (freebsd for sure), usually by default. I can't remember ever having to type apt-get install colrm
.
okay it solved, here is my final code
if($(this).width() > $(this).height()) {
$(this).css('width',MaxPreviewDimension+'px');
$(this).css('height','auto');
} else {
$(this).css('height',MaxPreviewDimension+'px');
$(this).css('width','auto');
}
Thanks guys
It's very simple to control custom messages with the help of HTML5
event oninvalid
Here is code:
<input id="UserID" type="text" required="required"
oninvalid="this.setCustomValidity('Witinnovation')"
onvalid="this.setCustomValidity('')">
This is most important:
onvalid="this.setCustomValidity('')"
One last thing is to check for Event Listeners > "scroll" and test deleting them.
Even if you delete the Javascript that created them, the listeners will stick around and prevent scrolling.
.c : c file (where the real action is, in general)
.h : header file (to be included with a preprocessor #include
directive). Contains stuff that is normally deemed to be shared with other parts of your code, like function prototypes, #define'd stuff, extern declaration for global variables (oh, the horror) and the like.
Technically, you could put everything in a single file. A whole C program. million of lines. But we humans tend to organize things. So you create different C files, each one containing particular functions. That's all nice and clean. Then suddenly you realize that a declaration you have into a given C file should exist also in another C file. So you would duplicate them. The best is therefore to extract the declaration and put it into a common file, which is the .h
For example, in the cs50.h you find what are called "forward declarations" of your functions. A forward declaration is a quick way to tell the compiler how a function should be called (e.g. what input params) and what it returns, so it can perform proper checking (for example if you call a function with the wrong number of parameters, it will complain).
Another example. Suppose you write a .c file containing a function performing regular expression matching. You want your function to accept the regular expression, the string to match, and a parameter that tells if the comparison has to be case insensitive.
in the .c you will therefore put
bool matches(string regexp, string s, int flags) { the code }
Now, assume you want to pass the following flags:
0: if the search is case sensitive
1: if the search is case insensitive
And you want to keep yourself open to new flags, so you did not put a boolean. playing with numbers is hard, so you define useful names for these flags
#define MATCH_CASE_SENSITIVE 0
#define MATCH_CASE_INSENSITIVE 1
This info goes into the .h, because if any program wants to use these labels, it has no way of knowing them unless you include the info. Of course you can put them in the .c, but then you would have to include the .c code (whole!) which is a waste of time and a source of trouble.
I've had the same issue after running out of disk space. Closing and reopening terminal fixed it one time. Restarting my Mac the next.
Some easy things to try before jumping to random commands:
Ideally the email content should be about 550px wide to fit within most email clients preview window. If you know for sure your target market can view bigger then you can design bigger. Loads of email examples over on http://www.beautiful-email-newsletters.com/
assertEquals
uses the equals
method for comparison. There is a different assert, assertSame
, which uses the ==
operator.
To understand why ==
shouldn't be used with strings you need to understand what ==
does: it does an identity check. That is, a == b
checks to see if a
and b
refer to the same object. It is built into the language, and its behavior cannot be changed by different classes. The equals
method, on the other hand, can be overridden by classes. While its default behavior (in the Object
class) is to do an identity check using the ==
operator, many classes, including String
, override it to instead do an "equivalence" check. In the case of String
, instead of checking if a
and b
refer to the same object, a.equals(b)
checks to see if the objects they refer to are both strings that contain exactly the same characters.
Analogy time: imagine that each String
object is a piece of paper with something written on it. Let's say I have two pieces of paper with "Foo" written on them, and another with "Bar" written on it. If I take the first two pieces of paper and use ==
to compare them it will return false
because it's essentially asking "are these the same piece of paper?". It doesn't need to even look at what's written on the paper. The fact that I'm giving it two pieces of paper (rather than the same one twice) means it will return false
. If I use equals
, however, the equals
method will read the two pieces of paper and see that they say the same thing ("Foo"), and so it'll return true
.
The bit that gets confusing with Strings is that the Java has a concept of "interning" Strings, and this is (effectively) automatically performed on any string literals in your code. This means that if you have two equivalent string literals in your code (even if they're in different classes) they'll actually both refer to the same String
object. This makes the ==
operator return true
more often than one might expect.
This worked for me:
#include <iostream>
#include <pthread.h>
using namespace std;
void* print_message(void*) {
cout << "Threading\n";
}
int main() {
pthread_t t1;
pthread_create(&t1, NULL, &print_message, NULL);
cout << "Hello";
// Optional.
void* result;
pthread_join(t1,&result);
// :~
return 0;
}
Before removing the service you should review the dependencies.
You can check it:
Open services.msc
and find the service name, switch to the "Dependencies" tab.
Source: http://www.sysadmit.com/2016/03/windows-eliminar-un-servicio.html
I was looking for something similar and this seemed a bit complicated so I did this. I think it's a little easier to understand. You can use it as a Comparator or as a one liner. For this question you would change to compareToIgnoreCase(). As is, nulls float up. You can flip the 1, -1 if you want them to sink.
StringUtil.NULL_SAFE_COMPARATOR.compare(getName(), o.getName());
.
public class StringUtil {
public static final Comparator<String> NULL_SAFE_COMPARATOR = new Comparator<String>() {
@Override
public int compare(final String s1, final String s2) {
if (s1 == s2) {
//Nulls or exact equality
return 0;
} else if (s1 == null) {
//s1 null and s2 not null, so s1 less
return -1;
} else if (s2 == null) {
//s2 null and s1 not null, so s1 greater
return 1;
} else {
return s1.compareTo(s2);
}
}
};
public static void main(String args[]) {
final ArrayList<String> list = new ArrayList<String>(Arrays.asList(new String[]{"qad", "bad", "sad", null, "had"}));
Collections.sort(list, NULL_SAFE_COMPARATOR);
System.out.println(list);
}
}
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
Above many answers but doesn't work for me some of them no exception handling in correct way. here am adding a perfect solution work amazing for me sure also for you too.
//base64 decode string
String s = "ewoic2VydmVyIjoic2cuenhjLmx1IiwKInNuaSI6InRlc3RpbmciLAoidXNlcm5hbWUiOiJ0ZXN0
ZXIiLAoicGFzc3dvcmQiOiJ0ZXN0ZXIiLAoicG9ydCI6IjQ0MyIKfQ==";
String val = a(s) ;
Toast.makeText(this, ""+val, Toast.LENGTH_SHORT).show();
public static String a(String str) {
try {
return new String(Base64.decode(str, 0), "UTF-8");
} catch (UnsupportedEncodingException | IllegalArgumentException unused) {
return "This is not a base64 data";
}
}
According to documentation you're correct (http://php.net/manual/en/pdo.connections.php):
The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
Note that if you initialise the PDO object as a persistent connection it will not automatically close the connection.
You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.
As I mentioned in the comment, having to use the dot()
function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.
Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @
infix-operator for matrix multiplication, thanks to pep 465.
Edit: Regarding your comment:
Yes. The whole of numpy is based on arrays.
Yes. linalg.norm(v)
is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.
To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.
An example in ipython:
In [1]: import math
In [2]: import numpy as np
In [3]: a = np.array([4,2,7])
In [4]: np.linalg.norm(a)
Out[4]: 8.3066238629180749
In [5]: math.sqrt(sum([n**2 for n in a]))
Out[5]: 8.306623862918075
In [6]: b = a/np.linalg.norm(a)
In [7]: np.linalg.norm(b)
Out[7]: 1.0
Note that In [5]
is an alternative way to calculate the length. In [6]
shows normalizing the vector.
Hex to Decimal Conversion
Convert.ToInt32(number, 16);
Decimal to Hex Conversion
int.Parse(number, System.Globalization.NumberStyles.HexNumber)
For Kotlin you can use context
directly in fragments. But in some cased you will find an error like
Type mismatch: inferred type is Context? but Context was expected
for that you can do this
val ctx = context ?: return
textViewABC.setTextColor(ContextCompat.getColor(ctx, android.R.color.black))
Why you don't use CSS for centering a div?
#timer_wrap{
position: fixed;
left: 50%;
top: 50%;
}
I prefer to use sub query list:
rm -r `ls | grep -v "textfile.txt\|backup.tar.gz\|script.php\|database.sql\|info.txt"`
-v, --invert-match select non-matching lines
\|
Separator
[Covariance and contravariance]
Lets take a look at example
public class A { }
//B is A
public class B extends A { }
//C is A
public class C extends A { }
Generics allows you to work with Types dynamically in a safe way
//ListA
List<A> listA = new ArrayList<A>();
//add
listA.add(new A());
listA.add(new B());
listA.add(new C());
//get
A a0 = listA.get(0);
A a1 = listA.get(1);
A a2 = listA.get(2);
//ListB
List<B> listB = new ArrayList<B>();
//add
listB.add(new B());
//get
B b0 = listB.get(0);
Since Java's Collection is a reference type as a result we have next issues:
Problem #1
//not compiled
//danger of **adding** non-B objects using listA reference
listA = listB;
*Swift's generic does not have such problem because Collection is Value type
[About] therefore a new collection is created
Problem #2
//not compiled
//danger of **getting** non-B objects using listB reference
listB = listA;
Wildcard is a reference type feature and it can not be instantiated directly
Solution #1
<? super A>
aka lower bound aka contravariance aka consumers guarantees that it is operates by A and all superclasses, that is why it is safe to add
List<? super A> listSuperA;
listSuperA = listA;
listSuperA = new ArrayList<Object>();
//add
listSuperA.add(new A());
listSuperA.add(new B());
//get
Object o0 = listSuperA.get(0);
Solution #2
<? extends A>
aka upper bound aka covariance aka producers guarantees that it is operates by A and all subclasses, that is why it is safe to get and cast
List<? extends A> listExtendsA;
listExtendsA = listA;
listExtendsA = listB;
//get
A a0 = listExtendsA.get(0);
If you are trying to use the null coalescing operator ??
in a version of PHP prior to PHP 7 you will get this error.
<?= $a ?? 2; // works in PHP 7+
<?= (!empty($a)) ? $a : 2; // All versions of PHP
A similar error can occur for nullable types, as in:
function add(?int $sum): ?int {
Which again indicates an outdated PHP version being used (either the CLI version php -v
or the webserver bound one phpinfo();
).
On the Unity Editor open your project and:
If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:
cd to/your/unity/project/folder
git init
git add *
git commit -m "First commit"
git remote add origin [email protected]:username/project.git
git push -u origin master
You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).
Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.
And here's my own .gitignore recipe for my Unity projects:
# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*
# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj
# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db
Another way is to use a utility function (you could make this a static method of a generic utility class if you like):
byte[] concat(byte[]...arrays)
{
// Determine the length of the result array
int totalLength = 0;
for (int i = 0; i < arrays.length; i++)
{
totalLength += arrays[i].length;
}
// create the result array
byte[] result = new byte[totalLength];
// copy the source arrays into the result array
int currentIndex = 0;
for (int i = 0; i < arrays.length; i++)
{
System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
currentIndex += arrays[i].length;
}
return result;
}
Invoke like so:
byte[] a;
byte[] b;
byte[] result = concat(a, b);
It will also work for concatenating 3, 4, 5 arrays, etc.
Doing it this way gives you the advantage of fast arraycopy code which is also very easy to read and maintain.
There are 3 basic commands to compare files in unix:
cmp
: This command is used to compare two files byte by byte and as any mismatch occurs,it echoes it on the screen.if no mismatch occurs i gives no response.
syntax:$cmp file1 file2.
comm
: This command is used to find out the records available in one but not in another
diff
In Kotlin
evLoginPassword.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
doTheLoginWork()
}
true
}
Partial Xml Code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<EditText
android:id="@+id/evLoginUserEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/email"
android:inputType="textEmailAddress"
android:textColor="@color/black_54_percent" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<EditText
android:id="@+id/evLoginPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/password"
android:inputType="textPassword"
android:imeOptions="actionDone"
android:textColor="@color/black_54_percent" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
This is a simple prove that you cannot destroy an object, you can only destroy a link to it.
$var = (object)['a'=>1];
$var2 = $var;
$var2->a = 2;
unset($var2);
echo $var->a;
returns
2
See it in action here: https://eval.in/1054130
Late but more complete answer in point of getting the most advanced date from $Output
## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv
## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
Sort-Object Date | Select-Object -Last 1 -Expand Date
## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
Sort-Object | Select-Object -Last 1
## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
[datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1
## for non English locales
$Output.Date | ForEach-Object{
[datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1
## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
[datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1
Add these methods to your Activity:
private MyService myServiceBinder;
public ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
myServiceBinder = ((MyService.MyBinder) binder).getService();
Log.d("ServiceConnection","connected");
showServiceData();
}
public void onServiceDisconnected(ComponentName className) {
Log.d("ServiceConnection","disconnected");
myService = null;
}
};
public Handler myHandler = new Handler() {
public void handleMessage(Message message) {
Bundle data = message.getData();
}
};
public void doBindService() {
Intent intent = null;
intent = new Intent(this, BTService.class);
// Create a new Messenger for the communication back
// From the Service to the Activity
Messenger messenger = new Messenger(myHandler);
intent.putExtra("MESSENGER", messenger);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}
And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.
@Override
protected void onResume() {
Log.d("activity", "onResume");
if (myService == null) {
doBindService();
}
super.onResume();
}
@Override
protected void onPause() {
//FIXME put back
Log.d("activity", "onPause");
if (myService != null) {
unbindService(myConnection);
myService = null;
}
super.onPause();
}
Note, that when binding to a service only the onCreate()
method is called in the service class.
In your Service class you need to define the myBinder method:
private final IBinder mBinder = new MyBinder();
private Messenger outMessenger;
@Override
public IBinder onBind(Intent arg0) {
Bundle extras = arg0.getExtras();
Log.d("service","onBind");
// Get messager from the Activity
if (extras != null) {
Log.d("service","onBind with extra");
outMessenger = (Messenger) extras.get("MESSENGER");
}
return mBinder;
}
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
After you defined these methods you can reach the methods of your service at your Activity:
private void showServiceData() {
myServiceBinder.myMethod();
}
and finally you can start your service when some event occurs like _BOOT_COMPLETED_
public class MyReciever extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("android.intent.action.BOOT_COMPLETED")) {
Intent service = new Intent(context, myService.class);
context.startService(service);
}
}
}
note that when starting a service the onCreate()
and onStartCommand()
is called in service class
and you can stop your service when another event occurs by stopService()
note that your event listener should be registerd in your Android manifest file:
<receiver android:name="MyReciever" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
You'll want to include action="javascript:void(0);"
to your form to prevent page reloads and maintain HTML standard.
If the main problem is the loss of precision when converting from a float to a string, one possible way to go is to convert the floats to the decimal
S: http://docs.python.org/library/decimal.html.
In python 2.7 and higher you can directly convert a float to a decimal
object.
In case you want to avoid too much confusion for your translators, I've come up with a way to have just a placeholder in the strings, which will be handled in code.
So, supposed you have this in the strings:
<string name="test">
<![CDATA[
We found %1$s items]]>
</string>
And you want the placeholder text to have a different size and color, you can use this:
val textToPutAsPlaceHolder = "123"
val formattedStr = getString(R.string.test, "$textToPutAsPlaceHolder<bc/>")
val placeHolderTextSize = resources.getDimensionPixelSize(R.dimen.some_text_size)
val placeHolderTextColor = ContextCompat.getColor(this, R.color.design_default_color_primary_dark)
val textToShow = HtmlCompat.fromHtml(formattedStr, HtmlCompat.FROM_HTML_MODE_LEGACY, null, object : Html.TagHandler {
var start = 0
override fun handleTag(opening: Boolean, tag: String, output: Editable, xmlReader: XMLReader) {
when (tag) {
"bc" -> if (!opening) start = output.length - textToPutAsPlaceHolder.length
"html" -> if (!opening) {
output.setSpan(AbsoluteSizeSpan(placeHolderTextSize), start, start + textToPutAsPlaceHolder.length, 0)
output.setSpan(ForegroundColorSpan(placeHolderTextColor), start, start + textToPutAsPlaceHolder.length, 0)
}
}
}
})
textView.text = textToShow
And the result:
Set the default console colors and fonts:
http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)
Set-StrictMode -Version Latest
Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location
You could also use
print(tbl_df(df), n=40)
or with the help of the pipe operator
df %>% tbl_df %>% print(n=40)
To print all rows specify tbl_df %>% print(n = Inf)
Cython
It seems that the goto answer for this is Cython. I'm really surprised no one else mentioned this yet? Here's the home page: https://cython.org
In a nutshell, this transforms your python into C and compiles it, thus making it as well protected as any "normal" compiled distributable C program.
There are limitations though. I haven't explored them in depth myself, because as I started to read about them, I dropped the idea for my own purposes. But it might still work for yours. Essentially, you can't use Python to the fullest, with the dynamic awesomeness it offers. One major issue that jumped out at me, was that keyword parameters are not usable :( You must write function calls using positional parameters only. I didn't confirm this, but I doubt you can use conditional imports, or evals. I'm not sure how polymorphism is handled...
Anyway, if you aren't trying to obfuscate a huge code base after the fact, or ideally if you have the use of Cython in mind to begin with, this is a very notable option.
Not sure if your question was answered.
This will write the time & date every 20 seconds in the file ping_ip.txt. The second to last line just says run the same batch file again, and agan, and again,..........etc.
Does not seem to create multiple instances, so that's a good thing.
@echo %time% %date% >>ping_ip.txt
ping -n 20 -w 3 127.0.0.1 >>ping_ip.txt
This_Batch_FileName.bat
cls
Why you need to implement shuffle when it already exists? Stay on the shoulders of giants.
import random
d1 = {0:'zero', 1:'one', 2:'two', 3:'three', 4:'four',
5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'}
keys = list(d1)
random.shuffle(keys)
d2 = {}
for key in keys: d2[key] = d1[key]
print(d1)
print(d2)
Concept Solution:br.read() returns particular character's int value so loop continue's until we won't get -1 as int value and Hence up to there it prints br.readLine() which returns a line into String form.
//Way 1:
while(br.read()!=-1)
{
//continues loop until we won't get int value as a -1
System.out.println(br.readLine());
}
//Way 2:
while((line=br.readLine())!=null)
{
System.out.println(line);
}
//Way 3:
for(String line=br.readLine();line!=null;line=br.readLine())
{
System.out.println(line);
}
Way 4: It's an advance way to read file using collection and arrays concept How we iterate using for each loop. check it here http://www.java67.com/2016/01/how-to-use-foreach-method-in-java-8-examples.html
As I wrote is best to use the file .htaccess
. However beware of the time you leave the contents in the cache.
Use:
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
Where: 604800 = 7 days
PS: This can be used to reset any header
Simple:
When you use curl it encodes the string to utf-8
you just need to decode them..
Description
string utf8_decode ( string $data )
This function decodes data , assumed to be UTF-8
encoded, to ISO-8859-1
.
If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).
Eclipse Classic is basically the full featured Eclipse without the Java EE part.
There's a free trial for 100 minutes on https://browserling.com and you can test on Safari v7.0 during the trial period.
This answer from here helped me:
You should take a look at the build path of your project to check whether the referenced libraries are still there. So right-click on your project, then "Properties -> Java Build Path -> Libraries" and check whether you still have the spring library JARs in the place that is mentioned there. If not, just re-add them to your classpath within this dialog.
Please Search Google given to the world by Larry Page and Sergey Brin.
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
if(out != null) {
out.close();
}
}
If for some reason you don't want to use the break instruction (if you think it will disrupt your reading flow next time you will read your programm, for example), you can try the following :
boolean test = true;
for (int i = 0; i < 1220 && test; i++) {
System.out.println(i);
if (i == 20) {
test = false;
}
}
The second arg of a for loop is a boolean test. If the result of the test is true, the loop will stop. You can use more than just an simple math test if you like. Otherwise, a simple break will also do the trick, as others said :
for (int i = 0; i < 1220 ; i++) {
System.out.println(i);
if (i == 20) {
break;
}
}
I'll slightly expand @assylias answer to take time zone into account. There are at least two ways to get LocalDateTime for specific time zone.
You can use setDefault time zone for whole application. It should be called before any timestamp -> java.time conversion:
public static void main(String... args) {
TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(utcTimeZone);
...
timestamp.toLocalDateTime().toLocalDate();
}
Or you can use toInstant.atZone chain:
timestamp.toInstant()
.atZone(ZoneId.of("UTC"))
.toLocalDate();
You can use the build job
step from Jenkins Pipeline (Minimum Jenkins requirement: 2.130).
Here's the full API for the build
step: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/
How to use build
:
job
: Name of a downstream job to build. May be another Pipeline job, but more commonly a freestyle or other project.
../sister-folder/downstream
/top-level-folder/nested-folder/downstream
At my company many of our branches include "/". You must replace any instances of "/" with "%2F" (as it appears in the URL of the job).
In this example we're using relative paths
stage('Trigger Branch Build') {
steps {
script {
echo "Triggering job for branch ${env.BRANCH_NAME}"
BRANCH_TO_TAG=env.BRANCH_NAME.replace("/","%2F")
build job: "../my-relative-job/${BRANCH_TO_TAG}", wait: false
}
}
}
build job: 'your-job-name',
parameters: [
string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
]
Source: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/
More info on Parallel here: https://jenkins.io/doc/book/pipeline/syntax/#parallel
stage ('Trigger Builds In Parallel') {
steps {
// Freestyle build trigger calls a list of jobs
// Pipeline build() step only calls one job
// To run all three jobs in parallel, we use "parallel" step
// https://jenkins.io/doc/pipeline/examples/#jobs-in-parallel
parallel (
linux: {
build job: 'full-build-linux', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
},
mac: {
build job: 'full-build-mac', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
},
windows: {
build job: 'full-build-windows', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
},
failFast: false)
}
}
Or alternatively:
stage('Build A and B') {
failFast true
parallel {
stage('Build A') {
steps {
build job: "/project/A/${env.BRANCH}", wait: true
}
}
stage('Build B') {
steps {
build job: "/project/B/${env.BRANCH}", wait: true
}
}
}
}
In WinForm, we can always get the Control Key status by:
bool IsCtrlPressed = (Control.ModifierKeys & Keys.Control) != 0;
Need to remove C:\Program Files (x86)\Common Files\Oracle\Java\javapath from environment and replace by JAVA_HOME which is works fine for me
To round up you can use modulus.
The second part of the equation will add to True if there's a remainder. (True = 1; False = 0)
ex: 3/2
answer=$(((3 / 2) + (3 % 2 > 0)))
echo $answer
2
ex: 100 / 2
answer=$(((100 / 2) + (100 % 2 > 0)))
echo $answer
50
ex: 100 / 3
answer=$(((100 / 3) + (100 % 3 > 0)))
echo $answer
34
In Windows, you also normally need to run command line as administrator.
As standard-user:
docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon 106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
Get https://mcr.microsoft.com/v2/: dial tcp: lookup mcr.microsoft.com on [::1]:53: read udp [::1]:45540->[::1]:53: read:
>>>connection refused
But as an administrator.
docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon 106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
3.0: Pulling from dotnet/core/runtime
68ced04f60ab: Pull complete e936bd534ffb: Pull complete caf64655bcbb: Pull complete d1927dbcbcab: Pull complete Digest: sha256:e0c67764f530a9cad29a09816614c0129af8fe3bd550eeb4e44cdaddf8f5aa40
Status: Downloaded newer image for mcr.microsoft.com/dotnet/core/runtime:3.0
---> f059cd71a22a
Successfully built f059cd71a22a
Successfully tagged myimage:latest
I would all but guarantee that the issue is some sort of non-printing character that's present in the value you pulled off your socket. It looks like you're using Python 2.x, in which case you can check for them with this:
print repr(temp)
You'll likely see something in there that's escaped in the form \x00
. These non-printing characters don't show up when you print directly to the console, but their presence is enough to negatively impact the parsing of a string value into a float.
-- Edited for question changes --
It turns this is partly accurate for your issue - the root cause however appears to be that you're reading more information than you expect from your socket or otherwise receiving multiple values. You could do something like
map(float, temp.strip().split('\r\n'))
In order to convert each of the values, but if your function is supposed to return a single float value this is likely to cause confusion. Anyway, the issue certainly revolves around the presence of characters you did not expect to see in the value you retrieved from your socket.
UPDATED
Some time on, I see a comment that brings me back to my old answer, and I think I'd do it differently now. These days I'd write:
private static IEnumerable<T> GetEnumValues<T>()
{
// Can't use type constraints on value types, so have to do check like this
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException("T must be of type System.Enum");
}
return Enum.GetValues(typeof(T)).Cast<T>();
}
You can do this by using @ViewChild
for more info check this link
With type selector
child component
@Component({
selector: 'child-cmp',
template: '<p>child</p>'
})
class ChildCmp {
doSomething() {}
}
parent component
@Component({
selector: 'some-cmp',
template: '<child-cmp></child-cmp>',
directives: [ChildCmp]
})
class SomeCmp {
@ViewChild(ChildCmp) child:ChildCmp;
ngAfterViewInit() {
// child is set
this.child.doSomething();
}
}
With string selector
child component
@Component({
selector: 'child-cmp',
template: '<p>child</p>'
})
class ChildCmp {
doSomething() {}
}
parent component
@Component({
selector: 'some-cmp',
template: '<child-cmp #child></child-cmp>',
directives: [ChildCmp]
})
class SomeCmp {
@ViewChild('child') child:ChildCmp;
ngAfterViewInit() {
// child is set
this.child.doSomething();
}
}
This link might help you out: http://pastebin.com/f10584951.
Pasted below for posterity:
/*
* Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
* from the iBATIS Apache project. Only removed dependency on Resource class
* and a constructor
*/
/*
* Copyright 2004 Clinton Begin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.*;
/**
* Tool to run database scripts
*/
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
private Connection connection;
private boolean stopOnError;
private boolean autoCommit;
private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
/**
* Default constructor
*/
public ScriptRunner(Connection connection, boolean autoCommit,
boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property
*
* @param logWriter
* - the new value of the logWriter property
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property
*
* @param errorLogWriter
* - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter)
*
* @param reader
* - the source of the script
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != this.autoCommit) {
connection.setAutoCommit(this.autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException e) {
throw e;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the
* connection passed in
*
* @param conn
* - the connection to use for the script
* @param reader
* - the source of the script
* @throws SQLException
* if any SQL errors occur
* @throws IOException
* if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException,
SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter
&& trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter
&& trimmedLine.equals(getDelimiter())) {
command.append(line.substring(0, line
.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
// Ignore to workaround a bug in Jakarta DBCP
}
Thread.yield();
} else {
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
assign
copy:
retain:
You should use some HTML parsing library like lxml
:
from lxml import etree
s = """<table>
<tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
<tr><td>a</td><td>b</td><td>c</td></tr>
<tr><td>d</td><td>e</td><td>f</td></tr>
<tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""
table = etree.HTML(s).find("body/table")
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
values = [col.text for col in row]
print dict(zip(headers, values))
prints
{'End Date': 'c', 'Start Date': 'b', 'Event': 'a'}
{'End Date': 'f', 'Start Date': 'e', 'Event': 'd'}
{'End Date': 'i', 'Start Date': 'h', 'Event': 'g'}
I had an inversion problem, but a neat solution.
Motivation was that the XAML designer would show an empty control e.g. when there was no datacontext / no MyValues
(itemssource).
Initial code: hide control when MyValues
is empty.
Improved code: show control when MyValues
is NOT null or empty.
Ofcourse the problem is how to express '1 or more items', which is the opposite of 0 items.
<ListBox ItemsSource={Binding MyValues}">
<ListBox.Style x:Uid="F404D7B2-B7D3-11E7-A5A7-97680265A416">
<Style TargetType="{x:Type ListBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding MyValues.Count}">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.Style>
</ListBox>
I solved it by adding:
<DataTrigger Binding="{Binding MyValues.Count, FallbackValue=0, TargetNullValue=0}">
Ergo setting the default for the binding. Ofcourse this doesn't work for all kinds of inverse problems, but helped me out with clean code.
Others mentioned django-phonenumber-field
. To get the display format how you want you need to set PHONENUMBER_DEFAULT_FORMAT
setting to "E164"
, "INTERNATIONAL"
, "NATIONAL"
, or "RFC3966"
, however you want it displayed. See the GitHub source.
We've used Ants Profiler Pro by Red Gate software in our project. It works really well for all .NET language-based applications.
We found that the .NET Garbage Collector is very "safe" in its cleaning up of in-memory objects (as it should be). It would keep objects around just because we might be using it sometime in the future. This meant we needed to be more careful about the number of objects that we inflated in memory. In the end, we converted all of our data objects over to an "inflate on-demand" (just before a field is requested) in order to reduce memory overhead and increase performance.
EDIT: Here's a further explanation of what I mean by "inflate on demand." In our object model of our database we use Properties of a parent object to expose the child object(s). For example if we had some record that referenced some other "detail" or "lookup" record on a one-to-one basis we would structure it like this:
class ParentObject
Private mRelatedObject as New CRelatedObject
public Readonly property RelatedObject() as CRelatedObject
get
mRelatedObject.getWithID(RelatedObjectID)
return mRelatedObject
end get
end property
End class
We found that the above system created some real memory and performance problems when there were a lot of records in memory. So we switched over to a system where objects were inflated only when they were requested, and database calls were done only when necessary:
class ParentObject
Private mRelatedObject as CRelatedObject
Public ReadOnly Property RelatedObject() as CRelatedObject
Get
If mRelatedObject is Nothing
mRelatedObject = New CRelatedObject
End If
If mRelatedObject.isEmptyObject
mRelatedObject.getWithID(RelatedObjectID)
End If
return mRelatedObject
end get
end Property
end class
This turned out to be much more efficient because objects were kept out of memory until they were needed (the Get method was accessed). It provided a very large performance boost in limiting database hits and a huge gain on memory space.
i had this made to answer the problem:
Sub goTIMER(NumOfSeconds As Long) 'in (seconds) as: call gotimer (1) 'seconds
Application.Wait now + NumOfSeconds / 86400#
'Application.Wait (Now + TimeValue("0:00:05")) 'other
Application.EnableEvents = True 'EVENTS
End Sub
Try This Code: It may help you
<html>
<head>
<style>
body
{
background:url('images/top-left.jpg') no-repeat center center fixed;
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<form action="LoginCheck.jsp"method="post">
</br>Username:<input type="text" name="username">
</br>Password:<input type="password" name="password">
</br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
You can use the Median of Medians algorithm to find median of an unsorted array in linear time.
You have to return JSON error object yourself after setting the StatusCode, like so ...
if (BadRequest)
{
Dictionary<string, object> error = new Dictionary<string, object>();
error.Add("ErrorCode", -1);
error.Add("ErrorMessage", "Something really bad happened");
return Json(error);
}
Another way is to have a JsonErrorModel
and populate it
public class JsonErrorModel
{
public int ErrorCode { get; set;}
public string ErrorMessage { get; set; }
}
public ActionResult SomeMethod()
{
if (BadRequest)
{
var error = new JsonErrorModel
{
ErrorCode = -1,
ErrorMessage = "Something really bad happened"
};
return Json(error);
}
//Return valid response
}
Take a look at the answer here as well
Python has a language feature called List Comprehensions that is perfectly suited to making this sort of thing extremely easy. The following statement does exactly what you want and stores the result in l3
:
l3 = [x for x in l1 if x not in l2]
l3
will contain [1, 6]
.
It is better if you find quotation marks by using the indexof()
method and then add a string behind that index.
string s="hai";
int s=s.indexof(""");
I found the answer:
$mail->AddEmbeddedImage('img/2u_cs_mini.jpg', 'logo_2u');
and on the <img>
tag put src='cid:logo_2u'
sys.exit
is the canonical way to exit.
Internally sys.exit
just raises SystemExit
. However, calling sys.exit
is more idiomatic than raising SystemExit
directly.
os.exit
is a low-level system call that exits directly without calling any cleanup handlers.
quit
and exit
exist only to provide an easy way out of the Python prompt. This is for new users or users who accidentally entered the Python prompt, and don't want to know the right syntax. They are likely to try typing exit
or quit
. While this will not exit the interpreter, it at least issues a message that tells them a way out:
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()
$
This is essentially just a hack that utilizes the fact that the interpreter prints the __repr__
of any expression that you enter at the prompt.
I tried most of the previous answers, but it didn’t work for my machine, Ubuntu 18.04 (Bionic Beaver), but what worked for me was this.
First: check your PHP version
$ php -version
Second: add your PHP version to the command. Mine was:
$ sudo apt-get install php7.2-curl
Lastly, restart the Apache server:
sudo service apache2 restart
Although most persons claimed that it not necessary to restart Apache :)
You can implement a class that holds the fields you have in your JSON
class MyData
{
public string t;
public bool a;
public object[] data;
public string[][] type;
}
and then use the generic version of DeserializeObject:
MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
// Do something with typeStr
}
Documentation: Serializing and Deserializing JSON
Fiddle to your heart's content
HTML
<div>
<a tabindex="1" class="testA">Test A</a> | <a tabindex="2" class="testB">Test B</a>
<div class="hiddendiv" id="testA">1</div>
<div class="hiddendiv" id="testB">2</div>
</div>
CSS
.hiddendiv {display: none; }
.testA:focus ~ #testA {display: block; }
.testB:focus ~ #testB {display: block; }
Benefits
You can put your menu links horizontally = one after the other in HTML code, and then you can put all the content one after another in the HTML code, after the menu.
In other words - other solutions offer an accordion approach where you click a link and the content appears immediately after the link. The next link then appears after that content.
With this approach you don't get the accordion effect. Rather, all links remain in a fixed position and clicking any link simply updates the displayed content. There is also no limitation on content height.
How it works
In your HTML, you first have a DIV
. Everything else sits inside this DIV
. This is important - it means every element in your solution (in this case, A
for links, and DIV
for content), is a sibling to every other element.
Secondly, the anchor tags (A
) have a tabindex
property. This makes them clickable and therefore they can get focus. We need that for the CSS to work. These could equally be DIV
s but I like using A
for links - and they'll be styled like my other anchors.
Third, each menu item has a unique class name. This is so that in the CSS we can identify each menu item individually.
Fourth, every content item is a DIV
, and has the class="hiddendiv"
. However each each content item has a unique id
.
In your CSS, we set all .hiddendiv
elements to display:none;
- that is, we hide them all.
Secondly, for each menu item we have a line of CSS. This means if you add more menu items (ie. and more hidden content), you will have to update your CSS, yes.
Third, the CSS is saying that when .testA
gets focus (.testA:focus
) then the corresponding DIV
, identified by ID (#testA
) should be displayed.
Last, when I just said "the corresponding DIV
", the trick here is the tilde character (~
) - this selector will select a sibling element, and it does not have to be the very next element, that matches the selector which, in this case, is the unique ID value (#testA
).
It is this tilde that makes this solution different than others offered and this lets you simply update some "display panel" with different content, based on clicking one of those links, and you are not as constrained when it comes to where/how you organise your HTML. All you need, though, is to ensure your hidden DIV
s are contained within the same parent element as your clickable links.
Season to taste.
If your aim is to redirect all pages to a single maintenance page (as the title could suggest also this), then use:
RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.php$
RewriteCond %{REMOTE_HOST} !^000\.000\.000\.000
RewriteRule $ /maintenance.php [R=302,L]
Where 000 000 000 000 should be replaced by your ip adress.
Source:
http://www.techiecorner.com/97/redirect-to-maintenance-page-during-upgrade-using-htaccess/
This code works in my case, after a lot of research. You will require to install the request npm package.
var url = "http://api.example.com/api/v1/?param1=1¶m2=2";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
exports.checkApi = function (req, res) {
// do the GET request
request.get({
url: url,
headers: {
"Authorization": auth
}
}, function (error, response, body) {
if(error)
{ console.error("Error while communication with api and ERROR is : " + error);
res.send(error);
}
console.log('body : ', body);
res.send(body);
});
}
If you want to grow the array dynamically, you should use malloc() to dynamically allocate some fixed amount of memory, and then use realloc() whenever you run out. A common technique is to use an exponential growth function such that you allocate some small fixed amount and then make the array grow by duplicating the allocated amount.
Some example code would be:
size = 64; i = 0;
x = malloc(sizeof(words)*size); /* enough space for 64 words */
while (read_words()) {
if (++i > size) {
size *= 2;
x = realloc(sizeof(words) * size);
}
}
/* done with x */
free(x);
Try this instead:
print_r($sth->errorInfo());
Add this before your prepare:
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.
Your class:
class name {
public:
string first;
string last;
name() { } //Default constructor.
name(string a, string b){
first = a;
last = b;
}
};
Has an explicit constructor that requires two string parameters. Classes with no constructor written explicitly get default constructors taking no parameters. Adding the explicit one stopped the compiler from generating that default constructor for you.
So, if you wish to make an array of uninitialized objects, add a default constructor to your class so the compiler knows how to create them without providing those two string parameters - see the commented line above.
The other answers show you how to make a list of data.frames when you already have a bunch of data.frames, e.g., d1
, d2
, .... Having sequentially named data frames is a problem, and putting them in a list is a good fix, but best practice is to avoid having a bunch of data.frames not in a list in the first place.
The other answers give plenty of detail of how to assign data frames to list elements, access them, etc. We'll cover that a little here too, but the Main Point is to say don't wait until you have a bunch of a data.frames
to add them to a list. Start with the list.
The rest of the this answer will cover some common cases where you might be tempted to create sequential variables, and show you how to go straight to lists. If you're new to lists in R, you might want to also read What's the difference between [[
and [
in accessing elements of a list?.
Don't ever create d1
d2
d3
, ..., dn
in the first place. Create a list d
with n
elements.
This is done pretty easily when reading in files. Maybe you've got files data1.csv, data2.csv, ...
in a directory. Your goal is a list of data.frames called mydata
. The first thing you need is a vector with all the file names. You can construct this with paste (e.g., my_files = paste0("data", 1:5, ".csv")
), but it's probably easier to use list.files
to grab all the appropriate files: my_files <- list.files(pattern = "\\.csv$")
. You can use regular expressions to match the files, read more about regular expressions in other questions if you need help there. This way you can grab all CSV files even if they don't follow a nice naming scheme. Or you can use a fancier regex pattern if you need to pick certain CSV files out from a bunch of them.
At this point, most R beginners will use a for
loop, and there's nothing wrong with that, it works just fine.
my_data <- list()
for (i in seq_along(my_files)) {
my_data[[i]] <- read.csv(file = my_files[i])
}
A more R-like way to do it is with lapply
, which is a shortcut for the above
my_data <- lapply(my_files, read.csv)
Of course, substitute other data import function for read.csv
as appropriate. readr::read_csv
or data.table::fread
will be faster, or you may also need a different function for a different file type.
Either way, it's handy to name the list elements to match the files
names(my_data) <- gsub("\\.csv$", "", my_files)
# or, if you prefer the consistent syntax of stringr
names(my_data) <- stringr::str_replace(my_files, pattern = ".csv", replacement = "")
This is super-easy, the base function split()
does it for you. You can split by a column (or columns) of the data, or by anything else you want
mt_list = split(mtcars, f = mtcars$cyl)
# This gives a list of three data frames, one for each value of cyl
This is also a nice way to break a data frame into pieces for cross-validation. Maybe you want to split mtcars
into training, test, and validation pieces.
groups = sample(c("train", "test", "validate"),
size = nrow(mtcars), replace = TRUE)
mt_split = split(mtcars, f = groups)
# and mt_split has appropriate names already!
Maybe you're simulating data, something like this:
my_sim_data = data.frame(x = rnorm(50), y = rnorm(50))
But who does only one simulation? You want to do this 100 times, 1000 times, more! But you don't want 10,000 data frames in your workspace. Use replicate
and put them in a list:
sim_list = replicate(n = 10,
expr = {data.frame(x = rnorm(50), y = rnorm(50))},
simplify = F)
In this case especially, you should also consider whether you really need separate data frames, or would a single data frame with a "group" column work just as well? Using data.table
or dplyr
it's quite easy to do things "by group" to a data frame.
If they're an odd assortment (which is unusual), you can simply assign them:
mylist <- list()
mylist[[1]] <- mtcars
mylist[[2]] <- data.frame(a = rnorm(50), b = runif(50))
...
If you have data frames named in a pattern, e.g., df1
, df2
, df3
, and you want them in a list, you can get
them if you can write a regular expression to match the names. Something like
df_list = mget(ls(pattern = "df[0-9]"))
# this would match any object with "df" followed by a digit in its name
# you can test what objects will be got by just running the
ls(pattern = "df[0-9]")
# part and adjusting the pattern until it gets the right objects.
Generally, mget
is used to get multiple objects and return them in a named list. Its counterpart get
is used to get a single object and return it (not in a list).
A common task is combining a list of data frames into one big data frame. If you want to stack them on top of each other, you would use rbind
for a pair of them, but for a list of data frames here are three good choices:
# base option - slower but not extra dependencies
big_data = do.call(what = rbind, args = df_list)
# data table and dplyr have nice functions for this that
# - are much faster
# - add id columns to identify the source
# - fill in missing values if some data frames have more columns than others
# see their help pages for details
big_data = data.table::rbindlist(df_list)
big_data = dplyr::bind_rows(df_list)
(Similarly using cbind
or dplyr::bind_cols
for columns.)
To merge (join) a list of data frames, you can see these answers. Often, the idea is to use Reduce
with merge
(or some other joining function) to get them together.
Put similar data in lists because you want to do similar things to each data frame, and functions like lapply
, sapply
do.call
, the purrr
package, and the old plyr
l*ply
functions make it easy to do that. Examples of people easily doing things with lists are all over SO.
Even if you use a lowly for loop, it's much easier to loop over the elements of a list than it is to construct variable names with paste
and access the objects with get
. Easier to debug, too.
Think of scalability. If you really only need three variables, it's fine to use d1
, d2
, d3
. But then if it turns out you really need 6, that's a lot more typing. And next time, when you need 10 or 20, you find yourself copying and pasting lines of code, maybe using find/replace to change d14
to d15
, and you're thinking this isn't how programming should be. If you use a list, the difference between 3 cases, 30 cases, and 300 cases is at most one line of code---no change at all if your number of cases is automatically detected by, e.g., how many .csv
files are in your directory.
You can name the elements of a list, in case you want to use something other than numeric indices to access your data frames (and you can use both, this isn't an XOR choice).
Overall, using lists will lead you to write cleaner, easier-to-read code, which will result in fewer bugs and less confusion.
class Program
{
Variable va = new Variable();
static void Main(string[] args)
{
va.name = "Stackoverflow";
}
}
Ansible has a version_compare
filter since 1.6.
You can do something like below in when
conditional:
when: ansible_distribution_version | version_compare('12.04', '>=')
This will give you support for major & minor versions comparisons and you can compare versions using operators like:
<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
You can find more information about this here: Ansible - Version comparison filters
Otherwise if you have really simple case you can use what @ProfHase85 suggested
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
This is how I rotate 360 in right direction.
[UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionRepeat|UIViewAnimationOptionCurveLinear
animations:^{
[imageIndView setTransform:CGAffineTransformRotate([imageIndView transform], M_PI-0.00001f)];
} completion:nil];
I know this is well answered, but if you're interested, I wrote a library that makes executing commands much easier.
Check it out here: https://github.com/twitchax/Sheller.
This may not actually answer the question (How to keep whitespaces in XML) but it may solve the underlying problem more gracefully.
Instead of relying only on the XML resources, concatenate using format strings. So first remove the whitespaces
<string name="Toast_Memory_GameWon_part1">you found ALL PAIRS ! on</string>
<string name="Toast_Memory_GameWon_part2">flips !</string>
And then build your string differently:
String message_all_pairs_found =
String.format(Locale.getDefault(),
"%s %d %s",
getString(R.string.Toast_Memory_GameWon_part1),
total_flips,
getString(R.string.Toast_Memory_GameWon_part2);
Toast.makeText(this, message_all_pairs_found, 1000).show();
I think C in fact supports pass by reference.
Most languages require syntactic sugar to pass by reference instead of value. (C++ for example requires & in the parameter declaration).
C also requires syntactic sugar for this. It's * in the parameter type declaration and & on the argument. So * and & is the C syntax for pass by reference.
One could now argue that real pass by reference should only require syntax on the parameter declaration, not on the argument side.
But now comes C# which does support by reference passing and requires syntactic sugar on both parameter and argument sides.
The argument that C has no by-ref passing cause the the syntactic elements to express it exhibit the underlying technical implementation is not an argument at all, as this applies more or less to all implementations.
The only remaining argument is that passing by ref in C is not a monolithic feature but combines two existing features. (Take ref of argument by &, expect ref to type by *.) C# for example does require two syntactic elements, but they can't be used without each other.
This is obviously a dangerous argument, cause lots of other features in languages are composed of other features. (like string support in C++)
I love the Swift language, but using NSAttributedString
with a Swift Range
that is not compatible with NSRange
has made my head hurt for too long. So to get around all that garbage I devised the following methods to return an NSMutableAttributedString
with the highlighted words set with your color.
This does not work for emojis. Modify if you must.
extension String {
func getRanges(of string: String) -> [NSRange] {
var ranges:[NSRange] = []
if contains(string) {
let words = self.components(separatedBy: " ")
var position:Int = 0
for word in words {
if word.lowercased() == string.lowercased() {
let startIndex = position
let endIndex = word.characters.count
let range = NSMakeRange(startIndex, endIndex)
ranges.append(range)
}
position += (word.characters.count + 1) // +1 for space
}
}
return ranges
}
func highlight(_ words: [String], this color: UIColor) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: self)
for word in words {
let ranges = getRanges(of: word)
for range in ranges {
attributedString.addAttributes([NSForegroundColorAttributeName: color], range: range)
}
}
return attributedString
}
}
Usage:
// The strings you're interested in
let string = "The dog ran after the cat"
let words = ["the", "ran"]
// Highlight words and get back attributed string
let attributedString = string.highlight(words, this: .yellow)
// Set attributed string
label.attributedText = attributedString
I am not a big fan of if...else; so I took a simpler approach.
$(document).ready(function(event) {
$('ul.nav.nav-tabs a:first').tab('show'); // Select first tab
$('ul.nav.nav-tabs a[href="'+ window.location.hash+ '"]').tab('show'); // Select tab by name if provided in location hash
$('ul.nav.nav-tabs a[data-toggle="tab"]').on('shown', function (event) { // Update the location hash to current tab
window.location.hash= event.target.hash;
})
});
Doesn't address scrolling to requested hash; but should it?
All you have to do is:
You will be able to see historical attributions (using git blame
) and full history of changes (using git log
) for both files.
Suppose you want to create a copy of file foo
called bar
. In that case the workflow you'd use would look like this:
git mv foo bar
git commit
SAVED=`git rev-parse HEAD`
git reset --hard HEAD^
git mv foo copy
git commit
git merge $SAVED # This will generate conflicts
git commit -a # Trivially resolved like this
git mv copy foo
git commit
After you execute the above commands, you end up with a revision history that looks like this:
( revision history ) ( files )
ORIG_HEAD foo
/ \ / \
SAVED ALTERNATE bar copy
\ / \ /
MERGED bar,copy
| |
RESTORED bar,foo
When you ask Git about the history of foo
, it will:
copy
between MERGED and RESTORED,copy
came from the ALTERNATE parent of MERGED, andfoo
between ORIG_HEAD and ALTERNATE.From there it will dig into the history of foo
.
When you ask Git about the history of bar
, it will:
bar
came from the SAVED parent of MERGED, and foo
between ORIG_HEAD and SAVED.From there it will dig into the history of foo
.
It's that simple. :)
You just need to force Git into a merge situation where you can accept two traceable copies of the file(s), and we do this with a parallel move of the original (which we soon revert).
Other examples here are difficult to remember. At its simplest:
date -r 1305712800
Virtualenv is your friend
Even if you want to add a package to your primary install, it's still best to do it in a virtual environment first, to ensure compatibility with your other packages. However, if you get familiar with virtualenv, you'll probably find there's really no reason to install anything in your base install.
I just put --password
flag into my command and after hitting Enter it asked me for password, which I supplied.
Try this:
function someFunction(site)
{
return site.replace(/\/$/, "");
}
Another alternative, not sure if this applies to your particular problem but to some it may be applicable is to use UnaryOperator
in java.util.function library.
where it returns same type you specify, so you put all your variables in one class and is it as a parameter:
public class FunctionsLibraryUse {
public static void main(String[] args){
UnaryOperator<People> personsBirthday = (p) ->{
System.out.println("it's " + p.getName() + " birthday!");
p.setAge(p.getAge() + 1);
return p;
};
People mel = new People();
mel.setName("mel");
mel.setAge(27);
mel = personsBirthday.apply(mel);
System.out.println("he is now : " + mel.getAge());
}
}
class People{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
So the class you have, in this case Person
, can have numerous instance variables and won't have to change the parameter of your lambda expression.
For those interested, I've written notes on how to use java.util.function library: http://sysdotoutdotprint.com/index.php/2017/04/28/java-util-function-library/
this works for me... try it
// Check #x_x000D_
$( "#x" ).prop( "checked", true );_x000D_
_x000D_
// Uncheck #x_x000D_
$( "#x" ).prop( "checked", false );
_x000D_
Remember that your img is not really a DOM element but a javascript expression.
This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions
In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components
/** @jsx React.DOM */
var Hello = React.createClass({
render: function() {
return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
}
});
React.renderComponent(<Hello name="World" />, document.body);
Try
#include <inttypes.h>
...
printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k);
The z
represents an integer of length same as size_t
, and the PRIu32
macro, defined in the C99 header inttypes.h
, represents an unsigned 32-bit integer.
Why not just use the following simple call (with any exception handling added)?
File.AppendAllText(strFile, "Start Error Log for today")
EDITED ANSWER
This should answer the question fully!
If File.Exists(strFile)
File.AppendAllText(strFile, String.Format("Error Message in Occured at-- {0:dd-MMM-yyyy}{1}", Date.Today, Environment.NewLine))
Else
File.AppendAllText(strFile, "Start Error Log for today{0}Error Message in Occured at-- {1:dd-MMM-yyyy}{0}", Environment.NewLine, Date.Today)
End If
Each class will use its own classloader to load other classes. So if ClassA.class
references ClassB.class
then ClassB
needs to be on the classpath of the classloader of ClassA
, or its parents.
The thread context classloader is the current classloader for the current thread. An object can be created from a class in ClassLoaderC
and then passed to a thread owned by ClassLoaderD
. In this case the object needs to use Thread.currentThread().getContextClassLoader()
directly if it wants to load resources that are not available on its own classloader.
I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.
The full shortcut target is:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"
So I put the following at the start of my script and it seemed to function as expected:
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
Notes:
This is cross-browser and fully responsive:
<iframe
src="https://drive.google.com/file/d/0BxrMaW3xINrsR3h2cWx0OUlwRms/preview"
style="
position: fixed;
top: 0px;
bottom: 0px;
right: 0px;
width: 100%;
border: none;
margin: 0;
padding: 0;
overflow: hidden;
z-index: 999999;
height: 100%;
">
</iframe>
It is impossible to change the format
We have to differentiate between the over the wire format and the browser's presentation format.
The HTML5 date input specification refers to the RFC 3339 specification, which specifies a full-date format equal to: yyyy-mm-dd
. See section 5.6 of the RFC 3339 specification for more details.
This format is used by the value
HTML attribute and DOM property and is the one used when doing an ordinary form submission.
Browsers are unrestricted in how they present a date input. At the time of writing Chrome, Edge, Firefox, and Opera have date support (see here). They all display a date picker and format the text in the input field.
Desktop devices
For Chrome, Firefox, and Opera, the formatting of the input field's text is based on the browser's language setting. For Edge, it is based on the Windows language setting. Sadly, all web browsers ignore the date formatting configured in the operating system. To me this is very strange behaviour, and something to consider when using this input type. For example, Dutch users that have their operating system or browser language set to en-us
will be shown 01/30/2019
instead of the format they are accustomed to: 30-01-2019
.
Internet Explorer 9, 10, and 11 display a text input field with the wire format.
Mobile devices
Specifically for Chrome on Android, the formatting is based on the Android display language. I suspect that the same is true for other browsers, though I've not been able to verify this.
Excel has no way of gathering that attribute with it's built-in functions. If you're willing to use some VB, all your color-related questions are answered here:
http://www.cpearson.com/excel/colors.aspx
Example form the site:
The SumColor function is a color-based analog of both the SUM and SUMIF function. It allows you to specify separate ranges for the range whose color indexes are to be examined and the range of cells whose values are to be summed. If these two ranges are the same, the function sums the cells whose color matches the specified value. For example, the following formula sums the values in B11:B17 whose fill color is red.
=SUMCOLOR(B11:B17,B11:B17,3,FALSE)
A very basic approach is alert(arrayObj.join('\n'))
, which will display each array element in a row.
From the Errata:
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Should be:
ModelState.AddModelErrors(dinner.GetRuleViolations());
From Apple Docs
You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."
Always keep in mind when you want to overcome this error, the default value of indexing and range starts from 0, so if total items is 100 then l[99] and range(99) will give you access up to the last element.
whenever you get this type of error please cross check with items that comes between/middle in range, and insure that their index is not last if you get output then you have made perfect error that mentioned above.
Object oriented style:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
Procedural style:
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
When this is in a python console if you update a module to be able to use it through the console does not help reset, you must use a
import importlib
and
importlib.reload (*module*)
likely to solve your problem
try
<div class="container">
<div class="row">
<div class="col-md-12">header section</div>
</div>
<div class="row fill">
<div class="col-md-4">Navigation</div>
<div class="col-md-8">Content</div>
</div>
</div>
css for .fill class is below
.fill{
width:100%;
height:100%;
min-height:100%;
padding:10px;
color:#efefef;
background: blue;
}
.col-md-12
{
background: red;
}
.col-md-4
{
background: yellow;
height:100%;
min-height:100%;
}
.col-md-8
{
background: green;
height:100%;
min-height:100%;
}
For your reference just look into the fiddle.
Try this:
<style>
#wrapper { position: relative; }
#over_map { position: absolute; top: 10px; left: 10px; z-index: 99; }
</style>
<div id="wrapper">
<div id="google_map">
</div>
<div id="over_map">
</div>
</div>
Prior to Java 6, there is no support of file permission update at Java level. You have to implement your own native method or call Runtime.exec()
to execute OS level command such as chmod.
Starting from Java 6, you can useFile.setReadable()/File.setWritable()/File.setExecutable()
to set file permissions. But it doesn't simulate the POSIX file system which allows to set permission for different users. File.setXXX() only allows to set permission for owner and everyone else.
Starting from Java 7, POSIX file permission is introduced. You can set file permissions like what you have done on *nix systems. The syntax is :
File file = new File("file4.txt");
file.createNewFile();
Set<PosixFilePermission> perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
Files.setPosixFilePermissions(file.toPath(), perms);
This method can only be used on POSIX file system, this means you cannot call it on Windows system.
For details on file permission management, recommend you to read this post.
As stated in one of the comments, this works for Mac (probably for Windows/Linux too):
I WANT TO CONNECT FROM A CONTAINER TO A SERVICE ON THE HOST
The host has a changing IP address (or none if you have no network access). We recommend that you connect to the special DNS name
host.docker.internal
which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.You can also reach the gateway using
gateway.docker.internal
.
Quoted from https://docs.docker.com/docker-for-mac/networking/
This worked for me without using --net=host
.
You can try this
$("#target").prop("selectedIndex", 0);
The documentation reiterates your findings here: https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service
If my memory serves, $stateParams
was introduced later than the original $state.params
, and seems to be a simple helper injector to avoid continuously writing $state.params
.
I doubt there are any best practice guidelines, but context wins out for me. If you simply want access to the params received into the url, then use $stateParams
. If you want to know something more complex about the state itself, use $state
.
SyntaxError: missing ) after argument list
This code produces the error:
<html>
<body>
<script type="text/javascript" src="jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
}
</script>
</body>
</html>
If you run this and look at the error output in firebug, you get this error. The empty function passed into 'ready' is not closed. Fix it like this:
<html>
<body>
<script type="text/javascript" src="jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
}); //<-- notice the right parenthesis and semicolon
</script>
</body>
</html>
And then the Javascript is interpreted correctly.
Differences might not be meaningful in a typical use case, but using the standard DOM functionality
$("#el")[0].outerHTML
is about twice as fast as
$("<div />").append($("#el").clone()).html();
so I would go with:
/*
* Return outerHTML for the first element in a jQuery object,
* or an empty string if the jQuery object is empty;
*/
jQuery.fn.outerHTML = function() {
return (this[0]) ? this[0].outerHTML : '';
};
You can parse all arguments and check if they exist.
file: parse-cli-arguments.js:
module.exports = function(requiredArguments){
var arguments = {};
for (var index = 0; index < process.argv.length; index++) {
var re = new RegExp('--([A-Za-z0-9_]+)=([A/-Za-z0-9_]+)'),
matches = re.exec(process.argv[index]);
if(matches !== null) {
arguments[matches[1]] = matches[2];
}
}
for (var index = 0; index < requiredArguments.length; index++) {
if (arguments[requiredArguments[index]] === undefined) {
throw(requiredArguments[index] + ' not defined. Please add the argument with --' + requiredArguments[index]);
}
}
return arguments;
}
Than just do:
var arguments = require('./parse-cli-arguments')(['foo', 'bar', 'xpto']);
The DateTime::ToString() method has a string formatter that can be used to output datetime in any required format. See DateTime.ToString Method (String) for more information.
valueLink/checkedLink
are deprecated from core React, because it is confusing some users. This answer won't work if you use a recent version of React. But if you like it, you can easily emulate it by creating your own Input
component
What you want to achieve can be much more easily achieved using the 2-way data binding helpers of React.
var Hello = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {input1: 0, input2: 0};
},
render: function() {
var total = this.state.input1 + this.state.input2;
return (
<div>{total}<br/>
<input type="text" valueLink={this.linkState('input1')} />;
<input type="text" valueLink={this.linkState('input2')} />;
</div>
);
}
});
React.renderComponent(<Hello />, document.getElementById('content'));
Easy right?
http://facebook.github.io/react/docs/two-way-binding-helpers.html
You can even implement your own mixin
You can open the DevTools in Chrome with CTRL+I on Windows (or CMD+I Mac), and Firefox with F12, then select the Console
tab), and check the XPath by typing $x("your_xpath_here")
.
This will return an array of matched values. If it is empty, you know there is no match on the page.
Suppose that you have a string like this :
String mDate="2019-09-17T10:56:07.827088"
Now we want to change this String
format separate date and time in Java and Kotlin.
JAVA:
we have a method for extract date :
public String getDate() {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
Date date = dateFormat.parse(mDate);
dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
return dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Return
is this : 09/17/2019
And we have method for extract time :
public String getTime() {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
Date date = dateFormat.parse(mCreatedAt);
dateFormat = new SimpleDateFormat("h:mm a", Locale.US);
return dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Return
is this : 10:56 AM
KOTLIN:
we have a function for extract date :
fun getDate(): String? {
var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
val date = dateFormat.parse(mDate!!)
dateFormat = SimpleDateFormat("MM/dd/yyyy", Locale.US)
return dateFormat.format(date!!)
}
Return
is this : 09/17/2019
And we have method for extract time :
fun getTime(): String {
var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
val time = dateFormat.parse(mDate!!)
dateFormat = SimpleDateFormat("h:mm a", Locale.US)
return dateFormat.format(time!!)
}
Return
is this : 10:56 AM
You could do it with jsoup http://jsoup.org/
Whitelist whitelist = Whitelist.none();
String cleanStr = Jsoup.clean(yourText, whitelist);
public string RemoveSpecial(string evalstr)
{
StringBuilder finalstr = new StringBuilder();
foreach(char c in evalstr){
int charassci = Convert.ToInt16(c);
if (!(charassci >= 33 && charassci <= 47))// special char ???
finalstr.append(c);
}
return finalstr.ToString();
}
You should be able to accomplish this by using the statement $ErrorActionPreference = "Stop"
at the beginning of your scripts.
The default setting of $ErrorActionPreference
is Continue
, which is why you are seeing your scripts keep going after errors occur.
I think you should use the Rails debug options:
logger.debug "Person attributes hash: #{@person.attributes.inspect}"
logger.info "Processing the request..."
logger.fatal "Terminating application, raised unrecoverable error!!!"
https://guides.rubyonrails.org/debugging_rails_applications.html
source URL for image can be a URL on a website like http://www.google.co.il/images/srpr/nav_logo73.png or https://https.openbsd.org/images/tshirt-26_front.gif or if you want to use a local file try this: url("file:///MacintoshHDOriginal/Users/lowri/Desktop/acgnx/image s/images/acgn-site-background-X_07.jpg")
Bootstrap has a way of using media queries to define the different task for different sites. It uses four breakpoints.
we have extra small screen sizes which are less than 576 pixels that small in which I mean it's size from 576 to 768 pixels.
medium screen sizes take up screen size from 768 pixels up to 992 pixels large screen size from 992 pixels up to 1200 pixels.
E.g Small Text
This means that at the small screen between 576px and 768px, center the text For medium screen, change "sm" to "md" and same goes to large "lg"
Even though it has already been answered, I suggest a different approach that makes use of numpy.histogram
. Such function given a sequence it returns the frequency of its elements grouped in bins.
Beware though: it works in this example because numbers are integers. If they where real numbers, then this solution would not apply as nicely.
>>> from numpy import histogram
>>> y = histogram (x, bins=x.max()-1)
>>> y
(array([5, 3, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1]),
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.,
12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22.,
23., 24., 25.]))
For those that might be curious about the ConcreteListTypeConverter that was referenced by Oliver, here is my attempt:
public class ConcreteListTypeConverter<TInterface, TImplementation> : JsonConverter where TImplementation : TInterface
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var res = serializer.Deserialize<List<TImplementation>>(reader);
return res.ConvertAll(x => (TInterface) x);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
I ran across the same issue you did but the above answers did not solve my issue. The only way I was able to resolve it - was to make a class and use specific widths to trigger the wrapping for my specific use case. As an example, I provided a snippet below - but I found you will need to adjust it for the table in question - since I typically use multiple colspans depending on the layout. The reasoning I believe Bootstrap is failing - is because it removes the wrapping constraints to get a full table for the scrollbars. THe colspan must be tripping it up.
<style>
@media (max-width: 768px) { /* use the max to specify at each container level */
.specifictd {
width:360px; /* adjust to desired wrapping */
display:table;
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
}
I hope this helps
I've been using:
new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));
From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):
1.10 Empty Operator -
empty A
The
empty
operator is a prefix operator that can be used to determine if a value is null or empty.To evaluate
empty A
- If
A
isnull
, returntrue
- Otherwise, if
A
is the empty string, then returntrue
- Otherwise, if
A
is an empty array, then returntrue
- Otherwise, if
A
is an emptyMap
, returntrue
- Otherwise, if
A
is an emptyCollection
, returntrue
- Otherwise return
false
So, considering the interfaces, it works on Collection
and Map
only. In your case, I think Collection
is the best option. Or, if it's a Javabean-like object, then Map
. Either way, under the covers, the isEmpty()
method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException
.
Right click the shortcut and select properties. Make sure you are on the "Shortcut" Tab. Select the RUN drop down box and change it to Maximized.
This may assist in launching the program in full screen on the primary monitor.
It's just shorthand for "constructor" - and it's what the constructor is called in IL, too. For example, open up Reflector and look at a type and you'll see members called .ctor
for the various constructors.