There's no need to manually put class files on Tomcat. Just make sure your package declaration for Member
is correctly defined as
package pageNumber;
since, that's the only application package you're importing in your JSP.
<%@ page import="pageNumber.*, java.util.*, java.io.*" %>
Here's the Query Analyzer template for an in-line function - it returns 2 values by default:
-- =============================================
-- Create inline function (IF)
-- =============================================
IF EXISTS (SELECT *
FROM sysobjects
WHERE name = N'<inline_function_name, sysname, test_function>')
DROP FUNCTION <inline_function_name, sysname, test_function>
GO
CREATE FUNCTION <inline_function_name, sysname, test_function>
(<@param1, sysname, @p1> <data_type_for_param1, , int>,
<@param2, sysname, @p2> <data_type_for_param2, , char>)
RETURNS TABLE
AS
RETURN SELECT @p1 AS c1,
@p2 AS c2
GO
-- =============================================
-- Example to execute function
-- =============================================
SELECT *
FROM <owner, , dbo>.<inline_function_name, sysname, test_function>
(<value_for_@param1, , 1>,
<value_for_@param2, , 'a'>)
GO
I just wanted to bring a small contribution, because I have been able to debug on my Nexus 5 device on Windows 8, without doing all of this.
When I plugged it, there was no yellow exclamation mark within the device manager. So for me, the drivers was OK. But the device was not listed within my eclipse ddms. After a little bit of searching, It was just an option to change in the device settings. By default, the Nexus 5 usb computer connection is in MTP mode (Media Device).
What you have to do is:
I hope this will help!
Make sure there's no hidden whitespace at the start of your XML file. Also maybe include encoding="UTF-8" (or 16? No clue) in the node.
Verification, do not forget the to_s
def nottolonng?(value)
if value.to_s.length <=8
return true
else
return false
end
end
First install newtonsoft.json
package to Visual Studio
using NuGet Package Manager
then add the following code:
ClassName ObjectName = JsonConvert.DeserializeObject < ClassName > (jsonObject);
You can declare an event with the following code:
public event EventHandler MyOwnEvent;
A custom delegate type instead of EventHandler can be used if needed.
You can find detailed information/tutorials on the use of events in .NET in the article Events Tutorial (MSDN).
When you get this error some annotation is missing. I was missing @service annotation on service. When I added that annotation it worked fine for me.
You Need to create a notification channel for API level above 26(oreo).
`NotificationChannel channel = new NotificationChannel(STRING_ID,CHANNEL_NAME,NotificationManager.IMPORTANCE_HIGH);
STRING_ID = string notification channelid is the same as in Notification.Builder like this
`Notification notification = new Notification.Builder(this,STRING_ID)
.setSmallIcon(android.R.drawable.ic_menu_help)
.setContentTitle("Hello Notification")
.setContentText("It is Working")
.setContentIntent(pendingIntent)
.build();`
Channel id in the notification and in the notification should be same Whole code is like this.. `
@RequiresApi(api = Build.VERSION_CODES.O)
private void callNotification2() {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,11,
intent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this,"22")
.setSmallIcon(android.R.drawable.ic_menu_help)
.setContentTitle("Hello Notification")
.setContentText("It is Working")
.setContentIntent(pendingIntent)
.build();
NotificationChannel channel = new
NotificationChannel("22","newName",NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
manager.notify(11,notification);
}'
I actually just overwrite anything I want to change in the site.css, you should load the site.css after bootstrap so it will overwrite the classes. What I have done now is just made my own classes with my own little bootstrap theme. Little things like this
.navbar-nav li a{
color: #fff;
font-size: 15px;
margin-top: 9px;
}
.navbar-nav li a:hover{
background-color: #18678E;
height: 61px;
}
I also changed the likes of the validations errors the same way.
If you are unaware of the position to replace, use list iterator to find and replace element ListIterator.set(E e)
ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next.equals("Two")) {
//Replace element
iterator.set("New");
}
}
You can have only one default export which you declare like:
export default App;
or
export default class App extends React.Component {...
and later do import App from './App'
If you want to export something more you can use named exports which you declare without default
keyword like:
export {
About,
Contact,
}
or:
export About;
export Contact;
or:
export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);
and later you import them like:
import App, { About, Contact } from './App';
EDIT:
There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js
file. Other than that why export anything if it is no used outside the file?. Correct main.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'
class App extends React.Component {
...
}
class Home extends React.Component {
...
}
class About extends React.Component {
...
}
class Contact extends React.Component {
...
}
ReactDOM.render((
<Router history = {browserHistory}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />
<Route path = "about" component = {About} />
<Route path = "contact" component = {Contact} />
</Route>
</Router>
), document.getElementById('app'))
EDIT2:
another thing is that this tutorial is based on react-router-V3 which has different api than v4.
Following is the list of conversion characters that you may use in the printf:
%d – for signed decimal integer
%f – for the floating point
%o – octal number
%c – for a character
%s – a string
%i – use for integer base 10
%u – for unsigned decimal number
%x – hexadecimal number
%% – for writing % (percentage)
%n – for new line = \n
Edit: the api call has been removed by google. so it is no longer functioning.
Agree with Pareshkumar's answer. Now there is a python wrapper googlefinance for the url call.
Install googlefinance
$pip install googlefinance
It is easy to get current stock price:
>>> from googlefinance import getQuotes
>>> import json
>>> print json.dumps(getQuotes('AAPL'), indent=2)
[
{
"Index": "NASDAQ",
"LastTradeWithCurrency": "129.09",
"LastTradeDateTime": "2015-03-02T16:04:29Z",
"LastTradePrice": "129.09",
"Yield": "1.46",
"LastTradeTime": "4:04PM EST",
"LastTradeDateTimeLong": "Mar 2, 4:04PM EST",
"Dividend": "0.47",
"StockSymbol": "AAPL",
"ID": "22144"
}
]
Google finance is a source that provides real-time stock data. There are also other APIs from yahoo, such as yahoo-finance, but they are delayed by 15min for NYSE and NASDAQ stocks.
Use the PHP function serialize()
to convert arrays to strings. These strings can easily be stored in MySQL database. Using unserialize()
they can be converted to arrays again if needed.
Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:
Given what you wrote, I suspect whatever converts the database data to XML is broken; it's propagating non-XML characters.
Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.
If the converter output looks good, the problem is in your XML consumer; it's inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.
Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn't, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.
Just add this in you styles.xml. The colorPrimary is for the action bar and the colorPrimaryDark is for the status bar.
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:colorPrimary">@color/primary</item>
<item name="android:colorPrimaryDark">@color/primary_dark</item>
</style>
This picture from developer android explains more about color pallete. You can read more on this link.
if you need the category ID, you would get it via get_query_var, that is capable of retrieving all publicly queryble variables.
$category_id = get_query_var('cat');
here is an example to get the category name
$category_name = get_query_var('category_name');
and of course the all mighty get_queried_object
$queried_object = get_queried_object();
that is returning the complete taxonomy term object (when used on a taxonomy-archive page..)
check this out :)
var traingIds = "[1,2]"; // ${triningIdArray} this value getting from server
alert(traingIds); // alerts [1,2]
var type = typeof(traingIds);
alert(type); // // alerts String
//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds); // alerts 1,2
var trainindIdArray = traingIds.split(',');
?for(i = 0; i< trainindIdArray.length; i++){
alert(trainindIdArray[i]); //outputs individual numbers in array
}?
Sets don't have a join
method but you can use str.join
instead.
', '.join(set_3)
The str.join
method will work on any iterable object including lists and sets.
Note: be careful about using this on sets containing integers; you will need to convert the integers to strings before the call to join. For example
set_4 = {1, 2}
', '.join(str(s) for s in set_4)
trainosais - you are right, validation should be done on a directive level. It's clean, modular and allows for reusability of code. When you have basic validation like that in a controller you have write it over and over again for different forms. That's super anti-dry.
I had a similar problem recently and sorted it out with a simple directive, which plugs in to the parsers pipeline, therefore stays consistent with Angular architecture. Chaining validators makes it very easy to reuse and that should be considered the only solution in my view.
Without further ado, here's the simplified markup:
<form novalidate="novalidate">
<label>email</label>
<input type="text"
ng-model="email"
name="email" />
<label>email repeated</label>
<input ng-model="emailRepeated"
same-as="email"
name="emailRepeated" />
</form>
And the JS code:
angular.module('app', [])
.directive('sameAs', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
ngModel.$parsers.unshift(validate);
// Force-trigger the parsing pipeline.
scope.$watch(attrs.sameAs, function() {
ngModel.$setViewValue(ngModel.$viewValue);
});
function validate(value) {
var isValid = scope.$eval(attrs.sameAs) == value;
ngModel.$setValidity('same-as', isValid);
return isValid ? value : undefined;
}
}
};
});
The directive hooks into the parsers pipeline in order to get notified of any changes to the view value and set validity based on comparison of the new view value and the value of the reference field. That bit is easy. The tricky bit is sniffing for changes on the reference field. For that the directive sets a watcher on the reference value and force-triggeres the parsing pipeline, in order to get all the validators run again.
If you want to play with it, here is my pen: http://codepen.io/jciolek/pen/kaKEn
I hope it helps, Jacek
I have done this in a project a long time ago. The code given below write a whole rows bold with specific column names and all of these columns are written in bold format.
private void WriteColumnHeaders(DataColumnCollection columnCollection, int row, int column)
{
// row represent particular row you want to bold its content.
for (i = 0; i < columnCollection.Count; i++)
{
DataColumn col = columnCollection[i];
xlWorkSheet.Cells[row, column + i + 1] = col.Caption;
// Some Font Styles
xlWorkSheet.Cells[row, column + i + 1].Style.Font.Bold = true;
xlWorkSheet.Cells[row, column + i + 1].Interior.Color = Color.FromArgb(192, 192, 192);
//xlWorkSheet.Columns[i + 1].ColumnWidth = xlWorkSheet.Columns[i+1].ColumnWidth + 10;
}
}
You must pass value of row 0 so that first row of your excel sheets have column headers with bold font size. Just change DataColumnCollection
to your columns name and change col.Caption
to specific column name.
Alternate
You may do this to cell of excel sheet you want bold.
xlWorkSheet.Cells[row, column].Style.Font.Bold = true;
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
names = [];
$('input[name=text], textarea').each(
function(index){
var input = $(this);
names.push( input.attr('name') );
//input.attr('id');
}
);
it select all textboxes and textarea in your DOM, where $.each function iterates to provide name of ecah element.
View more detail from my previous answer I have created an nuget package Nuget
Code on Github
sample : you can use :
string login = "";
string domain = "";
string password = "";
using (UserImpersonation user = new UserImpersonation(login, domain, password))
{
if (user.ImpersonateValidUser())
{
File.WriteAllText("test.txt", "your text");
Console.WriteLine("File writed");
}
else
{
Console.WriteLine("User not connected");
}
}
Vieuw the full code :
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
/// <summary>
/// Object to change the user authticated
/// </summary>
public class UserImpersonation : IDisposable
{
/// <summary>
/// Logon method (check athetification) from advapi32.dll
/// </summary>
/// <param name="lpszUserName"></param>
/// <param name="lpszDomain"></param>
/// <param name="lpszPassword"></param>
/// <param name="dwLogonType"></param>
/// <param name="dwLogonProvider"></param>
/// <param name="phToken"></param>
/// <returns></returns>
[DllImport("advapi32.dll")]
private static extern bool LogonUser(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
/// <summary>
/// Close
/// </summary>
/// <param name="handle"></param>
/// <returns></returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
private WindowsImpersonationContext _windowsImpersonationContext;
private IntPtr _tokenHandle;
private string _userName;
private string _domain;
private string _passWord;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
/// <summary>
/// Initialize a UserImpersonation
/// </summary>
/// <param name="userName"></param>
/// <param name="domain"></param>
/// <param name="passWord"></param>
public UserImpersonation(string userName, string domain, string passWord)
{
_userName = userName;
_domain = domain;
_passWord = passWord;
}
/// <summary>
/// Valiate the user inforamtion
/// </summary>
/// <returns></returns>
public bool ImpersonateValidUser()
{
bool returnValue = LogonUser(_userName, _domain, _passWord,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref _tokenHandle);
if (false == returnValue)
{
return false;
}
WindowsIdentity newId = new WindowsIdentity(_tokenHandle);
_windowsImpersonationContext = newId.Impersonate();
return true;
}
#region IDisposable Members
/// <summary>
/// Dispose the UserImpersonation connection
/// </summary>
public void Dispose()
{
if (_windowsImpersonationContext != null)
_windowsImpersonationContext.Undo();
if (_tokenHandle != IntPtr.Zero)
CloseHandle(_tokenHandle);
}
#endregion
}
With PYTHONPATH set as in your example, you should be able to do
python -m gmbx
-m
option will make Python search for your module in paths Python usually searches modules in, including what you added to PYTHONPATH. When you run interpreter like python gmbx.py
, it looks for particular file and PYTHONPATH does not apply.
Install a stable version instead of the latest one, I have downgrade my version to node-v0.10.29-x86.msi
from 'node-v0.10.33-x86.msi'
and it is working well for me!
See the article Django Documentation
ur_data_model.objects.filter(ur_date_field__gte=datetime(2009, 8, 22), ur_date_field__lt=datetime(2009, 8, 23))
If you will be doing many searches of the array, AND matching always is defined as string equivalence, then you can normalize your data and use a hash.
my @strings = qw( aAa Bbb cCC DDD eee );
my %string_lut;
# Init via slice:
@string_lut{ map uc, @strings } = ();
# or use a for loop:
# for my $string ( @strings ) {
# $string_lut{ uc($string) } = undef;
# }
#Look for a string:
my $search = 'AAa';
print "'$string' ",
( exists $string_lut{ uc $string ? "IS" : "is NOT" ),
" in the array\n";
Let me emphasize that doing a hash lookup is good if you are planning on doing many lookups on the array. Also, it will only work if matching means that $foo eq $bar
, or other requirements that can be met through normalization (like case insensitivity).
Sounds like you need to change the path to your java
executable to match the newest version.
Basically, installing the latest Java does not necessarily mean your machine is configured to use the latest version. You didn't mention any platform details, so that's all I can say.
Try this,
x in mylist
is better and more readable than x in mylist[:]
and your len(x)
should be equal to 3
.
>>> mylist = [[1,2,3],[4,5,6,7],[8,9,10]]
>>> for x in mylist:
... if len(x)==3:
... print x
...
[1, 2, 3]
[8, 9, 10]
or if you need more pythonic use list-comprehensions
>>> [x for x in mylist if len(x)==3]
[[1, 2, 3], [8, 9, 10]]
>>>
Terminal type:
Last login: Thu Dec 20 08:28:43 on console
~ ? sudo spctl --master-disable
Password:
~ ? spctl --status
assessments disabled
~ ?
System Preferences->Security & Privacy
Wrote a small class for doing this cleanly.
import tempfile
class FileModifierError(Exception):
pass
class FileModifier(object):
def __init__(self, fname):
self.__write_dict = {}
self.__filename = fname
self.__tempfile = tempfile.TemporaryFile()
with open(fname, 'rb') as fp:
for line in fp:
self.__tempfile.write(line)
self.__tempfile.seek(0)
def write(self, s, line_number = 'END'):
if line_number != 'END' and not isinstance(line_number, (int, float)):
raise FileModifierError("Line number %s is not a valid number" % line_number)
try:
self.__write_dict[line_number].append(s)
except KeyError:
self.__write_dict[line_number] = [s]
def writeline(self, s, line_number = 'END'):
self.write('%s\n' % s, line_number)
def writelines(self, s, line_number = 'END'):
for ln in s:
self.writeline(s, line_number)
def __popline(self, index, fp):
try:
ilines = self.__write_dict.pop(index)
for line in ilines:
fp.write(line)
except KeyError:
pass
def close(self):
self.__exit__(None, None, None)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
with open(self.__filename,'w') as fp:
for index, line in enumerate(self.__tempfile.readlines()):
self.__popline(index, fp)
fp.write(line)
for index in sorted(self.__write_dict):
for line in self.__write_dict[index]:
fp.write(line)
self.__tempfile.close()
Then you can use it this way:
with FileModifier(filename) as fp:
fp.writeline("String 1", 0)
fp.writeline("String 2", 20)
fp.writeline("String 3") # To write at the end of the file
you can use
style="display:none"
Ex:
<asp:TextBox ID="txbProv" runat="server" style="display:none"></asp:TextBox>
In your php.ini file check for display_errors
. I think it is off.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
Use this one. It will fix it.
#ibox_footer {
padding-top: 3px;
position: absolute;
height: 20px;
margin-bottom: 0;
bottom: 0;
width: 100%;
}
nchar[(n)]
(national character)
n
defines the string length and must be a value from 1 through 4,000.n
bytes.nvarchar [(n | max)]
(national character varying.)
n
defines the string length and can be a value from 1 through 4,000.max
indicates that the maximum storage size is 2^31-1 bytes (2 GB).char [(n)]
(character)
non-Unicode
string data.n
defines the string length and must be a value from 1 through 8,000.n
bytes.varchar [(n | max)]
(character varying)
n
defines the string length and can be a value from 1 through 8,000.max
indicates that the maximum storage size is 2^31-1 bytes (2 GB).In pretty much all modern languages, null logically refers to pointers (or references) not having a value, or a variable that is not initialized. 0 is the integer value of zero, and false is the boolean value of, well, false. To make things complicated, in C, for example, null, 0, and false are all represented the exact same way. I don't know how it works in PHP.
Then, to complicate things more, databases have a concept of null, which means missing or not applicable, and most languages don't have a direct way to map a DBNull to their null. Until recently, for example, there was no distinction between an int being null and being zero, but that was changed with nullable ints.
Sorry to make this sound complicated. It's just that this has been a harry sticking point in languages for years, and up until recently, it hasn't had any clear resolution anywhere. People used to just kludge things together or make blank or 0 represent nulls in the database, which doesn't always work too well.
I am using a powershell build and couldn't get npm to run without changing the current directory.
Ended up using the start command and just specifying the working directory:
start "npm" -ArgumentList "install --warn" -wo $buildFolder
If you are using Java 8 and don't want to manipulate CompletableFuture
s, I have written a tool to retrieve results for a List<Future<T>>
using streaming. The key is that you are forbidden to map(Future::get)
as it throws.
public final class Futures
{
private Futures()
{}
public static <E> Collector<Future<E>, Collection<E>, List<E>> present()
{
return new FutureCollector<>();
}
private static class FutureCollector<T> implements Collector<Future<T>, Collection<T>, List<T>>
{
private final List<Throwable> exceptions = new LinkedList<>();
@Override
public Supplier<Collection<T>> supplier()
{
return LinkedList::new;
}
@Override
public BiConsumer<Collection<T>, Future<T>> accumulator()
{
return (r, f) -> {
try
{
r.add(f.get());
}
catch (InterruptedException e)
{}
catch (ExecutionException e)
{
exceptions.add(e.getCause());
}
};
}
@Override
public BinaryOperator<Collection<T>> combiner()
{
return (l1, l2) -> {
l1.addAll(l2);
return l1;
};
}
@Override
public Function<Collection<T>, List<T>> finisher()
{
return l -> {
List<T> ret = new ArrayList<>(l);
if (!exceptions.isEmpty())
throw new AggregateException(exceptions, ret);
return ret;
};
}
@Override
public Set<java.util.stream.Collector.Characteristics> characteristics()
{
return java.util.Collections.emptySet();
}
}
This needs an AggregateException
that works like C#'s
public class AggregateException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = -4477649337710077094L;
private final List<Throwable> causes;
private List<?> successfulElements;
public AggregateException(List<Throwable> causes, List<?> l)
{
this.causes = causes;
successfulElements = l;
}
public AggregateException(List<Throwable> causes)
{
this.causes = causes;
}
@Override
public synchronized Throwable getCause()
{
return this;
}
public List<Throwable> getCauses()
{
return causes;
}
public List<?> getSuccessfulElements()
{
return successfulElements;
}
public void setSuccessfulElements(List<?> successfulElements)
{
this.successfulElements = successfulElements;
}
}
This component acts exactly as C#'s Task.WaitAll. I am working on a variant that does the same as CompletableFuture.allOf
(equivalento to Task.WhenAll
)
The reason why I did this is that I am using Spring's ListenableFuture
and don't want to port to CompletableFuture
despite it is a more standard way
found this very clever idea from https://gist.github.com/scottrippey/3428114 for every $.ajax calls it modifies the request and add the token.
// Setup CSRF safety for AJAX:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (options.type.toUpperCase() === "POST") {
// We need to add the verificationToken to all POSTs
var token = $("input[name^=__RequestVerificationToken]").first();
if (!token.length) return;
var tokenName = token.attr("name");
// If the data is JSON, then we need to put the token in the QueryString:
if (options.contentType.indexOf('application/json') === 0) {
// Add the token to the URL, because we can't add it to the JSON data:
options.url += ((options.url.indexOf("?") === -1) ? "?" : "&") + token.serialize();
} else if (typeof options.data === 'string' && options.data.indexOf(tokenName) === -1) {
// Append to the data string:
options.data += (options.data ? "&" : "") + token.serialize();
}
}
});
For adding margins to specified cells, you can use this custom flow layout. https://github.com/voyages-sncf-technologies/VSCollectionViewCellInsetFlowLayout/
extension ViewController : VSCollectionViewDelegateCellInsetFlowLayout
{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemAt indexPath: IndexPath) -> UIEdgeInsets {
if indexPath.item == 0 {
return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
}
return UIEdgeInsets.zero
}
}
A little late to the party, found this while looking for an example of the marker click event. The undefined error the original poster got is because the onClick function is referred to before it's defined. Swap line 2 and 3 and it should work.
The git cherry-pick <commit>
command allows you to take a single commit (from whatever branch) and, essentially, rebase it in your working branch.
Chapter 5 of the Pro Git book explains it better than I can, complete with diagrams and such. (The chapter on Rebasing is also good reading.)
Lastly, there are some good comments on the cherry-picking vs merging vs rebasing in another SO question.
This is similar to Solution 1 from @JSuar...
Assume your original city data is a named range called dataCity
. In a new sheet, enter the following:
A | B
----------------------------------------------------------
1 | =UNIQUE(dataCity) | Count
2 | | =DCOUNTA(dataCity,"City",{"City";$A2})
3 | | [copy down the formula above]
4 | | ...
5 | | ...
While some of the above solutions work, I thought I'd post our eventual solution - which defines a 'ready' method that will fire as soon as FB is initialized and ready to go. It has the advantage over other solutions that it's safe to call either before or after FB is ready.
It can be used like so:
f52.fb.ready(function() {
// safe to use FB here
});
Here's the source file (note that it's defined within a 'f52.fb' namespace).
if (typeof(f52) === 'undefined') { f52 = {}; }
f52.fb = (function () {
var fbAppId = f52.inputs.base.fbAppId,
fbApiInit = false;
var awaitingReady = [];
var notifyQ = function() {
var i = 0,
l = awaitingReady.length;
for(i = 0; i < l; i++) {
awaitingReady[i]();
}
};
var ready = function(cb) {
if (fbApiInit) {
cb();
} else {
awaitingReady.push(cb);
}
};
window.fbAsyncInit = function() {
FB.init({
appId: fbAppId,
xfbml: true,
version: 'v2.0'
});
FB.getLoginStatus(function(response){
fbApiInit = true;
notifyQ();
});
};
return {
/**
* Fires callback when FB is initialized and ready for api calls.
*/
'ready': ready
};
})();
Could you not use typeof(object) to compare against
Use the FormBorderStyle
property of your Form
:
this.FormBorderStyle = FormBorderStyle.FixedDialog;
I made this codepen to help you out!
const navbar = document.querySelector('#nav')
window.addEventListener('scroll', function(e) {
const lastPosition = window.scrollY
if (lastPosition > 50 ) {
navbar.classList.add('active')
} else if (navbar.classList.contains('active')) {
navbar.classList.remove('active')
} else {
navbar.classList.remove('active')
}
})
Try this,
for (char[] temp : box) {
System.err.println(Arrays.toString(temp).replaceAll(",", " ").replaceAll("\\[|\\]", ""));
}
Common Answer: itoa()
This is bad. itoa
is non-standard, as pointed out here.
To solve the issue try to repair the .net framework 4
and then run the command
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
Your use of it isn't a hack, though like many things in C++, mutable can be hack for a lazy programmer who doesn't want to go all the way back and mark something that shouldn't be const as non-const.
Put the line
$this->db->order_by("course_name","desc");
at top of your query. Like
$this->db->order_by("course_name","desc");$this->db->select('*');
$this->db->where('tennant_id',$tennant_id);
$this->db->from('courses');
$query=$this->db->get();
return $query->result();
Class Assertions in org.junit.jupiter.api
Use:
public static void assertArrayEquals(int[] expected,
int[] actual)
Two issues I can see here:
The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.
The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.
I figured it out!
With almost 2 hours worth of trial and error, i figured it out.
This WORKS and is what you do to pass variables to remote job:
def handle = triggerRemoteJob(remoteJenkinsName: 'remoteJenkins', job: 'RemoteJob' paramters: "param1=${env.PARAM1}\nparam2=${env.param2}")
Use \n to separate two parameters, no spaces..
As opposed to parameters: '''someparams'''
we use paramters: "someparams"
the " ... " is what gets us the values of the desired variables. (These are double quotes, not two single quotes)
the ''' ... ''' or ' ... ' will not get us those values. (Three single quotes or just single quotes)
All parameters here are defined in environment{} block at the start of the pipeline and are modified in stages>steps>scripts wherever necessary.
I also tested and found that when you use " ... " you cannot use something like ''' ... "..." ''' or "... '..'..." or any combination of it...
The catch here is that when you are using "..." in parameters section, you cannot pass a string parameter; for example This WILL NOT WORK:
def handle = triggerRemoteJob(remoteJenkinsName: 'remoteJenkins', job: 'RemoteJob' paramters: "param1=${env.PARAM1}\nparam2='param2'")
if you want to pass something like the one above, you will need to set an environment variable param2='param2' and then use ${env.param2} in the parameters section of remote trigger plugin step
Somewhere around r59 this gets easier (rotate around x):
bb.GraphicsEngine.prototype.calcRotation = function ( obj, rotationX)
{
var euler = new THREE.Euler( rotationX, 0, 0, 'XYZ' );
obj.position.applyEuler(euler);
}
I stumbled upon this problem during attempt to dockerise Avahi which needs to be aware of its public IP to function properly. Assigning static IP to the container is tricky due to lack of support for static IP assignment in Docker.
This article describes technique how to assign static IP to the container on Debian:
Docker service should be started with DOCKER_OPTS="--bridge=br0 --ip-masq=false --iptables=false"
. I assume that br0
bridge is already configured.
Container should be started with --cap-add=NET_ADMIN --net=bridge
Inside container pre-up ip addr flush dev eth0
in /etc/network/interfaces
can be used to dismiss IP address assigned by Docker as in following example:
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
pre-up ip addr flush dev eth0
address 192.168.0.249
netmask 255.255.255.0
gateway 192.168.0.1
/etc/init.d/networking start
. Also entry script needs to edit or populate /etc/hosts
file in order to remove references to Docker-assigned IP.Just put ojdbc6.jar
in class path, so that we can fix CallbaleStatement
exception:
oracle.jdbc.driver.T4CPreparedStatement.setBinaryStream(ILjava/io/InputStream;J)V)
in Oracle.
Since I can't add a comment. @ruaka To make the example more readable write it like this
full_string="I love Suzy and Mary"
search_string="Suzy"
replace_string="Sara"
my_string=${full_string/$search_string/$replace_string}
or
my_string=${full_string/Suzy/Sarah}
var divs = $("div[class*='alert-box']");
I had a similar problem; the anchor text in my Bootstrap4 navbar wasn't centered. Simply added text-center
in the anchor's class.
A tuple consists of a number of values separated by commas. like
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
tuple are index based (and also immutable) in Python.
Here in this case x = rows[1][1] + " " + rows[1][2]
have only two index 0, 1 available but you are trying to access the 3rd index.
Building on pkozlowski.opensource's answer, I've added a way to have dynamic input names that also work with ngMessages. Note the ng-init
part on the ng-form
element and the use of furryName
. furryName
becomes the variable name that contains the variable value for the input
's name
attribute.
<ion-item ng-repeat="animal in creatures track by $index">
<ng-form name="animalsForm" ng-init="furryName = 'furry' + $index">
<!-- animal is furry toggle buttons -->
<input id="furryRadio{{$index}}"
type="radio"
name="{{furryName}}"
ng-model="animal.isFurry"
ng-value="radioBoolValues.boolTrue"
required
>
<label for="furryRadio{{$index}}">Furry</label>
<input id="hairlessRadio{{$index}}"
name="{{furryName}}"
type="radio"
ng-model="animal.isFurry"
ng-value="radioBoolValues.boolFalse"
required
>
<label for="hairlessRadio{{$index}}">Hairless</label>
<div ng-messages="animalsForm[furryName].$error"
class="form-errors"
ng-show="animalsForm[furryName].$invalid && sectionForm.$submitted">
<div ng-messages-include="client/views/partials/form-errors.ng.html"></div>
</div>
</ng-form>
</ion-item>
I know this question is about Linux, but in case someone stumbles on this problem on Mac like I did here is the solution for that. I had the exact same problem on Mac because ffmpeg
is not installed by default apparently, and so I could solve it using:
brew install yasm
brew install ffmpeg
How to do what @connor said:
iOS
platforms/ios
on XCodeio.ionic.starter
in all files for a unique identifierionic cordova run ios --device --livereload
I guess the problem you have is related to the dynamic height that the fixed navbar at the top has. For example, when a user logs in, you need to display some kind of "Hello [User Name]" and when the name is too wide, the navbar needs to use more height so this text doesn't overlap with the navbar menu. As the navbar has the style "position: fixed", the body stays underneath it and a taller part of it becomes hidden so you need to "dynamically" change the padding at the top every time the navbar height changes which would happen in the following case scenarios:
This dynamicity is not covered by regular CSS so I can only think of one way to solve this problem if the user has JavaScript enabled. Please try the following jQuery code snippet to resolve case scenarios 1 and 2; for case scenario 3 please remember to call the function onResize() after any change in the navbar content:
var onResize = function() {_x000D_
// apply dynamic padding at the top of the body according to the fixed navbar height_x000D_
$("body").css("padding-top", $(".navbar-fixed-top").height());_x000D_
};_x000D_
_x000D_
// attach the function to the window resize event_x000D_
$(window).resize(onResize);_x000D_
_x000D_
// call it also when the page is ready after load or reload_x000D_
$(function() {_x000D_
onResize();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
_x000D_
You can plot several columns at once by supplying a list of column names to the plot
's y
argument.
df.plot(x="X", y=["A", "B", "C"], kind="bar")
This will produce a graph where bars are sitting next to each other.
In order to have them overlapping, you would need to call plot
several times, and supplying the axes to plot to as an argument ax
to the plot.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
y = np.random.rand(10,4)
y[:,0]= np.arange(10)
df = pd.DataFrame(y, columns=["X", "A", "B", "C"])
ax = df.plot(x="X", y="A", kind="bar")
df.plot(x="X", y="B", kind="bar", ax=ax, color="C2")
df.plot(x="X", y="C", kind="bar", ax=ax, color="C3")
plt.show()
td
cellThe answers provided do a great job to right-align text in a td
cell.
This might not be the solution when you're looking to align a block element as commented in the accepted answer. To achieve such with a block element, I have found it useful to make use of margins;
selector {
margin: top right bottom left;
}
td {
/* there is a shorthand, TODO! */
margin: auto 0 auto auto;
}
td {
margin: auto auto auto auto;
}
/* or the short-hand */
margin: auto;
td {
margin: auto;
}
Alternatively, you could make you td
content display inline-block
if that's an option, but that may distort the position of its child elements.
You may not want absolute positioning because it breaks the reflow: in some circumstances, a better solution is to make the grandparent element display:table;
and the parent element display:table-cell;vertical-align:bottom;
. After doing this, you should be able to give the the child elements display:inline-block;
and they will automagically flow towards the bottom of the parent.
Just add to string object extention methods.
public static class StringEx
{
public static bool Contains(this String str, string[] Arr, StringComparison comp)
{
if (Arr != null)
{
foreach (string s in Arr)
{
if (str.IndexOf(s, comp)>=0)
{ return true; }
}
}
return false;
}
public static bool Contains(this String str,string[] Arr)
{
if (Arr != null)
{
foreach (string s in Arr)
{
if (str.Contains(s))
{ return true; }
}
}
return false;
}
}
usage:
use namespase that contains this class;
var sPortCode = Database.DischargePorts
.Where(p => p.PortName.Contains(new string [] {"BALTIMORE"}, StringComparison.CurrentCultureIgnoreCase) )
.Single().PortCode;
This one worked for me:
df=df.sort_values(by=[2])
Whereas:
df=df.sort_values(by=['2'])
is not working.
you could keep your files untracked after
git rm -r --cached <file>
add your files with
git add -u
them push or do whatever you want.
exit
is a helper for the interactive shell - sys.exit
is intended for use in programs.
The
site
module (which is imported automatically during startup, except if the-S
command-line option is given) adds several constants to the built-in namespace (e.g.exit
). They are useful for the interactive interpreter shell and should not be used in programs.
Technically, they do mostly the same: raising SystemExit
. sys.exit
does so in sysmodule.c:
static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
PyObject *exit_code = 0;
if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
return NULL;
/* Raise SystemExit so callers may catch it or clean up. */
PyErr_SetObject(PyExc_SystemExit, exit_code);
return NULL;
}
While exit
is defined in site.py and _sitebuiltins.py, respectively.
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()
).
@echo off
color 0a
set /p language=
if %language% == DE (
goto LGDE
) else (
if %language% == EN (
goto LGEN
) else (
echo N/A
)
:LGDE
(code)
:LGEN
(code)
Python lists were not made to operate on the beginning of the list and are very ineffective at this operation.
While you can write
mylist = [1, 2 ,3 ,4]
mylist.pop(0)
It's very inefficient.
If you only want to delete items from your list, you can do this with del
:
del mylist[:n]
Which is also really fast:
In [34]: %%timeit
help=range(10000)
while help:
del help[:1000]
....:
10000 loops, best of 3: 161 µs per loop
If you need to obtain elements from the beginning of the list, you should use collections.deque
by Raymond Hettinger and its popleft()
method.
from collections import deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
A comparison:
In [30]: %%timeit
....: help=range(10000)
....: while help:
....: help.pop(0)
....:
100 loops, best of 3: 17.9 ms per loop
In [33]: %%timeit
help=deque(range(10000))
while help:
help.popleft()
....:
1000 loops, best of 3: 812 µs per loop
I met the same problem. I found the solution in the solution from kb.vmware.com.
It works for me by adding
usb.quirks.device0 = "0xvid:0xpid skip-refresh"
Detail as below:
vmx | USB: Found device [name:Apple\ IR\ Receiver vid:05ac pid:8240 path:13/7/2 speed:full family:hid]
The line has the name of the USB device and its vid and pid information. Make a note of the vid and pid values.
usb.quirks.device0 = "0xvid:0xpid skip-reset"
For example, for the Apple device found in step 2, this line is:
usb.quirks.device0 = "0x05ac:0x8240 skip-reset"
usb.quirks.device0 = "0xvid:0xpid skip-refresh"
usb.quirks.device0 = "0xvid:0xpid skip-setconfig"
usb.quirks.device0 = "0xvid:0xpid skip-reset, skip-refresh, skip-setconfig"
Notes:
Refer this to see in detail.
Update the create
action as below:
def create
...
respond_to do |format|
if @reservation.save
format.html do
redirect_to '/'
end
format.json { render json: @reservation.to_json }
else
format.html { render 'new'} ## Specify the format in which you are rendering "new" page
format.json { render json: @reservation.errors } ## You might want to specify a json format as well
end
end
end
You are using respond_to
method but anot specifying the format in which a new
page is rendered. Hence, the error ActionController::UnknownFormat
.
You are getting something wrong... RTSP is a realtime streaming protocol. Meaning, you can stream whatever you want in real time. So you can use it to stream LIVE content (no matter what it is, video, audio, text, presentation...). RTP is a transport protocol which is used to transport media data which is negotiated over RTSP.
You use RTSP to control media transmission over RTP. You use it to setup, play, pause, teardown the stream...
So, if you want your server to just start streaming when the URL is requested, you can implement some sort of RTP-only server. But if you want more control and if you are streaming live video, you must use RTSP, because it transmits SDP and other important decoding data.
Read the documents I linked here, they are a good starting point.
Download numpy-1.9.2+mkl-cp27-none-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy .
Copy the file to C:\Python27\Scripts
Run cmd from the above location and type
pip install numpy-1.9.2+mkl-cp27-none-win32.whl
You will hopefully get the below output:
Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2
Hope that works for you.
EDIT 1
Adding @oneleggedmule 's suggestion:
You can also run the following command in the cmd:
pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl
Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"
use /c as a cmd argument to close cmd.exe once its finish processing your commands
/somepath/{variable:.+}
works in Java requestMapping
tag.
You want to add libraries to your project and in doing so you have two options as you yourself identified:
Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.
This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).
Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.
As for the other alernatives you have either global libraries using Library Manager
or jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager
.
we have to create your own docker volume mapped with the host directory before we mention in the docker-compose.yml as external
1.Create volume named share
docker volume create --driver local \
--opt type=none \
--opt device=/home/mukundhan/share \
--opt o=bind share
2.Use it in your docker-compose
version: "3"
volumes:
share:
external: true
services:
workstation:
container_name: "workstation"
image: "ubuntu"
stdin_open: true
tty: true
volumes:
- share:/share:consistent
- ./source:/source:consistent
working_dir: /source
ipc: host
privileged: true
shm_size: '2gb'
db:
container_name: "db"
image: "ubuntu"
stdin_open: true
tty: true
volumes:
- share:/share:consistent
working_dir: /source
ipc: host
This way we can share the same directory with many services running in different containers
//Javascript file 1
localStorage.setItem('Data',10);
//Javascript file 2
var number=localStorage.getItem('Data');
Don't forget to link your JS files in html :)
appsettings.json:
"MySetting": {
"MyValues": [
"C#",
"ASP.NET",
"SQL"
]
},
MySetting class:
namespace AspNetCore.API.Models
{
public class MySetting : IMySetting
{
public string[] MyValues { get; set; }
}
public interface IMySetting
{
string[] MyValues { get; set; }
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<MySetting>(Configuration.GetSection(nameof(MySetting)));
services.AddSingleton<IMySetting>(sp => sp.GetRequiredService<IOptions<MySetting>>().Value);
...
}
Controller.cs
public class DynamicController : ControllerBase
{
private readonly IMySetting _mySetting;
public DynamicController(IMySetting mySetting)
{
this._mySetting = mySetting;
}
}
Access values:
var myValues = this._mySetting.MyValues;
Microsoft has listened to the cry for supporting installers (MSI) in Visual Studio and release the Visual Studio Installer Projects Extension. You can now create installers in VS2013, download the extension here from the visualstudiogallery.
try this code, it will work for all version of URLs like
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS_HOST} !^www.website.com$ [NC]
RewriteRule ^(.*)$ https://www.website.com/$1 [L,R=301]
Though this seems to be an old question with many answers I'm posting another one, because it provides information about another approaches (looking more convenient than already mentioned), and the question itself remains actual.
First, there is a blogpost Running multiple versions of Google Chrome on Windows. It describes a method which works, but has 2 drawbacks:
Second method is a preferred one, which I'm currently using. It relies on portable versions of Chrome, which become available for every stable release at the portableapps.com.
The only requirement of this method is that existing Chrome version should not run during installation of a next version. Of course, each version must be installed in a separate directory. This way, after installation, you can run Chromes of different versions in parallel. Of course, there is a drawback in this method as well:
Updated for Swift 3
This example will show two methods to programmatically add the following constraints the same as if doing it in the Interface Builder:
Width and Height
Center in Container
override func viewDidLoad() {
super.viewDidLoad()
// set up the view
let myView = UIView()
myView.backgroundColor = UIColor.blue
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
// Add constraints code here (choose one of the methods below)
// ...
}
// width and height
myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true
// center in container
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
// width and height
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true
// center in container
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint
Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint
Style.The HTTP server doesn't send the response header back to the client until you either specify an error or else you start sending data. If you start sending data back to the client, then the server has to send the response head (which contains the status code) first. Once the header has been sent, you can no longer put a status code in the header, obviously.
Here's the usual problem. You start up the page, and send some initial tags (i.e. <head>
). The server then sends those tags to the client, after first sending the HTTP response header with an assumed SUCCESS status. Now you start working on the meat of the page and discover a problem. You can not send an error at this point because the response header, which would contain the error status, has already been sent.
The solution is this: Before you generate any content at all, check if there are going to be any errors. Only then, when you have assured that there will be no problems, can you then start sending content, like the tag.
In your case, it seems like you have a login page that processes a POST request from a form. You probably throw out some initial HTML, then check if the username and password are valid. Instead, you should authenticate the user/password first, before you generate any HTML at all.
A common idiom to change every element of a list looks like this:
for i in range(len(L)):
item = L[i]
# ... compute some result based on item ...
L[i] = result
This can be rewritten using enumerate() as:
for i, item in enumerate(L):
# ... compute some result based on item ...
L[i] = result
See enumerate.
Quick and easy to do:
# Create new directory for MySQL data
mkdir /new/dir/for/mysql
# Set ownership of new directory to match existing one
chown --reference=/var/lib/mysql /new/dir/for/mysql
# Set permissions on new directory to match existing one
chmod --reference=/var/lib/mysql /new/dir/for/mysql
# Stop MySQL before copying over files
service mysql stop
# Copy all files in default directory, to new one, retaining perms (-p)
cp -rp /var/lib/mysql/* /new/dir/for/mysql/
Edit the /etc/my.cnf
file, and under [mysqld]
add this line:
datadir=/new/dir/for/mysql/
If you are using CageFS (with or without CloudLinux) and want to change the MySQL directory, you MUST add the new directory to this file:
/etc/cagefs/cagefs.mp
And then run this command:
cagefsctl --remount-all
There are a few ways of passing data around to different routes. The most correct answer is, of course, query strings. You'll need to ensure that the values are properly encodeURIComponent and decodeURIComponent.
app.get('/category', function(req, res) {
var string = encodeURIComponent('something that would break');
res.redirect('/?valid=' + string);
});
You can snag that in your other route by getting the parameters sent by using req.query
.
app.get('/', function(req, res) {
var passedVariable = req.query.valid;
// Do something with variable
});
For more dynamic way you can use the url
core module to generate the query string for you:
const url = require('url');
app.get('/category', function(req, res) {
res.redirect(url.format({
pathname:"/",
query: {
"a": 1,
"b": 2,
"valid":"your string here"
}
}));
});
So if you want to redirect all req query string variables you can simply do
res.redirect(url.format({
pathname:"/",
query:req.query,
});
});
And if you are using Node >= 7.x you can also use the querystring
core module
const querystring = require('querystring');
app.get('/category', function(req, res) {
const query = querystring.stringify({
"a": 1,
"b": 2,
"valid":"your string here"
});
res.redirect('/?' + query);
});
Another way of doing it is by setting something up in the session. You can read how to set it up here, but to set and access variables is something like this:
app.get('/category', function(req, res) {
req.session.valid = true;
res.redirect('/');
});
And later on after the redirect...
app.get('/', function(req, res) {
var passedVariable = req.session.valid;
req.session.valid = null; // resets session variable
// Do something
});
There is also the option of using an old feature of Express, req.flash
. Doing so in newer versions of Express will require you to use another library. Essentially it allows you to set up variables that will show up and reset the next time you go to a page. It's handy for showing errors to users, but again it's been removed by default. EDIT: Found a library that adds this functionality.
Hopefully that will give you a general idea how to pass information around in an Express application.
Traditionally daemon processes in UNIX were those that were constantly running in background, much like services in Windows.
A daemon thread in Java is one that doesn't prevent the JVM from exiting. Specifically the JVM will exit when only daemon threads remain. You create one by calling the setDaemon()
method on Thread
.
Have a read of Daemon threads.
Use like this,
HTML:
<input type="text" disabled="disabled" class="inputDisabled" value="">
<div id="edit">edit</div>
JS:
$('#edit').click(function(){ // click to
$('.inputDisabled').attr('disabled',false); // removing disabled in this class
});
Let me clarify two points here :
(a = 'b',c)
in function.
The correct order of defining parameter in function are :(a,b,c)
(a = 'b',r= 'j')
(*args)
(**kwargs)
def example(a, b, c=None, r="w" , d=[], *ae, **ab):
(a,b)
are positional parameter
(c=none)
is optional parameter
(r="w")
is keyword parameter
(d=[])
is list parameter
(*ae)
is keyword-only
(*ab)
is var-keyword parameter
so first re-arrange your parameters
so second remove this "len1 = hgt"
it's not allowed in python.
keep in mind the difference between argument and parameters.
This slide show shows how to get both keys updated June 2013.
http://www.slideshare.net/Tweetganic/generate-twitter-applications
This is a problem when you open the project incorrectly. open the project do not import the project
protected $_convertTable = array(
'&' => 'and', '@' => 'at', '©' => 'c', '®' => 'r', 'À' => 'a',
'Á' => 'a', 'Â' => 'a', 'Ä' => 'a', 'Å' => 'a', 'Æ' => 'ae','Ç' => 'c',
'È' => 'e', 'É' => 'e', 'Ë' => 'e', 'Ì' => 'i', 'Í' => 'i', 'Î' => 'i',
'Ï' => 'i', 'Ò' => 'o', 'Ó' => 'o', 'Ô' => 'o', 'Õ' => 'o', 'Ö' => 'o',
'Ø' => 'o', 'Ù' => 'u', 'Ú' => 'u', 'Û' => 'u', 'Ü' => 'u', 'Ý' => 'y',
'ß' => 'ss','à' => 'a', 'á' => 'a', 'â' => 'a', 'ä' => 'a', 'å' => 'a',
'æ' => 'ae','ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e',
'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ò' => 'o', 'ó' => 'o',
'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u',
'û' => 'u', 'ü' => 'u', 'ý' => 'y', 'þ' => 'p', 'ÿ' => 'y', 'A' => 'a',
'a' => 'a', 'A' => 'a', 'a' => 'a', 'A' => 'a', 'a' => 'a', 'C' => 'c',
'c' => 'c', 'C' => 'c', 'c' => 'c', 'C' => 'c', 'c' => 'c', 'C' => 'c',
'c' => 'c', 'D' => 'd', 'd' => 'd', 'Ð' => 'd', 'd' => 'd', 'E' => 'e',
'e' => 'e', 'E' => 'e', 'e' => 'e', 'E' => 'e', 'e' => 'e', 'E' => 'e',
'e' => 'e', 'E' => 'e', 'e' => 'e', 'G' => 'g', 'g' => 'g', 'G' => 'g',
'g' => 'g', 'G' => 'g', 'g' => 'g', 'G' => 'g', 'g' => 'g', 'H' => 'h',
'h' => 'h', 'H' => 'h', 'h' => 'h', 'I' => 'i', 'i' => 'i', 'I' => 'i',
'i' => 'i', 'I' => 'i', 'i' => 'i', 'I' => 'i', 'i' => 'i', 'I' => 'i',
'i' => 'i', '?' => 'ij','?' => 'ij','J' => 'j', 'j' => 'j', 'K' => 'k',
'k' => 'k', '?' => 'k', 'L' => 'l', 'l' => 'l', 'L' => 'l', 'l' => 'l',
'L' => 'l', 'l' => 'l', '?' => 'l', '?' => 'l', 'L' => 'l', 'l' => 'l',
'N' => 'n', 'n' => 'n', 'N' => 'n', 'n' => 'n', 'N' => 'n', 'n' => 'n',
'?' => 'n', '?' => 'n', '?' => 'n', 'O' => 'o', 'o' => 'o', 'O' => 'o',
'o' => 'o', 'O' => 'o', 'o' => 'o', 'Œ' => 'oe','œ' => 'oe','R' => 'r',
'r' => 'r', 'R' => 'r', 'r' => 'r', 'R' => 'r', 'r' => 'r', 'S' => 's',
's' => 's', 'S' => 's', 's' => 's', 'S' => 's', 's' => 's', 'Š' => 's',
'š' => 's', 'T' => 't', 't' => 't', 'T' => 't', 't' => 't', 'T' => 't',
't' => 't', 'U' => 'u', 'u' => 'u', 'U' => 'u', 'u' => 'u', 'U' => 'u',
'u' => 'u', 'U' => 'u', 'u' => 'u', 'U' => 'u', 'u' => 'u', 'U' => 'u',
'u' => 'u', 'W' => 'w', 'w' => 'w', 'Y' => 'y', 'y' => 'y', 'Ÿ' => 'y',
'Z' => 'z', 'z' => 'z', 'Z' => 'z', 'z' => 'z', 'Ž' => 'z', 'ž' => 'z',
'?' => 'z', '?' => 'e', 'ƒ' => 'f', 'O' => 'o', 'o' => 'o', 'U' => 'u',
'u' => 'u', 'A' => 'a', 'a' => 'a', 'I' => 'i', 'i' => 'i', 'O' => 'o',
'o' => 'o', 'U' => 'u', 'u' => 'u', 'U' => 'u', 'u' => 'u', 'U' => 'u',
'u' => 'u', 'U' => 'u', 'u' => 'u', 'U' => 'u', 'u' => 'u', '?' => 'a',
'?' => 'a', '?' => 'ae','?' => 'ae','?' => 'o', '?' => 'o', '?' => 'e',
'?' => 'jo','?' => 'e', '?' => 'i', '?' => 'i', '?' => 'a', '?' => 'b',
'?' => 'v', '?' => 'g', '?' => 'd', '?' => 'e', '?' => 'zh','?' => 'z',
'?' => 'i', '?' => 'j', '?' => 'k', '?' => 'l', '?' => 'm', '?' => 'n',
'?' => 'o', '?' => 'p', '?' => 'r', '?' => 's', '?' => 't', '?' => 'u',
'?' => 'f', '?' => 'h', '?' => 'c', '?' => 'ch','?' => 'sh','?' => 'sch',
'?' => '-', '?' => 'y', '?' => '-', '?' => 'je','?' => 'ju','?' => 'ja',
'?' => 'a', '?' => 'b', '?' => 'v', '?' => 'g', '?' => 'd', '?' => 'e',
'?' => 'zh','?' => 'z', '?' => 'i', '?' => 'j', '?' => 'k', '?' => 'l',
'?' => 'm', '?' => 'n', '?' => 'o', '?' => 'p', '?' => 'r', '?' => 's',
'?' => 't', '?' => 'u', '?' => 'f', '?' => 'h', '?' => 'c', '?' => 'ch',
'?' => 'sh','?' => 'sch','?' => '-','?' => 'y', '?' => '-', '?' => 'je',
'?' => 'ju','?' => 'ja','?' => 'jo','?' => 'e', '?' => 'i', '?' => 'i',
'?' => 'g', '?' => 'g', '?' => 'a', '?' => 'b', '?' => 'g', '?' => 'd',
'?' => 'h', '?' => 'v', '?' => 'z', '?' => 'h', '?' => 't', '?' => 'i',
'?' => 'k', '?' => 'k', '?' => 'l', '?' => 'm', '?' => 'm', '?' => 'n',
'?' => 'n', '?' => 's', '?' => 'e', '?' => 'p', '?' => 'p', '?' => 'C',
'?' => 'c', '?' => 'q', '?' => 'r', '?' => 'w', '?' => 't', '™' => 'tm',
);
From magento, im using it for basically everything
DEPRECATED - this part is outdated so please don't use it.
You can also try this code, if you have for example later added dynamic forms. For example you loaded a window async with ajax and want to submit this form.
$('#cpa-form').live('submit' ,function(e){
e.preventDefault();
// do something
});
UPDATE - you should use the jQuery on() method an try to listen to the document DOM if you want to handle dynamically added content.
Case 1, static version: If you have only a few listeners and your form to handle is hardcoded, then you can listen directly on "document level". I wouldn't use the listeners on document level but I would try to go deeper in the doom tree because it could lead to performance issues (depends on the size of your website and your content)
$('form#formToHandle').on('submit'...
OR
$('form#formToHandle').submit(function(e) {
e.preventDefault();
// do something
});
Case 2, dynamic version: If you already listen to the document in your code, then this way would be good for you. This will also work for code that was added later via DOM or dynamic with AJAX.
$(document).on('submit','form#formToHandle',function(){
// do something like e.preventDefault();
});
OR
$(document).ready(function() {
console.log( "Ready, Document loaded!" );
// all your other code listening to the document to load
$("#formToHandle").on("submit", function(){
// do something
})
});
OR
$(function() { // <- this is shorthand version
console.log( "Ready, Document loaded!" );
// all your other code listening to the document to load
$("#formToHandle").on("submit", function(){
// do something
})
});
floor a;
floor b;
a = -0.340515;
so what to do?
b = 65565 +a;
a = 65565 -b;
or
if(a < 0){
a = 65565-(65565+a);}
Use this.
$dsn1 = 'mysql://user:password@localhost/db1';
$this->db1 = $this->load->database($dsn1, true);
$dsn2 = 'mysql://user:password@localhost/db2';
$this->db2= $this->load->database($dsn2, true);
$dsn3 = 'mysql://user:password@localhost/db3';
$this->db3= $this->load->database($dsn3, true);
Usage
$this->db1 ->insert('tablename', $insert_array);
$this->db2->insert('tablename', $insert_array);
$this->db3->insert('tablename', $insert_array);
byte[] buff = {1, -2, 5, 66};
for(byte c : buff) {
System.out.format("%d ", c);
}
System.out.println();
gets you
1 -2 5 66
Use the lock
statement to do this. (Read here for more information.)
private List<T> _list;
private List<T> MyT
{
get { return _list; }
set
{
//Lock so only one thread can change the value at any given time.
lock (_list)
{
_list = value;
}
}
}
FYI this probably isn't exactly what your asking - you likely want to lock farther out in your code but I can't assume that. Have a look at the lock
keyword and tailor its use to your specific situation.
If you need to, you could lock
in both the get
and set
block using the _list
variable which would make it so a read/write can not occur at the same time.
You haven't stated what you do with the prefsEditor
object after this, but in order to persist the preference data, you also need to use:
prefsEditor.commit();
There should be an easier way to do this, but, depending on what you're trying to do, the best route might be to convert to a regular Python datetime object:
datetime64Obj = np.datetime64('2002-07-04T02:55:41-0700')
print datetime64Obj.astype(object).year
# 2002
print datetime64Obj.astype(object).day
# 4
Based on comments below, this seems to only work in Python 2.7.x and Python 3.6+
try $conn = mysql_connect("localhost", "root")
or $conn = mysql_connect("localhost", "root", "")
The problem is that readlines
is a list of strings, each of which is a line of filename
. Perhaps you meant:
for line in readlines:
Type = line.split(",")
x = Type[1]
y = Type[2]
print(x,y)
Use the variables "$1"
, "$2"
, "$3"
and so on to access arguments. To access all of them you can use "$@"
, or to get the count of arguments $#
(might be useful to check for too few or too many arguments).
This is what worked for me:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlHelpers {
public static int getHTTPResponseStatusCode(String u) throws IOException {
URL url = new URL(u);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
return http.getResponseCode();
}
}
Hope this helps someone :)
Or if one want to use lambda
function in the apply
function:
data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))
If you're coming to Python from a language in the C/Java/etc. family, it may help you to stop thinking about a
as a "variable", and start thinking of it as a "name".
a
, b
, and c
aren't different variables with equal values; they're different names for the same identical value. Variables have types, identities, addresses, and all kinds of stuff like that.
Names don't have any of that. Values do, of course, and you can have lots of names for the same value.
If you give Notorious B.I.G.
a hot dog,* Biggie Smalls
and Chris Wallace
have a hot dog. If you change the first element of a
to 1, the first elements of b
and c
are 1.
If you want to know if two names are naming the same object, use the is
operator:
>>> a=b=c=[0,3,5]
>>> a is b
True
You then ask:
what is different from this?
d=e=f=3
e=4
print('f:',f)
print('e:',e)
Here, you're rebinding the name e
to the value 4
. That doesn't affect the names d
and f
in any way.
In your previous version, you were assigning to a[0]
, not to a
. So, from the point of view of a[0]
, you're rebinding a[0]
, but from the point of view of a
, you're changing it in-place.
You can use the id
function, which gives you some unique number representing the identity of an object, to see exactly which object is which even when is
can't help:
>>> a=b=c=[0,3,5]
>>> id(a)
4473392520
>>> id(b)
4473392520
>>> id(a[0])
4297261120
>>> id(b[0])
4297261120
>>> a[0] = 1
>>> id(a)
4473392520
>>> id(b)
4473392520
>>> id(a[0])
4297261216
>>> id(b[0])
4297261216
Notice that a[0]
has changed from 4297261120 to 4297261216—it's now a name for a different value. And b[0]
is also now a name for that same new value. That's because a
and b
are still naming the same object.
Under the covers, a[0]=1
is actually calling a method on the list object. (It's equivalent to a.__setitem__(0, 1)
.) So, it's not really rebinding anything at all. It's like calling my_object.set_something(1)
. Sure, likely the object is rebinding an instance attribute in order to implement this method, but that's not what's important; what's important is that you're not assigning anything, you're just mutating the object. And it's the same with a[0]=1
.
user570826 asked:
What if we have,
a = b = c = 10
That's exactly the same situation as a = b = c = [1, 2, 3]
: you have three names for the same value.
But in this case, the value is an int
, and int
s are immutable. In either case, you can rebind a
to a different value (e.g., a = "Now I'm a string!"
), but the won't affect the original value, which b
and c
will still be names for. The difference is that with a list, you can change the value [1, 2, 3]
into [1, 2, 3, 4]
by doing, e.g., a.append(4)
; since that's actually changing the value that b
and c
are names for, b
will now b [1, 2, 3, 4]
. There's no way to change the value 10
into anything else. 10
is 10 forever, just like Claudia the vampire is 5 forever (at least until she's replaced by Kirsten Dunst).
* Warning: Do not give Notorious B.I.G. a hot dog. Gangsta rap zombies should never be fed after midnight.
There are good instructions on the Virtualenv official site. https://pypi.python.org/pypi/virtualenv
Basically what I did, is install pip
with sudo easy_install pip
, then used sudo pip install virtualenv
then created an environment with: virtualenv my_env
(name it what you want), following that I did: virtualenv --distribute my_env
; which installed distribute
and pip
in my virtualenv.
Again, follow the instruction on the virtualenv
page.
Kind of a hassle, coming from Ruby ;P
Please consider using some code like this:
SqlDataReader reader = command.ExecuteReader();
int numRows = 0;
DataTable dt = new DataTable();
dt.Load(reader);
numRows = dt.Rows.Count;
string attended_type = "";
for (int index = 0; index < numRows; index++)
{
attended_type = dt.Rows[indice2]["columnname"].ToString();
}
reader.Close();
Simpler nio usage:
URL website = new URL("http://www.website.com/information.asp");
try (InputStream in = website.openStream()) {
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
}
I had the same problem. Solved using single quotes like this:
$ wget 'http://www.icerts.com/images/logo.jpg'
wget version in use:
$ wget --version
GNU Wget 1.11.4 Red Hat modified
This may help you, I was getting this error because I was trying to reload my .profile
with the command . .profile
and it had a syntax error
the wmic bios get serialnumber
command call the Win32_BIOS
wmi class and get the value of the SerialNumber
property, which retrieves the serial number of the BIOS Chip of your system.
How about this? You can probably take it a step further and use route instead of enum to resolve service type.
Interface which is typed to a Parent Class where BalanceSheetReportDto : ReportDto
public interface IReportService<T> where T : ReportDto
{
Task<byte[]> GetFileStream(T reportDto);
}
An abstract class that implements it.
public abstract class ReportService : IReportService<ReportDto>
{
public abstract Task<byte[]> GetFileStream(ReportDto reportDto);
}
This abstract class is what we need to resolve concrete types as you will not be able to specify resolver type as IReportService<ReportDto>
and return implementation BalaceSheetReportService
. Look at next code block.
Service Resolver for DI.
public delegate ReportService ServiceResolver(ReportType key);
public static IServiceCollection AddReportServices(this IServiceCollection services)
{
services.AddScoped<BalanceSheetReportService>();
services.AddScoped<ServiceResolver>(serviceProvider => key =>
{
switch (key)
{
case ReportType.BalanceSheet:
return serviceProvider.GetService<BalanceSheetReportService>();
default:
throw new KeyNotFoundException();
}
});
And in controller add resolver but not need to cast to specific type.
public class FinancialReportsController : BaseController
{
private ServiceCollectionExtension.ServiceResolver _resolver;
...
[HttpPost("balance-sheet")]
public async Task<byte[]> GetBalanceSheetReport([FromBody] BalanceSheetReportDto request)
{
try
{
var reportService = _resolver(ReportType.BalanceSheet); //magic
var data = await reportService.GetFileStream(request);
Concrete implementation.
public class BalanceSheetReportService: ReportService
{
...
public override async Task<byte[]> GetFileStream(ReportDto reportDto)
{
return await GetFileStream((BalanceSheetReportDto) reportDto);
}
private async Task<byte[]> GetFileStream(BalanceSheetReportDto reportDto)
{
Unrelated but you could inject other services (data classes for example) to abstract class.
private MongoDbContext _context;
public ReportService(MongoDbContext context) {
_context = context;
}
And then in your subclasses call this constructor and be done with it.
public BalanceSheetReportService(MongoDbContext context) : base(context) {}
MbUnit got a nice wrapper for this called Reflector.
Reflector dogReflector = new Reflector(new Dog());
dogReflector.Invoke("DreamAbout", DogDream.Food);
You can also set and get values from properties
dogReflector.GetProperty("Age");
Regarding the "test private" I agree that.. in the perfect world. there is no point in doing private unit tests. But in the real world you might end up wanting to write private tests instead of refactoring code.
A very, very good resource for these kinds of algorithms is Simmetrics: http://sourceforge.net/projects/simmetrics/
Unfortunately the awesome website containing a lot of the documentation is gone :( In case it comes back up again, its previous address was this: http://www.dcs.shef.ac.uk/~sam/simmetrics.html
Voila (courtesy of "Wayback Machine"): http://web.archive.org/web/20081230184321/http://www.dcs.shef.ac.uk/~sam/simmetrics.html
You can study the code source, there are dozens of algorithms for these kinds of comparisons, each with a different trade-off. The implementations are in Java.
NOTE: You must have the Team Agent or Admin role in App Store Connect to perform any of these tasks. If you are not part of a Team in App Store Connect this probably does not affect you.
Sending push notifications to an iOS application requires creating encyption keys. In the past this was a cumbersome process that used SSL keys and certificates. Each SSL certificate was specific to a single iOS application. In 2016 Apple introduced a new authentication key mechanism that is more reliable and easier to use. The new authentication keys are more flexible, simple to maintain and apply to more than on iOS app.
Even though it has been years since authentication keys were introduced not every service supports them. FireBase and Amazon Pinpoint support authentication keys. Amazon SNS, Urban Airship, Twilio, and LeanPlum do not. Many open source software packages do not yet support authentication keys.
To create the required SSL certificate and export it as PEM file containing public and private keys:
If you already have the SSL certificate set up for the app in the Apple Developer Center website you can skip ahead to Convert the certificate to PEM format. Keep in mind that you will run into problems if you do not also have the private key that was generated on the Mac that created the signing request that was uploaded to Apple.
Read on to see how to avoid losing track of that private key.
Xcode does not control certificates or keys for push notifications. To create keys and enable push notifications for an app you must go to the Apple Developer Center website. The Certificates, Identifiers & Profiles section of your account controls App IDs and certificates.
To access certificates and profiles you must either have a paid Apple Developer Program membership or be part of a Team that does.
Apps that use push notifications can not use wildcard App IDs or provisioning profiles. Each app requires you to set up an App ID record in the Apple Developer Center portal to enable push notifications.
Creating SSL certificates for push notifications is a process of several tasks. Each task has several steps. All of these are necessary to export the keys in P12 or PEM format. Review the steps before proceeding.
To create a certificate you will need to make a Certificate Signing Request (CSR) on a Mac and upload it to Apple.
Later if you need to export this certificate as a pkcs12 (aka p12) file you will need to use the keychain from the same Mac. When the signing request is created Keychain Access generates a set of keys in the default keychain. These keys are necessary for working with the certificate Apple will create from the signing request.
It is a good practice to have a separate keychain specifically for credentials used for development. If you do this make sure this keychain is set to be the default before using Certificate Assistant.
When creating the Certificate Signing Request the Certificate Assistant generates two encryption keys in the default keychain. It is important to make the development keychain the default so the keys are in the right keychain.
Creating the signing request generated a pair of keys. Before the signing request is uploaded verify that the development keychain has the keys. Their names will be the same as the Common Name used in the signing request.
Once the Certicate Signing Request is created upload it to the Apple Developer Center. Apple will create the push notification certificate from the signing request.
Your development keychain should now show the push certificate with a private key under My Certificates in Keychain Access:
At this point the development keychain should be backed up. Many teams keep their push certificates on secure USB drives, commit to internal version control or use a backup solution like Time Machine. The development keychain can be shared between different team members because it does not contain any personal code signing credentials.
Keychain files are located in
~/Library/Keychains
.
Some third party push services require certificates in Privacy Enhanced Mail (PEM) format, while others require Public-Key Cryptography Standards #12 (PKCS12 or P12). The certificate downloaded from Apple can be used to export certificates in these formats - but only if you have kept the private key.
Be careful, the solution proposed with $a = array_combine($a, $a);
will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384)
to be the keys as well as the values however PHP manual states:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}
The device pixel ratio is the ratio between physical pixels and logical pixels. For instance, the iPhone 4 and iPhone 4S report a device pixel ratio of 2, because the physical linear resolution is double the logical linear resolution.
The formula is:
Where:
is the physical linear resolution
and:
is the logical linear resolution
Other devices report different device pixel ratios, including non-integer ones. For example, the Nokia Lumia 1020 reports 1.6667, the Samsumg Galaxy S4 reports 3, and the Apple iPhone 6 Plus reports 2.46 (source: dpilove). But this does not change anything in principle, as you should never design for any one specific device.
The CSS "pixel" is not even defined as "one picture element on some screen", but rather as a non-linear angular measurement of viewing angle, which is approximately of an inch at arm's length. Source: CSS Absolute Lengths
This has lots of implications when it comes to web design, such as preparing high-definition image resources and carefully applying different images at different device pixel ratios. You wouldn't want to force a low-end device to download a very high resolution image, only to downscale it locally. You also don't want high-end devices to upscale low resolution images for a blurry user experience.
If you are stuck with bitmap images, to accommodate for many different device pixel ratios, you should use CSS Media Queries to provide different sets of resources for different groups of devices. Combine this with nice tricks like background-size: cover
or explicitly set the background-size
to percentage values.
#element { background-image: url('lores.png'); }
@media only screen and (min-device-pixel-ratio: 2) {
#element { background-image: url('hires.png'); }
}
@media only screen and (min-device-pixel-ratio: 3) {
#element { background-image: url('superhires.png'); }
}
This way, each device type only loads the correct image resource. Also keep in mind that the px
unit in CSS always operates on logical pixels.
As more and more device types appear, it gets trickier to provide all of them with adequate bitmap resources. In CSS, media queries is currently the only way, and in HTML5, the picture element lets you use different sources for different media queries, but the support is still not 100 % since most web developers still have to support IE11 for a while more (source: caniuse).
If you need crisp images for icons, line-art, design elements that are not photos, you need to start thinking about SVG, which scales beautifully to all resolutions.
According to http://php.net/manual/en/function.error-get-last.php, use:
print_r(error_get_last());
Which will return an array of the last error generated. You can access the [message]
element to display the error.
None of the answers worked for me. But inspired in BarryPye's answer I found out it works when using relative paths!
# Contents from the '/media/user/README_1.md' markdown file:
Read more [here](./README_2.md) # It works!
Read more [here](file:///media/user/README_2.md) # Doesn't work
Read more [here](/media/user/README_2.md) # Doesn't work
Now we can simply use environments file which angular provide default if your project is generated via angular-cli.
for example
In your environments folder create following files
environment.prod.ts
environment.qa.ts
environment.dev.ts
and each file can hold related code changes such as:
environment.prod.ts
export const environment = {
production: true,
apiHost: 'https://api.somedomain.com/prod/v1/',
CONSUMER_KEY: 'someReallyStupidTextWhichWeHumansCantRead',
codes: [ 'AB', 'AC', 'XYZ' ],
};
environment.qa.ts
export const environment = {
production: false,
apiHost: 'https://api.somedomain.com/qa/v1/',
CONSUMER_KEY : 'someReallyStupidTextWhichWeHumansCantRead',
codes: [ 'AB', 'AC', 'XYZ' ],
};
environment.dev.ts
export const environment = {
production: false,
apiHost: 'https://api.somedomain.com/dev/v1/',
CONSUMER_KEY : 'someReallyStupidTextWhichWeHumansCantRead',
codes: [ 'AB', 'AC', 'XYZ' ],
};
You can import environments into any file such as services clientUtilServices.ts
import {environment} from '../../environments/environment';
getHostURL(): string {
return environment.apiHost;
}
Open your angular cli file .angular-cli.json
and inside "apps": [{...}]
add following code
"apps":[{
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts",
"qa": "environments/environment.qa.ts",
}
}
]
If you want to build for production, run ng build --env=prod
it will read configuration from environment.prod.ts
, same way you can do it for qa
or dev
I have been doing something like below, in my provider:
import {Injectable} from '@angular/core';
@Injectable()
export class ConstantService {
API_ENDPOINT :String;
CONSUMER_KEY : String;
constructor() {
this.API_ENDPOINT = 'https://api.somedomain.com/v1/';
this.CONSUMER_KEY = 'someReallyStupidTextWhichWeHumansCantRead'
}
}
Then i have access to all Constant data at anywhere
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
import {ConstantService} from './constant-service'; //This is my Constant Service
@Injectable()
export class ImagesService {
constructor(public http: Http, public ConstantService: ConstantService) {
console.log('Hello ImagesService Provider');
}
callSomeService() {
console.log("API_ENDPOINT: ",this.ConstantService.API_ENDPOINT);
console.log("CONSUMER_KEY: ",this.ConstantService.CONSUMER_KEY);
var url = this.ConstantService.API_ENDPOINT;
return this.http.get(url)
}
}
ffill
now has it's own method pd.DataFrame.ffill
df.ffill()
0 1 2
0 1.0 2.0 3.0
1 4.0 2.0 3.0
2 4.0 2.0 9.0
When there are multiple activities entries in AndroidManifest.xml, how does android know which activity to start first?
There is no "first". In your case, with your manifest as shown, you will have two icons in your launcher. Whichever one the user taps on is the one that gets launched.
I could not understand intent-filters. Can anyone please explain.
There is quite a bit of documentation on the subject. Please consider reading that, then asking more specific questions.
Also, when you get "application has stopped unexpectedly, try again", use adb logcat
, DDMS, or the DDMS perspective in Eclipse to examine the Java stack trace associated with the error.
The following steps are to reset the password for a user in case you forgot, this would also solve your mentioned error.
First, stop your MySQL:
sudo /etc/init.d/mysql stop
Now start up MySQL in safe mode and skip the privileges table:
sudo mysqld_safe --skip-grant-tables &
Login with root:
mysql -uroot
And assign the DB that needs to be used:
use mysql;
Now all you have to do is reset your root password of the MySQL user and restart the MySQL service:
update user set password=PASSWORD("YOURPASSWORDHERE") where User='root';
flush privileges;
quit and restart MySQL:
quit
sudo /etc/init.d/mysql stop sudo /etc/init.d/mysql start Now your root password should be working with the one you just set, check it with:
mysql -u root -p
The automatic install of peer dependencies was explicitly removed with npm 3, as it cause more problems than it tried to solve. You can read about it here for example:
So no, for the reasons given, you cannot install them automatically with npm 3 upwards.
NPM V7
NPM v7 has reintroduced the automatic peerDependencies installation. They had made some changes to fix old problems as version compatibility across multiple dependants. You can see the discussion here and the announcement here
Now in V7, as in versions before V3, you only need to do an npm i
and all peerDependences should be automatically installed.
Use this as a template
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE FUNCTION <Table_Function_Name, sysname, FunctionName>
(
-- Add the parameters for the function here
<@param1, sysname, @p1> <data_type_for_param1, , int>,
<@param2, sysname, @p2> <data_type_for_param2, , char>
)
RETURNS
<@Table_Variable_Name, sysname, @Table_Var> TABLE
(
-- Add the column definitions for the TABLE variable here
<Column_1, sysname, c1> <Data_Type_For_Column1, , int>,
<Column_2, sysname, c2> <Data_Type_For_Column2, , int>
)
AS
BEGIN
-- Fill the table variable with the rows for your result set
RETURN
END
GO
That will define your function. Then you would just use it as any other table:
Select * from MyFunction(Param1, Param2, etc.)
Probably "mysql_real_escape_string()
" will work for u
From the documentation, you do it like:
<div class="row">
<div class="col-md-6">left</div>
<div class="col-md-push-6">content needs to be right aligned</div>
</div>
StringBuffer sb = new StringBuffer();
sb.append(a).append(b).append(c)...
Keeping the values as an int is preferred thou, as the other answers show you.
I got the error using TFS, my AssemblyInfo wasn't mapped in the branch I was working on.
I use AngularJS v1.3.4
HTML:
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
JS controller:
'use strict';
angular.module('xxxxxxxxApp')
.controller('MathController', function ($scope, MathServicePDF) {
$scope.downloadPdf = function () {
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
MathServicePDF.downloadPdf().then(function (result) {
var file = new Blob([result.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
};
});
JS services:
angular.module('xxxxxxxxApp')
.factory('MathServicePDF', function ($http) {
return {
downloadPdf: function () {
return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
Java REST Web Services - Spring MVC:
@RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<byte[]> getPDF() {
FileInputStream fileStream;
try {
fileStream = new FileInputStream(new File("C:\\xxxxx\\xxxxxx\\test.pdf"));
byte[] contents = IOUtils.toByteArray(fileStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "test.pdf";
headers.setContentDispositionFormData(filename, filename);
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;
} catch (FileNotFoundException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
return null;
}
Session.Abandon()
destroys the session and the Session_OnEnd event is triggered.
Session.Clear()
just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon()
, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear()
, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.
I think the application start event only gets fired when the first request is made, are you hitting your website (i.e. making a request)?
I just discovered the Hmisc package:
Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.
library(Hmisc)
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th
By specifying the column as VARCHAR(500)
you've set an explicit 500 character limit. You might not have done this yourself explicitly, but Django has done it for you somewhere. Telling you where is hard when you haven't shown your model, the full error text, or the query that produced the error.
If you don't want one, use an unqualified VARCHAR
, or use the TEXT
type.
varchar
and text
are limited in length only by the system limits on column size - about 1GB - and by your memory. However, adding a length-qualifier to varchar
sets a smaller limit manually. All of the following are largely equivalent:
column_name VARCHAR(500)
column_name VARCHAR CHECK (length(column_name) <= 500)
column_name TEXT CHECK (length(column_name) <= 500)
The only differences are in how database metadata is reported and which SQLSTATE is raised when the constraint is violated.
The length constraint is not generally obeyed in prepared statement parameters, function calls, etc, as shown:
regress=> \x
Expanded display is on.
regress=> PREPARE t2(varchar(500)) AS SELECT $1;
PREPARE
regress=> EXECUTE t2( repeat('x',601) );
-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
?column? | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
and in explicit casts it result in truncation:
regress=> SELECT repeat('x',501)::varchar(1);
-[ RECORD 1 ]
repeat | x
so I think you are using a VARCHAR(500)
column, and you're looking at the wrong table or wrong instance of the database.
I was facing this issue in eclipse . What I did was, killed the running java process from the task manager.
It worked for me.
There's a great blog post on this here:
http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/
Along with a demo here:
http://www.kylejlarson.com/files/iosdemo/
In summary, you can use the following on a div containing your main content:
.scrollable {
position: absolute;
top: 50px;
left: 0;
right: 0;
bottom: 0;
overflow: scroll;
-webkit-overflow-scrolling: touch;
}
The problem I think you're describing is when you try to scroll up within a div that is already at the top - it then scrolls up the page instead of up the div and causes a bounce effect at the top of the page. I think your question is asking how to get rid of this?
In order to fix this, the author suggests that you use ScrollFix to auto increase the height of scrollable divs.
It's also worth noting that you can use the following to prevent the user from scrolling up e.g. in a navigation element:
document.addEventListener('touchmove', function(event) {
if(event.target.parentNode.className.indexOf('noBounce') != -1
|| event.target.className.indexOf('noBounce') != -1 ) {
event.preventDefault(); }
}, false);
Unfortunately there are still some issues with ScrollFix (e.g. when using form fields), but the issues list on ScrollFix is a good place to look for alternatives. Some alternative approaches are discussed in this issue.
Other alternatives, also mentioned in the blog post, are Scrollability and iScroll
Disclosure: I wrote the code that Trello uses; the code below is the actual source code Trello uses to accomplish the clipboard trick.
We don't actually "access the user's clipboard", instead we help the user out a bit by selecting something useful when they press Ctrl+C.
Sounds like you've figured it out; we take advantage of the fact that when you want to hit Ctrl+C, you have to hit the Ctrl key first. When the Ctrl key is pressed, we pop in a textarea that contains the text we want to end up on the clipboard, and select all the text in it, so the selection is all set when the C key is hit. (Then we hide the textarea when the Ctrl key comes up.)
Specifically, Trello does this:
TrelloClipboard = new class
constructor: ->
@value = ""
$(document).keydown (e) =>
# Only do this if there's something to be put on the clipboard, and it
# looks like they're starting a copy shortcut
if !@value || !(e.ctrlKey || e.metaKey)
return
if $(e.target).is("input:visible,textarea:visible")
return
# Abort if it looks like they've selected some text (maybe they're trying
# to copy out a bit of the description or something)
if window.getSelection?()?.toString()
return
if document.selection?.createRange().text
return
_.defer =>
$clipboardContainer = $("#clipboard-container")
$clipboardContainer.empty().show()
$("<textarea id='clipboard'></textarea>")
.val(@value)
.appendTo($clipboardContainer)
.focus()
.select()
$(document).keyup (e) ->
if $(e.target).is("#clipboard")
$("#clipboard-container").empty().hide()
set: (@value) ->
In the DOM we've got:
<div id="clipboard-container"><textarea id="clipboard"></textarea></div>
CSS for the clipboard stuff:
#clipboard-container {
position: fixed;
left: 0px;
top: 0px;
width: 0px;
height: 0px;
z-index: 100;
display: none;
opacity: 0;
}
#clipboard {
width: 1px;
height: 1px;
padding: 0px;
}
... and the CSS makes it so you can't actually see the textarea when it pops in ... but it's "visible" enough to copy from.
When you hover over a card, it calls
TrelloClipboard.set(cardUrl)
... so then the clipboard helper knows what to select when the Ctrl key is pressed.
I have written an implementation that properly works with dates exactly one year apart.
However, it does not gracefully handle negative timespans, unlike the other algorithm. It also doesn't use its own date arithmetic, instead relying upon the standard library for that.
So without further ado, here is the code:
DateTime zeroTime = new DateTime(1, 1, 1);
DateTime a = new DateTime(2007, 1, 1);
DateTime b = new DateTime(2008, 1, 1);
TimeSpan span = b - a;
// Because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;
// 1, where my other algorithm resulted in 0.
Console.WriteLine("Yrs elapsed: " + years);
Since the main
method is static
and the fxn()
method is not, you can't call the method without first creating a Two
object. So either you change the method to:
public static int fxn(int y) {
y = 5;
return y;
}
or change the code in main
to:
Two two = new Two();
x = two.fxn(x);
Read more on static
here in the Java Tutorials.
in the folder where the build.xml resides run command only -
ant
and not the command - `
ant build.xml
`
. if you are using the ant file as build xml then the below steps helps you Steps : open cmd Prompt >> switch to the project location >>type ant and click enter key
removing all the exited containers
docker rm $(docker ps -a -f status=exited -q)
a) object Class "Long" versus primitive type "long". (At least in Java)
b) There are different (even unclear) memory-sizes of the primitive types:
Java - all clear: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
C .. just mess: https://en.wikipedia.org/wiki/C_data_types
Instead of using HTML comments (which have no effect on PHP code -- which will still be executed), you should use PHP comments:
<?php /*
<tr>
<td><?php echo $entry_keyword; ?></td>
<td><input type="text" name="keyword" value="<?php echo $keyword; ?>" /></td>
</tr>
<tr>
<td><?php echo $entry_sort_order; ?></td>
<td><input name="sort_order" value="<?php echo $sort_order; ?>" size="1" /></td>
</tr>
*/ ?>
With that, the PHP code inside the HTML will not be executed; and nothing (not the HTML, not the PHP, not the result of its non-execution) will be displayed.
Just one note: you cannot nest C-style comments... which means the comment will end at the first */
encountered.
Try this
li = soup.find('li', {'class': 'text'})
children = li.findChildren("a" , recursive=False)
for child in children:
print(child)
Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.
Just use the Date
property:
var today = DateTime.Today;
var q = db.Games.Where(t => t.StartDate.Date >= today)
.OrderBy(t => t.StartDate);
Note that I've explicitly evaluated DateTime.Today
once so that the query is consistent - otherwise each time the query is executed, and even within the execution, Today
could change, so you'd get inconsistent results. For example, suppose you had data of:
Entry 1: March 8th, 8am
Entry 2: March 10th, 10pm
Entry 3: March 8th, 5am
Entry 4: March 9th, 8pm
Surely either both entries 1 and 3 should be in the results, or neither of them should... but if you evaluate DateTime.Today
and it changes to March 9th after it's performed the first two checks, you could end up with entries 1, 2, 4.
Of course, using DateTime.Today
assumes you're interested in the date in the local time zone. That may not be appropriate, and you should make absolutely sure you know what you mean. You may want to use DateTime.UtcNow.Date
instead, for example. Unfortunately, DateTime
is a slippery beast...
EDIT: You may also want to get rid of the calls to DateTime
static properties altogether - they make the code hard to unit test. In Noda Time we have an interface specifically for this purpose (IClock
) which we'd expect to be injected appropriately. There's a "system time" implementation for production and a "stub" implementation for testing, or you can implement it yourself.
You can use the same idea without using Noda Time, of course. To unit test this particular piece of code you may want to pass the date in, but you'll be getting it from somewhere - and injecting a clock means you can test all the code.
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
It's not easy to find a full solution of the problem of a convertion of an arbitrary HTML to PDF with non-english letters in Android. I test it for russian unicode letters.
We use three libraries:
(1) Jsoup (jsoup-1.7.3.jar) for a convertion from HTML to XHTML,
(2) iTextPDF (itextpdf-5.5.0.jar),
(3) XMLWorker (xmlworker-5.5.1.jar).
public boolean createPDF(String rawHTML, String fileName, ContextWrapper context){
final String APPLICATION_PACKAGE_NAME = context.getBaseContext().getPackageName();
File path = new File( Environment.getExternalStorageDirectory(), APPLICATION_PACKAGE_NAME );
if ( !path.exists() ){ path.mkdir(); }
File file = new File(path, fileName);
try{
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
// ?????????????? HTML
String htmlText = Jsoup.clean( rawHTML, Whitelist.relaxed() );
InputStream inputStream = new ByteArrayInputStream( htmlText.getBytes() );
// ???????? ???????? PDF
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
inputStream, null, Charset.defaultCharset(), new MyFont());
document.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
The difficult problem is to display russian letters in PDF by using iTextPDF XMLWorker library. For this we should create our own implementation of FontProvider interface:
public class MyFont implements FontProvider{
private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
private static final String FONT_ALIAS = "my_font";
public MyFont(){ FontFactory.register(FONT_PATH, FONT_ALIAS); }
@Override
public Font getFont(String fontname, String encoding, boolean embedded,
float size, int style, BaseColor color){
return FontFactory.getFont(FONT_ALIAS, BaseFont.IDENTITY_H,
BaseFont.EMBEDDED, size, style, color);
}
@Override
public boolean isRegistered(String name) { return name.equals( FONT_ALIAS ); }
}
Here we use the standard Android font Droid Sans, which is located in the system folder:
private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
If you have access to Mac OS I have found that the Apple spreadsheet Numbers does a good job of unpicking a complex multi-line CSV file that Excel could not handle. Just open the .csv
with Numbers and then export to Excel.
The error message is due to the unfortunate fact that PHP will implicitly declare an unknown token as a constant string of the same name.
That is, it's trying to interpret this (note the missing quote marks):
$_POST[department]
The only valid way this would be valid syntax in PHP is if there was previously a constant department
defined. So sadly, rather than dying with a Fatal error at this point, it issues this Notice and acts as though a constant had been defined with the same name and value:
// Implicit declaration of constant called department with value 'department'
define('department', 'department');
There are various ways you can get this error message, but they all have the same root cause - a token that could be a constant.
$my_array[bad_key]
This is what the problem is in your case, and it's because you've got string array keys that haven't been quoted. Fixing the string keys will fix the bug:
Change:
$department = mysql_real_escape_string($_POST[department]);
...(etc)...
To:
$department = mysql_real_escape_string($_POST['department']);
...(etc)...
var_without_dollar
Another reason you might see this error message is if you leave off the $
from a variable, or $this->
from a member. Eg, either of the following would cause a similar error message:
my_local; // should be $my_local
my_member; // should be $this->my_member
$bad-variable-name
A similar but more subtle issue can result if you try to use a disallowed character in a variable name - a hyphen (-
) instead of an underscore _
would be a common case.
For example, this is OK, since underscores are allowed in variable names:
if (123 === $my_var) {
do_something();
}
But this isn't:
if (123 === $my-var) {
do_something();
}
It'll be interpreted the same as this:
if (123 === $my - var) { // variable $my minus constant 'var'
do_something();
}
In order to refer to a class constant you need to specify the class scope with ::
, if you miss this off PHP will think you're talking about a global define()
.
Eg:
class MyClass {
const MY_CONST = 123;
public function my_method() {
return self::MY_CONST; // This is fine
}
public function my_method() {
return MyClass::MY_CONST; // This is fine
}
public function my_bad_method() {
return MY_CONST; // BUG - need to specify class scope
}
}
There are some system-defined constants that only exist in newer versions of PHP, for example the mode option constants for round()
such as PHP_ROUND_HALF_DOWN
only exist in PHP 5.3 or later.
So if you tried to use this feature in PHP 5.2, say:
$rounded = round($my_var, 0, PHP_ROUND_HALF_DOWN);
You'd get this error message:
Use of undefined constant PHP_ROUND_HALF_DOWN - assumed 'PHP_ROUND_HALF_DOWN' Warning (2): Wrong parameter count for round()
You can declare a simple function to provide namespaces.
function namespace(namespace) {
var object = this, tokens = namespace.split("."), token;
while (tokens.length > 0) {
token = tokens.shift();
if (typeof object[token] === "undefined") {
object[token] = {};
}
object = object[token];
}
return object;
}
// Usage example
namespace("foo.bar").baz = "I'm a value!";
In a case
statement, a ,
is the equivalent of ||
in an if
statement.
case car
when 'toyota', 'lexus'
# code
end
Take care with gradle daemon, you have to stop it before clear and re-run gradle.
Stop first daemon:
./gradlew --stop
Clean cache using:
rm -rf ~/.gradle/caches/
Run again you compilation
A simple solution for empty floated divs is to add:
this way you can keep the float functionality and force it to fill space when empty.
I use this technique in page layout columns, to keep every column in its position even if the other columns are empty.
Example:
.left-column
{
width: 200px;
min-height: 1px;
float: left;
}
.right-column
{
width: 500px;
min-height: 1px;
float: left;
}
What really makes me feel bad about mocking abstract classes is the fact, that neither the default constructor YourAbstractClass()
gets called (missing super()
in mock) nor seems there to be any way in Mockito to default initialize mock properties (e.g List
properties with empty ArrayList
or LinkedList
).
My abstract class (basically the class source code gets generated) does NOT provide a dependency setter injection for list elements, nor a constructor where it initializes the list elements (which I tried to add manually).
Only the class attributes use default initialization:
private List<MyGenType> dep1 = new ArrayList<MyGenType>();
private List<MyGenType> dep2 = new ArrayList<MyGenType>();
So there is NO way to mock an abstract class without using a real object implementation (e.g inner class definition in unit test class, overriding abstract methods) and spying the real object (which does proper field initialization).
Too bad that only PowerMock would help here further.
change import cv
to import cv2.cv as cv
See also the post here.
You can also use the new Java 8 API
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class StackoverflowTest{
public static void main(String args[]){
String strDate = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454
}
}
The DateTimeFormatter
class replaces the old SimpleDateFormat
. You can then create a ZonedDateTime
from which you can extract the desired epoch time.
The main advantage is that you are now thread safe.
Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.
You can do that using count
:
my_dict = {i:MyList.count(i) for i in MyList}
>>> print my_dict #or print(my_dict) in python-3.x
{'a': 3, 'c': 3, 'b': 1}
Or using collections.Counter
:
from collections import Counter
a = dict(Counter(MyList))
>>> print a #or print(a) in python-3.x
{'a': 3, 'c': 3, 'b': 1}
library(httr)
url <- "http://www.omdbapi.com/?apikey=72bc447a&t=Annie+Hall&y=&plot=short&r=json"
resp <- GET(url)
content(resp, as = "text")
content(resp)
Use content() to get the content of resp, but this time do not specify a second argument. R figures out automatically that you're dealing with a JSON, and converts the JSON to a named R list.
TemplateBinding is a shorthand for Binding with TemplatedParent but it does not expose all the capabilities of the Binding class, for example you can't control Binding.Mode from TemplateBinding.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form method="GET">
<h1>Calculator</h1>
<p>This is a calculator made by Hau Teen Yee Fabrice and is free to use.</p>
<ul>
<ol> Multiplication: * </ol>
<ol> Substraction: - </ol>
<ol> Division: / </ol>
<ol> Addition: + </ol>
</ul>
<p>Enter first number:</p>
<input type="text" name="cal1">
<p>Enter second number:</p>
<input type="text" name="cal2">
<p>Enter the calculator symbol</p>
<input type="text" name="symbol">
<button>Calculate</button>
</form>
<?php
$cal1= $_GET['cal1'];
$cal2= $_GET['cal2'];
$symbol =$_GET['symbol'];
if($symbol == '+')
{
$add = $cal1 + $cal2;
echo "Addition is:".$add;
}
else if($symbol == '-')
{
$subs = $cal1 - $cal2;
echo "Substraction is:".$subs;
}
else if($symbol == '*')
{
$mul = $cal1 * $cal2;
echo "Multiply is:".$mul;
}
else if($symbol == '/')
{
$div = $cal1 / $cal2;
echo "Division is:".$div;
}
else
{
echo "Oops ,something wrong in your code son";
}
?>
</body>
</html>
Like others, the accepted answer also gave me an outdated version.
Here is another way to do it that works very well:
$ curl --silent --location https://rpm.nodesource.com/setup_14.x | bash -
$ yum -y install nodejs
You can also replace the 14.x with another version, such as 12.x, 10.x, etc.
You can see all available versions on the NodeSource Github page, and pull from there as well if desired.
Note: you may need to run using sudo
depending on your environment.
BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.
$('#btnSaveComments').click(function () {
var comments = $('#txtComments').val();
var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '<%: Url.Action("SaveComments")%>',
data: { 'id' : selectedId, 'comments' : comments },
type: "post",
cache: false,
success: function (savingStatu`enter code here`s) {
$("#hdnOrigComments").val($('#txtComments').val());
$('#lblCommentsNotification').text(savingStatus);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
To convert int32 to string in mongo without creating an array just add "" to your number :-)
db.foo.find( { 'mynum' : { $type : 16 } } ).forEach( function (x) {
x.mynum = x.mynum + ""; // convert int32 to string
db.foo.save(x);
});
Go and get the latest version of miniconda for Raspberry Pi - made for armv7l processor and bundled with Python 3 (eg.: uname -m
)
wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
md5sum Miniconda3-latest-Linux-armv7l.sh
bash Miniconda3-latest-Linux-armv7l.sh
After installation, source your updated .bashrc file with source ~/.bashrc
. Then enter the command python --version
, which should give you:
Python 3.4.3 :: Continuum Analytics, Inc.
You can do it via FileInfo or DirectoryInfo:
DirectoryInfo di = new DirectoryInfo("TempDir");
di.Delete(true);
And then recreate the directory
Guava 15 has now added a set of straightforward URL escapers.
Use textView.text
for getter and setter, ex:
val textView = findViewById<TextView>(R.id.textView)
// Set text
textView.text = "Hello World!"
// Get text
val textViewString = textView.text.toString()
While it might not be the best approach the closest equivalent I can think of that works is this with the support/compatibility library
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
or
getActivity().getFragmentManager().beginTransaction().remove(this).commit();
otherwise.
In addition you can use the backstack and pop it. However keep in mind that the fragment might not be on the backstack (depending on the fragmenttransaction that got it there..) or it might not be the last one that got onto the stack so popping the stack could remove the wrong one...
You could decorate your view model property with the [DisplayName]
attribute and specify the text to be used:
[DisplayName("foo bar")]
public string SomekingStatus { get; set; }
Or use another overload of the LabelFor helper which allows you to specify the text:
@Html.LabelFor(model => model.SomekingStatus, "foo bar")
And, no, you cannot specify a class name in MVC3 as you tried to do, as the LabelFor
helper doesn't support that. However, this would work in MVC4 or 5.
requests
does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.
Python comes with built-in XML parsers. I recommend you use the ElementTree API:
import requests
from xml.etree import ElementTree
response = requests.get(url)
tree = ElementTree.fromstring(response.content)
or, if the response is particularly large, use an incremental approach:
response = requests.get(url, stream=True)
# if the server sent a Gzip or Deflate compressed response, decompress
# as we read the raw stream:
response.raw.decode_content = True
events = ElementTree.iterparse(response.raw)
for event, elem in events:
# do something with `elem`
The external lxml project builds on the same API to give you more features and power still.
There is no =>
for if.
Use if %energy% GEQ %m2enc%
See if /?
for some other details.
I am not very sure if what i did was right, but it worked anyways. I renamed repo2 folder present inside repo1, and committed the changes. In my case it was just one repo which i wanted to merge , so this approach worked. Later on, some path changes were done.
git rev-list --exclude=master --branches --no-walk
will list the tips of every branch that isn't master
.
git rev-list master --not $(git rev-list --exclude=master --branches --no-walk)
will list every commit in master
's history that's not in any other branch's history.
Sequencing is important for the options that set up the filter pipeline for commit selection, so --branches
has to follow any exclusion patterns it's supposed to apply, and --no-walk
has to follow the filters supplying commits rev-list isn't supposed to walk.
I bumped into this when tried to write something like:
Continuable<T> callAsync(Callable<T> code) {....}
and
Continuable<Continuable<T>> callAsync(Callable<Continuable<T>> veryAsyncCode) {...}
They become for compiler the 2 definitions of
Continuable<> callAsync(Callable<> veryAsyncCode) {...}
The type erasure literally means erasing of type arguments information from generics. This is VERY annoying, but this is a limitation that will be with Java for while. For constructors case not much can be done, 2 new subclasses specialized with different parameters in constructor for example. Or use initialization methods instead... (virtual constructors?) with different names...
for similar operation methods renaming would help, like
class Test{
void addIntegers(Set<Integer> ii){}
void addStrings(Set<String> ss){}
}
Or with some more descriptive names, self-documenting for oyu cases, like addNames
and addIndexes
or such.
first, store the last time the user made a request
<?php
$_SESSION['timeout'] = time();
?>
in subsequent request, check how long ago they made their previous request (10 minutes in this example)
<?php
if ($_SESSION['timeout'] + 10 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return function() {
console.log(i);
}
};
setTimeout(tick(i), 500 * i);
}
Demo here: http://jsfiddle.net/hW7Ch/
Try
private boolean hasKey(JSONObject jsonObject, String key) {
return jsonObject != null && jsonObject.has(key);
}
try {
JSONObject jsonObject = new JSONObject(yourJson);
if (hasKey(jsonObject, "labelData")) {
JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
if (hasKey(labelDataJson, "video")) {
String video = labelDataJson.getString("video");
}
}
} catch (JSONException e) {
}
Add this permission in Manifest
,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Do something on success
} else {
// Do something else on failure
}
when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder
Original Answer
Windows Grep does this really well.
Edit: Windows Grep is no longer being maintained or made available by the developer. An alternate download link is here: Windows Grep - alternate
Current Answer
Visual Studio Code has excellent search and replace capabilities across files. It is extremely fast, supports regex and live preview before replacement.
Have a look at this list on Wikipedia about which browsers support SVG. It also provides links to more details in the footnotes. Firefox for example supports basic SVG, but at the moment lacks most animation features.
A tutorial about how to create SVG objects using Javascript can be found here:
var svgns = "http://www.w3.org/2000/svg";
var svgDocument = evt.target.ownerDocument;
var shape = svgDocument.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r", 20);
shape.setAttributeNS(null, "fill", "green");
With the help of GoogleApiClient's LocationServices API we can get the current location of the user/device in specific time interval. This can be added into a background service which updates the Activity when onLocationChanged callbacks
The background service will keep running as long as the application exists in the memory and sticks to the notification drawer. The service handles the following functionalities,
Service With Location Listener
public class LocationMonitoringService extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
...
...
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest.setInterval(10000); //10 secs
mLocationRequest.setFastestInterval(5000); //5 secs
int priority = LocationRequest.PRIORITY_HIGH_ACCURACY; //by default
//PRIORITY_BALANCED_POWER_ACCURACY, PRIORITY_LOW_POWER, PRIORITY_NO_POWER are the other priority modes
mLocationRequest.setPriority(priority);
mLocationClient.connect();
//Make it stick to the notification panel so it is less prone to get cancelled by the Operating System.
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*
* LOCATION CALLBACKS
*/
@Override
public void onConnected(Bundle dataBundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Log.d(TAG, "== Error On onConnected() Permission not granted");
//Permission not granted by user so cancel the further execution.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);
Log.d(TAG, "Connected to Google API");
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "Connection suspended");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Failed to connect to Google API");
}
//to get the location change
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Location changed");
if (location != null) {
//Do something with the location details,
if (location != null) {
//call your API
callAPI(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
}
}
}
}
See Complete Tutorial With source code and explanation in detail >>
In some case NTLM authentication still won't work if given the correct credential.
There's a mechanism which will void NTLM auth within WebClient, see here for more information: System.Net.WebClient doesn't work with Windows Authentication
If you're trying above answer and it's still not working, follow the above link to add registry to make the domain whitelisted.
Post this here to save other's time ;)
callLog(){
this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
.subscribe(data => {
this.getstud=data as string[];
if(this.getstud.length!==0) {
console.log(data)
this.route.navigate(['home']);// used for routing after importing Router
}
});
}
step 1. sudo mysql -u root -p
step 2. USE mysql;
step 3. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'admin';
Here 'admin' is your new password, yo can change it.
step 4. exit
Thanks. You are done.
Here's is my version. It checks against both positive and negative values lists, raising an exception for unknown values. And it does not receive a string, but any type should do.
def to_bool(value):
"""
Converts 'something' to boolean. Raises exception for invalid formats
Possible True values: 1, True, "1", "TRue", "yes", "y", "t"
Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...
"""
if str(value).lower() in ("yes", "y", "true", "t", "1"): return True
if str(value).lower() in ("no", "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"): return False
raise Exception('Invalid value for boolean conversion: ' + str(value))
Sample runs:
>>> to_bool(True)
True
>>> to_bool("tRUe")
True
>>> to_bool("1")
True
>>> to_bool(1)
True
>>> to_bool(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: 2
>>> to_bool([])
False
>>> to_bool({})
False
>>> to_bool(None)
False
>>> to_bool("Wasssaaaaa")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: Wasssaaaaa
>>>