I've been using Mercurial in the recommended manner and urge that you be cautious, especially if any of the machines differ. The Dropbox fora are full of complaints of mysterious filename case problems turning up spontaneously. Hg (and I presume Git) won't notice or complain during routine checkins and you'll only hear about the corruption when it complains of a corrupt repo when you try to use it for real. Bad news. Wish I could be more specific about the problem and its workarounds; I'm still trying to dig out from this mess myself.
You can add your own static resource handler (it overwrites the default), e.g.
@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("file:/path/to/my/dropbox/");
}
}
There is some documentation about this in Spring Boot, but it's really just a vanilla Spring MVC feature.
Also since spring boot 1.2 (I think) you can simply set spring.resources.staticLocations
.
Frankly, I can't find a single reason to use MySQL rather than MSSQL. The issue before used to be cost but SQL Server 2005 Express is free and there are lots of web hosting companies which offer full hosting with sql server for less than $5.00 a month.
MSSQL is easier to use and has many features which do not exist in MySQL.
As all the other answers say; it can be almost anything but is usually "JQuery".
However, in ES6 it is a string interpolation operator in a template "literal" eg.
var s = "new" ; // you can put whatever you think appropriate here.
var s2 = `There are so many ${s} ideas these days !!` ; //back-ticks not quotes
console.log(s2) ;
result:
There are so many new ideas these days !!
#include <iostream>
class bar
{
public:
bar()
{
std::cout << "bar() called" << std::endl;
}
~bar()
{
std::cout << "~bar() called" << std::endl;
}
};
class foo
{
public:
foo()
: b(new bar())
{
std::cout << "foo() called" << std::endl;
throw "throw something";
}
~foo()
{
delete b;
std::cout << "~foo() called" << std::endl;
}
private:
bar *b;
};
int main(void)
{
try {
std::cout << "heap: new foo" << std::endl;
foo *f = new foo();
} catch (const char *e) {
std::cout << "heap exception: " << e << std::endl;
}
try {
std::cout << "stack: foo" << std::endl;
foo f;
} catch (const char *e) {
std::cout << "stack exception: " << e << std::endl;
}
return 0;
}
the output:
heap: new foo
bar() called
foo() called
heap exception: throw something
stack: foo
bar() called
foo() called
stack exception: throw something
the destructors are not called, so if a exception need to be thrown in a constructor, a lot of stuff(e.g. clean up?) to do.
$(this).parent().css('z-index',3000);
Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".
I couldn't find mysql socket at all so reinstalled mysql server(all tables and phpmyadmin settings were preserved). Here are the commands:
1) Install
sudo apt-get install mysql-server
2) Follow terminal configuration steps
sudo mysql_secure_installation
3) Check status: (Should return "Active: active (running)")
systemctl status mysql.service
Try this:
<select id="sel">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" value="Change option to 2" onclick="changeOpt()"/>
<script>
function changeOpt(){
document.getElementById("sel").options[1].selected = true;
alert("changed")
}
</script>
You can also use @Captor annotated ArgumentCaptor. For example:
@Mock
List<String> mockedList;
@Captor
ArgumentCaptor<String> argCaptor;
@BeforeTest
public void init() {
//Initialize objects annotated with @Mock, @Captor and @Spy.
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldCallAddMethodTwice() {
mockedList.add("one");
mockedList.add("two");
Mockito.verify(mockedList, times(2)).add(argCaptor.capture());
assertEquals("one", argCaptor.getAllValues().get(0));
assertEquals("two", argCaptor.getAllValues().get(1));
}
NoClassDefFoundError
is a linkage error basically. It occurs when you try and instantiate an object (statically with "new") and it's not found when it was during compilation.
ClassNotFoundException
is more general and is a runtime exception when you try to use a class that doesn't exist. For example, you have a parameter in a function accepts an interface and someone passes in a class that implements that interface but you don't have access to the class. It also covers case of dynamic class loading, such as using loadClass()
or Class.forName()
.
There is two easy way to set the alias.
Using Bash
Open bash terminal and type git command. For instance:
$ git config --global alias.a add
$ git config --global alias.aa 'add .'
$ git config --global alias.cm 'commit -m'
$ git config --global alias.s status
---
---
It will eventually add those aliases on .gitconfig file.
Updating .gitconfig file
Open .gitconfig file located at 'C:\Users\username\.gitconfig' in Windows environment. Then add following lines:
[alias]
a = add
aa = add .
cm = commit -m
gau = add --update
au = add --update
b = branch
---
---
Did you try to do a composer self-update?
composer self-update
or
composer install
All you need to do is run the sp_tables stored procedure. http://msdn.microsoft.com/en-us/library/aa260318(SQL.80).aspx
With numerical types, negating the elements before and after sort seems an option. Speed relative to a single reverse after sort depends on cache, and if reverse is not faster, any difference may well be lost in noise.
When the normType
is NORM_MINMAX
, cv::normalize
normalizes _src
in such a way that the min value of dst
is alpha
and max value of dst
is beta
. cv::normalize
does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).
CV_8UC1
says how many channels dst
has.
The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize
Copy-pasteable code based on Pavlo Neyman's method
RedirectPost(string url, T bodyPayload) and GetPostData() are for those who just want to dump some strongly typed data in the source page and fetch it back in the target one. The data must be serializeable by NewtonSoft Json.NET and you need to reference the library of course.
Just copy-paste into your page(s) or better yet base class for your pages and use it anywhere in you application.
My heart goes out to all of you who still have to use Web Forms in 2019 for whatever reason.
protected void RedirectPost(string url, IEnumerable<KeyValuePair<string,string>> fields)
{
Response.Clear();
const string template =
@"<html>
<body onload='document.forms[""form""].submit()'>
<form name='form' action='{0}' method='post'>
{1}
</form>
</body>
</html>";
var fieldsSection = string.Join(
Environment.NewLine,
fields.Select(x => $"<input type='hidden' name='{HttpUtility.UrlEncode(x.Key)}' value='{HttpUtility.UrlEncode(x.Value)}'>")
);
var html = string.Format(template, HttpUtility.UrlEncode(url), fieldsSection);
Response.Write(html);
Response.End();
}
private const string JsonDataFieldName = "_jsonData";
protected void RedirectPost<T>(string url, T bodyPayload)
{
var json = JsonConvert.SerializeObject(bodyPayload, Formatting.Indented);
//explicit type declaration to prevent recursion
IEnumerable<KeyValuePair<string, string>> postFields = new List<KeyValuePair<string, string>>()
{new KeyValuePair<string, string>(JsonDataFieldName, json)};
RedirectPost(url, postFields);
}
protected T GetPostData<T>() where T: class
{
var urlEncodedFieldData = Request.Params[JsonDataFieldName];
if (string.IsNullOrEmpty(urlEncodedFieldData))
{
return null;// default(T);
}
var fieldData = HttpUtility.UrlDecode(urlEncodedFieldData);
var result = JsonConvert.DeserializeObject<T>(fieldData);
return result;
}
I am running eclipse from Ubuntu. Had this same problem and was able run the program through terminal. So I just moved the existing public static void main(String[] args) {
just below the class declaration (it got automatically formatted by eclipse) and the next launch was successful. Then moved the main method back to where it was before and it worked fine this time.
This is a mix of HTML and code but it's pretty basic, easy to understand and should be fairly simple to decouple to suit your needs I think.
try {
// Find out how many items are in the table
$total = $dbh->query('
SELECT
COUNT(*)
FROM
table
')->fetchColumn();
// How many items to list per page
$limit = 20;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '<a href="?page=1" title="First page">«</a> <a href="?page=' . ($page - 1) . '" title="Previous page">‹</a>' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">›</a> <a href="?page=' . $pages . '" title="Last page">»</a>' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Display the paging information
echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';
// Prepare the paged query
$stmt = $dbh->prepare('
SELECT
*
FROM
table
ORDER BY
name
LIMIT
:limit
OFFSET
:offset
');
// Bind the query params
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
// Do we have any results?
if ($stmt->rowCount() > 0) {
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);
// Display the results
foreach ($iterator as $row) {
echo '<p>', $row['name'], '</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
It's Works
.ts -> pi = 3.1415
.html -> {{ pi | number : '1.0-2' }}
Ouput -> 3.14
https://stackblitz.com/edit/angular-e8g2pt?file=src/app/app.component.html
this works for me!!! thanks!!
You don't want to list all 1000 object in your bucket at a time. A more robust solution will be to fetch a max of 10 objects at a time. You can do this with the withMaxKeys method.
The following code creates an S3 client, fetches 10 or less objects at a time and filters based on a prefix and generates a pre-signed url for the fetched object:
import com.amazonaws.HttpMethod;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import java.net.URL;
import java.util.Date;
/**
* @author shabab
* @since 21 Sep, 2020
*/
public class AwsMain {
static final String ACCESS_KEY = "";
static final String SECRET = "";
static final Regions BUCKET_REGION = Regions.DEFAULT_REGION;
static final String BUCKET_NAME = "";
public static void main(String[] args) {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET);
try {
final AmazonS3 s3Client = AmazonS3ClientBuilder
.standard()
.withRegion(BUCKET_REGION)
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(BUCKET_NAME).withMaxKeys(10);
ListObjectsV2Result result;
do {
result = s3Client.listObjectsV2(req);
result.getObjectSummaries()
.stream()
.filter(s3ObjectSummary -> {
return s3ObjectSummary.getKey().contains("Market-subscriptions/")
&& !s3ObjectSummary.getKey().equals("Market-subscriptions/");
})
.forEach(s3ObjectSummary -> {
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(BUCKET_NAME, s3ObjectSummary.getKey())
.withMethod(HttpMethod.GET)
.withExpiration(getExpirationDate());
URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
System.out.println(s3ObjectSummary.getKey() + " Pre-Signed URL: " + url.toString());
});
String token = result.getNextContinuationToken();
req.setContinuationToken(token);
} while (result.isTruncated());
} catch (SdkClientException e) {
e.printStackTrace();
}
}
private static Date getExpirationDate() {
Date expiration = new java.util.Date();
long expTimeMillis = expiration.getTime();
expTimeMillis += 1000 * 60 * 60;
expiration.setTime(expTimeMillis);
return expiration;
}
}
Note: the solution in this and other answers involves disabling safety measures that are there to fix arbitrary code execution vulnerabilities. See for instance this ghostscript-related and this ubuntu-related announcement. Only go forward with these solutions if the input to
convert
comes from a trusted source.
I use ImageMagick in php (v.7.1) to slice PDF file to images.
First I got errors like:
Exception type: ImagickException
Exception message: not authorized ..... @ error/constitute.c/ReadImage/412
After some changes in /etc/ImageMagick-6/policy.xml
I start getting erroes like:
Exception type: ImagickException
Exception message: unable to create temporary file ..... Permission denied @ error/pdf.c/ReadPDFImage/465
My fix:
In file /etc/ImageMagick-6/policy.xml
(or /etc/ImageMagick/policy.xml
)
comment line
<!-- <policy domain="coder" rights="none" pattern="MVG" /> -->
change line
<policy domain="coder" rights="none" pattern="PDF" />
to
<policy domain="coder" rights="read|write" pattern="PDF" />
add line
<policy domain="coder" rights="read|write" pattern="LABEL" />
Then restart your web server (nginx, apache).
If you want the placeholder text to be red you need to target it specifically in CSS.
Write:
input::placeholder{
color: #f00;
}
I had the same problem and any solution worked for me.
The cause was I am using allowRequest to accept or reject the connection using a token I pass in a query parameter.
I have a typo in the query parameter name in the client side, so the connection was always rejected, but the browser complained about cors...
As soon as I fixed the typo, it started working as expected, and I don't need to use anything extra, the global express cors settings is enough.
So, if anything is working for you, and you are using allowRequest, check that this function is working properly, because the errors it throws shows up as cors errors in the browser. Unless you add there the cors headers manually when you want to reject the connection, I guess.
Let me give the churlish "unofficial" explanation.
POSIX is a set of standards which attempts to distinguish "UNIX" and UNIX-like systems from those which are incompatible with them. It was created by the U.S. government for procurement purposes. The idea was that the U.S. federal procurements needed a way to legally specify the requirements for various sorts of bids and contracts in a way that could be used to exclude systems to which a given existing code base or programming staff would NOT be portable.
Since POSIX was written post facto ... to describe a loosely similar set of competing systems ... it was NOT written in a way that could be implemented.
So, for example, Microsoft's NT was written with enough POSIX conformance to qualify for some bids ... even though the POSIX subsystem was essentially useless in terms of practical portability and compatibility with UNIX systems.
Various other standards for UNIX have been written over the decades. Things like the SPEC1170 (specified eleven hundred and seventy function calls which had to be implemented compatibly) and various incarnations of the SUS (Single UNIX Specification).
For the most part these "standards" have been inadequate to any practical technical application. They most exist for argumentation, legal wrangling and other dysfunctional reasons.
CGRect buttonFrame = CGRectMake( 10, 80, 100, 30 );
UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
[button setTitle: @"My Button" forState: UIControlStateNormal];
[button addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];
[button setTitleColor: [UIColor redColor] forState: UIControlStateNormal];
[view addSubview:button];
I use [NSException raise:format:]
as follows:
[NSException raise:@"Invalid foo value" format:@"foo of %d is invalid", foo];
For the benefit of others, I though I'd include what I did.
Since you cannot get Visual Studio (2010 in my case) to ignore the LNK4204 warnings, my approach was to give it what it wanted: the pdb files. As I was using open source libraries in my case, I have the code building the pdb files already.
BUT, the default is to name all of the PDF files the same thing: vc100.pdb in my case. As you need a .pdb for each and every .lib, this creates a problem, especially if you are using something like ImageMagik, which creates about 20 static .lib files. You cannot have 20 lib files in one directory (which your application's linker references to link in the libraries from) and have all the 20 .pdb files called the same thing.
My solution was to go and rebuild my static library files, and configure VS2010 to name the .pdb file with respect to the PROJECT. This way, each .lib gets a similarly named .pdb, and you can put all of the LIBs and PDBs in one directory for your project to use.
So for the "Debug" configuraton, I edited:
Properties->Configuration Properties -> C/C++ -> Output Files -> Program Database File Name from
$(IntDir)vc$(PlatformToolsetVersion).pdb
to be the following value:
$(OutDir)vc$(PlatformToolsetVersion)D$(ProjectName).pdb
Now rather than somewhere in the intermediate directory, the .pdb files are written to the output directory, where the .lib files are also being written, AND most importantly, they are named with a suffix of D+project name. This means each library project produduces a project .lib and a project specific .pdb.
I'm now able to copy all of my release .lib files, my debug .lib files and the debug .pdb files into one place on my development system, and the project that uses that 3rd party library in debug mode, has the pdb files it needs in debug mode.
You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:
-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
k NUMBER:= 0;
BEGIN
FOR i IN 1..10 LOOP
k:= k+1;
dbms_output.put_line(i||' '||k);
END LOOP;
END;
/
-- Cursor FOR loop --
set serveroutput on
DECLARE
CURSOR c1 IS SELECT * FROM scott.emp;
i NUMBER:= 0;
BEGIN
FOR e_rec IN c1 LOOP
i:= i+1;
dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
END LOOP;
END;
/
-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
FROM dual
CONNECT BY LEVEL <= 10
/
A solution in Java 8:
Date startOfToday = Date.from(ZonedDateTime.now().with(LocalTime.MIN).toInstant());
var data = 'id='+ id & 'name='+ name;
The ampersand needs to be quoted as well:
var data = 'id='+ id + '&name='+ name;
My problem was something like that:
FileStream ms = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
but instead of using path I should use File.FullName... I don't know if it's going to help anyone else, just passing my own experience with this erro given!
If you are checking if an instance of a custom class or struct is contained in an array, you'll need to implement the Equatable protocol before you can use .contains(myObject).
For example:
struct Cup: Equatable {
let filled:Bool
}
static func ==(lhs:Cup, rhs:Cup) -> Bool { // Implement Equatable
return lhs.filled == rhs.filled
}
then you can do:
cupArray.contains(myCup)
Tip: The == override should be at the global level, not within your class/struct
I ran into a similar error
"from: can't read /var/mail/django.test.utils"
when trying to run a command
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
in the tutorial at https://docs.djangoproject.com/en/1.8/intro/tutorial05/
after reading the answer by Tamás I realized I was not trying this command in the python shell but in the termnial (this can happen to those new to linux)
solution was to first enter in the python shell with the command python and when you get these >>> then run any python commands
No, it is not valid but you can trick your inner form position on the HTML
with a help of CSS
and jQuery
usage. First create some container div inside your parent form and then in any other place on the page the div with your child (inner) form:
<form action="a">
<input.../>
<div class="row" id="other_form_container"></div>
<input.../>
</form>
....
<div class="row" id="other_form">
<form action="b">
<input.../>
<input.../>
<input.../>
</form>
</div>
Give your container div some stable heaght
<style>
#other_form_container {
height:90px;
position:relative;
}
</style>
Thank trick the "other_form" position relatively to container div.
<script>
$(document).ready(function() {
var pos = $("#other_form_container").position();
$("#other_form").css({
position: "absolute",
top: pos.top - 40,
left: pos.left + 7,
width: 500,
}).show();
});
</script>
P.S.: You'll have to play with numbers to make it look nice.
Mongodb and Mongoose are two different drivers to interact with MongoDB database.
Mongoose : object data modeling (ODM) library that provides a rigorous modeling environment for your data. Used to interact with MongoDB, it makes life easier by providing convenience in managing data.
Mongodb: native driver in Node.js to interact with MongoDB.
In my case the problem was not having a proper javabin folder in the PATH variable.
Open the PATH variable and make sure it points to a proper JRE bin folder.
The answer to this question is, use nuget to obtain JSON.NET then use this inside your JsonResult
method:
JsonConvert.SerializeObject(/* JSON OBJECT TO SEND TO VIEW */);
inside your view simple do this in javascript
:
JSON.parse(/* Converted JSON object */)
If it is an ajax call:
var request = $.ajax({ url: "@Url.Action("SomeAjaxAction", "SomeController")", dataType: "json"});
request.done(function (data, result) { var safe = JSON.parse(data); var date = new Date(safe.date); });
Once JSON.parse
has been called, you can put the JSON date into a new Date
instance because JsonConvert
creates a proper ISO time instance
The value
attribute on submit
-type <input>
elements controls the text displayed.
<input type="submit" class="like" value="Like" />
org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.
Summary:
You opened up more than the allowed limit of connections to the database. You ran something like this: Connection conn = myconn.Open();
inside of a loop, and forgot to run conn.close();
. Just because your class is destroyed and garbage collected does not release the connection to the database. The quickest fix to this is to make sure you have the following code with whatever class that creates a connection:
protected void finalize() throws Throwable
{
try { your_connection.close(); }
catch (SQLException e) {
e.printStackTrace();
}
super.finalize();
}
Place that code in any class where you create a Connection. Then when your class is garbage collected, your connection will be released.
Run this SQL to see postgresql max connections allowed:
show max_connections;
The default is 100. PostgreSQL on good hardware can support a few hundred connections at a time. If you want to have thousands, you should consider using connection pooling software to reduce the connection overhead.
Take a look at exactly who/what/when/where is holding open your connections:
SELECT * FROM pg_stat_activity;
The number of connections currently used is:
SELECT COUNT(*) from pg_stat_activity;
Debugging strategy
You could give different usernames/passwords to the programs that might not be releasing the connections to find out which one it is, and then look in pg_stat_activity to find out which one is not cleaning up after itself.
Do a full exception stack trace when the connections could not be created and follow the code back up to where you create a new Connection
, make sure every code line where you create a connection ends with a connection.close();
How to set the max_connections higher:
max_connections in the postgresql.conf sets the maximum number of concurrent connections to the database server.
SHOW config_file;
/var/lib/pgsql/data/postgresql.conf
max_connections=100
.What's the maximum max_connections?
Use this query:
select min_val, max_val from pg_settings where name='max_connections';
I get the value 8388607
, in theory that's the most you are allowed to have, but then a runaway process can eat up thousands of connections, and surprise, your database is unresponsive until reboot. If you had a sensible max_connections like 100. The offending program would be denied a new connection.
// Earlier in your code
mysql_connect();
set_a_flag_that_db_is_connected();
// Later....
if (flag_is_set())
mysql_connect(....);
When you use re.split
and the split pattern contains capturing groups, the groups are retained in the output. If you don't want this, use a non-capturing group instead.
Are you missing a using directive for System.Linq
?
The error shows that com.bd.service.ArticleService
is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:
<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>
Alternatively, if you want to include all subpackages in com.bd
:
<context:component-scan base-package="com.bd">
<context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>
As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan
annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration
.
@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {
@Autowired
ArticleService articleService;
...
}
You might find this Spring in depth section on Autowiring useful.
Although the answer that Gunter posted was correct, it is not different than what I already had posted. The problem was not the ENV
directive, but the subsequent instruction RUN export $PATH
There's no need to export the environment variables, once you have declared them via ENV
in your Dockerfile.
As soon as the RUN export ...
lines were removed, my image was built successfully
This while else statement should only execute the else code when the condition is false, this means it will always execute it. But, there is a catch, when you use the break keyword within the while loop, the else statement should not execute.
The code that satisfies does condition is only:
boolean entered = false;
while (condition) {
entered = true; // Set it to true stright away
// While loop code
// If you want to break out of this loop
if (condition) {
entered = false;
break;
}
} if (!entered) {
// else code
}
E-mail addresses are very difficult to verify correctly with a mere regex. Here is a pretty scary regex that supposedly implements RFC822, chapter 6, the specification of valid e-mail addresses.
Not really an answer, but maybe related to what you're trying to accomplish.
Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view.
Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc).
Django 1.4.1
Python 2.7.3
#Model
class MonthEnd(models.Model):
report = models.FileField(db_index=True, upload_to='not_used')
import csv
from os.path import join
#build and store the file
def write_csv():
path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv')
f = open(path, "w+b")
#wipe the existing content
f.truncate()
csv_writer = csv.writer(f)
csv_writer.writerow(('col1'))
for num in range(3):
csv_writer.writerow((num, ))
month_end_file = MonthEnd()
month_end_file.report.name = path
month_end_file.save()
from my_app.models import MonthEnd
#serve it up as a download
def get_report(request):
month_end = MonthEnd.objects.get(file_criteria=criteria)
response = HttpResponse(month_end.report, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=report.csv'
return response
If you want to delete file first close all the connections and streams. after that delete the file.
rebellion's answer above won't actually work, because to CSS, 'background-position' is actually shorthand for 'background-position-x' and 'background-position-y' so the correct version of his code would be:
$(document).ready(function(){
$('#submenu li').hover(function(){
$('#carousel').css('background-position-x', newValueX);
$('#carousel').css('background-position-y', newValue);
}, function(){
$('#carousel').css('background-position-x', oldValueX);
$('#carousel').css('background-position-y', oldValueY);
});
});
It took about 4 hours of banging my head against it to come to that aggravating realization.
try
block will execute a sensitive code which can throw exceptionscatch
block will be used whenever an exception (of the type caught) is thrown in the try blockfinally
block is called in every case after the try/catch blocks. Even if the exception isn't caught or if your previous blocks break the execution flow.throw
keyword will allow you to throw an exception (which will break the execution flow and can be caught in a catch
block).throws
keyword in the method prototype is used to specify that your method might throw exceptions of the specified type. It's useful when you have checked exception (exception that you have to handle) that you don't want to catch in your current method.Resources :
On another note, you should really accept some answers. If anyone encounter the same problems as you and find your questions, he/she will be happy to directly see the right answer to the question.
My solution might not be the cleanest but it should work with no problems.
The logic is simply to create a static variable to store your data on the Service
and update your view each second on your Activity
.
Let's say that you have a String
on your Service
that you want to send it to a TextView
on your Activity
. It should look like this
Your Service:
public class TestService extends Service {
public static String myString = "";
// Do some stuff with myString
Your Activty:
public class TestActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
update();
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
update();
}
});
}
} catch (InterruptedException ignored) {}
}
};
t.start();
startService(new Intent(this, TestService.class));
}
private void update() {
// update your interface here
tv.setText(TestService.myString);
}
}
In C, static has two meanings, depending on scope of its use. In the global scope, when an object is declared at the file level, it means that that object is only visible within that file.
At any other scope it declares an object that will retain its value between the different times that the particular scope is entered. For example, if an int is delcared within a procedure:
void procedure(void)
{
static int i = 0;
i++;
}
the value of 'i' is initialized to zero on the first call to the procedure, and the value is retained each subsequent time the procedure is called. if 'i' were printed it would output a sequence of 0, 1, 2, 3, ...
componentWillReceiveProps
is being deprecated because using it "often leads to bugs and inconsistencies".
If something changes from the outside, consider resetting the child component entirely with key
.
Providing a key
prop to the child component makes sure that whenever the value of key
changes from the outside, this component is re-rendered. E.g.,
<EmailInput
defaultEmail={this.props.user.email}
key={this.props.user.id}
/>
On its performance:
While this may sound slow, the performance difference is usually insignificant. Using a key can even be faster if the components have heavy logic that runs on updates since diffing gets bypassed for that subtree.
You can do it as you do in vi, for example to yank lines from 3020 to the end, execute this command (write the block to a file):
:3020,$ w /tmp/yank
And to write this block in another line/file, go to the desired position and execute next command (insert file written before):
:r /tmp/yank
(Reminder: don't forget to remove file: /tmp/yank)
The answers here are worth a try, but you should also review your code. Specifically have a read of Polyfun's answer here: How to get rid of deadlock in a SQL Server 2005 and C# application?
It explains the concurrency issue, and how the usage of "with (updlock)" in your queries might correct your deadlock situation - depending really on exactly what your code is doing. If your code does follow this pattern, this is likely a better fix to make, before resorting to dirty reads, etc.
For the Record:
Note that in PHP the switch statement is considered a looping structure for the purposes of continue.
@kris answer is helpful for me anyone want it in Objective-C.
Here is the code
-(void)viewDidLayoutSubviews{
[super viewDidLayoutSubviews];
[self sizeHeaderToFit];
}
-(void)sizeHeaderToFit{
UIView *headerView = self.tableView.tableHeaderView;
[headerView setNeedsLayout];
[headerView layoutIfNeeded];
CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
CGRect frame = headerView.frame;
frame.size.height = height;
headerView.frame = frame;
self.tableView.tableHeaderView = headerView;
}
scala> lazy val lazyEight = {
| println("I am lazy !")
| 8
| }
lazyEight: Int = <lazy>
scala> lazyEight
I am lazy !
res1: Int = 8
One way is to associating unique properties with your file while creation.
properties = "{ \
key='somekey' and \
value='somevalue'
}"
then create a query.
query = "title = " + "\'" + title + "\'" + \
AND + "mimeType = " + "\'" + mimeType + "\'" + \
AND + "trashed = false" + \
AND + "properties has " + properties
All the file properties(title, etc) already known to you can go here + properties.
You either haven't selected a CPU/ABI target in the dropdown below the target, or you haven't installed a system image. Open your SDK manager and ensure that you've installed ARM EABI v7a System Image
under the Android 4.2 section.
As described in Cast Functions and Operators:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Therefore, you should use:
SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT
updated() should be what you're looking for:
Called after a data change causes the virtual DOM to be re-rendered and patched.
The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.
Upper div use higher z-index and lower div use lower z-index then use absolute/fixed/relative position
This code is tested. You can check it again.
@ECHO OFF
CLS
SETLOCAL
::Get a number of lines contain "File(s)" to a mytmp file in TEMP location.
DIR /S /-C | FIND "bytes" | FIND /V "free" | FIND /C "File(s)" >%TEMP%\mytmp
SET /P nline=<%TEMP%\mytmp
SET nline=[%nline%]
::-------------------------------------
DIR /S /-C | FIND "bytes" | FIND /V "free" | FIND /N "File(s)" | FIND "%nline%" >%TEMP%\mytmp1
SET /P mainline=<%TEMP%\mytmp1
CALL SET size=%mainline:~29,15%
ECHO %size%
ENDLOCAL
PAUSE
The Python Magic library provides the functionality you need.
You can install the library with pip install python-magic
and use it as follows:
>>> import magic
>>> magic.from_file('iceland.jpg')
'JPEG image data, JFIF standard 1.01'
>>> magic.from_file('iceland.jpg', mime=True)
'image/jpeg'
>>> magic.from_file('greenland.png')
'PNG image data, 600 x 1000, 8-bit colormap, non-interlaced'
>>> magic.from_file('greenland.png', mime=True)
'image/png'
The Python code in this case is calling to libmagic beneath the hood, which is the same library used by the *NIX file
command. Thus, this does the same thing as the subprocess/shell-based answers, but without that overhead.
You can use set
with the /p
argument:
SET /P variable=[promptString]
The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
So, simply use something like
set /p Input=Enter some text:
Later you can use that variable as argument to a command:
myCommand %Input%
Be careful though, that if your input might contain spaces it's probably a good idea to quote it:
myCommand "%Input%"
I got the following error using Docker 19.03.8 on CentOS 7:
COPY failed: stat /var/lib/docker/tmp/docker-builderXXXXXXX/abc.txt: no such file or directory
The solution for me was to build from Docker file with docker build .
instead of docker build - < Dockerfile
.
Here is an option. This is just for the x coordinates.
var div1Pos = $("#div1").offset();
var div1X = div1Pos.left;
$('#div2').css({left: div1X});
After some investigation I have come to the conclusion that the following approach seems the best.
some/subpackage/Util.groovy
@GrabResolver(name = 'nexus', root = 'https://local-nexus-server:8443/repository/maven-public', m2Compatible = true)
@Grab('com.google.errorprone:error_prone_annotations:2.1.3')
@Grab('com.google.guava:guava:23.0')
@GrabExclude('com.google.errorprone:error_prone_annotations')
import com.google.common.base.Strings
class Util {
void msg(int a, String b, Map c) {
println 'Message printed by msg method inside Util.groovy'
println "Print 5 asterisks using the Guava dependency ${Strings.repeat("*", 5)}"
println "Arguments are a=$a, b=$b, c=$c"
}
}
example.groovy
#!/usr/bin/env groovy
Class clazz = new GroovyClassLoader().parseClass("${new File(getClass().protectionDomain.codeSource.location.path).parent}/some/subpackage/Util.groovy" as File)
GroovyObject u = clazz.newInstance()
u.msg(1, 'b', [a: 'b', c: 'd'])
In order to run the example.groovy
script, add it to your system path and type from any directory:
example.groovy
The script prints:
Message printed by msg method inside Util.groovy
Print 5 asterisks using the Guava dependency *****
Arguments are a=1, b=b, c=[a:b, c:d]
The above example was tested in the following environment: Groovy Version: 2.4.13 JVM: 1.8.0_151 Vendor: Oracle Corporation OS: Linux
The example demonstrates the following:
Util
class inside a groovy script.Util
class calling the Guava
third party library by including it as a Grape
dependency (@Grab('com.google.guava:guava:23.0')
).Util
class can reside in a subdirectory.Util
class.Additional comments/suggestions:
new Util()
, but most importantly it would have to be placed in a file named anything but Util.groovy. Refer to Scripts versus classes for more details about the differences between groovy scripts and groovy classes."${new File(getClass().protectionDomain.codeSource.location.path).parent}/some/subpackage/Util.groovy"
instead of "some/subpackage/Util.groovy"
. This will guarantee that the Util.groovy
file will always be found in relation to the groovy script's location (example.groovy
) and not the current working directory. For example, using "some/subpackage/Util.groovy"
would result in searching at WORK_DIR/some/subpackage/Util.groovy
.myScript.groovy
is a script name, and MyClass.groovy
is a class name. Naming my-script.groovy
will result in runtime errors in certain scenarios because the resulting class will not have a valid Java class name.<div style="height: 100px;"> </div>
OR
<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px; }
For those still experimenting, npm install react-html-parser
When I installed it it had 123628 weekly downloads.
import ReactHtmlParser from 'react-html-parser'
<div>{ReactHtmlParser(htmlString)}</div>
Try this method. It's very easy:
public static boolean setSsidAndPassword(Context context, String ssid, String ssidPassword) {
try {
WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
Method getConfigMethod = wifiManager.getClass().getMethod("getWifiApConfiguration");
WifiConfiguration wifiConfig = (WifiConfiguration) getConfigMethod.invoke(wifiManager);
wifiConfig.SSID = ssid;
wifiConfig.preSharedKey = ssidPassword;
Method setConfigMethod = wifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
setConfigMethod.invoke(wifiManager, wifiConfig);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
function pad_2(number)
{
return (number < 10 ? '0' : '') + number;
}
function hours(date)
{
var hours = date.getHours();
if(hours > 12)
return hours - 12; // Substract 12 hours when 13:00 and more
return hours;
}
function am_pm(date)
{
if(date.getHours()==0 && date.getMinutes()==0 && date.getSeconds()==0)
return ''; // No AM for MidNight
if(date.getHours()==12 && date.getMinutes()==0 && date.getSeconds()==0)
return ''; // No PM for Noon
if(date.getHours()<12)
return ' AM';
return ' PM';
}
function date_format(date)
{
return pad_2(date.getDate()) + '/' +
pad_2(date.getMonth()+1) + '/' +
(date.getFullYear() + ' ').substring(2) +
pad_2(hours(date)) + ':' +
pad_2(date.getMinutes()) +
am_pm(date);
}
Code corrected as of Sep 3 '12 at 10:11
If it helps anyone, I found that the problem was I already had an android:onClick event in my layout file (which I inflated for the ListView rows). This was superseding the onItemClick event.
A good library available named log4j for Java.
This will provide numerous feature. Go through link and you will find your solution.
You may try this:-
Scanner scan = new Scanner(System.in);
System.out.println("Type a sentence and press enter.");
String input = scan.nextLine();
String strippedInput = input.replaceAll("\\W", "");
System.out.println("Your string: " + strippedInput);
[^\w]
matches a non-word character, so the above regular expression will match and remove all non-word characters.
The actual reason is that, in a new repo (git init), there is no branch (no master
, no branch at all, zero branches)
So when you are pushing for the first time to an empty upstream repo (generally a bare one), that upstream repo has no branch of the same name.
And:
matching
' (push all the branches of the same name, creating them if they don't exist), simple
' (push only the current branch, and only if it has a similarly named remote tracking branch on upstream, since git 1.7.11)In both cases, since the upstream empty repo has no branch:
That means your local first push has no idea:
So you need at least to do a:
git push origin master
But if you do only that, you:
master
branch on the upstream (now non-empty repo): good.master
' needs to be pushed to upstream (origin
) 'master
' (upstream branch): bad.That is why it is recommended, for the first push, to do a:
git push -u origin master
That will record origin/master
as a remote tracking branch, and will enable the next push to automatically push master
to origin/master
.
git checkout master
git push
And that will work too with push policies 'current
' or 'upstream
'.
In each case, after the initial git push -u origin master
, a simple git push will be enough to continue pushing master to the right upstream branch.
To get an object from a xib file programatically you can use: [[NSBundle mainBundle] loadNibNamed:@"MyXibName" owner:self options:nil]
which returns an array of the top level objects in the xib.
So, you could do something like this:
UIView *rootView = [[[NSBundle mainBundle] loadNibNamed:@"MyRootView" owner:self options:nil] objectAtIndex:0];
UIView *containerView = [[[NSBundle mainBundle] loadNibNamed:@"MyContainerView" owner:self options:nil] lastObject];
[rootView addSubview:containerView];
[self.view addSubview:rootView];
There's also php2xmi. You have to do a bit of manual work, but it generates all the classes, so all you have to do is to drag them into a classdiagram in Umbrello.
Otherwise, generating a diagram with the use of reflection and graphviz, is fairly simple. I have a snippet over here, that you can use as a starting point.
While this can't be achieved with CSS/HTML alone, it can be achieved with JavaScript (without need of a library):
var textareas = document.getElementsByTagName('textarea');
for (i=0;i<textareas.length;i++){
// you can omit the 'if' if you want to style the parent node regardless of its
// element type
if (textareas[i].parentNode.tagName.toString().toLowerCase() == 'div') {
textareas[i].onfocus = function(){
this.parentNode.style.borderStyle = 'solid';
}
textareas[i].onblur = function(){
this.parentNode.style.borderStyle = 'dashed';
}
}
}
Incidentally, with a library, such as jQuery, the above could be condensed down to:
$('textarea').focus(
function(){
$(this).parent('div').css('border-style','solid');
}).blur(
function(){
$(this).parent('div').css('border-style','dashed');
});
References:
If you need a simple list of size 1:
List<String> strings = new ArrayList<String>(Collections.singletonList("A"));
If you need a list of several objects:
List<String> strings = new ArrayList<String>();
Collections.addAll(strings,"A","B","C","D");
In dashboard you can see running word press version at "At a Glance"
I find this to be the best solution for me. Let the Date object calculate it for you.
var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);
Setting day parameter to 0 means one day less than first day of the month which is last day of the previous month.
<br>
worked for me.
Right-click folder -> TortiseGit -> Clean up.. -> click OK
None of the above solutions worked for me but this one did.
Strange that no-one mentioned the Cross Site scripting prevention benefit of .text()
over .html()
(Although others have just mentioned that .text()
escapes the data).
It's always recommended to use .text()
when you want to update data in DOM which is just data / text for the user to see.
.html()
should be mostly used to get the HTML content within a div.
When using angular.copy, instead of updating the reference, a new object is created and assigned to the destination(if a destination is provided). But there's more. There's this cool thing that happens after a deep copy.
Say you have a factory service which has methods which updates factory variables.
angular.module('test').factory('TestService', [function () {
var o = {
shallow: [0,1], // initial value(for demonstration)
deep: [0,2] // initial value(for demonstration)
};
o.shallowCopy = function () {
o.shallow = [1,2,3]
}
o.deepCopy = function () {
angular.copy([4,5,6], o.deep);
}
return o;
}]);
and a controller which uses this service,
angular.module('test').controller('Ctrl', ['TestService', function (TestService) {
var shallow = TestService.shallow;
var deep = TestService.deep;
console.log('****Printing initial values');
console.log(shallow);
console.log(deep);
TestService.shallowCopy();
TestService.deepCopy();
console.log('****Printing values after service method execution');
console.log(shallow);
console.log(deep);
console.log('****Printing service variables directly');
console.log(TestService.shallow);
console.log(TestService.deep);
}]);
When the above program is run the output will be as follows,
****Printing initial values
[0,1]
[0,2]
****Printing values after service method execution
[0,1]
[4,5,6]
****Printing service variables directly
[1,2,3]
[4,5,6]
Thus the cool thing about using angular copy is that, the references of the destination are reflected with the change of values, without having to re-assign the values manually, again.
Here's how I would do it.
I think it's about as efficient as it reasonably can be. It optimizes the single character case and avoids creating multiple substrings for each subsequence removed.
Note that the corner case of passing an empty string to trim is handled (some of the other answers would go into an infinite loop).
/** Trim all occurrences of the string <code>rmvval</code> from the left and right of <code>src</code>. Note that <code>rmvval</code> constitutes an entire string which must match using <code>String.startsWith</code> and <code>String.endsWith</code>. */
static public String trim(String src, String rmvval) {
return trim(src,rmvval,rmvval,true);
}
/** Trim all occurrences of the string <code>lftval</code> from the left and <code>rgtval</code> from the right of <code>src</code>. Note that the values to remove constitute strings which must match using <code>String.startsWith</code> and <code>String.endsWith</code>. */
static public String trim(String src, String lftval, String rgtval, boolean igncas) {
int str=0,end=src.length();
if(lftval.length()==1) { // optimize for common use - trimming a single character from left
char chr=lftval.charAt(0);
while(str<end && src.charAt(str)==chr) { str++; }
}
else if(lftval.length()>1) { // handle repeated removal of a specific character sequence from left
int vallen=lftval.length(),newstr;
while((newstr=(str+vallen))<=end && src.regionMatches(igncas,str,lftval,0,vallen)) { str=newstr; }
}
if(rgtval.length()==1) { // optimize for common use - trimming a single character from right
char chr=rgtval.charAt(0);
while(str<end && src.charAt(end-1)==chr) { end--; }
}
else if(rgtval.length()>1) { // handle repeated removal of a specific character sequence from right
int vallen=rgtval.length(),newend;
while(str<=(newend=(end-vallen)) && src.regionMatches(igncas,newend,rgtval,0,vallen)) { end=newend; }
}
if(str!=0 || end!=src.length()) {
if(str<end) { src=src.substring(str,end); } // str is inclusive, end is exclusive
else { src=""; }
}
return src;
}
there are 3 ways to do it.
1.Add the following line on style.xml to change entire application
<item name="android:textAllCaps">false</item>
2.Use
android:textAllCaps="false"
in your layout-v21
mButton.setTransformationMethod(null);
android:textAllCaps="false"
regards
You could solve this many ways. One that is pretty simple to understand is to just use a loop.
def comp(list1, list2):
for val in list1:
if val in list2:
return True
return False
A more compact way you can do it is to use map
and reduce
:
reduce(lambda v1,v2: v1 or v2, map(lambda v: v in list2, list1))
Even better, the reduce
can be replaced with any
:
any(map(lambda v: v in list2, list1))
You could also use sets:
len(set(list1).intersection(list2)) > 0
I have not compiled this as it is meant for a proof of concept. This is how I have implemented a Progress bar for database access in the past. This example shows access to a SQLite database using the System.Data.SQLite module
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;
using(SQLiteConnection cnn = new SQLiteConnection("Data Source=MyDatabase.db"))
{
cnn.Open();
int TotalQuerySize = GetQueryCount("Query", cnn); // This needs to be implemented and is not shown in example
using (SQLiteCommand cmd = cnn.CreateCommand())
{
cmd.CommandText = "Query is here";
using(SQLiteDataReader reader = cmd.ExecuteReader())
{
int i = 0;
while(reader.Read())
{
// Access the database data using the reader[]. Each .Read() provides the next Row
if(worker.WorkerReportsProgress) worker.ReportProgress(++i * 100/ TotalQuerySize);
}
}
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Notify someone that the database access is finished. Do stuff to clean up if needed
// This could be a good time to hide, clear or do somthign to the progress bar
}
public void AcessMySQLiteDatabase()
{
BackgroundWorker backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.DoWork +=
new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(
backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged +=
new ProgressChangedEventHandler(
backgroundWorker1_ProgressChanged);
}
This might be a more niche answer but if you are on windows and MYSQL Workbench you can just select the table you want and click Export/Import in the Result grid. This will give you multiple format options including .json
You might take advantage of ruby's "splat" or flattening syntax.
This makes overgrown when
clauses — you have about 10 values to test per branch if I understand correctly — a little more readable in my opinion. Additionally, you can modify the values to test at runtime. For example:
honda = ['honda', 'acura', 'civic', 'element', 'fit', ...]
toyota = ['toyota', 'lexus', 'tercel', 'rx', 'yaris', ...]
...
if include_concept_cars
honda += ['ev-ster', 'concept c', 'concept s', ...]
...
end
case car
when *toyota
# Do something for Toyota cars
when *honda
# Do something for Honda cars
...
end
Another common approach would be to use a hash as a dispatch table, with keys for each value of car
and values that are some callable object encapsulating the code you wish to execute.
So, not directly related but this is the first question that appears when you try to find how to terminate a process running from a specific folder using Python.
It also answers the question in a way(even though it is an old one with lots of answers).
While creating a faster way to scrape some government sites for data I had an issue where if any of the processes in the pool got stuck they would be skipped but still take up memory from my computer. This is the solution I reached for killing them, if anyone knows a better way to do it please let me know!
import pandas as pd
import wmi
from re import escape
import os
def kill_process(kill_path, execs):
f = wmi.WMI()
esc = escape(kill_path)
temp = {'id':[], 'path':[], 'name':[]}
for process in f.Win32_Process():
temp['id'].append(process.ProcessId)
temp['path'].append(process.ExecutablePath)
temp['name'].append(process.Name)
temp = pd.DataFrame(temp)
temp = temp.dropna(subset=['path']).reset_index().drop(columns=['index'])
temp = temp.loc[temp['path'].str.contains(esc)].loc[temp.name.isin(execs)].reset_index().drop(columns=['index'])
[os.system('taskkill /PID {} /f'.format(t)) for t in temp['id']]
$("#myTable").offset().top;
This will give you the computed offset (relative to document) of any object.
It comes down to whether the feature is used by one person or if others are working off of it.
You can force the push after the rebase if it's just you:
git push origin feature -f
However, if others are working on it, you should merge and not rebase off of master.
git merge master
git push origin feature
This will ensure that you have a common history with the people you are collaborating with.
On a different level, you should not be doing back-merges. What you are doing is polluting your feature branch's history with other commits that don't belong to the feature, making subsequent work with that branch more difficult - rebasing or not.
This is my article on the subject called branch per feature.
Hope this helps.
ROOT default app is usually Tomcat Manager - which can be useful so I felt like keeping it around.
So the way i made my app ROOT and kept TCmgr was like this.
renamed ROOT to something else
mv ROOT TCmgr
then created a symbolic link whereby ROOT points to the app i want to make the default.
ln -s <your app> ROOT
worked for me and seemed the easiest approach.
As you can probably see from the multitude of different (and often mutually exclusive) answers, it depends on who you ask. In some arenas, the terms are synonymous. Or they might each refer to two similar concepts:
In either case, the intention is to allow the program to not be blocked waiting for a slow process to complete - how the program is expected to respond is the only real difference. Which term refers to which also changes from programmer to programmer, language to language, or platform to platform. Or the terms may refer to completely different concepts (such as the use of synchronous/asynchronous in relation to thread programming).
Sorry, but I don't believe there is a single right answer that is globally true.
Wildcards can only be used in the ServerAlias
rather than the ServerName
. Something which had me stumped.
For your use case, the following should suffice
<VirtualHost *:80>
ServerAlias *.example.com
VirtualDocumentRoot /var/www/%1/
</VirtualHost>
optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));
You can also used below code
<html>
<head>
<style>
.labelClass{
float: left;
width: 113px;
}
</style>
</head>
<body>
<form action="yourclassName.jsp">
<span class="labelClass">First name: </span><input type="text" name="fname"><br>
<span class="labelClass">Last name: </span><input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
If you simply want to print a newline in the console you can use ´\n´ for newlines.
If you want to break text in swing components you can use html:
String s = "<html>first line<br />second line</html>";
.length
is a field, containing the capacity (NOT the number of elements the array contains at the moment) of arrays.
length()
is a method used by Strings (amongst others), it returns the number of chars in the String; with Strings, capacity and number of containing elements (chars) have the same value.
size()
is a method implemented by all members of Collection (lists, sets, stacks,...). It returns the number of elements (NOT the capacity; some collections even don´t have a defined capacity) the collection contains.You can use jquery-disablescroll to solve the problem:
$window.disablescroll();
$window.disablescroll("undo");
Supports handleWheel
, handleScrollbar
, handleKeys
and scrollEventKeys
.
You can use
public static final String HELLO = "hello";
if you have many string constants, you can use external property file / simple "constant holder" class
From the documentation on http://curl.haxx.se/docs/httpscripting.html :
HTTP Authentication
curl --user name:password http://www.example.com
Put a file to a HTTP server with curl:
curl --upload-file uploadfile http://www.example.com/receive.cgi
Send post data with curl:
curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi
You can get this using Emulation (Ctrl + 8) Document mode (10,9,8,7,5), Browser Profile (Desktop, Windows Phone)
to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.
essentially it will look something like this
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$
Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?
It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.
So do the regular expression and validate the structure but forget about validating against a service.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(string.length > 0)
{
NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];
BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
return stringIsValid;
}
return YES;
}
An alternative solution is to use a wrapper for the String
, for instances this:
public class StringResponse {
private String response;
public StringResponse(String response) {
this.response = response;
}
public String getResponse() {
return response;
}
}
Then return this in your controller's methods:
ResponseEntity<StringResponse>
Recently I was working on a gradle plugin for Android that makes generating versionCode and versionName automatically. there are lots of customization. here you can find more info about it https://github.com/moallemi/gradle-advanced-build-version
Fast-forward almost 9 years since this was first asked, and in the world of .NET Core and .NET Standard, it seems the most common options we have for URL-encoding are WebUtility.UrlEncode (under System.Net
) and Uri.EscapeDataString. Judging by the most popular answer here and elsewhere, Uri.EscapeDataString appears to be preferable. But is it? I did some analysis to understand the differences and here's what I came up with:
WebUtility.UrlEncode
encodes space as +
; Uri.EscapeDataString
encodes it as %20
.Uri.EscapeDataString
percent-encodes !
, (
, )
, and *
; WebUtility.UrlEncode
does not.WebUtility.UrlEncode
percent-encodes ~
; Uri.EscapeDataString
does not.Uri.EscapeDataString
throws a UriFormatException
on strings longer than 65,520 characters; WebUtility.UrlEncode
does not. (A more common problem than you might think, particularly when dealing with URL-encoded form data.)Uri.EscapeDataString
throws a UriFormatException
on the high surrogate characters; WebUtility.UrlEncode
does not. (That's a UTF-16 thing, probably a lot less common.)For URL-encoding purposes, characters fit into one of 3 categories: unreserved (legal in a URL); reserved (legal in but has special meaning, so you might want to encode it); and everything else (must always be encoded).
According to the RFC, the reserved characters are: :/?#[]@!$&'()*+,;=
And the unreserved characters are alphanumeric and -._~
Uri.EscapeDataString clearly defines its mission: %-encode all reserved and illegal characters. WebUtility.UrlEncode is more ambiguous in both definition and implementation. Oddly, it encodes some reserved characters but not others (why parentheses and not brackets??), and stranger still it encodes that innocently unreserved ~
character.
Therefore, I concur with the popular advice - use Uri.EscapeDataString when possible, and understand that reserved characters like /
and ?
will get encoded. If you need to deal with potentially large strings, particularly with URL-encoded form content, you'll need to either fall back on WebUtility.UrlEncode and accept its quirks, or otherwise work around the problem.
EDIT: I've attempted to rectify ALL of the quirks mentioned above in Flurl via the Url.Encode
, Url.EncodeIllegalCharacters
, and Url.Decode
static methods. These are in the core package (which is tiny and doesn't include all the HTTP stuff), or feel free to rip them from the source. I welcome any comments/feedback you have on these.
Here's the code I used to discover which characters are encoded differently:
var diffs =
from i in Enumerable.Range(0, char.MaxValue + 1)
let c = (char)i
where !char.IsHighSurrogate(c)
let diff = new {
Original = c,
UrlEncode = WebUtility.UrlEncode(c.ToString()),
EscapeDataString = Uri.EscapeDataString(c.ToString()),
}
where diff.UrlEncode != diff.EscapeDataString
select diff;
foreach (var diff in diffs)
Console.WriteLine($"{diff.Original}\t{diff.UrlEncode}\t{diff.EscapeDataString}");
The Loop Invariant Property is a condition that holds for every step of a loops execution (ie. for loops, while loops, etc.)
This is essential to a Loop Invariant Proof, where one is able to show that an algorithm executes correctly if at every step of its execution this loop invariant property holds.
For an algorithm to be correct, the Loop Invariant must hold at:
Initialization (the beginning)
Maintenance (each step after)
Termination (when it's finished)
This is used to evaluate a bunch of things, but the best example is greedy algorithms for weighted graph traversal. For a greedy algorithm to yield an optimal solution (a path across the graph), it must reach connect all nodes in the lowest weight path possible.
Thus, the loop invariant property is that the path taken has the least weight. At the beginning we haven't added any edges, so this property is true (it isn't false, in this case). At each step, we follow the lowest weight edge (the greedy step), so again we're taking the lowest weight path. At the end, we have found the lowest weighted path, so our property is also true.
If an algorithm doesn't do this, we can prove that it isn't optimal.
I am not sure whether anyone faced issues with getting the whole string "test from adb". Using the escape character in front of the space worked for me.
adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test\ from\ adb" -n com.whereismywifeserver/.IntentReceiver
Browsers and OS's determine the style of the select boxes in most cases, and it's next to impossible to alter them with CSS alone. You'll have to look into replacement methods. The main trick is to apply appearance: none
which lets you override some of the styling.
My favourite method is this one:
http://cssdeck.com/item/265/styling-select-box-with-css3
It doesn't replace the OS select menu UI element so all the problems related to doing that are non-existant (not being able to break out of the browser window with a long list being the main one).
Good luck :)
south
plugin:Like T.T suggested in his answer, my previous answer was for south
migration plugin, when Django hasn't any schema migration features.
Now (works in Django 1.9+):
You can try this!
python manage.py makemigrations python manage.py migrate --run-syncdb
south
migrations pluginAs I can see you done it all in wrong order, to fix it up your should complete this checklist (I assume you can't delete sqlite3 database file to start over):
- Grab any SQLite GUI tool (i.e. http://sqliteadmin.orbmu2k.de/)
- Change your model definition to match database definition (best approach is to comment new fields)
- Delete
migrations
folder in your model- Delete rows in
south_migrationhistory
table whereapp_name
match your application name (probablyhomework
)- Invoke:
./manage.py schemamigration <app_name> --initial
- Create tables by
./manage.py migrate <app_name> --fake
(--fake
will skip SQL execute because table already exists in your database)- Make changes to your app's model
- Invoke
./manage.py schemamigration <app_name> --auto
- Then apply changes to database:
./manage.py migrate <app_name>
Steps 7,8,9 repeat whenever your model needs any changes.
Easy Solution
Got to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager ->Expand SQL Server Network Configuration-> Protocol ->Enable TCP/IP Right box
Double Click on TCP/IP and go to IP Adresses Tap and Put port 1433 under TCP port.
My Solution:
I am using QuickHeal Antivirus and by following these steps it worked for me.
Step #1 Go to Firewall Protection
Step #2 Select Advance Settings
Step #3 Find "Public" under Network Profile column and turn "File & Printer Sharing option "ON"
The simple question to your answer is already answered a lot of times:
/*
LINES I WANT COMMENTED
LINES I WANT COMMENTED
LINES I WANT COMMENTED
*/
From your question it sounds like you want to comment out a lot of code?? I would advise to use a repository(git/github) to manage your files instead of commenting out lines.
I found great tutorial on the web about some workaround. It is simple and efficient, I used it in several projects with REST urls styles approach:
http://www.kuligowski.pl/java/rest-style-urls-and-url-mapping-for-static-content-apache-tomcat,5
I've also had the same issue ( Website body background rendering a right white margin in iPhone Safari ) and found that adding the background image to the <html>
tag fixed the problem.
Before
body {background:url('images/back.jpg');}
After
html, body {background:url('images/back.jpg');}
Define state attributes. Add universal handleChange event handler. Add name param to input tag for mapping.
this.state = { stateAttrName:"" }
handleChange=(event)=>{
this.setState({[event.target.name]:event.target.value });
}
<input className="form-control" name="stateAttrName" value=
{this.state.stateAttrName} onChange={this.handleChange}/>
You can setup a custom error page for every location block in your nginx.conf, or a global error page for the site as a whole.
To redirect to a simple 404 not found page for a specific location:
location /my_blog {
error_page 404 /blog_article_not_found.html;
}
A site wide 404 page:
server {
listen 80;
error_page 404 /website_page_not_found.html;
...
You can append standard error codes together to have a single page for several types of errors:
location /my_blog {
error_page 500 502 503 504 /server_error.html
}
To redirect to a totally different server, assuming you had an upstream server named server2 defined in your http section:
upstream server2 {
server 10.0.0.1:80;
}
server {
location /my_blog {
error_page 404 @try_server2;
}
location @try_server2 {
proxy_pass http://server2;
}
The manual can give you more details, or you can search google for the terms nginx.conf and error_page for real life examples on the web.
If you want to remove the back button item title in iOS11, you can try it!
@implementation UIView (PrivateBackButton)
+ (void)initialize {
if ([NSProcessInfo processInfo].operatingSystemVersion.majorVersion < 11.0) return;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[NSObject hookInstanceMethodForClass:[self class] originalMethod:@selector(layoutSubviews) newMethod:@selector(mc_layoutSubviews)];
});
}
- (void)mc_layoutSubviews {
[self mc_layoutSubviews];
[self updateiOS11LaterUI];
}
- (void)updateiOS11LaterUI {
if ([NSProcessInfo processInfo].operatingSystemVersion.majorVersion < 11.0) return;
if (![self isKindOfClass:NSClassFromString(@"_UIBackButtonContainerView")]) return;
[self removeAllSubviews];
[self.superview mas_remakeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(@44);
}];
}
@end
I'll second Real World Haskell. After visiting the #stackoverflow IRC Channel (irc.freenode.net) As of now I have spoke to two authors, one on Reddit and one on the #haskell channel on the same server as the SO channel and they have been nothing but helpful in my quest to learn Haskell. It's the first time I would highly recommend a book on programming to anyone.
You can't follow the cursor with a DIV
, but you can draw a DIV
when moving the cursor!
$(document).on('mousemove', function(e){
$('#your_div_id').css({
left: e.pageX,
top: e.pageY
});
});
That div must be off the float, so position: absolute
should be set.
You are using a local path. Is that really what you want? If it is, you need to use the file:///
prefix:
file:///H:/media/css/static/img/sprites/buttons-v3-10.png
obviously, this will work only on your local computer.
Also, in many modern browsers, this works only if the page itself is also on a local file path. Addressing local files from remote (http://
, https://
) pages has been widely disabled due to security reasons.
It is worth noting that if changing default_socket_timeout on the fly, it might be useful to restore its value after your file_get_contents call:
$default_socket_timeout = ini_get('default_socket_timeout');
....
ini_set('default_socket_timeout', 10);
file_get_contents($url);
...
ini_set('default_socket_timeout', $default_socket_timeout);
In linux shell, many commands accept multiple parameters and therefore could be used with wild cards. So, for example if you want to move all files from folder A to folder B, you write:
mv A/* B
If you want to move all files with a certain "look" to it, you could do like this:
mv A/*.txt B
Which copies all files that are blablabla.txt to folder B
Star (*) can substitute any number of characters or letters while ? can substitute one. For example if you have many files in the shape file_number.ext and you want to move only the ones that have two digit numbers, you could use a command like this:
mv A/file_??.ext B
Or more complicated examples:
mv A/fi*_??.e* B
For files that look like fi<-something->_<-two characters->.e<-something->
Unlike many commands in shell that require -R to (for example) copy or remove subfolders, mv does that itself.
Remember that mv overwrites without asking (unless the files being overwritten are read only or you don't have permission) so make sure you don't lose anything in the process.
For your future information, if you have subfolders that you want to copy, you could use the -R option, saying you want to do the command recursively. So it would look something like this:
cp A/* B -R
By the way, all I said works with rm (remove, delete) and cp (copy) too and beware, because once you delete, there is no turning back! Avoid commands like rm * -R
unless you are sure what you are doing.
First thing first. set the column in which you are working in by clicking on format cells->number-> date and then format e.g Jan-16 representing Jan, 1, 2016. and then apply either of the formulas above.
From Docker documentation:
docker export
does not export the contents of volumes associated with the container. If a volume is mounted on top of an existing directory in the container,docker export
will export the contents of the underlying directory, not the contents of the volume. Refer to Backup, restore, or migrate data volumes in the user guide for examples on exporting data in a volume.
Sounds like you just need to install MySQLi.
If you think you've done that and still have a problem, please post your operating system and anything else that might help diagnose it further.
You don't need an IIF() at all here. The comparisons return true or false anyway.
Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.
=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0
But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:
=Sum(
IIF(
Fields!OpeningStock.Value=0 AND
Fields!GrossDispatched.Value=0 AND
Fields!TransferOutToMW.Value=0 AND
Fields!TransferOutToDW.Value=0 AND
Fields!TransferOutToOW.Value=0 AND
Fields!NetDispatched.Value=0 AND
Fields!QtySold.Value=0 AND
Fields!StockAdjustment.Value=0 AND
Fields!ClosingStock.Value=0,
0,
1
)
) = 0
This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.
Here are the steps I used to manually install python3 for anyone else who wants to do it as it's not super straight forward. EDIT: It's almost certainly easier to use the yum package manager (see other answers).
Note, you'll probably want to do sudo yum groupinstall 'Development Tools'
before doing this otherwise pip won't install.
wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz
tar zxvf Python-3.4.2.tgz
cd Python-3.4.2
sudo yum install gcc
./configure --prefix=/opt/python3
make
sudo yum install openssl-devel
sudo make install
sudo ln -s /opt/python3/bin/python3 /usr/bin/python3
python3 (should start the interpreter if it's worked (quit() to exit)
You don't need an array to do it.
var ItemNode = this.state.data.map(function(itemData) {
return (
<ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
);
});
This should work fine:
Dim result As DialogResult = MessageBox.Show("message", "caption", MessageBoxButtons.YesNoCancel)
If result = DialogResult.Cancel Then
MessageBox.Show("Cancel pressed")
ElseIf result = DialogResult.No Then
MessageBox.Show("No pressed")
ElseIf result = DialogResult.Yes Then
MessageBox.Show("Yes pressed")
End If
Decompyle++ (pycdc) appears to work for a range of python versions: https://github.com/zrax/pycdc
For example:
git clone https://github.com/zrax/pycdc
cd pycdc
make
./bin/pycdc Example.pyc > Example.py
There's a couple of other tricks that Postgres offers for string matching (if that happens to be your DB):
ILIKE, which is a case insensitive LIKE match:
select * from people where name ilike 'JOHN'
Matches:
And if you want to get really mad you can use regular expressions:
select * from people where name ~ 'John.*'
Matches:
for replace all (') in your string, use
.replace(/\'/g,"''")
example:
sample = "St. Mary's and St. John's";
escapedSample = sample.replace(/\'/g,"''")
In essence its job is very similar to IEnumerable<T>
- to represent a queryable data source - the difference being that the various LINQ methods (on Queryable
) can be more specific, to build the query using Expression
trees rather than delegates (which is what Enumerable
uses).
The expression trees can be inspected by your chosen LINQ provider and turned into an actual query - although that is a black art in itself.
This is really down to the ElementType
, Expression
and Provider
- but in reality you rarely need to care about this as a user. Only a LINQ implementer needs to know the gory details.
Re comments; I'm not quite sure what you want by way of example, but consider LINQ-to-SQL; the central object here is a DataContext
, which represents our database-wrapper. This typically has a property per table (for example, Customers
), and a table implements IQueryable<Customer>
. But we don't use that much directly; consider:
using(var ctx = new MyDataContext()) {
var qry = from cust in ctx.Customers
where cust.Region == "North"
select new { cust.Id, cust.Name };
foreach(var row in qry) {
Console.WriteLine("{0}: {1}", row.Id, row.Name);
}
}
this becomes (by the C# compiler):
var qry = ctx.Customers.Where(cust => cust.Region == "North")
.Select(cust => new { cust.Id, cust.Name });
which is again interpreted (by the C# compiler) as:
var qry = Queryable.Select(
Queryable.Where(
ctx.Customers,
cust => cust.Region == "North"),
cust => new { cust.Id, cust.Name });
Importantly, the static methods on Queryable
take expression trees, which - rather than regular IL, get compiled to an object model. For example - just looking at the "Where", this gives us something comparable to:
var cust = Expression.Parameter(typeof(Customer), "cust");
var lambda = Expression.Lambda<Func<Customer,bool>>(
Expression.Equal(
Expression.Property(cust, "Region"),
Expression.Constant("North")
), cust);
... Queryable.Where(ctx.Customers, lambda) ...
Didn't the compiler do a lot for us? This object model can be torn apart, inspected for what it means, and put back together again by the TSQL generator - giving something like:
SELECT c.Id, c.Name
FROM [dbo].[Customer] c
WHERE c.Region = 'North'
(the string might end up as a parameter; I can't remember)
None of this would be possible if we had just used a delegate. And this is the point of Queryable
/ IQueryable<T>
: it provides the entry-point for using expression trees.
All this is very complex, so it is a good job that the compiler makes it nice and easy for us.
For more information, look at "C# in Depth" or "LINQ in Action", both of which provide coverage of these topics.
You should rather use GROUP BY UNIX_TIMESTAMP(time_stamp) DIV 300
instead of round(../300) because of the rounding I found that some records are counted into two grouped result sets.
ant-contrib is evil; write a custom ant task.
ant-contrib is evil because it tries to convert ant from a declarative style to an imperative style. But xml makes a crap programming language.
By contrast a custom ant task allows you to write in a real language (Java), with a real IDE, where you can write unit tests to make sure you have the behavior you want, and then make a clean declaration in your build script about the behavior you want.
This rant only matters if you care about writing maintainable ant scripts. If you don't care about maintainability by all means do whatever works. :)
Jtf
This may be too simplistic of an answer (I am still new here), but what I have done in the past to remedy this situation is figured out the percentage of the screen I would like the image to take up. For example, there is one webpage I am working on where the logo must take up 30% of the screen size to look best. I played around and finally tried this code and it has worked for me thus far:
img {
width:30%;
height:auto;
}
That being said, this will change all of your images to be 30% of the screen size at all times. To get around this issue, simply make this a class and apply it to the image that you desire to be at 30% directly. Here is an example of the code I wrote to accomplish this on the aforementioned site:
the CSS portion:
.logo {
position:absolute;
right:25%;
top:0px;
width:30%;
height:auto;
}
the HTML portion:
<img src="logo_001_002.png" class="logo">
Alternatively, you could place ever image you hope to automatically resize into a div of its own and use the class tag option on each div (creating now class tags whenever needed), but I feel like that would cause a lot of extra work eventually. But, if the site calls for it: the site calls for it.
Hopefully this helps. Have a great day!
If, while using the mysql_upgrade -u root -p --force
command You get this error:
Could not create the upgrade info file '/var/lib/mysql/mysql_upgrade_info' in the MySQL Servers datadir, errno: 13
just add the sudo
before the command. That worked for me, and I solved my problem. So, it's: sudo mysql_upgrade -u root -p --force
:)
Cast works where the actual instance of the list is an ArrayList
. If it is, say, a Vector
(which is another extension of List
) it will throw a ClassCastException.
The error when changing the definition of your HashMap is due to the elements later being processed, and that process expects a method that is defined only in ArrayList
. The exception tells you that it did not found the method it was looking for.
Create a new ArrayList
with the contents of the old one.
new ArrayList<String>(myList);
This provides a named variable to work with:
foreach my $line ( <STDIN> ) {
chomp( $line );
print "$line\n";
}
To read a file, pipe it in like this:
program.pl < inputfile
If your img folder is inside your theme folder, just follow the example below:
<img src="<?php echo get_theme_file_uri(); ?>/img/yourimagename.jpg" class="story-img" alt="your alt text">
use
~/.bash_profile
or
~/.MacOSX/environment.plist
(see Runtime Configuration Guidelines)
Declare it as a decimal
which uses the int
variable and divide this by 100
int number = 700
decimal correctNumber = (decimal)number / 100;
Edit: Bala was faster with his reaction
Add below line to your .gitignore
*/node_modules/*
This will ignore all node_modules in your current directory as well as subdirectory.
I think, this is the simplest technique to beautify the json data,
String indented = (new JSONObject(Response)).toString(4);
where Response is a String.
Simply pass the 4(indentSpaces) in toString()
method.
Note: It works fine in the android without any library. But in java you have to use the org.json library.
I had same issue but it turned out that it was because I created two different map API keys with same SHA-1 fingerprint with nearly similar package name com.bla.bla
and the other com.bla.bla.something
.
This will get you the list
select * from information_schema.columns
where table_name='table1' and column_name like 'a%'
If you want to use that to construct a query, you could do something like this:
declare @sql nvarchar(max)
set @sql = 'select '
select @sql = @sql + '[' + column_name +'],'
from information_schema.columns
where table_name='table1' and column_name like 'a%'
set @sql = left(@sql,len(@sql)-1) -- remove trailing comma
set @sql = @sql + ' from table1'
exec sp_executesql @sql
Note that the above is written for SQL Server.
xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c
should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).
For reference about the arguments: http://ss64.com/nt/xcopy.html
There is a round
available in the Foundation
library (it's actually in Darwin
, but Foundation
imports Darwin
and most of the time you'll want to use Foundation
instead of using Darwin
directly).
import Foundation
users = round(users)
Running your code in a playground and then calling:
print(round(users))
Outputs:
15.0
round()
always rounds up when the decimal place is >= .5
and down when it's < .5
(standard rounding). You can use floor()
to force rounding down, and ceil()
to force rounding up.
If you need to round to a specific place, then you multiply by pow(10.0, number of places)
, round
, and then divide by pow(10, number of places)
:
Round to 2 decimal places:
let numberOfPlaces = 2.0
let multiplier = pow(10.0, numberOfPlaces)
let num = 10.12345
let rounded = round(num * multiplier) / multiplier
print(rounded)
Outputs:
10.12
Note: Due to the way floating point math works, rounded
may not always be perfectly accurate. It's best to think of it more of an approximation of rounding. If you're doing this for display purposes, it's better to use string formatting to format the number rather than using math to round it.
You could make it like this:
<script type="text/javascript">
function myFunction(thisElement)
{
document.getElementByName(thisElement)[0];
}
</script>
<input type="text" name="txtInput1" onBlur="myFunction(this.name)"/>
This catches the loopback(::1) as well and ipv6 addresses. changed {} to + and put : inside the first square bracket.
([a-f0-9:]+:+)+[a-f0-9]+
tested on with ifconfig -a output http://regexr.com/
Unix or Mac OSx terminal o option returns only the matching output(ipv6) including ::1
ifconfig -a | egrep -o '([a-f0-9:]+:+)+[a-f0-9]+'
Get All IP addresses (IPv4 OR IPv6) and print match on unix OSx term
ifconfig -a | egrep -o '([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) | (([a-f0-9:]+:+)+[a-f0-9]+)'
FWIW, here's the generic solution that I'm using. I'm using Bootstrap 3, but I think the general approach should work with Bootstrap 2 as well.
The solution enables popovers and adds a 'close' button for all popovers identified by the 'rel="popover"' tag using a generic block of JS code. Other than the (standard) requirement that there be a rel="popover" tag, you can put an arbitrary number of popovers on the page, and you don't need to know their IDs -- in fact they don't need IDs at all. You do need to use the 'data-title' HTML tag format to set the title attribute of your popovers, and have data-html set to "true".
The trick that I found necessary was to build an indexed map of references to the popover objects ("po_map"). Then I can add an 'onclick' handler via HTML that references the popover object via the index that JQuery gives me for it ("p_list['+index+'].popover(\'toggle\')"). That way I don't need to worry about the ids of the popover objects, since I have a map of references to the objects themselves with a JQuery-provided unique index.
Here's the javascript:
var po_map = new Object();
function enablePopovers() {
$("[rel='popover']").each(function(index) {
var po=$(this);
po_map[index]=po;
po.attr("data-title",po.attr("data-title")+
'<button id="popovercloseid" title="close" type="button" class="close" onclick="po_map['+index+'].popover(\'toggle\')">×</button>');
po.popover({});
});
}
$(document).ready(function() { enablePopovers() });
this solution let me easily put a close button on all the popovers all across my site.
In my case, @
caused some sort of encoding problem, I still prefer my old way:
curl -d "$(cat /path/to/file)" https://example.com
SELECT owner, table_name
FROM dba_constraints
WHERE constraint_name = <<your constraint name>>
will give you the name of the table. If you don't have access to the DBA_CONSTRAINTS
view, ALL_CONSTRAINTS
or USER_CONSTRAINTS
should work as well.
If the functions are re-written with completely different variables and we call id on them, it then illustrates the point well. I didn't get this at first and read jfs' post with the great explanation, so I tried to understand/convince myself:
def f(y, z):
y = 2
z.append(4)
print ('In f(): ', id(y), id(z))
def main():
n = 1
x = [0,1,2,3]
print ('Before in main:', n, x,id(n),id(x))
f(n, x)
print ('After in main:', n, x,id(n),id(x))
main()
Before in main: 1 [0, 1, 2, 3] 94635800628352 139808499830024
In f(): 94635800628384 139808499830024
After in main: 1 [0, 1, 2, 3, 4] 94635800628352 139808499830024
z and x have the same id. Just different tags for the same underlying structure as the article says.
As this option may need in many different manners, i reached to conclusion to develop an object so that it can be used in different scenarios and in future projects
first add this class to your project
public class SelectListDefaults
{
private IList<SelectListItem> getDefaultItems = new List<SelectListItem>();
public SelectListDefaults()
{
this.AddDefaultItem("(All)", "-1");
}
public SelectListDefaults(string text, string value)
{
this.AddDefaultItem(text, value);
}
public IList<SelectListItem> GetDefaultItems
{
get
{
return getDefaultItems;
}
}
public void AddDefaultItem(string text, string value)
{
getDefaultItems.Add(new SelectListItem() { Text = text, Value = value });
}
}
Now in Controller Action you can do like this
// Now you can do like this
ViewBag.MainCategories = new SelectListDefaults().GetDefaultItems.Concat(new SelectList(db.MainCategories, "MainCategoryID", "Name", Request["DropDownListMainCategory"] ?? "-1"));
// Or can change it by such a simple way
ViewBag.MainCategories = new SelectListDefaults("Any","0").GetDefaultItems.Concat(new SelectList(db.MainCategories, "MainCategoryID", "Name", Request["DropDownListMainCategory"] ?? "0"));
// And even can add more options
SelectListDefaults listDefaults = new SelectListDefaults();
listDefaults.AddDefaultItme("(Top 5)", "-5");
// If Top 5 selected by user, you may need to do something here with db.MainCategories, or pass in parameter to method
ViewBag.MainCategories = listDefaults.GetDefaultItems.Concat(new SelectList(db.MainCategories, "MainCategoryID", "Name", Request["DropDownListMainCategory"] ?? "-1"));
And finally in View you will code like this.
@Html.DropDownList("DropDownListMainCategory", (IEnumerable<SelectListItem>)ViewBag.MainCategories, new { @class = "form-control", onchange = "this.form.submit();" })
See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)
1. You might also use EXIT_ON_CLOSE
, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.
The 'button' to invoke this operation is already on a frame.
DISPOSE_ON_CLOSE
functionality.On CentOS 5.x, installing curl-devel fixed the problem for me.
Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.
Javascript code embedded aswell:
$(document).ready(function () {
var map;
var elevator;
var myOptions = {
zoom: 1,
center: new google.maps.LatLng(0, 0),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map
});
});
}
});
Do not forget to verify if your text editor encodes properly your code in UTF-8.
Otherwise, you may have invisible characters that are not interpreted as UTF-8.
If you DELETE the branch after merging it, just be aware that all hyperlinks, URLs, and references of your DELETED branch will be BROKEN.
As of year 2020, JetBrains suggests to commit the .idea
folder.
The JetBrains IDEs (webstorm, intellij, android studio, pycharm, clion, etc.) automatically add that folder to your git repository (if there's one).
Inside the folder .idea
, has been already created a .gitignore
, updated by the IDE itself to avoid to commit user related settings that may contains privacy/password data.
It is safe (and usually useful) to commit the .idea
folder.
I came to this question looking for a way to enable oracle session pool expiration based on total session lifetime instead of idle time. Another goal is to avoid force closes unexpected to application.
It seems it's possible by setting pool validation query to
select 1 from V$SESSION
where AUDSID = userenv('SESSIONID') and sysdate-LOGON_TIME < 30/24/60
This would close sessions aging over 30 minutes in predictable manner that doesn't affect application.
The 2018 ES6+ ANSWER IS:
const arr = [1, 2, 3];
arr.forEach((val, key, arr) => {
if (Object.is(arr.length - 1, key)) {
// execute last item logic
console.log(`Last callback call at index ${key} with value ${val}` );
}
});
Pure4J supports what you are after, in two ways.
First, it provides an @ImmutableValue
annotation, so that you can annotate a class to say that it is immutable. There is a maven plugin to allow you to check that your code actually is immutable (use of final
etc.).
Second, it provides the persistent collections from Clojure, (with added generics) and ensures that elements added to the collections are immutable. Performance of these is apparently pretty good. Collections are all immutable, but implement java collections interfaces (and generics) for inspection. Mutation returns new collections.
Disclaimer: I'm the developer of this
We are also looking for some way to convert html files with complex javascript to pdf.
The javasript in our files contains document.write
and DOM manipulation.
We have tried using a combination of HtmlUnit to parse the files and Flying Saucer to render to pdf but the results are not satisfactory enough. It works, but in our case the pdf is not close enough to what the user wants.
If you want to try this out, here is a code snippet to convert a local html file to pdf.
URL url = new File("test.html").toURI().toURL();
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(url);
OutputStream os = null;
try{
os = new FileOutputStream("test.pdf");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(page,url.toString());
renderer.layout();
renderer.createPDF(os);
} finally{
if(os != null) os.close();
}
If you created Connection Manager in your project then you can simply pull the connection string from there.
String connection = this.dts.connections["<connection_manager_name>"];
And use this connection in:
using (var conn = new SqlConnection(connection))
Please correct me if I am wrong.
I think you meant that you want to clear all the cells in the jTable and make it just like a new blank jTable. For an example, if your table is myTable, you can do following.
DefaultTableModel model = new DefaultTableModel();
myTable.setModel(model);
Apart from the similarities i.e. Task.Run() being a shorthand for Task.Factory.StartNew(), there is a minute difference between their behaviour in case of sync and async delegates.
Suppose there are following two methods:
public async Task<int> GetIntAsync()
{
return Task.FromResult(1);
}
public int GetInt()
{
return 1;
}
Now consider the following code.
var sync1 = Task.Run(() => GetInt());
var sync2 = Task.Factory.StartNew(() => GetInt());
Here both sync1 and sync2 are of type Task<int>
However, difference comes in case of async methods.
var async1 = Task.Run(() => GetIntAsync());
var async2 = Task.Factory.StartNew(() => GetIntAsync());
In this scenario, async1 is of type Task<int>
, however async2 is of type Task<Task<int>>
EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length());
Your nameContent scope is only inside first function. You'll never get it's value that way.
var nameContent; // now it's global!
function first(){
nameContent = document.getElementById('full_name').value;
}
function second() {
first();
y=nameContent;
alert(y);
}
second();
This is method I created to handle async scenarios with ForEach
.
public static class ParallelExecutor
{
/// <summary>
/// Executes asynchronously given function on all elements of given enumerable with task count restriction.
/// Executor will continue starting new tasks even if one of the tasks throws. If at least one of the tasks throwed exception then <see cref="AggregateException"/> is throwed at the end of the method run.
/// </summary>
/// <typeparam name="T">Type of elements in enumerable</typeparam>
/// <param name="maxTaskCount">The maximum task count.</param>
/// <param name="enumerable">The enumerable.</param>
/// <param name="asyncFunc">asynchronous function that will be executed on every element of the enumerable. MUST be thread safe.</param>
/// <param name="onException">Acton that will be executed on every exception that would be thrown by asyncFunc. CAN be thread unsafe.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public static async Task ForEachAsync<T>(int maxTaskCount, IEnumerable<T> enumerable, Func<T, Task> asyncFunc, Action<Exception> onException = null, CancellationToken cancellationToken = default)
{
using var semaphore = new SemaphoreSlim(initialCount: maxTaskCount, maxCount: maxTaskCount);
// This `lockObject` is used only in `catch { }` block.
object lockObject = new object();
var exceptions = new List<Exception>();
var tasks = new Task[enumerable.Count()];
int i = 0;
try
{
foreach (var t in enumerable)
{
await semaphore.WaitAsync(cancellationToken);
tasks[i++] = Task.Run(
async () =>
{
try
{
await asyncFunc(t);
}
catch (Exception e)
{
if (onException != null)
{
lock (lockObject)
{
onException.Invoke(e);
}
}
// This exception will be swallowed here but it will be collected at the end of ForEachAsync method in order to generate AggregateException.
throw;
}
finally
{
semaphore.Release();
}
}, cancellationToken);
if (cancellationToken.IsCancellationRequested)
{
break;
}
}
}
catch (OperationCanceledException e)
{
exceptions.Add(e);
}
foreach (var t in tasks)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
// Exception handling in this case is actually pretty fast.
// https://gist.github.com/shoter/d943500eda37c7d99461ce3dace42141
try
{
await t;
}
#pragma warning disable CA1031 // Do not catch general exception types - we want to throw that exception later as aggregate exception. Nothing wrong here.
catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
{
exceptions.Add(e);
}
}
if (exceptions.Any())
{
throw new AggregateException(exceptions);
}
}
}
I had a similar issue, I started to write my application in Kotlin, after I rewrote one of my activities I wanted to see if there are any issues, the problem was that I was not sure how to send an intent from java file to kotlin file.
In this case I created a static function in kotlin (companion object), this function is getting a context (from the current activity) and returning the new intent while using the current context ("java" context) while using the kotlin class ("::class.java").
Here is my code:
//this code will be in the kotlin activity - SearchActivity
companion object {
fun newIntent(context: Context): Intent {
return Intent(context, SearchActivity::class.java)
}
}
//this is how you call SearchActivity from MainActivity.java
Intent searchIntent = SearchActivity.Companion.newIntent(this);
startActivity(searchIntent);
I had this same issue, and searched the internet for a solution and none of the suggestions didn’t not open by double clicking the .jar
file.
In my case the reason is I have multiple JDK & JRE versions installed on my computer. Since I am a software developer working with several different versions for different clients I need to use multiple JDKs in my PC (Windows 10 Pro). So I do not want to change the system variables (i.e. JAVA_HOME
, JRE_HOME
or PATH
), instead I use command prompt to run java in user process whenever I wanted to use a different version.
When installing JDK it registers the .jar
file association with latest version we installed in the PC. If you right click on the .jar icon and select properties, it will show that file opens with “Java(TM) Platform SE Binary”. If we look at the registry key: HKEY_CLASSES_ROOT\jarfile\shell\open\command
, it will point to latest JDK version.
It is not a good idea (sometimes annoying) to change the registry key every time I want to run an app build from a different version.
So in my situation it is impossible to just double click the .jar
file to execute it. But instead I found a work around solution myself.
Scenario:
Multiple JDKs (1.7, 1.8, 9.0, 10.0, 11.0, and 12.0)are installed in the PC, so the latest installed was 12.0.
Problem
Want to double click an executable .jar
developed using JDK 1.8 and didn’t work
This is my work around solution:
.jar
file that you want to open. Change the text in the target (for example "D:\Dev\JavaApp1.8.jar"
)
To
"C:\Program Files\Java\jdk1.8.0\bin\javaw.exe
" -jar
"D:\Dev\JavaApp1.8.jar
"
Then click ok Double click the shortcut.
It should now open the app.
Use the glob function in a foreach loop to do whatever is an option. I also used the file_exists function in the example below to check if the directory exists before going any further.
$directory = 'my_directory/';
$extension = '.txt';
if ( file_exists($directory) ) {
foreach ( glob($directory . '*' . $extension) as $file ) {
echo $file;
}
}
else {
echo 'directory ' . $directory . ' doesn\'t exist!';
}
Since Java 8 you can sort using the Streams API:
List<String> fruits = Arrays.asList("apple", "Apricot", "banana");
List<String> sortedFruit = fruits.stream()
.sorted(String.CASE_INSENSITIVE_ORDER)
.collect(Collectors.toList())
The difference with Collections.sort
is that this will return a new list and will not modify the existing one.
I just need to initialize all the array elements to Boolean false.
Either use boolean[]
instead so that all values defaults to false
:
boolean[] array = new boolean[size];
Or use Arrays#fill()
to fill the entire array with Boolean.FALSE
:
Boolean[] array = new Boolean[size];
Arrays.fill(array, Boolean.FALSE);
Also note that the array index is zero based. The freq[Global.iParameter[2]] = false;
line as you've there would cause ArrayIndexOutOfBoundsException
. To learn more about arrays in Java, consult this basic Oracle tutorial.
If I'm reading your question correctly, objects in general are agnostic about where they are contained. They don't know who their parents are. To find that information, you have to parse the parent data structure. The DOM has ways of doing this for us when you're talking about element objects in a document, but it looks like you're talking about vanilla objects.
"I have been under the impression for that JavaScript was always asynchronous"
You can use JavaScript in a synchronous way, or an asynchronous way. In fact JavaScript has really good asynchronous support. For example I might have code that requires a database request. I can then run other code, not dependent
on that request, while I wait for that request to complete. This asynchronous coding is supported with promises, async/await, etc. But if you don't need a nice way to handle long waits then just use JS synchronously.
What do we mean by 'asynchronous'. Well it does not mean multi-threaded, but rather describes a non-dependent relationship. Check out this image from this popular answer:
A-Start ------------------------------------------ A-End
| B-Start -----------------------------------------|--- B-End
| | C-Start ------------------- C-End | |
| | | | | |
V V V V V V
1 thread->|<-A-|<--B---|<-C-|-A-|-C-|--A--|-B-|--C-->|---A---->|--B-->|
We see that a single threaded application can have async behavior. The work in function A is not dependent on function B completing, and so while function A began before function B, function A is able to complete at a later time and on the same thread.
So, just because JavaScript executes one command at a time, on a single thread, it does not then follow that JavaScript can only be used as a synchronous language.
"Is there a good reference anywhere about when it will be synchronous and when it will be asynchronous"
I'm wondering if this is the heart of your question. I take it that you mean how do you know if some code you are calling is async or sync. That is, will the rest of your code run off and do something while you wait for some result? Your first check should be the documentation for whichever library you are using. Node methods, for example, have clear names like readFileSync
. If the documentation is no good there is a lot of help here on SO. EG:
Some notes that I also found useful:
Keep your default values on the right side.
function whatever($var1, $var2, $var3="constant", $var4="another")
The default value of the argument must be a constant expression. It can't be a variable or a function call.
If, by some crazy coincidence, you want to convert a string of characters to an integer, you can do that too!
char *num = "1024";
int val = atoi(num); // atoi = ASCII TO Int
val
is now 1024. Apparently atoi()
is fine, and what I said about it earlier only applies to me (on OS X (maybe (insert Lisp joke here))). I have heard it is a macro that maps roughly to the next example, which uses strtol()
, a more general-purpose function, to do the conversion instead:
char *num = "1024";
int val = (int)strtol(num, (char **)NULL, 10); // strtol = STRing TO Long
strtol()
works like this:
long strtol(const char *str, char **endptr, int base);
It converts *str
to a long
, treating it as if it were a base base
number. If **endptr
isn't null, it holds the first non-digit character strtol()
found (but who cares about that).
UrlConnection is an awkward API to work with. HttpClient is by far the better API and it'll spare you from loosing time searching how to achieve certain things like this stackoverflow question illustrates perfectly. I write this after having used the jdk HttpUrlConnection in several REST clients. Furthermore when it comes to scalability features (like threadpools, connection pools etc.) HttpClient is superior
When you intend to print the memory address of any variable or a pointer, using %d
won't do the job and will cause some compilation errors, because you're trying to print out a number instead of an address, and even if it does work, you'd have an intent error, because a memory address is not a number. the value 0xbfc0d878
is surely not a number, but an address.
What you should use is %p
. e.g.,
#include<stdio.h>
int main(void) {
int a;
a = 5;
printf("The memory address of a is: %p\n", (void*) &a);
return 0;
}
Good luck!
I authored (yet another) angular html5 storage service. I wanted to keep the automatic updates made possible by ngStorage
, but make digest cycles more predictable/intuitive (at least for me), add events to handle when state reloads are required, and also add sharing session storage between tabs. I modelled the API after $resource
and called it angular-stored-object
. It can be used as follows:
angular
.module('auth', ['yaacovCR.storedObject']);
angular
.module('auth')
.factory('session', session);
function session(ycr$StoredObject) {
return new ycr$StoredObject('session');
}
API is here.
Repo is here.
Hope it helps somebody!
The other solutions didn't work for me. Maybe the old DOCTYPE in the project I am working on prevents HTML5 options.
My solution:
<form id="form_1" action="result.php" method="post"
onsubmit="sendForm(this.id);return false">
<input type="hidden" name="something" value="1">
</form>
js:
function sendForm(form_id){
var form = $('#'+form_id);
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: $(form).serialize(),
success: function(result) {
console.log(result)
}
});
}
Use the gcc
compiler. This assumes that you have the developer tools installed.
There is no need to download any binaries or files or follow difficult installation instructions.
All you really needed to do is:
sudo apt update && sudo apt install android-sdk
Update: Ubuntu 18.04 only
This is really a question about whether the path to the Python interpreter should be absolute or Logical (/usr/bin/env
) in respect to portability.
Encountering other answers on this and other Stack sites which talked about the issue in a general way without supporting proofs, I've performed some really, REALLY, granular testing & analysis on this very question on the unix.stackexchange.com. Rather than paste that answer here, I'll point those interested to the comparative analysis to that answer:
https://unix.stackexchange.com/a/566019/334294
Being a Linux Engineer, my goal is always to provide the most suitable, optimized hosts for my developer clients, so the issue of Python environments was something I really needed a solid answer to. My view after the testing was that the logical path in the she-bang was the better of the (2) options.
You're throwing away a result row when you do $sth->fetchColumn()
. That's not how you check if there's any results. you do
if ($sth->rowCount() > 0) {
... got results ...
} else {
echo 'nothing';
}
relevant docs here: http://php.net/manual/en/pdostatement.rowcount.php
Add /Q
for quiet mode and it should remove the prompt.
Seems like the cleanest way in this example is to:
Example adapted from shamanland implementation, use whatever FAB you wish. Assume FAB is 64dp high including shadow:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="120dp"
/>
<View
android:id="@+id/body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/header"
/>
<fully.qualified.name.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignBottom="@id/header"
android:layout_marginBottom="-32dp"
android:layout_marginRight="20dp"
/>
</RelativeLayout>
When I have org.json.JSONObject
in the classpath, I do:
Map<String, Object> stats = ...;
System.out.println(new JSONObject(stats).toString(2));
(this beautifully indents lists, sets and maps which may be nested)
Anybody wondering how to do it in EF core:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
..... rest of the code.....