Try http://simplefocus.com/flowtype/. This is what I use for my sites, and it has worked perfectly.
Angularjs (versions below 1.1.5) does not provide the if/else
functionality . Following are a few options to consider for what you want to achieve:
(Jump to the update below (#5) if you are using version 1.1.5 or greater)
As suggested by @Kirk in the comments, the cleanest way of doing this would be to use a ternary operator as follows:
<span>{{isLarge ? 'video.large' : 'video.small'}}</span>
ng-switch
directive:can be used something like the following.
<div ng-switch on="video">
<div ng-switch-when="video.large">
<!-- code to render a large video block-->
</div>
<div ng-switch-default>
<!-- code to render the regular video block -->
</div>
</div>
ng-hide
/ ng-show
directivesAlternatively, you might also use ng-show/ng-hide
but using this will actually render both a large video and a small video element and then hide the one that meets the ng-hide
condition and shows the one that meets ng-show
condition. So on each page you'll actually be rendering two different elements.
ng-class
directive.This can be used as follows.
<div ng-class="{large-video: video.large}">
<!-- video block goes here -->
</div>
The above basically will add a large-video
css class to the div element if video.large
is truthy.
ngIf directive
ng-if
directive:In the versions above 1.1.5
you can use the ng-if
directive. This would remove the element if the expression provided returns false
and re-inserts the element
in the DOM if the expression returns true
. Can be used as follows.
<div ng-if="video == video.large">
<!-- code to render a large video block-->
</div>
<div ng-if="video != video.large">
<!-- code to render the regular video block -->
</div>
This has been answered a hundred times but this solution worked the best for me and helped address the issue when new devices are introduced and I don't have a size defined.
Swift 5 Helper:
extension UIScreen {
func phoneSizeInInches() -> CGFloat {
switch (self.nativeBounds.size.height) {
case 960, 480:
return 3.5 //iPhone 4
case 1136:
return 4 //iPhone 5
case 1334:
return 4.7 //iPhone 6
case 2208:
return 5.5 //iPhone 6 Plus
case 2436:
return 5.8 //iPhone X
case 1792:
return 6.1 //iPhone XR
case 2688:
return 6.5 //iPhone XS Max
default:
let scale = self.scale
let ppi = scale * 163
let width = self.bounds.size.width * scale
let height = self.bounds.size.height * scale
let horizontal = width / ppi, vertical = height / ppi
let diagonal = sqrt(pow(horizontal, 2) + pow(vertical, 2))
return diagonal
}
}
}
This is because it's easy to memorize a phone's inch sizes, like, "5.5 inch" or "4.7 inch" device but difficult to remember the exact pixel sizes.
if UIScreen.main.phoneSizeInInches() == 4 {
//do something with only 4 inch iPhones
}
This also gives you the opportunity to do something like this:
if UIScreen.main.phoneSizeInInches() < 5.5 {
//do something on all iPhones smaller than the plus
}
The default: tries to uses the screen size and scale to try and calculate the diagonal inches. This is in case some new device size appears, it will try its best to determine and code, such as the last example, should still work.
Use the Auto Layout
feature for views. It will adjust automatically to all resolutions.
Create two xibs for a controller having controller name with suffix either ~iphone or ~ipad. At compile time, Xcode will take the right xib based on the device.
Use size classes, if you want to create a single xib for both iPhone and iPad, if the view is simple enough to port to iPhone and iPad.
I use WinSplit Revolution for the keyboard arrangement capability and I use bblean as a replacement for Explorer. It has multiple workspace capabilities built right in and it allows you to customize it exactly how you want it to look.
myTextBox.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
TextView myOutputBox = (TextView) findViewById(R.id.myOutputBox);
myOutputBox.setText(s);
}
});
Using JQuery would take care of that browser inconsistency. With the jquery library included in your project simply write:
$('#yourDivName').html('yourtHTML');
You may also consider using:
$('#yourDivName').append('yourtHTML');
This will add your gallery as the last item in the selected div. Or:
$('#yourDivName').prepend('yourtHTML');
This will add it as the first item in the selected div.
See the JQuery docs for these functions:
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
Try:
adb shell ip addr show rmnet0
It will return something like that:
3: rmnet0: <UP,LOWER_UP> mtu 1500 qdisc htb state UNKNOWN qlen 1000
link/[530]
inet 172.22.1.100/29 scope global rmnet0
inet6 fc01:abab:cdcd:efe0:8099:af3f:2af2:8bc/64 scope global dynamic
valid_lft forever preferred_lft forever
inet6 fe80::8099:af3f:2af2:8bc/64 scope link
valid_lft forever preferred_lft forever
This part is your IPV4 assigned by the operator
inet 172.22.1.100
This part is your IPV6 assigned by the operator
inet6 fc01:abab:cdcd:efe0:8099:af3f:2af2:8bc
The socket has been closed by the client (browser).
A bug in your code:
byte[] outputByte=new byte[4096];
while(in.read(outputByte,0,4096)!=-1){
output.write(outputByte,0,4096);
}
The last packet read, then write may have a length < 4096, so I suggest:
byte[] outputByte=new byte[4096];
int len;
while(( len = in.read(outputByte, 0, 4096 )) > 0 ) {
output.write( outputByte, 0, len );
}
It's not your question, but it's my answer... ;-)
-webkit-overflow-scrolling:touch
as mentioned in the answer is infact the possible solution.
<div style="overflow:scroll !important; -webkit-overflow-scrolling:touch !important;">
<iframe src="YOUR_PAGE_URL" width="600" height="400"></iframe>
</div>
But if you are unable to scroll up and down inside the iframe as shown in image below,
you could try scrolling with 2 fingers diagonally like this,
This actually worked in my case, so just sharing it if you haven't still found a solution for this.
This won't be secure, and it's simple to explain why:
If you hash the password on the client side and use that token instead of the password, then an attacker will be unlikely to find out what the password is.
But, the attacker doesn't need to find out what the password is, because your server isn't expecting the password any more - it's expecting the token. And the attacker does know the token because it's being sent over unencrypted HTTP!
Now, it might be possible to hack together some kind of challenge/response form of encryption which means that the same password will produce a different token each request. However, this will require that the password is stored in a decryptable format on the server, something which isn't ideal, but might be a suitable compromise.
And finally, do you really want to require users to have javascript turned on before they can log into your website?
In any case, SSL is neither an expensive or especially difficult to set up solution any more
As far as I know Angular-cli file can't be created via a command like Package-lock file, If you want to create it, you have to do it manually.
You can type ng new to create a new angular project
Locate its .angular-cli.json file
Copy all its content
Create a folder in your original project, and name it .angular-cli.json
Paste what copied from new project in newly created angular cli file of original project.
Locate this line in angular cli file you created, and change the name field to original project's name. You can find the project name in package.json file
project": { "name": "<name of the project>" },
However, in newer angular version now it uses angular.json instead of angular-cli.json.
Using SQL Server, here is another way to find last day of month :
SELECT DATEADD(MONTH,1,GETDATE())- day(DATEADD(MONTH,1,GETDATE()))
You can use the Build Helper Plugin, e.g:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>some directory</source>
...
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Make sure when you use icon image it is not manipulated extension, like if you download a png
image and then manually change its extension from png
to icon
. In this case, your image will be corrupted. And browser does not understand.
I did this mistake, but after using original icon image its start working.
Console.WriteLine(dt2 != null ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "n/a");
EDIT: As stated in other comments, check that there is a non-null value.
Update: as recommended in the comments, extension method:
public static string ToString(this DateTime? dt, string format)
=> dt == null ? "n/a" : ((DateTime)dt).ToString(format);
And starting in C# 6, you can use the null-conditional operator to simplify the code even more. The expression below will return null if the DateTime?
is null.
dt2?.ToString("yyyy-MM-dd hh:mm:ss")
put a semicolon between the two functions as statement terminator.
To set the range of the x-axis, you can use set_xlim(left, right)
, here are the docs
Update:
It looks like you want an identical plot, but only change the 'tick values', you can do that by getting the tick values and then just changing them to whatever you want. So for your need it would be like this:
ticks = your_plot.get_xticks()*10**9
your_plot.set_xticklabels(ticks)
jcalfee314's idea worked for me - I had a window.onload = onLoad
which meant that the functions in <body onload="...">
were not being called (which I don't have control over).
This fixed it:
oldOnLoad = window.onload
window.onload = onLoad;
function onLoad()
{
oldOnLoad();
...
}
Edit: Firefox didn't like oldOnLoad = document.body.onload;
, so replaced with oldOnLoad = window.onload
.
What about the SystemParameters class in PresentationFramework? It has a WorkArea property that seems to be what you are looking for.
But, why won't setting the Window.WindowStartupLocation work? CenterScreen is one of the enum values. Do you have to tweak the centering?
What worked for me was:
$('select option').each(function(){$(this).removeAttr('selected');});
If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
Also see this SO thread: Open directory dialog
ConcurrentHashMap was presented as alternative to Hashtable in Java 1.5 as part of concurrency package. With ConcurrentHashMap, you have a better choice not only if it can be safely used in the concurrent multi-threaded environment but also provides better performance than Hashtable and synchronizedMap. ConcurrentHashMap performs better because it locks a part of Map. It allows concurred read operations and the same time maintains integrity by synchronizing write operations.
ConcurrentHashMap was developed as alternative of Hashtable and support all functionality of Hashtable with additional ability, so called concurrency level. ConcurrentHashMap allows multiple readers to read simultaneously without using blocks. It becomes possible by separating Map to different parts and blocking only part of Map in updates. By default, concurrency level is 16, so Map is spitted to 16 parts and each part is managed by separated block. It means, that 16 threads can work with Map simultaneously, if they work with different parts of Map. It makes ConcurrentHashMap hight productive, and not to down thread-safety.
If you are interested in some important features of ConcurrentHashMap and when you should use this realization of Map - I just put a link to a good article - How to use ConcurrentHashMap in Java
If you are loading the image via AJAX you could use a callback to check if the image is loaded and do the hiding and src attribute assigning. Something like this:
$.ajax({
url: [image source],
success: function() {
// Do the hiding here and the attribute setting
}
});
For more reading refer to this JQuery AJAX
This is how a snapshot looks like for a repository and in this case is not enabled, which means that the repository referred in here is stable and there's no need for updates.
<project>
...
<repositories>
<repository>
<id>lds-main</id>
<name>LDS Main Repo</name>
<url>http://code.lds.org/nexus/content/groups/main-repo</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
Another case would be for:
<snapshots>
<enabled>true</enabled>
</snapshots>
which means that Maven will look for updates for this repository. You can also specify an interval for the updates with tag.
To select top n rows updated recently
SELECT *
FROM (
SELECT *
FROM table
ORDER BY UpdateDateTime DESC
)
WHERE ROWNUM < 101;
For me, I found the suggestion in the following thread helped:
It suggested running the following command in the Terminal application:
sudo /usr/sbin/DevToolsSecurity --enable
I suggest you to use 2 queries:
db.collection.count()
will return total number of items. This value is stored somewhere in Mongo and it is not calculated.
db.collection.find().skip(20).limit(10)
here I assume you could use a sort by some field, so do not forget to add an index on this field. This query will be fast too.
I think that you shouldn't query all items and than perform skip and take, cause later when you have big data you will have problems with data transferring and processing.
Here's a 3D array case
class Array3D
def initialize(d1,d2,d3)
@data = Array.new(d1) { Array.new(d2) { Array.new(d3) } }
end
def [](x, y, z)
@data[x][y][z]
end
def []=(x, y, z, value)
@data[x][y][z] = value
end
end
You can access subsections of each array just like any other Ruby array. @data[0..2][3..5][8..10] = 0 etc
I did the following to resolve mine:
In Adapter 1 tab, It should be attached to Host-Only Adapter. Check what is the name of the used adapter Name then close it.
Open File|Preferences in Virtualbox, then go to Network section/tab
Under Host-only Networks tab, find the same name you have already gotten in step 3.
Double click on that name and apple the following configuration
IPv4 Adapter: 192.168.65.1
IPV4 Network Mask: 255.255.255.0
DHCP Server:
192.168.65.100
255.255.255.0
192.168.65.101
192.168.65.255
xxhdpi was not specified before but now new devices S4, HTC one are surely comes inside xxhdpi .These device dpi are around 440. I do not know exact limit for xxhdpi See how to develop android application for xxhdpi device Samsung S4 I know this is late answer but as thing had change since the question asked
Note Google Nexus 10 need to add a 144*144px icon in the drawable-xxhdpi or drawable-480dpi folder.
Escaping curly brackets AND using string interpolation makes for an interesting challenge. You need to use quadruple brackets to escape the string interpolation parsing and string.format
parsing.
string localVar = "dynamic";
string templateString = $@"<h2>{0}</h2><div>this is my {localVar} template using a {{{{custom tag}}}}</div>";
string result = string.Format(templateString, "String Interpolation");
// OUTPUT: <h2>String Interpolation</h2><div>this is my dynamic template using a {custom tag}</div>
This error indicates that the two tables have the 1 or more column names that have the same column name. The error message translates to: "I can see the same column in both tables but you haven't told me to rename either before bringing one of them in"
You either want to delete one of the columns before bringing it in from the other on using del df['column name'], or use lsuffix to re-write the original column, or rsuffix to rename the one that is being brought it.
df_a.join(df_b, on='mukey', how='left', lsuffix='_left', rsuffix='_right')
You can do it in one statement like this:
CachedObject.where(key: "the given key").first_or_create! do |cached|
cached.attribute1 = 'attribute value'
cached.attribute2 = 'attribute value'
end
This looks like a good reference although it's not in Regex.
Really, unless you're actually shipping something to your users, I don't think it's worth the effort. And if you are shipping it, there are address cleaning tools/services you can look into to make it way easier on yourself.
I found this worked best for my usecase:
<i class="btn btn-light fa fa-dribbble fa-4x" href="#"></i>
<i class="btn btn-light fa fa-behance-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-linkedin-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-twitter-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-facebook-square fa-4x" href="#"></i>
Here's a solution to the "headers were already sent" problem. Assume you are validating and emailing a form. Make sure the php code is the first thing on your page... before any of the doctype and head tags and all that jazz. Then, when the POST arrives back at the page the php code will come first and not encounter the headers already sent problem.
You want:
DECLARE @times int
SELECT @times = COUNT(DidWin)
FROM thetable
WHERE DidWin = 1 AND Playername='Me'
You also don't need the 'as' clause.
To remove claim details from database we can use below code. Also, we need to sign in again to update the cookie values
// create a new identity
var identity = new ClaimsIdentity(User.Identity);
// Remove the existing claim value of current user from database
if(identity.FindFirst("NameOfUser")!=null)
await UserManager.RemoveClaimAsync(applicationUser.Id, identity.FindFirst("NameOfUser"));
// Update customized claim
await UserManager.AddClaimAsync(applicationUser.Id, new Claim("NameOfUser", applicationUser.Name));
// the claim has been updates, We need to change the cookie value for getting the updated claim
AuthenticationManager.SignOut(identity.AuthenticationType);
await SignInManager.SignInAsync(Userprofile, isPersistent: false, rememberBrowser: false);
return RedirectToAction("Index", "Home");
The same as @neobot's answer but a little more modern and succinct.
>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'
htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.
There is a manual page dedicated to help choosing between mysql, mysqli and PDO at
The PHP team recommends mysqli or PDO_MySQL for new development:
It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.
The page also has a feature matrix comparing the extension APIs. The main differences between mysqli and mysql API are as follows:
mysqli mysql
Development Status Active Maintenance only
Lifecycle Active Long Term Deprecation Announced*
Recommended Yes No
OOP API Yes No
Asynchronous Queries Yes No
Server-Side Prep. Statements Yes No
Stored Procedures Yes No
Multiple Statements Yes No
Transactions Yes No
MySQL 5.1+ functionality Yes No
* http://news.php.net/php.internals/53799
There is an additional feature matrix comparing the libraries (new mysqlnd versus libmysql) at
and a very thorough blog article at
Here is a neat and clean way to install Python2 & Python3 on windows.
My case: I had to install Apache cassandra. I already had Python3 installed in my D: drive. With loads of development work under process i didn't wanted to mess my Python3 installation. And, i needed Python2 only for Apache cassandra.
So i took following steps:
C:\Python27;C:\Python27\Scripts
)So, my Python3 installation remained intact.
Well, it's not a direct answer to your question, but there's a tool in GNU/Linux whose job is to rotate log files on regular basis, keeping old ones zipped up to a certain limit. It's logrotate
1.
function setColor(e) {
var target = e.target,
count = +target.dataset.count;
target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF';
target.dataset.count = count === 1 ? 0 : 1;
/*
() : ? - this is conditional (ternary) operator - equals
if (count === 1) {
target.style.backgroundColor = "#7FFF00";
target.dataset.count = 0;
} else {
target.style.backgroundColor = "#FFFFFF";
target.dataset.count = 1;
}
target.dataset - return all "data attributes" for current element,
in the form of object,
and you don't need use global variable in order to save the state 0 or 1
*/
}
<input
type="button"
id="button"
value="button"
style="color:white"
onclick="setColor(event)";
data-count="1"
/>
2.
function setColor(e) {
var target = e.target,
status = e.target.classList.contains('active');
e.target.classList.add(status ? 'inactive' : 'active');
e.target.classList.remove(status ? 'active' : 'inactive');
}
.active {
background-color: #7FFF00;
}
.inactive {
background-color: #FFFFFF;
}
<input
type="button"
id="button"
value="button"
style="color:white"
onclick="setColor(event)"
/>
you may use htmlspecialchars()
<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
?>
That's how I just did it on OsX 10.10.3
for f in *.txt; do (cat $f; echo '') >> fullData.txt; done
since the simple 'echo' command with no params ended up in no new lines inserted.
For old Ruby (1.8.x):
myDate = Date.parse(myDateTime.to_s)
Your syntax is incorrect, you should either specify a hash:
hash = {abc: true, def: true, ghi: true};
Or an array:
arr = ['abc','def','ghi'];
You can effectively remove an item from a hash by simply setting it to null:
hash['def'] = null;
hash.def = null;
Or removing it entirely:
delete hash.def;
To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:
arr.splice(arr.indexOf("def"), 1);
This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:
arr.filter(function(item) { return item !== 'def'; });
This will create a new array with only elements that are not 'def'.
It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.
There may not be anything 'Python specific', but the KDE and GNOME desktops offer text-to-speech as a part of their accessibility support, and also offer python library bindings. It may be possible to use the python bindings to control the desktop libraries for text to speech.
If using the Jython implementation of Python on the JVM, the FreeTTS system may be usable.
Finally, OSX and Windows have native APIs for text to speech. It may be possible to use these from python via ctypes or other mechanisms such as COM.
The Json conversion should work out-of-the box. In order this to happen you need add some simple configurations:
First add a contentNegotiationManager into your spring config file. It is responsible for negotiating the response type:
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="true" />
<property name="ignoreAcceptHeader" value="true" />
<property name="useJaf" value="false" />
<property name="defaultContentType" value="application/json" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
<mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager" />
<context:annotation-config />
Then add Jackson2 jars (jackson-databind and jackson-core) in the service's class path. Jackson is responsible for the data serialization to JSON. Spring will detect these and initialize the MappingJackson2HttpMessageConverter automatically for you. Having only this configured I have my automatic conversion to JSON working. The described config has an additional benefit of giving you the possibility to serialize to XML if you set accept:application/xml header.
Here is another quick way, just using the key as an index into the hash table to get the value:
$hash = @{
'a' = 1;
'b' = 2;
'c' = 3
};
foreach($key in $hash.keys) {
Write-Host ("Key = " + $key + " and Value = " + $hash[$key]);
}
You can simply pass the functions as a list:
In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:
mean sum
dummy
1 0.036901 0.369012
or as a dictionary:
In [21]: df.groupby('dummy').agg({'returns':
{'Mean': np.mean, 'Sum': np.sum}})
Out[21]:
returns
Mean Sum
dummy
1 0.036901 0.369012
Try this:
<SCRIPT LANGUAGE="JavaScript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("C:\test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
</SCRIPT>
</head>
<body>
<p>To sign up for the Excel workshop please fill out the form below:
</p>
<form onSubmit="WriteToFile(this)">
Type your first name:
<input type="text" name="FirstName" size="20">
<br>Type your last name:
<input type="text" name="LastName" size="20">
<br>
<input type="submit" value="submit">
</form>
This will work only on IE
array with zero elements converts to false
I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful
library(dplyr)
iris %>%
mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))
So if I get it right, on click of a button, you want to open up a modal that lists the values entered by the users followed by submitting it.
For this, you first change your input type="submit"
to input type="button"
and add data-toggle="modal" data-target="#confirm-submit"
so that the modal gets triggered when you click on it:
<input type="button" name="btn" value="Submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />
Next, the modal dialog:
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div>
<div class="modal-body">
Are you sure you want to submit the following details?
<!-- We display the details entered by the user here -->
<table class="table">
<tr>
<th>Last Name</th>
<td id="lname"></td>
</tr>
<tr>
<th>First Name</th>
<td id="fname"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a href="#" id="submit" class="btn btn-success success">Submit</a>
</div>
</div>
</div>
</div>
Lastly, a little bit of jQuery:
$('#submitBtn').click(function() {
/* when the button in the form, display the entered values in the modal */
$('#lname').text($('#lastname').val());
$('#fname').text($('#firstname').val());
});
$('#submit').click(function(){
/* when the submit button in the modal is clicked, submit the form */
alert('submitting');
$('#formfield').submit();
});
You haven't specified what the function validateForm()
does, but based on this you should restrict your form from being submitted. Or you can run that function on the form's button #submitBtn
click and then load the modal after the validations have been checked.
Error message clearly says that source
parameter is null
. Source is the enumerable you are enumerating. In your case it is ListMetadataKor
object. And its definitely null
at the time you are filtering it second time. Make sure you never assign null
to this list. Just check all references to this list in your code and look for assignments.
One object may contain another as a part of its attribute.
So containment need not be physical. e.g., computer system has a warranty.
If you already have the figure object use:
f.set_figheight(15)
f.set_figwidth(15)
But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:
f, axs = plt.subplots(2,2,figsize=(15,15))
can make your custom fonts via iReport and converting like jars files
A static library(.a) is a library that can be linked directly into the final executable produced by the linker,it is contained in it and there is no need to have the library into the system where the executable will be deployed.
A shared library(.so) is a library that is linked but not embedded in the final executable, so will be loaded when the executable is launched and need to be present in the system where the executable is deployed.
A dynamic link library on windows(.dll) is like a shared library(.so) on linux but there are some differences between the two implementations that are related to the OS (Windows vs Linux) :
A DLL can define two kinds of functions: exported and internal. The exported functions are intended to be called by other modules, as well as from within the DLL where they are defined. Internal functions are typically intended to be called only from within the DLL where they are defined.
An SO library on Linux doesn't need special export statement to indicate exportable symbols, since all symbols are available to an interrogating process.
Try something like this:
<div id="LoadingImage" style="display: none">
<img src="" />
</div>
<script>
function ajaxCall(){
$("#LoadingImage").show();
$.ajax({
type: "GET",
url: surl,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "newarticlescallback",
crossDomain: "true",
success: function(response) {
$("#LoadingImage").hide();
alert("Success");
},
error: function (xhr, status) {
$("#LoadingImage").hide();
alert('Unknown error ' + status);
}
});
}
</script>
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.
For me the filter/gradient approach didn't work (perhaps due to the existing CSS) so I have used :before
pseudo styling trick instead:
.eventBannerContainer {
position: relative;
}
.eventBannerContainer:before {
background-color: black;
height: 100%;
width: 100%;
content: "";
opacity: 0.5;
position: absolute;
display: block;
}
/* make any immediate child elements above our darkening mask */
.eventBannerContainer > * {
position: relative;
}
Have you considered lsof
(list open files)?
Here is my python cv2
implementation:
import cv2
img=cv2.imread("path_to_image.jpg")
# rotate ccw
out=cv2.transpose(img)
out=cv2.flip(out,flipCode=0)
# rotate cw
out=cv2.transpose(img)
out=cv2.flip(out,flipCode=1)
cv2.imwrite("rotated.jpg", out)
I think the easiest way to do it is:
rmdir /s /q "C:\FolderToNotToDelete\"
The last "\" in the path is the important part.
Just change the SqlCommand.CommandText
instead of creating a new SqlCommand
every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.
Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.
From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:
E:first-child
, E:hover
, E > F
(Child combinator), E + F
(Adjacent sibling combinator), E ~ F
(General sibling combinator). This unfortunately means resorting to workarounds like inline styles.white-space
won't work.background-image
property won't work.height
, width
, and the max-
versions are either not usable or have bugs for certain elements.display
, float
s and position
are all out).In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.
PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top
" where you probably meant to use vertical-align
. Also: cell-padding
for td
s doesn't exist.
There could be many reasons, but the most common are:
The port is not open on the destination machine.
The port is open on the destination machine, but its backlog of pending connections is full.
A firewall between the client and server is blocking access (also check local firewalls).
After checking for firewalls and that the port is open, use telnet to connect to the ip/port to test connectivity. This removes any potential issues from your application.
Using something like self-clearing div
is perfect for a situation like this. Then you'll just use a class on the parent... like:
<div id="parent" class="clearfix">
UPDATE:
After all the details summarized and discussed, I spent 2 fair hours in checking the options, and this update is to dot all i
s.
First of all, I performed a clean Office 2010 x86 install on Clean Win7 SP1 Ultimate x64 virtual machine powered by VMWare (this is usual routine for my everyday testing tasks, so I have many of them deployed).
Then, I changed only the following Excel options (i.e. all the other are left as is after installation):
Advanced > General > Ask to update automatic links
checked:Trust Center > Trust Center Settings... > External Content > Enable All...
(although that one that relates to Data Connections is most likely not important for the case):I prepared and placed to C:\
a workbook exactly as per @Siddharth Rout
suggestions in his updated answer (shared for your convenience): https://www.dropbox.com/s/mv88vyc27eljqaq/Book1withLinkToBook2.xlsx Linked book was then deleted so that link in the shared book is unavailable (for sure).
The above shared file shows on opening (having the above listed Excel options) 2 warnings - in the order of appearance:
WARNING #1
After click on Update
I expectedly got another:
WARNING #2
So, I suppose my testing environment is now pretty much similar to OP
's) So far so good, we finally go to
Now I'll try all possible options step by step to make the picture clear. I'll share only relevant lines of code for simplicity (complete sample file with code will be shared in the end).
1. Simple Application.Workbooks.Open
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
No surprise - this produces BOTH warnings, as for manual opening above.
2. Application.DisplayAlerts = False
Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True
This code ends up with WARNING #1, and either option clicked (Update
/ Don't Update
) produces NO further warnings, i.e. Application.DisplayAlerts = False
suppresses WARNING #2.
3. Application.AskToUpdateLinks = False
Application.AskToUpdateLinks = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.AskToUpdateLinks = True
Opposite to DisplayAlerts
, this code ends up with WARNING #2 only, i.e. Application.AskToUpdateLinks = False
suppresses WARNING #1.
4. Double False
Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Apparently, this code ends up with suppressing BOTH WARNINGS.
5. UpdateLinks:=False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=False
Finally, this 1-line solution (originally proposed by @brettdj
) works the same way as Double False: NO WARNINGS are shown!
Except a good testing practice and very important solved case (I may face such issues everyday while sending my workbooks to 3rd party, and now I'm prepared), 2 more things learned:
Thanks very much to everyone who contributed to the solution, and especially OP who raised the question. Hope my investigations and thoroughly described testing steps were helpful not only for me)
Sample file with the above code samples is shared (many lines are commented deliberately): https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm
Original answer (tested for Excel 2007 with certain options):
This code works fine for me - it loops through ALL Excel files specified using wildcards in the InputFolder
:
Sub WorkbookOpening2007()
Dim InputFolder As String
Dim LoopFileNameExt As String
InputFolder = "D:\DOCUMENTS\" 'Trailing "\" is required!
LoopFileNameExt = Dir(InputFolder & "*.xls?")
Do While LoopFileNameExt <> ""
Application.DisplayAlerts = False
Application.Workbooks.Open (InputFolder & LoopFileNameExt)
Application.DisplayAlerts = True
LoopFileNameExt = Dir
Loop
End Sub
I tried it with books with unavailable external links - no warnings.
Sample file: https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm
A little more elaborate example.
Setup: You have a website at example.com
and you have a web app at example.com/webapp
...
server {
listen 443 ssl;
server_name example.com;
root /usr/share/nginx/html/website_dir;
index index.html index.htm;
try_files $uri $uri/ /index.html;
location /webapp/ {
alias /usr/share/nginx/html/webapp_dir/;
index index.html index.htm;
try_files $uri $uri/ /webapp/index.html;
}
}
...
I've named webapp_dir
and website_dir
on purpose. If you have matching names and folders you can use the root
directive.
This setup works and is tested with Docker.
NB!!! Be careful with the slashes. Put them exactly as in the example.
This works on Windows with Cygwin installed:
System.getenv("NUMBER_OF_PROCESSORS")
this worked perfectly for me:
for(a in array)console.log(array[a])
you can extract any array created in console for find/replace cleanup and posterior usage of this data extracted
In Ubuntu if you execute the script with sh scriptname.sh
you get this problem.
Try executing the script with ./scriptname.sh
instead.
A slight variant of Matthew Dowell's post which avoids the short flash, but displays whenever the contact form 7 form is visible:
div.grecaptcha-badge{
width:0 !important;
}
div.grecaptcha-badge.show{
width:256px !important;
}
I then added the following to the header.php in my child theme:
<script>
jQuery( window ).load(function () {
if( jQuery( '.wpcf7' ).length ){
jQuery( '.grecaptcha-badge' ).addClass( 'show' );
}
});
</script>
<script type = "text/javascript">
function DisableButtons() {
var inputs = document.getElementsByTagName("INPUT");
for (var i in inputs) {
if (inputs[i].type == "button" || inputs[i].type == "submit") {
inputs[i].disabled = true;
}
}
}
window.onbeforeunload = DisableButtons;
</script>
To answer your query on "How to convert 2.3423424666767E13 to 23423424666767"
You can use a decimal formatter for formatting decimal numbers.
double d = 2.3423424666767E13;
DecimalFormat decimalFormat = new DecimalFormat("#");
System.out.println(decimalFormat.format(d));
Output : 23423424666767
In your Case you can write the following jquery code:
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").attr("readonly", false);
}
else{
$("#no_of_staff").attr("readonly", true);
}
});
});
Here is the Fiddle: http://jsfiddle.net/P4QWx/3/
You can only do this if you are connecting to a DNS server for the domain -and- AXFR is enabled for your IP address. This is the mechanism that secondary systems use to load a zone from the primary. In the old days, this was not restricted, but due to security concerns, most primary name servers have a whitelist of: secondary name servers + a couple special systems.
If the nameserver you are using allows this then you can use dig or nslookup.
For example:
#nslookup
>ls domain.com
NOTE: because nslookup is being deprecated for dig and other newere tools, some versions of nslookup do not support "ls", most notably Mac OS X's bundled version.
You can convert that time in Unix timestamp by using
select UNIX_TIMESTAMP('2013-11-26 01:24:34')
then convert it in the readable format in whatever format you need
select from_unixtime(UNIX_TIMESTAMP('2013-11-26 01:24:34'),"%Y-%m-%d");
For in detail you can visit link
val navigationView: NavigationView = findViewById(R.id.nv)
val header: View = navigationView.getHeaderView(0)
val tv: TextView = header.findViewById(R.id.profilename)
tv.text = "Your_Text"
This will fix your problem <3
One alternative would be a KeyedCollection if the key is embedded in the value.
Just create a basic implementation in a sealed class to use.
So to replace Dictionary<string, int>
(which isn't a very good example as there isn't a clear key for a int).
private sealed class IntDictionary : KeyedCollection<string, int>
{
protected override string GetKeyForItem(int item)
{
// The example works better when the value contains the key. It falls down a bit for a dictionary of ints.
return item.ToString();
}
}
KeyedCollection<string, int> intCollection = new ClassThatContainsSealedImplementation.IntDictionary();
intCollection.Add(7);
int valueByIndex = intCollection[0];
Best practice is to throw an error if the class is constructed.
Example:
/**
* The Class FooUtilityService.
*/
final class FooUtilityService{
/**
* Instantiates a new FooUtilityService. Private to prevent instantiation
*/
private FooUtilityService() {
// Throw an exception if this ever *is* called
throw new AssertionError("Instantiating utility class.");
}
ob_start(); // turns on output buffering
$foo->bar(); // all output goes only to buffer
ob_clean(); // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents(); // buffer content is now an empty string
ob_end_clean(); // turn off output buffering
Buffers can be nested, so while one buffer is active, another ob_start()
activates a new buffer. So ob_end_flush()
and ob_flush()
are not really sending the buffer to the output, but to the parent buffer. And only when there is no parent buffer, contents is sent to browser or terminal.
Nicely explained here: https://phpfashion.com/everything-about-output-buffering-in-php
numpy.append
always copies the array before appending the new values. Your code is equivalent to the following:
import numpy as np
result = np.zeros((2,0))
new_result = np.append([result[0]],[1,2])
result[0] = new_result # ERROR: has shape (2,0), new_result has shape (2,)
Perhaps you mean to do this?
import numpy as np
result = np.zeros((2,0))
result = np.append([result[0]],[1,2])
You can create a custom link as described here using a small jQuery script
$('.linkPinIt').click(function(){
var url = $(this).attr('href');
var media = $(this).attr('data-image');
var desc = $(this).attr('data-desc');
window.open("//www.pinterest.com/pin/create/button/"+
"?url="+url+
"&media="+media+
"&description="+desc,"_blank","top=0,right=0,width=750,height=320");
return false;
});
this will work for all links with class linkPinIt
which have the image and the description stored in the HTML 5 data attributes data-image
and data-desc
<a href="https%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F"
data-image="https%3A%2F%2Fc4.staticflickr.com%2F8%2F7027%2F6851755809_df5b2051c9_b.jpg"
data-desc="Title for Pinterest Photo" class="linkPinIt">
Pin it!
</a>
see this jfiddle example
You need to change source to viewmodel object:
myBinding.Source = viewModelObject;
As workaround you could use formaction
attribute on submit button. And just use different names on your inputs.
<form action="a">
<input.../>
<!-- Form 2 inputs -->
<input.../>
<input.../>
<input.../>
<input type="submit" formaction="b">
</form>
<input.../>
You are looking for strongly typed enumerations, a feature available in the C++11 standard. It turns enumerations into classes with scope values.
Using your own code example, it is:
enum class Days {Saturday, Sunday, Tuesday,Wednesday, Thursday, Friday};
Days day = Days::Saturday;
if (day == Days::Saturday) {
cout << " Today is Saturday !" << endl;
}
//int day2 = Days::Sunday; // Error! invalid
Using ::
as accessors to enumerations will fail if targeting a C++ standard prior C++11. But some old compilers doesn't supported it, as well some IDEs just override this option, and set a old C++ std.
If you are using GCC, enable C+11 with -std=c++11 or -std=gnu11 .
Be happy!
If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.
You can however drop this web.config in the root of the folder or site where you want to set it:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
</staticContent>
</system.webServer>
</configuration>
That will inform the client to cache content for 7 days in that folder and all subfolders.
You can also do this by editing the IIS7 metabase via appcmd.exe
, like so:
\Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMode:UseMaxAge \Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMaxAge:"7.00:00:00"
You cloud also simply override the width of the Column...
<div class="col-md-1" style="width: 12.499999995%"></div>
Since col-md-1
is of width 8.33333333%; simply multiply 8.33333333 * 1.5 and set it as your width.
in bootstrap 4
, you will have to override flex and max-width property too:
<div class="col-md-1" style="width: 12.499999995%;
flex: 0 0 12.499%;max-width: 12.499%;"></div>
I know this question is 8 year old, however there was and is a better solution for this purpose. It's always been there, and still is: User32.dll!MessageBoxTimeout.
This is an undocumented function used by Microsoft Windows, and it does exactly what you want and even more. It supports different languages as well.
C# Import:
[DllImport("user32.dll", SetLastError = true)]
public static extern int MessageBoxTimeout(IntPtr hWnd, String lpText, String lpCaption, uint uType, Int16 wLanguageId, Int32 dwMilliseconds);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetForegroundWindow();
How to use it in C#:
uint uiFlags = /*MB_OK*/ 0x00000000 | /*MB_SETFOREGROUND*/ 0x00010000 | /*MB_SYSTEMMODAL*/ 0x00001000 | /*MB_ICONEXCLAMATION*/ 0x00000030;
NativeFunctions.MessageBoxTimeout(NativeFunctions.GetForegroundWindow(), $"Kitty", $"Hello", uiFlags, 0, 5000);
Work smarter, not harder.
Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.
in javascript return statement only used inside function block. if you try to use return statement inside independent if else block it trigger syntax error : Illegal return statement in JavaScript
Here is my example code to avoid such error :
<script type = 'text/javascript'>
(function(){
var ss= 'no';
if(getStatus(ss)){
alert('Status return true');
}else{
alert('Status return false');
}
function getStatus(ask){
if(ask=='yes')
{
return true;
}
else
{
return false;
}
}
})();
</script>
Please check Jsfiddle example
//STEP01 EXEC SORT90MB
//SORTJNF1 DD DSN=INPUTFILE1,
// DISP=SHR
//SORTJNF2 DD DSN=INPUTFILE2,
// DISP=SHR
//SORTOUT DD DSN=MISMATCH_OUTPUT_FILE,
// DISP=(,CATLG,DELETE),
// UNIT=TAPE,
// DCB=(RECFM=FB,BLKSIZE=0),
// DSORG=PS
//SYSOUT DD SYSOUT=*
//SYSIN DD *
JOINKEYS FILE=F1,FIELDS=(1,79,A)
JOINKEYS FILE=F2,FIELDS=(1,79,A)
JOIN UNPAIRED,F1,ONLY
SORT FIELDS=COPY
/*
Try this:
@echo off
setlocal
cd /d %~dp0
Call :UnZipFile "C:\Temp\" "c:\path\to\batch.zip"
exit /b
:UnZipFile <ExtractTo> <newzipfile>
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs% echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%
Revision
To have it perform the unzip on each zip file creating a folder for each use:
@echo off
setlocal
cd /d %~dp0
for %%a in (*.zip) do (
Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
)
exit /b
If you don't want it to create a folder for each zip, change
Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
to
Call :UnZipFile "C:\Temp\" "c:\path\to\%%~nxa"
Here's a list of the environment variables. I think you might want CURRENT_VARIANT
. See also BUILD_VARIANTS
.
Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Then you could use
Call fso.CopyFile(source, destination[, overwrite] )
where source and destination are the full names (including paths) of the file.
See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
You can use for loop to untar multiple .tar.gz files to another folder. The following code will take /destination/folder/path as an argument to the script and untar all .tar.gz files present at the current location in /destination/folder/path.
if [ $# -ne 1 ];
then
echo "invalid argument/s"
echo "Usage: ./script-file-name.sh /target/directory"
exit 0
fi
for file in *.tar.gz
do
tar -zxvf "$file" --directory $1
done
Let me try example
for x in 1 2 3 ; do { echo a $x ; sleep 1 ; echo b $x ; } & done ; sleep 10
And use jobs
to see what's running.
create another class and increase the with size with 2px example
.enquiry_fld_normal{
width:278px !important;
}
.enquiry_fld_normal_select{
width:280px !important;
}
If you want to run your scripts, then
mysql -u root -p < yourscript.sql
Here is a one-liner that can be extended with grep to filter by name.
kubectl get pods -o jsonpath="{.items[*].metadata.name}" | \
tr " " "\n" | \
xargs -i -P 0 kubectl delete pods {}
For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);
Root<SomeClass> root = criteriaQuery.from(SomeClass.class);
Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");
Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);
Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);
Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);
criteriaQuery
.select(root)
.where(predicateResult);
List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
You need the sleep
method of the Thread
class.
public static void sleep (long time)
Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds). The precision is not guaranteed - the Thread may sleep more or less than requested.
Parameters
time
The time to sleep in milliseconds.
You can edit style with pure Javascript. No library needed, supported by all browsers except IE where you need to set to ''
instead of null
(see comments).
var element = document.getElementById('sample_id');
element.style.width = null;
element.style.height = null;
For more information, you can refer to HTMLElement.style documentation on MDN.
By combining contributions from many enthusiasts (including Glenn Maynard and MrHIDEn from above comments), I came up with following piece of code in python 2:
def simpleSieve(sieveSize):
#creating Sieve.
sieve = [True] * (sieveSize+1)
# 0 and 1 are not considered prime.
sieve[0] = False
sieve[1] = False
for i in xrange(2,int(math.sqrt(sieveSize))+1):
if sieve[i] == False:
continue
for pointer in xrange(i**2, sieveSize+1, i):
sieve[pointer] = False
# Sieve is left with prime numbers == True
primes = []
for i in xrange(sieveSize+1):
if sieve[i] == True:
primes.append(i)
return primes
sieveSize = input()
primes = simpleSieve(sieveSize)
Time taken for computation on my machine for different inputs in power of 10 is:
I like this for log4j:
log4j.logger.org.hibernate.SQL=trace
log4j.logger.org.hibernate.engine.query=trace
log4j.logger.org.hibernate.type=trace
log4j.logger.org.hibernate.jdbc=trace
log4j.logger.org.hibernate.type.descriptor.sql.BasicExtractor=error
log4j.logger.org.hibernate.type.CollectionType=error
As the other posters say, pull merges changes from upstream into your repository. If you want to replace what is in your repository with what is in upstream, you have several options. Off the cuff, I'd go with
git checkout HEAD^1 # Get off your repo's master.. doesn't matter where you go, so just go back one commit
git branch -d master # Delete your repo's master branch
git checkout -t upstream/master # Check out upstream's master into a local tracking branch of the same name
I combine Alexandre Jasmin and Gab Le Roux answers like this:
[![Demo CountPages alpha](https://share.gifyoutube.com/KzB6Gb.gif)](https://www.youtube.com/watch?v=ek1j272iAmc)
Demo:
You can see this demo on github.
I used gifyoutube here, but I recommend using a local gif converter (like ffmpeg, see how) instead of an online one.
To record your screen to gif directly, you may want to check ScreenToGif.
Here's a workaround. If you want to copy everything from A that does not already exist in B:
Copy A to a new directory C. Copy B to C, overwriting anything that overlaps with A. Copy C to B.
Simplest way is:
bgSound = new Audio("sounds/background.mp3");
bgSound.loop = true;
bgSound.play();
in addition: for those who have a empty POST variable, don't use this:
name="[levels][level][]"
rather use this (as it is already here in this example):
name="levels[level][]"
I think that you should make the reference to your config file
26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf
you can try to start your redis server like
./redis-server /path/to/redis-stable/redis.conf
Problem 1
You mentioned it was your private docker registry, so you probably need to check Registry API instead of Hub registry API doc, which is the link you provided.
Problem 2
docker registry API is a client/server protocol, it is up to the server's implementation on whether to remove the images in the back-end. (I guess)
DELETE /v1/repositories/(namespace)/(repository)/tags/(tag*)
Detailed explanation
Below I demo how it works now from your description as my understanding for your questions.
I run a private docker registry.
I use the default one, and listen on port 5000
.
docker run -d -p 5000:5000 registry
Then I tag the local image and push into it.
$ docker tag ubuntu localhost:5000/ubuntu
$ docker push localhost:5000/ubuntu
The push refers to a repository [localhost:5000/ubuntu] (len: 1)
Sending image list
Pushing repository localhost:5000/ubuntu (1 tags)
511136ea3c5a: Image successfully pushed
d7ac5e4f1812: Image successfully pushed
2f4b4d6a4a06: Image successfully pushed
83ff768040a0: Image successfully pushed
6c37f792ddac: Image successfully pushed
e54ca5efa2e9: Image successfully pushed
Pushing tag for rev [e54ca5efa2e9] on {http://localhost:5000/v1/repositories/ubuntu/tags/latest}
After that I can use Registry API to check it exists in your private docker registry
$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags
{"latest": "e54ca5efa2e962582a223ca9810f7f1b62ea9b5c3975d14a5da79d3bf6020f37"}
Now I can delete the tag using that API !!
$ curl -X DELETE localhost:5000/v1/repositories/ubuntu/tags/latest
true
Check again, the tag doesn't exist in my private registry server
$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags/latest
{"error": "Tag not found"}
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form $('form[name=form1] input[type=text]') Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
It's a bug of RadioGroup
RadioButton radioBtn2 = new RadioButton(context);
radioBtn2 without viewId, and generateViewId is in onChildViewAdded()
public void onChildViewAdded(View parent, View child) {
if (parent == RadioGroup.this && child instanceof RadioButton) {
int id = child.getId();
// generates an id if it's missing
if (id == View.NO_ID) {
id = View.generateViewId();
child.setId(id);
}
((RadioButton) child).setOnCheckedChangeWidgetListener(
mChildOnCheckedChangeListener);
}
if (mOnHierarchyChangeListener != null) {
mOnHierarchyChangeListener.onChildViewAdded(parent, child);
}
}
so, first radioGroup.addView(radioBtn2), then radioBtn2.setChecked(true);
Like this:
RadioGroup radioGroup = new RadioGroup(context);
RadioButton radioBtn1 = new RadioButton(context);
RadioButton radioBtn2 = new RadioButton(context);
RadioButton radioBtn3 = new RadioButton(context);
radioBtn1.setText("Less");
radioBtn2.setText("Normal");
radioBtn3.setText("More");
radioGroup.addView(radioBtn1);
radioGroup.addView(radioBtn2);
radioGroup.addView(radioBtn3);
radioBtn2.setChecked(true);
It looks like the JavaScript error your getting is probably being caused by
password: {
required:true,
rangelenght:[4.20]
},
As the [4.20]
should be [4,20]
, which i'd guess is throwing off the validation code in additional-methods
hence giving the type error's you posted.
Edit: As others have noted in the below comments rangelenght
is also misspelled & jquery.validate.js
library appears to be missing (assuming its not compiled in to one of your other assets)
Just in case this helps anyone else; this error can occur in Visual Studio if you have a View as the open tab, and that tab depends on a parameter.
Close the current view and start your application and the app will start 'Normally'; if you have a view open, Visual Studio interprets this as you want to run the current view.
You can try out the package jpflat.
It flattens, inflates, resolves promises, flattens arrays, has customizable path creation and customizable value serialization.
The reducers and serializers receive the whole path as an array of it's parts, so more complex operations can be done to the path instead of modifying a single key or changing the delimiter.
Json path is the default, hence "jp"flat.
https://www.npmjs.com/package/jpflat
let flatFoo = await require('jpflat').flatten(foo)
If its only for validating you could do: 887979789 > 99999999
It doesn't take the 50% of the whole page is because the "whole page" is only how tall your contents are. Change the enclosing html
and body
to 100%
height and it will work.
html, body{
height: 100%;
}
div{
height: 50%;
}
http://jsfiddle.net/DerekL/5YukJ/1/
^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.
^ Now if you change the height of the document to the height of the whole page (150px), 50% of 150px is 75px, then it will work.
Update:
Separate the event and property bindings:
<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
console.log(newValue);
this.selectedItem = newValue; // don't forget to update the model here
// ... do other stuff here ...
}
You could also use
<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">
and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.
Old answer, before they fixed a bug in beta.1:
Create a local template variable and attach a (change)
event:
<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">
See also How can I get new selection in "select" in Angular 2?
Well I know this maybe rather dumb than and simple, but I think it should work:
string n;
cin>> n;
char b[200];
for (int i = 0; i < sizeof(n); i++)
{
b[i] = n[i];
cout<< b[i]<< " ";
}
The steps are very simple and it'll take just few mins. 1.Go to your C drive and in that go to the 'USER' section. 2.Under 'USER' section go to your 'name(e.g-'user1') and then find ".eclipse" folder and delete that folder 3.Along with that folder also delete "eclipse" folder and you can find that you're work has been done completely.
Use KeyPressEventArgs,
Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
e.Handled = True
End Sub
In typescript you can do the following to suppress the error
:
let subString?: string;
subString > !null;
- Note the added exclamation mark before null.
I think @Zack properly answered the question but just to cover all the bases:
Update myTable set MyColumn = NULL
This would set the entire column to null as the Question Title asks.
To set a specific row on a specific column to null use:
Update myTable set MyColumn = NULL where Field = Condition.
This would set a specific cell to null as the inner question asks.
Always : If you always want vertical scrollbar, use overflow-y: scroll;
<div style="overflow-y: scroll;">
......
</div>
When needed: If you only want vertical scrollbar when needed, use overflow-y: auto;
(You need to specify a height in this case)
<div style="overflow-y: auto; height:150px; ">
....
</div>
This may be very old. But for those whose looking for a quick code.
public String handleEscapeCharacter( String str ) {
String[] escapeCharacters = { ">", "<", "&", """, "'" };
String[] onReadableCharacter = {">", "<", "&", "\"\"", "'"};
for (int i = 0; i < escapeCharacters.length; i++) {
str = str.replace(escapeCharacters[i], onReadableCharacter[i]);
} return str;
}
That handles escape characters, you can add characters and symbols on their respective arrays.
-Cheers
Make it simple : DEMO
section {_x000D_
display: flex;_x000D_
flex-flow: column;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
header {_x000D_
background: tomato;_x000D_
/* no flex rules, it will grow */_x000D_
}_x000D_
_x000D_
div {_x000D_
flex: 1; /* 1 and it will fill whole space left if no flex value are set to other children*/_x000D_
background: gold;_x000D_
overflow: auto;_x000D_
}_x000D_
_x000D_
footer {_x000D_
background: lightgreen;_x000D_
min-height: 60px; /* min-height has its purpose :) , unless you meant height*/_x000D_
}
_x000D_
<section>_x000D_
<header>_x000D_
header: sized to content_x000D_
<br/>(but is it really?)_x000D_
</header>_x000D_
<div>_x000D_
main content: fills remaining space<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
<!-- uncomment to see it break -->_x000D_
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
<!-- -->_x000D_
</div>_x000D_
<footer>_x000D_
footer: fixed height in px_x000D_
</footer>_x000D_
</section>
_x000D_
Full screen version
section {_x000D_
display: flex;_x000D_
flex-flow: column;_x000D_
height: 100vh;_x000D_
}_x000D_
_x000D_
header {_x000D_
background: tomato;_x000D_
/* no flex rules, it will grow */_x000D_
}_x000D_
_x000D_
div {_x000D_
flex: 1;_x000D_
/* 1 and it will fill whole space left if no flex value are set to other children*/_x000D_
background: gold;_x000D_
overflow: auto;_x000D_
}_x000D_
_x000D_
footer {_x000D_
background: lightgreen;_x000D_
min-height: 60px;_x000D_
/* min-height has its purpose :) , unless you meant height*/_x000D_
}_x000D_
_x000D_
body {_x000D_
margin: 0;_x000D_
}
_x000D_
<section>_x000D_
<header>_x000D_
header: sized to content_x000D_
<br/>(but is it really?)_x000D_
</header>_x000D_
<div>_x000D_
main content: fills remaining space<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
<!-- uncomment to see it break -->_x000D_
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
<!-- -->_x000D_
</div>_x000D_
<footer>_x000D_
footer: fixed height in px_x000D_
</footer>_x000D_
</section>
_x000D_
You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType
value. If I have two rows with the same FruitType
value but different Fruit_Id
values for example, what should the system do?
Select Min(tblFruit_id) As tblFruit_id
, tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType
To know if the iCheck box is checked
var isChecked = $("#myicheckboxid").prop("checked");
pde is extesion for:
Processing: Java derived language
Wiring: C/C++ derived language (Wiring is derived from Processing)
Early versions of Arduino: C/C++ derived (Arduino IDE is derived from Wiring)
For Arduino for example the IDE preprocessor is adding some #defines and some C/C++ files before giving all to gcc.
public class someClass
{
public static void main(String[] args) // your app start point
{
long start = java.util.Calendar.getInstance().getTimeInMillis();
... your stuff ...
long end = java.util.Calendar.getInstance().getTimeInMillis();
System.out.println("it took this long to complete this stuff: " + (end - start) + "ms");
}
}
You are making an ajax request which is asynchronous therefore your console log of the list length occurs before the ajax request has completed.
The only way of achieving what you want is changing the ajax call to be synchronous. You can do this by using the .ajax and passing in asynch : false however this is not recommended as it locks the UI up until the call has returned, if it fails to return the user has to crash out of the browser.
Object to array
$array = (array) $players_Obj;
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
Output:
array(2) {
'foo' => int(1)
'bar' => int(2)
}
It's a little late but...
script.
loginName="#{login}";
This is working fine in my script. In Express, I am doing this:
exports.index = function(req, res){
res.render( 'index', { layout:false, login: req.session.login } );
};
I guess the latest jade is different?
Merc.
edit: added "." after script to prevent Jade warning.
While @perrejba s answer is correct, it uses the legacy C-style functions. As the question is tagged C++, you may want to use a method instead:
inputMat.copyTo(outputMat, maskMat);
All objects are of type cv::Mat
.
Please be aware that the masking is binary. Any non-zero value in the mask is interpreted as 'do copy'. Even if the mask is a greyscale image.
Also be aware that the .copyTo() function does not clear the output before copying.
If you want to permanently alter the original Image, you have to do an additional copy/clone/assignment. The copyTo() function is not defined for overlapping input/output images. So you can't use the same image as both input and output.
In my case TLS1_2 was enabled both on client and server but the server was using MD5 while client disabled it. So, test both client and server on http://ssllabs.com or test using openssl/s_client to see what's happening. Also, check the selected cipher using Wireshark.
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
Actually, this is a duplicate of Encrypt Password in Configuration Files?.
The best solution I found so far is in this answert: https://stackoverflow.com/a/1133815/1549977
Pros: Password is saved a a char array, not as a string. It's still not good, but better than anything else.
you can simply bind @Hostlistener with the component, and rest will take care by it. It won't need binding of any method from its HTML template.
@HostListener('keydown',['$event'])
onkeydown(event:keyboardEvent){
if(event.key == 'Enter'){
// TODO do something here
// form.submit() OR API hit for any http method
}
}
The above code should work with Angular 1+ version
Tumblr has a public API that provides JSON. You can get a dump of posts using a simple url like http://puppygifs.tumblr.com/api/read/json
.
Yes, you could use either the JavaScript setTimeout()
method or setInterval()
method to invoke the code that you would like to run. Here's how you might do it with setTimeout:
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}
$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});
There are couple of options to achieve that:
The fastest ():
while (node.lastChild) {
node.removeChild(node.lastChild);
}
Alternatives (slower):
while (node.firstChild) {
node.removeChild(node.firstChild);
}
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
Bootstrap 3 has been released since this question was originally answered in January, so if you are a BS3 user, please refer to the BS3 documentation. For those still on BS2, the original answer still applies. If you are interested in switching from 2 to 3, see the migration guide.
From the bootstrap 2 docs:
Make any row "fluid" by changing .row to .row-fluid. The column classes stay the exact same, making it easy to flip between fixed and fluid grids.
Code
<div class="row-fluid">
<div class="span4">...</div>
<div class="span8">...</div>
</div>
This, in conjunction with setting the width of your container to a fluid value, should allow you to get your desired layout.
another example:
request:
curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y
then:
request.method: GET
request.url: http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url: http://127.0.0.1:5000/alert/dingding/test
request.url_charset: utf-8
request.url_root: http://127.0.0.1:5000/
str(request.url_rule): /alert/dingding/test
request.host_url: http://127.0.0.1:5000/
request.host: 127.0.0.1:5000
request.script_root:
request.path: /alert/dingding/test
request.full_path: /alert/dingding/test?x=y
request.args: ImmutableMultiDict([('x', 'y')])
request.args.get('x'): y
It was fixed for me after removing and re-adding the Android and Android-Gradle Facets in the Module Settings dialog.
Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so
let markdown = `
1. Apple
2. Mango
this is juicy
3. Orange
`
Techniques I gathered from other answers:
Makes a 0 byte file a very clear, backward-compatible way:
type nul >EmptyFile.txt
idea via: anonymous, Danny Backett, possibly others, myself inspired by JdeBP's work
A 0 byte file another way, it's backward-compatible-looking:
REM. >EmptyFile.txt
idea via: Johannes
A 0 byte file 3rd way backward-compatible-looking, too:
echo. 2>EmptyFile.txt
idea via: TheSmurf
A 0 byte file the systematic way probably available since Windows 2000:
fsutil file createnew EmptyFile.txt 0
idea via: Emm
A 0 bytes file overwriting readonly files
ATTRIB -R filename.ext>NUL
(CD.>filename.ext)2>NUL
idea via: copyitright
A single newline (2 bytes: 0x0D 0x0A
in hex notation, alternatively written as \r\n
):
echo.>AlmostEmptyFile.txt
Note: no space between echo
, .
and >
.
idea via: How can you echo a newline in batch files?
edit It seems that any invalid command redirected to a file would create an empty file. heh, a feature! compatibility: uknown
TheInvisibleFeature <nul >EmptyFile.txt
A 0 bytes file: invalid command/ with a random name (compatibility: uknown):
%RANDOM%-%TIME:~6,5% <nul >EmptyFile.txt
via: great source for random by Hung Huynh
edit 2 Andriy M points out the probably most amusing/provoking way to achieve this via invalid command
A 0 bytes file: invalid command/ the funky way (compatibility: unknown)
*>EmptyFile.txt
idea via: Andriy M
A 0 bytes file 4th-coming way:
break > file.txt
idea via: foxidrive thanks to comment of Double Gras!
You can use attributes of html tag instead of validation from html input type ="date" can be used instead of validating it. That's the benifits html 5 gives you
The 1.3 docs offer a very simple solution: KeyedTuple._asdict()
def to_array(rows):
return [r._asdict() for r in rows]
def query():
data = session.query(Table).all()
return to_array(data)
Thread share the heap (there is a research about thread specific heap) but current implementation share the heap. (and of course the code)
Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there.
<img id="photo"
onload='loaded(this.id)'
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
PHP has a built-in function file_get_contents(), which reads the content of a file into a string.
<?php
//Get the file
$content = file_get_contents("http://example.com/image.jpg");
//Store in the filesystem. $fp = fopen("/location/to/save/image.jpg", "w"); fwrite($fp, $content); fclose($fp); ?> If you wish to store the file in a database, simply use the $content variable and don't save the file to disk.
If you try to login on site with cookies.
This code:
if ($server_output == "OK") { ... } else { ... }
May not works if you try to login, because many sites returns status 200, but the post is not successful.
Easy way to check if the login post is successful is check if it setting cookies again. If in output have Set-Cookies string, this means the posts is not successful and it starts new session.
Also the post can be successful, but the status can be redirect instead 200.
To be sure the post is successful try this:
Follow location after the post, so it will go to the page where the post do redirect to:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
And than check if new cookies existing in the request:
if (!preg_match('/^Set-Cookie:\s*([^;]*)/mi', $server_output))
{echo 'post successful'; }
else { echo 'not successful'; }
Well maybe a little late after 4 years haha... but I was looking for solution to do OBJECT to CSV, however most solutions here is actually for ARRAY to CSV...
After some tinkering, here is my solution to convert object into CSV, I think is pretty neat. Hope this would help someone else.
$resp = array();
foreach ($entries as $entry) {
$row = array();
foreach ($entry as $key => $value) {
array_push($row, $value);
}
array_push($resp, implode(',', $row));
}
echo implode(PHP_EOL, $resp);
Note that for the $key => $value
to work, your object
's attributes must be public, the private ones will not get fetched.
The end result is that you get something like this:
blah,blah,blah
blah,blah,blah
The problem is even if you create a proxy or load the content and inject it as if it's local, any scripts that that content defines will be loaded from the other domain and cause cross-domain problems.
Regarding the beautiful code of Raghunandan above.
Many have asked how to "clear" the drawing. Here's how to do that:
public void clearDrawing()
{
Utils.Log("RaghunandanDraw, how to clear....");
setDrawingCacheEnabled(false);
// don't forget that one and the match below,
// or you just keep getting a duplicate when you save.
onSizeChanged(width, height, width, height);
invalidate();
setDrawingCacheEnabled(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
width = w; // don't forget these
height = h;
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
Many have asked how to "save" the drawing. Here's how to do that:
public DrawingView(Context c)
{
circlePaint.setStrokeJoin(Paint.Join.MITER);
circlePaint.setStrokeWidth(4f);
etc...
// in the class where you set up the view, add this:
setDrawingCacheEnabled( true );
}
public void saveDrawing()
{
Bitmap whatTheUserDrewBitmap = getDrawingCache();
// don't forget to clear it (see above) or you just get duplicates
// almost always you will want to reduce res from the very high screen res
whatTheUserDrewBitmap =
ThumbnailUtils.extractThumbnail(whatTheUserDrewBitmap, 256, 256);
// NOTE that's an incredibly useful trick for cropping/resizing squares
// while handling all memory problems etc
// http://stackoverflow.com/a/17733530/294884
// you can now save the bitmap to a file, or display it in an ImageView:
ImageView testArea = ...
testArea.setImageBitmap( whatTheUserDrewBitmap );
// these days you often need a "byte array". for example,
// to save to parse.com or other cloud services
ByteArrayOutputStream baos = new ByteArrayOutputStream();
whatTheUserDrewBitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
byte[] yourByteArray;
yourByteArray = baos.toByteArray();
}
Hope it helps someone as this has helped me.
if you are using Spring data you can also use the Range object from Spring.
range = new org.springframework.data.domain.Range(3, 8); range.contains(5) will return true.
Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:
<script type="text/javascript">
$(function() {
$('form').submit(function(){
$.post('http://example.com/upload', function() {
window.location = 'http://google.com';
});
return false;
});
});
</script>
I actually did a research in this topic for months in my free time and came up with a benchmark and here is a code to benchmark all the different ways to read a File line by line.The individual performance may vary based on the underlying system. I ran on a windows 10 Java 8 Intel i5 HP laptop:Here is the code.
import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class ReadComplexDelimitedFile {
private static long total = 0;
private static final Pattern FIELD_DELIMITER_PATTERN = Pattern.compile("\\^\\|\\^");
@SuppressWarnings("unused")
private void readFileUsingScanner() {
String s;
try (Scanner stdin = new Scanner(new File(this.getClass().getResource("input.txt").getPath()))) {
while (stdin.hasNextLine()) {
s = stdin.nextLine();
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total = total + fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
//Winner
private void readFileUsingCustomBufferedReader() {
try (CustomBufferedReader stdin = new CustomBufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total += fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
private void readFileUsingBufferedReader() {
try (BufferedReader stdin = new BufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total += fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
private void readFileUsingLineReader() {
try (LineNumberReader stdin = new LineNumberReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total += fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
private void readFileUsingStreams() {
try (Stream<String> stream = Files.lines((new File(this.getClass().getResource("input.txt").getPath())).toPath())) {
total += stream.mapToInt(s -> FIELD_DELIMITER_PATTERN.split(s, 0).length).sum();
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void readFileUsingBufferedReaderFileChannel() {
try (FileInputStream fis = new FileInputStream(this.getClass().getResource("input.txt").getPath())) {
try (FileChannel inputChannel = fis.getChannel()) {
try (CustomBufferedReader stdin = new CustomBufferedReader(Channels.newReader(inputChannel, "UTF-8"))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total = total + fields.length;
}
}
} catch (Exception e) {
System.err.println("Error");
}
} catch (Exception e) {
System.err.println("Error");
}
}
public static void main(String args[]) {
//JVM wamrup
for (int i = 0; i < 100000; i++) {
total += i;
}
// We know scanner is slow-Still warming up
ReadComplexDelimitedFile readComplexDelimitedFile = new ReadComplexDelimitedFile();
List<Long> longList = new ArrayList<>(50);
for (int i = 0; i < 50; i++) {
total = 0;
long startTime = System.nanoTime();
//readComplexDelimitedFile.readFileUsingScanner();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingScanner");
longList.forEach(System.out::println);
// Actual performance test starts here
longList = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingBufferedReaderFileChannel();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingBufferedReaderFileChannel");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingBufferedReader();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingBufferedReader");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingStreams();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingStreams");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingCustomBufferedReader();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingCustomBufferedReader");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingLineReader();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingLineReader");
longList.forEach(System.out::println);
}
}
I had to rewrite BufferedReader to avoid synchronized and a couple of boundary conditions that is not needed.(Atleast that's what I felt.It is not unit tested so use it at your own risk.)
import com.sun.istack.internal.NotNull;
import java.io.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Reads text from a character-input stream, buffering characters so as to
* provide for the efficient reading of characters, arrays, and lines.
* <p>
* <p> The buffer size may be specified, or the default size may be used. The
* default is large enough for most purposes.
* <p>
* <p> In general, each read request made of a Reader causes a corresponding
* read request to be made of the underlying character or byte stream. It is
* therefore advisable to wrap a CustomBufferedReader around any Reader whose read()
* operations may be costly, such as FileReaders and InputStreamReaders. For
* example,
* <p>
* <pre>
* CustomBufferedReader in
* = new CustomBufferedReader(new FileReader("foo.in"));
* </pre>
* <p>
* will buffer the input from the specified file. Without buffering, each
* invocation of read() or readLine() could cause bytes to be read from the
* file, converted into characters, and then returned, which can be very
* inefficient.
* <p>
* <p> Programs that use DataInputStreams for textual input can be localized by
* replacing each DataInputStream with an appropriate CustomBufferedReader.
*
* @author Mark Reinhold
* @see FileReader
* @see InputStreamReader
* @see java.nio.file.Files#newBufferedReader
* @since JDK1.1
*/
public class CustomBufferedReader extends Reader {
private final Reader in;
private char cb[];
private int nChars, nextChar;
private static final int INVALIDATED = -2;
private static final int UNMARKED = -1;
private int markedChar = UNMARKED;
private int readAheadLimit = 0; /* Valid only when markedChar > 0 */
/**
* If the next character is a line feed, skip it
*/
private boolean skipLF = false;
/**
* The skipLF flag when the mark was set
*/
private boolean markedSkipLF = false;
private static int defaultCharBufferSize = 8192;
private static int defaultExpectedLineLength = 80;
private ReadWriteLock rwlock;
/**
* Creates a buffering character-input stream that uses an input buffer of
* the specified size.
*
* @param in A Reader
* @param sz Input-buffer size
* @throws IllegalArgumentException If {@code sz <= 0}
*/
public CustomBufferedReader(@NotNull final Reader in, int sz) {
super(in);
if (sz <= 0)
throw new IllegalArgumentException("Buffer size <= 0");
this.in = in;
cb = new char[sz];
nextChar = nChars = 0;
rwlock = new ReentrantReadWriteLock();
}
/**
* Creates a buffering character-input stream that uses a default-sized
* input buffer.
*
* @param in A Reader
*/
public CustomBufferedReader(@NotNull final Reader in) {
this(in, defaultCharBufferSize);
}
/**
* Fills the input buffer, taking the mark into account if it is valid.
*/
private void fill() throws IOException {
int dst;
if (markedChar <= UNMARKED) {
/* No mark */
dst = 0;
} else {
/* Marked */
int delta = nextChar - markedChar;
if (delta >= readAheadLimit) {
/* Gone past read-ahead limit: Invalidate mark */
markedChar = INVALIDATED;
readAheadLimit = 0;
dst = 0;
} else {
if (readAheadLimit <= cb.length) {
/* Shuffle in the current buffer */
System.arraycopy(cb, markedChar, cb, 0, delta);
markedChar = 0;
dst = delta;
} else {
/* Reallocate buffer to accommodate read-ahead limit */
char ncb[] = new char[readAheadLimit];
System.arraycopy(cb, markedChar, ncb, 0, delta);
cb = ncb;
markedChar = 0;
dst = delta;
}
nextChar = nChars = delta;
}
}
int n;
do {
n = in.read(cb, dst, cb.length - dst);
} while (n == 0);
if (n > 0) {
nChars = dst + n;
nextChar = dst;
}
}
/**
* Reads a single character.
*
* @return The character read, as an integer in the range
* 0 to 65535 (<tt>0x00-0xffff</tt>), or -1 if the
* end of the stream has been reached
* @throws IOException If an I/O error occurs
*/
public char readChar() throws IOException {
for (; ; ) {
if (nextChar >= nChars) {
fill();
if (nextChar >= nChars)
return (char) -1;
}
return cb[nextChar++];
}
}
/**
* Reads characters into a portion of an array, reading from the underlying
* stream if necessary.
*/
private int read1(char[] cbuf, int off, int len) throws IOException {
if (nextChar >= nChars) {
/* If the requested length is at least as large as the buffer, and
if there is no mark/reset activity, and if line feeds are not
being skipped, do not bother to copy the characters into the
local buffer. In this way buffered streams will cascade
harmlessly. */
if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
return in.read(cbuf, off, len);
}
fill();
}
if (nextChar >= nChars) return -1;
int n = Math.min(len, nChars - nextChar);
System.arraycopy(cb, nextChar, cbuf, off, n);
nextChar += n;
return n;
}
/**
* Reads characters into a portion of an array.
* <p>
* <p> This method implements the general contract of the corresponding
* <code>{@link Reader#read(char[], int, int) read}</code> method of the
* <code>{@link Reader}</code> class. As an additional convenience, it
* attempts to read as many characters as possible by repeatedly invoking
* the <code>read</code> method of the underlying stream. This iterated
* <code>read</code> continues until one of the following conditions becomes
* true: <ul>
* <p>
* <li> The specified number of characters have been read,
* <p>
* <li> The <code>read</code> method of the underlying stream returns
* <code>-1</code>, indicating end-of-file, or
* <p>
* <li> The <code>ready</code> method of the underlying stream
* returns <code>false</code>, indicating that further input requests
* would block.
* <p>
* </ul> If the first <code>read</code> on the underlying stream returns
* <code>-1</code> to indicate end-of-file then this method returns
* <code>-1</code>. Otherwise this method returns the number of characters
* actually read.
* <p>
* <p> Subclasses of this class are encouraged, but not required, to
* attempt to read as many characters as possible in the same fashion.
* <p>
* <p> Ordinarily this method takes characters from this stream's character
* buffer, filling it from the underlying stream as necessary. If,
* however, the buffer is empty, the mark is not valid, and the requested
* length is at least as large as the buffer, then this method will read
* characters directly from the underlying stream into the given array.
* Thus redundant <code>CustomBufferedReader</code>s will not copy data
* unnecessarily.
*
* @param cbuf Destination buffer
* @param off Offset at which to start storing characters
* @param len Maximum number of characters to read
* @return The number of characters read, or -1 if the end of the
* stream has been reached
* @throws IOException If an I/O error occurs
*/
public int read(char cbuf[], int off, int len) throws IOException {
int n = read1(cbuf, off, len);
if (n <= 0) return n;
while ((n < len) && in.ready()) {
int n1 = read1(cbuf, off + n, len - n);
if (n1 <= 0) break;
n += n1;
}
return n;
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @param ignoreLF If true, the next '\n' will be skipped
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
* @throws IOException If an I/O error occurs
* @see java.io.LineNumberReader#readLine()
*/
String readLine(boolean ignoreLF) throws IOException {
StringBuilder s = null;
int startChar;
bufferLoop:
for (; ; ) {
if (nextChar >= nChars)
fill();
if (nextChar >= nChars) { /* EOF */
if (s != null && s.length() > 0)
return s.toString();
else
return null;
}
boolean eol = false;
char c = 0;
int i;
/* Skip a leftover '\n', if necessary */
charLoop:
for (i = nextChar; i < nChars; i++) {
c = cb[i];
if ((c == '\n')) {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if (eol) {
String str;
if (s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
return str;
}
if (s == null)
s = new StringBuilder(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
* @throws IOException If an I/O error occurs
* @see java.nio.file.Files#readAllLines
*/
public String readLine() throws IOException {
return readLine(false);
}
/**
* Skips characters.
*
* @param n The number of characters to skip
* @return The number of characters actually skipped
* @throws IllegalArgumentException If <code>n</code> is negative.
* @throws IOException If an I/O error occurs
*/
public long skip(long n) throws IOException {
if (n < 0L) {
throw new IllegalArgumentException("skip value is negative");
}
rwlock.readLock().lock();
long r = n;
try{
while (r > 0) {
if (nextChar >= nChars)
fill();
if (nextChar >= nChars) /* EOF */
break;
if (skipLF) {
skipLF = false;
if (cb[nextChar] == '\n') {
nextChar++;
}
}
long d = nChars - nextChar;
if (r <= d) {
nextChar += r;
r = 0;
break;
} else {
r -= d;
nextChar = nChars;
}
}
} finally {
rwlock.readLock().unlock();
}
return n - r;
}
/**
* Tells whether this stream is ready to be read. A buffered character
* stream is ready if the buffer is not empty, or if the underlying
* character stream is ready.
*
* @throws IOException If an I/O error occurs
*/
public boolean ready() throws IOException {
rwlock.readLock().lock();
try {
/*
* If newline needs to be skipped and the next char to be read
* is a newline character, then just skip it right away.
*/
if (skipLF) {
/* Note that in.ready() will return true if and only if the next
* read on the stream will not block.
*/
if (nextChar >= nChars && in.ready()) {
fill();
}
if (nextChar < nChars) {
if (cb[nextChar] == '\n')
nextChar++;
skipLF = false;
}
}
} finally {
rwlock.readLock().unlock();
}
return (nextChar < nChars) || in.ready();
}
/**
* Tells whether this stream supports the mark() operation, which it does.
*/
public boolean markSupported() {
return true;
}
/**
* Marks the present position in the stream. Subsequent calls to reset()
* will attempt to reposition the stream to this point.
*
* @param readAheadLimit Limit on the number of characters that may be
* read while still preserving the mark. An attempt
* to reset the stream after reading characters
* up to this limit or beyond may fail.
* A limit value larger than the size of the input
* buffer will cause a new buffer to be allocated
* whose size is no smaller than limit.
* Therefore large values should be used with care.
* @throws IllegalArgumentException If {@code readAheadLimit < 0}
* @throws IOException If an I/O error occurs
*/
public void mark(int readAheadLimit) throws IOException {
if (readAheadLimit < 0) {
throw new IllegalArgumentException("Read-ahead limit < 0");
}
rwlock.readLock().lock();
try {
this.readAheadLimit = readAheadLimit;
markedChar = nextChar;
markedSkipLF = skipLF;
} finally {
rwlock.readLock().unlock();
}
}
/**
* Resets the stream to the most recent mark.
*
* @throws IOException If the stream has never been marked,
* or if the mark has been invalidated
*/
public void reset() throws IOException {
rwlock.readLock().lock();
try {
if (markedChar < 0)
throw new IOException((markedChar == INVALIDATED)
? "Mark invalid"
: "Stream not marked");
nextChar = markedChar;
skipLF = markedSkipLF;
} finally {
rwlock.readLock().unlock();
}
}
public void close() throws IOException {
rwlock.readLock().lock();
try {
in.close();
} finally {
cb = null;
rwlock.readLock().unlock();
}
}
public Stream<String> lines() {
Iterator<String> iter = new Iterator<String>() {
String nextLine = null;
@Override
public boolean hasNext() {
if (nextLine != null) {
return true;
} else {
try {
nextLine = readLine();
return (nextLine != null);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@Override
public String next() {
if (nextLine != null || hasNext()) {
String line = nextLine;
nextLine = null;
return line;
} else {
throw new NoSuchElementException();
}
}
};
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
}
}
And now the results:
Time taken for readFileUsingBufferedReaderFileChannel 2902690903 1845190694 1894071377 1815161868 1861056735 1867693540 1857521371 1794176251 1768008762 1853089582
Time taken for readFileUsingBufferedReader 2022837353 1925901163 1802266711 1842689572 1899984555 1843101306 1998642345 1821242301 1820168806 1830375108
Time taken for readFileUsingStreams 1992855461 1930827034 1850876033 1843402533 1800378283 1863581324 1810857226 1798497108 1809531144 1796345853
Time taken for readFileUsingCustomBufferedReader 1759732702 1765987214 1776997357 1772999486 1768559162 1755248431 1744434555 1750349867 1740582606 1751390934
Time taken for readFileUsingLineReader 1845307174 1830950256 1829847321 1828125293 1827936280 1836947487 1832186310 1820276327 1830157935 1829171481
Process finished with exit code 0
Inference: The test was run on a 200 MB file. The test was repeated several times. The data looked like this
Start Date^|^Start Time^|^End Date^|^End Time^|^Event Title ^|^All Day Event^|^No End Time^|^Event Description^|^Contact ^|^Contact Email^|^Contact Phone^|^Location^|^Category^|^Mandatory^|^Registration^|^Maximum^|^Last Date To Register
9/5/2011^|^3:00:00 PM^|^9/5/2011^|^^|^Social Studies Dept. Meeting^|^N^|^Y^|^Department meeting^|^Chris Gallagher^|^[email protected]^|^814-555-5179^|^High School^|^2^|^N^|^N^|^25^|^9/2/2011
Bottomline not much difference between BufferedReader and my CustomReader and it is very miniscule and hence you can use this to read your file.
Trust me you don't have to break your head.use BufferedReader with readLine,it is properly tested.At worst if you feel you can improve it just override and change it to StringBuilder instead of StringBuffer just to shave off half a second
It seems to be working fine:
List<BigDecimal> list = Arrays.asList(new BigDecimal("24.455"), new BigDecimal("23.455"), new BigDecimal("28.455"), new BigDecimal("20.455"));
System.out.println("Unsorted list: " + list);
final List<BigDecimal> sortedList = list.stream().sorted((o1, o2) -> o1.compareTo(o2)).collect(Collectors.toList());
System.out.println("Sorted list: " + sortedList);
Example Input/Output
Unsorted list: [24.455, 23.455, 28.455, 20.455]
Sorted list: [20.455, 23.455, 24.455, 28.455]
Are you sure you are not verifying list instead of sortedList
[in above example] i.e. you are storing the result of stream()
in a new List
object and verifying that object?
Don't see any answers here that mention parsing directly to an object other than a Hash, but it is possible using the poorly-documented object_class option(see https://ruby-doc.org/stdlib-2.7.1/libdoc/json/rdoc/JSON.html):
JSON.parse('{"foo":{"bar": 2}}', object_class: OpenStruct).foo.bar
=> 2
The better way to read that option is "The ruby class that a json object turns into", which explains why it defaults to Hash. Likewise, there is an array_class option for json arrays.
Latecomer to the party here. I'm extremely surprised none of the answers mention the simplest, fastest, most portable solution; the case
statement.
case ${variable#[-+]} in
*[!0-9]* | '') echo Not a number ;;
* ) echo Valid number ;;
esac
The trimming of any sign before the comparison feels like a bit of a hack, but that makes the expression for the case statement so much simpler.
You have updated the android sdk but not updated the adt to match with it.
You can update the adt from here
You might need to update the software source for your adt update
Go to eclipse > help > Check for updates.
It should list the latest update of adt. If it is not working try the same *Go to eclipse > help > Install new software * but now please do the follwing:
Click on add
Add this url : https://dl-ssl.google.com/android/eclipse/
Give it any name.
It will list the updates available- which should ideally be adt 20.xx
Eclipse will restart and hopefully everything should work fine for you.
Actually, you can save you picture at any place. If you want to save in a public space, so any other application can access, use this code:
storageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
),
getAlbumName()
);
The picture doesn't go to the album. To do this, you need to call a scan:
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
You can found more info at https://developer.android.com/training/camera/photobasics.html#TaskGallery
Another potential cause for this (Intellij was involved in my case, not sure that mattered though): trying to merge in changes from a main branch into a branch off of a feature branch.
In other words, merging "main" into "current" in the following arrangement:
main
|
--feature
|
--current
I resolved all conflicts and GiT reported unmerged files and I was stuck until I merged from main into feature, then feature into current.
assume series s
s = pd.Series(np.arange(100))
Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]
s.quantile(np.linspace(.1, 1, 9, 0))
0.1 9.9
0.2 19.8
0.3 29.7
0.4 39.6
0.5 49.5
0.6 59.4
0.7 69.3
0.8 79.2
0.9 89.1
dtype: float64
OR
s.quantile(np.linspace(.1, 1, 9, 0), 'lower')
0.1 9
0.2 19
0.3 29
0.4 39
0.5 49
0.6 59
0.7 69
0.8 79
0.9 89
dtype: int32
The SyntheticEvent interface is generic:
interface SyntheticEvent<T> {
...
currentTarget: EventTarget & T;
...
}
(Technically the currentTarget
property is on the parent BaseSyntheticEvent type.)
And the currentTarget
is an intersection of the generic constraint and EventTarget
.
Also, since your events are caused by an input element you should use the ChangeEvent
(in definition file, the react docs).
Should be:
update = (e: React.ChangeEvent<HTMLInputElement>): void => {
this.props.login[e.currentTarget.name] = e.currentTarget.value
}
(Note: This answer originally suggested using React.FormEvent
. The discussion in the comments is related to this suggestion, but React.ChangeEvent
should be used as shown above.)
There may be a little problem with code from Vishnu's answer. If there is no digits in the string it will return ValueError. Here is my suggestion avoid this:
>>> digit = lambda x: int(filter(str.isdigit, x) or 0)
>>> digit('3158 reviews')
3158
>>> digit('reviews')
0
Put the things like /src/main/resources/foo/bar.properties
and then reference them as classpath:/foo/bar.properties
.
Per Phairoh: Use this in the Page/Component just in case the panel name changes
<script type="text/javascript">
<!--
//must be global to be called by ExternalInterface
function JSFunction() {
__doPostBack('<%= myUpdatePanel.ClientID %>', '');
}
-->
</script>
To add to this - it seems important to define the width & height of the drawable as per this post:
(his code works)
If the answers must be constrained to Google Sheets, this answer works but it has limitations and is clumsy enough UX that it may be hard to get others to adopt. In trying to solve this problem I've found that, for many applications, Airtable solves this by allowing for multi-select columns and the UX is worlds better.
Instead of document or $(document) to avoid JQuery, you can add a TimeOut to validate the objects. TimeOut is executed after loading all objects within the page and other events...
setTimeout(function () {
var str = document.getElementById("cal_preview").value;
var str1 = document.getElementById("year").value;
....
....
....
}, 0);
I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. @Domnic answer didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.
An extended answer for remote IP db connections:
Step 1: Link servers
EXEC sp_addlinkedserver @server='SRV_NAME',
@srvproduct=N'',
@provider=N'SQLNCLI',
@datasrc=N'aaa.bbb.ccc.ddd';
EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'
...where SRV_NAME
is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd
is the ip address of the remote server hosting your SQLserver DB.
Step 2: Run your queries For instance:
SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table
...and that's it!
Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin
If your keys are dynamic I would suggest deserializing directly into a DataTable:
class SampleData
{
[JsonProperty(PropertyName = "items")]
public System.Data.DataTable Items { get; set; }
}
public void DerializeTable()
{
const string json = @"{items:["
+ @"{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
+ @"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
+ @"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]}";
var sampleData = JsonConvert.DeserializeObject<SampleData>(json);
var table = sampleData.Items;
// write tab delimited table without knowing column names
var line = string.Empty;
foreach (DataColumn column in table.Columns)
line += column.ColumnName + "\t";
Console.WriteLine(line);
foreach (DataRow row in table.Rows)
{
line = string.Empty;
foreach (DataColumn column in table.Columns)
line += row[column] + "\t";
Console.WriteLine(line);
}
// Name Age Job
// AAA 22 PPP
// BBB 25 QQQ
// CCC 38 RRR
}
You can determine the DataTable column names and types dynamically once deserialized.
often this is due to missing permissions. The windows account the local IIS Application Pool is running with may not have the permission to write to the applications directory. You could create a directory somewhere, give everyone permission to write in it and point your log4net config to that directory. If then a log file is created there, you can modify the permissions for your desired log directory so that the app pool can write to it.
Another reason could be an uninitialized log4net. In a winforms app, you usually configure log4net upon application start. In a web app, you can do this either dynamically (in your logging component, check if you can create a specific Ilog logger using its name, if not -> call configure()) or again upon application start in global.asax.cs.
There's a pretty good explanation of first level caching on the Streamline Logic blog.
Basically, first level caching happens on a per session basis where as second level caching can be shared across multiple sessions.
Of course AJAX is the solution,
To perform an AJAX request (for easiness we can use jQuery library).
Step1.
Include jQuery library in your web page
a. you can download jQuery library from jquery.com and keep it locally.
b. or simply paste the following code,
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Step 2.
Call a javascript function on button click
<button type="button" onclick="foo()">Click Me</button>
Step 3.
and finally the function
function foo () {
$.ajax({
url:"test.php", //the page containing php script
type: "POST", //request type
success:function(result){
alert(result);
}
});
}
it will make an AJAX request to test.php when ever you clicks the button and alert the response.
For example your code in test.php is,
<?php echo 'hello'; ?>
then it will alert "hello" when ever you clicks the button.
I had a problem similar to this and I will report how I solved mine because it could be that someone is also experiencing the same.
In my case, the error was caused because the server was not finding some static files from the homepage.
So make sure the error only occurs in the index
or occurs on another page. If the problem is only occurring in the index very probably you need to check the static files. I recommend opening the Chrome preview console and checking for any errors.
In my case, the server couldn't find favicon.ico
and two other CSS.
To fix this I passed python manage.py collectstatic
and it worked.
As already mentioned this can't be done with floats, they can't inherit heights, they're unaware of their siblings so for example the side two floats don't know the height of the centre content, so they can't inherit from anything.
Usually inherited height has to come from either an element which has an explicit height or if height: 100%;
has been passed down through the display tree to it.. The only thing I'm aware of that passes on height which hasn't come from top of the "tree" is an absolutely positioned element - so you could for example absolutely position all the top right bottom left sides and corners (you know the height and width of the corners anyway) And as you seem to know the widths (of left/right borders) and heights of top/bottom) borders, and the widths of the top/bottom centers, are easy at 100% - the only thing that needs calculating is the height of the right/left sides if the content grows -
This you can do, even without using all four positioning co-ordinates which IE6 /7 doesn't support
I've put up an example based on what you gave, it does rely on a fixed width (your frame), but I think it could work with a flexible width too? the uses of this could be cool for those fancy image borders we can't get support for until multiple background images or image borders become fully available.. who knows, I was playing, so just sticking it out there!
proof of concept example is here
You have two syntax options:
Option 1
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
CREATE TABLE Table2 (
id int identity(1, 1) not null,
LongIntColumn2 int,
CurrencyColumn2 money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
INSERT INTO Table2
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1
Option 2
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1
INTO Table2
FROM Table1
GROUP BY LongIntColumn1
Bear in mind that Option 2 will create a table with only the columns on the projection (those on the SELECT).
Vue.js props are not to be mutated as this is considered an Anti-Pattern in Vue.
The approach you will need to take is creating a data property on your component that references the original prop property of list
props: ['list'],
data: () {
return {
parsedList: JSON.parse(this.list)
}
}
Now your list structure that is passed to the component is referenced and mutated via the data
property of your component :-)
If you wish to do more than just parse your list property then make use of the Vue component' computed
property.
This allow you to make more in depth mutations to your props.
props: ['list'],
computed: {
filteredJSONList: () => {
let parsedList = JSON.parse(this.list)
let filteredList = parsedList.filter(listItem => listItem.active)
console.log(filteredList)
return filteredList
}
}
The example above parses your list prop and filters it down to only active list-tems, logs it out for schnitts and giggles and returns it.
note: both data
& computed
properties are referenced in the template the same e.g
<pre>{{parsedList}}</pre>
<pre>{{filteredJSONList}}</pre>
It can be easy to think that a computed
property (being a method) needs to be called... it doesn't
A good workaround to remind you that m2e could be better configured, without the project inheriting a false positive error marker, is to just downgrade those errors to warnings:
Window -> Preferences -> Maven -> Errors/Warnings -> Plugin execution not covered by lifecycle configuration = Warning
As you can see here:
html5 oninvalid doesn't work after fixed the input field
Is good to you put in that way, for when you fix the error disapear the warning message.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')" />
One more solution:
no toolbar but a segmented control (eyecandy)
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:nil
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
[actionSheet addSubview:pickerView];
[pickerView release];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];
[closeButton release];
[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
To export db rather it is SQLITE or ROOM:
Firstly, add this permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Secondly, we drive to code the db functions:
private void exportDB() {
try {
File dbFile = new File(this.getDatabasePath(DATABASE_NAME).getAbsolutePath());
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = DirectoryName + File.separator +
DATABASE_NAME + ".db";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
} catch (IOException e) {
Log.e("dbBackup:", e.getMessage());
}
}
Create Folder on Daily basis with name of folder is Current date:
public void createBackup() {
sharedPref = getSharedPreferences("dbBackUp", MODE_PRIVATE);
editor = sharedPref.edit();
String dt = sharedPref.getString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));
if (dt != new SimpleDateFormat("dd-MM-yy").format(new Date())) {
editor.putString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));
editor.commit();
}
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "BackupDBs");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
DirectoryName = folder.getPath() + File.separator + sharedPref.getString("dt", "");
folder = new File(DirectoryName);
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
exportDB();
}
} else {
Toast.makeText(this, "Not create folder", Toast.LENGTH_SHORT).show();
}
}
Assign the DATABASE_NAME without .db extension and its data type is string
The add
method that takes a String
and a Person
is calling a different add
method that takes a Position
. The one that takes Position
is inherited from the ArrayList
class.
Since your class Staff
extends ArrayList<Position>
, it automatically has the add(Position)
method. The new add(String, Person)
method is one that was written particularly for the Staff class.
Arrays are designed with so-called axis=0 and rows positioned vertically versus axis=1 and columns positioned horizontally. Axis refers to the dimension of the array.
I have enumerated possibly all cases where this error may occur in code and its comments below. Please add to it, if you come across more cases.
#include<stdio.h>
#include<malloc.h>
typedef struct AStruct TypedefedStruct;
struct AStruct
{
int member;
};
void main()
{
/* Case 1
============================================================================
Use (->) operator to access structure member with structure pointer, instead
of dot (.) operator.
*/
struct AStruct *aStructObjPtr = (struct AStruct *)malloc(sizeof(struct AStruct));
//aStructObjPtr.member = 1; //Error: request for member ‘member’ in something not
//a structure or union.
//It should be as below.
aStructObjPtr->member = 1;
printf("%d",aStructObjPtr->member); //1
/* Case 2
============================================================================
We can use dot (.) operator with struct variable to access its members, but
not with with struct pointer. But we have to ensure we dont forget to wrap
pointer variable inside brackets.
*/
//*aStructObjPtr.member = 2; //Error, should be as below.
(*aStructObjPtr).member = 2;
printf("%d",(*aStructObjPtr).member); //2
/* Case 3
=============================================================================
Use (->) operator to access structure member with typedefed structure pointer,
instead of dot (.) operator.
*/
TypedefedStruct *typedefStructObjPtr = (TypedefedStruct *)malloc(sizeof(TypedefedStruct));
//typedefStructObjPtr.member=3; //Error, should be as below.
typedefStructObjPtr->member=3;
printf("%d",typedefStructObjPtr->member); //3
/* Case 4
============================================================================
We can use dot (.) operator with struct variable to access its members, but
not with with struct pointer. But we have to ensure we dont forget to wrap
pointer variable inside brackets.
*/
//*typedefStructObjPtr.member = 4; //Error, should be as below.
(*typedefStructObjPtr).member=4;
printf("%d",(*typedefStructObjPtr).member); //4
/* Case 5
============================================================================
We have to be extra carefull when dealing with pointer to pointers to
ensure that we follow all above rules.
We need to be double carefull while putting brackets around pointers.
*/
//5.1. Access via struct_ptrptr and ->
struct AStruct **aStructObjPtrPtr = &aStructObjPtr;
//*aStructObjPtrPtr->member = 5; //Error, should be as below.
(*aStructObjPtrPtr)->member = 5;
printf("%d",(*aStructObjPtrPtr)->member); //5
//5.2. Access via struct_ptrptr and .
//**aStructObjPtrPtr.member = 6; //Error, should be as below.
(**aStructObjPtrPtr).member = 6;
printf("%d",(**aStructObjPtrPtr).member); //6
//5.3. Access via typedefed_strct_ptrptr and ->
TypedefedStruct **typedefStructObjPtrPtr = &typedefStructObjPtr;
//*typedefStructObjPtrPtr->member = 7; //Error, should be as below.
(*typedefStructObjPtrPtr)->member = 7;
printf("%d",(*typedefStructObjPtrPtr)->member); //7
//5.4. Access via typedefed_strct_ptrptr and .
//**typedefStructObjPtrPtr->member = 8; //Error, should be as below.
(**typedefStructObjPtrPtr).member = 8;
printf("%d",(**typedefStructObjPtrPtr).member); //8
//5.5. All cases 5.1 to 5.4 will fail if you include incorrect number of *
// Below are examples of such usage of incorrect number *, correspnding
// to int values assigned to them
//(aStructObjPtrPtr)->member = 5; //Error
//(*aStructObjPtrPtr).member = 6; //Error
//(typedefStructObjPtrPtr)->member = 7; //Error
//(*typedefStructObjPtrPtr).member = 8; //Error
}
The underlying ideas are straight:
.
with structure variable. (Cases 2 and 4)->
with pointer to structure. (Cases 1 and 3)(*ptr).
and (*ptr)->
vs *ptr.
and *ptr->
(All cases except case 1)for my example:
Windows XP ---> Synology:DS218+
Step2:
Enable Telnet service (?? Telnet ??)
or Enable SSH Service (?? SSH ??)
Step3: Launch the terminal on Windows (or via executing cmd
to launch the terminal)
Step4: type: telnet your_nas_ip_or_domain_name, like below telnet 192.168.1.104
Fzz login: tsungjung411 Password: # shows the current working directory (?????????) $ pwd /var/services/homes/tsungjung411 # edit a Java file (via vi), then compile and run it # (?? vi ?? Java ??,???????) $ vi Main.java # show the file content (??????) $ cat Main.java public class Main { public static void main(String [] args) { System.out.println("hello, World!"); } } # compiles the Java file (?? Java ??) javac Main.java # executes the Java file (?? Java ??) $ java Main hello, World! # shows the file list (??????) $ ls CloudStation Main.class Main.java www
# shows the JRE version on this Synology Disk Station $ java -version openjdk version "1.8.0_151" OpenJDK Runtime Environment (IcedTea 3.6.0) (linux-gnu build 1.8.0_151-b12) OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)
$ python Python 2.7.12 (default, Nov 10 2017, 20:30:30) [GCC 4.9.3 20150311 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import sys >>> >>> # shows the the python version >>> print(sys.version) 2.7.12 (default, Nov 10 2017, 20:30:30) [GCC 4.9.3 20150311 (prerelease)] >>> >>> import os >>> >>> # shows the current working directory >>> print(os.getcwd()) /volume1/homes/tsungjung411
$ # launch Python 3 $ python3 Python 3.5.1 (default, Dec 9 2016, 00:20:03) [GCC 4.9.3 20150311 (prerelease)] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
I am using namespaces and rooms - I found
socket.broadcast.to('room1').emit('event', 'hi');
to work where
namespace.broadcast.to('room1').emit('event', 'hi');
did not
(should anyone else face that problem)