You can also remove files from the repository based on your .gitignore without deleting them from the local file system :
git rm --cached `git ls-files -i -X .gitignore`
Or, alternatively, on Windows Powershell:
git rm --cached $(git ls-files -i -X .gitignore)
To set up an external DB and still use your local DB, you need to edit the config.inc.php file:
On Ubuntu: sudo gedit /etc/phpmyadmin/config.inc.php
The file is roughly set up like this:
if (!empty($dbname)) {
//Your local db setup
$i++;
}
What you need to do is duplicate the "your local db setup" by copying and pasting it outside of the IF
statement I've shown in the code below, and change the host to you external IP. Mine for example is:
$cfg['Servers'][$i]['host'] = '10.10.1.90:23306';
You can leave the defaults (unless you know you need to change them)
Save and refresh your PHPMYADMIN login page and a new dropdown should appear. You should be good to go.
EDIT: if you want to give the server a name to select at login page, rather than having just the IP address to select, add this to the server setup:
$cfg['Servers'][$i]['verbose'] = 'Name to show when selecting your server';
It's good if you have multiple server configs.
you can use script module
Example
- name: Transfer and execute a script.
hosts: all
tasks:
- name: Copy and Execute the script
script: /home/user/userScript.sh
I just solved this kind of a problem. What I've learned is:
my.cnf
and set the bind-address = your.mysql.server.address
under [mysqld]
check if it's running
mysql -u root -h your.mysql.server.address –p
create a user (usr or anything) with % as domain and grant her access to the database in question.
mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)
you should be able to now connect mysql server form your client server php script.
On server
Install rsub:
wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate
chmod a+x /usr/local/bin/rsub
On local
On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub and install it
ssh -R 52698:localhost:52698 server_user@server_address
rsub path_to_file/file.txt
As of today (2018/09/05) you should use : https://github.com/randy3k/RemoteSubl because you can find it in packagecontrol.io while "rsub" is not present.
$ git push origin develop:master
or, more generally
$ git push <remote> <local branch name>:<remote branch to push into>
Many answers already, but one more option
PyPSExec https://pypi.org/project/pypsexec/
It's a python clone of the famous psexec. Works without any installation on the remote windows machine.
I'm just adding this answer here as it's the quickest
solution for me. Just set the default database engine to 'InnoDB'
on
/config/database.php
'mysql' => [
...,
...,
'engine' => 'InnoDB',
]
then run php artisan config:cache
to clear and refresh the configuration cache
EDIT: Answers found here might explain what's behind the scenes of this one
jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).
In my case the answer is pretty simple. Please check carefully the hardcoded url port: it is 8080. For some reason the value has changed to: for example 3030.
Just refresh the port in your ajax url string to the appropriate one.
conn = new WebSocket('ws://localhost:3030'); //should solve the issue
Content-Type:application/json
When you define any POST request method input parameter that should be annotated as [FromBody]
, e.g.:
[HttpPost]
public HttpResponseMessage Post([FromBody]ActivityResult ar)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
Any JSON input data must be raw data.
You called an incorrect method of String class, try:
int tmpInt = 10;
String tmpStr10 = String.valueOf(tmpInt);
You can also do:
int tmpInt = 10;
String tmpStr10 = Integer.toString(tmpInt);
What language are you using?
Many C based languages have a rule that any mathematical expression is performed in size int or larger. Because of this, once you add two shorts the result is of type int. This causes the need for a cast.
The Run as *Anything command saves you from logging out and logging in as the user for which you use the runas command for.
The reason programs ask for this elevated privilege started with Black Comb and the Panther folder. There is 0 access to the Kernel in windows unless through the Admin prompt and then it is only a virtual relation with the O/S kernel.
Hoorah!
After few hours of searching, I just solved this issue with a few lines of code
Your model
[Required(ErrorMessage = "Enter the issued date.")]
[DataType(DataType.Date)]
public DateTime IssueDate { get; set; }
Razor Page
@Html.TextBoxFor(model => model.IssueDate)
@Html.ValidationMessageFor(model => model.IssueDate)
Jquery DatePicker
<script type="text/javascript">
$(document).ready(function () {
$('#IssueDate').datepicker({
dateFormat: "dd/mm/yy",
showStatus: true,
showWeeks: true,
currentText: 'Now',
autoSize: true,
gotoCurrent: true,
showAnim: 'blind',
highlightWeek: true
});
});
</script>
Webconfig File
<system.web>
<globalization uiCulture="en" culture="en-GB"/>
</system.web>
Now your text-box will accept "dd/MM/yyyy" format.
Private Sub Worksheet_Change(ByVal Target As Range)
'data starts on row 3 which has the formulas
'the sheet is protected - input cells not locked - formula cells locked
'this routine is triggered on change of any cell on the worksheet so first check if
' it's a cell that we're interested in - and the row doesn't already have formulas
If Target.Column = 3 And Target.Row > 3 _
And Range("M" & Target.Row).Formula = "" Then
On Error GoTo ERROR_OCCURRED
'unprotect the sheet - otherwise can't copy and paste
ActiveSheet.Unprotect
'disable events - this prevents this routine from triggering again when
'copy and paste below changes the cell values
Application.EnableEvents = False
'copy col D (with validation list) from row above to new row (not locked)
Range("D" & Target.Row - 1).Copy
Range("D" & Target.Row).PasteSpecial
'copy col M to P (with formulas) from row above to new row
Range("M" & Target.Row - 1 & ":P" & Target.Row - 1).Copy
Range("M" & Target.Row).PasteSpecial
'make sure if an error occurs (or not) events are re-enabled and sheet re-protected
ERROR_OCCURRED:
If Err.Number <> 0 Then
MsgBox "An error occurred. Formulas may not have been copied." & vbCrLf & vbCrLf & _
Err.Number & " - " & Err.Description
End If
're-enable events
Application.EnableEvents = True
're-protect the sheet
ActiveSheet.Protect
'put focus back on the next cell after routine was triggered
Range("D" & Target.Row).Select
End If
End Sub
your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.
Both should work.
/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2
/node/text()[1] - should return Text1
/node/text()[2] - should return text2
Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.
OpenSessionInViewFilter
calls the openSession
method of the underlying SessionFactory
and obtains a new Session
.Session
is bound to the TransactionSynchronizationManager
.OpenSessionInViewFilter
calls the doFilter
of the javax.servlet.FilterChain
object reference and the request is further processedDispatcherServlet
is called, and it routes the HTTP request to the underlying PostController
.PostController
calls the PostService
to get a list of Post
entities.PostService
opens a new transaction, and the HibernateTransactionManager
reuses the same Session
that was opened by the OpenSessionInViewFilter
.PostDAO
fetches the list of Post
entities without initializing any lazy association.PostService
commits the underlying transaction, but the Session
is not closed because it was opened externally.DispatcherServlet
starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.OpenSessionInViewFilter
can close the Session
, and the underlying database connection is released as well.At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.
The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection
as read-only which would allow the database server to avoid writing to the transaction log.
There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.
The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize
for fetching associations in batches, and FetchMode.SUBSELECT
to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.
Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.
Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.
So, make sure that in the application.properties
configuration file, you have the following entry:
spring.jpa.open-in-view=false
This will disable OSIV so that you can handle the LazyInitializationException
the right way.
Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.
Try replacing your meta tag with this below:
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'" />
Or in addition to what you have, you should add http://*
to both style-src
and script-src
as seen above added after 'self'.
If your server is including the Content-Security-Policy
header, the header will override the meta.
You can add script tags in your HTML document, ideally inside the which points to your javascript files. Order of the script tags are important. Load the jQuery before your script files if you want to use jQuery from your script.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="relative/path/to/your/javascript.js"></script>
Then in your javascript file you can refer to jQuery either using $
sign or jQuery
.
Example:
jQuery.each(arr, function(i) { console.log(i); });
This problem is similar to this leetcode problem. Here is the answer I submitted for this problem to leetcode (check github and video for explanation).
So the very first thing we need is some way to hold the mappings of a digit and we can use a map for this:
private Map<Integer, String> getDigitMap() {
return Stream.of(
new AbstractMap.SimpleEntry<>(2, "abc"),
new AbstractMap.SimpleEntry<>(3, "def"),
new AbstractMap.SimpleEntry<>(4, "ghi"),
new AbstractMap.SimpleEntry<>(5, "jkl"),
new AbstractMap.SimpleEntry<>(6, "mno"),
new AbstractMap.SimpleEntry<>(7, "pqrs"),
new AbstractMap.SimpleEntry<>(8, "tuv"),
new AbstractMap.SimpleEntry<>(9, "wxyz"))
.collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey,
AbstractMap.SimpleEntry::getValue));
}
The above method is preparing the map and next method I would use is to provide the mapping for provided digit:
private String getDigitMappings(String strDigit, Map<Integer,String> digitMap) {
int digit = Integer.valueOf(strDigit);
return digitMap.containsKey(digit) ? digitMap.get(digit) : "";
}
This problem can be solved using backtracking and a backtracking solution generally has a structure where the method signature will contain: result container, temp results, original source with index etc. So the method structure would be of the form:
private void compute(List<String> result, StringBuilder temp, String digits, int start, Map<Integer, String> digitMap) {
// Condition to populate temp value to result
// explore other arrangements based on the next input digit
// Loop around the mappings of a digit and then to explore invoke the same method recursively
// Also need to remove the digit which was in temp at last so as to get proper value in temp for next cycle in loop
}
And now the method body can be filled as (result will be kept in a list, temp in string builder etc.)
private void compute(List<String> result, StringBuilder temp, String digits, int start, Map<Integer, String> digitMap) {
if(start >= digits.length()) { // condition
result.add(temp.toString());
return;
}
String letters = getDigitMappings(digits.substring(start, start + 1), digitMap); // mappings of a digit to loop around
for (int i = 0; i < letters.length(); i++) {
temp.append(letters.charAt(i));
compute(result, temp, digits, start+1, digitMap); //explore for remaining digits
temp.deleteCharAt(temp.length() - 1); // remove last in temp
}
}
And finally the method can be invoked as:
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
if(digits == null || digits.length() == 0) return result;
compute(result, new StringBuilder(), digits, 0, getDigitMap());
return result;
}
Now the max mapped chars for a digit can be 4 (e.g. 9 has wxyz) and backtracking involves exhaustive search to explore all possible arrangements (state space tree) so for a digit of size n
we are going to have 4x4x4....n times
i.e. complexity would be O(4^n)
.
as @Jörg W Mittag pointed out: in jruby, fix num size is always 8 bytes long. This code snippet shows the truth:
fmax = ->{
if RUBY_PLATFORM == 'java'
2**63 - 1
else
2**(0.size * 8 - 2) - 1
end
}.call
p fmax.class # Fixnum
fmax = fmax + 1
p fmax.class #Bignum
Generally, I agree with @kgrittn's advice. Go for it.
But to address your basic question about concat()
: The new function concat()
is useful if you need to deal with null values - and null has neither been ruled out in your question nor in the one you refer to.
If you can rule out null values, the good old (SQL standard) concatenation operator ||
is still the best choice, and @luis' answer is just fine:
SELECT col_a || col_b;
If either of your columns can be null, the result would be null in that case. You could defend with COALESCE
:
SELECT COALESCE(col_a, '') || COALESCE(col_b, '');
But that get tedious quickly with more arguments. That's where concat()
comes in, which never returns null, not even if all arguments are null. Per documentation:
NULL arguments are ignored.
SELECT concat(col_a, col_b);
The remaining corner case for both alternatives is where all input columns are null in which case we still get an empty string ''
, but one might want null instead (at least I would). One possible way:
SELECT CASE
WHEN col_a IS NULL THEN col_b
WHEN col_b IS NULL THEN col_a
ELSE col_a || col_b
END;
This gets more complex with more columns quickly. Again, use concat()
but add a check for the special condition:
SELECT CASE WHEN (col_a, col_b) IS NULL THEN NULL
ELSE concat(col_a, col_b) END;
How does this work?
(col_a, col_b)
is shorthand notation for a row type expression ROW (col_a, col_b)
. And a row type is only null if all columns are null. Detailed explanation:
Also, use concat_ws()
to add separators between elements (ws
for "with separator").
An expression like the one in Kevin's answer:
SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
is tedious to prepare for null values in PostgreSQL 8.3 (without concat()
). One way (of many):
SELECT COALESCE(
CASE
WHEN $1.zipcode IS NULL THEN $1.city
WHEN $1.city IS NULL THEN $1.zipcode
ELSE $1.zipcode || ' - ' || $1.city
END, '')
|| COALESCE(', ' || $1.state, '');
STABLE
concat()
and concat_ws()
are STABLE
functions, not IMMUTABLE
because they can invoke datatype output functions (like timestamptz_out
) that depend on locale settings.
Explanation by Tom Lane.
This prohibits their direct use in index expressions. If you know that the result is actually immutable in your case, you can work around this with an IMMUTABLE
function wrapper. Example here:
SignalR provides ConnectionId for each connection. To find which connection belongs to whom (the user), we need to create a mapping between the connection and the user. This depends on how you identify a user in your application.
In SignalR 2.0, this is done by using the inbuilt IPrincipal.Identity.Name
, which is the logged in user identifier as set during the ASP.NET authentication.
However, you may need to map the connection with the user using a different identifier instead of using the Identity.Name. For this purpose this new provider can be used with your custom implementation for mapping user with the connection.
Lets assume our application uses a userId
to identify each user. Now, we need to send message to a specific user. We have userId
and message
, but SignalR must also know the mapping between our userId and the connection.
To achieve this, first we need to create a new class which implements IUserIdProvider
:
public class CustomUserIdProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
// your logic to fetch a user identifier goes here.
// for example:
var userId = MyCustomUserClass.FindUserId(request.User.Identity.Name);
return userId.ToString();
}
}
The second step is to tell SignalR to use our CustomUserIdProvider
instead of the default implementation. This can be done in the Startup.cs while initializing the hub configuration:
public class Startup
{
public void Configuration(IAppBuilder app)
{
var idProvider = new CustomUserIdProvider();
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
Now, you can send message to a specific user using his userId
as mentioned in the documentation, like:
public class MyHub : Hub
{
public void Send(string userId, string message)
{
Clients.User(userId).send(message);
}
}
Hope this helps.
Internet Explorer 8 (and earlier versions) doesn't support rounded corners, however there are few other solutions you may consider:
Use Rounded Corners Images
instead (this generator is a good resource)
Use a jQuery Corner plugin
from here
Use a very good script called CSS3 PIE
from here (Pro's & Con's here)
Checkout CSS Juice
from here
Another good script is IE-CSS3
from here
Even though CSS PIE is the most popular solution, I'm suggesting you to review all other solutions and choose what works best for your needs.
Hope it was useful. Good Luck!
you might have bash but it is still a windows window manager. Highlite some text in the bash terminal window. Right click on the title bar, select "Edit", select "Copy", Now Right Click again on the Title bar, select "Edit" , Select "Paste", Done. You should be able to Highlite text, hit "Enter" then Control V but this seems to be broken
Well, since nobody else has stepped up, I'll write the easy code to do this:
x = ms / 1000
seconds = x % 60
x /= 60
minutes = x % 60
x /= 60
hours = x % 24
x /= 24
days = x
I'm just glad you stopped at days and didn't ask for months. :)
Note that in the above, it is assumed that /
represents truncating integer division. If you use this code in a language where /
represents floating point division, you will need to manually truncate the results of the division as needed.
XPath 2 has a lower-case (and upper-case) string function. That's not quite the same as case-insensitive, but hopefully it will be close enough:
//CD[lower-case(@title)='empire burlesque']
If you are using XPath 1, there is a hack using translate.
This worked for me:
I removed the single quotes.
I then used a replace ","
with "."
.
Surely this will help someone:
" & txtFinalscore.Text.Replace(",", ".") & "
I have <M-DOWN>
(alt down arrow) mapped to <DOWN>.
so that I can repeat the last command on a series of lines very quickly. with this mapping I can:
A,<ESC>
And then hold alt while pressing down repeatedly to append the comma to the end of each line.
This works well for me because it allows very good control over what lines do and do not get the change.
(I also have the other arrows mapped similarly to allow for easy repeating of .
)
Here's the mapping line to paste into your vimrc:
map <M-DOWN> <DOWN>.
Just to add to @Nathan Hughes's excellent answer:
The return
statement can be used as a kind of control flow. By putting one (or more) return
statements in the middle of a function, we can say: "stop executing this function. We've either got what we wanted or something's gone wrong!"
Here's an example:
>>> def make_3_characters_long(some_string):
... if len(some_string) == 3:
... return False
... if str(some_string) != some_string:
... return "Not a string!"
... if len(some_string) < 3:
... return ''.join(some_string,'x')[:,3]
... return some_string[:,3]
...
>>> threechars = make_3_characters_long('xyz')
>>> if threechars:
... print threechars
... else:
... print "threechars is already 3 characters long!"
...
threechars is already 3 characters long!
See the Code Style section of the Python Guide for more advice on this way of using return
.
Since image is deprecated, you should use varbinary.
per Microsoft (thanks for the link @Christopher)
ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.
It works for me:
function stringIncludes(a, b) {
return a.indexOf(b) !== -1;
}
While Hash#has_key?
gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?
.
hash.key?(some_key)
public static BufferedImage rotateCw( BufferedImage img )
{
int width = img.getWidth();
int height = img.getHeight();
BufferedImage newImage = new BufferedImage( height, width, img.getType() );
for( int i=0 ; i < width ; i++ )
for( int j=0 ; j < height ; j++ )
newImage.setRGB( height-1-j, i, img.getRGB(i,j) );
return newImage;
}
from https://coderanch.com/t/485958/java/Rotating-buffered-image
Steps:
Example
x=pd.DataFrame([1,2,3,4])
def add(i1, i2):
return i1+i2
x.apply(add,i2=9)
The outcome of this example is that each number in the dataframe will be added to the number 9.
0
0 10
1 11
2 12
3 13
Explanation:
The "add" function has two parameters: i1, i2. The first parameter is going to be the value in data frame and the second is whatever we pass to the "apply" function. In this case, we are passing "9" to the apply function using the keyword argument "i2".
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
(in the following code, you should substitute 'UTC'
for zone and now()
for timestamp)
timestamp AT TIME ZONE zone
- SQL-standard-conformingtimezone(zone, timestamp)
- arguably more readableThe function timezone(zone, timestamp) is equivalent to the SQL-conforming construct timestamp AT TIME ZONE zone.
'UTC'
) or as an interval (e.g., INTERVAL '-08:00'
) - here is a list of all available time zonesnow()
returns a value of type timestamp (just what we need) with your database's default time zone attached (e.g. 2018-11-11T12:07:22.3+05:00
).timezone('UTC', now())
turns our current time (of type timestamp with time zone) into the timezonless equivalent in UTC
.SELECT timestamp with time zone '2020-03-16 15:00:00-05' AT TIME ZONE 'UTC'
will return 2020-03-16T20:00:00Z
.Docs: timezone()
According to the documentation of Spring-Cloud-Config
there is one extra scope next to the existing five. It is @RefreshScope
.
This is the short description of RefreshScope
:
When there is a configuration change, a Spring @Bean that is marked as @RefreshScope gets special treatment. This feature addresses the problem of stateful beans that only get their configuration injected when they are initialized. For instance, if a DataSource has open connections when the database URL is changed via the Environment, you probably want the holders of those connections to be able to complete what they are doing. Then, the next time something borrows a connection from the pool, it gets one with the new URL.
Sometimes, it might even be mandatory to apply the @RefreshScope annotation on some beans which can be only initialized once. If a bean is "immutable", you will have to either annotate the bean with @RefreshScope or specify the classname under the property key spring.cloud.refresh.extra-refreshable.
Refresh scope beans are lazy proxies that initialize when they are used (that is, when a method is called), and the scope acts as a cache of initialized values. To force a bean to re-initialize on the next method call, you must invalidate its cache entry.
The RefreshScope is a bean in the context and has a public refreshAll() method to refresh all beans in the scope by clearing the target cache. The /refresh endpoint exposes this functionality (over HTTP or JMX). To refresh an individual bean by name, there is also a refresh(String) method.
The reasonable way how to launch apps from HTML is through url schemes. So you can launch email via mailto:
links and irc through irc:
links. Individual apps can implement these schemes, but I'm not sure WinMerge does this.
I encountered the same problem today. I was trying to create a table users
, and was prompted that ERROR 1146 (42S02): Table users doesn't exist
, which did not make any sense, because I was just trying to create the table!!
I then tried to drop the table by typing DROP TABLE users
, knowing it would fail because it did not exist, and I got an error, saying Unknown table users
. After getting this error, I tried to create the table again, and magically, it successfully created the table!
My intuition is that I probably created this table before and it was not completely cleared somehow. By explicitly saying DROP TABLE
I managed to reset the internal state somehow? But that is just my guess.
In short, try DROP whatever table you are creating, and CREATE it again.
If it is a simple py script refer here
Else for GUI :
$ pip3 install cx_Freeze
1) Create a setup.py file and put in the same directory as of the .py file you want to convert.
2)Copy paste the following lines in the setup.py and do change the "filename.py" into the filename you specified.
from cx_Freeze import setup, Executable
setup(
name="GUI PROGRAM",
version="0.1",
description="MyEXE",
executables=[Executable("filename.py", base="Win32GUI")],
)
3) Run the setup.py "$python setup.py build"
4)A new directory will be there there called "build". Inside it you will get your .exe file to be ready to launced directly. (Make sure you copy paste the images files and other external files into the build directory)
Check out the moment.js
library. It works with browsers as well as with Node.JS. Allows you to write
moment().hour();
or
moment().hours();
without prior writing of any functions.
<-
does assignment in the current environment.
When you're inside a function R creates a new environment for you. By default it includes everything from the environment in which it was created so you can use those variables as well but anything new you create will not get written to the global environment.
In most cases <<-
will assign to variables already in the global environment or create a variable in the global environment even if you're inside a function. However, it isn't quite as straightforward as that. What it does is checks the parent environment for a variable with the name of interest. If it doesn't find it in your parent environment it goes to the parent of the parent environment (at the time the function was created) and looks there. It continues upward to the global environment and if it isn't found in the global environment it will assign the variable in the global environment.
This might illustrate what is going on.
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
bar <- "in baz - before <<-"
bar <<- "in baz - after <<-"
print(bar)
}
print(bar)
baz()
print(bar)
}
> bar
[1] "global"
> foo()
[1] "in foo"
[1] "in baz - before <<-"
[1] "in baz - after <<-"
> bar
[1] "global"
The first time we print bar we haven't called foo
yet so it should still be global - this makes sense. The second time we print it's inside of foo
before calling baz
so the value "in foo" makes sense. The following is where we see what <<-
is actually doing. The next value printed is "in baz - before <<-" even though the print statement comes after the <<-
. This is because <<-
doesn't look in the current environment (unless you're in the global environment in which case <<-
acts like <-
). So inside of baz
the value of bar stays as "in baz - before <<-". Once we call baz
the copy of bar inside of foo
gets changed to "in baz" but as we can see the global bar
is unchanged. This is because the copy of bar
that is defined inside of foo
is in the parent environment when we created baz
so this is the first copy of bar
that <<-
sees and thus the copy it assigns to. So <<-
isn't just directly assigning to the global environment.
<<-
is tricky and I wouldn't recommend using it if you can avoid it. If you really want to assign to the global environment you can use the assign function and tell it explicitly that you want to assign globally.
Now I change the <<-
to an assign statement and we can see what effect that has:
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
assign("bar", "in baz", envir = .GlobalEnv)
}
print(bar)
baz()
print(bar)
}
bar
#[1] "global"
foo()
#[1] "in foo"
#[1] "in foo"
bar
#[1] "in baz"
So both times we print bar inside of foo
the value is "in foo" even after calling baz
. This is because assign
never even considered the copy of bar
inside of foo because we told it exactly where to look. However, this time the value of bar in the global environment was changed because we explicitly assigned there.
Now you also asked about creating local variables and you can do that fairly easily as well without creating a function... We just need to use the local
function.
bar <- "global"
# local will create a new environment for us to play in
local({
bar <- "local"
print(bar)
})
#[1] "local"
bar
#[1] "global"
Your application icon shows in the taskbar. The icon on the topleft (window) is the form-icon. Go to your form and fill the property "icon" with the same icon; problem solved. You don't need to put the icon in the outputfolder (that's just for setups).
If the string containing the phone number will always start this way (+33 or another country code) you should use regex to parse and get the country code and then use the library to get the country associated to the number.
Please be carefull with the usage of autoSizeColumn()
. It can be used without problems on small files but please take care that the method is called only once (at the end) for each column and not called inside a loop which would make no sense.
Please avoid using autoSizeColumn()
on large Excel files. The method generates a performance problem.
We used it on a 110k rows/11 columns file. The method took ~6m to autosize all columns.
For more details have a look at: How to speed up autosizing columns in apache POI?
You can use a span with 50% border radius.
.mydot{_x000D_
background: rgb(66, 183, 42);_x000D_
border-radius: 50%;_x000D_
display: inline-block;_x000D_
height: 20px;_x000D_
margin-left: 4px;_x000D_
margin-right: 4px;_x000D_
width: 20px;_x000D_
}
_x000D_
<span class="mydot"></span>
_x000D_
This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.
tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000
This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.
I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:
#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000
You'll want to use the static method Character.toString(char c) to convert the character into a string first. Then you can use the normal string concatenation functions.
In Windows it is dependent on the "Regional and Language Options" customize screen where you find a List separator. This is the char Windows applications expect to be the CSV separator.
Of course this only has effect in Windows applications, for example Excel will not automatically split data into columns if the file is not using the above mentioned separator. All applications that use Windows regional settings will have this behavior.
If you are writing a program for Windows that will require importing the CSV in other applications and you know that the list separator set for your target machines is ,
, then go for it, otherwise I prefer ;
since it causes less problems with decimal points, digit grouping and does not appear in much text.
plt.close()
will close current instance.
plt.close(2)
will close figure 2
plt.close(plot1)
will close figure with instance plot1
plt.close('all')
will close all fiures
Found here.
Remember that plt.show()
is a blocking function, so in the example code you used above, plt.close()
isn't being executed until the window is closed, which makes it redundant.
You can use plt.ion()
at the beginning of your code to make it non-blocking, although this has other implications.
After our discussion in the comments, I've put together a bit of an example just to demonstrate how the plot functionality can be used.
Below I create a plot:
fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
....
par_plot, = plot(x_data,y_data, lw=2, color='red')
In this case, ax
above is a handle to a pair of axes. Whenever I want to do something to these axes, I can change my current set of axes to this particular set by calling axes(ax)
.
par_plot
is a handle to the line2D instance. This is called an artist. If I want to change a property of the line, like change the ydata, I can do so by referring to this handle.
I can also create a slider widget by doing the following:
axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)
The first line creates a new axes for the slider (called axsliderA
), the second line creates a slider instance sA
which is placed in the axes, and the third line specifies a function to call when the slider value changes (update
).
My update function could look something like this:
def update(val):
A = sA.val
B = sB.val
C = sC.val
y_data = A*x_data*x_data + B*x_data + C
par_plot.set_ydata(y_data)
draw()
The par_plot.set_ydata(y_data)
changes the ydata property of the Line2D object with the handle par_plot
.
The draw()
function updates the current set of axes.
Putting it all together:
from pylab import *
import matplotlib.pyplot as plt
import numpy
def update(val):
A = sA.val
B = sB.val
C = sC.val
y_data = A*x_data*x_data + B*x_data + C
par_plot.set_ydata(y_data)
draw()
x_data = numpy.arange(-100,100,0.1);
fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)
ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')
axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)
axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)
axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)
axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;
par_plot, = plot(x_data,y_data, lw=2, color='red')
show()
A note about the above: When I run the application, the code runs sequentially right through (it stores the update
function in memory, I think), until it hits show(), which is blocking. When you make a change to one of the sliders, it runs the update function from memory (I think?).
This is the reason why show() is implemented in the way it is, so that you can change values in the background by using functions to process the data.
Create a Virtual Machine with Windows running on it and download the file to a shared folder. :-D
This is a working example :
RegexpExample.java
package org.regexp.replace;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexpExample
{
public static void main(String[] args)
{
String string = "var1[value1], var2[value2], var3[value3]";
Pattern pattern = Pattern.compile("(\\[)(.*?)(\\])");
Matcher matcher = pattern.matcher(string);
List<String> listMatches = new ArrayList<String>();
while(matcher.find())
{
listMatches.add(matcher.group(2));
}
for(String s : listMatches)
{
System.out.println(s);
}
}
}
It displays :
value1
value2
value3
The Win32_Process
class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.
If this is not an option for you, you can try using the taskkill
command:
Dim oShell : Set oShell = CreateObject("WScript.Shell")
' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000
' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True
There are a number of steps you have to go through to create an installer and it varies for each Operating System. For Example:
.pkg
, there are instructions on how to do that here: https://coolaj86.com/articles/how-to-create-an-osx-pkg-installer.html.deb
, there are instruction on how to do that here: https://coolaj86.com/articles/how-to-create-a-debian-installer.html.exe
or .msi
, there are instruction on how do that using the innosetup installer here: https://coolaj86.com/articles/how-to-create-an-innosetup-installer.htmlSome notes that I also found useful:
Keep your default values on the right side.
function whatever($var1, $var2, $var3="constant", $var4="another")
The default value of the argument must be a constant expression. It can't be a variable or a function call.
Once you have Selected a group of sheets, you can use Selection
Consider:
Sub luxation()
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
Selection.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="C:\TestFolder\temp.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
EDIT#1:
Further testing has reveled that this technique depends on the group of cells selected on each worksheet. To get a comprehensive output, use something like:
Sub Macro1()
Sheets("Sheet1").Activate
ActiveSheet.UsedRange.Select
Sheets("Sheet2").Activate
ActiveSheet.UsedRange.Select
Sheets("Sheet3").Activate
ActiveSheet.UsedRange.Select
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\James\Desktop\pdfmaker.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
Past 10g the current answer no longer works for renaming views. The only method that still works is dropping and recreating the view. The best way I can think of to do this would be:
SELECT TEXT FROM ALL_VIEWS WHERE owner='some_schema' and VIEW_NAME='some_view';
Add this in front of the SQL returned
Create or replace view some_schema.new_view_name as ...
Drop the old view
Drop view some_schema.some_view;
This is simple, and works with Django 1.4:
class ClientAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ClientAdminForm, self).__init__(*args, **kwargs)
# access object through self.instance...
self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)
class ClientAdmin(admin.ModelAdmin):
form = ClientAdminForm
....
You don't need to specify this in a form class, but can do it directly in the ModelAdmin, as Django already includes this built-in method on the ModelAdmin (from the docs):
ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)¶
'''The formfield_for_foreignkey method on a ModelAdmin allows you to
override the default formfield for a foreign keys field. For example,
to return a subset of objects for this foreign key field based on the
user:'''
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car":
kwargs["queryset"] = Car.objects.filter(owner=request.user)
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
An even niftier way to do this (for example in creating a front-end admin interface that users can access) is to subclass the ModelAdmin and then alter the methods below. The net result is a user interface that ONLY shows them content that is related to them, while allowing you (a super-user) to see everything.
I've overridden four methods, the first two make it impossible for a user to delete anything, and it also removes the delete buttons from the admin site.
The third override filters any query that contains a reference to (in the example 'user' or 'porcupine' (just as an illustration).
The last override filters any foreignkey field in the model to filter the choices available the same as the basic queryset.
In this way, you can present an easy to manage front-facing admin site that allows users to mess with their own objects, and you don't have to remember to type in the specific ModelAdmin filters we talked about above.
class FrontEndAdmin(models.ModelAdmin):
def __init__(self, model, admin_site):
self.model = model
self.opts = model._meta
self.admin_site = admin_site
super(FrontEndAdmin, self).__init__(model, admin_site)
remove 'delete' buttons:
def get_actions(self, request):
actions = super(FrontEndAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
prevents delete permission
def has_delete_permission(self, request, obj=None):
return False
filters objects that can be viewed on the admin site:
def get_queryset(self, request):
if request.user.is_superuser:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
return qs
else:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
if hasattr(self.model, ‘user’):
return qs.filter(user=request.user)
if hasattr(self.model, ‘porcupine’):
return qs.filter(porcupine=request.user.porcupine)
else:
return qs
filters choices for all foreignkey fields on the admin site:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if request.employee.is_superuser:
return super(FrontEndAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
else:
if hasattr(db_field.rel.to, 'user'):
kwargs["queryset"] = db_field.rel.to.objects.filter(user=request.user)
if hasattr(db_field.rel.to, 'porcupine'):
kwargs["queryset"] = db_field.rel.to.objects.filter(porcupine=request.user.porcupine)
return super(ModelAdminFront, self).formfield_for_foreignkey(db_field, request, **kwargs)
Press Ctrl+Alt+Down or Ctrl+Alt+Up to insert cursors below or above.
There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:
@media only screen
and (min-width : 415px){
/* Styles */
}
@media only screen
and (min-width : 769px){
/* Styles */
}
@media only screen
and (min-width : 992px){
/* Styles */
}
But if you are writing media queries for smaller device first, then it would be something like:
@media only screen
and (max-width : 991px){
/* Styles */
}
@media only screen
and (max-width : 768px){
/* Styles */
}
@media only screen
and (max-width : 414px){
/* Styles */
}
Don't forget to return
the mapped array , like:
lapsList() {
return this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
Reference for the map()
method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
If the elapsed event takes longer then the interval, it will create another thread to raise the elapsed event. But there is a workaround for this
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
timer.Stop();
Thread.Sleep(2000);
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
finally
{
timer.Start();
}
}
Make sure SQL Server is enabled for TCP/IP (someone may have disabled it)?
This will also help you to check/verify the port number the SQL instance is using (in case someone changed it from the default of port 1433).
Obviously port 1433 (or whatever port SQL is listening on) needs to be unblocked by any firewalls between your machine and the box SQL is running on.
To check SQL's network configuration (requires SQL Server Client Tools installed): Start -> Programs -> SQL Server 200x -> Configuration Tools -> SQL Server Configuration Manager
Connect to the machine you need then expand the Tree Item (LHS) "SQL Server Network Configuration", then pick instance. You should have four options - Shared Memory, Named Pipes, TCP/IP and VIA. You can check that TCP/IP is enabled in the RHS window.
If you double click TCP/IP and hit the "Advanced" tab, you can also view the Port number.
Other thoughts.. Are you using SQL Authentication or Windows (Domain) authentication?
If SQL Authentication (which I assume you are using given you said username and password), are you sure the SQL instance you're connecting to has mixed mode authentication enabled? If not, you have to connect as Administrator and change the default security settings to allow SQL authentication.
If Windows Authentication, could your network be using Kerberos potentially? One would think the VPN credentials would be used for the handshake. I'd check your account has appropriate login rights.
Build up a JavaScript data structure with the required information, then turn it into the json string at the end.
Based on what I think you're doing, try something like this:
var result = [];
for (var name in goals) {
if (goals.hasOwnProperty(name)) {
result.push({name: name, goals: goals[name]});
}
}
res.contentType('application/json');
res.send(JSON.stringify(result));
or something along those lines.
As of October 3, 2012, a new "Elastic Beanstalk for Java with Apache Tomcat 7" Linux x64 AMI deployed with the Sample Application has the install here:
/etc/tomcat7/
The /etc/tomcat7/tomcat7.conf file has the following settings:
# Where your java installation lives
JAVA_HOME="/usr/lib/jvm/jre"
# Where your tomcat installation lives
CATALINA_BASE="/usr/share/tomcat7"
CATALINA_HOME="/usr/share/tomcat7"
JASPER_HOME="/usr/share/tomcat7"
CATALINA_TMPDIR="/var/cache/tomcat7/temp"
I'd start with:
secedit /export /areas USER_RIGHTS /cfg OUTFILE.CFG
Then examine the line for the relevant privilege. However, the problem now is that the accounts are listed as SIDs, not usernames.
Firebase provides some good features like real time change reflection , easy integration of authentication mechanism , and lots of other built-in features for rapid web development. Firebase, really makes Web development so simple that never exists. Firebase database is a fork of MongoDB.
What's the advantage of using Firebase over MongoDB?
You can take advantage of all built-in features of Firebase over MongoDB.
I had the same problem and the solution was pretty easy:
"If you create a new conda environment while VS Code is running, use the Reload Window command to refresh the environment list shown with Python: Select Interpreter; otherwise you may not see the environment there. It might take a short time to appear; if you don't see it at first, wait 15 seconds then try using the command again."
That's written on Vscode site
Note: to Reload Window: ctrl+shift+p in Vscode, then write reload window
I want to mention one important note regarding req.query
, because currently I am working on pagination functionality based on req.query
and I have one interesting example to demonstrate to you...
Example:
// Fetching patients from the database
exports.getPatients = (req, res, next) => {
const pageSize = +req.query.pageSize;
const currentPage = +req.query.currentPage;
const patientQuery = Patient.find();
let fetchedPatients;
// If pageSize and currentPage are not undefined (if they are both set and contain valid values)
if(pageSize && currentPage) {
/**
* Construct two different queries
* - Fetch all patients
* - Adjusted one to only fetch a selected slice of patients for a given page
*/
patientQuery
/**
* This means I will not retrieve all patients I find, but I will skip the first "n" patients
* For example, if I am on page 2, then I want to skip all patients that were displayed on page 1,
*
* Another example: if I am displaying 7 patients per page , I want to skip 7 items because I am on page 2,
* so I want to skip (7 * (2 - 1)) => 7 items
*/
.skip(pageSize * (currentPage - 1))
/**
* Narrow dont the amound documents I retreive for the current page
* Limits the amount of returned documents
*
* For example: If I got 7 items per page, then I want to limit the query to only
* return 7 items.
*/
.limit(pageSize);
}
patientQuery.then(documents => {
res.status(200).json({
message: 'Patients fetched successfully',
patients: documents
});
});
};
You will noticed +
sign in front of req.query.pageSize
and req.query.currentPage
Why? If you delete +
in this case, you will get an error, and that error will be thrown because we will use invalid type (with error message 'limit' field must be numeric).
Important: By default if you extracting something from these query parameters, it will always be a string, because it's coming the URL and it's treated as a text.
If we need to work with numbers, and convert query statements from text to number, we can simply add a plus sign in front of statement.
run composer update
. That's it
You can use the new YouTube Data API v3
if you retrieve the video, the statistics part contains the viewCount:
from the doc:
https://developers.google.com/youtube/v3/docs/videos#resource
statistics.viewCount / The number of times the video has been viewed.
You can retrieve this info in the client side, or in the server side using some of the client libraries:
https://developers.google.com/youtube/v3/libraries
And you can test the API call from the doc:
https://developers.google.com/youtube/v3/docs/videos/list
Sample:
Request:
GET https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Q5mHPo2yDG8&key={YOUR_API_KEY}
Authorization: Bearer ya29.AHES6ZSCT9BmIXJmjHlRlKMmVCU22UQzBPRuxzD7Zg_09hsG
X-JavaScript-User-Agent: Google APIs Explorer
Response:
200 OK
- Show headers -
{
"kind": "youtube#videoListResponse",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/dZ8K81pnD1mOCFyHQkjZNynHpYo\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"id": "Q5mHPo2yDG8",
"kind": "youtube#video",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/4NA7C24hM5mprqQ3sBwI5Lo9vZE\"",
"statistics": {
"viewCount": "36575966",
"likeCount": "127569",
"dislikeCount": "5715",
"favoriteCount": "0",
"commentCount": "20317"
}
}
]
}
It selects the next paragraph and indents the beginning of the paragraph from the left just as you might in Microsoft Word.
I got further with Valeres answer:
pip install configparser sudo cp /usr/lib/python3.6/configparser.py /usr/lib/python3.6/ConfigParser.py Then try to install the MYSQL-python again. That Worked for me
I would suggest to link the file instead of copy it. It is save to update. I linked the file to /usr/lib/python3/
directory.
Presumably, if one wants to use an OnTouchListener
rather than an OnClickListener
, then the extra functionality of the OnTouchListener
is needed. This is a supplemental answer to show more detail of how an OnTouchListener
can be used.
Define the listener
Put this somewhere in your activity or fragment.
private View.OnTouchListener handleTouch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("TAG", "touched down");
break;
case MotionEvent.ACTION_MOVE:
Log.i("TAG", "moving: (" + x + ", " + y + ")");
break;
case MotionEvent.ACTION_UP:
Log.i("TAG", "touched up");
break;
}
return true;
}
};
Set the listener
Set the listener in onCreate
(for an Activity) or onCreateView
(for a Fragment).
myView.setOnTouchListener(handleTouch);
Notes
getX
and getY
give you the coordinates relative to the view (that is, the top left corner of the view). They will be negative when moving above or to the left of your view. Use getRawX
and getRawY
if you want the absolute screen coordinates.x
and y
values to determine things like swipe direction.Select option by Index:
var selectDropdownElement= element(by.id('select-dropdown'));
selectDropdownElement.all(by.tagName('option'))
.then(function (options) {
options[0].click();
});
Change the file content of c:\wamp\alias\phpmyadmin.conf
to the following.
<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Allow from all
</Directory>
Here my WAMP installation is in the c:\wamp folder. Change it according to your installation.
Previously, it was like this:
<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Directory>
Restart your Apache server after making these changes.
For Meteor developers.
Open a second terminal window while running your app in localhost:3000
.
In your project's folder run, meteor mongo
.
coolName = new Mongo.Collection('yourCollectionName');
Then simply enter db.yourCollectionName.drop();
You'll automatically see the changes in your local server.
For everybody else.
db.yourCollectionName.drop();
In dplyr 0.3 this can be easily achieved using the distinct()
method.
Here is an example:
distinct_df = df %>% distinct(field1)
You can get a vector of the distinct values with:
distinct_vector = distinct_df$field1
You can also select a subset of columns at the same time as you perform the distinct()
call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:
distinct_df = df %>% distinct(field1) %>% select(field1)
distinct_vector = distinct_df$field1
In modern browsers (IE8+, FF3.6+, Chrome), you can just listen to the hashchange
event on window
.
In some old browsers, you need a timer that continually checks location.hash
. If you're using jQuery, there is a plugin that does exactly that.
In HTML:
<a href="index.php?link=home" name="home">home</a>
Then in PHP:
if(isset($_GET['link'])){$_SESSION['link'] = $_GET['link'];}
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
My suggestion would be to finish the activity that you don't want the users to go back to. For instance, in your sign in activity, right after you call startActivity
, call finish()
. When the users hit the back button, they will not be able to go to the sign in activity because it has been killed off the stack.
A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form
File.open("my/file/path", "r") do |f|
f.each_line do |line|
puts line
end
end
# File is closed automatically at end of block
It is also possible to explicitly close file after as above (pass a block to open
closes it for you):
f = File.open("my/file/path", "r")
f.each_line do |line|
puts line
end
f.close
Simply add alignSelf: "stretch"
to your item's stylesheet.
line1: {
backgroundColor: '#FDD7E4',
alignSelf: 'stretch',
textAlign: 'center',
},
One caveat! If you want to compose this via OR or AND you cannot use it in this form:
-myfield:*
but you must use
(*:* NOT myfield:*)
This form is perfectly composable. Apparently SOLR will expand the first form to the second, but only when it is a top node. Hope this saves you some time!
There is extensive paramiko API documentation you can find at: http://docs.paramiko.org/en/stable/index.html
I use the following method to execute commands on a password protected client:
import paramiko
nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username'
password = 'password'
command = 'ls'
client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)
stdout_data = []
stderr_data = []
session = client.open_channel(kind='session')
session.exec_command(command)
while True:
if session.recv_ready():
stdout_data.append(session.recv(nbytes))
if session.recv_stderr_ready():
stderr_data.append(session.recv_stderr(nbytes))
if session.exit_status_ready():
break
print 'exit status: ', session.recv_exit_status()
print ''.join(stdout_data)
print ''.join(stderr_data)
session.close()
client.close()
Around 1:51 in the video, notice how she puts a <script>
tag in there? The way it works is like this:
Create an html file (that's just a text file with a .html
ending) somewhere on your computer. In the same folder that you put index.html
, put a javascript file (that's just a textfile with a .js
ending - let's call it game.js
). Then, in your index.html
file, put some html that includes the script tag with game.js
, like Mary did in the video. index.html
should look something like this:
<html>
<head>
<script src="game.js"></script>
</head>
</html>
Now, double click on that file in finder, and it should open it up in your browser. To open up the console to see the output of your javascript code, hit Command-alt-j (those three buttons at the same time).
Good luck on your journey, hope it's as fun for you as it has been for me so far :)
I've used MPDF library. For more information view this tutorial https://arjunphp.com/generating-a-pdf-in-codeigniter-using-mpdf/
http://www.jetbrains.com/resharper/
My story: started working in a new company, never used Visual Studio before. One of the first things - how to duplicate line. After setting up macro ReSharper told me: would you like to substitute my shortcut which was: "duplicate text" :)
Why does C# have both 'ref' and 'out'?
The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.
In contrast ref parameters are considered initially assigned by the caller. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.
So, out
means out, while ref
is for in and out.
These correspond closely to the [out]
and [in,out]
parameters of COM interfaces, the advantages of out
parameters being that callers need not pass a pre-allocated object in cases where it is not needed by the method being called - this avoids both the cost of allocation, and any cost that might be associated with marshaling (more likely with COM, but not uncommon in .NET).
Easy way to do:
NSInteger value = x;
NSString *string = [@(value) stringValue];
Here the @(value)
converts the given NSInteger
to an NSNumber
object for which you can call the required function, stringValue
.
Enum.GetValues(typeof(MyEnum)).Length;
Every interface is implicitly abstract.
This modifier is obsolete and should not be used in new programs.
[The Java Language Specification - 9.1.1.1 abstract
Interfaces]
Also note that interface member methods are implicitly public abstract
.
[The Java Language Specification - 9.2 Interface Members]
Why are those modifiers implicit? There is no other modifier (not even the 'no modifier'-modifier) that would be useful here, so you don't explicitly have to type it.
Element.children
returns only element children, while Node.childNodes
returns all node children. Note that elements are nodes, so both are available on elements.
I believe childNodes
is more reliable. For example, MDC (linked above) notes that IE only got children
right in IE 9. childNodes
provides less room for error by browser implementors.
I suppose that the array size if a computed value.
int size = ComputeArraySize();
// Then
String[] array = new String[size];
An alternative to nvm-windows, which is mentioned in other answers would be Nodist.
I've had some issues with nvm-windows and admin privileges, which Nodist doesn't seem to have.
I assume from db
that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);
Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).
For a trivial example of the type of thing you can do:
select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" };
You can do much richer things, but I really doubt you can pick the table in the conditional. You're welcome to try, of course...
With the web.xml configured they way you have in the question, in particular:
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
ALL requests being made to your web app will be directed to the DispatcherServlet
. This includes requests like /tasklist/
, /tasklist/some-thing.html
, /tasklist/WEB-INF/views/index.jsp
.
Because of this, when your controller returns a view that points to a .jsp
, instead of allowing your server container to service the request, the DispatcherServlet
jumps in and starts looking for a controller that can service this request, it doesn't find any and hence the 404
.
The simplest way to solve is to have your servlet url mapping as follows:
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Notice the missing *
. This tells the container that any request that does not have a path info
in it (urls without a .xxx at the end), should be sent to the DispatcherServlet
. With this configuration, when a xxx.jsp
request is received, the DispatcherServlet
is not consulted, and your servlet container's default servlet will service the request and present the jsp as expected.
Hope this helps, I realize your earlier comments state that the problem has been resolved, but the solution CAN NOT be just adding method=RequestMethod.GET
to the RequestMethod
.
No, there is not really any other way : if you have many locations and want to display them on a map, the best solution is to :
This is, of course, considering that you have a lot less creation/modification of locations than you have consultations of locations.
Yes, it means you'll have to do a bit more work when saving the locations -- but it also means :
You could create a helper function:
def re_match_group(pattern, str, out_groups):
del out_groups[:]
result = re.match(pattern, str)
if result:
out_groups[:len(result.groups())] = result.groups()
return result
And then use it like this:
groups = []
if re_match_group("I love (\w+)", statement, groups):
print "He loves", groups[0]
elif re_match_group("Ich liebe (\w+)", statement, groups):
print "Er liebt", groups[0]
elif re_match_group("Je t'aime (\w+)", statement, groups):
print "Il aime", groups[0]
It's a little clunky, but it gets the job done.
I wrote a wrapper, that will cache text surfaces, only re-render when dirty. googlecode/ninmonkey/nin.text/demo/
Well, i guess M represent the mantissa. Decimal can be used to save money, but it doesn't mean, decimal only used for money.
function redirectHome($theMsg, $url = null, $seconds = 3) {
if ($url === null) {
$url = 'index.php';
$link = 'Homepage';
} else {
if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] !== '') {
$url = $_SERVER['HTTP_REFERER'];
$link = 'Previous Page';
} else {
$url = 'index.php';
$link = 'Homepage';
}
}
echo $theMsg;
echo "<div class='alert alert-info'>You Will Be Redirected to $link After $seconds Seconds.</div>";
header("refresh:$seconds;url=$url");
exit();
}
If all the staged files were actually committed, then the branch can simply be reset e.g. from your GUI with about three mouse clicks: Branch, Reset, Yes!
So what I often do in practice to revert unwanted local changes is to commit all the good stuff, and then reset the branch.
If the good stuff is committed in a single commit, then you can use "amend last commit" to bring it back to being staged or unstaged if you'd ultimately like to commit it a little differently.
This might not be the technical solution you are looking for to your problem, but I find it a very practical solution. It allows you to discard unstaged changes selectively, resetting the changes you don't like and keeping the ones you do.
So in summary, I simply do commit, branch reset, and amend last commit.
$Hour1 = "09:00 am";
$Hour = date("H:i", strtotime($Hour1));
I had a similar problem and was able to solve it by following the below approach (similar to other answers but needed credentials too),
1- add Microsoft.SharePointOnline.CSOM by tools->NuGet Package Manager->Manage NuGet Packages for solution->Browse-> select and install
2- Add "using Microsoft.SharePoint.Client; "
then the below code
string siteUrl = "https://yourcompany.sharepoint.com/sites/Yoursite";
SecureString passWord = new SecureString();
var password = "Your password here";
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", securePassword);/*passWord*/
List oList = clientContext.Web.Lists.GetByTitle("The name of your list here");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(itemCreateInfo);
oListItem["PK"] = "1";
oListItem["Precinct"] = "Mangere";
oListItem["Title"] = "Innovation";
oListItem["Project_x005F_x0020_Name"] = "test from C#";
oListItem["Project_x005F_x0020_ID"] = "ID_123_from C#";
oListItem["Project_x005F_x0020_start_x005F_x0020_date"] = "2020-05-01 01:01:01";
oListItem.Update();
clientContext.ExecuteQuery();
Remember that your fields may be different with what you see, for example in my list I see "Project Name", while the actual value is "Project_x005F_x0020_ID". How to get these values (i.e. internal filed values)?
A few approaches:
1- Use MS flow and see them
2- https://mstechtalk.com/check-column-internal-name-sharepoint-list/ or https://sharepoint.stackexchange.com/questions/787/finding-the-internal-name-and-display-name-for-a-list-column
3- Use a C# reader and read your sharepoint list
The rest of operations (update/delete): https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee539976(v%3Doffice.14)
In Ubuntu if you execute the script with sh scriptname.sh
you get this problem.
Try executing the script with ./scriptname.sh
instead.
Be sure there is nothing on your button (such a div or a trasparent img) that keeps from clicking the button. It sounds stupid, but sometimes we think that jQuery is not working and all that stuffs and the problem is on the positioning of DOM elements.
An alternate method that limits the scope of the lambda rather than giving it access to the whole this
is to pass in a local reference to the member variable, e.g.
auto& localGrid = grid;
int i;
for_each(groups.cbegin(),groups.cend(),[localGrid,&i](pair<int,set<int>> group){
i++;
cout<<i<<endl;
});
IMHO
Builder is some kind of more complex Factory.
But in Builder you can instantiate objects with using another factories, that are required to build final and valid object.
So, talking about "Creational Patterns" evolution by complexity you can think about it in this way:
Dependency Injection Container -> Service Locator -> Builder -> Factory
The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only
I have my own api back end with laravel, so I usually just the following:
$(document).ready( function() {
$.getJSON( "http://api.whoisdoma.com/v1/ip/visitor?api_key=key",
function(data){
alert( data.ip);
}
);
});
For extra security, I provide an api key which is required to get results.
Yet, it is possible to fake it using a dedicated table, named for your fake-sp, with an AFTER INSERT trigger. The dedicated table rows contain the parameters for your fake sp, and if it needs to return results you can have a second (poss. temp) table (with name related to the fake-sp) to contain those results. It would require two queries: first to INSERT data into the fake-sp-trigger-table, and the second to SELECT from the fake-sp-results-table, which could be empty, or have a message-field if something went wrong.
Now from docker client you can simply search your private registry directly without using the HTTP APIs or any extra tools:
e.g. searching for centos image:
docker search localhost:5000/centos
Haider's answer is correct for pre-iOS 6. However, as of iOS 6 viewDidUnload and viewWillUnload are never called. The docs state: "Views are no longer purged under low-memory conditions and so this method is never called."
That should work, you may need a space after the commas.
Also, the function you call afterwards must support an array of objects, and not just a singleton object.
This is how I would write using more functional way
. Here is the code:
new List<Money>()
{
new Money() { Amount = 10, Type = "US"},
new Money() { Amount = 20, Type = "US"}
}
.ForEach(money =>
{
Console.WriteLine($"amount is {money.Amount}, and type is {money.Type}");
});
Use the unicode escape sequence. First you'll have to find the codepoint for the character you seek to replace (let's just say it is ABCD in hex):
str = str.replaceAll("\uABCD", "");
you can go to project properties --> configuration properties --> General -->Project default and there change the "Character set" from "Unicode" to "Not set".
Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance.
Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.
The only commands that worked for me were:
git fetch --all
git reset --hard origin/{{your branch name}}
I take it from your question that your hover effect changes the content of your page. In that case, my advice is to:
touchstart
and mouseenter
.mouseleave
, touchmove
and click
.Alternatively, you can edit your page that there is no content change.
In order to simulate a mouse, browsers such as Webkit mobile fire the following events if a user touches and releases a finger on touch screen (like iPad) (source: Touch And Mouse on html5rocks.com):
touchstart
touchmove
touchend
mouseover
mouseenter
mouseover
, mouseenter
or mousemove
event changes the page content, the following events are never fired.mousemove
mousedown
mouseup
click
It does not seem possible to simply tell the webbrowser to skip the mouse events.
What's worse, if a mouseover event changes the page content, the click event is never fired, as explained on Safari Web Content Guide - Handling Events, in particular figure 6.4 in One-Finger Events. What exactly a "content change" is, will depend on browser and version. I've found that for iOS 7.0, a change in background color is not (or no longer?) a content change.
To recap:
touchstart
and mouseenter
.mouseleave
, touchmove
and click
.Note that there is no action on touchend
!
This clearly works for mouse events: mouseenter
and mouseleave
(slightly improved versions of mouseover
and mouseout
) are fired, and add and remove the hover.
If the user actually click
s a link, the hover effect is also removed. This ensure that it is removed if the user presses the back button in the web browser.
This also works for touch events: on touchstart the hover effect is added. It is '''not''' removed on touchend. It is added again on mouseenter
, and since this causes no content changes (it was already added), the click
event is also fired, and the link is followed without the need for the user to click again!
The 300ms delay that a browser has between a touchstart
event and click
is actually put in good use because the hover effect will be shown during this short time.
If the user decides to cancel the click, a move of the finger will do so just as normal. Normally, this is a problem since no mouseleave
event is fired, and the hover effect remains in place. Thankfully, this can easily be fixed by removing the hover effect on touchmove
.
That's it!
Note that it is possible to remove the 300ms delay, for example using the FastClick library, but this is out of scope for this question.
I've found the following problems with the following alternatives:
touchend
: This will incorrectly follow the link, even if the user only wanted to scroll or zoom, without the intention of actually clicking the link.touchend
that is used as a if-condition in subsequent mouse events to prevents state changes at that point in time. The variable is reset in the click event. See Walter Roman's answer on this page. This is a decent solution if you really don't want a hover effect on touch interfaces. Unfortunately, this does not work if a touchend
is fired for another reason and no click event is fired (e.g. the user scrolled or zoomed), and is subsequently trying to following the link with a mouse (i.e on a device with both mouse and touch interface).mouseover
or mousemove
event.First globally declare
Context mContext;
pass context with the constructor, by modifying it.
public FeedAdapter(List<Post> myDataset, Context context) {
mDataset = myDataset;
this.mContext = context;
}
then use the mContext
whereever you need it
1st way is to use props
<Row id = "someRandomID">
Wherein, in the Definition, you may just go
const Row = props => {
div id = {props.id}
}
The same could be done with class, replacing id with className in the above example.
You might as well use react-html-id
, that is an npm package.
This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.
Ref: react-html-id
Peace.
Put this in your CSS:
white-space:nowrap;
Get more information here: http://www.w3.org/wiki/CSS/Properties/white-space
white-space
The white-space
property declares how white space inside the element is handled.
Values
normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.
pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at newlines in the source, or at occurrences of "\A" in generated content.
nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.
pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.
pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.
inherit
Takes the same specified value as the property for the element's parent.
You can disable need to run Internet Explorer's first launch configuration by running this PowerShell script, it will adjust corresponding registry property:
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer\Main" -Name "DisableFirstRunCustomize" -Value 2
After this, WebClient will work without problems
I don´t think you can have two Id´s but it should be possible. Using the same id twice is a different case... like two people using the same passport. However one person could have multiple passports... Came looking for this since I have a situation where a single employee can have several functions. Say "sysadm" and "team coordinator" having the id="sysadm teamcoordinator" would let me reference them from other pages so that employees.html#sysadm and employees.html#teamcoordinator would lead to the same place... One day somebody else might take over the team coordinator function while the sysadm remains the sysadm... then I only have to change the ids on the employees.html page ... but like I said - it doesn´t work :(
sounds silly but font-size:0; might just work. It did for me. And you can easily override this with the child element you need to show.
The thing you can do is create a .bat that will execute the .jar file created, checking if there is a JRE present.
From Mitch useful link (source)
java -classpath myprogram.jar de.vogella.eclipse.ide.first.MyFirstClass
This can be used into your batch...
Since http proxy protocol is similar to raw http protocol, you can redirect desired traffic to your development server by telling firefox it's a proxy server.
two limitations:
A. this won't let you use https connections.
B. some frameworks (e,g: wordpress) don't like this method and redirect the request the wrong way
just copy the following code into a .pac file (enter your site domain and IP address, of course), and switch development/production just by changing proxy configuration.
function FindProxyForURL(url, host) {
var prox4site = {
"mysite.com":"PROXY 10.0.1.100:80",
"www.mysite.com":"PROXY 10.0.1.100:80"
}
return prox4site[host] || "DIRECT";
}
Instinctively one thinks geometrically: horizontal (X) axis and then vertical (Y) axis. This is not, however, the case with a 2D array, rows come first and then columns.
Consider the following analogy: in geometry one walks to the ladder (X axis) and climbs it (Y axis). Conversely, in Java one descends the ladder (rows) and walks away (columns).
It looks like it is an extension method (in System.Net.Http.Formatting):
Update:
PM> install-package Microsoft.AspNet.WebApi.Client
According to the System.Net.Http.Formatting NuGet package page, the System.Net.Http.Formatting
package is now legacy and can instead be found in the Microsoft.AspNet.WebApi.Client
package available on NuGet here.
None of this will work as expected.. The correct way is to change position: fixed to position: absolute for .modal class
SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID
As others have said, Objective-C is much more dynamic in terms of how it thinks of objects vs. C++'s fairly static realm.
Objective-C, being in the Smalltalk lineage of object-oriented languages, has a concept of objects that is very similar to that of Java, Python, and other "standard", non-C++ object-oriented languages. Lots of dynamic dispatch, no operator overloading, send messages around.
C++ is its own weird animal; it mostly skipped the Smalltalk portion of the family tree. In some ways, it has a good module system with support for inheritance that happens to be able to be used for object-oriented programming. Things are much more static (overridable methods are not the default, for example).
I would like to add recommendations from oracle trouble shooting article.
Exception in thread thread_name: java.lang.OutOfMemoryError: Java heap space
The detail message Java heap space indicates object could not be allocated in the Java heap. This error does not necessarily imply a memory leak
Possible causes:
Simple configuration issue, where the specified heap size is insufficient for the application.
Application is unintentionally holding references to objects, and this prevents the objects from being garbage collected.
Excessive use of finalizers.
One other potential source of this error arises with applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time
After garbage collection, the objects are queued for finalization, which occurs at a later time. finalizers are executed by a daemon thread that services the finalization queue. If the finalizer thread cannot keep up with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown.
One scenario that can cause this situation is when an application creates high-priority threads that cause the finalization queue to increase at a rate that is faster than the rate at which the finalizer thread is servicing that queue.
next
- it's like return
, but for blocks! (So you can use this in any proc
/lambda
too.)
That means you can also say next n
to "return" n
from the block. For instance:
puts [1, 2, 3].map do |e|
next 42 if e == 2
e
end.inject(&:+)
This will yield 46
.
Note that return
always returns from the closest def
, and never a block; if there's no surrounding def
, return
ing is an error.
Using return
from within a block intentionally can be confusing. For instance:
def my_fun
[1, 2, 3].map do |e|
return "Hello." if e == 2
e
end
end
my_fun
will result in "Hello."
, not [1, "Hello.", 2]
, because the return
keyword pertains to the outer def
, not the inner block.
You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..
But another question is this: How do you set the color of the text You write?
Answer: You use the turtle.color() method or turtle.fillcolor(), like this:
turtle.fillcolor("blue")
or just:
turtle.color("orange")
These calls must come before the turtle.write() command..
std::string s(v.begin(), v.end());
Where v is pretty much anything iterable. (Specifically begin() and end() must return InputIterators.)
Probably the jstl libraries are missing from your classpath/not accessible by tomcat.
You need to add at least the following jar files in your WEB-INF/lib
directory:
And here's an example of the customizer implemented in Groovy:
I was having the same problem. Currently I am using the version 8.1, First of all go to the window tab, that is just before the tab help. Click on window and there click reset "Reset Window", after that in the bottom right click on the tab where your project runs, right click and select show output.
This worked for me on all browsers:
I was facing the same issue and the reason was single backslah. I used double backslash in my "Data source" and it worked
connetionString = "Data Source=localhost\\SQLEXPRESS;Database=databasename;Integrated Security=SSPI";
I collected some information on the internet and prepared the script that requires no external tool: See my response here. Hope it's helpful.
myString.Substring(myString.Length - 3, 3)
Here are examples on substring.>>
http://www.dotnetperls.com/substring
Refer those.
When I refer to Dijkstra’s algorithm in my explanation I will be talking about the Dijkstra's Algorithm as implemented below,
So starting out the values (the distance from the source to the vertex) initially assigned to each vertex are,
We first extract the vertex in Q = [A,B,C] which has smallest value, i.e. A, after which Q = [B, C]. Note A has a directed edge to B and C, also both of them are in Q, therefore we update both of those values,
Now we extract C as (2<5), now Q = [B]. Note that C is connected to nothing, so line16
loop doesn't run.
Finally we extract B, after which . Note B has a directed edge to C but C isn't present in Q therefore we again don't enter the for loop in line16
,
So we end up with the distances as
Note how this is wrong as the shortest distance from A to C is 5 + -10 = -5, when you go .
So for this graph Dijkstra's Algorithm wrongly computes the distance from A to C.
This happens because Dijkstra's Algorithm does not try to find a shorter path to vertices which are already extracted from Q.
What the line16
loop is doing is taking the vertex u and saying "hey looks like we can go to v from source via u, is that (alt or alternative) distance any better than the current dist[v] we got? If so lets update dist[v]"
Note that in line16
they check all neighbors v (i.e. a directed edge exists from u to v), of u which are still in Q. In line14
they remove visited notes from Q. So if x is a visited neighbour of u, the path is not even considered as a possible shorter way from source to v.
In our example above, C was a visited neighbour of B, thus the path was not considered, leaving the current shortest path unchanged.
This is actually useful if the edge weights are all positive numbers, because then we wouldn't waste our time considering paths that can't be shorter.
So I say that when running this algorithm if x is extracted from Q before y, then its not possible to find a path - which is shorter. Let me explain this with an example,
As y has just been extracted and x had been extracted before itself, then dist[y] > dist[x] because otherwise y would have been extracted before x. (line 13
min distance first)
And as we already assumed that the edge weights are positive, i.e. length(x,y)>0. So the alternative distance (alt) via y is always sure to be greater, i.e. dist[y] + length(x,y)> dist[x]. So the value of dist[x] would not have been updated even if y was considered as a path to x, thus we conclude that it makes sense to only consider neighbors of y which are still in Q (note comment in line16
)
But this thing hinges on our assumption of positive edge length, if length(u,v)<0 then depending on how negative that edge is we might replace the dist[x] after the comparison in line18
.
So any dist[x] calculation we make will be incorrect if x is removed before all vertices v - such that x is a neighbour of v with negative edge connecting them - is removed.
Because each of those v vertices is the second last vertex on a potential "better" path from source to x, which is discarded by Dijkstra’s algorithm.
So in the example I gave above, the mistake was because C was removed before B was removed. While that C was a neighbour of B with a negative edge!
Just to clarify, B and C are A's neighbours. B has a single neighbour C and C has no neighbours. length(a,b) is the edge length between the vertices a and b.
For a array of strings:
function removeDuplicatesFromArray(arr) {
const unique = {};
arr.forEach((word) => {
unique[word] = 1; // it doesn't really matter what goes here
});
return Object.keys(unique);
}
In my case I have a group of files which needs to be renamed before I can work with them. Each file has its own role in group and has its own pattern.
As result I have a list of rename commands like this:
f=`ls *canctn[0-9]*` ; mv $f CNLC.$f
f=`ls *acustb[0-9]*` ; mv $f CATB.$f
f=`ls *accusgtb[0-9]*` ; mv $f CATB.$f
f=`ls *acus[0-9]*` ; mv $f CAUS.$f
Try this also :
f=MyFileName; mv $f {pref1,pref2}$f{suf1,suf2}
This will produce all combinations with prefixes and suffixes:
pref1.MyFileName.suf1
...
pref2.MyFileName.suf2
Another way to solve same problem is to create mapping array and add corespondent prefix for each file type as shown below:
#!/bin/bash
unset masks
typeset -A masks
masks[ip[0-9]]=ip
masks[iaf_usg[0-9]]=ip_usg
masks[ipusg[0-9]]=ip_usg
...
for fileMask in ${!masks[*]};
do
registryEntry="${masks[$fileMask]}";
fileName=*${fileMask}*
[ -e ${fileName} ] && mv ${fileName} ${registryEntry}.${fileName}
done
Thankyou Frank.i got the idea. Here is the working code.
Option Explicit
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
If .Show = True Then
fileName = Dir(.SelectedItems(1))
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open (fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)
Next sheet
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
The Lazy way (which will cause future designers to curse your name and murder you in your sleep):
#myelement
{
display: none !important;
}
Disclaimer: I do not advocate this approach, but it certainly is the lazy way.
You should have a 'skeleton' somewhere in /etc
, probably /etc/skeleton
, or check the default settings, probably /etc/default
or something. Those are scripts that define standard environment variables getting set during a login.
If it is just for your own account: check the (hidden) file ~/.profile
and ~/.login
. Or generate them, if they don't exist. These are also evaluated by the login process.
Simple INNER JOIN VIEW code....
CREATE VIEW room_view
AS SELECT a.*,b.*
FROM j4_booking a INNER JOIN j4_scheduling b
on a.room_id = b.room_id;
$text="abc1234567890";
// truncate to 4 chars
echo substr(str_pad($text,4),0,4);
This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)
You can also do like this
select *
from table
where columnName like '%' + case when @varColumn is null then '' else @varColumn end + ' %'
important:
after any changes or new settings you must restart SQLSERVER
service. run services.msc
on Windows
Presumably you mean heap from a memory allocation point of view, not from a data structure point of view (the term has multiple meanings).
A very simple explanation is that the heap is the portion of memory where dynamically allocated memory resides (i.e. memory allocated via malloc
). Memory allocated from the heap will remain allocated until one of the following occurs:
free
'dIf all references to allocated memory are lost (e.g. you don't store a pointer to it anymore), you have what is called a memory leak. This is where the memory has still been allocated, but you have no easy way of accessing it anymore. Leaked memory cannot be reclaimed for future memory allocations, but when the program ends the memory will be free'd up by the operating system.
Contrast this with stack memory which is where local variables (those defined within a method) live. Memory allocated on the stack generally only lives until the function returns (there are some exceptions to this, e.g. static local variables).
You can find more information about the heap in this article.
Spark RDD (resilient distributed dataset)
:
RDD is the core data abstraction API and is available since very first release of Spark (Spark 1.0). It is a lower-level API for manipulating distributed collection of data. The RDD APIs exposes some extremely useful methods which can be used to get very tight control over underlying physical data structure. It is an immutable (read only) collection of partitioned data distributed on different machines. RDD enables in-memory computation on large clusters to speed up big data processing in a fault tolerant manner. To enable fault tolerance, RDD uses DAG (Directed Acyclic Graph) which consists of a set of vertices and edges. The vertices and edges in DAG represent the RDD and the operation to be applied on that RDD respectively. The transformations defined on RDD are lazy and executes only when an action is called
Spark DataFrame
:
Spark 1.3 introduced two new data abstraction APIs – DataFrame and DataSet. The DataFrame APIs organizes the data into named columns like a table in relational database. It enables programmers to define schema on a distributed collection of data. Each row in a DataFrame is of object type row. Like an SQL table, each column must have same number of rows in a DataFrame. In short, DataFrame is lazily evaluated plan which specifies the operations needs to be performed on the distributed collection of the data. DataFrame is also an immutable collection.
Spark DataSet
:
As an extension to the DataFrame APIs, Spark 1.3 also introduced DataSet APIs which provides strictly typed and object-oriented programming interface in Spark. It is immutable, type-safe collection of distributed data. Like DataFrame, DataSet APIs also uses Catalyst engine in order to enable execution optimization. DataSet is an extension to the DataFrame APIs.
Other Differences
-
Oracle provides a utility called tnsping
:
R:\>tnsping someconnection
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:38:07
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
TNS-03505: Failed to resolve name
R:\>
R:\>tnsping entpr01
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:39:22
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **)
(PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR0
1)))
OK (40 msec)
R:\>
This should show what file you're using. The utility sits in the Oracle bin
directory.
I think the even shorter answer that you'll like is: StringUtils.isBlank(acct);
From the documentation: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29
isBlank
public static boolean isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
Parameters:
str - the String to check, may be null
Returns:
true if the String is null, empty or whitespace
Regarding NSNotificationCenter Post above (sorry can't find out where to post a comment under it...)
In case some were getting the -[NSConcreteNotification allKeys] error of sorts. Change this:
-(void)didReceiveRemoteNotification:(NSDictionary *)userInfo
to this:
-(void)didReceiveRemoteNotification:(NSNotification*)notif {
NSDictionary *dict = notif.userInfo;
}
Some of the answers here are misleading because they concern containers that are running, not stopped.
Sven Dowideit explained on the Docker forum that containers are bound to their process (and Docker can't change the process of a stopped container, seemingly due at least to its internal structure: https://github.com/docker/docker/issues/1437). So, basically the only option is to commit
the container to an image and run
it with a different command.
See https://forums.docker.com/t/run-command-in-stopped-container/343
(I believe the "ENTRYPOINT
with arguments" approach wouldn't work either, since you still wouldn't be able to change the arguments to a stopped container.)
There are some gotchas. Assignment in Javascript is from right to left so when you write:
var moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
it effectively translates to:
var moveUp = (moveDown = (moveLeft = (moveRight = (mouseDown = (touchDown = false)))));
which effectively translates to:
var moveUp = (window.moveDown = (window.moveLeft = (window.moveRight = (window.mouseDown = (window.touchDown = false)))));
Inadvertently, you just created 5 global variables--something I'm pretty sure you didn't want to do.
Note: My above example assumes you are running your code in the browser, hence window
. If you were to be in a different environment these variables would attach to whatever the global context happens to be for that environment (i.e., in Node.js, it would attach to global
which is the global context for that environment).
Now you could first declare all your variables and then assign them to the same value and you could avoid the problem.
var moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown;
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
Long story short, both ways would work just fine, but the first way could potentially introduce some pernicious bugs in your code. Don't commit the sin of littering the global namespace with local variables if not absolutely necessary.
Sidenote: As pointed out in the comments (and this is not just in the case of this question), if the copied value in question was not a primitive value but instead an object, you better know about copy by value vs copy by reference. Whenever assigning objects, the reference to the object is copied instead of the actual object. All variables will still point to the same object so any change in one variable will be reflected in the other variables and will cause you a major headache if your intention was to copy the object values and not the reference.
As the answer by @plaul mentions TouchableOpacity
, here is an example of how you can use that;
<TouchableOpacity
style={someStyles}
onPress={doSomething}
>
<Text>Press Here</Text>
</TouchableOpacity>
This will capture requests for files like version
,
release
, and README.md
, etc. which should be
treated either as endpoints, if defined (as in the
case of /release), or as "not found."
You can do this way
@Html.HiddenFor(model=>model.title, new {ng_init = string.Format("model.title='{0}'", Model.title) })
Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.
brew switch libfoo mycopy
You can use brew switch
to switch between versions of the same package, if it's installed as versioned subdirectories under Cellar/<packagename>/
This will list versions installed ( for example I had Cellar/sdl2/2.0.3
, I've compiled into Cellar/sdl2/2.0.4
)
brew info sdl2
Then to switch between them
brew switch sdl2 2.0.4
brew info
Info now shows *
next to the 2.0.4
To install under Cellar/<packagename>/<version>
from source you can do for example
cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make
check where it gets installed with
make install -n
if all looks correct
make install
Then from cd $(brew --Cellar)
do the switch between version.
I'm using brew version 0.9.5
quite simple:
ul.yourlist li { float:left; }
or
ul.yourlist li { display:inline; }
if multiple (x) rows in Dim_Member are associated with a single row in Susp_Visits, there will be x rows in the resul set.
<div class="headerdivider"></div>
and
.headerdivider {
border-left: 1px solid #38546d;
background: #16222c;
width: 1px;
height: 80px;
position: absolute;
right: 250px;
top: 10px;
}
If the first item is to be used as a placeholder (empty value) and your select is required
then you can use the :invalid
pseudo-class to target it.
select {_x000D_
-webkit-appearance: menulist-button;_x000D_
color: black;_x000D_
}_x000D_
_x000D_
select:invalid {_x000D_
color: green;_x000D_
}
_x000D_
<select required>_x000D_
<option value="">Item1</option>_x000D_
<option value="Item2">Item2</option>_x000D_
<option value="Item3">Item3</option>_x000D_
</select>
_x000D_
In a broad sense, Socket - is just that, a socket, just like your electrical, cable or telephone socket. A point where "requisite stuff" (power, signal, information) can go out and come in from. It hides a lot of detailed stuff, which is not required for the use of the "requisite stuff". In software parlance, it provides a generic way of defining a mechanism of communication between two entities (those entities could be anything - two applications, two physically separate devices, User & Kernel space within an OS, etc)
A Port is an endpoint discriminator. It differentiates one endpoint from another. At networking level, it differentiates one application from another, so that the networking stack can pass on information to the appropriate application.
uncompress the zip HibernateTools-3.2.4.Beta1-R20081031133 later in eclipse --> menu Help -> Update Sofwate -> add site -> local add, and select de folder uncompress an install automatic
two-bit-fool's excellent answer provides all the background, but let me attempt a concise, pragmatic summary of how to handle orientation changes across iOS and Android:
resize
event only.window.innerWidth
and window.InnerHeight
only.window.orientation
- it won't be current on iOS. resize
event on Android, and only the orientationchange
event on iOS.window.orientation
(and window.innerWidth
and window.InnerHeight
)These approaches offer slight benefits over remembering the previous orientation and comparing:
window.orientation
is not available on desktop browsers).Just complementing the answer.
Merging the last tag on a branch:
git checkout my-branch
git merge $(git describe --tags $(git rev-list --tags --max-count=1))
Inspired by https://gist.github.com/rponte/fdc0724dd984088606b0
You should use IS NOT NULL
. (The comparison operators =
and <>
both give UNKNOWN
with NULL
on either side of the expression.)
SELECT *
FROM table
WHERE YourColumn IS NOT NULL;
Just for completeness I'll mention that in MySQL you can also negate the null safe equality operator but this is not standard SQL.
SELECT *
FROM table
WHERE NOT (YourColumn <=> NULL);
Edited to reflect comments. It sounds like your table may not be in first normal form in which case changing the structure may make your task easier. A couple of other ways of doing it though...
SELECT val1 AS val
FROM your_table
WHERE val1 IS NOT NULL
UNION ALL
SELECT val2
FROM your_table
WHERE val2 IS NOT NULL
/*And so on for all your columns*/
The disadvantage of the above is that it scans the table multiple times once for each column. That may possibly be avoided by the below but I haven't tested this in MySQL.
SELECT CASE idx
WHEN 1 THEN val1
WHEN 2 THEN val2
END AS val
FROM your_table
/*CROSS JOIN*/
JOIN (SELECT 1 AS idx
UNION ALL
SELECT 2) t
HAVING val IS NOT NULL /*Can reference alias in Having in MySQL*/
Another way to get this error is by accidentally writing the definition of something in an anonymous namespace:
foo.h:
namespace foo {
void bar();
}
foo.cc:
namespace foo {
namespace { // wrong
void bar() { cout << "hello"; };
}
}
other.cc file:
#include "foo.h"
void baz() {
foo::bar();
}
As others have also mentioned, this can be readily solved by adding the following to the onCreate() of the Activity:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.primary_dark));
}
However, the important point I want to add here is that in some cases, even the above does not change the status bar color. For example, when using MikePenz library for Navigation Drawer, it implicityly overrides the status bar color, so that you need to manually add the following for it to work:
.withStatusBarColorRes(R.color.status_bar_color)
aapt dump badging test.apk | grep "VersionName" | sed -e "s/.*versionName='//" -e "s/' .*//"
This answers the question by returning only the version number as a result. However......
The goal as previously stated should be to find out if the apk on the server is newer than the one installed BEFORE attempting to download or install it. The easiest way to do this is include the version number in the filename of the apk hosted on the server eg myapp_1.01.apk
You will need to establish the name and version number of the apps already installed (if it is installed) in order to make the comparison. You will need a rooted device or a means of installing the aapt binary and busybox if they are not already included in the rom.
This script will get the list of apps from your server and compare with any installed apps. The result is a list flagged for upgrade/installation.
#/system/bin/sh
SERVER_LIST=$(wget -qO- "http://demo.server.com/apk/" | grep 'href' | grep '\.apk' | sed 's/.*href="//' | \
sed 's/".*//' | grep -v '\/' | sed -E "s/%/\\\\x/g" | sed -e "s/x20/ /g" -e "s/\\\\//g")
LOCAL_LIST=$(for APP in $(pm list packages -f | sed -e 's/package://' -e 's/=.*//' | sort -u); do \
INFO=$(echo -n $(aapt dump badging $APP | grep -e 'package: name=' -e 'application: label=')) 2>/dev/null; \
PACKAGE=$(echo $INFO | sed "s/.*package: name='//" | sed "s/'.*$//"); \
LABEL=$(echo $INFO | sed "s/.*application: label='//" | sed "s/'.*$//"); if [ -z "$LABEL" ]; then LABEL="$PACKAGE"; fi; \
VERSION=$(echo $INFO | sed -e "s/.*versionName='//" -e "s/' .*//"); \
NAME=$LABEL"_"$VERSION".apk"; echo "$NAME"; \
done;)
OFS=$IFS; IFS=$'\t\n'
for REMOTE in $SERVER_LIST; do
INSTALLED=0
REMOTE_NAME=$(echo $REMOTE | sed 's/_.*//'); REMOTE_VER=$(echo $REMOTE | sed 's/^[^_]*_//g' | sed 's/[^0-9]*//g')
for LOCAL in $LOCAL_LIST; do
LOCAL_NAME=$(echo $LOCAL | sed 's/_.*//'); LOCAL_VER=$(echo $LOCAL | sed 's/^[^_]*_//g' | sed 's/[^0-9]*//g')
if [ "$REMOTE_NAME" == "$LOCAL_NAME" ]; then INSTALLED=1; fi
if [ "$REMOTE_NAME" == "$LOCAL_NAME" ] && [ ! "$REMOTE_VER" == "$LOCAL_VER" ]; then echo remote=$REMOTE ver=$REMOTE_VER local=$LOCAL ver=$LOCAL_VER; fi
done
if [ "$INSTALLED" == "0" ]; then echo "$REMOTE"; fi
done
IFS=$OFS
As somebody asked how to do it without using aapt. It is also possible to extract apk info with apktool and a bit of scripting. This way is slower and not simple in android but will work on windows/mac or linux as long as you have working apktool setup.
#!/bin/sh
APK=/path/to/your.apk
TMPDIR=/tmp/apktool
rm -f -R $TMPDIR
apktool d -q -f -s --force-manifest -o $TMPDIR $APK
APK=$(basename $APK)
VERSION=$(cat $TMPDIR/apktool.yml | grep "versionName" | sed -e "s/versionName: //")
LABEL=$(cat $TMPDIR/res/values/strings.xml | grep 'string name="title"' | sed -e 's/.*">//' -e 's/<.*//')
rm -f -R $TMPDIR
echo ${LABEL}_$(echo $V).apk
Also consider a drop folder on your server. Upload apks to it and a cron task renames and moves them to your update folder.
#!/bin/sh
# Drop Folder script for renaming APKs
# Read apk file from SRC folder and move it to TGT folder while changing filename to APKLABEL_APKVERSION.apk
# If an existing version of the APK exists in the target folder then script will remove it
# Define METHOD as "aapt" or "apktool" depending upon what is available on server
# Variables
METHOD="aapt"
SRC="/home/user/public_html/dropfolders/apk"
TGT="/home/user/public_html/apk"
if [ -d "$SRC" ];then mkdir -p $SRC
if [ -d "$TGT" ]then mkdir -p $TGT
# Functions
get_apk_filename () {
if [ "$1" = "" ]; then return 1; fi
local A="$1"
case $METHOD in
"apktool")
local D=/tmp/apktool
rm -f -R $D
apktool d -q -f -s --force-manifest -o $D $A
local A=$(basename $A)
local V=$(cat $D/apktool.yml | grep "versionName" | sed -e "s/versionName: //")
local T=$(cat $D/res/values/strings.xml | grep 'string name="title"' | sed -e 's/.*">//' -e 's/<.*//')
rm -f -R $D<commands>
;;
"aapt")
local A=$(aapt dump badging $A | grep -e "application-label:" -e "VersionName")
local V=$(echo $A | sed -e "s/.*versionName='//" -e "s/' .*//")
local T=$(echo $A | sed -e "s/.*application-label:'//" -e "s/'.*//")
;;
esac
echo ${T}_$(echo $V).apk
}
# Begin script
for APK in $(ls "$SRC"/*.apk); do
APKNAME=$(get_apk_filename "$APK")
rm -f $TGT/$(echo APKNAME | sed "s/_.*//")_*.apk
mv "$APK" "$TGT"/$APKNAME
done
If you are running multiple extensions that perform ad or script blocking you will need to
individually update each one to your whitelist
Taking from this source, here are some of the extensions that may cause the case and how to deal with them.
Adblock Plus
Firefox Tracking Protection
In Firefox “Tracking Protection” may activate our adblock notice. It can be temporarily disabled for a browsing session by clicking the “shield” icon in the url bar if visible and following the instructions.
For further details on Tracking Protection please review Mozilla’s support.
Adblock
Ghostery
uBlock / uBlock Origin
Click the uBlock / uBlock Origin icon.
Click the “power” button in the menu that appears to whitelist the current web site.
Click the reload icon to reload the page you were viewing.
Disconnect
Kaspersky Ant-Banner
Please review How to configure Anti-Banner in Kaspersky Total Security for information on how to whitelist with Kaspersky Total Security.
if it is not the first two chars and you wanna remove F0 from the whole string then you gotta use this regex
let string = 'F0123F0456F0';_x000D_
let result = string.replace(/F0/ig, '');_x000D_
console.log(result);
_x000D_
export PATH=/usr/pgsql-9.2/bin:$PATH
The program executable psql
is in the directory /usr/pgsql-9.2/bin
, and that directory is not included in the path by default, so we have to tell our shell (terminal) program where to find psql
. When most packages are installed, they are added to an existing path, such as /usr/local/bin
, but not this program.
So we have to add the program's path to the shell PATH variable if we do not want to have to type the complete path to the program every time we execute it.
This line should typically be added to theshell startup script, which for the bash shell will be in the file ~/.bashrc
.
You need to call the Value property of the nullable DateTime. This will return a DateTime.
Assuming that UpdatedDate
is DateTime?
, then this should work:
DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null ? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;
To make the code a bit easier to read, you could use the HasValue property instead of the null
check:
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue
? _objHotelPackageOrder.UpdatedDate.Value
: DateTime.Now;
This can be then made even more concise:
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;
I got this problem on Android studio, there in either sync or build square were this link like blue text about this issue, press that button and it download something that fix this problem
To find all the links, we will in this example use the urllib2 module together with the re.module *One of the most powerful function in the re module is "re.findall()". While re.search() is used to find the first match for a pattern, re.findall() finds all the matches and returns them as a list of strings, with each string representing one match*
import urllib2
import re
#connect to a URL
website = urllib2.urlopen(url)
#read html code
html = website.read()
#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)
print links
Using ES6 you can just make component wrappers inline:
<Route path="/" component={() => <App myProp={someValue}/>} >
If you need to pass children:
<Route path="/" component={(props) => <App myProp={someValue}>{props.children}</App>} >
Try a generic:
public static T CastTo<T>(this dynamic obj, bool safeCast) where T:class
{
try
{
return (T)obj;
}
catch
{
if(safeCast) return null;
else throw;
}
}
This is in extension method format, so its usage would be as if it were a member of dynamic objects:
dynamic myDynamic = new Something();
var typedObject = myDynamic.CastTo<Something>(false);
EDIT: Grr, didn't see that. Yes, you could reflectively close the generic, and it wouldn't be hard to hide in a non-generic extension method:
public static dynamic DynamicCastTo(this dynamic obj, Type castTo, bool safeCast)
{
MethodInfo castMethod = this.GetType().GetMethod("CastTo").MakeGenericMethod(castTo);
return castMethod.Invoke(null, new object[] { obj, safeCast });
}
I'm just not sure what you'd get out of this. Basically you're taking a dynamic, forcing a cast to a reflected type, then stuffing it back in a dynamic. Maybe you're right, I shouldn't ask. But, this'll probably do what you want. Basically when you go into dynamic-land, you lose the need to perform most casting operations as you can discover what an object is and does through reflective methods or trial and error, so there aren't many elegant ways to do this.
firstly you need to import the Select class and then you need to create the instance of Select class. After creating the instance of Select class, you can perform select methods on that instance to select the options from dropdown list. Here is the code
from selenium.webdriver.support.select import Select
select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)
Thanks to @jarno I know about the -z option and I found out that when using GNU grep with the -P option, matching against \n
is possible. :)
Example:
grep -zoP 'foo\n\K.*'<<<$'foo\nbar'
Prints bar
API Sanity Checker — test framework for C/C++ libraries:
An automatic generator of basic unit tests for a shared C/C++ library. It is able to generate reasonable (in most, but unfortunately not all, cases) input data for parameters and compose simple ("sanity" or "shallow"-quality) test cases for every function in the API through the analysis of declarations in header files.
The quality of generated tests allows to check absence of critical errors in simple use cases. The tool is able to build and execute generated tests and detect crashes (segfaults), aborts, all kinds of emitted signals, non-zero program return code and program hanging.
Unique features in comparison with CppUnit, Boost and Google Test:
Very simple, no library required:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
or you might prefer:
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
Some browsers will treat two digit years as being in the 20th century, so that:
new Date(14, 0, 1);
gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:
var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14
for 14.04.1-Ubuntu https://wkhtmltopdf.org/downloads.html
wget https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz -O mktemp.tar.xz
tar xf mktemp.tar.xz
sudo cp wkhtmltox/bin/wkhtmltopdf /usr/bin/wkhtmltopdf
sudo chmod +x /usr/bin/wkhtmltopdf
rm mktemp.tar.xz
rm wkhtmltox -rf
apt-get update
apt-get install -y libxrender1 libxtst6 libxi6
wkhtmltopdf http://www.google.com test.pdf
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
Firewalld is a bit non-intuitive for the iptables veteran. For those who prefer an iptables-driven firewall with iptables-like syntax in an easy configurable tree, try replacing firewalld with fwtree: https://www.linuxglobal.com/fwtree-flexible-linux-tree-based-firewall/ and then do the following:
echo '-p tcp --dport 80 -m conntrack --cstate NEW -j ACCEPT' > /etc/fwtree.d/filter/INPUT/80-allow.rule
systemctl reload fwtree
There are several approaches:
You can normally see assembly code while debugging C++ in visual studio (and eclipse too). For this in Visual Studio put a breakpoint on code in question and when debugger hits it rigth click and find "Go To Assembly" ( or press CTRL+ALT+D )
Second approach is to generate assembly listings while compiling. For this go to project settings -> C/C++ -> Output Files -> ASM List Location and fill in file name. Also select "Assembly Output" to "Assembly With Source Code".
Compile the program and use any third-party debugger. You can use OllyDbg or WinDbg for this. Also you can use IDA (interactive disassembler). But this is hardcore way of doing it.
Sometimes your SVG will be inlined by React so you need quotes around it:
backgroundImage: `url("${Background}")`
otherwise it's invalid CSS and the browser dev tools will not show that you've set background-image at all.
non-managed pom.xml file found
, if you click on it a new pop up will come, saying add as maven project
, click on it, and done.For dynamic values!
<div class="col-md-4" ng-repeat="(k, v) in tiposAcesso">
<label class="control-label">
<input type="radio" name="tipoAcesso" ng-model="userLogin.tipoAcesso" value="{{k}}" ng-change="changeTipoAcesso(k)" />
<span ng-bind="v"></span>
</label>
</div>
in controller
$scope.changeTipoAcesso = function(value) {
console.log(value);
};