also, with wmode=opaque
and with IE, the Flash gets the keyboard events, but also the html page receives them, so it can't be use for something like embedding a flash game. Very annoying
Just a tip!--make sure you up the z-index on the element you want to be over the embedded video. I added the wmode querystring, and it still didn't work...until I upped the z-index of the other element. :)
If you want to reindent the block you're in without having to type any chords, you can do:
[[=]]
Take a look at JManage. It's able to execute MBean methods and get / set attributes from command line.
Simplest way is to use dimensions in % or em. Just change the base font size everything will change.
Less
@media (max-width: @screen-xs) {
body{font-size: 10px;}
}
@media (max-width: @screen-sm) {
body{font-size: 14px;}
}
h5{
font-size: 1.4rem;
}
Look at all the ways at https://stackoverflow.com/a/21981859/406659
You could use viewport units (vh,vw...) but they dont work on Android < 4.4
Without use ID (<tbody id="tbodyid">
) , it is a great way to cope with this issue
$('#table1').find("tr:gt(0)").remove();
PS:To remove specific row number as following example
$('#table1 tr').eq(1).remove();
or
$('#tr:nth-child(2)').remove();
With the latest NuGet 2.5 release there is now an "Update All" button in the packages manager: http://docs.nuget.org/docs/release-notes/nuget-2.5#Update_All_button_to_allow_updating_all_packages_at_once
Since Mockito 2.0 there's also possibility to use static method Matchers.argThat(ArgumentMatcher). With the help of Java 8 it is now much cleaner and more readable to write:
verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("OneSurname")));
verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("AnotherSurname")));
If you're tied to lower Java version there's also not-that-bad:
verify(mockBar).doSth(argThat(new ArgumentMatcher<Employee>() {
@Override
public boolean matches(Object emp) {
return ((Employee) emp).getSurname().equals("SomeSurname");
}
}));
Of course none of those can verify order of calls - for which you should use InOrder :
InOrder inOrder = inOrder(mockBar);
inOrder.verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("FirstSurname")));
inOrder.verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("SecondSurname")));
Please take a look at mockito-java8 project which makes possible to make calls such as:
verify(mockBar).doSth(assertArg(arg -> assertThat(arg.getSurname()).isEqualTo("Surname")));
Get the value of your textboxes using val()
and store them in a variable. Pass those values through $.post
. In using the $.Post Submit button
you can actually remove the form.
<script>
username = $("#username").val();
password = $("#password").val();
$("#post-btn").click(function(){
$.post("process.php", { username:username, password:password } ,function(data){
alert(data);
});
});
</script>
For those of you who came here looking for how to remove an object from a JSON array based on object value:
let users = [{"name": "Ben"},{"name": "Tim"},{"name": "Harry"}];
for (let [i, user] of users.entries()) {
if (user.name == "Tim") {
users.splice(i, 1);
}
}
_x000D_
User Tim is now removed from JSON array users.
from the FAQ
elem = $("#elemid");
if (elem.is (".class")) {
// whatever
}
or:
elem = $("#elemid");
if (elem.hasClass ("class")) {
// whatever
}
As others have said, BeautifulSoup doesn't have xpath support. There are probably a number of ways to get something from an xpath, including using Selenium. However, here's a solution that works in either Python 2 or 3:
from lxml import html
import requests
page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.content)
#This will create a list of buyers:
buyers = tree.xpath('//div[@title="buyer-name"]/text()')
#This will create a list of prices
prices = tree.xpath('//span[@class="item-price"]/text()')
print('Buyers: ', buyers)
print('Prices: ', prices)
I used this as a reference.
List all images
docker search <registry_host>:<registry_port>/
List images like 'vcs'
docker search <registry_host>:<registry_port>/vcs
Yes, that is supported.
Check the documentation provided here for the supported keywords inside method names.
You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:
List<Inventory> findByIdIn(List<Long> ids);
I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:
The Entity
@Entity
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
// other fields
// getters/setters
}
The Repository
@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {
List<Inventory> findByIdIn(List<Long> ids);
}
You can always code your own button with custom graphics and a PictureBox, though it won't necessarily match the Windows theme of your users.
In SQLite the best you can do is use the integers 0 and 1 to represent false and true. You could declare the column type like this:
CREATE TABLE foo(mycolumn BOOLEAN NOT NULL CHECK (mycolumn IN (0,1)));
Omit the NOT NULL
if you want to allow NULL
in addition to 0 and 1.
The use of the type name BOOLEAN
here is for readability, to SQLite it's just a type with NUMERIC affinity.
Note that CHECK constraints have been supported since SQLite 3.3.0 (2006).
Here are some example INSERTs that will work: (note how strings and floating point numbers are parsed as integers)
sqlite> INSERT INTO foo VALUES(0);
sqlite> INSERT INTO foo VALUES(1);
sqlite> INSERT INTO foo VALUES(0.0);
sqlite> INSERT INTO foo VALUES(1.0);
sqlite> INSERT INTO foo VALUES("0.0");
sqlite> INSERT INTO foo VALUES("1.0");
sqlite> select mycolumn, typeof(mycolumn) from foo;
0|integer
1|integer
0|integer
1|integer
0|integer
1|integer
and some that will fail:
sqlite> INSERT INTO foo VALUES("-1");
Error: constraint failed
sqlite> INSERT INTO foo VALUES(0.24);
Error: constraint failed
sqlite> INSERT INTO foo VALUES(100);
Error: constraint failed
sqlite> INSERT INTO foo VALUES(NULL);
Error: foo.mycolumn may not be NULL
sqlite> INSERT INTO foo VALUES("true");
Error: constraint failed
sqlite> INSERT INTO foo VALUES("false");
Error: constraint failed
This is how did it works like a charm.
#loader {
position:fixed;
left:1px;
top:1px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('../images/ajax-loader100X100.gif') 50% 50% no-repeat rgb(249,249,249);
}
in _layout file inside body tag but outside the container div. Every time page loads it shows loading. Once page is loaded JS fadeout(second)
<div id="loader">
</div>
JS at the bottom of _layout file
<script type="text/javascript">
// With the element initially shown, we can hide it slowly:
$("#loader").fadeOut(1000);
</script>
For some non-activity classes, like Worker, you're already given a Context object in the public constructor.
Worker(Context context, WorkerParameters workerParams)
You can just use that, e.g., save it to a private Context variable in the class (say, mContext
), and then, for example
mContext.getSystenService(Context.ACTIVITY_SERVICE)
Heres a good one with NSRegularExpression that's working for me.
[text rangeOfString:@"^.+@.+\\..{2,}$" options:NSRegularExpressionSearch].location != NSNotFound;
You can insert whatever regex you want but I like being able to do it in one line.
You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,
+----------+
| _c0|
+----------+
|1872-11-30|
|1873-03-08|
|1874-03-07|
|1875-03-06|
|1876-03-04|
|1876-03-25|
|1877-03-03|
|1877-03-05|
|1878-03-02|
|1878-03-23|
|1879-01-18|
I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.
df.createOrReplaceTempView("res")
sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")
Here I'm creating a temporary view and store the year values using this single line and the output will be,
+-----------------------+
|year(CAST(_c0 AS DATE))|
+-----------------------+
| 1872|
| 1873|
| 1874|
| 1875|
| 1876|
| 1876|
| 1877|
| 1877|
| 1878|
| 1878|
| 1879|
| 1879|
| 1879|
public class MainActivity extends Activity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.submitButton);
button.setOnClickListener(new MyClass());
}
public class MyClass implements View.OnClickListener {
@Override
public void onClick(View v) {
}
}
}
For those wondering why this happens on some systems and not on others (with the same source, build parameters, and so on), check your LANG
environment variable. I get the warning/error when LANG=C.UTF-8
, but not when LANG=en_US.UTF-8
.
It is possible to change only arrow's color (not back button title's color) on this way:
[[self.navigationController.navigationBar.subviews lastObject] setTintColor:[UIColor blackColor]];
Navigation bar contains subview of _UINavigationBarBackIndicatorView type (last item in subviews array) which represents arrow.
Result is navigation bar with different colors of back button arrow and back button title
None of the above answers worked "out of the box" for me, however, the following function, obtained by copying the ideas of the other answers works:
apply_func_2_cols = @(f,M) cell2mat(cellfun(f,num2cell(M,1), 'UniformOutput',0));
It takes a function f
and applies it to every column of the matrix M
.
So for example:
f = @(v) [0 1;1 0]*v + [0 0.1]';
apply_func_2_cols(f,[0 0 1 1;0 1 0 1])
ans =
0.00000 1.00000 0.00000 1.00000
0.10000 0.10000 1.10000 1.10000
I found the best answer :P :
String.ToString.Count - String.ToString.Replace("e", "").Count
String.ToString.Count - String.ToString.Replace("t", "").Count
Try using this simple and fasted solution. Android provides some default animation
s.
fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
fragmentManager.addOnBackStackChangedListener(this);
fragmentTransaction.replace(R.id.frame, firstFragment, "h");
fragmentTransaction.addToBackStack("h");
fragmentTransaction.commit();
Output:
Create a Requestfactory class
import java.net.URI;
import javax.annotation.PostConstruct;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class RequestFactory {
private RestTemplate restTemplate = new RestTemplate();
@PostConstruct
public void init() {
this.restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestWithBodyFactory());
}
private static final class HttpComponentsClientHttpRequestWithBodyFactory extends HttpComponentsClientHttpRequestFactory {
@Override
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
if (httpMethod == HttpMethod.GET) {
return new HttpGetRequestWithEntity(uri);
}
return super.createHttpUriRequest(httpMethod, uri);
}
}
private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetRequestWithEntity(final URI uri) {
super.setURI(uri);
}
@Override
public String getMethod() {
return HttpMethod.GET.name();
}
}
public RestTemplate getRestTemplate() {
return restTemplate;
}
}
and @Autowired where ever you require and use, Here is one sample code GET request with RequestBody
@RestController
@RequestMapping("/v1/API")
public class APIServiceController {
@Autowired
private RequestFactory requestFactory;
@RequestMapping(method = RequestMethod.GET, path = "/getData")
public ResponseEntity<APIResponse> getLicenses(@RequestBody APIRequest2 APIRequest){
APIResponse response = new APIResponse();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Gson gson = new Gson();
try {
StringBuilder createPartUrl = new StringBuilder(PART_URL).append(PART_URL2);
HttpEntity<String> entity = new HttpEntity<String>(gson.toJson(APIRequest),headers);
ResponseEntity<APIResponse> storeViewResponse = requestFactory.getRestTemplate().exchange(createPartUrl.toString(), HttpMethod.GET, entity, APIResponse.class); //.getForObject(createLicenseUrl.toString(), APIResponse.class, entity);
if(storeViewResponse.hasBody()) {
response = storeViewResponse.getBody();
}
return new ResponseEntity<APIResponse>(response, HttpStatus.OK);
}catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<APIResponse>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
Here's my improvement: added parseInt. for some weird reason it didn't work without it.
// usage: jQuery('#my_div1').hasVerticalScrollBar();
// Credit: http://stackoverflow.com/questions/4814398/how-can-i-check-if-a-scrollbar-is-visible
(function($) {
$.fn.hasVerticalScrollBar = function() {
return this.get(0) ? parseInt( this.get(0).scrollHeight ) > parseInt( this.innerHeight() ) : false;
};
})(jQuery);
You can call bash directly within your Makefile instead of using the default shell:
bash -c "ls -al"
instead of:
ls -al
Don't. Leave them as Java and use IKVM to convert them to .Net DLLs.
You can do it calling setRowSelectionInterval :
table.setRowSelectionInterval(0, 0);
to select the first row.
A trick that works is to position box #2 with position: absolute
instead of position: relative
. We usually put a position: relative
on an outer box (here box #2) when we want an inner box (here box #3) with position: absolute
to be positioned relative to the outer box. But remember: for box #3 to be positioned relative to box #2, box #2 just need to be positioned. With this change, we get:
And here is the full code with this change:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
/* Positioning */
#box1 { overflow: hidden }
#box2 { position: absolute }
#box3 { position: absolute; top: 10px }
/* Styling */
#box1 { background: #efe; padding: 5px; width: 125px }
#box2 { background: #fee; padding: 2px; width: 100px; height: 100px }
#box3 { background: #eef; padding: 2px; width: 75px; height: 150px }
</style>
</head>
<body>
<br/><br/><br/>
<div id="box1">
<div id="box2">
<div id="box3"/>
</div>
</div>
</body>
</html>
The here
package provides the here()
function, which returns your project root directory based on some heuristics.
Not the perfect solution, since it doesn't find the location of the script, but it suffices for some purposes so I thought I'd put it here.
You can use the .rows
property and check it's .length
, like this:
var rowCount = document.getElementById('myTableID').rows.length;
One could use an additional hidden input element with the same name and value as that of the disabled list. This will ensure that the value is passed in $_POST variables.
Eg:
<select name="sel" disabled><option>123</select>_x000D_
<input type="hidden" name="sel" value=123>
_x000D_
It might seem like a hack, but I personally prefer copying the cells as text (or exporting as a CSV) into Winmerge or any other diff tool. Assuming the two sheets contain mostly identical data, Winmerge will show the differences immediately.
If someone is using column names like "key"
or "value"
, then you still see the same error that your mysql query syntax is bad. This should fix:
.where("`key` LIKE ?", "%#{key}%")
I got the same error when trying to decrypt the key from a different user account via su - <otherUser>
. (Like jayhendren suggests in his answer)
In my case, this happened because there would normally start a graphical pinentry
prompt so I could enter the password to decrypt the key, but the su -
ed to user had no access to the (graphical) X-Window-System that was currently running.
The solution was to simply issue in that same console (as the user under which the X Server was currently running):
xhost +local:
Which gives other local users access to the currently running (local) X-Server. After that, the pinentry
prompt appeared, I could enter the password to decrypt the key and it worked...
Of course you can also forward X over ssh
connections. For this look into ssh
's -X
parameter (client side) and X11Forwarding yes
(server side).
In symfony 4 (probably 3.3 also, but only real-tested in 4) you can inject the Security
service via auto-wiring in the controller like this:
<?php
use Symfony\Component\Security\Core\Security;
class SomeClass
{
/**
* @var Security
*/
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function privatePage() : Response
{
$user = $this->security->getUser(); // null or UserInterface, if logged in
// ... do whatever you want with $user
}
}
As @ktolis says, you first have to configure your /app/config/security.yml
.
Then with
$user = $this->get('security.token_storage')->getToken()->getUser();
$user->getUsername();
should be enougth!
$user
is your User Object! You don't need to query it again.
Find out the way to set up your providers in security.yml
from Sf2 Documentation and try again.
Best luck!
.hide()
stores the previous display
property just before setting it to none
, so if it wasn't the standard display
property for the element you're a bit safer, .show()
will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.
Add a build task to concatenate and register your html partials in the Angular $templateCache
. (This answer is a more detailed variant of karlgold's answer.)
For grunt, use grunt-angular-templates. For gulp, use gulp-angular-templatecache.
Below are config/code snippets to illustrate.
gruntfile.js Example:
ngtemplates: {
app: {
src: ['app/partials/**.html', 'app/views/**.html'],
dest: 'app/scripts/templates.js'
},
options: {
module: 'myModule'
}
}
gulpfile.js Example:
var templateCache = require('gulp-angular-templatecache');
var paths = ['app/partials/.html', 'app/views/.html'];
gulp.task('createTemplateCache', function () {
return gulp.src(paths)
.pipe(templateCache('templates.js', { module: 'myModule', root:'app/views'}))
.pipe(gulp.dest('app/scripts'));
});
templates.js (this file is autogenerated by the build task)
$templateCache.put('app/views/main.html', "<div class=\"main\">\r"...
index.html
<script src="app/scripts/templates.js"></script>
<div ng-include ng-controller="main as vm" src="'app/views/main.html'"></div>
Be aware that a lot of the really killer features are only in Enterprise Edition. Data compression and backup compression are among two of my top favorites - they give you free performance improvements right off the bat. Data compression lessens the amount of I/O you have to do, so a lot of queries speed up 20-40%. CPU use goes up, but in today's multi-core environments, we often have more CPU power but not more IO. Anyway, those are only in Enterprise.
If you're only going to use Standard Edition, then most of the improvements require changes to your application code and T-SQL code, so it's not quite as easy of a sell.
$(document).ready(function(){ contsize();});
$(window).bind("resize",function(){contsize();});
function contsize()
{
var h = window.innerHeight;
var calculatecontsize = h - 70;/*if header and footer heights= 35 then total 70px*/
$('#content').css({"height":calculatecontsize + "px"} );
}
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
Integrated Security
and User ID
\ Password
authentication are mutually exclusive. To connect to SQL Server as the user running the code, remove User ID
and Password
from your connection string:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
To connect with specific credentials, remove Integrated Security
:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $uid; Password = $pwd;"
I had the same problem except I did not know in advance what were the thousands separators and the decimal separator. I ended up writing a library to do this. If you are interested it here it is : https://github.com/GuillaumeLeclerc/number-parsing
You are probably having a problem with the sort of CSV file that you have.
Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.
For the things that you are suggesting you can just change the levels using the levels
:
levels(iris$Species)[3] <- 'new'
This answer does not use backticks/template literals/template strings (``
), which are not supported by Internet Explorer.
You could keep the HTML block in an invisible container (like a <script>
) within your HTML code, then use its innerHTML
at runtime in JS
For example:
var div = document.createElement('div');
div.setAttribute('class', 'someClass');
div.innerHTML = document.getElementById('blockOfStuff').innerHTML;
document.getElementById('targetElement').appendChild(div);
_x000D_
.red {
color: red
}
_x000D_
<script id="blockOfStuff" type="text/html">
Here's some random text.
<h1>Including HTML markup</h1>
And quotes too, or as one man said, "These are quotes, but
'these' are quotes too."
</script>
<div id="targetElement" class="red"></div>
_x000D_
Idea from this answer: JavaScript HERE-doc or other large-quoting mechanism?
If you want to insert a particularly long block of HTML in PHP you can use the Nowdoc syntax, like so:
<?php
$some_var = " - <b>isn't that awesome!</b>";
echo
<<<EOT
Here's some random text.
<h1>Including HTML markup</h1>
And quotes too, or as one man said, "These are quotes, but 'these' are quotes too."
<br><br>
The beauty of Nowdoc in PHP is that you can use variables too $some_var
<br><br>
Or even a value contained within an array - be it an array from a variable you've set
yourself, or one of PHP's built-in arrays. E.g. a user's IP: {$_SERVER['REMOTE_ADDR']}
EOT;
?>
Here's a PHP Fiddle demo of the above code that you can run in your browser.
One important thing to note: The <<<EOT
and EOT;
MUST be on their own line, without any preceding whitespace.
One huge advantage of using Nowdoc syntax over the usual starting and stopping your PHP tag is its support for variables. Consider the usual way of doing it (shown in the example below), contrasted to the simplicity of Nowdoc (shown in the example above).
<?php
// Load of PHP code here
?>
Now here's some HTML...<br><br>
Let's pretend that this HTML block is actually a couple of hundred lines long, and we
need to insert loads of variables<br><br>
Hi <?php echo $first_name; ?>!<br><br>
I can see it's your birthday on <?php echo $birthday; ?>, what are you hoping to get?
<?php
// Another big block of PHP here
?>
And some more HTML!
</body>
</html>
Another way of reducing your iteration to a single-level loop would be via the use of generators as also specified in the python reference
for i, j in ((i, j) for i in A for j in B):
print(i , j)
if (some_condition):
break
You could scale it up to any number of levels for the loop
The downside is that you can no longer break only a single level. It's all or nothing.
Another downside is that it doesn't work with a while loop. I originally wanted to post this answer on Python - `break` out of all loops but unfortunately that's closed as a duplicate of this one
it can also be in your capistrano config (Capfile
):
set :rbenv_ruby, "2.7.1"
In a very general way and to support SQL server here is
SELECT TOP(N) *
FROM tbl_name
ORDER BY tbl_id DESC
and for the performance, it is not bad (less than one second for more than 10,000 records On Server machine)
Not in core, no. A search for "java array join string glue" will give you some code snippets on how to achieve this though.
e.g.
public static String join(Collection s, String delimiter) {
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
This looks like Dijstra's algorithm. In any case, the time taken to run will depend on N. If it takes more than 3 seconds there isn't any way I can see of speeding it up, as all the calculations that it is doing need to be done.
Depending on what problem you're trying to solve, there might be a faster algorithm.
Here is my case. I had a remote machine that hosted SQL Server. From my local machine, I was trying to access the SQL instance via some C# code and I was getting this error. My password for the user account on my machine/domain had expired. I fixed it with the following:
windows
+ L
key so I didn't have to completely sign off) so that I could get back to the sign-on pageEverything then worked fine.
And if you have lot insert queries but not wanna ger a ERROR message everytime , you can do it:
CREATE UNIQUE NONCLUSTERED INDEX SK01 ON dbo.Person(ID,Name,Active,PersonNumber)
WITH(IGNORE_DUP_KEY = ON)
//animated show/hide
function showHide(id) {
var hidden= ("none" == $( "#".concat(id) ).css("display"));
if(hidden){
$( "#".concat(id) ).show(1000);
}else{
$("#".concat(id) ).hide(1000);
}
}
Without device (or rather browser) specific JS I'm pretty sure you're out of luck.
Edit: thought you wanted to avoid that until i reread your question. In case of Mobile Safari you can register to get all touch events similar to what you can do with native UIView-s. Can't find the documentation right now, will try to though.
777
is a permission in Unix based system with full read/write/execute permission to owner, group and everyone.. in general we give this permission to assets which are not much needed to be hidden from public on a web server, for example images..
You said I am using windows 7.
if that means that your web server is Windows based then you should login to that and right click the folder and set permissions to everyone
and if you are on a windows client and server is unix/linux based then use some ftp software and in the parent directory right click and change the permission for the folder.
If you want permission to be set on sub-directories
too then usually their is option to set permission recursively use that.
And, if you feel like doing it from command line the use putty and login to server and go to the parent directory includes
and write the following command
chmod 0777 module_installation/
for recursive
chmod -R 0777 module_installation/
Hope this will help you
If you don't want to change to numeric you can try this.
> as.vector(t(df)[,1])
[1] 1.0 2.0 2.6
The most simple way I found to deal with simple JSON object that I pass into MVC 6 is getting the the type of the post parameter like NewtonSoft jObject:
public ActionResult Test2([FromBody] jObject str)
{
return Json(new { message = "Test1 Returned: "+ str }); ;
}
From now on is better to use the .prop() function instead of the .attr() one.
Here the jQuery documentation:
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.
var div1Class = $('#div1').prop('class');
you can type the following step:
mysql> exit;
C:\xampp\mysql\bin> cls
C:\xampp\mysql\bin> mysql -u root -h localhost
it's work!
Step: set a button in XML with onClick Action:
<Button
android:id="@+id/btnEditUserInfo"
style="?android:borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="@dimen/txt_height"
android:layout_gravity="center"
android:background="@drawable/round_btn"
android:contentDescription="@string/image_view"
android:onClick="edit_user_info"
android:text="Edit"
android:textColor="#000"
android:textSize="@dimen/login_textSize" />
Step: on button clicked show animation point
//pgrm mark ---- ---- ----- ---- ---- ----- ---- ---- ----- ---- ---- -----
public void edit_user_info(View view) {
// show click effect on button pressed
final AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
view.startAnimation(buttonClick);
Intent intent = new Intent(getApplicationContext(), EditUserInfo.class);
startActivity(intent);
}// end edit_user_info
For anyone reading this post in the future, you don't need to cd to the directory where the jar is present. Here is what you need to do -
Go to your project folder from where you can run maven commands (When you do an ls -ltr in this folder, you should see pom.xml)
Do this -
mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=<Path where the jar is, example downloads>/ojdbc6.jar -DgeneratePom=true
Once this is done, you can add the dependency in your pom.xml, something like this -
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
All good answers...From the validation perspective, I also noticed that MaxLength gets validated at the server side only, while StringLength gets validated at client side too.
[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.
Roughly (untested):
app.get('/users/:email/messages/unread', function(req, res, next) {
var firstItem=true, query=MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
query.each(function(docs) {
// Start the JSON array or separate the next element.
res.write(firstItem ? (firstItem=false,'[') : ',');
res.write(JSON.stringify({ msgId: msg.fileName }));
});
res.end(']'); // End the JSON array and response.
});
Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:
// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));
The python wiki is a great page for profiling resources: http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Profiling_Code
as is the python docs: http://docs.python.org/library/profile.html
as shown by Chris Lawlor cProfile is a great tool and can easily be used to print to the screen:
python -m cProfile -s time mine.py <args>
or to file:
python -m cProfile -o output.file mine.py <args>
PS> If you are using Ubuntu, make sure to install python-profile
apt-get install python-profiler
If you output to file you can get nice visualizations using the following tools
PyCallGraph : a tool to create call graph images
install:
pip install pycallgraph
run:
pycallgraph mine.py args
view:
gimp pycallgraph.png
You can use whatever you like to view the png file, I used gimp
Unfortunately I often get
dot: graph is too large for cairo-renderer bitmaps. Scaling by 0.257079 to fit
which makes my images unusably small. So I generally create svg files:
pycallgraph -f svg -o pycallgraph.svg mine.py <args>
PS> make sure to install graphviz (which provides the dot program):
pip install graphviz
Alternative Graphing using gprof2dot via @maxy / @quodlibetor :
pip install gprof2dot
python -m cProfile -o profile.pstats mine.py
gprof2dot -f pstats profile.pstats | dot -Tsvg -o mine.svg
All you need is:
[OutputCache(Duration=0)]
public JsonResult MyAction(
or, if you want to disable it for an entire Controller:
[OutputCache(Duration=0)]
public class MyController
Despite the debate in comments here, this is enough to disable browser caching - this causes ASP.Net to emit response headers that tell the browser the document expires immediately:
you can't increase the heap size dynamically.
you can request to use more by using android:largeHeap="true"
in the manifest.
also, you can use native memory (NDK & JNI)
, so you actually bypass the heap size limitation.
here are some posts i've made about it:
and here's a library i've made for it:
No, you have no way to get the "name" from the value in C++ because all the symbols are discarded during compilation.
You may need this way X Macros
I am providing the modern answer. The Timestamp
class was always poorly designed, a real hack on top of the already poorly designed Date
class. Both those classes are now long outdated. Don’t use them.
When the question was asked, you would need a Timestamp
for sending a point in time to the SQL database. Since JDBC 4.2 that is no longer the case. Assuming your database needs a timestamp with time zone
(recommended for true timestamps), pass it an OffsetDateTime
.
Before we can do that we need to overcome a real trouble with your sample string, Mon May 27 11:46:15 IST 2013
: the time zone abbreviation. IST
may mean Irish Summer Time, Israel Standard Time or India Standard Time (I have even read that Java may parse it into Atlantic/Reykjavik time zone — Icelandic Standard Time?) To control the interpretation we pass our preferred time zone to the formatter that we are using for parsing.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("EEE MMM dd HH:mm:ss ")
.appendZoneText(TextStyle.SHORT, Set.of(ZoneId.of("Asia/Kolkata")))
.appendPattern(" yyyy")
.toFormatter(Locale.ROOT);
String dateString = "Mon May 27 11:46:15 IST 2013";
OffsetDateTime dateTime = formatter.parse(dateString, Instant::from)
.atOffset(ZoneOffset.UTC);
System.out.println(dateTime);
This snippet prints:
2013-05-27T06:16:15Z
This is the UTC equivalent of your string (assuming IST was for India Standard Time). Pass the OffsetDateTime
to your database using one of the PreparedStatement.setObject
methods (not setTimestamp
).
How can I convert this into timestamp and calculate in seconds the difference between the same and current time?
Calculating the difference in seconds goes very naturally with java.time:
long differenceInSeconds = ChronoUnit.SECONDS
.between(dateTime, OffsetDateTime.now(ZoneOffset.UTC));
System.out.println(differenceInSeconds);
When running just now I got:
202213260
Link: Oracle tutorial: Date Time explaining how to use java.time.
I did this:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AutoDealer</title>
<style>
.container{
width: 860px;
height: 1074px;
margin-right: auto;
margin-left: auto;
border: 1px solid red;
}
.nav{
}
.wrapper{
display: block;
overflow: hidden;
border: 1px solid green;
}
.otherWrapper{
display: block;
overflow: hidden;
border: 1px solid green;
float:left;
}
.left{
width: 399px;
float: left;
background-color: pink;
}
.bottom{
clear: both;
width: 399px;
background-color: yellow;
}
.right{
height:350px;
width: 449px;
overflow: hidden;
background-color: blue;
overflow: hidden;
float:right;
}
</style>
</head>
<body>
<div class="container">
<div class="nav"></div>
<div class="wrapper">
<div class="otherWrapper">
<div class="left">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies aliquet tellus sit amet ultrices. Sed faucibus, nunc vitae accumsan laoreet, enim metus varius nulla, ac ultricies felis ante venenatis justo. In hac habitasse platea dictumst. In cursus enim nec urna molestie, id mattis elit mollis. In sed eros eget nibh congue vehicula. Nunc vestibulum enim risus, sit amet suscipit dui auctor et. Morbi orci magna, accumsan at turpis a, scelerisque congue eros. Morbi non mi vel nibh varius blandit sed et urna.</p>
</div>
<div class="bottom">
<p>ucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesq</p></div>
</div>
<div class="right">
<p>Quisque vulputate mi id turpis luctus, quis laoreet nisi vestibulum. Morbi facilisis erat vitae augue ornare convallis. Fusce sit amet magna rutrum, hendrerit purus vitae, congue justo. Nam non mi eget purus ultricies lacinia. Fusce ante nisl, efficitur venenatis urna ut, pellentesque egestas nisl. In ut faucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesque maximus. Quisque a tempus lectus.</p>
</div>
</div>
</div>
</body>
So basically I just made another div to wrap the pink and yellow, and I make that div have a float:left on it. The blue div has a float:right on it.
Unfortunately the performance of getScaledInstance() is very poor if not problematic.
The alternative approach is to create a new BufferedImage and and draw a scaled version of the original on the new one.
BufferedImage resized = new BufferedImage(newWidth, newHeight, original.getType());
Graphics2D g = resized.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(original, 0, 0, newWidth, newHeight, 0, 0, original.getWidth(),
original.getHeight(), null);
g.dispose();
newWidth,newHeight indicate the new BufferedImage size and have to be properly calculated. In case of factor scaling:
int newWidth = new Double(original.getWidth() * widthFactor).intValue();
int newHeight = new Double(original.getHeight() * heightFactor).intValue();
EDIT: Found the article illustrating the performance issue: The Perils of Image.getScaledInstance()
myfile.h
#ifndef _myfile_h
#define _myfile_h
void function();
#endif
myfile.c
#include "myfile.h"
void function() {
}
For browser compatibility you can use this code. This method returns browser name and version :
private string GetBrowserNameWithVersion
{
var userAgent = Request.UserAgent;
var browserWithVersion = "";
if (userAgent.IndexOf("Edge") > -1)
{
//Edge
browserWithVersion = "Edge Browser Version : " + userAgent.Split(new string[] { "Edge/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Chrome") > -1)
{
//Chrome
browserWithVersion = "Chrome Browser Version : " + userAgent.Split(new string[] { "Chrome/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Safari") > -1)
{
//Safari
browserWithVersion = "Safari Browser Version : " + userAgent.Split(new string[] { "Safari/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Firefox") > -1)
{
//Firefox
browserWithVersion = "Firefox Browser Version : " + userAgent.Split(new string[] { "Firefox/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("rv") > -1)
{
//IE11
browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "rv:" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("MSIE") > -1)
{
//IE6-10
browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "MSIE" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Other") > -1)
{
//Other
browserWithVersion = "Other Browser Version : " + userAgent.Split(new string[] { "Other" }, StringSplitOptions.None)[1].Split('.')[0];
}
return browserWithVersion;
}
Toastr is a very nice component, and you can show messages with theses commands:
// for success - green box
toastr.success('Success messages');
// for errors - red box
toastr.error('errors messages');
// for warning - orange box
toastr.warning('warning messages');
// for info - blue box
toastr.info('info messages');
If you want to provide a title on the toastr message, just add a second argument:
// for info - blue box
toastr.success('The process has been saved.', 'Success');
you also can change the default behaviour using something like this:
toastr.options.timeOut = 3000; // 3s
See more on the github of the project.
A sample of use:
$(document).ready(function() {
// show when page load
toastr.info('Page Loaded!');
$('#linkButton').click(function() {
// show when the button is clicked
toastr.success('Click Button');
});
});
and a html:
<a id='linkButton'>Show Message</a>
You can use the following line to drop the first two columns (or any column you don't need):
df.drop([df.columns[0], df.columns[1]], axis=1)
This worked for me with 5 images in diferent sizes.
This works because of justify-content:space-between, and it's on a list, displayed horizontally.
On CSS
#container {
display: flex;
justify-content: space-between;
}
#container ul li{ display:inline; list-style-type:none;
}
On html
<div id="container">
<ul>
<li><img src="box1.png"><li>
<li><img src="box2.png"><li>
<li><img src="box3.png"><li>
<li><img src="box4.png"><li>
<li><img src="box5.png"><li>
</ul>
</div>
public static bool IsBalanced(string input)
{
Dictionary<char, char> bracketPairs = new Dictionary<char, char>() {
{ '(', ')' },
{ '{', '}' },
{ '[', ']' },
{ '<', '>' }
};
Stack<char> brackets = new Stack<char>();
try
{
// Iterate through each character in the input string
foreach (char c in input)
{
// check if the character is one of the 'opening' brackets
if (bracketPairs.Keys.Contains(c))
{
// if yes, push to stack
brackets.Push(c);
}
else
// check if the character is one of the 'closing' brackets
if (bracketPairs.Values.Contains(c))
{
// check if the closing bracket matches the 'latest' 'opening' bracket
if (c == bracketPairs[brackets.First()])
{
brackets.Pop();
}
else
// if not, its an unbalanced string
return false;
}
else
// continue looking
continue;
}
}
catch
{
// an exception will be caught in case a closing bracket is found,
// before any opening bracket.
// that implies, the string is not balanced. Return false
return false;
}
// Ensure all brackets are closed
return brackets.Count() == 0 ? true : false;
}
Extending Django User Model (UserProfile) like a Pro
I've found this very useful: link
An extract:
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User)
department = models.CharField(max_length=100)
>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department
The error message says it all. At runtime, the type is gone, there is no way to check for it.
You could catch it by making a factory for your object like this:
public static <T> MyObject<T> createMyObject(Class<T> type) {
return new MyObject<T>(type);
}
And then in the object's constructor store that type, so variable so that your method could look like this:
if (arg0 != null && !(this.type.isAssignableFrom(arg0.getClass()))
{
return -1;
}
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
DIV is a generic block level container that can contain any other block or inline elements, including other DIV elements, whereas P is to wrap paragraphs (text).
Since version 3.0 of Jquery you might get an error
TypeError: url.indexOf is not a function
Which can be easily fix by doing
$('#iframe').on('load', function() {
alert('frame has (re)loaded ');
});
Python
element.get_attribute("attribute name")
Java
element.getAttribute("attribute name")
Ruby
element.attribute("attribute name")
C#
element.GetAttribute("attribute name");
The resize event should never be used directly as it is fired continuously as we resize.
Use a debounce function to mitigate the excess calls.
window.addEventListener('resize',debounce(handler, delay, immediate),false);
Here's a common debounce floating around the net, though do look for more advanced ones as featuerd in lodash.
const debounce = (func, wait, immediate) => {
var timeout;
return () => {
const context = this, args = arguments;
const later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
This can be used like so...
window.addEventListener('resize', debounce(() => console.log('hello'),
200, false), false);
It will never fire more than once every 200ms.
For mobile orientation changes use:
window.addEventListener('orientationchange', () => console.log('hello'), false);
Here's a small library I put together to take care of this neatly.
Another example to illustrate the __declspec keyword:
When you are writing a Windows Kernel Driver, sometimes you want to write your own prolog/epilog code sequences using inline assembler code, so you could declare your function with the naked attribute.
__declspec( naked ) int func( formal_parameters ) {}
Or
#define Naked __declspec( naked )
Naked int func( formal_parameters ) {}
Please refer to naked (C++)
In onCreate with activity or in onCreateView with fragment.
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
parent.removeView(view);
}
}
try {
view = inflater.inflate(R.layout.fragment_main, container, false);
} catch (InflateException e) {
}
Take IISReset as a suite of commands that helps you manage IIS start / stop etc.
Which means you need to specify option (/switch
) what you want to do to carry any operation.
Default behavior OR default switch is /restart
with iisreset
so you do not need to run command twice with /start
and /stop
.
Hope this clarifies your question. For reference the output of iisreset /?
is:
IISRESET.EXE (c) Microsoft Corp. 1998-2005 Usage: iisreset [computername] /RESTART Stop and then restart all Internet services. /START Start all Internet services. /STOP Stop all Internet services. /REBOOT Reboot the computer. /REBOOTONERROR Reboot the computer if an error occurs when starting, stopping, or restarting Internet services. /NOFORCE Do not forcefully terminate Internet services if attempting to stop them gracefully fails. /TIMEOUT:val Specify the timeout value ( in seconds ) to wait for a successful stop of Internet services. On expiration of this timeout the computer can be rebooted if the /REBOOTONERROR parameter is specified. The default value is 20s for restart, 60s for stop, and 0s for reboot. /STATUS Display the status of all Internet services. /ENABLE Enable restarting of Internet Services on the local system. /DISABLE Disable restarting of Internet Services on the local system.
FIRST U NEED TO DEFINE WHAT'S A GET VAR:
function getVar()
{
this.length = 0;
this.keys = [];
this.push = function(key, value)
{
if(key=="") key = this.length++;
this[key] = value;
this.keys.push(key);
return this[key];
}
}
Than just read:
function urlElement()
{
var thisPrototype = window.location;
for(var prototypeI in thisPrototype) this[prototypeI] = thisPrototype[prototypeI];
this.Variables = new getVar();
if(!this.search) return this;
var variables = this.search.replace(/\?/g,'').split('&');
for(var varI=0; varI<variables.length; varI++)
{
var nameval = variables[varI].split('=');
var name = nameval[0].replace(/\]/g,'').split('[');
var pVariable = this.Variables;
for(var nameI=0;nameI<name.length;nameI++)
{
if(name.length-1==nameI) pVariable.push(name[nameI],nameval[1]);
else var pVariable = (typeof pVariable[name[nameI]] != 'object')? pVariable.push(name[nameI],new getVar()) : pVariable[name[nameI]];
}
}
}
and use like:
var mlocation = new urlElement();
mlocation = mlocation.Variables;
for(var key=0;key<mlocation.keys.length;key++)
{
console.log(key);
console.log(mlocation[mlocation.keys[key]];
}
What about -mmin
?
find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
-exec rm -f {} \;
From man find:
-mmin n File's data was last modified n minutes ago.
Also, make sure to test this first!
... -exec echo rm -f '{}' \; ^^^^ Add the 'echo' so you just see the commands that are going to get run instead of actual trying them first.
Recreate your database. Do not delete it and your app should continue to work.
You can use a simple approach...
$('YourDataTableID').dataTable()._fnAjaxUpdate();
It will refresh the data by making an ajax request with the same parameters. Very simple.
toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.
var fval = 4;
console.log(fval.toFixed(2)); // prints 4.00
The preprocessor is looking for StdCUtil/split.h
in
./
(i.e. /root/Core/
, the directory that contains the #include statement). So ./
+ StdCUtil/split.h
= ./StdCUtil/split.h
and the file is missingand in
$INC_DIR
(i.e. ../StdCUtil/
= /root/Core/../StdCUtil/
= /root/StdCUtil/
). So ../StdCUtil/
+ StdCUtil/split.h
= ../StdCUtil/StdCUtil/split.h
and the file is missingYou can fix the error changing the $INC_DIR
variable (best solution):
$INC_DIR = ../
or the include directive:
#include "split.h"
but in this way you lost the "path syntax" that makes it very clear what namespace or module the header file belongs to.
Reference:
EDIT/UPDATE
It should also be
CXX = g++
CXXFLAGS = -c -Wall -I$(INC_DIR)
...
%.o: %.cpp $(DEPS)
$(CXX) -o $@ $< $(CXXFLAGS)
Interesting. On my 64-bit (i7 Ubuntu) box:
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'int'>
Guess it steps up to 64 bit ints on a larger machine.
I recommend use /(?=.*...)/g
Example
const text1 = 'I am using regex';
/(?=.*regex)/g.test(text1) // true
const text2 = 'regex is awesome';
/(?=.*regex)/g.test(text2) // true
const text3 = 'regex is util';
/(?=.*util)(?=.*regex)/g.test(text3) // true
const text4 = 'util is necessary';
/(?=.*util)(?=.*regex)/g.test(text4) // false because need regex in text
Use regex101 to test
I was getting the xml as a String and using xml.getBytes() and getting this error. Changing to xml.getBytes(Charset.forName("UTF-8")) worked for me.
export class Car {
id: number;
make: string;
model: string;
color: string;
year: Date;
constructor(car) {
{
this.id = car.id;
this.make = car.make || '';
this.model = car.model || '';
this.color = car.color || '';
this.year = new Date(car.year).getYear();
}
}
}
The || can become super useful for very complex data objects to default data that doesn't exist.
. .
In your component.ts or service.ts file you can deserialize response data into the model:
// Import the car model
import { Car } from './car.model.ts';
// If single object
car = new Car(someObject);
// If array of cars
cars = someDataToDeserialize.map(c => new Car(c));
On Linux, in order to relax access to the document root, you should edit the following file:
/etc/httpd/conf/httpd.conf
And depending on what directory level you want to relax access to, you have to change the directive
AllowOverride None
to
AllowOverride All
So, assuming you want to allow access to files on the /var/www/html directory, you should change the following lines from:
<Directory "/var/www/html">
AllowOverride None
</Directory>
to
<Directory "/var/www/html">
AllowOverride All
</Directory>
One more useful command:
vmstat -s | grep memory
sample output on my machine is:
2050060 K total memory
1092992 K used memory
743072 K active memory
177084 K inactive memory
957068 K free memory
385388 K buffer memory
another useful command to get memory information is:
free
sample output is:
total used free shared buffers cached
Mem: 2050060 1093324 956736 108 385392 386812
-/+ buffers/cache: 321120 1728940
Swap: 2095100 2732 2092368
One observation here is that, the command free
gives information about swap space also.
The following link may be useful for you:
http://www.linuxnix.com/find-ram-details-in-linuxunix/
In my opinion, a dynamic PL/SQL block is somewhat obscure. While is very flexible, is also hard to tune, hard to debug and hard to figure out what's up. My vote goes to your first option,
EXECUTE IMMEDIATE v_query_str INTO v_num_of_employees USING p_job;
Both uses bind variables, but first, for me, is more redeable and tuneable than @jonearles option.
If you really want to be sure, grabbing the first kilobyte or two of the given URL should be sufficient to determine everything you need to know about the image.
Here's an example of how you can get that information, using Python, and here's an example of it being put to use, as a Django form field which allows you to easily validate an image's existence, filesize, dimensions and format, given its URL.
Ideally, you want to be using window.location.replace(...)
.
See this answer here for a full explanation: How do I redirect to another webpage?
you should give permission on your db
grant execute on (packageName or tableName) to user;
This solved it for me:
https://gist.github.com/beccasaurus/929007/a8f820b153a1cfdee3d06a9c0a1d7ebfced8bb77
TL;DR:
Problem:
localhost returns expected content, remote IP alters 400 content to "Bad Request"
Solution:
Adding <httpErrors existingResponse="PassThrough"></httpErrors>
to web.config/configuration/system.webServer
solved this for me; now all servers (local & remote) return the exact same content (generated by me) regardless of the IP address and/or HTTP code I return.
file_get_contents(php://input) - gets the raw POST data and you need to use this when you write APIs and need XML/JSON/... input that cannot be decoded to $_POST by PHP some example :
send by post JSON string
<input type="button" value= "click" onclick="fn()">
<script>
function fn(){
var js_obj = {plugin: 'jquery-json', version: 2.3};
var encoded = JSON.stringify( js_obj );
var data= encoded
$.ajax({
type: "POST",
url: '1.php',
data: data,
success: function(data){
console.log(data);
}
});
}
</script>
1.php
//print_r($_POST); //empty!!! don't work ...
var_dump( file_get_contents('php://input'));
you can set the width of right cell to minimum of required width, then apply overflow-hidden+text-overflow to the inside of left cell, but Firefox is buggy here...
although, seems, flexbox can help
All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.
return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);
According to the closure
definition:
A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
You are using closure
if you define a function which use a variable which is defined outside of the function. (we call the variable a free variable).
They all use closure
(even in the 1st example).
I am using .Net Core 3.1 or higher version.Please follow the solution:
public class UpdateAssignUserRole
{
public string username { get; set; }
public string rolename { get; set; }
public bool IsEdit { get; set; }
}
private async Task UpdateSeedUsers(UserManager<IdentityUser> userManager, UpdateAssignUserRole updateassignUsername)
{
IList<Users> Users = await FindByUserName(updateassignUsername.username);
if (await userManager.FindByNameAsync(updateassignUsername.username) != null)
{
var user = new IdentityUser
{
UserName = updateassignUsername.username,
Email = Users[0].Email,
};
var result = await userManager.FindByNameAsync(updateassignUsername.username);
if (result != null)
{
IdentityResult deletionResult = await userManager.RemoveFromRolesAsync(result, await userManager.GetRolesAsync(result));
if (deletionResult != null)
{
await userManager.AddToRoleAsync(result, updateassignUsername.rolename);
}
}
}
}
Despite being an old question, I'll add my opinion.
I think the right answer depends on the error message of the gcc compiler, something like "Missing xxxx.h"
This might help in some cases:
sudo apt-get install build-essential python-dev
s = s.Replace("\"",string.Empty);
This could be an answer to your question:
JSONArray msg1 = (JSONArray) json.get("source");
for(int i = 0; i < msg1.length(); i++){
String name = msg1.getString("name");
int age = msg1.getInt("age");
}
For .net 2.0 this works. It DOES compile both in the same project if you create sub directories of in app code with the related language code. As of yet, I am looking for whether this should work in 3.5 or not though.
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
One can also use a test ApplicationContextInitializer to initialize a system property:
public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
@Override
public void initialize(ConfigurableApplicationContext applicationContext)
{
System.setProperty("myproperty", "value");
}
}
and then configure it on the test class in addition to the Spring context config file locations:
@ContextConfiguration(initializers = TestApplicationContextInitializer.class, locations = "classpath:whereever/context.xml", ...)
@RunWith(SpringJUnit4ClassRunner.class)
public class SomeTest
{
...
}
This way code duplication can be avoided if a certain system property should be set for all the unit tests.
For anyone completely new to Qt Creator like me, you can modify your project's .pro file from within Qt Creator:
Just double-click on "your project name".pro in the Projects window and add the include path at the bottom of the .pro file like I've done.
You can call more of 1 function filters in the same ng-repeat filter
<article data-ng-repeat="result in results | filter:search() | filter:filterFn()" class="result">
Yes if the structure is of the same type. Think it as a memory copy.
Here is how to do dump the database (with just the schema):
mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql
If you also want the data, remove the --no-data
option.
Check the following code. It shows 2 edit text fields programmatically without any layout xml. Change 'this' to 'getActivity()' if you use it in a fragment.
The tricky thing is we have to set the second text field's input type after creating alert dialog, otherwise, the second text field shows texts instead of dots.
public void showInput() {
OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
@Override
public void onFocusChange(final View v, boolean hasFocus) {
if (hasFocus) {
// Must use message queue to show keyboard
v.post(new Runnable() {
@Override
public void run() {
InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(v, 0);
}
});
}
}
};
final EditText editTextName = new EditText(this);
editTextName.setHint("Name");
editTextName.setFocusable(true);
editTextName.setClickable(true);
editTextName.setFocusableInTouchMode(true);
editTextName.setSelectAllOnFocus(true);
editTextName.setSingleLine(true);
editTextName.setImeOptions(EditorInfo.IME_ACTION_NEXT);
editTextName.setOnFocusChangeListener(onFocusChangeListener);
final EditText editTextPassword = new EditText(this);
editTextPassword.setHint("Password");
editTextPassword.setFocusable(true);
editTextPassword.setClickable(true);
editTextPassword.setFocusableInTouchMode(true);
editTextPassword.setSelectAllOnFocus(true);
editTextPassword.setSingleLine(true);
editTextPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
editTextPassword.setOnFocusChangeListener(onFocusChangeListener);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.addView(editTextName);
linearLayout.addView(editTextPassword);
DialogInterface.OnClickListener alertDialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
// Done button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
// Cancel button clicked
break;
}
}
};
final AlertDialog alertDialog = (new AlertDialog.Builder(this)).setMessage("Please enter name and password")
.setView(linearLayout)
.setPositiveButton("Done", alertDialogClickListener)
.setNegativeButton("Cancel", alertDialogClickListener)
.create();
editTextName.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
editTextPassword.requestFocus(); // Press Return to focus next one
return false;
}
});
editTextPassword.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Press Return to invoke positive button on alertDialog.
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
return false;
}
});
// Must set password mode after creating alert dialog.
editTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
alertDialog.show();
}
JSONP is a way of getting around the browser's same-origin policy. How? Like this:
The goal here is to make a request to otherdomain.com
and alert
the name in the response. Normally we'd make an AJAX request:
$.get('otherdomain.com', function (response) {
var name = response.name;
alert(name);
});
However, since the request is going out to a different domain, it won't work.
We can make the request using a <script>
tag though. Both <script src="otherdomain.com"></script>
and $.get('otherdomain.com')
will result in the same request being made:
GET otherdomain.com
Q: But if we use the <script>
tag, how could we access the response? We need to access it if we want to alert
it.
A: Uh, we can't. But here's what we could do - define a function that uses the response, and then tell the server to respond with JavaScript that calls our function with the response as its argument.
Q: But what if the server won't do this for us, and is only willing to return JSON to us?
A: Then we won't be able to use it. JSONP requires the server to cooperate.
Q: Having to use a <script>
tag is ugly.
A: Libraries like jQuery make it nicer. Ex:
$.ajax({
url: "http://otherdomain.com",
jsonp: "callback",
dataType: "jsonp",
success: function( response ) {
console.log( response );
}
});
It works by dynamically creating the <script>
tag DOM element.
Q: <script>
tags only make GET requests - what if we want to make a POST request?
A: Then JSONP won't work for us.
Q: That's ok, I just want to make a GET request. JSONP is awesome and I'm going to go use it - thanks!
A: Actually, it isn't that awesome. It's really just a hack. And it isn't the safest thing to use. Now that CORS is available, you should use it whenever possible.
Here is an example without a parameter: http://en.csharp-online.net/CSharp_FAQ:_How_call_a_method_using_a_name_string
with params: http://www.daniweb.com/forums/thread98148.html#
you basically pass in an array of objects along with name of method. you then use both with the Invoke method.
params Object[] parameters
See RFC2616:
401 Unauthorized:
If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials.
403 Forbidden:
The server understood the request, but is refusing to fulfill it.
Update
From your use case, it appears that the user is not authenticated. I would return 401.
There is a very simple solution: http_build_query()
. It takes your query parameters as an associative array:
$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));
will return
string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"
http_build_query()
handles all the necessary escaping for you (%5B
=> [
and %5D
=> ]
), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d
.
i) what is the difference between these two objects
The simple answer is that [object]
indicates a host object that has no internal class. A host object is an object that is not part of the ECMAScript implementation you're working with, but is provided by the host as an extension. The DOM is a common example of host objects, although in most newer implementations DOM objects inherit from the native Object and have internal class names (such as HTMLElement, Window, etc). IE's proprietary ActiveXObject is another example of a host object.
[object]
is most commonly seen when alerting DOM objects in Internet Explorer 7 and lower, since they are host objects that have no internal class name.
ii) what type of Object is this
You can get the "type" (internal class) of object using Object.prototype.toString
. The specification requires that it always returns a string in the format [object [[Class]]]
, where [[Class]]
is the internal class name such as Object, Array, Date, RegExp, etc. You can apply this method to any object (including host objects), using
Object.prototype.toString.apply(obj);
Many isArray
implementations use this technique to discover whether an object is actually an array (although it's not as robust in IE as it is in other browsers).
iii) what all properties does this object contains and values of each property
In ECMAScript 3, you can iterate over enumerable properties using a for...in
loop. Note that most built-in properties are non-enumerable. The same is true of some host objects. In ECMAScript 5, you can get an array containing the names of all non-inherited properties using Object.getOwnPropertyNames(obj)
. This array will contain non-enumerable and enumerable property names.
There's also an option to Auto Sync built-in in Aptana.
You won't need a library; if you are using a recent version of Java, have a look at String.format
:
String.format("Hello %s!", "world");
There's no built-in JavaScript function to do this, but you can write your own fairly easily:
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
Meanwhile there is a native JS function that does that. See String#padStart
console.log(String(5).padStart(2, '0'));
_x000D_
mysql -u root -P 4406 -h localhost --protocol=tcp -p
Remember to change the user, port and host so that it matches your configurations. The -p flag is required if your database user is configured with a password
If youR data was in A1:C100
then:
Excel - all versions
=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))
Excel - 2007 onwards
=COUNTIFS(A1:A100,"M",C1:C100,"Yes")
None of these methods worked for me in .NET Core 2.2 but I was able to adapt some code I had for defining a different primary key to work for this purpose.
In the instance below I want to ensure the OutletRef field is unique:
public class ApplicationDbContext : IdentityDbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Outlet>()
.HasIndex(o => new { o.OutletRef });
}
}
This adds the required unique index in the database. What it doesn't do though is provide the ability to specify a custom error message.
From PowerShell remove force answer: help Remove-Item says:
The Recurse parameter in this cmdlet does not work properly
The command to workaround is
Get-ChildItem -Path $Destination -Recurse | Remove-Item -force -recurse
And then delete the folder itself
Remove-Item $Destination -Force
(copy-paste/adapted from https://stackoverflow.com/a/24048772/1733117).
First you can subclass urllib2.BaseHandler
or urllib2.HTTPBasicAuthHandler
, and implement http_request
so that each request has the appropriate Authorization
header.
import urllib2
import base64
class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
'''Preemptive basic auth.
Instead of waiting for a 403 to then retry with the credentials,
send the credentials if the url is handled by the password manager.
Note: please use realm=None when calling add_password.'''
def http_request(self, req):
url = req.get_full_url()
realm = None
# this is very similar to the code from retry_http_basic_auth()
# but returns a request object.
user, pw = self.passwd.find_user_password(realm, url)
if pw:
raw = "%s:%s" % (user, pw)
auth = 'Basic %s' % base64.b64encode(raw).strip()
req.add_unredirected_header(self.auth_header, auth)
return req
https_request = http_request
Then if you are lazy like me, install the handler globally
api_url = "http://api.foursquare.com/"
api_username = "johndoe"
api_password = "some-cryptic-value"
auth_handler = PreemptiveBasicAuthHandler()
auth_handler.add_password(
realm=None, # default realm.
uri=api_url,
user=api_username,
passwd=api_password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
I'm using the followin code. Note: It's made for an AnyCPU project.
public static bool Is32bitProcess(Process proc) {
if (!IsThis64bitProcess()) return true; // We're in 32-bit mode, so all are 32-bit.
foreach (ProcessModule module in proc.Modules) {
try {
string fname = Path.GetFileName(module.FileName).ToLowerInvariant();
if (fname.Contains("wow64")) {
return true;
}
} catch {
// What on earth is going on here?
}
}
return false;
}
public static bool Is64bitProcess(Process proc) {
return !Is32bitProcess(proc);
}
public static bool IsThis64bitProcess() {
return (IntPtr.Size == 8);
}
@( condition ? "true" : "false" )
I do just like below, after you set your column AsEnumarable you can sort, order or how you want.
_dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();
This one line jQuery code creates (and loads) a DOM element img without showing it:
$('<img src="img/1.jpg"/>');
THX - for this benchmark code:
My results on array I use for configuration are as fallows:
JSON encoded in 0.0031511783599854 seconds
PHP serialized in 0.0037961006164551 seconds
json_encode()
was roughly 20.47% faster than serialize()
JSON encoded in 0.0070841312408447 seconds
PHP serialized in 0.0035839080810547 seconds
unserialize()
was roughly 97.66% faster than json_encode()
So - test it on your own data.
What i have done and it works is create an instance in the MainActivity and getter for that instance:
public class MainActivity extends AbstractMainActivity {
private static MainActivity mInstanceActivity;
public static MainActivity getmInstanceActivity() {
return mInstanceActivity;
}
And the in the onCreate method just point to that activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
mInstanceActivity = this;
}
And in onDestroy you should set this instance to null:
@Override
protected void onDestroy() {
super.onDestroy();
mInstanceActivity = null;
}
Later you can call every method in whatever class you want:
MainActivity.getmInstanceActivity().yourMethod();
There is no global solution. For any given country it is at best rather tricky.
In the UK, the PostOffice controlls postal addresses, and can provide (at a cost) address information for validation purposes.
Government agencies also keep an extensive list of addresses, and these are centrally collated in the NLPG (National Land and Property Gazetteer).
Actually validating against these lists is very difficult. Most people don't even know exactly how their address as it is held by the PostOffice. Some businesses don't even know what number they are on a particular street.
Your best bet is to approach a company that specialises in this kind of thing.
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '[Replacement]')
In your instance it would be
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '')
Because there is no replacement (you want to get rid of it).
This will run on every row of the specified table. No need for a WHERE clause unless you want to specify only certain rows.
I end up with this issue by changing the images. Just added extra transparent background in png files. This solution works excellent on all the APIs.
The Registry locations
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\3.5
give the location for the executable.
But if you need the location where to save the Task extensions, it's on
%ProgramFiles%\MSBuild
Make sure you are on the Lastest version
implementation 'com.github.bumptech.glide:glide:4.10.0'
Kotlin:
Glide.with(this)
.asBitmap()
.load(imagePath)
.into(object : CustomTarget<Bitmap>(){
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
imageView.setImageBitmap(resource)
}
override fun onLoadCleared(placeholder: Drawable?) {
// this is called when imageView is cleared on lifecycle call or for
// some other reason.
// if you are referencing the bitmap somewhere else too other than this imageView
// clear it here as you can no longer have the bitmap
}
})
Bitmap Size:
if you want to use the original size of the image use the default constructor as above, else You can pass your desired size for bitmap
into(object : CustomTarget<Bitmap>(1980, 1080)
Java:
Glide.with(this)
.asBitmap()
.load(path)
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
Old Answer:
With compile 'com.github.bumptech.glide:glide:4.8.0'
and below
Glide.with(this)
.asBitmap()
.load(path)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
});
For compile 'com.github.bumptech.glide:glide:3.7.0'
and below
Glide.with(this)
.load(path)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
imageView.setImageBitmap(resource);
}
});
Now you might see a warning SimpleTarget is deprecated
Reason:
The main point of deprecating SimpleTarget is to warn you about the ways in which it tempts you to break Glide's API contract. Specifically, it doesn't do anything to force you to stop using any resource you've loaded once the SimpleTarget is cleared, which can lead to crashes and graphical corruption.
The SimpleTarget
still can be used as long you make sure you are not using the bitmap once the imageView is cleared.
You have to Download the driver for your Device just go to device manager-->> your device-->update driver-->choose the usb driver path from sdk extras folder and click next. You can get the correct driver and you can run on real device
Nested classes are very useful for implementing internal details that should not be exposed. If you use Reflector to check classes like Dictionary<Tkey,TValue> or Hashtable you'll find some examples.
I recommend using React.createRef()
and ref=this.elementRef
to get the DOM element reference instead of ReactDOM.findDOMNode(this)
. This way you can get the reference to the DOM element as an instance variable.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class MenuItem extends Component {
constructor(props) {
super(props);
this.elementRef = React.createRef();
}
handleNVFocus = event => {
console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
}
componentDidMount() {
this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
}
componentWillUnmount() {
this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
}
render() {
return (
<element ref={this.elementRef} />
)
}
}
export default MenuItem;
Hibernate, because it's basically the defacto standard in Java and was one of the driving forces in the creation of the JPA. It's got excellent support in Spring, and almost every Java framework supports it. Finally, GORM is a really cool wrapper around it doing dynamic finders and so on using Groovy.
It's even been ported to .NET (NHibernate) so you can use it there too.
Try adding this at the end of your code:
import matplotlib.pyplot as plt
plt.title('add title here')
Note that the default when you make a class is not public as far as packages are considered. Make sure that you actually write public class [MyClass] {
when defining your class. I've made this mistake more times than I care to admit.
Bootstrap datepicker (the first result from bootstrap datepickcer search) has a method to get the selected date.
https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html#getdate
getDate: Returns a localized date object representing the internal date object of the first datepicker in the selection. For multidate pickers, returns the latest date selected.
$('.datepicker').datepicker("getDate")
or
$('.datepicker').datepicker("getDate").valueOf()
Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.
So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.
Solution:
By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution
The main difference is that, with interfaces, you must define the actual implementation of each method within each class that implements said interface, so you can have many classes implement the same interface but with different behavior, while traits are just chunks of code injected in a class; another important difference is that trait methods can only be class-methods or static-methods, unlike interface methods which can also (and usually are) be instance methods.
I used andrew joslin's answer, which works great but triggered an angular route change, which created a jumpy looking scroll for me. If you want to avoid triggering a route change,
myApp.directive('scrollOnClick', function() {
return {
restrict: 'A',
link: function(scope, $elm, attrs) {
var idToScroll = attrs.href;
$elm.on('click', function(event) {
event.preventDefault();
var $target;
if (idToScroll) {
$target = $(idToScroll);
} else {
$target = $elm;
}
$("body").animate({scrollTop: $target.offset().top}, "slow");
return false;
});
}
}
});
NSMutableArray *arrSearchData;
NSArray *data=[arrNearByData objectAtIndex:i];
NSString *strValue=[NSString stringWithFormat:@"%@", [data valueForKey:@"restName"]];
NSRange r = [strValue rangeOfString:key options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound)
{
[arrSearchData addObject:data];
}
I had the same problem but from IIS in visual studio, I went to project properties -> Web -> and project url change http to https
From MS's Patterns & Practices documentation:
Data Validation and Error Reporting
Your view model or model will often be required to perform data validation and to signal any data validation errors to the view so that the user can act to correct them.
Silverlight and WPF provide support for managing data validation errors that occur when changing individual properties that are bound to controls in the view. For single properties that are data-bound to a control, the view model or model can signal a data validation error within the property setter by rejecting an incoming bad value and throwing an exception. If the ValidatesOnExceptions property on the data binding is true, the data binding engine in WPF and Silverlight will handle the exception and display a visual cue to the user that there is a data validation error.
However, throwing exceptions with properties in this way should be avoided where possible. An alternative approach is to implement the IDataErrorInfo or INotifyDataErrorInfo interfaces on your view model or model classes. These interfaces allow your view model or model to perform data validation for one or more property values and to return an error message to the view so that the user can be notified of the error.
The documentation goes on to explain how to implement IDataErrorInfo and INotifyDataErrorInfo.
Solution as proposed by Aziz would be:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children:children,
)
It would not be in the exact center because of padding:
padding: new EdgeInsets.all(25.0),
To make exactly center Column - at least in this case - you would need to remove padding.
hg up -C
This will remove all the changes and update to the latest head in the current branch.
And you can turn on purge extension to be able to remove all unversioned files too.
See code below
ArrayList<String> a = new ArrayList<>(Arrays.asList(strings));
a.remove(i);
strings = new String[a.size()];
a.toArray(strings);
Let me add my grain of sand here
I personally like adding a constructors as static functions that return an instance of the class (the object). The following code is an example:
class Person
{
private $name;
private $email;
public static function withName($name)
{
$person = new Person();
$person->name = $name;
return $person;
}
public static function withEmail($email)
{
$person = new Person();
$person->email = $email;
return $person;
}
}
Note that now you can create instance of the Person class like this:
$person1 = Person::withName('Example');
$person2 = Person::withEmail('yo@mi_email.com');
I took that code from:
http://alfonsojimenez.com/post/30377422731/multiple-constructors-in-php
Running a simple local HTTP server
To test such examples, one needs a local webserver. One of the easiest ways to do this for our purposes is to use Python's SimpleHTTPServer (or http.server, depending on the version of Python installed.)
# Install Python & try one of the following depending on your python version. if the version is 3.X
python3 -m http.server
# On windows try "python" instead of "python3", or "py -3"
# If Python version is 2.X
python -m SimpleHTTPServer
d = {'key1': 1,'key2': 14,'key3': 47}
sum1 = sum(d[item] for item in d)
print(sum1)
you can do it using the for loop
It's not a direct answer to the question, however I would suggest in most cases to simply set multiple classes to each element:
<div class="myclass one"></div>
<div class="myclass two></div>
<div class="myclass three"></div>
In this way you can set rules for all myclass
elements and then more specific rules for one
, two
and three
.
.myclass { color: #f00; }
.two { font-weight: bold; }
etc.
$('#effective_to').datepicker({
dateFormat: "dd-mm-yyyy",
changeMonth: true,
changeYear: true,
beforeShow: function() {
$('#ui-datepicker-div').addClass('datepicker');
}
});
CSS
.datepicker {
z-index: 100000 !important;
display: block;
}
This works form me. Even though I called model via ajax
List<Integer> listA = new ArrayList<>();
listA.add(1);
listA.add(5);
listA.add(3);
listA.add(4);
List<Integer> listB = new ArrayList<>();
listB.add(1);
listB.add(5);
listB.add(6);
listB.add(7);
System.out.println(listA.stream().filter(listB::contains).collect(Collectors.toList()));
Java 1.8 Stream API Solutions
Output [1, 5]
MongoDB actually stores the millis of a date as an int(64), as prescribed by http://bsonspec.org/#/specification
However, it can get pretty confusing when you retrieve dates as the client driver will instantiate a date object with its own local timezone. The JavaScript driver in the mongo console will certainly do this.
So, if you care about your timezones, then make sure you know what it's supposed to be when you get it back. This shouldn't matter so much for the queries, as it will still equate to the same int(64), regardless of what timezone your date object is in (I hope). But I'd definitely make queries with actual date objects (not strings) and let the driver do its thing.
innerText property sets or returns the text content as plain text of the specified node, and all its descendants whereas the innerHTML property gets and sets the plain text or HTML contents in the elements. Unlike innerText, inner HTML lets you work with HTML rich text and doesn’t automatically encode and decode text.
In addition to using Request.Form
and Request.QueryString
and depending on your specific scenario, it may also be useful to check the Page
's IsPostBack
property.
if (Page.IsPostBack)
{
// HTTP Post
}
else
{
// HTTP Get
}
UPDATE:
Since I was lazy, and didn't fully implement my solution, I searched around and found BlockComment for Xcode, a recently released plugin (June 2017). Don't bother with my solution, this plugin works beautifully, and I highly recommend it.
ORIGINAL ANSWER:
None of the above worked for me on Xcode 7 and 8, so I:
Enter the following code:
on run {input, parameters}
return "/*\n" & (input as string) & "*/"
end run
Now you can access that service through Xcode - Services menu, or by right clicking on the selected block of code you wish to comment, or giving it a shortcut under System Preferences.
Packet
A packet is the unit of data that is routed between an origin and a destination on the Internet or any other packet-switched network. When any file (e-mail message, HTML file, Graphics Interchange Format file, Uniform Resource Locator request, and so forth) is sent from one place to another on the Internet, the Transmission Control Protocol (TCP) layer of TCP/IP divides the file into "chunks" of an efficient size for routing. Each of these packets is separately numbered and includes the Internet address of the destination. The individual packets for a given file may travel different routes through the Internet. When they have all arrived, they are reassembled into the original file (by the TCP layer at the receiving end).
Frame
1) In telecommunications, a frame is data that is transmitted between network points as a unit complete with addressing and necessary protocol control information. A frame is usually transmitted serial bit by bit and contains a header field and a trailer field that "frame" the data. (Some control frames contain no data.)
2) In time-division multiplexing (TDM), a frame is a complete cycle of events within the time division period.
3) In film and video recording and playback, a frame is a single image in a sequence of images that are recorded and played back.
4) In computer video display technology, a frame is the image that is sent to the display image rendering devices. It is continuously updated or refreshed from a frame buffer, a highly accessible part of video RAM.
5) In artificial intelligence (AI) applications, a frame is a set of data with information about a particular object, process, or image. An example is the iris-print visual recognition system used to identify users of certain bank automated teller machines. This system compares the frame of data for a potential user with the frames in its database of authorized users.
string Folder = Directory.GetParent(path).Name;
I borrowed from ideas above. This is neither fast nor elegant. but it is accurate.
CASE
WHEN left(column, 3) = '000' THEN right(column, (len(column)-3))
WHEN left(column, 2) = '00' THEN right(a.column, (len(column)-2))
WHEN left(column, 1) = '0' THEN right(a.column, (len(column)-1))
ELSE
END
In Kotlin I did the following to just show the icon:
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setIcon(R.drawable.ic_icon_small)
Please check the xml file whether it has any junk character like this ?.If exists,please use the following syntax to remove that.
String XString = writer.toString();
XString = XString.replaceAll("[^\\x20-\\x7e]", "");
The accepted answer wasn't working for me when trying to parse the registry for uninstall strings, and execute them. Turns out I didn't need the call to Invoke-Expression
after all.
I finally came across this nice template for seeing how to execute uninstall strings:
$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
$app = 'MyApp'
$apps= @{}
Get-ChildItem $path |
Where-Object -FilterScript {$_.getvalue('DisplayName') -like $app} |
ForEach-Object -process {$apps.Set_Item(
$_.getvalue('UninstallString'),
$_.getvalue('DisplayName'))
}
foreach ($uninstall_string in $apps.GetEnumerator()) {
$uninstall_app, $uninstall_arg = $uninstall_string.name.split(' ')
& $uninstall_app $uninstall_arg
}
This works for me, namely because $app
is an in house application that I know will only have two arguments. For more complex uninstall strings you may want to use the join operator. Also, I just used a hash-map, but really, you'd probably want to use an array.
Also, if you do have multiple versions of the same application installed, this uninstaller will cycle through them all at once, which confuses MsiExec.exe
, so there's that too.
This seems to restore the normal onResume()
behavior that you would expect. It plays well with pressing the home key to leave the app and then re-entering the app. onResume()
is not called twice in a row.
@Override
public void setUserVisibleHint(boolean visible)
{
super.setUserVisibleHint(visible);
if (visible && isResumed())
{
//Only manually call onResume if fragment is already visible
//Otherwise allow natural fragment lifecycle to call onResume
onResume();
}
}
@Override
public void onResume()
{
super.onResume();
if (!getUserVisibleHint())
{
return;
}
//INSERT CUSTOM CODE HERE
}
To find count of unique elements of list use the combination of len()
and set()
.
>>> ls = [1, 2, 3, 4, 1, 1, 2]
>>> len(ls)
7
>>> len(set(ls))
4
Run it like this on the command line:
java -jar /path/to/your/jar/jarFile.jar
One more example for 2 dimension String array:
public void arrayExam() {
List<String[]> A = new ArrayList<String[]>();
A.add(new String[] {"Jack","good"});
A.add(new String[] {"Mary","better"});
A.add(new String[] {"Kate","best"});
for (String[] row : A) {
Log.i(TAG,row[0] + "->" + row[1]);
}
}
Output:
17467 08-02 19:24:40.518 8456 8456 I MyExam : Jack->good
17468 08-02 19:24:40.518 8456 8456 I MyExam : Mary->better
17469 08-02 19:24:40.518 8456 8456 I MyExam : Kate->best
Also check out include-what-you-use, which solves a similar problem.
if ($("#myid1").hasClass("mydivclass")){// Do any thing}
Try this query
DECLARE @PrintVarchar nvarchar(max) = (Select Sum(Amount) From Expense)
PRINT 'Varchar format =' + @PrintVarchar
DECLARE @PrintInt int = (Select Sum(Amount) From Expense)
PRINT @PrintInt
I also had this problem when doing migration => after performing php artisan migrate:refresh --seed command
"Base table or view not found: 1146 Table posts do not exist" and I solved it, I was using "soft deletes" in a separate migration file, and my original migration for "posts" table which was responsible for creating the "posts" table was performing after the "soft deletes" migration in the database\migration folder, I simply needed to rename the "posts" migration file name and put it before "softdeletes" migration to perform sooner. the do the migration again => php artisan migrate:refresh --seed it's done.
You can use pragma related commands in sqlite like below
pragma table_info("table_name")
--Alternatively
select * from pragma_table_info("table_name")
If you require column names like id|foo|bar|age|street|address
, basically your answer is in below query.
select group_concat(name,'|') from pragma_table_info("table_name")
Classes should be used when you have multiple similar elements.
Ex: Many div's displaying song lyrics, you could assign them a class of lyrics
since they are all similar.
ID's must be unique! They are used to target specific elements
Ex: An input for a users email could have the ID txtEmail
-- No other element should have this ID.
If you want to control the level of transparency you can use rgba. where a is the alpha. 0 for transparent and 1 for opaque. Make sure that final output file must have .png extension for transparency.
convert
test.png
-channel rgba
-matte
-fuzz 40%
-fill "rgba(255,255,255,0.5)"
-opaque "rgb(255,255,255)"
semi_transparent.png
If i am understanding your question. You now have both VMs on the same network segment VMnet8,
Thanks
Remote Procedure Call (RPC) is a inter process communication which allows calling a function in another process residing in local or remote machine.
Remote method invocation (RMI) is an API, which implements RPC in java with support of object oriented paradigms.
You can think of invoking RPC is like calling a C procedure. RPC supports primitive data types where as RMI support method parameters/return types as java objects.
RMI is easy to program unlike RPC. You can think your business logic in terms of objects instead of a sequence of primitive data types.
RPC is language neutral unlike RMI, which is limited to java
RMI is little bit slower to RPC
Have a look at this article for RPC implementation in C
Do ctrl+F5 to compile and run your project without debugging. Look at the output pane (defaults to "Show output from Build"). If it compiled successfully, the path to the .exe file should be there after {projectname}.vcxproj ->
I believe the best way to change the password is simply to use:
\password
in the Postgres console.
Per ALTER USER
documentation:
Caution must be exercised when specifying an unencrypted password with this command. The password will be transmitted to the server in cleartext, and it might also be logged in the client's command history or the server log. psql contains a command \password that can be used to change a role's password without exposing the cleartext password.
Note: ALTER USER
is an alias for ALTER ROLE
Try the following
for ( const auto &p : table )
{
std::cout << p.first << '\t' << p.second << std::endl;
}
The same can be written using an ordinary for loop
for ( auto it = table.begin(); it != table.end(); ++it )
{
std::cout << it->first << '\t' << it->second << std::endl;
}
Take into account that value_type for std::map
is defined the following way
typedef pair<const Key, T> value_type
Thus in my example p is a const reference to the value_type where Key is std::string
and T is int
Also it would be better if the function would be declared as
void output( const map<string, int> &table );