this.mainInput
doesn't actually point to anything. Since you are using a controlled component (i.e. the value of the input is obtained from state) you can set this.state.city
to null:
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({ city: '' });
}
automaticallyAdjustsScrollViewInsets is deprecated in iOS11 (and the accepted solution no longer works). use:
if #available(iOS 11.0, *) {
scrollView.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
I know its quite late to answer this, but I guess it will help anyone ahead.
Well using CSS3 FlexBox. It can be acheived.
Make you header as display:flex
and divide its entire width into 3 parts. In the first part I have placed the logo, the searchbar in second part and buttons container in last part.
apply justify-content: between
to the header container and flex-grow:1
to the searchbar.
That's it. The sample code is below.
#header {_x000D_
background-color: #323C3E;_x000D_
justify-content: space-between;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#searchBar, img{_x000D_
align-self: center;_x000D_
}_x000D_
_x000D_
#searchBar{_x000D_
flex-grow:1;_x000D_
background-color: orange;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
#searchBar input {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.button {_x000D_
padding: 22px;_x000D_
}_x000D_
_x000D_
.buttonsHolder{_x000D_
display:flex;_x000D_
}
_x000D_
<div id="header" class="d-flex justify-content-between">_x000D_
<img src="img/logo.png" />_x000D_
<div id="searchBar">_x000D_
<input type="text" />_x000D_
</div>_x000D_
<div class="buttonsHolder">_x000D_
<div class="button orange inline" id="myAccount">_x000D_
My Account_x000D_
</div>_x000D_
<div class="button red inline" id="basket">_x000D_
Basket (2)_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
$(document).ready(function() {
$('#main_search').val('hi');
});
I know this thread is old now but I am answering it to keep things a bit updated.
With Angular 1.4 and above you can directly use limitTo filter which apart from accepting the limit
parameter also accepts a begin
parameter.
Usage: {{ limitTo_expression | limitTo : limit : begin}}
So now you may not need to use any third party library to achieve something like pagination. I have created a fiddle to illustrate the same.
This may help you if you are experiencing \u00a0
in stead of (whitespace). I had this problem when I was trying to extract Device Contact Phone Numbers. I needed to modify the phoneNumber string so it has no whitespace in it.
NSString* yourString = [yourString stringByReplacingOccurrencesOfString:@"\u00a0" withString:@""];
When yourString
was the current phone number.
[v setBackgroundColor ColorwithRed: Green: Blue: ];
What finally worked for me is similar to what @????DJ suggested, but the tabBackground
should be in the layout
file and not inside the style
, so it looks like:
res/layout/somefile.xml
:
<android.support.design.widget.TabLayout
....
app:tabBackground="@drawable/tab_color_selector"
...
/>
and the selector
res/drawable/tab_color_selector.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/tab_background_selected" android:state_selected="true"/>
<item android:drawable="@color/tab_background_unselected"/>
</selector>
select top 1 yr,count(*) from movie
join casting on casting.movieid=movie.id
join actor on casting.actorid = actor.id
where actor.name = 'John Travolta'
group by yr order by 2 desc
Here are two simple kotlin extension functions over view.
fun View.expand() {
visibility = View.VISIBLE
val animate = TranslateAnimation(0f, 0f, -height.toFloat(), 0f)
animate.duration = 200
animate.fillAfter = true
startAnimation(animate)
}
fun View.collapse() {
val animate = TranslateAnimation(0f, 0f, 0f, -height.toFloat() )
animate.duration = 200
animate.fillAfter = true
startAnimation(animate)
}
All the solutions are correct, but I found it easier just write a function to implement this. like this:
template <class T1, class T2>
void ContainerInsert(T1 t1, T2 t2)
{
t1->insert(t1->end(), t2->begin(), t2->end());
}
That way you can avoid the temporary placement like this:
ContainerInsert(vec, GetSomeVector());
In languages that support regular expressions with non-capturing groups:
((?:[^/]*/)*)(.*)
I'll explain the gnarly regex by exploding it...
(
(?:
[^/]*
/
)
*
)
(.*)
What the parts mean:
( -- capture group 1 starts
(?: -- non-capturing group starts
[^/]* -- greedily match as many non-directory separators as possible
/ -- match a single directory-separator character
) -- non-capturing group ends
* -- repeat the non-capturing group zero-or-more times
) -- capture group 1 ends
(.*) -- capture all remaining characters in group 2
To test the regular expression, I used the following Perl script...
#!/usr/bin/perl -w
use strict;
use warnings;
sub test {
my $str = shift;
my $testname = shift;
$str =~ m#((?:[^/]*/)*)(.*)#;
print "$str -- $testname\n";
print " 1: $1\n";
print " 2: $2\n\n";
}
test('/var/log/xyz/10032008.log', 'absolute path');
test('var/log/xyz/10032008.log', 'relative path');
test('10032008.log', 'filename-only');
test('/10032008.log', 'file directly under root');
The output of the script...
/var/log/xyz/10032008.log -- absolute path
1: /var/log/xyz/
2: 10032008.log
var/log/xyz/10032008.log -- relative path
1: var/log/xyz/
2: 10032008.log
10032008.log -- filename-only
1:
2: 10032008.log
/10032008.log -- file directly under root
1: /
2: 10032008.log
SQL> select Username from dba_users
2 ;
USERNAME
------------------------------
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL
MDSYS
USERNAME
------------------------------
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR
16 rows selected.
SQL> create user testdb identified by password;
User created.
SQL> select username from dba_users;
USERNAME
------------------------------
TESTDB
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL
USERNAME
------------------------------
MDSYS
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR
17 rows selected.
SQL> grant create session to testdb;
Grant succeeded.
SQL> create tablespace testdb_tablespace
2 datafile 'testdb_tabspace.dat'
3 size 10M autoextend on;
Tablespace created.
SQL> create temporary tablespace testdb_tablespace_temp
2 tempfile 'testdb_tabspace_temp.dat'
3 size 5M autoextend on;
Tablespace created.
SQL> drop user testdb;
User dropped.
SQL> create user testdb
2 identified by password
3 default tablespace testdb_tablespace
4 temporary tablespace testdb_tablespace_temp;
User created.
SQL> grant create session to testdb;
Grant succeeded.
SQL> grant create table to testdb;
Grant succeeded.
SQL> grant unlimited tablespace to testdb;
Grant succeeded.
SQL>
public static String readFileToString(String filePath) {
InputStream in = Test.class.getResourceAsStream(filePath);//filePath="/com/myproject/Sample.xml"
try {
return IOUtils.toString(in, StandardCharsets.UTF_8);
} catch (IOException e) {
logger.error("Failed to read the xml : ", e);
}
return null;
}
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE DATE(signup_date) = CURDATE()
In my case, the problem was caused by not being logged in with Postman, so I opened a connection in another tab with a session cookie I took from the headers in my Chrome session.
The question has changed, so to has the answer:
Strings can't be tested using math.isnan
as this expects a float argument. In your countries
list, you have floats and strings.
In your case the following should suffice:
cleanedList = [x for x in countries if str(x) != 'nan']
In your countries
list, the literal 'nan'
is a string not the Python float nan
which is equivalent to:
float('NaN')
In your case the following should suffice:
cleanedList = [x for x in countries if x != 'nan']
onChange will not call handleChange on mobile when using defaultChecked. As an alternative you can can use onClick and onTouchEnd.
<input onClick={this.handleChange} onTouchEnd={this.handleChange} type="checkbox" defaultChecked={!!this.state.complete} />;
Noone cand read the file except for those who have access to the file. You must make the code readable (but not writable) by the web server. If the php code handler is running properly you can't read it by requesting by name from the web server.
If someone compromises your server you are at risk. Ensure that the web server can only write to locations it absolutely needs to. There are a few locations under /var which should be properly configured by your distribution. They should not be accessible over the web. /var/www should not be writable, but may contain subdirectories written to by the web server for dynamic content. Code handlers should be disabled for these.
Ensure you don't do anything in your php code which can lead to code injection. The other risk is directory traversal using paths containing .. or begining with /. Apache should already be patched to prevent this when it is handling paths. However, when it runs code, including php, it does not control the paths. Avoid anything that allows the web client to pass a file path.
You can use my code here
//Print Button Event Handeler
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += PrintPage;
//here to select the printer attached to user PC
PrintDialog printDialog1 = new PrintDialog();
printDialog1.Document = pd;
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
pd.Print();//this will trigger the Print Event handeler PrintPage
}
}
//The Print Event handeler
private void PrintPage(object o, PrintPageEventArgs e)
{
try
{
if (File.Exists(this.ImagePath))
{
//Load the image from the file
System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\myimage.jpg");
//Adjust the size of the image to the page to print the full image without loosing any part of it
Rectangle m = e.MarginBounds;
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
}
}
catch (Exception)
{
}
}
This is slightly modified version of Mark Ransom's answer that works if ch
could be more than one character in length.
def find(term, ch):
"""Find all places with ch in str
"""
for i in range(len(term)):
if term[i:i + len(ch)] == ch:
yield i
I downgraded via NuGet to MVC 4 and then upgraded again to 5.2.7 and it fixed this issue
Hope this could help someone
$(document).on("input", ".numeric", function() {
this.value = this.value.match(/^\d+\.?\d{0,2}/);});
I had a similar question, but was actually looking for a different answer; I'm looking to create a custom event. For example instead of always saying this:
$('#myInput').keydown(function(ev) {
if (ev.which == 13) {
ev.preventDefault();
// Do some stuff that handles the enter key
}
});
I want to abbreviate it to this:
$('#myInput').enterKey(function() {
// Do some stuff that handles the enter key
});
trigger and bind don't tell the whole story - this is a JQuery plugin. http://docs.jquery.com/Plugins/Authoring
The "enterKey" function gets attached as a property to jQuery.fn - this is the code required:
(function($){
$('body').on('keydown', 'input', function(ev) {
if (ev.which == 13) {
var enterEv = $.extend({}, ev, { type: 'enterKey' });
return $(ev.target).trigger(enterEv);
}
});
$.fn.enterKey = function(selector, data, fn) {
return this.on('enterKey', selector, data, fn);
};
})(jQuery);
http://jsfiddle.net/b9chris/CkvuJ/4/
A nicety of the above is you can handle keyboard input gracefully on link listeners like:
$('a.button').on('click enterKey', function(ev) {
ev.preventDefault();
...
});
Edits: Updated to properly pass the right this
context to the handler, and to return any return value back from the handler to jQuery (for example in case you were looking to cancel the event and bubbling). Updated to pass a proper jQuery event object to handlers, including key code and ability to cancel event.
Old jsfiddle: http://jsfiddle.net/b9chris/VwEb9/24/
The simplest way would be to convert your hexadecimal string to a byte array and use the File.WriteAllBytes
method.
Using the StringToByteArray()
method from this question, you'd do something like this:
string hexString = "0CFE9E69271557822FE715A8B3E564BE";
File.WriteAllBytes("output.dat", StringToByteArray(hexString));
The StringToByteArray
method is included below:
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
<button>
vs.
<input type='button'>
--
in modern browsers, both elements are easily styleable with css but in most cases, button
element is preferred as you can style more with inner html and pseudo elements
If your using Java8 you can use the IntStream:
int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());
Results: 181
Just 1 line of code which will sum the array.
for cakephp 2.0 Write this function in AppModel.php
function getLastQuery()
{
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
To use this in Controller Write : echo $this->YourModelName->getLastQuery();
I had this issue after migrating from spring-boot-starter-data-jpa
ver. 1.5.7 to 2.0.2 (from old hibernate to hibernate 5.2). In my @Configuration
class I injected entityManagerFactory
and transactionManager
.
//I've got my data source defined in application.yml config file,
//so there is no need to configure it from java.
@Autowired
DataSource dataSource;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
//JpaVendorAdapteradapter can be autowired as well if it's configured in application properties.
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
//Add package to scan for entities.
factory.setPackagesToScan("com.company.domain");
factory.setDataSource(dataSource);
return factory;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
Also remember to add hibernate-entitymanager dependency to pom.xml otherwise EntityManagerFactory won't be found on classpath:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.12.Final</version>
</dependency>
You can chnage font size by ctrl + mousewheel.
OR
tools --> options --> environment --> font and color.
Detail with screenshot is mentonied here
With the other answer you may have troubles with the time info (compare the dates with unexpected results!)
I suggest:
java.util.Calendar cal = Calendar.getInstance();
java.util.Date utilDate = new java.util.Date(); // your util date
cal.setTime(utilDate);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime()); // your sql date
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
In case of this similar error Warning: Error in $: object of type 'closure' is not subsettable [No stack trace available]
Just add corresponding package name using :: e.g.
instead of tags(....)
write shiny::tags(....)
All email clients adjust the HTML and the CSS code you provide by their own rules:
e.g.: gmail removes everything but the inner HTML of the body tag.
1. for most other clients you can have a style-tag in your header
<style type="text/css">
a {text-decoration: none !important;}
</style>
note: don't use CSS comments as YAHOO!Mail might cause trouble.
2. to be on the save side add the same code inline into the A tag as you did and an extra span tag as well (the style rules in a tags get often removed)
<a href="" style="text-decoration: none !important;">
<span style="text-decoration: none !important;">
text
</span>
</a>
Not an answer to the original question, but an example to the how-to-make-reusable and working custom renderers without breaking MVC :-)
// WRONG
public class DataWrapper {
final Data data;
final String description;
public DataWrapper(Object data, String description) {
this.data = data;
this.description = description;
}
....
@Override
public String toString() {
return description;
}
}
// usage
myModel.add(new DataWrapper(data1, data1.getName());
It is wrong in a MVC environment, because it is mixing data and view: now the model doesn't contain the data but a wrapper which is introduced for view reasons. That's breaking separation of concerns and encapsulation (every class interacting with the model needs to be aware of the wrapped data).
The driving forces for breaking of rules were:
As in Swing a custom renderer is the small coin designed to accomodate for custom visual representation, a default manager which can't cope is ... broken. Tweaking design just to accommodate for such a crappy default is the wrong way round, kind of upside-down. The correct is, to implement a coping manager.
While re-use is fine, doing so at the price of breaking the basic architecture is not a good bargin.
We have a problem in the presentation realm, let's solve it in the presentation realm with the elements designed to solve exactly that problem. As you might have guessed, SwingX already has such a solution :-)
In SwingX, the provider of a string representation is called StringValue, and all default renderers take such a StringValue to configure themselves:
StringValue sv = new StringValue() {
@Override
public String getString(Object value) {
if (value instanceof Data) {
return ((Data) value).getSomeProperty();
}
return TO_STRING.getString(value);
}
};
DefaultListRenderer renderer = new DefaultListRenderer(sv);
As the defaultRenderer is-a StringValue (implemented to delegate to the given), a well-behaved implementation of KeySelectionManager now can delegate to the renderer to find the appropriate item:
public BetterKeySelectionManager implements KeySelectionManager {
@Override
public int selectionForKey(char ch, ComboBoxModel model) {
....
if (getCellRenderer() instance of StringValue) {
String text = ((StringValue) getCellRenderer()).getString(model.getElementAt(row));
....
}
}
}
Outlined the approach because it is easily implementable even without using SwingX, simply define implement something similar and use it:
All except the string provider is reusable as-is (that is exactly one implemenation of the custom renderer and the keySelectionManager). There can be general implementations of the string provider, f.i. those formatting value or using bean properties via reflection. And all without breaking basic rules :-)
You can use Task
to specify what you want to do then attach that Task
with a Thread
. so that Task
would be executed in that newly made Thread
rather than on the GUI thread.
Use Task
with the TaskFactory.StartNew(Action action)
. In here you execute a delegate so if you didn't use any thread it would be executed in the same thread (GUI thread). If you mention a thread you can execute this Task
in a different thread. This is an unnecessary work cause you can directly execute the delegate or attach that delegate to a thread and execute that delegate in that thread. So don't use it. it's just unnecessary. If you intend to optimize your software this is a good candidate to be removed.
**Please note that the Action
is a delegate
.
In my limited experience with the following details.throws is a declaration that declares multiple exceptions that may occur but do not necessarily occur, throw is an action that can throw only one exception, typically a non-runtime exception, try catch is a block that catches exceptions that can be handled when an exception occurs in a method,this exception can be thrown.An exception can be understood as a responsibility that should be taken care of by the behavior that caused the exception, rather than by its upper callers. I hope my answer will help you
You have two versions of mysql using the same port. 3306. Change the port.
How to change the mysql port for xampp?
Code:
Password = your_password
port = 3306 ---> 3307
socket = "/ xampp / mysql / mysql.sock"
and here also
Code:
The MySQL server
[ mysqld ]
port = 3306 ---> 3307
socket = "/ xampp / mysql / mysql.sock"
2. Start mysql service
I was also getting "Request return with error:parsererror." in the javascript console. In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.
String encodedString = getEncodedString(text, encoding);
view.setTextAreaContent(encodedString);
A small variation on Husky's idea that I use. Make a file called 'globals' (or whatever you like) and then define multiple classes in it, as such:
#globals.py
class dbinfo : # for database globals
username = 'abcd'
password = 'xyz'
class runtime :
debug = False
output = 'stdio'
Then, if you have two code files c1.py and c2.py, both can have at the top
import globals as gl
Now all code can access and set values, as such:
gl.runtime.debug = False
print(gl.dbinfo.username)
People forget classes exist, even if no object is ever instantiated that is a member of that class. And variables in a class that aren't preceded by 'self.' are shared across all instances of the class, even if there are none. Once 'debug' is changed by any code, all other code sees the change.
By importing it as gl, you can have multiple such files and variables that lets you access and set values across code files, functions, etc., but with no danger of namespace collision.
This lacks some of the clever error checking of other approaches, but is simple and easy to follow.
When you're exporting to HTML, using <br>
works. However, if you're using pandoc to export to LaTeX/PDF as well, you should use grid tables:
+---------------+---------------+--------------------+
| Fruit | Price | Advantages |
+===============+===============+====================+
| Bananas | first line\ | first line\ |
| | next line | next line |
+---------------+---------------+--------------------+
| Bananas | first line\ | first line\ |
| | next line | next line |
+---------------+---------------+--------------------+
In addition set the proxy for the command line session Open a command line where you might want to run your script
netsh winhttp set proxy YourProxySERVER:yourProxyPORT
run your script in that terminal.
Further to the above excellent comments about trusted constraints:
select * from sys.foreign_keys where is_not_trusted = 1 ;
select * from sys.check_constraints where is_not_trusted = 1 ;
An untrusted constraint, much as its name suggests, cannot be trusted to accurately represent the state of the data in the table right now. It can, however, but can be trusted to check data added and modified in the future.
Additionally, untrusted constraints are disregarded by the query optimiser.
The code to enable check constraints and foreign key constraints is pretty bad, with three meanings of the word "check".
ALTER TABLE [Production].[ProductCostHistory]
WITH CHECK -- This means "Check the existing data in the table".
CHECK CONSTRAINT -- This means "enable the check or foreign key constraint".
[FK_ProductCostHistory_Product_ProductID] -- The name of the check or foreign key constraint, or "ALL".
If you changed awk '{print $1}' to '{ $1=""; print $0}' you will get all processes except for the first as a result. It will start with the field separator (a space generally) but I don't recall killall caring. So:
#! /bin/bash
logfile="/var/oscamlog/oscam1check.log"
case "$(pidof oscam1 | wc -w)" in
0) echo "oscam1 not running, restarting oscam1: $(date)" >> $logfile
/usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
;;
2) echo "oscam1 running, all OK: $(date)" >> $logfile
;;
*) echo "multiple instances of oscam1 running. Stopping & restarting oscam1: $(date)" >> $logfile
kill $(pidof oscam1 | awk '{ $1=""; print $0}')
;;
esac
It is worth noting that the pidof route seems to work fine for commands that have no spaces, but you would probably want to go back to a ps-based string if you were looking for, say, a python script named myscript that showed up under ps like
root 22415 54.0 0.4 89116 79076 pts/1 S 16:40 0:00 /usr/bin/python /usr/bin/myscript
Just an FYI
It's impossible (for me) to add the first file to an empty repository cloned from GitHub. You need to follow the link README, that GitHub suggests to create. After you create your first file online, you can work normally with git.
This happened to me Nov 17, 2016.
Using fgetc(fp)
only to be able to call strcpy(buffer,c);
doesn't seem right.
You could simply build this buffer on your own:
char buffer[MAX_SIZE_OF_MY_BUFFER];
int i = 0;
char ch;
while (i < MAX_SIZE_OF_MY_BUFFER - 1 && (ch = fgetc(fp)) != EOF) {
buffer[i++] = ch;
}
buffer[i] = '\0'; // terminating character
Note that this relies on the fact that you will read less than MAX_SIZE_OF_MY_BUFFER
characters
If you can't import MockMultipartFile
using
import org.springframework.mock.web.MockMultipartFile;
you need to add the below dependency into pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
I fixed a similar error by adding the json dataType like so:
$.ajax({
type: "POST",
url: "someUrl",
dataType: "json",
data: {
varname1 : "varvalue1",
varname2 : "varvalue2"
},
success: function (data) {
$.each(data, function (varname, varvalue){
...
});
}
});
And in my controller I had to use double quotes around any strings like so (note: they have to be escaped in java):
@RequestMapping(value = "/someUrl", method=RequestMethod.POST)
@ResponseBody
public String getJsonData(@RequestBody String parameters) {
// parameters = varname1=varvalue1&varname2=varvalue2
String exampleData = "{\"somename1\":\"somevalue1\",\"somename2\":\"somevalue2\"}";
return exampleData;
}
So, you could try using double quotes around your numbers if they are being used as strings (and remove that last comma):
[{"id":"50","name":"SEO"},{"id":"22","name":"LPO"}]
Always use tax_query to get posts/products from a particular category or any other taxonomy. You can also get the products using ID/slug of particular taxonomy...
$the_query = new WP_Query( array(
'post_type' => 'product',
'tax_query' => array(
array (
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'accessories',
)
),
) );
while ( $the_query->have_posts() ) :
$the_query->the_post();
the_title(); echo "<br>";
endwhile;
wp_reset_postdata();
There are a ton of options here, but I was surprised no quick one-liners. This is what I used at the beginning of my scripts:
[[ "$(command -v mvn)" ]] || { echo "mvn is not installed" 1>&2 ; exit 1; }
[[ "$(command -v java)" ]] || { echo "java is not installed" 1>&2 ; exit 1; }
This is based on the selected answer here and another source.
express-error-handler lets you specify custom templates, static pages, or error handlers for your errors. It also does other useful error-handling things that every app should implement, like protect against 4xx error DOS attacks, and graceful shutdown on unrecoverable errors. Here's how you do what you're asking for:
var errorHandler = require('express-error-handler'),
handler = errorHandler({
static: {
'404': 'path/to/static/404.html'
}
});
// After all your routes...
// Pass a 404 into next(err)
app.use( errorHandler.httpError(404) );
// Handle all unhandled errors:
app.use( handler );
Or for a custom handler:
handler = errorHandler({
handlers: {
'404': function err404() {
// do some custom thing here...
}
}
});
Or for a custom view:
handler = errorHandler({
views: {
'404': '404.jade'
}
});
if you have any id for the SVG image, you can fill the colours with respect to the ID.
let image = SVGKImage(named: "iconName")
let svgIMGV = SVGKFastImageView(frame: self.imgView.frame)
svgIMGV.image = image
svgIMGV.fillTintColor(colorImage: UIColor.red, iconID: "Bank")
// Add in extension SVGKImageView
extension SVGKImageView {
func fillTintColor(colorImage: UIColor, iconID: String) {
if self.image != nil && self.image.caLayerTree != nil {
print(self.image.caLayerTree.sublayers)
guard let sublayers = self.image.caLayerTree.sublayers else { return }
fillRecursively(sublayers: sublayers, color: colorImage, iconID: iconID)
}
}
private func fillRecursively(sublayers: [CALayer], color: UIColor, iconID: String, hasFoundLayer: Bool) {
var isLayerFound = false
for layer in sublayers {
if let l = layer as? CAShapeLayer {
print(l.name)
//IF you want to color the specific shapelayer by id else remove the l.name == "myID" validation
if let name = l.name, hasFoundLayer == true && name == "myID" {
self.colorThatImageWIthColor(color: color, layer: l)
print("Colouring FInished")
}
} else {
if layer.name == iconID {
if let innerSublayer = layer.sublayers as? [CAShapeLayer] {
fillRecursively(sublayers: innerSublayer, color: color, iconID: iconID, hasFoundLayer: true )
print("FOund")
}
} else {
if let l = layer as? CALayer, let sub = l.sublayers {
fillRecursively(sublayers: sub, color: color, iconID: iconID, hasFoundLayer: false)
}
}
}
}
}
func colorThatImageWIthColor(color: UIColor, layer: CAShapeLayer) {
if layer.strokeColor != nil {
layer.strokeColor = color.cgColor
}
if layer.fillColor != nil {
layer.fillColor = color.cgColor
}
}
}
OR Checkout this example.
As per OpenCV docs(1), below steps using OpenCV manager is the recommended way to use OpenCV for production runs. But, OpenCV manager(2) is an additional install from Google play store. So, if you prefer a self contained apk(not using OpenCV manager) or is currently in development/testing phase, I suggest answer at https://stackoverflow.com/a/27421494/1180117.
Recommended steps for using OpenCV in Android Studio with OpenCV manager.
File -> Import Module
, choose sdk/java
folder in the unzipped opencv archive. build.gradle
under imported OpenCV module to update 4 fields to match your project's build.gradle
a) compileSdkVersion b) buildToolsVersion c) minSdkVersion and 4) targetSdkVersion. Application -> Module Settings
, and select the Dependencies
tab. Click +
icon at bottom(or right), choose Module Dependency
and select the imported OpenCV module.As the final step, in your Activity class, add snippet below.
public class SampleJava extends Activity {
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch(status) {
case LoaderCallbackInterface.SUCCESS:
Log.i(TAG,"OpenCV Manager Connected");
//from now onwards, you can use OpenCV API
Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
break;
case LoaderCallbackInterface.INIT_FAILED:
Log.i(TAG,"Init Failed");
break;
case LoaderCallbackInterface.INSTALL_CANCELED:
Log.i(TAG,"Install Cancelled");
break;
case LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION:
Log.i(TAG,"Incompatible Version");
break;
case LoaderCallbackInterface.MARKET_ERROR:
Log.i(TAG,"Market Error");
break;
default:
Log.i(TAG,"OpenCV Manager Install");
super.onManagerConnected(status);
break;
}
}
};
@Override
protected void onResume() {
super.onResume();
//initialize OpenCV manager
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, mLoaderCallback);
}
}
Note: You could only make OpenCV calls after you receive success callback on onManagerConnected
method. During run, you will be prompted for installation of OpenCV manager from play store, if it is not already installed. During development, if you don't have access to play store or is on emualtor, use appropriate OpenCV manager apk present in apk
folder under downloaded OpenCV sdk archive .
Pros
Cons
string sqlCon = @"Data Source=.\SQLEXPRESS;" +
@"AttachDbFilename=|DataDirectory|\SampleDB.mdf;
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
SqlConnection Con = new SqlConnection(sqlCon);
The filepath should have |DataDirectory| which actually links to "current project directory\App_Data\" or "current project directory" and get the .mdf file.....Place the .mdf in either of these places and should work in visual studio 2010.And when you use the standalone application on production system, then the current path where the executable file is, should have the .mdf file.
If you have a list with 53 items, the last one is thelist[52]
because indexing starts at 0.
IndexError
IndexError
The IndexError
is raised when attempting to retrieve an index from a sequence (e.g. list
, tuple
), and the index isn’t found in the sequence. The Python documentation defines when this exception is raised:
Raised when a sequence subscript is out of range. (Source)
Here’s an example that raises the IndexError
:
test = list(range(53))
test[53]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-6-7879607f7f36> in <module>
1 test = list(range(53))
----> 2 test[53]
IndexError: list index out of range
The error message line for an IndexError
doesn’t provide great information. See that there is a sequence reference that is out of range and what the type of the sequence is, a list
in this case. That information, combined with the rest of the traceback, is usually enough to help quickly identify how to fix the issue.
I have faced the same issue, but none of the answers above helped me! I just simply closed my Visual Studio 2017 then re-run it, and It worked!
Using source or $0 will not give you the real path of your script. You could use the process id of the script to retrieve its real path
ls -l /proc/$$/fd |
grep "255 ->" |
sed -e 's/^.\+-> //'
I am using this script and it has always served me well :)
Disable all input
:
[...document.querySelectorAll('input')].map(e => e.disabled = true);
Disable input
with id="my-input"
document.getElementById('my-input').disabled = true;
The question is with JQuery, it's just FYI.
Actually I found the best solution is the following:
$cur_dir = explode('\\', getcwd());
echo $cur_dir[count($cur_dir)-1];
if your dir is www\var\path\ Current_Path
then this returns Current_path
They do different things. exec
replaces the current process with the new process and never returns. system
invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.
Try this runner I wrote. It could be helpful.
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class ProxyAuthHelper {
public static void main(String[] args) throws Exception {
String tmp = System.getProperty("http.proxyUser", System.getProperty("https.proxyUser"));
if (tmp == null) {
System.out.println("Proxy username: ");
tmp = new Scanner(System.in).nextLine();
}
final String userName = tmp;
tmp = System.getProperty("http.proxyPassword", System.getProperty("https.proxyPassword"));
if (tmp == null) {
System.out.println("Proxy password: ");
tmp = new Scanner(System.in).nextLine();
}
final char[] password = tmp.toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("\n--------------\nProxy auth: " + userName);
return new PasswordAuthentication (userName, password);
}
});
Class<?> clazz = Class.forName(args[0]);
Method method = clazz.getMethod("main", String[].class);
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
method.invoke(null, new Object[]{newArgs});
}
}
Since it is being passed a duration of 0
, I suppose it is in order to remove the code passed to the setTimeout
from the flow of execution. So if it's a function that could take a while, it won't prevent the subsequent code from executing.
If you are using SQL Server 2012, 2014 or newer, use the Format Function instead:
select Format( decimalColumnName ,'FormatString','en-US' )
Review the Microsoft topic and .NET format syntax for how to define the format string.
An example for this question would be:
select Format( MyDecimalColumn ,'N','en-US' )
If nothing works then add authentication mode="Windows" in your system.web attribute in your Web.Config file. hope it will work for you.
If you need simplify code then live is better in the most cases. If you need to get the best performance then delegate will always better than live. bind (click) vs delegate isn't so simple question (if you have a lot of similar items then delegate will be better).
Edge (as opposed to IE11) has a better UI for Local storage / Session storage and cookies:
Use sudo npm install -g appium
.
This solution works with Swift 4 (Xcode 9.2) and also with Swift 5 (Xcode 10.2.1+):
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
// process files
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}
Here's a reusable FileManager extension that also lets you skip or include hidden files in the results:
import Foundation
extension FileManager {
func urls(for directory: FileManager.SearchPathDirectory, skipsHiddenFiles: Bool = true ) -> [URL]? {
let documentsURL = urls(for: directory, in: .userDomainMask)[0]
let fileURLs = try? contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [] )
return fileURLs
}
}
// Usage
print(FileManager.default.urls(for: .documentDirectory) ?? "none")
You can change from the property of every item.
def directory(path,extension):
list_dir = []
list_dir = os.listdir(path)
count = 0
for file in list_dir:
if file.endswith(extension): # eg: '.txt'
count += 1
return count
And for PHP 5.3, you can use this function, which can be embedded in a class or used in procedural style:
http://svn.kd2.org/svn/misc/libs/tools/json_readable_encode.php
Both Redirect::to()
and Redirect::away()
should work.
Difference
Redirect::to() does additional URL checks and generations. Those additional steps are done in Illuminate\Routing\UrlGenerator and do the following, if the passed URL is not a fully valid URL (even with protocol):
Determines if URL is secure rawurlencode() the URL trim() URL
src : https://medium.com/@zwacky/laravel-redirect-to-vs-redirect-away-dd875579951f
For the TL;DR, here are 2 cents and a simpler version for your questions:
WebSockets provides these benefits over HTTP:
WebSocket and HTTP protocol have been designed to solve different problems, I.E. WebSocket was designed to improve bi-directional communication whereas HTTP was designed to be stateless, distributed using a request/response model. Other than sharing the ports for legacy reasons (firewall/proxy penetration), there isn't much common ground to combine them into one protocol.
Easy, add cmd to your last line of bat, BUT! if you reset or clear your system path, you must start your cmd with the full path, like:
%windir%\system32\cmd.exe
For example, I have a bat file to reset jdk to old version like this:
PATH=C:\Program Files\Java\jdk1.6.0_45\bin;C:\apache-ant-1.7.1\bin
SET JAVA_HOME=C:\Program Files\Java\jdk1.6.0_45
%windir%\system32\cmd.exe
since I reset the system path, I have to run cmd with the full path, or the system can't find cmd.exe, it will fail to run cmd, and just close the window, and you can't see the error msg.
There's a much better solution for this problem.
Just take a normal Button
and use the drawableLeft
and the gravity
attributes.
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/my_btn_icon"
android:gravity="left|center_vertical" />
This way you get a button which displays a icon in the left side of the button and the text at the right site of the icon vertical centered.
I made a library named AndroidImageSlider, you can have a try.
this is the most simple way but it works for me with a ComboBox1 name
SOLUTION on 3 Basic STEPS:
step 1.
Declare a variable at the beginning of your form which will hold the original text value of the ComboBox. Example:
Dim xCurrentTextValue as string
step 2.
Create the event combobox1 key down and Assign to xCurrentTextValue variable the current text of the combobox if any key diferrent than "ENTER" is pressed the combobox text value keeps the original text value
Example:
Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles ComboBox1.KeyDown
xCurrentTextValue = ComboBox1.Text
If e.KeyCode <> Keys.Enter Then
Me.ComboBox1.Text = xCmbItem
End If
End Sub
step 3.
Validate the when the combo text is changed if len(xcurrenttextvalue)> 0 or is different than nothing then the combobox1 takes the xcurrenttextvalue variable value
Private Sub ComboBox1_TextChanged(sender As Object, e As EventArgs) Handles ComboBox1.TextChanged
If Len(xCurrentTextValue) > 0 Then
Me.ComboBox1.Text = xCurrentTextValue
End If
End Sub
========================================================== that's it,
Originally I only tried the step number 2, but I have problems when you press the DEL key and DOWN arrow key, also for some reason it didn't validate the keydown event unless I display any message box
!Sorry, this is a correction on step number 2, I forgot to change the variable xCmbItem to xCurrentTextValue, xCmbItem it was used for my personal use
THIS IS THE CORRECT CODE
xCurrentTextValue = ComboBox1.Text
If e.KeyCode <> Keys.Enter Then
Me.ComboBox1.Text = xCurrentTextValue
End If
You should define source code encoding, add this to the top of your script:
# -*- coding: utf-8 -*-
The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:
import sys
print sys.getdefaultencoding()
Also see:
you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+". I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).
A few comments on the accepted answer:
The +
means "1 or more". I don't think you need to repeat \s
. I think you can simply write '/\s+/'
.
Also, if you want to remove whitespace first and last in the string, add trim
.
With these modifications, the code would be:
$string = preg_replace('/\s+/', ' ', trim($string));
I took Joe Love's answer and rewrote it using the IN
operator with sub-selects instead of =
to make the function faster (according to Hubbitus's suggestion):
create or replace function delete_cascade(p_schema varchar, p_table varchar, p_keys varchar, p_subquery varchar default null, p_foreign_keys varchar[] default array[]::varchar[])
returns integer as $$
declare
rx record;
rd record;
v_sql varchar;
v_subquery varchar;
v_primary_key varchar;
v_foreign_key varchar;
v_rows integer;
recnum integer;
begin
recnum := 0;
select ccu.column_name into v_primary_key
from
information_schema.table_constraints tc
join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema
and tc.constraint_type='PRIMARY KEY'
and tc.table_name=p_table
and tc.table_schema=p_schema;
for rx in (
select kcu.table_name as foreign_table_name,
kcu.column_name as foreign_column_name,
kcu.table_schema foreign_table_schema,
kcu2.column_name as foreign_table_primary_key
from information_schema.constraint_column_usage ccu
join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema
join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema
join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema
join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema
where ccu.table_name=p_table and ccu.table_schema=p_schema
and TC.CONSTRAINT_TYPE='FOREIGN KEY'
and tc2.constraint_type='PRIMARY KEY'
)
loop
v_foreign_key := rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name;
v_subquery := 'select "'||rx.foreign_table_primary_key||'" as key from '||rx.foreign_table_schema||'."'||rx.foreign_table_name||'"
where "'||rx.foreign_column_name||'"in('||coalesce(p_keys, p_subquery)||') for update';
if p_foreign_keys @> ARRAY[v_foreign_key] then
--raise notice 'circular recursion detected';
else
p_foreign_keys := array_append(p_foreign_keys, v_foreign_key);
recnum:= recnum + delete_cascade(rx.foreign_table_schema, rx.foreign_table_name, null, v_subquery, p_foreign_keys);
p_foreign_keys := array_remove(p_foreign_keys, v_foreign_key);
end if;
end loop;
begin
if (coalesce(p_keys, p_subquery) <> '') then
v_sql := 'delete from '||p_schema||'."'||p_table||'" where "'||v_primary_key||'"in('||coalesce(p_keys, p_subquery)||')';
--raise notice '%',v_sql;
execute v_sql;
get diagnostics v_rows = row_count;
recnum := recnum + v_rows;
end if;
exception when others then recnum=0;
end;
return recnum;
end;
$$
language PLPGSQL;
Choose the build
The answer is that you Mouse over the icon for your build and at the end of the line you'll see a little colored minus in a circle. This removes the build and you can now click on the + sign and choose a new build for submitting.
It is an unbelievably complicated web page with tricks and gizmos to do the thing you want. I'm sure Steve never saw this page or tried to use it.
Surely it's better practice to design the screen so that you can see the options all the time, not to have the screen change depending on whether you have an app in review or not!
First of all try this
sudo apt-get update
sudo apt-get clean
sudo apt-get autoremove
If error still persists then do this
sudo apt --fix-broken install
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get install -f
Afterwards try this again:
sudo apt-get install npm
But if it still couldn't resolve issues check for the dependencies using sudo dpkg --configure -a
and remove them one-by-one . Let's say dependencies are on npm then go for this ,
sudo apt-get remove nodejs
sudo apt-get remove npm
Then go to /etc/apt/sources.list.d and remove any node list if you have. Then do a
sudo apt-get update
Then check for the dependencies problem again using sudo dpkg --configure -a
and if it's all clear then you are done .
Later on install npm again using this
v=8 # set to 4, 5, 6, ... as needed
curl -sL https://deb.nodesource.com/setup_$v.x | sudo -E bash -
Then install the Node.js package.
sudo apt-get install -y nodejs
The answer above will work for general cases also(for dependencies on other packages like django ,etc) just after first two processes use the same process for the package you are facing dependency with.
VOLUME is used in Dockerfile
to expose the volume to be used by other containers. Example, create Dockerfile
as:
FROM ubuntu:14.04
RUN mkdir /myvol
RUN echo "hello world" > /myvol/greeting
VOLUME /myvol
build the image:
$ docker build -t testing_volume .
Run the container, say container1:
$ docker run -it <image-id of above image> bash
Now run another container with volumes-from option as (say-container2)
$ docker run -it --volumes-from <id-of-above-container> ubuntu:14.04 bash
You will get all data from container1 /myvol
directory into container2 at same location.
-v
option is given at run time of container which is used to mount container's directory on host. It is simple to use, just provide -v
option with argument as <host-path>:<container-path>
. The whole command may be as $ docker run -v <host-path>:<container-path> <image-id>
Remove Existing/Configured System Library: Eclipse(IDE) -> Project Explorer -> Project Name-> (Option) Build Path -> Configure Build Path -> Java Build Path -> Libraries -> (Select) JRE System Library [(For me)jre1.8.0_231] -> Remove.
Currently you are at same location: Eclipse(IDE) -> Project Explorer -> Project Name-> (Option) Build Path -> Configure Build Path -> Java Build Path -> Libraries
Now Add Same System Library Again: Add Library -> JRE System Library -> Workspace default JRE ((For me)jre1.8.0_231) -> Finish -> Apply -> Close.
Now wait to finish it.
Additionally for gists, it seems you must leave out the username
git remote set-url origin [email protected]:<Project code>
RESULT
HTML
<ul class="list">
<li>This is the text</li>
<li>This is another text</li>
<li>This is another another text</li>
</ul>
Use align-items
instead of align-self
and I also added flex-direction
to column
.
CSS
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
html,
body {
height: 100%;
}
.list {
display: flex;
justify-content: center;
flex-direction: column; /* <--- I added this */
align-items: center; /* <--- Change here */
height: 100px;
width: 100%;
background: silver;
}
.list li {
background: gold;
height: 20%;
}
Use:
L = ['Thanks You', 'Its fine no problem', 'Are you sure']
#create new df
df = pd.DataFrame({'col':L})
print (df)
col
0 Thanks You
1 Its fine no problem
2 Are you sure
df = pd.DataFrame({'oldcol':[1,2,3]})
#add column to existing df
df['col'] = L
print (df)
oldcol col
0 1 Thanks You
1 2 Its fine no problem
2 3 Are you sure
Thank you DYZ:
#default column name 0
df = pd.DataFrame(L)
print (df)
0
0 Thanks You
1 Its fine no problem
2 Are you sure
$broadcast
or $emit
.If the remote branch already exists then you can (probably) get away with..
git checkout branch_name
and git will automatically set up to track the remote branch with the same name on origin.
Don't you try it with that program? It'll goto finally block and executing the finally block, but, the exception won't be handled. But, that exception can be overruled in the finally block!
Unicode is a standard which maps the characters in all languages to a particular numeric value called Code Points. The reason it does this is that it allows different encodings to be possible using the same set of code points.
UTF-8 and UTF-16 are two such encodings. They take code points as input and encodes them using some well-defined formula to produce the encoded string.
Choosing a particular encoding depends upon your requirements. Different encodings have different memory requirements and depending upon the characters that you will be dealing with, you should choose the encoding which uses the least sequences of bytes to encode those characters.
For more in-depth details about Unicode, UTF-8 and UTF-16, you can check out this article,
Select the datecolumn of month so that u can get only one row per link, e.g.:
select link, min(datecolumn) from posted WHERE ad='$key' ORDER BY day, month
Good luck............
Or
u if you have date column as timestamp convert the format to date and perform distinct on link so that you can get distinct link values based on date instead datetime
The psql \o
command was already described by jhwist.
An alternative approach is using the COPY TO
command to write directly to a file on the server. This has the advantage that it's dumped in an easy-to-parse format of your choice -- rather than psql's tabulated format. It's also very easy to import to another table/database using COPY FROM
.
NB! This requires superuser privileges and will write to a file on the server.
Example: COPY (SELECT foo, bar FROM baz) TO '/tmp/query.csv' (format csv, delimiter ';')
Creates a CSV file with ';' as the field separator.
As always, see the documentation for details
There is also an undocumented utility class sun.net.util.IPAddressUtil
, which you should not actually use, although it might be useful in a quick one-off, throw-away utility:
boolean isIP = IPAddressUtil.isIPv4LiteralAddress(ipAddressString);
Internally, this is the utility class InetAddress
uses to parse IP addresses.
Note that this will return true for strings like "123", which, technically are valid IPv4 addresses, just not in dot-decimal notation.
You need to make sure that a mac compatible version of java exists on your computer. Do java -version from terminal to check that. If not, download the apple jdk from the apple website. (Sun doesn't make one for apple themselves, IIRC.)
From there, follow the same command line instructions from compiling your program that you would use for java on any other platform.
On the face of it, it looks okay - if you call eraseCookie()
on each cookie that is read from document.cookie
, then all of your cookies will be gone.
Try this:
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
eraseCookie(cookies[i].split("=")[0]);
All of this with the following caveat:
I know this is an old question, and most people have replied with good answers. But for reference and hopefully saving somebody else's time. Check if your function:
$(document).ready(function(){}
is being called after you have loaded the JQuery library
Have you tried:
Dim result As String
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("Data")
result = Application.WorksheetFunction.VLookup(sheet.Range("AN2"), sheet.Range("AA9:AF20"), 5, False)
small remark: I am using modules in webbased application (asp.net). I need to remember that everything I store in the variables on the module are seen by everyone in the application, read website. Not only in my session. If i try to add up a calculation in my session I need to make an array to filter the numbers for my session and for others. Modules is a great way to work but need concentration on how to use it.
To help against mistakes: classes are send to the
CarbageCollector
when the page is finished. My modules stay alive (as long as the application is not ended or restarted) and I can reuse the data in it. I use this to save data that sometimes is lost because of the sessionhandling by IIS.
IIS Form auth
and
IIS_session
are not in sync, and with my module I pull back data that went over de cliff.
There is many way to do this.
1. Using MediaQuery : Its return fullscreen of your device including appbar,toolbar
Container(
width: MediaQuery.of(context).size.width * 0.50,
height: MediaQuery.of(context).size.height*0.50,
color: Colors.blueAccent[400],
)
2. Using Expanded : You can set width/height in ratio
Container(
height: MediaQuery.of(context).size.height * 0.50,
child: Row(
children: <Widget>[
Expanded(
flex: 70,
child: Container(
color: Colors.lightBlue[400],
),
),
Expanded(
flex: 30,
child: Container(
color: Colors.deepPurple[800],
),
)
],
),
)
3. Others Like Flexible and AspectRatio and FractionallySizedBox
[edited]
using your comment about productCode (and assuming product code is a String) as reference...
for(Product p : productList){
s.put(p.getProductCode() , p);
}
STATICFILES_DIRS
: You can keep the static files for your project here e.g. the ones used by your templates.
STATIC_ROOT
: leave this empty, when you do manage.py collectstatic
, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.
--------Edit----------------
As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
or
STATIC_ROOT = '/opt/web/project/static_files'
--------End Edit -----------------
STATIC_URL
: '/static/' is usually fine, it's just a prefix for static files.
Did you check the Configuration manager settings? In the project settings dialog top right corner.
Sometimes it happens that between all the release entries a debug entry comes in. If so, the auto dependency created by the dependency graph of the solution gets all confused.
in my case error was because of using incorrect host value was
var options = {
host: 'graph.facebook.com/v2.12/',
path: path
}
should be
var options = {
host: 'graph.facebook.com',
path: path
}
so anything after .com or .net etc should be moved to path parameter value
I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).
This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.
So this is in our LocalSSLSocketFactory:
static {
try {
SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
} catch (KeyManagementException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
}
}
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });
return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}
Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.
Modern way:
newParent.append(...oldParent.childNodes);
.append
is the replacement for .appendChild
. The main difference is that it accepts multiple nodes at once and even plain strings, like .append('hello!')
oldParent.childNodes
is iterable so it can be spread with ...
to become multiple parameters of .append()
Compatibility tables of both (in short: Edge 17+, Safari 10+):
Simple implementation of BST in Python
class TreeNode:
def __init__(self, value):
self.left = None
self.right = None
self.data = value
class Tree:
def __init__(self):
self.root = None
def addNode(self, node, value):
if(node==None):
self.root = TreeNode(value)
else:
if(value<node.data):
if(node.left==None):
node.left = TreeNode(value)
else:
self.addNode(node.left, value)
else:
if(node.right==None):
node.right = TreeNode(value)
else:
self.addNode(node.right, value)
def printInorder(self, node):
if(node!=None):
self.printInorder(node.left)
print(node.data)
self.printInorder(node.right)
def main():
testTree = Tree()
testTree.addNode(testTree.root, 200)
testTree.addNode(testTree.root, 300)
testTree.addNode(testTree.root, 100)
testTree.addNode(testTree.root, 30)
testTree.printInorder(testTree.root)
I've been using @AndrewMarshall answer for a long time, but found some edge cases. The following tests doesn't pass:
equals(roundUp(9.69545, 4), 9.6955);
equals(roundUp(37.760000000000005, 4), 37.76);
equals(roundUp(5.83333333, 4), 5.8333);
Here is what I now use to have round up behave correctly:
// Closure
(function() {
/**
* Decimal adjustment of a number.
*
* @param {String} type The type of adjustment.
* @param {Number} value The number.
* @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).
* @returns {Number} The adjusted value.
*/
function decimalAdjust(type, value, exp) {
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// If the value is negative...
if (value < 0) {
return -decimalAdjust(type, -value, exp);
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}
// Decimal round
if (!Math.round10) {
Math.round10 = function(value, exp) {
return decimalAdjust('round', value, exp);
};
}
// Decimal floor
if (!Math.floor10) {
Math.floor10 = function(value, exp) {
return decimalAdjust('floor', value, exp);
};
}
// Decimal ceil
if (!Math.ceil10) {
Math.ceil10 = function(value, exp) {
return decimalAdjust('ceil', value, exp);
};
}
})();
// Round
Math.round10(55.55, -1); // 55.6
Math.round10(55.549, -1); // 55.5
Math.round10(55, 1); // 60
Math.round10(54.9, 1); // 50
Math.round10(-55.55, -1); // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1); // -50
Math.round10(-55.1, 1); // -60
Math.round10(1.005, -2); // 1.01 -- compare this with Math.round(1.005*100)/100 above
Math.round10(-1.005, -2); // -1.01
// Floor
Math.floor10(55.59, -1); // 55.5
Math.floor10(59, 1); // 50
Math.floor10(-55.51, -1); // -55.6
Math.floor10(-51, 1); // -60
// Ceil
Math.ceil10(55.51, -1); // 55.6
Math.ceil10(51, 1); // 60
Math.ceil10(-55.59, -1); // -55.5
Math.ceil10(-59, 1); // -50
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
The compiler must provide a consistent type system, and provide a set of standard conversions. Neither the integer value 0 nor the NULL pointer need to be represented by all-zero bits, but the compiler must take care of converting the "0" token in the input file to the correct representation for integer zero, and the cast to pointer type must convert from integer to pointer representation.
The implication of this is that
void *p;
memset(&p, 0, sizeof p);
if(p) { ... }
is not guaranteed to behave the same on all target systems, as you are making an assumption about the bit pattern here.
As an example, I have an embedded platform that has no memory protection, and keeps the interrupt vectors at address 0, so by convention, integers and pointers are XORed with 0x2000000 when converted, which leaves (void *)0 pointing at an address that generates a bus error when dereferenced, however testing the pointer with an if
statement will return it to integer representation first, which is then all-zeros.
A more modern way is to use flexbox:
ul{_x000D_
list-style-type:none;_x000D_
display:flex;_x000D_
justify-content: center;_x000D_
_x000D_
}_x000D_
ul li{_x000D_
display: list-item;_x000D_
background: black;_x000D_
padding: 5px 10px;_x000D_
color:white;_x000D_
margin: 0 3px;_x000D_
}_x000D_
div{_x000D_
background: wheat;_x000D_
}
_x000D_
<div>_x000D_
<ul>_x000D_
<li>One</li>_x000D_
<li>Two</li>_x000D_
<li>Three</li>_x000D_
</ul> _x000D_
_x000D_
</div>
_x000D_
For my answer, it is worth remembering that the TPL (Task-Parallel-Library), Task
class and TaskStatus
enumeration were introduced prior to the async-await keywords and the async-await keywords were not the original motivation of the TPL.
In the context of methods marked as async
, the resulting Task
is not a Task
representing the execution of the method, but a Task
for the continuation of the method.
This is only able to make use of a few possible states:
I understand that Running
could appear to have been a better default than WaitingForActivation
, however this could be misleading, as the majority of the time, an async method being executed is not actually running (i.e. it may be await
-ing something else). The other option may have been to add a new value to TaskStatus
, however this could have been a breaking change for existing applications and libraries.
All of this is very different to when making use of Task.Run
which is a part of the original TPL, this is able to make use of all the possible values of the TaskStatus
enumeration.
If you wish to keep track of the status of an async method, take a look at the IProgress(T)
interface, this will allow you to report the ongoing progress. This blog post, Async in 4.5: Enabling Progress and Cancellation in Async APIs will provide further information on the use of the IProgress(T)
interface.
I too found this perplexing. I'm running Ubuntu 18 and found the following: If the cv.imshow window has focus, you'll get one set of values in the terminal - like the ASCII values discussed above.
If the Terminal has focus, you'll see different values. IE- you'll see "a" when you press the a key (instead of ASCII value 97) and "^]" instead of "27" when you press Escape.
I didn't see the 6 digit numbers mentioned above in either case and I used similar code. It seems the value for waitKey is the polling period in mS. The dots illustrate this.
Run this snippet and press keys while focus is on the test image, then click on the terminal window and press the same keys.
import cv2
img = cv2.imread('test.jpg')
cv2.imshow('Your test image', img)
while(1):
k = cv2.waitKey(300)
if k == 27:
break
elif k==-1:
print "."
continue
else:
print k
You can configure a proxy with conda by adding it to the .condarc
, like
proxy_servers:
http: http://user:[email protected]:8080
https: https://user:[email protected]:8080
or set the HTTP_PROXY
and HTTPS_PROXY
environment variables. Note that in your case you need to add the scheme to the proxy url, like https://proxy-us.bla.com:123.
See http://conda.pydata.org/docs/config.html#configure-conda-for-use-behind-a-proxy-server.
After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter
to a separate sheet.
With .Range("A1:A" & LastRow)
.Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
.Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
Sheets("Sheet2").activate
DestinationRange.PasteSpecial
End With
In this block, the AutoFilter
finds all of the rows that contain the value of strSearch
and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.
thx Pentium10 - you made me join stackoverflow :) - this is my porting to msaccess - think it'll work on any version:
SELECT date_value
FROM (SELECT a.espr1+(10*b.espr1)+(100*c.espr1) AS integer_value,
dateadd("d",integer_value,dateserial([start_year], [start_month], [start_day])) as date_value
FROM (select * from
(
select top 1 "0" as espr1 from MSysObjects
union all
select top 1 "1" as espr2 from MSysObjects
union all
select top 1 "2" as espr3 from MSysObjects
union all
select top 1 "3" as espr4 from MSysObjects
union all
select top 1 "4" as espr5 from MSysObjects
union all
select top 1 "5" as espr6 from MSysObjects
union all
select top 1 "6" as espr7 from MSysObjects
union all
select top 1 "7" as espr8 from MSysObjects
union all
select top 1 "8" as espr9 from MSysObjects
union all
select top 1 "9" as espr9 from MSysObjects
) as a,
(
select top 1 "0" as espr1 from MSysObjects
union all
select top 1 "1" as espr2 from MSysObjects
union all
select top 1 "2" as espr3 from MSysObjects
union all
select top 1 "3" as espr4 from MSysObjects
union all
select top 1 "4" as espr5 from MSysObjects
union all
select top 1 "5" as espr6 from MSysObjects
union all
select top 1 "6" as espr7 from MSysObjects
union all
select top 1 "7" as espr8 from MSysObjects
union all
select top 1 "8" as espr9 from MSysObjects
union all
select top 1 "9" as espr9 from MSysObjects
) as b,
(
select top 1 "0" as espr1 from MSysObjects
union all
select top 1 "1" as espr2 from MSysObjects
union all
select top 1 "2" as espr3 from MSysObjects
union all
select top 1 "3" as espr4 from MSysObjects
union all
select top 1 "4" as espr5 from MSysObjects
union all
select top 1 "5" as espr6 from MSysObjects
union all
select top 1 "6" as espr7 from MSysObjects
union all
select top 1 "7" as espr8 from MSysObjects
union all
select top 1 "8" as espr9 from MSysObjects
union all
select top 1 "9" as espr9 from MSysObjects
) as c
) as d)
WHERE date_value
between dateserial([start_year], [start_month], [start_day])
and dateserial([end_year], [end_month], [end_day]);
referenced MSysObjects just 'cause access need a table countin' at least 1 record, in a from clause - any table with at least 1 record would do.
// The integer I want to convert
int myInt = 100;
// Casting of integer to float
float newFloat = (float) myInt
You can try this:
Me.cbo1.Text = Me.Cbo1.Items(0).Tostring
I was trying to do the same thing. While background-color and background-image exist on separate layers within an object -- meaning they can co-exist -- CSS gradients seem to co-opt the background-image layer.
From what I can tell, border-image seems to have wider support than multiple backgrounds, so maybe that's an alternative approach.
http://articles.sitepoint.com/article/css3-border-images
UPDATE: A bit more research. Seems Petra Gregorova has something working here --> http://petragregorova.com/demos/css-gradient-and-bg-image-final.html
You can use the -notmatch operator to get the lines that don't have the characters you are interested in.
Get-Content $FileName | foreach-object {
if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }
I had the same problem and I solved by using the postcast server. You can install it locally and use it.
fn + shift + leftArrow = goto beginning of line
fn + shift + rightArrow = goto end of line
these work for me
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
Use .form-inline = This will left-align labels and inline-block controls for a compact layout
Example: http://jsfiddle.net/hSuy4/292/
<div class="form-inline">
<input type="text">
<input type="button" class="btn" value="submit">
</div>
.form-horizontal = Right align labels and float them to the left to make them appear on the same line as controls which is better for 2 column form layout.
(e.g.
Label 1: [textbox]
Label 2: [textbox]
: [button]
)
Examples: http://twitter.github.io/bootstrap/base-css.html#forms
The following worked for me
const conString = "postgres://YourUserName:YourPassword@YourHostname:5432/YourDatabaseName";
Python really tries hard to intelligently set sys.path
. How it is
set can get really complicated. The following guide is a watered-down,
somewhat-incomplete, somewhat-wrong, but hopefully-useful guide
for the rank-and-file python programmer of what happens when python
figures out what to use as the initial values of sys.path
,
sys.executable
, sys.exec_prefix
, and sys.prefix
on a normal
python installation.
First, python does its level best to figure out its actual physical
location on the filesystem based on what the operating system tells
it. If the OS just says "python" is running, it finds itself in $PATH.
It resolves any symbolic links. Once it has done this, the path of
the executable that it finds is used as the value for sys.executable
, no ifs,
ands, or buts.
Next, it determines the initial values for sys.exec_prefix
and
sys.prefix
.
If there is a file called pyvenv.cfg
in the same directory as
sys.executable
or one directory up, python looks at it. Different
OSes do different things with this file.
One of the values in this config file that python looks for is
the configuration option home = <DIRECTORY>
. Python will use this directory instead of the directory containing sys.executable
when it dynamically sets the initial value of sys.prefix
later. If the applocal = true
setting appears in the
pyvenv.cfg
file on Windows, but not the home = <DIRECTORY>
setting,
then sys.prefix
will be set to the directory containing sys.executable
.
Next, the PYTHONHOME
environment variable is examined. On Linux and Mac,
sys.prefix
and sys.exec_prefix
are set to the PYTHONHOME
environment variable, if
it exists, superseding any home = <DIRECTORY>
setting in pyvenv.cfg
. On Windows,
sys.prefix
and sys.exec_prefix
is set to the PYTHONHOME
environment variable,
if it exists, unless a home = <DIRECTORY>
setting is present in pyvenv.cfg
,
which is used instead.
Otherwise, these sys.prefix
and sys.exec_prefix
are found by walking backwards
from the location of sys.executable
, or the home
directory given by pyvenv.cfg
if any.
If the file lib/python<version>/dyn-load
is found in that directory
or any of its parent directories, that directory is set to be to be
sys.exec_prefix
on Linux or Mac. If the file
lib/python<version>/os.py
is is found in the directory or any of its
subdirectories, that directory is set to be sys.prefix
on Linux,
Mac, and Windows, with sys.exec_prefix
set to the same value as
sys.prefix
on Windows. This entire step is skipped on Windows if
applocal = true
is set. Either the directory of sys.executable
is
used or, if home
is set in pyvenv.cfg
, that is used instead for
the initial value of sys.prefix
.
If it can't find these "landmark" files or sys.prefix
hasn't been
found yet, then python sets sys.prefix
to a "fallback"
value. Linux and Mac, for example, use pre-compiled defaults as the
values of sys.prefix
and sys.exec_prefix
. Windows waits
until sys.path
is fully figured out to set a fallback value for
sys.prefix
.
Then, (what you've all been waiting for,) python determines the initial values
that are to be contained in sys.path
.
sys.path
.
On Windows, this is always the empty string, which tells python to
use the full path where the script is located instead.sys.path
, unless you're
on Windows and applocal
is set to true in pyvenv.cfg
.<prefix>/lib/python35.zip
on Linux/Mac and
os.path.join(os.dirname(sys.executable), "python.zip")
on Windows, is added to sys.path
.applocal = true
was set in pyvenv.cfg
, then the contents of the subkeys of the registry key
HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
are added, if any.applocal = true
was set in pyvenv.cfg
, and sys.prefix
could not be found,
then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
is added, if it exists;applocal = true
was set in pyvenv.cfg
, then the contents of the subkeys of the registry key
HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\
are added, if any.applocal = true
was set in pyvenv.cfg
, and sys.prefix
could not be found,
then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
is added, if it exists;sys.prefix
.sys.exec_prefix
is added. On Windows, the directory
which was used (or would have been used) to search dynamically for sys.prefix
is
added.At this stage on Windows, if no prefix was found, then python will try to
determine it by searching all the directories in sys.path
for the landmark files,
as it tried to do with the directory of sys.executable
previously, until it finds something.
If it doesn't, sys.prefix
is left blank.
Finally, after all this, Python loads the site
module, which adds stuff yet further to sys.path
:
It starts by constructing up to four directories from a head and a tail part. For the head part, it uses
sys.prefix
andsys.exec_prefix
; empty heads are skipped. For the tail part, it uses the empty string and thenlib/site-packages
(on Windows) orlib/pythonX.Y/site-packages
and thenlib/site-python
(on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.
it is better to use json after post your resuest like below
var clien = new RestClient("https://smple.com/");
var request = new RestRequest("index", Method.POST);
request.AddHeader("Sign", signinstance);
request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
var response = client.Execute<YourReturnclassSample>(request);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
return Ok(response.Content);
}
I wanted to bind a particular data to dropdown and it should be distinct. I did the following:
List<ClassDetails> classDetails;
List<string> classDetailsData = classDetails.Select(dt => dt.Data).Distinct.ToList();
ddlData.DataSource = classDetailsData;
ddlData.Databind();
See if it helps
Actually an enum
's default is the first element in the enum
whose value is 0
.
So for example:
public enum Animals
{
Cat,
Dog,
Pony = 0,
}
//its value will actually be Cat not Pony unless you assign a non zero value to Cat.
Animals animal;
The existing answers all seem to run this script in a DOS console window.
This may be acceptable, but for example means that colour codes (changing text colour) don't work but instead get printed out as they are:
there is no item "[032mGroovy[0m"
I found this solution some time ago, so I'm not sure whether mintty.exe
is a standard Cygwin utility or whether you have to run the setup
program to get it, but I run like this:
D:\apps\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico bash.exe .\myShellScript.sh
... this causes the script to run in a Cygwin BASH console instead of a Windows DOS console.
Another example:
[2,4,8].splice(1, 2) -> returns [4, 8], original array is [2]
[2,4,8].slice(1, 2) -> returns 4, original array is [2,4,8]
Here is my function
char *fileName = "input-1.txt";
countOfLinesFromFile(fileName);
void countOfLinesFromFile(char *filename){
FILE* myfile = fopen(filename, "r");
int ch, number_of_lines = 0;
do
{
ch = fgetc(myfile);
if(ch == '\n')
number_of_lines++;
}
while (ch != EOF);
if(ch != '\n' && number_of_lines != 0)
number_of_lines++;
fclose(myfile);
printf("number of lines in %s = %d",filename, number_of_lines);
}
You can wait until the body is ready:
function onReady(callback) {_x000D_
var intervalId = window.setInterval(function() {_x000D_
if (document.getElementsByTagName('body')[0] !== undefined) {_x000D_
window.clearInterval(intervalId);_x000D_
callback.call(this);_x000D_
}_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
function setVisible(selector, visible) {_x000D_
document.querySelector(selector).style.display = visible ? 'block' : 'none';_x000D_
}_x000D_
_x000D_
onReady(function() {_x000D_
setVisible('.page', true);_x000D_
setVisible('#loading', false);_x000D_
});
_x000D_
body {_x000D_
background: #FFF url("https://i.imgur.com/KheAuef.png") top left repeat-x;_x000D_
font-family: 'Alex Brush', cursive !important;_x000D_
}_x000D_
_x000D_
.page { display: none; padding: 0 0.5em; }_x000D_
.page h1 { font-size: 2em; line-height: 1em; margin-top: 1.1em; font-weight: bold; }_x000D_
.page p { font-size: 1.5em; line-height: 1.275em; margin-top: 0.15em; }_x000D_
_x000D_
#loading {_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: 100;_x000D_
width: 100vw;_x000D_
height: 100vh;_x000D_
background-color: rgba(192, 192, 192, 0.5);_x000D_
background-image: url("https://i.stack.imgur.com/MnyxU.gif");_x000D_
background-repeat: no-repeat;_x000D_
background-position: center;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>_x000D_
<link href="https://fonts.googleapis.com/css?family=Alex+Brush" rel="stylesheet">_x000D_
<div class="page">_x000D_
<h1>The standard Lorem Ipsum passage</h1>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
<div id="loading"></div>
_x000D_
Here is a JSFiddle that demonstrates this technique.
window.onload = function() {
... etc. is not a great answer.
This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours. So, you can spend lots of hours later trying to figure out why something that was working isn't anymore.
A more robust answer here:
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
yourFunctionName(evt);
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
Some code I have been using, I forget where I found it to give the author credit.
function my_function() {
// whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}
Hope this helps :)
In v4 change the SASS variable:
$font-size-base: 1rem !default;
My answer is inspired by Jeffrey's answer. Where that answer gives a more abstract solution, I try to provide more concrete steps on how to potentially implement it. This is simply a guide, one that can be implemented more elegantly. For a more detailed example check out this tutorial by MDN web docs.
HTML:
<div id="zoom_here">....</div>
JS
<script>
var dist1=0;
function start(ev) {
if (ev.targetTouches.length == 2) {//check if two fingers touched screen
dist1 = Math.hypot( //get rough estimate of distance between two fingers
ev.touches[0].pageX - ev.touches[1].pageX,
ev.touches[0].pageY - ev.touches[1].pageY);
}
}
function move(ev) {
if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) {
// Check if the two target touches are the same ones that started
var dist2 = Math.hypot(//get rough estimate of new distance between fingers
ev.touches[0].pageX - ev.touches[1].pageX,
ev.touches[0].pageY - ev.touches[1].pageY);
//alert(dist);
if(dist1>dist2) {//if fingers are closer now than when they first touched screen, they are pinching
alert('zoom out');
}
if(dist1<dist2) {//if fingers are further apart than when they first touched the screen, they are making the zoomin gesture
alert('zoom in');
}
}
}
document.getElementById ('zoom_here').addEventListener ('touchstart', start, false);
document.getElementById('zoom_here').addEventListener('touchmove', move, false);
</script>
You just need to wrap items with linear layouts which have layout_weight. To have items horizontally separated, use this
<LinearLayout
...
...
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
// your item
</LinearLayout>
</LinearLayout>
Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.
{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li> {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}
I think this is a simple code in java which will show the string value in CSV after compile this code.
public class CsvWriter {
public static void main(String args[]) {
// File input path
System.out.println("Starting....");
File file = new File("/home/Desktop/test/output.csv");
try {
FileWriter output = new FileWriter(file);
CSVWriter write = new CSVWriter(output);
// Header column value
String[] header = { "ID", "Name", "Address", "Phone Number" };
write.writeNext(header);
// Value
String[] data1 = { "1", "First Name", "Address1", "12345" };
write.writeNext(data1);
String[] data2 = { "2", "Second Name", "Address2", "123456" };
write.writeNext(data2);
String[] data3 = { "3", "Third Name", "Address3", "1234567" };
write.writeNext(data3);
write.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println("End.");
}
}
Using the following 1 line command for changing many files name in linux using phrase specificity:
find -type f -name '*.jpg' | rename 's/holiday/honeymoon/'
For all files with the extension ".jpg", if they contain the string "holiday", replace it with "honeymoon". For instance, this command would rename the file "ourholiday001.jpg" to "ourhoneymoon001.jpg".
This example also illustrates how to use the find command to send a list of files (-type f) with the extension .jpg (-name '*.jpg') to rename via a pipe (|). rename then reads its file list from standard input.
Not a regexp expert, but I think you could use a negative lookahead from the start, e.g. ^(?!foo).*$
shouldn't match anything starting with foo
.
<target name="check-abc">
<available file="abc.txt" property="abc.present"/>
</target>
<target name="do-if-abc" depends="check-abc" if="abc.present">
...
</target>
You could use multiple approaches and see if they converge to the same answer. Or grab some from the 'net. The Chudnovsky algorithm is usually used as a very fast method of calculating pi. http://www.craig-wood.com/nick/articles/pi-chudnovsky/
You should write textcolor in xml as
android:textColor="@color/text_color"
or
android:textColor="#FFFFFF"
I think the main difference I can describe relates to record oriented vs. column oriented formats. Record oriented formats are what we're all used to -- text files, delimited formats like CSV, TSV. AVRO is slightly cooler than those because it can change schema over time, e.g. adding or removing columns from a record. Other tricks of various formats (especially including compression) involve whether a format can be split -- that is, can you read a block of records from anywhere in the dataset and still know it's schema? But here's more detail on columnar formats like Parquet.
Parquet, and other columnar formats handle a common Hadoop situation very efficiently. It is common to have tables (datasets) having many more columns than you would expect in a well-designed relational database -- a hundred or two hundred columns is not unusual. This is so because we often use Hadoop as a place to denormalize data from relational formats -- yes, you get lots of repeated values and many tables all flattened into a single one. But it becomes much easier to query since all the joins are worked out. There are other advantages such as retaining state-in-time data. So anyway it's common to have a boatload of columns in a table.
Let's say there are 132 columns, and some of them are really long text fields, each different column one following the other and use up maybe 10K per record.
While querying these tables is easy with SQL standpoint, it's common that you'll want to get some range of records based on only a few of those hundred-plus columns. For example, you might want all of the records in February and March for customers with sales > $500.
To do this in a row format the query would need to scan every record of the dataset. Read the first row, parse the record into fields (columns) and get the date and sales columns, include it in your result if it satisfies the condition. Repeat. If you have 10 years (120 months) of history, you're reading every single record just to find 2 of those months. Of course this is a great opportunity to use a partition on year and month, but even so, you're reading and parsing 10K of each record/row for those two months just to find whether the customer's sales are > $500.
In a columnar format, each column (field) of a record is stored with others of its kind, spread all over many different blocks on the disk -- columns for year together, columns for month together, columns for customer employee handbook (or other long text), and all the others that make those records so huge all in their own separate place on the disk, and of course columns for sales together. Well heck, date and months are numbers, and so are sales -- they are just a few bytes. Wouldn't it be great if we only had to read a few bytes for each record to determine which records matched our query? Columnar storage to the rescue!
Even without partitions, scanning the small fields needed to satisfy our query is super-fast -- they are all in order by record, and all the same size, so the disk seeks over much less data checking for included records. No need to read through that employee handbook and other long text fields -- just ignore them. So, by grouping columns with each other, instead of rows, you can almost always scan less data. Win!
But wait, it gets better. If your query only needed to know those values and a few more (let's say 10 of the 132 columns) and didn't care about that employee handbook column, once it had picked the right records to return, it would now only have to go back to the 10 columns it needed to render the results, ignoring the other 122 of the 132 in our dataset. Again, we skip a lot of reading.
(Note: for this reason, columnar formats are a lousy choice when doing straight transformations, for example, if you're joining all of two tables into one big(ger) result set that you're saving as a new table, the sources are going to get scanned completely anyway, so there's not a lot of benefit in read performance, and because columnar formats need to remember more about the where stuff is, they use more memory than a similar row format).
One more benefit of columnar: data is spread around. To get a single record, you can have 132 workers each read (and write) data from/to 132 different places on 132 blocks of data. Yay for parallelization!
And now for the clincher: compression algorithms work much better when it can find repeating patterns. You could compress AABBBBBBCCCCCCCCCCCCCCCC
as 2A6B16C
but ABCABCBCBCBCCCCCCCCCCCCCC
wouldn't get as small (well, actually, in this case it would, but trust me :-) ). So once again, less reading. And writing too.
So we read a lot less data to answer common queries, it's potentially faster to read and write in parallel, and compression tends to work much better.
Columnar is great when your input side is large, and your output is a filtered subset: from big to little is great. Not as beneficial when the input and outputs are about the same.
But in our case, Impala took our old Hive queries that ran in 5, 10, 20 or 30 minutes, and finished most in a few seconds or a minute.
Hope this helps answer at least part of your question!
I'm writing this answer in 2015, and for some reason (probably older versions of jQuery) none of the other answers have worked for me. I mean, they change the selected index, but it doesn't actually reflect on the actual dropdown.
Here is another way to change the index, and actually have it reflect in the dropdown:
$('#mydropdown').val('first').change();
Try adding these two lines to your code. I hope it will work. It worked for me :)
display.setLineWrap(true);
display.setWrapStyleWord(true);
Picture of output is shown below
<input type="text" disabled="disabled" />
is the valid markup.<input type="text" disabled />
is valid and used by W3C on their samples.I have exactly the same issue as above, and took me the whole day to discover that it doesn't like my newline approach. Instead I reused the same code with semi-colon approach instead. For example my initial code using the newline (which threw the same error as yours):
Y=1
while test "$Y" -le "20"
do
echo "Number $Y"
Y=$[Y+1]
done
And using code with semicolon approach with worked wonder:
Y=1 ; while test "$Y" -le "20"; do echo "Number $Y"; Y=$[Y+1] ; done
I notice the same problem occurs for other commands as well using the newline approach, so I think I am gonna stick to using semicolon for my future code.
You can use the CSS property max-width
and use it with ch
unit.
And, as this is a <span>
, use a display: inline-block;
(or block).
Here is an example:
<span style="
display:inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 13ch;">
Lorem ipsum dolor sit amet
</span>
Which outputs:
Lorem ipsum...
<span style="_x000D_
display:inline-block;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
max-width: 13ch;">_x000D_
Lorem ipsum dolor sit amet_x000D_
</span>
_x000D_
Window functions:
Something like this should do the trick:
import org.apache.spark.sql.functions.{row_number, max, broadcast}
import org.apache.spark.sql.expressions.Window
val df = sc.parallelize(Seq(
(0,"cat26",30.9), (0,"cat13",22.1), (0,"cat95",19.6), (0,"cat105",1.3),
(1,"cat67",28.5), (1,"cat4",26.8), (1,"cat13",12.6), (1,"cat23",5.3),
(2,"cat56",39.6), (2,"cat40",29.7), (2,"cat187",27.9), (2,"cat68",9.8),
(3,"cat8",35.6))).toDF("Hour", "Category", "TotalValue")
val w = Window.partitionBy($"hour").orderBy($"TotalValue".desc)
val dfTop = df.withColumn("rn", row_number.over(w)).where($"rn" === 1).drop("rn")
dfTop.show
// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// | 0| cat26| 30.9|
// | 1| cat67| 28.5|
// | 2| cat56| 39.6|
// | 3| cat8| 35.6|
// +----+--------+----------+
This method will be inefficient in case of significant data skew.
Plain SQL aggregation followed by join
:
Alternatively you can join with aggregated data frame:
val dfMax = df.groupBy($"hour".as("max_hour")).agg(max($"TotalValue").as("max_value"))
val dfTopByJoin = df.join(broadcast(dfMax),
($"hour" === $"max_hour") && ($"TotalValue" === $"max_value"))
.drop("max_hour")
.drop("max_value")
dfTopByJoin.show
// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// | 0| cat26| 30.9|
// | 1| cat67| 28.5|
// | 2| cat56| 39.6|
// | 3| cat8| 35.6|
// +----+--------+----------+
It will keep duplicate values (if there is more than one category per hour with the same total value). You can remove these as follows:
dfTopByJoin
.groupBy($"hour")
.agg(
first("category").alias("category"),
first("TotalValue").alias("TotalValue"))
Using ordering over structs
:
Neat, although not very well tested, trick which doesn't require joins or window functions:
val dfTop = df.select($"Hour", struct($"TotalValue", $"Category").alias("vs"))
.groupBy($"hour")
.agg(max("vs").alias("vs"))
.select($"Hour", $"vs.Category", $"vs.TotalValue")
dfTop.show
// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// | 0| cat26| 30.9|
// | 1| cat67| 28.5|
// | 2| cat56| 39.6|
// | 3| cat8| 35.6|
// +----+--------+----------+
With DataSet API (Spark 1.6+, 2.0+):
Spark 1.6:
case class Record(Hour: Integer, Category: String, TotalValue: Double)
df.as[Record]
.groupBy($"hour")
.reduce((x, y) => if (x.TotalValue > y.TotalValue) x else y)
.show
// +---+--------------+
// | _1| _2|
// +---+--------------+
// |[0]|[0,cat26,30.9]|
// |[1]|[1,cat67,28.5]|
// |[2]|[2,cat56,39.6]|
// |[3]| [3,cat8,35.6]|
// +---+--------------+
Spark 2.0 or later:
df.as[Record]
.groupByKey(_.Hour)
.reduceGroups((x, y) => if (x.TotalValue > y.TotalValue) x else y)
The last two methods can leverage map side combine and don't require full shuffle so most of the time should exhibit a better performance compared to window functions and joins. These cane be also used with Structured Streaming in completed
output mode.
Don't use:
df.orderBy(...).groupBy(...).agg(first(...), ...)
It may seem to work (especially in the local
mode) but it is unreliable (see SPARK-16207, credits to Tzach Zohar for linking relevant JIRA issue, and SPARK-30335).
The same note applies to
df.orderBy(...).dropDuplicates(...)
which internally uses equivalent execution plan.
The application I'm working on has to give the user the possibility to choose which fragments to display (fragments are dynamically changed at run-time). The best solution for me was to restart completely the application.
So I tried plenty of solutions and none of them has worked for me, but this:
final Intent mStartActivity = new Intent(SettingsActivity.this, Splash.class);
final int mPendingIntentId = 123456;
final PendingIntent mPendingIntent = PendingIntent.getActivity(SettingsActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
final AlarmManager mgr = (AlarmManager) SettingsActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
this.finishAffinity(); //notice here
Runtime.getRuntime().exit(0); //notice here
Hoping that is going to help someone else!
Your path should be like this : "http://websitedomain//folderpath/66.jpg">
<img src="http://websitedomain/folderpath/66.jpg" width="400" height="400" ></img>
You may use this type format (get formatted data from sql server)
FORMAT(convert(datetime,'16/04/2018 10:52:20',103),'dd/MM/yyyy HH:mm:ss', 'en-us')
CONVERT(VARCHAR,convert(datetime,'16/04/2018 10:52:20',103), 120)
By using the constraint definition on table creation, you can specify one or multiple constraints that span multiple columns. The syntax, simplified from technet's documentation, is in the form of:
CONSTRAINT constraint_name UNIQUE [ CLUSTERED | NONCLUSTERED ]
(
column [ ASC | DESC ] [ ,...n ]
)
Therefore, the resuting table definition would be:
CREATE TABLE [dbo].[user](
[userID] [int] IDENTITY(1,1) NOT NULL,
[fcode] [int] NULL,
[scode] [int] NULL,
[dcode] [int] NULL,
[name] [nvarchar](50) NULL,
[address] [nvarchar](50) NULL,
CONSTRAINT [PK_user_1] PRIMARY KEY CLUSTERED
(
[userID] ASC
),
CONSTRAINT [UQ_codes] UNIQUE NONCLUSTERED
(
[fcode], [scode], [dcode]
)
) ON [PRIMARY]
The Scanner should be closed. It is a good practice to close Readers, Streams...and this kind of objects to free up resources and aovid memory leaks; and doing so in a finally block to make sure that they are closed up even if an exception occurs while handling those objects.
I have recently implemented the receipt printing simply by pressing a button on a web page, without having to enter the printer options. I have done it using EPSON javascript SDK for ePOS. I have test it on EPSON TM-m30 receipt printer.
Here is the sample code.
var printer = null;
var ePosDev = null;
function InitMyPrinter() {
console.log("Init Printer");
var printerPort = 8008;
var printerAddress = "192.168.198.168";
if (isSSL) {
printerPort = 8043;
}
ePosDev = new epson.ePOSDevice();
ePosDev.connect(printerAddress, printerPort, cbConnect);
}
//Printing
function cbConnect(data) {
if (data == 'OK' || data == 'SSL_CONNECT_OK') {
ePosDev.createDevice('local_printer', ePosDev.DEVICE_TYPE_PRINTER,
{'crypto': false, 'buffer': false}, cbCreateDevice_printer);
} else {
console.log(data);
}
}
function cbCreateDevice_printer(devobj, retcode) {
if (retcode == 'OK') {
printer = devobj;
printer.timeout = 60000;
printer.onreceive = function (res) { //alert(res.success);
console.log("Printer Object Created");
};
printer.oncoveropen = function () { //alert('coveropen');
console.log("Printer Cover Open");
};
} else {
console.log(retcode);
isRegPrintConnected = false;
}
}
function print(salePrintObj) {
debugger;
if (isRegPrintConnected == false
|| printer == null) {
return;
}
console.log("Printing Started");
printer.addLayout(printer.LAYOUT_RECEIPT, 800, 0, 0, 0, 35, 0);
printer.addTextAlign(printer.ALIGN_CENTER);
printer.addTextSmooth(true);
printer.addText('\n');
printer.addText('\n');
printer.addTextDouble(true, true);
printer.addText(CompanyName + '\n');
printer.addTextDouble(false, false);
printer.addText(CompanyHeader + '\n');
printer.addText('\n');
printer.addTextAlign(printer.ALIGN_LEFT);
printer.addText('DATE: ' + currentDate + '\t\t');
printer.addTextAlign(printer.ALIGN_RIGHT);
printer.addText('TIME: ' + currentTime + '\n');
printer.addTextAlign(printer.ALIGN_LEFT);
printer.addTextAlign(printer.ALIGN_RIGHT);
printer.addText('REGISTER: ' + RegisterName + '\n');
printer.addTextAlign(printer.ALIGN_LEFT);
printer.addText('SALE # ' + SaleNumber + '\n');
printer.addTextAlign(printer.ALIGN_CENTER);
printer.addTextStyle(false, false, true, printer.COLOR_1);
printer.addTextStyle(false, false, false, printer.COLOR_1);
printer.addTextDouble(false, true);
printer.addText('* SALE RECEIPT *\n');
printer.addTextDouble(false, false);
....
....
....
}
I solved this problem by making sure that the value of JAVA_HOME was the folder location in English
C:\Program Files\Java\jdk1.8.0_31
rather than the folder location that one can see/explorer browse in my Windows7 - Portuguese installation
C:\Programas\Java\jdk1.8.0_31
Make use of the zfill()
helper method to left-pad any string, integer or float with zeros; it's valid for both Python 2.x and Python 3.x.
Sample usage:
print str(1).zfill(3);
# Expected output: 001
Description:
When applied to a value, zfill()
returns a value left-padded with zeros when the length of the initial string value less than that of the applied width value, otherwise, the initial string value as is.
Syntax:
str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.
For iOS 7 and above (Referring MKMapView.h) :
// Position the map such that the provided array of annotations are all visible to the fullest extent possible.
- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);
remark from – Abhishek Bedi
You just call:
[yourMapView showAnnotations:@[yourAnnotation] animated:YES];
<select class="dropdownmenu" name="drop-down">
<option class="dropdownmenu_list1" value="select-option">Choose ...</option>
<option class="dropdownmenu_list2" value="Topic 1">Option 1</option>
<option class="dropdownmenu_list3" value="Topic 2">Option 2</option>
</select>
This works best in Firefox. Too bad that Chrome and Safari do not support this rather easy CSS styling.
In Java Array Sizes are always of Fixed Length But there is way in which you can Dynamically increase the Size of the Array at Runtime Itself
This is the most "used" as well as preferred way to do it-
int temp[]=new int[stck.length+1];
for(int i=0;i<stck.length;i++)temp[i]=stck[i];
stck=temp;
In the above code we are initializing a new temp[] array, and further using a for loop to initialize the contents of the temp with the contents of the original array ie. stck[]. And then again copying it back to the original one, giving us a new array of new SIZE.
No doubt it generates a CPU Overhead due to reinitializing an array using for loop repeatedly. But you can still use and implement it in your code. For the best practice use "Linked List" instead of Array, if you want the data to be stored dynamically in the memory, of variable length.
Here's a Real-Time Example based on Dynamic Stacks to INCREASE ARRAY SIZE at Run-Time
File-name: DStack.java
public class DStack {
private int stck[];
int tos;
void Init_Stck(int size) {
stck=new int[size];
tos=-1;
}
int Change_Stck(int size){
return stck[size];
}
public void push(int item){
if(tos==stck.length-1){
int temp[]=new int[stck.length+1];
for(int i=0;i<stck.length;i++)temp[i]=stck[i];
stck=temp;
stck[++tos]=item;
}
else
stck[++tos]=item;
}
public int pop(){
if(tos<0){
System.out.println("Stack Underflow");
return 0;
}
else return stck[tos--];
}
public void display(){
for(int x=0;x<stck.length;x++){
System.out.print(stck[x]+" ");
}
System.out.println();
}
}
File-name: Exec.java
(with the main class)
import java.util.*;
public class Exec {
private static Scanner in;
public static void main(String[] args) {
in = new Scanner(System.in);
int option,item,i=1;
DStack obj=new DStack();
obj.Init_Stck(1);
do{
System.out.println();
System.out.println("--MENU--");
System.out.println("1. Push a Value in The Stack");
System.out.println("2. Pop a Value from the Stack");
System.out.println("3. Display Stack");
System.out.println("4. Exit");
option=in.nextInt();
switch(option){
case 1:
System.out.println("Enter the Value to be Pushed");
item=in.nextInt();
obj.push(item);
break;
case 2:
System.out.println("Popped Item: "+obj.pop());
obj.Change_Stck(obj.tos);
break;
case 3:
System.out.println("Displaying...");
obj.display();
break;
case 4:
System.out.println("Exiting...");
i=0;
break;
default:
System.out.println("Enter a Valid Value");
}
}while(i==1);
}
}
Hope this solves your query.
Verify that you can start your application like that:
java -cp myjarfile.jar snake.Controller
I just read when I double click on it - this sounds like a configuration issue with your operating system. You're double-clicking the file on a windows explorer window? Try to run it from a console/terminal with the command
java -jar myjarfile.jar
Further Reading
The manifest has to end with a new line. Please check your file, a missing new line will cause trouble.
I tried every method listed here and in Android adb devices unauthorized
What eventually worked for me was the option just below USB Debugging 'Revoke auths'
Sorry to be so late to the party! I came across a similar issue, in WinRT. I'm not sure whether you're using WPF or WinRT, but they do differ in some ways (some better than others). Hopefully this will help people across the board, whichever situation they're in.
You could always use the code from the converter class I created to re-use and do in your C# code-behind, or wherever you're using it, to be honest:
I made it with the intention that a 6-digit (RGB), or an 8-digit (ARGB) Hex value could be used either way.
So I created a converter class:
public class StringToSolidColorBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var hexString = (value as string).Replace("#", "");
if (string.IsNullOrWhiteSpace(hexString)) throw new FormatException();
if (hexString.Length != 6 || hexString.Length != 8) throw new FormatException();
try
{
var a = hexString.Length == 8 ? hexString.Substring(0, 2) : "255";
var r = hexString.Length == 8 ? hexString.Substring(2, 2) : hexString.Substring(0, 2);
var g = hexString.Length == 8 ? hexString.Substring(4, 2) : hexString.Substring(2, 2);
var b = hexString.Length == 8 ? hexString.Substring(6, 2) : hexString.Substring(4, 2);
return new SolidColorBrush(ColorHelper.FromArgb(
byte.Parse(a, System.Globalization.NumberStyles.HexNumber),
byte.Parse(r, System.Globalization.NumberStyles.HexNumber),
byte.Parse(g, System.Globalization.NumberStyles.HexNumber),
byte.Parse(b, System.Globalization.NumberStyles.HexNumber)));
}
catch
{
throw new FormatException();
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Added it into my App.xaml:
<ResourceDictionary>
...
<converters:StringToSolidColorBrushConverter x:Key="StringToSolidColorBrushConverter" />
...
</ResourceDictionary>
And used it in my View's Xaml:
<Grid>
<Rectangle Fill="{Binding RectangleColour,
Converter={StaticResource StringToSolidColorBrushConverter}}"
Height="20" Width="20" />
</Grid>
Works a charm!
Side note...
Unfortunately, WinRT hasn't got the System.Windows.Media.BrushConverter
that H.B. suggested; so I needed another way, otherwise I would have made a VM property that returned a SolidColorBrush
(or similar) from the RectangleColour
string property.
It might seem like a dirty hack.
grep "^\|highlight1\|highlight2\|highlight3" filename
Which means - match the beginning of the line(^) or highlight1 or highlight2 or highlight3. As a result, you will get highlighted all highlight* pattern matches, even in the same line.
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
Gson gson = new Gson();
JSONObject jsonObject = new JSONObject(s.toString());
String link = jsonObject.getString("Result");
You can't access Session
directly in JavaScript.
You can make a hidden field and pass it to your page and then use JavaScript to retrieve the object via document.getElementById
Install-Package System.Drawing.Common
Check if you don't have a ScrollView wrapping your Webview.
In my case that was the problem. It seems ScrollView gets in the way of the pinch gesture.
To fix it, just take your Webview outside the ScrollView.
String.format("Hello %s Please find attached %s which is due on %s", name, invoice, date)
We can add scroll bar even without using Canvas. I have read it in many other post we can't add vertical scroll bar in frame directly etc etc. But after doing many experiment found out way to add vertical as well as horizontal scroll bar :). Please find below code which is used to create scroll bar in treeView and frame.
f = Tkinter.Frame(self.master,width=3)
f.grid(row=2, column=0, columnspan=8, rowspan=10, pady=30, padx=30)
f.config(width=5)
self.tree = ttk.Treeview(f, selectmode="extended")
scbHDirSel =tk.Scrollbar(f, orient=Tkinter.HORIZONTAL, command=self.tree.xview)
scbVDirSel =tk.Scrollbar(f, orient=Tkinter.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scbVDirSel.set, xscrollcommand=scbHDirSel.set)
self.tree["columns"] = (self.columnListOutput)
self.tree.column("#0", width=40)
self.tree.heading("#0", text='SrNo', anchor='w')
self.tree.grid(row=2, column=0, sticky=Tkinter.NSEW,in_=f, columnspan=10, rowspan=10)
scbVDirSel.grid(row=2, column=10, rowspan=10, sticky=Tkinter.NS, in_=f)
scbHDirSel.grid(row=14, column=0, rowspan=2, sticky=Tkinter.EW,in_=f)
f.rowconfigure(0, weight=1)
f.columnconfigure(0, weight=1)
You have to give width:100%
to parent to center
the text.
.parent {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
position: absolute;_x000D_
width:100%_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">text</div>_x000D_
</div>
_x000D_
If you also need to centre align vertically, give height:100%
and align-itens: center
.parent {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
width:100%;
height: 100%;
}
You need to write a controller with ng-change
function in scope. In ng-change
callback you do a call to server and update completions. Here is a stub (without $http
as this is a plunk):
HTML
<!doctype html>
<html ng-app="plunker">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.4.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div class='container-fluid' ng-controller="TypeaheadCtrl">
<pre>Model: {{selected| json}}</pre>
<pre>{{states}}</pre>
<input type="text" ng-change="onedit()" ng-model="selected" typeahead="state for state in states | filter:$viewValue">
</div>
</body>
</html>
JS
angular.module('plunker', ['ui.bootstrap']);
function TypeaheadCtrl($scope) {
$scope.selected = undefined;
$scope.states = [];
$scope.onedit = function(){
$scope.states = [];
for(var i = 0; i < Math.floor((Math.random()*10)+1); i++){
var value = "";
for(var j = 0; j < i; j++){
value += j;
}
$scope.states.push(value);
}
}
}
You can manual disable ssl verfiy, and try again. :)
git config --global http.sslverify false
You can use string.punctuation
and any
function like this
import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
print "Invalid"
else:
print "Valid"
With this line
invalidChars = set(string.punctuation.replace("_", ""))
we are preparing a list of punctuation characters which are not allowed. As you want _
to be allowed, we are removing _
from the list and preparing new set as invalidChars
. Because lookups are faster in sets.
any
function will return True
if atleast one of the characters is in invalidChars
.
Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116
word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"
Yes! By passing a stream context in the third parameter:
Here with a timeout of 1s:
file_get_contents("https://abcedef.com", 0, stream_context_create(["http"=>["timeout"=>1]]));
Source in comment section of https://www.php.net/manual/en/function.file-get-contents.php
method
header
user_agent
content
request_fulluri
follow_location
max_redirects
protocol_version
timeout
Other contexts: https://www.php.net/manual/en/context.php
What i did was to uninstall and install the "^0.13.0". I confirm/ support this last answer. It worked for me as well. I had uninstall version "^0.800.0" and installed the "^0.13.0". rebuild your project it will work fine.
The result you've got is correct and fairly consistent across floating point implementations in different languages, processors and operating systems - the only thing that changes is the level of the inaccuracy when the float is actually a double (or higher).
0.1 in binary floating points is like 1/3 in decimal (i.e. 0.3333333333333... forever), there's just no accurate way to handle it.
If you're dealing with floats always expect small rounding errors, so you'll also always have to round the displayed result to something sensible. In return you get very very fast and powerful arithmetic because all the computations are in the native binary of the processor.
Most of the time the solution is not to switch to fixed-point arithmetic, mainly because it's much slower and 99% of the time you just don't need the accuracy. If you're dealing with stuff that does need that level of accuracy (for instance financial transactions) Javascript probably isn't the best tool to use anyway (as you've want to enforce the fixed-point types a static language is probably better).
You're looking for the elegant solution then I'm afraid this is it: floats are quick but have small rounding errors - always round to something sensible when displaying their results.
By using this query you get the answer:
select Column_name
from Information_schema.columns
where Table_name like 'table name'
Highlight block of text, then:
Comment Block: Ctrl + K + C
Uncomment Block: Ctrl + K + U
Tested in Visual Studio 2012
There is no updated
dynamic table. There is just inserted
and deleted
. On an UPDATE
command, the old data is stored in the deleted
dynamic table, and the new values are stored in the inserted
dynamic table.
Think of an UPDATE
as a DELETE/INSERT
combination.
1) When the user logs out (Forms signout in Action) I want to redirect to a login page.
public ActionResult Logout() {
//log out the user
return RedirectToAction("Login");
}
2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)
Why would you want to redirect from a controller init?
the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:
public ActionResult Index() {
return RedirectToAction("whateverAction", "whateverController");
}
The below code worked for me instead of the previous one - try it out !
df['DOB']=pd.to_datetime(df['DOB'].astype(str), format='%m/%d/%Y')
For the select tag, angular provides the ng-options directive. It gives you the specific framework to set up options and set a default. Here is the updated fiddle using ng-options that works as expected: http://jsfiddle.net/FxM3B/4/
Updated HTML (code stays the same)
<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.value as operator.displayName for operator in operators">
</select>
</body>
I think this is more readable given the intent:
$('someTableSelector').children( 'tr:not(:first)' ).remove();
Using children also takes care of the case where the first row contains a table by limiting the depth of the search.
If you had an TBODY element, you can do this:
$("someTableSelector > tbody:last").children().remove();
If you have THEAD or TFOOT elements you'll need to do something different.
The right way to do this is simple:
def rate(T):
if (T > 200):
return 200*exp(-T)
else:
return 400*exp(-T)
There is absolutely no advantage to using lambda
here. The only thing lambda
is good for is allowing you to create anonymous functions and use them in an expression (as opposed to a statement). If you immediately assign the lambda
to a variable, it's no longer anonymous, and it's used in a statement, so you're just making your code less readable for no reason.
The rate
function defined this way can be stored in an array, passed around, called, etc. in exactly the same way a lambda function could. It'll be exactly the same (except a bit easier to debug, introspect, etc.).
From a comment:
Well the function needed to fit in one line, which i didn't think you could do with a named function?
I can't imagine any good reason why the function would ever need to fit in one line. But sure, you can do that with a named function. Try this in your interpreter:
>>> def foo(x): return x + 1
Also these functions are stored as strings which are then evaluated using "eval" which i wasn't sure how to do with regular functions.
Again, while it's hard to be 100% sure without any clue as to why why you're doing this, I'm at least 99% sure that you have no reason or a bad reason for this. Almost any time you think you want to pass Python functions around as strings and call eval
so you can use them, you actually just want to pass Python functions around as functions and use them as functions.
But on the off chance that this really is what you need here: Just use exec
instead of eval
.
You didn't mention which version of Python you're using. In 3.x, the exec
function has the exact same signature as the eval
function:
exec(my_function_string, my_globals, my_locals)
In 2.7, exec
is a statement, not a function—but you can still write it in the same syntax as in 3.x (as long as you don't try to assign the return value to anything) and it works.
In earlier 2.x (before 2.6, I think?) you have to do it like this instead:
exec my_function_string in my_globals, my_locals
That header file is not part of the C++ standard, is therefore non-portable, and should be avoided.
Moreover, even if there were some catch-all header in the standard, you would want to avoid it in lieu of specific headers, since the compiler has to actually read in and parse every included header (including recursively included headers) every single time that translation unit is compiled.
I have edited the "Best answer" code, though I found a useful thing that was missing. This is will also track the ip of a user if they are using a Proxy or simply if the server has nginx installed as a proxy reverser.
I added this code to his script at the top of the function:
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$adresseip = getRealIpAddr();
Afther that I edited his code.
Find the line that says the following:
// get the user name if it is logged, or the visitors IP (and add the identifier)
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
and replace it with this:
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $adresseip. $vst_id;
This will work.
Here is the full code if anything happens:
<?php
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$adresseip = getRealIpAddr();
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start(); // start Session, if not already started
$filetxt = 'userson.txt'; // the file in which the online users /visitors are stored
$timeon = 120; // number of secconds to keep a user online
$sep = '^^'; // characters used to separate the user name and date-time
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
You can get a free registration script from: http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the line with visitors
$nrvst = 0; // to store the number of visitors
// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)
$addrow[] = $uvon. $sep. time();
// check if the file from $filetxt exists and is writable
if(is_writable($filetxt)) {
// get into an array the lines added in $filetxt
$ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrrows = count($ar_rows);
// number of rows
// if there is at least one line, parse the $ar_rows array
if($nrrows>0) {
for($i=0; $i<$nrrows; $i++) {
// get each line and separate the user /visitor and the timestamp
$ar_line = explode($sep, $ar_rows[$i]);
// add in $addrow array the records in last $timeon seconds
if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
$addrow[] = $ar_rows[$i];
}
}
}
}
$nruvon = count($addrow); // total online
$usron = ''; // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
if(preg_match($rgxvst, $addrow[$i])) $nrvst++; // increment the visitors
else {
// gets and stores the user's name
$ar_usron = explode($sep, $addrow[$i]);
$usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
}
}
$nrusr = $nruvon - $nrvst; // gets the users (total - visitors)
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
Haven't tested this on the Sql script yet.
Just special-case it. If you see a numerator of 0 and a denominator of 0, pretend like it has the values you really want.
You can simply print
it.
@a = qw(abc def hij);
print "@a";
You will got:
abc def hij
If there is no patch number, ~
is equivalent to appending .x
to the non-tilde version. If there is a patch number, ~
allows all patch numbers >= the specified one.
~1 := 1.x
~1.2 := 1.2.x
~1.2.3 := (>=1.2.3 <1.3.0)
I don't have enough points to comment on the accepted answer, but some of the tilde information is at odds with the linked semver documentation: "angular": "~1.2"
will not match 1.3, 1.4, 1.4.9. Also "angular": "~1"
and "angular": "~1.0"
are not equivalent. This can be verified with the npm semver calculator.
Just had the same problem - app was being installed OK, but won't run from Xcode with the "process launch failed: failed to get the task for process".
Turns out my development certificate expired during the night. Regenerating the certificate and the provisioning profiles solved the problem.
I've setup xampp for my localhost as well, I've not done anything with the files created by xampp during or after setup.
But in the '.htaccess' file, make sure you've set it to something like this. Works for me, and this should not make any difference for you.
RewriteEngine On
RewriteRule ^filename/?$ filename.html
Change .html to whatever format you're using.
Make sure your install is clean, and just make the .htaccess file. Also remember to put one .htaccess file for each directory (don't really know if you can use ONE file for all folders, but to be safe, just do this and it will always work.
I agree with the futility of the subject, but if you have to have a filter, check out Ning's Boxwood:
Boxwood is a PHP extension for fast replacement of multiple words in a piece of text. It supports case-sensitive and case-insensitive matching. It requires that the text it operates on be encoded as UTF-8.
Also see this blog post for more details:
With Boxwood, you can have your list of search terms be as long as you like -- the search and replace algorithm doesn't get slower with more words on the list of words to look for. It works by building a trie of all the search terms and then scans your subject text just once, walking down elements of the trie and comparing them to characters in your text. It supports US-ASCII and UTF-8, case-sensitive or insensitive matching, and has some English-centric word boundary checking logic.
Here is a solution that works for me. It involves radio button binding--but not binding to business data, but instead, binding to the state of the radio button. It is probably NOT the best solution for new projects, but is appropriate for my project. My project has a ton of existing code written in a different technology which I am porting to Angular. The old code follows a pattern in which the code is very interested in examining each radio button to see if it is the selected one. The solution is a variation of the click handler solutions, some of which have already been mentioned on Stack Overflow. The value added of this solution may be:
- Works with the pattern of old code that I have to work with.
- I created a helper class to try to reduce the number of "if" statements in the click handler, and to handle any group of radio buttons.
This solution involves
- Using a different model for each radio button.
- Setting the "checked" attribute with the radio button's model.
- Passing the model of the clicked radio button to the helper class.
- The helper class makes sure the models are up-to-date.
- At "submit time" this allows the old code to examine the state of the radio buttons to see which one is selected by examining the models.
Example:
<input type="radio"
[checked]="maleRadioButtonModel.selected"
(click)="radioButtonGroupList.selectButton(maleRadioButtonModel)"
...
<input type="radio"
[checked]="femaleRadioButtonModel.selected"
(click)="radioButtonGroupList.selectButton(femaleRadioButtonModel)"
...
When the user clicks a radio button, the selectButton method of the helper class gets invoked. It is passed the model for the radio button that got clicked. The helper class sets the boolean "selected" field of the passed in model to true, and sets the "selected" field of all the other radio button models to false.
During initialization the component must construct an instance of the helper class with a list of all radio button models in the group. In the example, "radioButtonGroupList" would be an instance of the helper class whose code is:
import {UIButtonControlModel} from "./ui-button-control.model";
export class UIRadioButtonGroupListModel {
private readonly buttonList : UIButtonControlModel[];
private readonly debugName : string;
constructor(buttonList : UIButtonControlModel[], debugName : string) {
this.buttonList = buttonList;
this.debugName = debugName;
if (this.buttonList == null) {
throw new Error("null buttonList");
}
if (this.buttonList.length < 2) {
throw new Error("buttonList has less than 2 elements")
}
}
public selectButton(buttonToSelect : UIButtonControlModel) : void {
let foundButton : boolean = false;
for(let i = 0; i < this.buttonList.length; i++) {
let oneButton : UIButtonControlModel = this.buttonList[i];
if (oneButton === buttonToSelect) {
oneButton.selected = true;
foundButton = true;
} else {
oneButton.selected = false;
}
}
if (! foundButton) {
throw new Error("button not found in buttonList");
}
}
}
With Column, use:
mainAxisAlignment: MainAxisAlignment.center
It align its children(s) to center of its parent Space vertically
const
applies for variables, and prevents them from being modified in your code.
constexpr
tells the compiler that this expression results in a compile time constant value, so it can be used in places like array lengths, assigning to const
variables, etc. The link given by Oli has a lot of excellent examples.
Basically they are 2 different concepts altogether, and can (and should) be used together.
The short answer:
Both maps are thread-safe implementations of the Map
interface. ConcurrentHashMap
is implemented for higher throughput in cases where high concurrency is expected.
Brian Goetz's article on the idea behind ConcurrentHashMap
is a very good read. Highly recommended.
Here is Neal Gafter's blog one of the pioneers introducing closures in Java. His post on closures from January 28, 2007 is named A Definition of Closures On his blog there is lots of information to get you started as well as videos. An here is an excellent Google talk - Advanced Topics In Programming Languages - Closures For Java with Neal Gafter, as well.
Here is the latest example from the Firestore documentation:
firebase.firestore.FieldValue.ArrayUnion
var washingtonRef = db.collection("cities").doc("DC");
// Atomically add a new region to the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});
// Atomically remove a region from the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayRemove("east_coast")
});
I fixed this problem with the following steps:
sudo apt-get install libmysqlclient-dev
sudo apt-get install python-dev
sudo python setup.py install
It appears this has been fixed in MVC4.
You can do this, which worked well for me:
public ActionResult SomeControllerAction()
{
var jsonResult = Json(veryLargeCollection, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}