It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/
is the same as /../
, and that will get normalized away.
(This is a combination of an answer by bobince and a comment by slowpoison.)
FTL stands for FreeMarker Template.
It is very useful when you want to follow the MVC (Model View Controller) pattern.
The idea behind using the MVC pattern for dynamic Web pages is that you separate the designers (HTML authors) from the programmers.
FYI, it looks like the syntax for retrieving the values has changed according to:
http://freemarker.sourceforge.net/docs/ref_builtins_hash.html
<#assign h = {"name":"mouse", "price":50}>
<#assign keys = h?keys>
<#list keys as key>${key} = ${h[key]}; </#list>
To check if the value exists:
[#if userName??]
Hi ${userName}, How are you?
[/#if]
Or with the standard freemarker syntax:
<#if userName??>
Hi ${userName}, How are you?
</#if>
To check if the value exists and is not empty:
<#if userName?has_content>
Hi ${userName}, How are you?
</#if>
Use ??
operator at the end of your <#if>
statement.
This example demonstrates how to handle null
values for two lists in a Freemaker template.
List of cars:
<#if cars??>
<#list cars as car>${car.owner};</#list>
</#if>
List of motocycles:
<#if motocycles??>
<#list motocycles as motocycle>${motocycle.owner};</#list>
</#if>
You need to subscribe to a SMS gateway. There are thousands of those (try searching with google) and they are usually not free. For example this one has support for PHP.
Simply casting the string as an int
won't work reliably. You need to convert it to an int32
. For this you can use the .NET convert
class and its ToInt32
method. The method requires a string
($strNum
) as the main input, and the base number
(10
) for the number system to convert to. This is because you can not only convert to the decimal system (the 10
base number), but also to, for example, the binary system (base 2).
Give this method a try:
[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)
$intNum
Use an object as a switch variable.
You can do this inline quite simply with:
<ul class="nav navbar-nav">
<li ng-class="{'active':switch.linkOne}" ng-click="switch = {linkOne: true}"><a href="/">Link One</a></li>
<li ng-class="{'active':switch.linkTwo}" ng-click="switch = {link-two: true}"><a href="/link-two">Link Two</a></li>
</ul>
Each time you click on a link the switch object is replaced by a new object where only the correct switch object property is true. The undefined properties will evaluate as false and so the elements which depend on them will not have the active class assigned.
marshaller.setProperty
only works on the JAX-B marshaller from Sun. The question was regarding the JAX-B marshaller from SpringSource
, which does not support setProperty
.
By far the best solution is the OSX Eclipse Launcher presented in http://torkild.resheim.no/2012/08/opening-multiple-eclipse-instances-on.html It can be downloaded in the Marketplace http://marketplace.eclipse.org/content/osx-eclipse-launcher#.UGWfRRjCaHk
I use it everyday and like it very much! To demonstrate the simplicity of usage just take a look at the following image:
And if you need to do it on items that match a specific condition...
double total = myList.Where(item => item.Name == "Eggs").Sum(item => item.Amount);
From MySQL 5.7 Reference Manual.
Syntax :
ALTER TABLE t1 CHANGE a b DATATYPE;
e.g. : for Customer TABLE having COLUMN customer_name, customer_street, customercity.
And we want to change customercity TO customer_city :
alter table customer change customercity customer_city VARCHAR(225);
Another possibility is to use bit sets, for which there is at least one package or you can use the built-in big package. In this case, basically you need to define a way to convert your object to an index.
I have modified the answer which @Christian Del Bianco is given. I changed the process for .net core 2 and upper as project.json file now absolute.
First, create appsettings.json file in root directory. with the content
{
// Possible string values reported below. When empty it use ENV
variable value or Visual Studio setting.
// - Production
// - Staging
// - Test
// - Development
"ASPNETCORE_ENVIRONMENT": "Development"
}
Then create another two setting file appsettings.Development.json and appsettings.Production.json with the necessary configuration.
Add necessary code to set up the environment to Program.cs file.
public class Program
{
public static void Main(string[] args)
{
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
***var currentDirectoryPath = Directory.GetCurrentDirectory();
var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();***
try
{
***CreateWebHostBuilder(args, enviromentValue).Build().Run();***
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "Stopped program because of setup related exception");
throw;
}
finally
{
NLog.LogManager.Shutdown();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args, string enviromentValue) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog()
***.UseEnvironment(enviromentValue);***
}
Add the envsettings.json to your .csproj file for copy to published directory.
<ItemGroup>
<None Include="envsettings.json" CopyToPublishDirectory="Always" />
</ItemGroup>
Now just change the ASPNETCORE_ENVIRONMENT as you want in envsettings.json file and published.
CSS3 introduced flexible boxes (aka. flex box) which can also achieve this behavior.
Simply define the width of the first div, and then give the second a flex-grow
value of 1
which will allow it to fill the remaining width of the parent.
.container{
display: flex;
}
.fixed{
width: 200px;
}
.flex-item{
flex-grow: 1;
}
<div class="container">
<div class="fixed"></div>
<div class="flex-item"></div>
</div>
Demo:
div {
color: #fff;
font-family: Tahoma, Verdana, Segoe, sans-serif;
padding: 10px;
}
.container {
background-color:#2E4272;
display:flex;
}
.fixed {
background-color:#4F628E;
width: 200px;
}
.flex-item {
background-color:#7887AB;
flex-grow: 1;
}
_x000D_
<div class="container">
<div class="fixed">Fixed width</div>
<div class="flex-item">Dynamically sized content</div>
</div>
_x000D_
Note that flex boxes are not backwards compatible with old browsers, but is a great option for targeting modern browsers (see also Caniuse and MDN). A great comprehensive guide on how to use flex boxes is available on CSS Tricks.
You can do it in 1 line, by using Linq
listBox1.Cast<ListItem>().Where(p=>p.Text.Contains("OBJECT")).ToList().ForEach(listBox1.Items.Remove);
In my case, cleaning and rebuilding the project resolved the problem.
[JAVA 8]
import java.util.Base64;
String dummy= "dummy string";
byte[] byteArray = dummy.getBytes();
byte[] salt = new byte[]{ -47, 1, 16, ... }
String encoded = Base64.getEncoder().encodeToString(salt);
Include required imports and you can make ur decision in handleError method Error status will give the error code
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError} from "rxjs/index";
import { catchError, retry } from 'rxjs/operators';
import {ApiResponse} from "../model/api.response";
import { TaxType } from '../model/taxtype.model';
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
getTaxTypes() : Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.baseUrl).pipe(
catchError(this.handleError)
);
}
From the official nodejs.org documentation:
process.exit(code)
Ends the process with the specified code. If omitted, exit uses the 'success' code 0.
To exit with a 'failure' code:
process.exit(1);
In case anyone still has to support legacy fancybox with jQuery 3.0+ here are some other changes you'll have to make:
.unbind() deprecated
Replace all instances of .unbind
with .off
.removeAttribute() is not a function
Change lines 580-581 to use jQuery's .removeAttr()
instead:
Old code:
580: content[0].style.removeAttribute('filter');
581: wrap[0].style.removeAttribute('filter');
New code:
580: content.removeAttr('filter');
581: wrap.removeAttr('filter');
This combined with the other patch mentioned above solved my compatibility issues.
You should use this command to set the global installation flocation of npm packages
(git bash) npm config --global set prefix </path/you/want/to/use>/npm
(cmd/git-cmd) npm config --global set prefix <drive:\path\you\want\to\use>\npm
You may also consider the npm-cache
location right next to it. (as would be in a normal nodejs installation on windows)
(git bash) npm config --global set cache </path/you/want/to/use>/npm-cache
(cmd/git-cmd) npm config --global set cache <drive:\path\you\want\to\use>\npm-cache
Even in mongo version 4 there is no way to export all collections at once. Export the specified collection to the specified output file from a local MongoDB instance running on port 27017 you can do with the following command:
.\mongoexport.exe --db=xstaging --collection=products --out=c:/xstaging.products.json
If you want to set in imageview an image that is inside the mipmap dirs you can do it like this:
myImageView.setImageDrawable(getResources().getDrawable(R.mipmap.my_picture)
I know this is an older thread but I wanted to give what I think to be helpful information.
I personally use PyPy which is really easy to install using pip. I interchangeably use Python/PyPy interpreter, you don't need to change your code at all and I've found it to be roughly 40x faster than the standard python interpreter (Either Python 2x or 3x). I use pyCharm Community Edition to manage my code and I love it.
I like writing code in python as I think it lets you focus more on the task than the language, which is a huge plus for me. And if you need it to be even faster, you can always compile to a binary for Windows, Linux, or Mac (not straight forward but possible with other tools). From my experience, I get about 3.5x speedup over PyPy when compiling, meaning 140x faster than python. PyPy is available for Python 3x and 2x code and again if you use an IDE like PyCharm you can interchange between say PyPy, Cython, and Python very easily (takes a little of initial learning and setup though).
Some people may argue with me on this one, but I find PyPy to be faster than Cython. But they're both great choices though.
Edit: I'd like to make another quick note about compiling: when you compile, the resulting binary is much bigger than your python script as it builds all dependencies into it, etc. But then you get a few distinct benefits: speed!, now the app will work on any machine (depending on which OS you compiled for, if not all. lol) without Python or libraries, it also obfuscates your code and is technically 'production' ready (to a degree). Some compilers also generate C code, which I haven't really looked at or seen if it's useful or just gibberish. Good luck.
Hope that helps.
For WSL2, I had to install cgroupfs-mount, than start the daemon, as described here:
sudo apt-get install cgroupfs-mount
sudo cgroupfs-mount
sudo service docker start
For MySQL 5.0.3 and higher, you can use BIT
. The manual says:
As of MySQL 5.0.3, the BIT data type is used to store bit-field values. A type of BIT(M) enables storage of M-bit values. M can range from 1 to 64.
Otherwise, according to the MySQL manual you can use BOOL
or BOOLEAN
, which are at the moment aliases of tinyint(1):
Bool, Boolean: These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.
MySQL also states that:
We intend to implement full boolean type handling, in accordance with standard SQL, in a future MySQL release.
References: http://dev.mysql.com/doc/refman/5.5/en/numeric-type-overview.html
If you want to do it from the command line and not built into the script itself, use:
.\myscript.ps1 | Out-File c:\output.csv
If else condition, also called alternatives in UML terms can indeed be represented in sequence diagrams. Here is a link where you can find some nice resources on the subject http://www.ibm.com/developerworks/rational/library/3101.html
From ES2016 you can also use slightly better / easier / more elegant method (case-sensitive):
if (referrer.includes("Ral")) { ... }
or (case-insensitive):
if (referrer.toLowerCase().includes(someString.toLowerCase())) { ... }
Here is some comparison of .indexOf()
and .includes()
:
https://dev.to/adroitcoder/includes-vs-indexof-in-javascript
.live()
is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax
$(document).on('click', "a.tabclick", function() {
This syntax will work for delegated events
Smart solution in Django 2.0.3 for keeping templates in project directory (/root/templates/app_name
):
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMP_DIR = os.path.join(BASE_DIR, 'templates')
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMP_DIR],
...
in views.py just add such template path:
app_name/html_name
Solution with awk:
awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file
Simply: if the row starts with all
print the row plus "anotherthing", else print just the row.
Another solution (but it requires jQueryUI as pointed out by Richard Neil Ilagan in comments) :-
addClass, removeClass and toggleClass also accepts a second argument; the time duration to go from one state to the other.
$(this).addClass('abc',1000);
See jsfiddle:- http://jsfiddle.net/6hvZT/1/
You can use below code for h2 and MySQl
@Query(value = "SELECT req.CREATED_AT createdAt, req.CREATED_BY createdBy,req.APP_ID appId,req.NOTE_ID noteId,req.MODEL model FROM SUMBITED_REQUESTS req inner join NOTE note where req.NOTE_ID=note.ID and note.CREATED_BY= :userId "
,
countQuery = "SELECT count(*) FROM SUMBITED_REQUESTS req inner join NOTE note WHERE req.NOTE_ID=note.ID and note.CREATED_BY=:userId",
nativeQuery = true)
Page<UserRequestsDataMapper> getAllRequestForCreator(@Param("userId") String userId,Pageable pageable);
You check if it's null
in C# like this:
if(MyObject != null) {
//do something
}
If you want to check against default (tough to understand the question on the info given) check:
if(MyObject != default(MyObject)) {
//do something
}
Here's pure javascript example of handling classes during scrolling.
You'd probably want to throttle handling scroll events, more so as handler logic gets more complex, in that case throttle
from lodash
lib comes in handy.
And if you're doing spa, keep in mind that you need to clear event listeners with removeEventListener
once they're not needed (eg during onDestroy
lifecycle hook of your component, like destroyed()
for Vue, or maybe return function of useEffect
hook for React).
const navbar = document.getElementById('navbar')_x000D_
_x000D_
// OnScroll event handler_x000D_
const onScroll = () => {_x000D_
_x000D_
// Get scroll value_x000D_
const scroll = document.documentElement.scrollTop_x000D_
_x000D_
// If scroll value is more than 0 - add class_x000D_
if (scroll > 0) {_x000D_
navbar.classList.add("scrolled");_x000D_
} else {_x000D_
navbar.classList.remove("scrolled")_x000D_
}_x000D_
}_x000D_
_x000D_
// Optional - throttling onScroll handler at 100ms with lodash_x000D_
const throttledOnScroll = _.throttle(onScroll, 100, {})_x000D_
_x000D_
// Use either onScroll or throttledOnScroll_x000D_
window.addEventListener('scroll', onScroll)
_x000D_
#navbar {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
width: 100%;_x000D_
height: 60px;_x000D_
background-color: #89d0f7;_x000D_
box-shadow: 0px 5px 0px rgba(0, 0, 0, 0);_x000D_
transition: box-shadow 500ms;_x000D_
}_x000D_
_x000D_
#navbar.scrolled {_x000D_
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);_x000D_
}_x000D_
_x000D_
#content {_x000D_
height: 3000px;_x000D_
margin-top: 60px;_x000D_
}
_x000D_
<!-- Optional - lodash library, used for throttlin onScroll handler-->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>_x000D_
<header id="navbar"></header>_x000D_
<div id="content"></div>
_x000D_
Blat:
blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body"
You can also check for bootstrap datatable plugin as well for above issue.
It will have a large column table scrollable feature with lot of other options
$(document).ready(function() {
$('#example').dataTable( {
"scrollX": true
} );
} );
for more info with example please check out this link
Marco Pellicciotta: The position of the element inside another element can be relative or absolute, about the element it's inside.
If you need to position the element in the browser window point of view it's best to use position:fixed
mkdirs()
will create the specified directory path in its entirety where mkdir()
will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.
In other words mkdir()
is like mkdir
and mkdirs()
is like mkdir -p
.
For example, imagine we have an empty /tmp
directory. The following code
new File("/tmp/one/two/three").mkdirs();
would create the following directories:
/tmp/one
/tmp/one/two
/tmp/one/two/three
Where this code:
new File("/tmp/one/two/three").mkdir();
would not create any directories - as it wouldn't find /tmp/one/two
- and would return false
.
The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.
If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.
On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).
Please check the access to drives.First create one folder and go to folder properties ,
You may find the security tab ,click on that check whether your user id having the access or not.
if couldn't find the your id,please click the add buttion and give user name with full access.
Given that they're simply fonts, then you should be able to style them as fonts:
#elementID {
color: #fff;
text-shadow: 1px 1px 1px #ccc;
font-size: 1.5em;
}
You can do:
$("#submittername").text("testing");
or
$("#submittername").html("testing <b>1 2 3</b>");
I believe there are two main reasons for trying to seperate templated code into a header and a cpp:
One is for mere elegance. We all like to write code that is wasy to read, manage and is reusable later.
Other is reduction of compilation times.
I am currently (as always) coding simulation software in conjuction with OpenCL and we like to keep code so it can be run using float (cl_float) or double (cl_double) types as needed depending on HW capability. Right now this is done using a #define REAL at the beginning of the code, but this is not very elegant. Changing desired precision requires recompiling the application. Since there are no real run-time types, we have to live with this for the time being. Luckily OpenCL kernels are compiled runtime, and a simple sizeof(REAL) allows us to alter the kernel code runtime accordingly.
The much bigger problem is that even though the application is modular, when developing auxiliary classes (such as those that pre-calculate simulation constants) also have to be templated. These classes all appear at least once on the top of the class dependency tree, as the final template class Simulation will have an instance of one of these factory classes, meaning that practically every time I make a minor change to the factory class, the entire software has to be rebuilt. This is very annoying, but I cannot seem to find a better solution.
DELETE FROM table WHERE date < '2011-09-21 08:21:22';
Functional Approach for ES6+
If you want to take a more functional approach to iterating over the Map
object, you can do something like this
const myMap = new Map()
myMap.forEach((value, key) => {
console.log(value, key)
})
You could first build a list of keys to delete, and then iterate over that list deleting them.
dict = {'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4}
delete = []
for k,v in dict.items():
if v%2 == 1:
delete.append(k)
for i in delete:
del dict[i]
I have figured out a solution to this problem. We can build a Function or View with "rendered" sql in a stored procedure that can then be executed as normal.
1.Create another sproc
CREATE PROCEDURE [dbo].[usp_FunctionBuilder]
DECLARE @outerSql VARCHAR(MAX)
DECLARE @innerSql VARCHAR(MAX)
2.Build the dynamic sql that you want to execute in your function (Example: you could use a loop and union, you could read in another sproc, use if statements and parameters for conditional sql, etc.)
SET @innerSql = 'your sql'
3.Wrap the @innerSql in a create function statement and define any external parameters that you have used in the @innerSql so they can be passed into the generated function.
SET @outerSql = 'CREATE FUNCTION [dbo].[fn_GeneratedFunction] ( @Param varchar(10))
RETURNS TABLE
AS
RETURN
' + @innerSql;
EXEC(@outerSql)
This is just pseudocode but the solution solves many problems such as linked server limitations, parameters, dynamic sql in function, dynamic server/database/table name, loops, etc.
You will need to tweak it to your needs, (Example: changing the return in the function)
You can easily auto-generate the C# code using: http://regexhero.net/tester/.
Its free.
Here is how I did it:
The website then auto-generates the .NET code:
string strRegex = @"\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @" {CD73FAD2-E226-4715-B6FA-14EDF0764162}.Debug|x64.ActiveCfg = Debug|x64";
string strReplace = @"""$0""";
return myRegex.Replace(strTargetString, strReplace);
When is it ok to use READ UNCOMMITTED
?
Good: Big aggregate reports showing constantly changing totals.
Risky: Nearly everything else.
The good news is that the majority of read-only reports fall in that Good category.
Ok to use it:
That covers probably the majority of what an Business Intelligence department would do in, say, SSRS. The exception of course, is anything with $ signs in front of it. Many people account for money with much more zeal than applied to the related core metrics required to service the customer and generate that money. (I blame accountants).
When risky
Any report that goes down to the detail level. If that detail is required it usually implies that every row will be relevant to a decision. In fact, if you can't pull a small subset without blocking it might be for the good reason that it's being currently edited.
Historical data. It rarely makes a practical difference but whereas users understand constantly changing data can't be perfect, they don't feel the same about static data. Dirty reads won't hurt here but double reads can occasionally be. Seeing as you shouldn't have blocks on static data anyway, why risk it?
Nearly anything that feeds an application which also has write capabilities.
When even the OK scenario is not OK.
NOLOCK
on those tables for anything.amap.find
returns amap::end
when it does not find what you're looking for -- you're supposed to check for that.
I tried to implement the result of Nick which is:
$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');
But that didn't work for me because i had multiple dialogs on 1 page. In such a situation it will only set the title correct the first time. Trying to staple commands did not work:
$("#modal_popup").html(data);
$("#modal_popup").dialog('option', 'title', 'My New Title');
$("#modal_popup").dialog({ width: 950, height: 550);
I fixed this by adding the title to the javascript function arguments of each dialog on the page:
function show_popup1() {
$("#modal_popup").html(data);
$("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my First Dialog'});
}
function show_popup2() {
$("#modal_popup").html(data);
$("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my Other Dialog'});
}
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
Using inline handlers is incompatible with Content Security Policy so the addEventListener
approach is more secure from that point of view. Of course you can enable the inline handlers with unsafe-inline
but, as the name suggests, it's not safe as it brings back the whole hordes of JavaScript exploits that CSP prevents.
In general, a condition in the WHERE
clause of an SQL query can reference only a single row. The context of a WHERE
clause is evaluated before any order has been defined by an ORDER BY
clause, and there is no implicit order to an RDBMS table.
You can use a derived table to join each row to the group of rows with a lesser id
value, and produce the sum of each sum group. Then test where the sum meets your criterion.
CREATE TABLE MyTable ( id INT PRIMARY KEY, cash INT );
INSERT INTO MyTable (id, cash) VALUES
(1, 200), (2, 301), (3, 101), (4, 700);
SELECT s.*
FROM (
SELECT t.id, SUM(prev.cash) AS cash_sum
FROM MyTable t JOIN MyTable prev ON (t.id > prev.id)
GROUP BY t.id) AS s
WHERE s.cash_sum >= 500
ORDER BY s.id
LIMIT 1;
Output:
+----+----------+
| id | cash_sum |
+----+----------+
| 3 | 501 |
+----+----------+
Swift 4 and above : Data Request using URLSession API
//create the url with NSURL
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
let request = URLRequest(url: url)
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
Swift 4 and above, Decodable and Result enum
//APPError enum which shows all possible errors
enum APPError: Error {
case networkError(Error)
case dataNotFound
case jsonParsingError(Error)
case invalidStatusCode(Int)
}
//Result enum to show success or failure
enum Result<T> {
case success(T)
case failure(APPError)
}
//dataRequest which sends request to given URL and convert to Decodable Object
func dataRequest<T: Decodable>(with url: String, objectType: T.Type, completion: @escaping (Result<T>) -> Void) {
//create the url with NSURL
let dataURL = URL(string: url)! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
let request = URLRequest(url: dataURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request, completionHandler: { data, response, error in
guard error == nil else {
completion(Result.failure(AppError.networkError(error!)))
return
}
guard let data = data else {
completion(Result.failure(APPError.dataNotFound))
return
}
do {
//create decodable object from data
let decodedObject = try JSONDecoder().decode(objectType.self, from: data)
completion(Result.success(decodedObject))
} catch let error {
completion(Result.failure(APPError.jsonParsingError(error as! DecodingError)))
}
})
task.resume()
}
example:
//if we want to fetch todo from placeholder API, then we define the ToDo struct and call dataRequest and pass "https://jsonplaceholder.typicode.com/todos/1" string url.
struct ToDo: Decodable {
let id: Int
let userId: Int
let title: String
let completed: Bool
}
dataRequest(with: "https://jsonplaceholder.typicode.com/todos/1", objectType: ToDo.self) { (result: Result) in
switch result {
case .success(let object):
print(object)
case .failure(let error):
print(error)
}
}
//this prints the result:
ToDo(id: 1, userId: 1, title: "delectus aut autem", completed: false)
Declare
public static int[] locations={1,2,3};
outside of the main method.
It's important to distinguish between the content of cells, their display format, the data type read from cells by VBA, and the data type written to cells from VBA and how Excel automatically interprets this. (See e.g. this previous answer.) The relationship between these can be a bit complicated, because Excel will do things like interpret values of one type (e.g. string) as being a certain other data type (e.g. date) and then automatically change the display format based on this. Your safest bet it do everything explicitly and not to rely on this automatic stuff.
I ran your experiment and I don't get the same results as you do. My cell A1 stays a Date the whole time, and B1 stays 41575. So I can't answer your question #1. Results probably depend on how your Excel version/settings choose to automatically detect/change a cell's number format based on its content.
Question #2, "How can I ensure that a cell will return a date value": well, not sure what you mean by "return" a date value, but if you want it to contain a numerical value that is displayed as a date, based on what you write to it from VBA, then you can either:
Write to the cell a string value that you hope Excel will automatically interpret as a date and format as such. Cross fingers. Obviously this is not very robust. Or,
Write a numerical value to the cell from VBA (obviously a Date type is the intended type, but an Integer, Long, Single, or Double could do as well) and explicitly set the cells' number format to your desired date format using the .NumberFormat
property (or manually in Excel). This is much more robust.
If you want to check that existing cell contents can be displayed as a date, then here's a function that will help:
Function CellContentCanBeInterpretedAsADate(cell As Range) As Boolean
Dim d As Date
On Error Resume Next
d = CDate(cell.Value)
If Err.Number <> 0 Then
CellContentCanBeInterpretedAsADate = False
Else
CellContentCanBeInterpretedAsADate = True
End If
On Error GoTo 0
End Function
Example usage:
Dim cell As Range
Set cell = Range("A1")
If CellContentCanBeInterpretedAsADate(cell) Then
cell.NumberFormat = "mm/dd/yyyy hh:mm"
Else
cell.NumberFormat = "General"
End If
Per default collections in scala are immutable, so you have a + method which returns a new list with the element added to it. If you really need something like an add method you need a mutable collection, e.g. http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.html which has a += method.
In your configuration you have 2 PropertySourcesPlaceholderConfigurer
instances.
applicationContext.xml
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="environment">
<bean class="org.springframework.web.context.support.StandardServletEnvironment"/>
</property>
</bean>
infraContext.xml
<context:property-placeholder location="classpath:context-core.properties"/>
By default a PlaceholderConfigurer
is going to fail-fast, so if a placeholder cannot be resolved it will throw an exception. The instance from the applicationContext.xml
file has no properties and as such will fail on all placeholders.
Solution: Remove the one from applicationContext.xml as it doesn't add anything it only breaks things.
You say you have a database on PhpMyAdmin, so you are using MySQL. PHP provides functions for connecting to a MySQL database.
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
In the while loop (which runs every time we encounter a result row), we echo which creates a new table row. I also add a to contain the fields.
This is a very basic template. You see the other answers using mysqli_connect instead of mysql_connect. mysqli stands for mysql improved. It offers a better range of features. You notice it is also a little bit more complex. It depends on what you need.
Using angular-google-maps
$scope.bounds = new google.maps.LatLngBounds();
for (var i = $scope.markers.length - 1; i >= 0; i--) {
$scope.bounds.extend(new google.maps.LatLng($scope.markers[i].coords.latitude, $scope.markers[i].coords.longitude));
};
$scope.control.getGMap().fitBounds($scope.bounds);
$scope.control.getGMap().setCenter($scope.bounds.getCenter());
If you are concerned about performance, use neither int.TryParse
nor Regex
- write your own (simple) function (DigitsOnly
or DigitsOnly2
below, but not DigitsOnly3
- LINQ seems to incur a significant overhead).
Also, be aware that int.TryParse
will fail if the string is too long to "fit" into int
.
This simple benchmark...
class Program {
static bool DigitsOnly(string s) {
int len = s.Length;
for (int i = 0; i < len; ++i) {
char c = s[i];
if (c < '0' || c > '9')
return false;
}
return true;
}
static bool DigitsOnly2(string s) {
foreach (char c in s) {
if (c < '0' || c > '9')
return false;
}
return true;
}
static bool DigitsOnly3(string s) {
return s.All(c => c >= '0' && c <= '9');
}
static void Main(string[] args) {
const string s1 = "916734184";
const string s2 = "916734a84";
const int iterations = 1000000;
var sw = new Stopwatch();
sw.Restart();
for (int i = 0 ; i < iterations; ++i) {
bool success = DigitsOnly(s1);
bool failure = DigitsOnly(s2);
}
sw.Stop();
Console.WriteLine(string.Format("DigitsOnly: {0}", sw.Elapsed));
sw.Restart();
for (int i = 0; i < iterations; ++i) {
bool success = DigitsOnly2(s1);
bool failure = DigitsOnly2(s2);
}
sw.Stop();
Console.WriteLine(string.Format("DigitsOnly2: {0}", sw.Elapsed));
sw.Restart();
for (int i = 0; i < iterations; ++i) {
bool success = DigitsOnly3(s1);
bool failure = DigitsOnly3(s2);
}
sw.Stop();
Console.WriteLine(string.Format("DigitsOnly3: {0}", sw.Elapsed));
sw.Restart();
for (int i = 0; i < iterations; ++i) {
int dummy;
bool success = int.TryParse(s1, out dummy);
bool failure = int.TryParse(s2, out dummy);
}
sw.Stop();
Console.WriteLine(string.Format("int.TryParse: {0}", sw.Elapsed));
sw.Restart();
var regex = new Regex("^[0-9]+$", RegexOptions.Compiled);
for (int i = 0; i < iterations; ++i) {
bool success = regex.IsMatch(s1);
bool failure = regex.IsMatch(s2);
}
sw.Stop();
Console.WriteLine(string.Format("Regex.IsMatch: {0}", sw.Elapsed));
}
}
...produces the following result...
DigitsOnly: 00:00:00.0346094
DigitsOnly2: 00:00:00.0365220
DigitsOnly3: 00:00:00.2669425
int.TryParse: 00:00:00.3405548
Regex.IsMatch: 00:00:00.7017648
See all Available Controller : You can do PHP artisan list to view all commands
For help: PHP artisan help make:controller
php artisan make:controller MyControllerName
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});
When you type integer numbers to JtextField1 after key release it will go to inside try , for any other character it will throw NumberFormatException. If you set empty string to jTextField1 inside the catch so the user cannot type any other keys except positive numbers because JTextField1 will be cleared for each bad attempt.
//Fields
int x;
JTextField jTextField1;
//Gui Code Here
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
try {
x = Integer.parseInt(jTextField1.getText());
} catch (NumberFormatException nfe) {
jTextField1.setText("");
}
}
Most modern languages are in varying degree both imperative and functional but to better understand functional programming, it will be best to take an example of pure functional language like Haskell in contrast of imperative code in not so functional language like java/C#. I believe it is always easy to explain by example, so below is one.
Functional programming: calculate factorial of n i.e n! i.e n x (n-1) x (n-2) x ...x 2 X 1
-- | Haskell comment goes like
-- | below 2 lines is code to calculate factorial and 3rd is it's execution
factorial 0 = 1
factorial n = n * factorial (n - 1)
factorial 3
-- | for brevity let's call factorial as f; And x => y shows order execution left to right
-- | above executes as := f(3) as 3 x f(2) => f(2) as 2 x f(1) => f(1) as 1 x f(0) => f(0) as 1
-- | 3 x (2 x (1 x (1)) = 6
Notice that Haskel allows function overloading to the level of argument value. Now below is example of imperative code in increasing degree of imperativeness:
//somewhat functional way
function factorial(n) {
if(n < 1) {
return 1;
}
return n * factorial(n-1);
}
factorial(3);
//somewhat more imperative way
function imperativeFactor(n) {
int f = 1;
for(int i = 1; i <= n; i++) {
f = f * i;
}
return f;
}
This read can be a good reference to understand that how imperative code focus more on how part, state of machine (i in for loop), order of execution, flow control.
The later example can be seen as java/C# lang code roughly and first part as limitation of the language itself in contrast of Haskell to overload the function by value (zero) and hence can be said it is not purist functional language, on the other hand you can say it support functional prog. to some extent.
Disclosure: none of the above code is tested/executed but hopefully should be good enough to convey the concept; also I would appreciate comments for any such correction :)
MySQL create function syntax:
DELIMITER //
CREATE FUNCTION GETFULLNAME(fname CHAR(250),lname CHAR(250))
RETURNS CHAR(250)
BEGIN
DECLARE fullname CHAR(250);
SET fullname=CONCAT(fname,' ',lname);
RETURN fullname;
END //
DELIMITER ;
Use This Function In Your Query
SELECT a.*,GETFULLNAME(a.fname,a.lname) FROM namedbtbl as a
SELECT GETFULLNAME("Biswarup","Adhikari") as myname;
Watch this Video how to create mysql function and how to use in your query
I had the same problem and I solved in a slightly different way from the others. I am using angular 1.4.4.
In my case, I have a shell template that creates a CSS Bootstrap panel:
<div class="class-container panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">{{title}} </h3>
</div>
<div class="panel-body">
<sp-panel-body panelbodytpl="{{panelbodytpl}}"></sp-panel-body>
</div>
</div>
I want to include panel body templates depending on the route.
angular.module('MyApp')
.directive('spPanelBody', ['$compile', function($compile){
return {
restrict : 'E',
scope : true,
link: function (scope, element, attrs) {
scope.data = angular.fromJson(scope.data);
element.append($compile('<ng-include src="\'' + scope.panelbodytpl + '\'"></ng-include>')(scope));
}
}
}]);
I then have the following template included when the route is #/students
:
<div class="students-wrapper">
<div ng-controller="StudentsIndexController as studentCtrl" class="row">
<div ng-repeat="student in studentCtrl.students" class="col-sm-6 col-md-4 col-lg-3">
<sp-panel
title="{{student.firstName}} {{student.middleName}} {{student.lastName}}"
panelbodytpl="{{'/student/panel-body.html'}}"
data="{{student}}"
></sp-panel>
</div>
</div>
</div>
The panel-body.html template as follows:
Date of Birth: {{data.dob * 1000 | date : 'dd MMM yyyy'}}
Sample data in the case someone wants to have a go:
var student = {
'id' : 1,
'firstName' : 'John',
'middleName' : '',
'lastName' : 'Smith',
'dob' : 1130799600,
'current-class' : 5
}
16x16 pixels, *.ico format.
A lot of great answers over here but among them, I didn't find one about docker. I spent some time to figure out that using the broker container is wrong for this case (obviously!!!)
## this is wrong!
docker exec broker1 kafka-topics --zookeeper localhost:2181 --alter --topic mytopic --config retention.ms=1000
Exception in thread "main" kafka.zookeeper.ZooKeeperClientTimeoutException: Timed out waiting for connection while in state: CONNECTING
at kafka.zookeeper.ZooKeeperClient.$anonfun$waitUntilConnected$3(ZooKeeperClient.scala:258)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:253)
at kafka.zookeeper.ZooKeeperClient.waitUntilConnected(ZooKeeperClient.scala:254)
at kafka.zookeeper.ZooKeeperClient.<init>(ZooKeeperClient.scala:112)
at kafka.zk.KafkaZkClient$.apply(KafkaZkClient.scala:1826)
at kafka.admin.TopicCommand$ZookeeperTopicService$.apply(TopicCommand.scala:280)
at kafka.admin.TopicCommand$.main(TopicCommand.scala:53)
at kafka.admin.TopicCommand.main(TopicCommand.scala)
and I should have used zookeeper:2181
instead of --zookeeper localhost:2181
as per my compose file
## this might be an option, but as per comment below not all zookeeper images can have this script included
docker exec zookeper1 kafka-topics --zookeeper localhost:2181 --alter --topic mytopic --config retention.ms=1000
the correct command would be
docker exec broker1 kafka-configs --zookeeper zookeeper:2181 --alter --entity-type topics --entity-name dev_gdn_urls --add-config retention.ms=12800000
Hope it will save someone's time.
Also, be aware that the messages won't be deleted immediately and it will happen when the segment of the log will be closed.
Your methods should be (something like)
public static int byteArrayToInt(byte[] b)
{
return b[3] & 0xFF |
(b[2] & 0xFF) << 8 |
(b[1] & 0xFF) << 16 |
(b[0] & 0xFF) << 24;
}
public static byte[] intToByteArray(int a)
{
return new byte[] {
(byte) ((a >> 24) & 0xFF),
(byte) ((a >> 16) & 0xFF),
(byte) ((a >> 8) & 0xFF),
(byte) (a & 0xFF)
};
}
These methods were tested with the following code :
Random rand = new Random(System.currentTimeMillis());
byte[] b;
int a, v;
for (int i=0; i<10000000; i++) {
a = rand.nextInt();
b = intToByteArray(a);
v = byteArrayToInt(b);
if (a != v) {
System.out.println("ERR! " + a + " != " + Arrays.toString(b) + " != " + v);
}
}
System.out.println("Done!");
change
fastcgi_pass unix:/var/run/php-fpm.sock;
to
fastcgi_pass unix:/var/run/php5-fpm.sock;
http:[\/]{2}.+?[.][^\/]+(.+)[.].+
let's see, what it done:
http:[\/]{2}.+?[.][^\/]
- non-capture group for http://php.net
(.+)[.]
- capture part until last dot occur: /manual/en/function.preg-match
[.].+
- matching extension of file like this: .php
Using the width function:
$('div#somediv').width('70%');
will turn:
<div id="somediv" />
into:
<div id="somediv" style="width: 70%;"/>
Given a sample dataframe df
as:
a,b
1,2
2,3
3,4
4,5
what you want is:
df['a'] = df['a'].apply(lambda x: x + 1)
that returns:
a b
0 2 2
1 3 3
2 4 4
3 5 5
If your arrays aren't too big or you don't have too many of them, you might be able to get away with forcing the left hand side of ==
to be a string:
myRows = df[str(df['Unnamed: 5']) == 'Peter'].index.tolist()
But this is ~1.5 times slower if df['Unnamed: 5']
is a string, 25-30 times slower if df['Unnamed: 5']
is a small numpy array (length = 10), and 150-160 times slower if it's a numpy array with length 100 (times averaged over 500 trials).
a = linspace(0, 5, 10)
b = linspace(0, 50, 100)
n = 500
string1 = 'Peter'
string2 = 'blargh'
times_a = zeros(n)
times_str_a = zeros(n)
times_s = zeros(n)
times_str_s = zeros(n)
times_b = zeros(n)
times_str_b = zeros(n)
for i in range(n):
t0 = time.time()
tmp1 = a == string1
t1 = time.time()
tmp2 = str(a) == string1
t2 = time.time()
tmp3 = string2 == string1
t3 = time.time()
tmp4 = str(string2) == string1
t4 = time.time()
tmp5 = b == string1
t5 = time.time()
tmp6 = str(b) == string1
t6 = time.time()
times_a[i] = t1 - t0
times_str_a[i] = t2 - t1
times_s[i] = t3 - t2
times_str_s[i] = t4 - t3
times_b[i] = t5 - t4
times_str_b[i] = t6 - t5
print('Small array:')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_a), mean(times_str_a)))
print('Ratio of time with/without string conversion: {}'.format(mean(times_str_a)/mean(times_a)))
print('\nBig array')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_b), mean(times_str_b)))
print(mean(times_str_b)/mean(times_b))
print('\nString')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_s), mean(times_str_s)))
print('Ratio of time with/without string conversion: {}'.format(mean(times_str_s)/mean(times_s)))
Result:
Small array:
Time to compare without str conversion: 6.58464431763e-06 s. With str conversion: 0.000173756599426 s
Ratio of time with/without string conversion: 26.3881526541
Big array
Time to compare without str conversion: 5.44309616089e-06 s. With str conversion: 0.000870866775513 s
159.99474375821288
String
Time to compare without str conversion: 5.89370727539e-07 s. With str conversion: 8.30173492432e-07 s
Ratio of time with/without string conversion: 1.40857605178
The issue is with this line
xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text
You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.
Hence replace this with
xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text
for(n in 1:5) {
if(n==3) next # skip 3rd iteration and go to next iteration
cat(n)
}
Is this possible in angular 2?
Yes, it is possible.
If both of the conditions are true, will they enable the button?
No, if they are true, then the button will be disabled. disabled="true"
.
I try the above code but it's not working well
What did you expect? the button will be disabled when valid
is false and the angular formGroup
, SAForm
is not valid.
A recommendation here as well, Please make the button of type button not a submit because this may cause the whole form to submit and you would need to use invalidate
and listen to (ngSubmit)
.
To unify all of the screens to show same element sizes including font size: - Design the UI on one screen size with whatever sizes you find appropriate during the design i.e. TextView font size is 14dp on default screen size with 4'6 inches.
Programmatically calculate the physical screen size of the other phones i.e. 5'2 inches of other phones/screens.
Use a formula to calculate the percentage difference between the 2 screens. i.e. what's the % difference between 4'6 and 5'2.
Calculate the pixel difference between the 2 TextViews based on the above formula.
Get the actual size (in pixels) of the TextView font-size and apply the pixels difference (you calculated earlier) to the default font-size.
With this way you can apply dynamic aspect ratio to all of screen sizes and the result is great. You'll have identical layout and sizes on each screen.
It can be a bit tricky at first but totally achieves the goal once you figure the formula out. With this method you don't need to make multiple layouts just to fit different screen sizes.
My solution:
#!/bin/bash
user_cmds="$@"
GID=$(id -g $USER)
UID=$(id -u $USER)
RUN_SCRIPT=$(mktemp -p $(pwd))
(
cat << EOF
addgroup --gid $GID $USER
useradd --no-create-home --home /cmd --gid $GID --uid $UID $USER
cd /cmd
runuser -l $USER -c "${user_cmds}"
EOF
) > $RUN_SCRIPT
trap "rm -rf $RUN_SCRIPT" EXIT
docker run -v $(pwd):/cmd --rm my-docker-image "bash /cmd/$(basename ${RUN_SCRIPT})"
This allows the user to run arbitrary commands using the tools provides by my-docker-image
. Note how the user's current working directory is volume mounted
to /cmd
inside the container.
I am using this workflow to allow my dev-team to cross-compile C/C++ code for the arm64 target, whose bsp I maintain (the my-docker-image
contains the cross-compiler, sysroot, make, cmake, etc). With this a user can simply do something like:
cd /path/to/target_software
cross_compile.sh "mkdir build; cd build; cmake ../; make"
Where cross_compile.sh
is the script shown above. The addgroup/useradd
machinery allows user-ownership of any files/directories created by the build.
While this works for us. It seems sort of hacky. I'm open to alternative implementations ...
\n
in c3 working correctlyusing System;
namespace testing2
public class Test {
public static void Main(string[] args) {
Console.WriteLine("Enter your name");
String s = Console.ReadLine();
Console.WriteLine("Your name is " + s + "\n" + "Thank You");
}
}
All of the examples listed above for sed break on one platform or another. None of them work with the version of sed shipped on Macs.
However, Perl's regex works the same on any machine with Perl installed:
perl -pe 's/\s+/\n/g' file.txt
If you want to save the output:
perl -pe 's/\s+/\n/g' file.txt > newfile.txt
If you want only unique occurrences of words:
perl -pe 's/\s+/\n/g' file.txt | sort -u > newfile.txt
input
element, of type file
<input id="fileInput" type="file" />
On your input
change use the FileReader
object and read your input
file property:
$('#fileInput').on('change', function () {
var fileReader = new FileReader();
fileReader.onload = function () {
var data = fileReader.result; // data <-- in this var you have the file data in Base64 format
};
fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});
FileReader will load your file and in fileReader.result
you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)
I have tried all solution. The -lopencv_core -lopencv_imgproc -lopencv_highgui
in comments solved my problem. And know my command line looks like this in geany:
g++ -lopencv_core -lopencv_imgproc -lopencv_highgui -o "%e" "%f"
When I build:
g++ -lopencv_core -lopencv_imgproc -lopencv_highgui -o "opencv" "opencv.cpp" (in directory: /home/fedora/Desktop/Implementations)
The headers are:
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
There is a way more convenient 'percent'-formatting option for the .format()
format method:
>>> '{:.1%}'.format(1/3.0)
'33.3%'
"A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered."
Not so. The purpose of a destructor is to allow the item that registered the listeners to unregister them. Once an object has no other references to it, it will be garbage collected.
For instance, in AngularJS, when a controller is destroyed, it can listen for a destroy event and respond to it. This isn't the same as having a destructor automatically called, but it's close, and gives us the opportunity to remove listeners that were set when the controller was initialized.
// Set event listeners, hanging onto the returned listener removal functions
function initialize() {
$scope.listenerCleanup = [];
$scope.listenerCleanup.push( $scope.$on( EVENTS.DESTROY, instance.onDestroy) );
$scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.SUCCESS, instance.onCreateUserResponse ) );
$scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.FAILURE, instance.onCreateUserResponse ) );
}
// Remove event listeners when the controller is destroyed
function onDestroy(){
$scope.listenerCleanup.forEach( remove => remove() );
}
var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr){
// result
});
try this:
.test {
position:absolute;
background:blue;
width:200px;
height:200px;
top:40px;
transition:left 1s linear;
left: 0;
}
I would recommend you to give a look to this library:
I really like it, it supports a variety of storage backends (from cookies to HTML5 storage, Gears, Flash, and more...), its usage is really transparent, you don't have to know or care which backend is used the library will choose the right storage backend depending on the browser capabilities.
If you want the list of all database sizes sorted, you can use :
SELECT *
FROM (SELECT table_schema AS `DB Name`,
ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) AS `DB Size in MB`
FROM information_schema.tables
GROUP BY `DB Name`) AS tmp_table
ORDER BY `DB Size in MB` DESC;
try this
Package manager console
Install-Package System.Net.Http.Formatting.Extension -Version 5.2.3
and then add by using add reference .
Here's what's this TS snippet compiled into (via TS Playground):
define(["require", "exports"], function(require, exports) {
var Library = (function () {
function Library() {
}
Library.BOOK_SHELF_NONE = "None";
Library.BOOK_SHELF_FULL = "Full";
return Library;
})();
exports.Library = Library;
});
As you see, both properties defined as public static
are simply attached to the exported function (as its properties); therefore they should be accessible as long as you properly access the function itself.
The is
operator in Python probably doesn't do what you expect. Instead of this:
if numpy.array_equal(tmp,universe_array) is True:
break
I would write it like this:
if numpy.array_equal(tmp,universe_array):
break
The is
operator tests object identity, which is something quite different from equality.
This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item|
you are assigning item
to a two-element array [key, value]
, so item[:symbol]
throws an error.
What your looking for is Reverse Geo Coding. Have a look at this example here. https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
As was stated, your reader needs to be 'step' scoped. You can accomplish this via the @Scope("step")
annotation. It should work for you if you add that annotation to your reader, like the following:
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("foo-reader")
@Scope("step")
public final class MyReader implements ItemReader<MyData> {
@Override
public MyData read() throws Exception {
//...
}
@Value("#{jobParameters['fileName']}")
public void setFileName(final String name) {
//...
}
}
This scope is not available by default, but will be if you are using the batch
XML namespace. If you are not, adding the following to your Spring configuration will make the scope available, per the Spring Batch documentation:
<bean class="org.springframework.batch.core.scope.StepScope" />
Try www.eclipse.org/downloads/packages/eclipse-android-developers-includes-incubating-components/neonrc3
The default sqlite library that comes with iOS is not compiled using the SQLITE_THREADSAFE macro on. This could be a reason why your code crashes.
The then()
method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:
getFeed().then(function(data) { vm.feed = data;});
The then()
function returns the promise with a resolved value of the previous then()
callback, allowing you the pass the value to subsequent callbacks:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1
According to the Wordpress documentation, you should use wp_localize_script()
in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.
See Codex
Example:
<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>
To access this variable within in Javascript, you would simply do:
<script type="text/javascript">
var url = WPURLS.siteurl;
</script>
Untested....but should work.
Dim lastrow as long
lastrow = range("D65000").end(xlup).Row
ActiveCell.FormulaR1C1 = _
"=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
Selection.AutoFill Destination:=Range("E2:E" & lastrow)
'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
Range("E2:E1344").Select
Only exception being are you sure your Autofill code is perfect...
You can do so. However, you can't assign to this. Thus the reason you state for doing this, "I want to change the view," seems very questionable. The better method, in my opinion, would be for the object that holds the view to replace that view.
Of course, you're using RAII objects and so you don't actually need to call delete at all...right?
In some cases cleaning the project/solution, physically removing bin/
and obj/
and rebuilding would resolve such errors. This could happen when, for example, some packages and references being installed/added and then removed, leaving some artifacts behind.
It happened to me with Microsoft.Web.Infrastructure
: initially, the project didn't require that assembly. After some experiments, the net effect of which was supposed to be zero at the end, I got this exception. Above steps resolved it without the need to install unused dependency.
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
Check if string is alphanumeric or alphanumeric + some allowed chars
The fastest alphanumeric method is likely as mentioned at: Best way to alphanumeric check in Javascript as it operates on number ranges directly.
Then, to allow a few other extra chars sanely we can just put them in a Set
for fast lookup.
I believe that this implementation will deal with surrogate pairs correctly correctly.
#!/usr/bin/env node
const assert = require('assert');
const char_is_alphanumeric = function(c) {
let code = c.codePointAt(0);
return (
// 0-9
(code > 47 && code < 58) ||
// A-Z
(code > 64 && code < 91) ||
// a-z
(code > 96 && code < 123)
)
}
const is_alphanumeric = function (str) {
for (let c of str) {
if (!char_is_alphanumeric(c)) {
return false;
}
}
return true;
};
// Arbitrarily defined as alphanumeric or '-' or '_'.
const is_almost_alphanumeric = function (str) {
for (let c of str) {
if (
!char_is_alphanumeric(c) &&
!is_almost_alphanumeric.almost_chars.has(c)
) {
return false;
}
}
return true;
};
is_almost_alphanumeric.almost_chars = new Set(['-', '_']);
assert( is_alphanumeric('aB0'));
assert(!is_alphanumeric('aB0_-'));
assert(!is_alphanumeric('aB0_-*'));
assert(!is_alphanumeric('??'));
assert( is_almost_alphanumeric('aB0'));
assert( is_almost_alphanumeric('aB0_-'));
assert(!is_almost_alphanumeric('aB0_-*'));
assert(!is_almost_alphanumeric('??'));
Tested in Node.js v10.15.1.
I think that's what you're looking for:
SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*
FROM WorkItems t1
WHERE (TextField01, TimeStamp) IN(
SELECT TextField01, MAX(TimeStamp)
FROM WorkItems t2
GROUP BY t2.TextField01
)
AND TimeStamp > '2009-02-12 18:00:00'
If you're in Oracle or in MS SQL 2005 and above, then you could do:
SELECT *
FROM (
SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*,
ROW_NUMBER() OVER (PARTITION BY TextField01 ORDER BY TimeStamp DESC) AS rn
FROM WorkItems t1
) to
WHERE rn = 1
, it's more efficient.
JVM Java Virtual Machine , actually executes the java bytecode. It is the execution block on the JAVA platform. It converts the bytecode to the machine code.
JRE Java Runtime Environment , provides the minimum requirements for executing a Java application; it consists of the Java Virtual Machine (JVM), core classes, and supporting files.
JDK Java Development Kit, it has all the tools to develop your application software. It is as JRE+JVM
Open JDK is a free and open source implementation of the Java Platform.
You could alter the figsize
by passing a tuple
showing the width, height
parameters you would like to keep.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10,10)) # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)
EDIT
I remember answering a similar question of yours where you had to set the index as TIMESTAMP
. So, you could then do something like below:
df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)
For the head
of the dataframe you posted, the plot would look like:
To extend Rodrigo's solution a little - for requests that are executed frequently, you may only want to display the loading image if the request takes more than a minimum time interval, otherwise the image will be continually popping up and quickly disappearing
var loading = false;
$.ajaxSetup({
beforeSend: function () {
// Display loading icon if AJAX call takes >1 second
loading = true;
setTimeout(function () {
if (loading) {
// show loading image
}
}, 1000);
},
complete: function () {
loading = false;
// hide loading image
}
});
Another option is to do like this:
<html>
<body>
<?php
//...php code...
?>
<script type="text/javascript">
document.write("Hello World!");
</script>
<?php
//....php code...
?>
</body>
</html>
and if you want to use PHP inside your JavaScript, do like this:
<html>
<body>
<?php
$text = "Hello World!";
?>
<script type="text/javascript">
document.write("<?php echo $text ?>");
</script>
<?php
//....php code...
?>
</body>
</html>
Hope this can help.
Using REGEX you can remove the spaces in a string.
The following namespace is mandatory.
using System.Text.RegularExpressions;
Syntax:
Regex.Replace(text, @"\s", "")
To find the version of the subversion REPOSITORY you can:
If not displayed, view source of the page
<svn version="1.6.13 (r1002816)" href="http://subversion.tigris.org/">
Now for the subversion CLIENT:
svn --version
will suffice
You can calculate with Dates.
var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25
Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.
Step 2: Let's say you're using Java. You would use JSONArray like this:
JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
JSONArray myInteriorArray=myArray.getJSONArray(i);
if (i==0) {
//this is the first one and is special because it holds the name of the query.
}else{
//do your stuff
String stateCode=myInteriorArray.getString(0);
String stateName=myInteriorArray.getString(1);
}
}
Simply just check with the number of characters in the string
class YorsClassName : UITextFieldDelegate {
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.text?.count == 1 {
return false
}
return true
}
Note: Here I checked for only char allowed in textField
SIMPLEST ANSWER
just spread the set inside []
let mySet = new Set()
mySet.add(1)
mySet.add(5)
mySet.add(5)
let arr = [...mySet ]
Result: [1,5]
I have solved this issue and edited my config->database.php
file to like my database ('charset'=>'utf8')
and the ('collation'=>'utf8_general_ci')
, so my problem is solved the code as follow:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
You can use the regular expression /(?!$)/
:
"overpopulation".split(/(?!$)/)
The negative look-ahead assertion (?!$)
will match right in front of every character.
What about:
list =[ ['a','b'], ['a','c'], ['b','d'] ]
search = 'b'
filter(lambda x:x[1]==search,list)
This will return each list in the list of lists with the second element being equal to search.
May be use Filter.
const list = [{id:0}, {id:1}, {id:2}];
let listCopy = [...list];
let filteredDataSource = listCopy.filter((item) => {
if (item.id === 1) {
item.id = 12345;
}
return item;
});
console.log(filteredDataSource);
Array [Object { id: 0 }, Object { id: 12345 }, Object { id: 2 }]
A referral was returned from the server error usually means that the IP address is not hosted by the domain that is provided on the connection string. For more detail, see this link:
Referral was returned AD Provider
To illustrate the problem, we define two IP addresses hosted on different domains:
IP Address DC Name Notes
172.1.1.10 ozkary.com Production domain
172.1.30.50 ozkaryDev.com Development domain
If we defined a LDAP connection string with this format:
LDAP://172.1.1.10:389/OU=USERS,DC=OZKARYDEV,DC=COM
This will generate the error because the IP is actually on the OZKARY DC not the OZKARYDEV DC. To correct the problem, we would need to use the IP address that is associated to the domain.
First, Navigate to the TOMCAT-HOME/bin
directory.
Then, Execute the following in the command-line:
catalina.bat jpda start
If the Tomcat server is running under Linux, just invoke the catalina.sh
program
catalina.sh jpda start
It's the same for Tomcat 5.5 and Tomcat 6
You can call the stat() function and use the S_ISREG()
macro on the st_mode
field of the stat structure in order to determine if your path points to a regular file:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int is_regular_file(const char *path)
{
struct stat path_stat;
stat(path, &path_stat);
return S_ISREG(path_stat.st_mode);
}
Note that there are other file types besides regular and directory, like devices, pipes, symbolic links, sockets, etc. You might want to take those into account.
final Map<String, String> mss1 = new ProcessBuilder().environment();
mss1.entrySet()
.stream()
//depending on how you want to join K and V use different delimiter
.map(entry ->
String.join(":", entry.getKey(),entry.getValue()))
.forEach(System.out::println);
Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying n
first):
>>> n = 43365644
>>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
[4, 3, 3, 6, 5, 6, 4, 4]
Updating this after many years in response to comments of this not working for powers of 10:
[(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][bool(math.log(n,10)%1):]
The issue is that with powers of 10 (and ONLY with these), an extra step is required. ---So we use the remainder in the log_10 to determine whether to remove the leading 0
--- We can't exactly use this because floating-point math errors cause this to fail for some powers of 10. So I've decided to cross the unholy river into sin and call upon regex.
In [32]: n = 43
In [33]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[33]: [4, 3]
In [34]: n = 1000
In [35]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[35]: [1, 0, 0, 0]
git rebase didn't seem to work for me. After git rebase, when I try to push changes to my local branch, I kept getting an error ("hint: Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes (e.g. 'git pull ...') before pushing again.") even after git pull. What finally worked for me was git merge.
git checkout <local_branch>
git merge <master>
If you are a beginner like me, here is a good article on git merge vs git rebase. https://www.atlassian.com/git/tutorials/merging-vs-rebasing
A more raw approach without using sort Arrays.sort method. This is using insertion sort.
public static void main(String[] args){
String wordSt="watch";
char[] word=wordSt.toCharArray();
for(int i=0;i<(word.length-1);i++){
for(int j=i+1;j>0;j--){
if(word[j]<word[j-1]){
char temp=word[j-1];
word[j-1]=word[j];
word[j]=temp;
}
}
}
wordSt=String.valueOf(word);
System.out.println(wordSt);
}
Typically we would place one of these at or near the top of the script. Scripts that parse their command lines would do the redirection after parsing.
Send stdout to a file
exec > file
with stderr
exec > file
exec 2>&1
append both stdout and stderr to file
exec >> file
exec 2>&1
As Jonathan Leffler mentioned in his comment:
exec
has two separate jobs. The first one is to replace the currently executing shell (script) with a new program. The other is changing the I/O redirections in the current shell. This is distinguished by having no argument to exec
.
I wrote a simple node script for deleting messages from public/private channels and chats. You can modify and use it.
https://gist.github.com/firatkucuk/ee898bc919021da621689f5e47e7abac
First, modify your token in the scripts configuration section then run the script:
node ./delete-slack-messages CHANNEL_ID
Also, the channel ID can be seen in the browser URL when you open slack in the browser. e.g.
https://mycompany.slack.com/messages/MY_CHANNEL_ID/
or
https://app.slack.com/client/WORKSPACE_ID/MY_CHANNEL_ID
Another option is the openxlsx
-package. It doesn't depend on java and can read, edit and write Excel-files. From the description from the package:
openxlsx simplifies the the process of writing and styling Excel xlsx files from R and removes the dependency on Java
Example usage:
library(openxlsx)
# read data from an Excel file or Workbook object into a data.frame
df <- read.xlsx('name-of-your-excel-file.xlsx')
# for writing a data.frame or list of data.frames to an xlsx file
write.xlsx(df, 'name-of-your-excel-file.xlsx')
Besides these two basic functions, the openxlsx
-package has a host of other functions for manipulating Excel-files.
For example, with the writeDataTable
-function you can create formatted tables in an Excel-file.
How about this: http://jsfiddle.net/5bNx4/
Please use .on
if you are using jq1.7 et al.
Behaviour: When you type anything or paste
anything on the 1st textarea the teaxtarea below captures the cahnge.
Rest I hope it helps the cause. :)
Helpful link =>
How do you handle oncut, oncopy, and onpaste in jQuery?
code
$(document).ready(function() {
var $editor = $('#editor');
var $clipboard = $('<textarea />').insertAfter($editor);
if(!document.execCommand('StyleWithCSS', false, false)) {
document.execCommand('UseCSS', false, true);
}
$editor.on('paste, keydown', function() {
var $self = $(this);
setTimeout(function(){
var $content = $self.html();
$clipboard.val($content);
},100);
});
});
keytool -printcert -file ANDROID_.RSA or keytool -list -printcert -jarfile app.apk
to obtain the hash md5keytool -list -v -keystore clave-release.jks
Let's look at both ways:
(function(){
var i2 = i;
setTimeout(function(){
console.log(i2);
}, 1000)
})();
Declares and immediately executes an anonymous function that runs setTimeout()
within its own context. The current value of i
is preserved by making a copy into i2
first; it works because of the immediate execution.
setTimeout((function(i2){
return function() {
console.log(i2);
}
})(i), 1000);
Declares an execution context for the inner function whereby the current value of i
is preserved into i2
; this approach also uses immediate execution to preserve the value.
Important
It should be mentioned that the run semantics are NOT the same between both approaches; your inner function gets passed to setTimeout()
whereas his inner function calls setTimeout()
itself.
Wrapping both codes inside another setTimeout()
doesn't prove that only the second approach uses closures, there's just not the same thing to begin with.
Conclusion
Both methods use closures, so it comes down to personal taste; the second approach is easier to "move" around or generalize.
The new command to flush the privileges is:
FLUSH PRIVILEGES
The old command FLUSH ALL PRIVILEGES
does not work any more.
You will get an error that looks like that:
MariaDB [(none)]> FLUSH ALL PRIVILEGES;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ALL PRIVILEGES' at line 1
Hope this helps :)
?month
states:
Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
Your object is a factor, not even a character vector (presumably because of stringsAsFactors = TRUE
). You have to convert your vector to some datetime class, for instance to POSIXlt
:
library(lubridate)
some_date <- c("01/02/1979", "03/04/1980")
month(as.POSIXlt(some_date, format="%d/%m/%Y"))
[1] 2 4
There's also a convenience function dmy
, that can do the same (tip proposed by @Henrik):
month(dmy(some_date))
[1] 2 4
Going even further, @IShouldBuyABoat gives another hint that dd/mm/yyyy character formats are accepted without any explicit casting:
month(some_date)
[1] 2 4
For a list of formats, see ?strptime
. You'll find that "standard unambiguous format" stands for
The default formats follow the rules of the ISO 8601 international standard which expresses a day as "2001-02-28" and a time as "14:01:02" using leading zeroes as here.
Suppose someone found his way here and does not understand the usage of the marked answer SQL, please read mine... it is edited and works. Table:staff, columns:staffname,staffphone and staffDOB
declare @body varchar(max)
-- Create the body
set @body = cast( (
select td = dbtable + '</td><td>' + cast( phone as varchar(30) ) + '</td><td>' + cast( age as varchar(30) )
from (
select dbtable = StaffName ,
phone = staffphone,
age = datepart(day,staffdob)
from staff
group by staffname,StaffPhone,StaffDOB
) as d
for xml path( 'tr' ), type ) as varchar(max) )
set @body = '<table cellpadding="2" cellspacing="2" border="1">'
+ '<tr><th>Database Table</th><th>Entity Count</th><th>Total Rows</th></tr>'
+ replace( replace( @body, '<', '<' ), '>', '>' )
+ '<table>'
print @body
System read-only variable %CD%
keeps the path of the caller of the batch, not the batch file location.
You can get the name of the batch script itself as typed by the user with %0
(e.g. scripts\mybatch.bat
). Parameter extensions can be applied to this so %~dp0
will return the Drive and Path to the batch script (e.g. W:\scripts\
) and %~f0
will return the full pathname (e.g. W:\scripts\mybatch.cmd
).
You can refer to other files in the same folder as the batch script by using this syntax:
CALL %0\..\SecondBatch.cmd
This can even be used in a subroutine, Echo %0
will give the call label but, echo "%~nx0"
will give you the filename of the batch script.
When the %0
variable is expanded, the result is enclosed in quotation marks.
A little late but someone can use this in future...You can increase your test timeout by updating scripts in your package.json with the following:
"scripts": {
"test": "test --timeout 10000" //Adjust to a value you need
}
Run your tests using the command test
You could really, really, really optimize your code a lot by paying the price of creating the delegate only once (there's also no need to instantiate the class to call an static method). I've done something very similar, and I just cache a delegate to the "Run" method with the help of a helper class :-). It looks like this:
static class Indent{
public static void Run(){
// implementation
}
// other helper methods
}
static class MacroRunner {
static MacroRunner() {
BuildMacroRunnerList();
}
static void BuildMacroRunnerList() {
macroRunners = System.Reflection.Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.Namespace.ToUpper().Contains("MACRO"))
.Select(t => (Action)Delegate.CreateDelegate(
typeof(Action),
null,
t.GetMethod("Run", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)))
.ToList();
}
static List<Action> macroRunners;
public static void Run() {
foreach(var run in macroRunners)
run();
}
}
It is MUCH faster this way.
If your method signature is different from Action you could replace the type-casts and typeof from Action to any of the needed Action and Func generic types, or declare your Delegate and use it. My own implementation uses Func to pretty print objects:
static class PrettyPrinter {
static PrettyPrinter() {
BuildPrettyPrinterList();
}
static void BuildPrettyPrinterList() {
printers = System.Reflection.Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.Name.EndsWith("PrettyPrinter"))
.Select(t => (Func<object, string>)Delegate.CreateDelegate(
typeof(Func<object, string>),
null,
t.GetMethod("Print", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)))
.ToList();
}
static List<Func<object, string>> printers;
public static void Print(object obj) {
foreach(var printer in printers)
print(obj);
}
}
For mac, this works really well: http://martinfitzpatrick.name/article/add-git-branch-name-to-terminal-prompt-mac/:
# Git branch in prompt.
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
All you need to do is add the mat-icon-button directive to the button element in your template. Within the button element specify your desired icon with a mat-icon component.
You'll need to import MatButtonModule and MatIconModule in your app module file.
From the Angular Material buttons example page, hit the view code button and you'll see several examples which use the material icons font, eg.
<button mat-icon-button>
<mat-icon aria-label="Example icon-button with a heart icon">favorite</mat-icon>
</button>
In your case, use
<mat-icon>thumb_up</mat-icon>
As per the getting started guide at https://material.angular.io/guide/getting-started, you'll need to load the material icon font in your index.html.
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
Or import it in your global styles.scss.
@import url("https://fonts.googleapis.com/icon?family=Material+Icons");
As it mentions, any icon font can be used with the mat-icon component.
Use this code to add years or months or days or hours or minutes or seconds to a given date
echo date("Y-m-d H:i:s", strtotime("+1 years", strtotime('2014-05-22 10:35:10'))); //2015-05-22 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 months", strtotime('2014-05-22 10:35:10')));//2014-06-22 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 days", strtotime('2014-05-22 10:35:10')));//2014-05-23 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 hours", strtotime('2014-05-22 10:35:10')));//2014-05-22 11:35:10
echo date("Y-m-d H:i:s", strtotime("+1 minutes", strtotime('2014-05-22 10:35:10')));//2014-05-22 10:36:10
echo date("Y-m-d H:i:s", strtotime("+1 seconds", strtotime('2014-05-22 10:35:10')));//2014-05-22 10:35:11
You can also subtract replacing + to -
SELECT l.*
FROM (
SELECT DISTINCT usr_id
FROM lives
) lo, lives l
WHERE l.ctid = (
SELECT ctid
FROM lives li
WHERE li.usr_id = lo.usr_id
ORDER BY
time_stamp DESC, trans_id DESC
LIMIT 1
)
Creating an index on (usr_id, time_stamp, trans_id)
will greatly improve this query.
You should always, always have some kind of PRIMARY KEY
in your tables.
You could use if type(ele) is dict
or use isinstance(ele, dict)
which would work if you had subclassed dict
:
d = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
for element in d.values():
if isinstance(element, dict):
for k, v in element.items():
print(k,' ',v)
This works too:
var exeBlk = {
() -> Void in
}
exeBlk = {
//do something
}
//instead of nil:
exeBlk = {}
The code below is based on Christian Brabandt's answer and seems to do what the OP wants:
function! Whitespace()
if !exists('b:ws')
highlight Conceal ctermbg=NONE ctermfg=240 cterm=NONE guibg=NONE guifg=#585858 gui=NONE
highlight link Whitespace Conceal
let b:ws = 1
endif
syntax clear Whitespace
syntax match Whitespace / / containedin=ALL conceal cchar=·
setlocal conceallevel=2 concealcursor=c
endfunction
augroup Whitespace
autocmd!
autocmd BufEnter,WinEnter * call Whitespace()
augroup END
Append those lines to your ~/.vimrc
and start a new Vim session to see the still imperfect magic happen.
Feel free to edit the default colors and conceal character.
Caveat: something in the *FuncBody
syntax group in several languages prevents the middle dot from showing. I don't know (yet?) how to make that solution more reliable.
It's simple to implement this with the built-in DOM methods without a big library like jQuery, if you want, it just takes a bit more code - iterate over an array of event names, and add a listener for each:
function validate() {
// ...
}
const element = document.querySelector('#element');
['keyup', 'keypress', 'blur', 'change'].forEach((eventName) => {
element.addEventListener(eventName, validate);
});
If you are using Express
, the cleanest complete answer is this
const express = require('express')
const app = express()
app.get('*', (req, res) => {
// REDIRECT goes here
res.redirect('https://www.YOUR_URL.com/')
})
app.set('port', (process.env.PORT || 3000))
const server = app.listen(app.get('port'), () => {})
In actual original Sass (not scss) you could use the below mixins to automatically set the paragraph's and all headings' font-size
.
I like it because it is much more compact. And quicker to type. Other than that, it provides the same functionality. Anyway, if you still want to stick to the new syntax - scss, then feel free to convert my Sass content to scss here: [CONVERT SASS TO SCSS HERE]
Below I give you four Sass mixins. You will have to tweak their settings to your needs.
=font-h1p-style-generator-manual() // You don’t need to use this one. Those are only styles to make it pretty.
=media-query-base-font-size-change-generator-manual() // This mixin sets the base body size that will be used by the h1-h6 tags to recalculate their size in a media query.
=h1p-font-size-generator-auto($h1-fs: 3em, $h1-step-down: 0.3, $body-min-font-size: 1.2em, $p-same-as-hx: 6) // Here you will set the size of h1 and size jumps between h tags
=config-and-run-font-generator() // This one only calls the other ones
After you finish playing with settings just make a call on one mixin - which is: +config-and-run-font-generator(). See code below and comments for more information.
I guess you could do it automatically for a media query like it is done for header tags, but we all use different media queries, so it would not be appropriate for everyone. I use a mobile-first design approach, so this is how I would do that. Feel free to copy and use this code.
COPY AND PASTE THESE MIXINS TO YOUR FILE:
=font-h1p-style-generator-manual()
body
font-family: "Source Sans Pro", "Helvetica Neue", Helvetica, Arial, sans-serif // google fonts
font-size: 100%
line-height: 1.3em
%headers
line-height: 1em
font-weight: 700
p
line-height: 1.3em
font-weight: 300
@for $i from 1 through 6
h#{$i}
@extend %headers
=media-query-base-font-size-change-generator-manual()
body
font-size: 1.2em
@media screen and (min-width: 680px)
body
font-size: 1.4em
@media screen and (min-width: 1224px)
body
font-size: 1.6em
@media screen and (min-width: 1400px)
body
font-size: 1.8em
=h1p-font-size-generator-auto($h1-fs: 3em, $h1-step-down: 0.3, $body-min-font-size: 1.2em, $p-same-as-hx: 6)
$h1-fs: $h1-fs // Set first header element to this size
$h1-step-down: $h1-step-down // Decrement each time by 0.3
$p-same-as-hx: $p-same-as-hx // Set p font-sieze same as h(6)
$h1-fs: $h1-fs + $h1-step-down // Looping correction
@for $i from 1 through 6
h#{$i}
font-size: $h1-fs - ($h1-step-down * $i)
@if $i == $p-same-as-hx
p
font-size: $h1-fs - ($h1-step-down * $i)
// RUN ONLY THIS MIXIN. IT WILL TRIGGER THE REST
=config-and-run-font-generator()
+font-h1p-style-generator-manual() // Just a place holder for our font style
+media-query-base-font-size-change-generator-manual() // Just a placeholder for our media query font size
+h1p-font-size-generator-auto($h1-fs: 2em, $h1-step-down: 0.2, $p-same-as-hx: 5) // Set all parameters here
CONFIGURE ALL MIXINS TO YOUR NEEDS - PLAY WITH IT! :) AND THEN CALL IT ON THE TOP OF YOUR ACTUAL SASS CODE WITH:
+config-and-run-font-generator()
This would generate this output. You can customize parameters to generate different sets of results. However, because we all use different media queries, some mixins you will have to edit manually (style and media).
GENERATED CSS:
body {
font-family: "Source Sans Pro", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 100%;
line-height: 1.3em;
word-wrap: break-word; }
h1, h2, h3, h4, h5, h6 {
line-height: 1em;
font-weight: 700; }
p {
line-height: 1.3em;
font-weight: 300; }
body {
font-size: 1.2em; }
@media screen and (min-width: 680px) {
body {
font-size: 1.4em; } }
@media screen and (min-width: 1224px) {
body {
font-size: 1.6em; } }
@media screen and (min-width: 1400px) {
body {
font-size: 1.8em; } }
h1 {
font-size: 2em; }
h2 {
font-size: 1.8em; }
h3 {
font-size: 1.6em; }
h4 {
font-size: 1.4em; }
h5 {
font-size: 1.2em; }
p {
font-size: 1.2em; }
h6 {
font-size: 1em;
}
Update:
As noted by @iX3, Typescript 2.4 has support for enum strings.
See:Create an enum with string values in Typescript
Original answer:
For String member values, TypeScript only allows numbers as enum member values. But there are a few solutions/hacks you can implement;
Solution 1:
copied from: https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/
There is a simple solution: Just cast the string literal to any before assigning:
export enum Language {
English = <any>"English",
German = <any>"German",
French = <any>"French",
Italian = <any>"Italian"
}
solution 2:
copied from: https://basarat.gitbooks.io/typescript/content/docs/types/literal-types.html
You can use a string literal as a type. For example:
let foo: 'Hello';
Here we have created a variable called foo that will only allow the literal value 'Hello' to be assigned to it. This is demonstrated below:
let foo: 'Hello';
foo = 'Bar'; // Error: "Bar" is not assignable to type "Hello"
They are not very useful on their own but can be combined in a type union to create a powerful (and useful) abstraction e.g.:
type CardinalDirection =
"North"
| "East"
| "South"
| "West";
function move(distance: number, direction: CardinalDirection) {
// ...
}
move(1,"North"); // Okay
move(1,"Nurth"); // Error!
Using ripgrep's replace option, it is possible to change the output to a capture group:
rg --only-matching --replace '$1' '(\d+) rofl'
--only-matching
or -o
outputs only the part that matches instead of the whole line.--replace '$1'
or -r
replaces the output by the first capture group.Using table aliases in the join condition:
update addresses a
set cid = b.id
from customers b
where a.id = b.id
If you put #!/bin/awk -f
on the first line of your AWK script it is easier. Plus editors like Vim and ... will recognize the file as an AWK script and you can colorize. :)
#!/bin/awk -f
BEGIN {} # Begin section
{} # Loop section
END{} # End section
Change the file to be executable by running:
chmod ugo+x ./awk-script
and you can then call your AWK script like this:
`$ echo "something" | ./awk-script`
Here's an option that stays as true I could make it to the OP's requirement to be able to switch on type. If you squint hard enough it almost looks like a real switch statement.
The calling code looks like this:
var @switch = this.Switch(new []
{
this.Case<WebControl>(x => { /* WebControl code here */ }),
this.Case<TextBox>(x => { /* TextBox code here */ }),
this.Case<ComboBox>(x => { /* ComboBox code here */ }),
});
@switch(obj);
The x
in each lambda above is strongly-typed. No casting required.
And to make this magic work you need these two methods:
private Action<object> Switch(params Func<object, Action>[] tests)
{
return o =>
{
var @case = tests
.Select(f => f(o))
.FirstOrDefault(a => a != null);
if (@case != null)
{
@case();
}
};
}
private Func<object, Action> Case<T>(Action<T> action)
{
return o => o is T ? (Action)(() => action((T)o)) : (Action)null;
}
Almost brings tears to your eyes, right?
Nonetheless, it works. Enjoy.
In windows first check under services if world wide web publishing services is running. If not start it.
If you cannot find it switch on IIS features of windows: In 7,8,10 it is under control panel , "turn windows features on or off". Internet Information Services World Wide web services and Internet information Services Hostable Core are required. Not sure if there is another way to get it going on windows, but this worked for me for all browsers. You might need to add localhost or http:/127.0.0.1 to the trusted websites also under IE settings.
From your question all I can understand is that you already have some hover effect on your button which you want remove. For that either remove that css which causes the hover effect or override it.
For overriding, do this
.buttonDisabled:hover
{
//overriding css goes here
}
For example if your button's background color changes on hover from red to blue. In the overriding css you will make it as red so that it doesnt change.
Also go through all the rules of writing and overriding css. Get familiar with what css will have what priority.
Best of luck.
Here is an example for Python 3 that you can edit for Python 2 ;)
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
import os
root = Tk()
root.geometry("550x300+300+150")
root.resizable(width=True, height=True)
def openfn():
filename = filedialog.askopenfilename(title='open')
return filename
def open_img():
x = openfn()
img = Image.open(x)
img = img.resize((250, 250), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
panel = Label(root, image=img)
panel.image = img
panel.pack()
btn = Button(root, text='open image', command=open_img).pack()
root.mainloop()
Length of an array:
UBound(columns)-LBound(columns)+1
UBound
alone is not the best method for getting the length of every array as arrays in VBA can start at different indexes, e.g Dim arr(2 to 10)
UBound
will return correct results only if the array is 1-based (starts indexing at 1 e.g. Dim arr(1 to 10)
. It will return wrong results in any other circumstance e.g. Dim arr(10)
More on the VBA Array in this VBA Array tutorial.
Simply get route form this url and do next ...
Origin ---> starting point latitude & longitude
Destination---> ending point latitude & longitude
here i have put origin as Delhi latitude and longitude & destination as chandigarh latitude longitude
https://maps.googleapis.com/maps/api/directions/json?origin=28.704060,77.102493&destination=30.733315,76.779419&sensor=false&key="PUT YOUR MAP API KEY"
Generically, do
/while
is good for any sort of loop construct where one must execute the loop at least once. It is possible to emulate this sort of looping through either a straight while
or even a for
loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:
do {
char c = read_input();
process_input(c);
} while (c != 'Q');
For <a>
tags:
You need to stick target="_self"
on your <a>
tag
There are three cases where AngularJS will perform a full page reload:
<a href="/ext/link?a=b" target="_self">link</a>
<a href="http://angularjs.org/">link</a>
<a href="/not-my-base/link">link</a>
Using javascript:
The $location
service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API: $window.location.href
.
See:
You need to make sure if package.json file exist in app folder. i run into same problem differently but solution would be same
Run this command where "package.json" file exist. even i experience similar problem then i change the folder and got resolve it. for more explanation i run c:\selfPractice> npm start whereas my package.json resides in c:\selfPractice\frontend> then i change the folder and run c:\selfPractice\frontend> npm start and it got run
If we declare a variable as static, there will be only one copy of the variable. So, whenever different threads access that variable, there will be only one final value for the variable(since there is only one memory location allocated for the variable).
If a variable is declared as volatile, all threads will have their own copy of the variable but the value is taken from the main memory.So, the value of the variable in all the threads will be the same.
So, in both cases, the main point is that the value of the variable is same across all threads.
PCDATA
is text that will be parsed by a parser. Tags inside the text
will be treated as markup and entities will be expanded. CDATA
is text that will not be parsed by a parser. Tags inside the text will
not be treated as markup and entities will not be expanded.By default, everything is PCDATA
. In the following example, ignoring the root, <bar>
will be parsed, and it'll have no content, but one child.
<?xml version="1.0"?>
<foo>
<bar><test>content!</test></bar>
</foo>
When we want to specify that an element will only contain text, and no child elements, we use the keyword PCDATA
, because this keyword specifies that the element must contain parsable character data – that is , any text except the characters less-than (<
) , greater-than (>
) , ampersand (&
), quote('
) and double quote ("
).
In the next example, <bar>
contains CDATA
. Its content will not be parsed and is thus <test>content!</test>
.
<?xml version="1.0"?>
<foo>
<bar><![CDATA[<test>content!</test>]]></bar>
</foo>
There are several content models in SGML. The #PCDATA
content model says that an element may contain plain text. The "parsed" part of it means that markup (including PIs, comments and SGML directives) in it is parsed instead of displayed as raw text. It also means that entity references are replaced.
Another type of content model allowing plain text contents is CDATA
. In XML, the element content model may not implicitly be set to CDATA
, but in SGML, it means that markup and entity references are ignored in the contents of the element. In attributes of CDATA
type however, entity references are replaced.
In XML, #PCDATA
is the only plain text content model. You use it if you at all want to allow text contents in the element. The CDATA
content model may be used explicitly through the CDATA
block markup in #PCDATA
, but element contents may not be defined as CDATA
per default.
In a DTD, the type of an attribute that contains text must be CDATA
. The CDATA
keyword in an attribute declaration has a different meaning than the CDATA
section in an XML document. In a CDATA
section all characters are legal (including <
,>
,&
,'
and "
characters), except the ]]>
end tag.
#PCDATA
is not appropriate for the type of an attribute. It is used for the type of "leaf" text.
#PCDATA
is prepended by a hash in the content model to distinguish this keyword from an element named PCDATA
(which would be perfectly legal).
All of the other contributors gave great answers, which work when you have a single dimension (leveled) list, however of the methods mentioned so far, only copy.deepcopy()
works to clone/copy a list and not have it point to the nested list
objects when you are working with multidimensional, nested lists (list of lists). While Felix Kling refers to it in his answer, there is a little bit more to the issue and possibly a workaround using built-ins that might prove a faster alternative to deepcopy
.
While new_list = old_list[:]
, copy.copy(old_list)'
and for Py3k old_list.copy()
work for single-leveled lists, they revert to pointing at the list
objects nested within the old_list
and the new_list
, and changes to one of the list
objects are perpetuated in the other.
As was pointed out by both Aaron Hall and PM 2Ring using
eval()
is not only a bad idea, it is also much slower thancopy.deepcopy()
.This means that for multidimensional lists, the only option is
copy.deepcopy()
. With that being said, it really isn't an option as the performance goes way south when you try to use it on a moderately sized multidimensional array. I tried totimeit
using a 42x42 array, not unheard of or even that large for bioinformatics applications, and I gave up on waiting for a response and just started typing my edit to this post.It would seem that the only real option then is to initialize multiple lists and work on them independently. If anyone has any other suggestions, for how to handle multidimensional list copying, it would be appreciated.
As others have stated, there are significant performance issues using the copy
module and copy.deepcopy
for multidimensional lists.
<c:if test="${ansokanInfo.pSystem eq 'NAT'}">
This will work:
select * into DestinationDatabase.dbo.[TableName1] from (
Select * from sourceDatabase.dbo.[TableName1])Temp
Simple solution:
<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>
This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.
Also received "Could not create SSL/TLS secure channel" error. This is what worked for me. System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)3072;
I'm not sure how "sophisticated" this is, but it's certainly a bit shorter. It will work with various different types of collection e.g. Set<Integer>, List<String>, etc.
public static final String toSqlList(Collection<?> values) {
String collectionString = values.toString();
// Convert the square brackets produced by Collection.toString() to round brackets used by SQL
return "(" + collectionString.substring(1, collectionString.length() - 1) + ")";
}
Exercise for reader: modify this method so that it correctly handles a null/empty collection :)
Just consider your drive as a folder so do cd e:
what worked for me was using this:
$data = $request->request->all();
$name = $data['form']['name'];
I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.
$(function() {
$('.mhz-news-img img').each(function() {
var maxWidth = 320; // Max width for the image
var maxHeight = 200; // Max height for the image
var maxratio=maxHeight/maxWidth;
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
var curentratio=height/width;
// Check if the current width is larger than the max
if(curentratio>maxratio)
{
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height *ratio); // Scale height based on ratio
}
else
{
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
}
});
});
Here's the solution I used in Kotlin
private fun startTimer()
{
Log.d(TAG, ":startTimer: timeString = '$timeString'")
object : CountDownTimer(TASK_SWITCH_TIMER, 250)
{
override fun onTick(millisUntilFinished: Long)
{
val secondsUntilFinished : Long =
Math.ceil(millisUntilFinished.toDouble()/1000).toLong()
val timeString = "${TimeUnit.SECONDS.toMinutes(secondsUntilFinished)}:" +
"%02d".format(TimeUnit.SECONDS.toSeconds(secondsUntilFinished))
Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $ttlseconds")
Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $millisUntilFinished")
}
@SuppressLint("SetTextI18n")
override fun onFinish()
{
timerTxtVw.text = "0:00"
gameStartEndVisibility(true)
}
}.start()
}
npm init
It is all you need. It will create the package.json file on the fly for you.
public class Journal : ApiController
{
public MyResult Get(journal id)
{
return null;
}
}
public class Journal : ApiController
{
public MyResult Get(journal id, publication id)
{
return null;
}
}
I am not sure whether overloading get/post method violates the concept of restfull api,but it workds. If anyone could've enlighten on this matter. What if I have a uri as
uri:/api/journal/journalid
uri:/api/journal/journalid/publicationid
so as you might seen my journal sort of aggregateroot, though i can define another controller for publication solely and pass id number of publication in my url however this gives much more sense. since my publication would not exist without journal itself.
I encountered the same issues: In a relative layout parentView, I have 2 children childView1 and childView2. At first, I put childView1 above childView2 and I want childView1 to be on top of childView2. Changing the order of children views did not solve the problem for me. What worked for me is to set android:clipChildren="false" on parentView and in the code I set:
childView1.bringToFront();
parentView.invalidate();
I suggest such way based on extension methods:
IEnumerable<Int32> countryIDs =
dataTable
.AsEnumerable()
.Where(row => row.Field<String>("CountryName") == countryName)
.Select(row => row.Field<Int32>("CountryID"));
System.Data.DataSetExtensions.dll needs to be referenced.
seq 1 100 | python3 -c 'print(__import__("random").choice(__import__("sys").stdin.readlines()))'
Can't. Interfaces don't exist at runtime.
Create a variable of the type and use Object.keys
on it
If you implement Thread.UncaughtExceptionHandler in class that starts the Threads, you can set and then rethrow the exception:
public final class ThreadStarter implements Thread.UncaughtExceptionHandler{
private volatile Throwable initException;
public void doSomeInit(){
Thread t = new Thread(){
@Override
public void run() {
throw new RuntimeException("UNCAUGHT");
}
};
t.setUncaughtExceptionHandler(this);
t.start();
t.join();
if (initException != null){
throw new RuntimeException(initException);
}
}
@Override
public void uncaughtException(Thread t, Throwable e) {
initException = e;
}
}
Which causes the following output:
Exception in thread "main" java.lang.RuntimeException: java.lang.RuntimeException: UNCAUGHT
at com.gs.gss.ccsp.enrichments.ThreadStarter.doSomeInit(ThreadStarter.java:24)
at com.gs.gss.ccsp.enrichments.ThreadStarter.main(ThreadStarter.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.lang.RuntimeException: UNCAUGHT
at com.gs.gss.ccsp.enrichments.ThreadStarter$1.run(ThreadStarter.java:15)
I know this is old, but should anyone find it more recently, I would suggest creating a separate class file in the controllers folder. Pass in the existing controller object into the class constructor and then you can access the functions from anywhere and it doesn't conflict with CI's setup and handling.
Adding @WebAppConfiguration
(org.springframework.test.context.web.WebAppConfiguration
) annotation to your DemoApplicationTests class will work.
Problem with border-bottom
is the extra distance between the text and the line. Problem with text-decoration-color
is lack of browser support. Therefore my solution is the use of a background-image with a line. This supports any markup, color(s) and style of the line. top
(12px in my example) is dependent on line-height
of your text.
u {
text-decoration: none;
background: transparent url(blackline.png) repeat-x 0px 12px;
}
I placed a TextView on top of the Spinner, same size and background as the Spinner, so that I would have more control over what it looked like before the user clicks on it. With the TextView there, I could also use the TextView to flag when the user has started interacting.
My Kotlin code looks something like this:
private var mySpinnerHasBeenTapped = false
private fun initializeMySpinner() {
my_hint_text_view.setOnClickListener {
mySpinnerHasBeenTapped = true //turn flag to true
my_spinner.performClick() //call spinner click
}
//Basic spinner setup stuff
val myList = listOf("Leonardo", "Michelangelo", "Rafael", "Donatello")
val dataAdapter: ArrayAdapter<String> = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, myList)
my_spinner.adapter = dataAdapter
my_spinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
if (mySpinnerHasBeenTapped) { //code below will only run after the user has clicked
my_hint_text_view.visibility = View.GONE //once an item has been selected, hide the textView
//Perform action here
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
//Do nothing
}
}
}
Layout file looks something like this, with the important part being that the Spinner and TextView share the same width, height, and margins:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:id="@+id/my_spinner"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:background="@drawable/bg_for_spinners"
android:paddingStart="8dp"
android:paddingEnd="30dp"
android:singleLine="true" />
<TextView
android:id="@+id/my_hint_text_view"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:background="@drawable/bg_for_spinners"
android:paddingStart="8dp"
android:paddingEnd="30dp"
android:singleLine="true"
android:gravity="center_vertical"
android:text="*Select A Turtle"
android:textColor="@color/green_ooze"
android:textSize="16sp" />
</FrameLayout>
I'm sure the other solutions work where you ignore the first onItemSelected call, but I really don't like the idea of assuming it will always be called.
It's very simple, I think.
document.getElementById("whatever").classList.remove("className");
You need to parse the string you are sending from javascript object to the JSON object
var json=$.parseJSON(data);
Execute the following command
sudo setfacl -R -m u:<user_name>:rwx /var/www
It will change the permissions of html directory so that you can upload, download and delete the files or directories
since your local username on your laptop frequently does not match the server's username, you can set this in the ~/.subversion/servers file
Add the server to the [groups] section with a name, then add a section with that name and provide a username.
for example, for a login like [email protected]
this is what your config would look like:
[groups]
exampleserver = svn.example.com
[exampleserver]
username = me
theharshest answered the question but here is another way to do the same thing. Also, In your example you have NAME in caps and in your code you have name in lowercase.
s = '<div class="question" id="get attrs" name="python" x="something">Hello World</div>'
soup = BeautifulSoup(s)
attributes_dictionary = soup.find('div').attrs
print attributes_dictionary
# prints: {'id': 'get attrs', 'x': 'something', 'class': ['question'], 'name': 'python'}
print attributes_dictionary['class'][0]
# prints: question
print soup.find('div').get_text()
# prints: Hello World
For MySQL > 5.1.11 or MariaDB
SET GLOBAL log_output = 'TABLE';
SET GLOBAL general_log = 'ON';
mysql.general_log
If you want to output to a log file:
SET GLOBAL log_output = "FILE";
SET GLOBAL general_log_file = "/path/to/your/logfile.log"
SET GLOBAL general_log = 'ON';
As mentioned by jeffmjack in comments, these settings will be forgetting before next session unless you edit the configuration files (e.g. edit /etc/mysql/my.cnf
, then restart to apply changes).
Now, if you'd like you can tail -f /var/log/mysql/mysql.log
i think a loop can be used.
1 - check if the last index of substring is not the end of the main string.
2 - take a new substring from the last index of the substring to the last index of the main string and check if it contains the search string
3 - repeat the steps in a loop
Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL
I'm not sure what version of Windows introduced this command.
To encode a file:
certutil -encode inputFileName encodedOutputFileName
To decode a file:
certutil -decode encodedInputFileName decodedOutputFileName
There are a number of available verbs and options available to CERTUTIL.
To get a list of nearly all available verbs:
certutil -?
To get help on a particular verb (-encode for example):
certutil -encode -?
To get complete help for nearly all verbs:
certutil -v -?
Mysteriously, the -encodehex
verb is not listed with certutil -?
or certutil -v -?
. But it is described using certutil -encodehex -?
. It is another handy function :-)
Regarding David Morales' comment, there is a poorly documented type option to the -encodehex
verb that allows creation of base64 strings without header or footer lines.
certutil [Options] -encodehex inFile outFile [type]
A type of 1 will yield base64 without the header or footer lines.
See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.
Not investigated, but the -decodehex
verb also has an optional trailing type argument.
In response to Haim Evgi's code, I added !== false to the end for it to work for me
$iPod = stripos($_SERVER['HTTP_USER_AGENT'],"iPod") !== false;
$iPhone = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone") !== false;
$iPad = stripos($_SERVER['HTTP_USER_AGENT'],"iPad") !== false;
$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android") !== false;
Biggest difference is a Web Server handles HTTP requests, while an Application server will execute business logic on any number of protocols.
When using jQuery, return false
is doing 3 separate things when you call it:
event.preventDefault();
event.stopPropagation();
See jQuery Events: Stop (Mis)Using Return False for more information and examples.
I just spent the better part of 3 days wrestling with this. I'm working on an application that loads other applications into itself while maintaining a fixed header and a fixed footer. Here's what I've come up with. (I also used EasyXDM, with success, but pulled it out later to use this solution.)
Make sure to run this code AFTER the <iframe>
exists in the DOM. Put it into the page that pulls in the iframe (the parent).
// get the iframe
var theFrame = $("#myIframe");
// set its height to the height of the window minus the combined height of fixed header and footer
theFrame.height(Number($(window).height()) - 80);
function resizeIframe() {
theFrame.height(Number($(window).height()) - 80);
}
// setup a resize method to fire off resizeIframe.
// use timeout to filter out unnecessary firing.
var TO = false;
$(window).resize(function() {
if (TO !== false) clearTimeout(TO);
TO = setTimeout(resizeIframe, 500); //500 is time in miliseconds
});
To call GET,POST,DELETE,PUT All kind of request, i have created one common function
function CallAPI($method, $api, $data) {
$url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case "GET":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "POST":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
break;
case "PUT":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
break;
}
$response = curl_exec($curl);
$data = json_decode($response);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check the HTTP Status code
switch ($httpCode) {
case 200:
$error_status = "200: Success";
return ($data);
break;
case 404:
$error_status = "404: API Not found";
break;
case 500:
$error_status = "500: servers replied with an error.";
break;
case 502:
$error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
break;
case 503:
$error_status = "503: service unavailable. Hopefully they'll be OK soon!";
break;
default:
$error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
break;
}
curl_close($curl);
echo $error_status;
die;
}
CALL Delete Method
$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);
CALL Post Method
$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);
CALL Get Method
$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);
CALL Put Method
$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);