You can use jade + express:
app.get('/', function (req, res) { res.render('index', { title : 'Home' } ) });
above you see 'index' and an object {title : 'Home'}, 'index' is your html and the object is your data that will be rendered in your html.
I don't like it either.
So use javascript:
Public Function GetJavaScriptResult(doc as HTMLDocument, jsString As String) As String
Dim el As IHTMLElement
Dim nd As HTMLDOMTextNode
Set el = doc.createElement("INPUT")
Do
el.ID = GenerateRandomAlphaString(100)
Loop Until Document.getElementById(el.ID) Is Nothing
el.Style.display = "none"
Set nd = Document.appendChild(el)
doc.parentWindow.ExecScript "document.getElementById('" & el.ID & "').value = " & jsString
GetJavaScriptResult = Document.getElementById(el.ID).Value
Document.removeChild nd
End Function
Function GenerateRandomAlphaString(Length As Long) As String
Dim i As Long
Dim Result As String
Randomize Timer
For i = 1 To Length
Result = Result & Chr(Int(Rnd(Timer) * 26 + 65 + Round(Rnd(Timer)) * 32))
Next i
GenerateRandomAlphaString = Result
End Function
Let me know if you have any problems with this; I've changed the context from a method to a function.
By the way, what version of IE are you using? I suspect you're on < IE8. If you upgrade to IE8 I presume it'll update shdocvw.dll to ieframe.dll and you will be able to use document.querySelector/All.
Edit
Comment response which isn't really a comment: Basically the way to do this in VBA is to traverse the child nodes. The problem is you don't get the correct return types. You could fix this by making your own classes that (separately) implement IHTMLElement and IHTMLElementCollection; but that's WAY too much of a pain for me to do it without getting paid :). If you're determined, go and read up on the Implements keyword for VB6/VBA.
Public Function getSubElementsByTagName(el As IHTMLElement, tagname As String) As Collection
Dim descendants As New Collection
Dim results As New Collection
Dim i As Long
getDescendants el, descendants
For i = 1 To descendants.Count
If descendants(i).tagname = tagname Then
results.Add descendants(i)
End If
Next i
getSubElementsByTagName = results
End Function
Public Function getDescendants(nd As IHTMLElement, ByRef descendants As Collection)
Dim i As Long
descendants.Add nd
For i = 1 To nd.Children.Length
getDescendants nd.Children.Item(i), descendants
Next i
End Function
For me it works this way:
putty -ssh [email protected] 22 -pw password
putty, protocol, user name @ ip address port and password. To connect in less than a second.
The HtmlDocument
class is a wrapper around the native IHtmlDocument2
COM interface.
You cannot easily create it from a string.
You should use the HTML Agility Pack.
Just to bump the thread, I've tried DOMPDF and it worked perfectly. I've used DIV
and other block level elements to position everything, I kept it strictly CSS 2.1 and it played very nicely.
They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).
The main equations are:
frame.origin = center - bounds.size / 2
(which is the same as)
center = frame.origin + bounds.size / 2
(and there’s also)
frame.size = bounds.size
That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.
This stuff is all explained in more detail with a useful mini-library here:
Here's an example update trigger:
create table Employees (id int identity, Name varchar(50), Password varchar(50))
create table Log (id int identity, EmployeeId int, LogDate datetime,
OldName varchar(50))
go
create trigger Employees_Trigger_Update on Employees
after update
as
insert into Log (EmployeeId, LogDate, OldName)
select id, getdate(), name
from deleted
go
insert into Employees (Name, Password) values ('Zaphoid', '6')
insert into Employees (Name, Password) values ('Beeblebox', '7')
update Employees set Name = 'Ford' where id = 1
select * from Log
This will print:
id EmployeeId LogDate OldName
1 1 2010-07-05 20:11:54.127 Zaphoid
A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.
If this is happening intermittently, then the most likely explanations are (IMO):
Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.
It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.
1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.
This worked fine !
var fd = new FormData();
$('input[type="file"]').on('change', function (e) {
[].forEach.call(this.files, function (file) {
fd.append('filename[]', file);
});
});
$.ajax({
url: '/url/to/post/on',
method: 'post',
data: fd,
contentType: false,
processData: false,
success: function (response) {
console.log(response)
},
error: function (err) {
console.log(err);
}
});
To see your log in SQL Developer
then press:
CTRL+SHIFT + L (or CTRL + CMD + L on macOS)
or
View -> Log
or by using mysql query
show errors;
public void AnalyseArray(ArrayList<Integer> array) {
// Do something
}
...
ArrayList<Integer> A = new ArrayList<Integer>();
AnalyseArray(A);
A quick way to explain this is to visualize it.
if both i and j are from 0 to N, it's easy to see O(N^2)
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
in this case, it's:
O
O O
O O O
O O O O
O O O O O
O O O O O O
O O O O O O O
O O O O O O O O
This comes out to be 1/2 of N^2, which is still O(N^2)
When I've stumbled upon this problem I usually start looking at the places where I FreeAndNil() or just xxx := NIL; variables and the code after that.
When nothing else has helped I've added a Log() function to output messages from various suspect places during execution, and then later looked at that log to trace where in the code the access violation comes.
There are ofcourse many more elegant solutions available for tracing these violations, but if you do not have them at your disposal the old-fashioned trial & error method works fine.
Note: The following only works for the next line of code, and only due to a coincidence.
With Lodash,
require('lodash');
_.isArray([]); // true
No var _ = require('lodash')
since Lodash mysteriously sets this value globally when required.
51Degrees' PHP solution is able to do this. you can get the free Open Source API here https://github.com/51Degrees/Device-Detection. You can use the HardwareFamily Property to determine if it is an iPad/iPod/iPhone etc.
Due to the nature of Apple's User-Agents the initial result will return a generic device, however if you are interested in the specific device you can use a JavaScript client side override to determine to specific model.
To do this you can implement something similar to the following logic once you have determined it is an Apple Device, in this case for an iPhone.
// iPhone model checks.
function getiPhoneModel() {
// iPhone 6 Plus
if ((window.screen.height / window.screen.width == 736 / 414) &&
(window.devicePixelRatio == 3)) {
return "iPhone 6 Plus";
}
// iPhone 6
else if ((window.screen.height / window.screen.width == 667 / 375) &&
(window.devicePixelRatio == 2)) {
return "iPhone 6";
}
// iPhone 5/5C/5S or 6 in zoom mode
else if ((window.screen.height / window.screen.width == 1.775) &&
(window.devicePixelRatio == 2)) {
return "iPhone 5, 5C, 5S or 6 (display zoom)";
}
// iPhone 4/4S
else if ((window.screen.height / window.screen.width == 1.5) &&
(window.devicePixelRatio == 2)) {
return "iPhone 4 or 4S";
}
// iPhone 1/3G/3GS
else if ((window.screen.height / window.screen.width == 1.5) &&
(window.devicePixelRatio == 1)) {
return "iPhone 1, 3G or 3GS";
} else {
return "Not an iPhone";
};
}
Or for an iPad
function getiPadVersion() {
var pixelRatio = getPixelRatio();
var return_string = "Not an iPad";
if (pixelRatio == 1 ) {
return_string = "iPad 1, iPad 2, iPad Mini 1";
}
if (pixelRatio == 2) {
return_string = "iPad 3, iPad 4, iPad Air 1, iPad Air 2, iPad Mini 2, iPad
Mini 3";
}
return return_string;
}
For more information on research 51Degrees have done into Apple devices you can read their blog post here https://51degrees.com/blog/device-detection-for-apple-iphone-and-ipad.
Disclosure: I work for 51Degrees.
'''my file name is
"0_male_0.wav", "0_male_2.wav"... "0_male_30.wav"...
"1_male_0.wav", "1_male_2.wav"... "1_male_30.wav"...
"8_male_0.wav", "8_male_2.wav"... "8_male_30.wav"
when I wav.read(files) I want to read them in a sorted torder, i.e., "0_male_0.wav"
"0_male_1.wav"
"0_male_2.wav" ...
"0_male_30.wav"
"1_male_0.wav"
"1_male_1.wav"
"1_male_2.wav" ...
"1_male_30.wav"
so this is how I did it.
Just take all files start with "0_*" as an example. Others you can just put it in a loop
'''
import scipy.io.wavfile as wav
import glob
from os.path import isfile, join
#get all the file names in file_names. THe order is totally messed up
file_names = [f for f in listdir(audio_folder_dir) if isfile(join(audio_folder_dir, f)) and '.wav' in f]
#find files that belongs to "0_*" group
filegroup0 = glob.glob(audio_folder_dir+'/0_*')
#now you get sorted files in group '0_*' by the last number in the filename
filegroup0 = sorted(filegroup0, key=getKey)
def getKey(filename):
file_text_name = os.path.splitext(os.path.basename(filename)) #you get the file's text name without extension
file_last_num = os.path.basename(file_text_name[0]).split('_') #you get three elements, the last one is the number. You want to sort it by this number
return int(file_last_num[2])
That's how I did my particular case. Hope it's helpful.
here is what i put into package.json (running angular 6):
{
"name": "local-weather-app",
"version": "1.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --port 5000",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
Then a plain npm start will pull in the contents of start. Could also add other options to contents
var min = dt.AsEnumerable().Min(row => row["AccountLevel"]);
var max = dt.AsEnumerable().Max(row => row["AccountLevel"]);
NoClassDefFoundError
is a linkage error basically. It occurs when you try and instantiate an object (statically with "new") and it's not found when it was during compilation.
ClassNotFoundException
is more general and is a runtime exception when you try to use a class that doesn't exist. For example, you have a parameter in a function accepts an interface and someone passes in a class that implements that interface but you don't have access to the class. It also covers case of dynamic class loading, such as using loadClass()
or Class.forName()
.
I like using a function decorator. I added a class, which also times the function time. Assume gLog is a standard python logger:
class EnterExitLog():
def __init__(self, funcName):
self.funcName = funcName
def __enter__(self):
gLog.debug('Started: %s' % self.funcName)
self.init_time = datetime.datetime.now()
return self
def __exit__(self, type, value, tb):
gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))
def func_timer_decorator(func):
def func_wrapper(*args, **kwargs):
with EnterExitLog(func.__name__):
return func(*args, **kwargs)
return func_wrapper
so now all you have to do with your function is decorate it and voila
@func_timer_decorator
def my_func():
If you will use pre defined delete methods as directly provided by spring JPA then below two queries will be execute by the framework.
First collect data(like id and other column) using by execute select query with delete query where clause.
then after getting resultSet of first query, second delete queries will be execute for all id(one by one)
Note : This is not optimized way for your application because many queries will be execute for single MYSQL delete query.
This is another optimized way for delete query code because only one delete query will execute by using below customized methods.
@NamedNativeQueries({
@NamedNativeQuery(name = "Abc.deleteByCreatedTimeBetween",
query = "DELETE FROM abc WHERE create_time BETWEEN ?1 AND ?2")
,
@NamedNativeQuery(name = "Abc.getByMaxId",
query = "SELECT max(id) from abc")
})
@Entity
public class Abc implements Serializable {
}
@Repository
public interface AbcRepository extends CrudRepository {
int getByMaxId();
@Transactional
@Modifying
void deleteByCreatedTimeBetween(String startDate, String endDate);
}
Swift 4+
button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
Try below jQuery snippet, you can change color :
<script type="text/javascript">
$(document).ready(function(){
$("#co").click(function() {
$("body").css("background-color", "yellow");
});
});
</script>
$(document).ready(function(){_x000D_
$("#co").click(function() {_x000D_
$("body").css("background-color", "yellow");_x000D_
});_x000D_
});
_x000D_
body {_x000D_
background-color:red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="co" click="change()">hello</div>
_x000D_
The column in the database is probably a DECIMAL
. You should process it as a BigInteger
, not an Integer
, otherwise you are losing digits. Or else change the column to int
.
Linux corrects for discrepancies between CPUs, but Windows does not. I suggest you assume System.nanoTime() is only accurate to around 1 micro-second. A simple way to get a longer timing is to call foo() 1000 or more times and divide the time by 1000.
You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?
but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
That is what xrange(n)
is for. It avoids creating a list of numbers, and instead just provides an iterator object.
In Python 3, xrange()
was renamed to range()
- if you want a list, you have to specifically request it via list(range(n))
.
There is good information on curl's page on SSL and certificate issues. I base most of my answer on the information there.
Using strict-ssl false is bad practice and can create issues. What we can do instead is add the certificate that is being injected, by the "man in the middle" certificate.
How to solve this on Windows:
openssl x509 -inform DES -in **rootcert**.cer -out outcert.pem -text
npm config set cafile **C:\Users\username\cacert.pem
npm config set strict-ssl true
Phew! We made it! Now npm can understand how to connect. Bonus is that you can tell curl to use the same cabundle.pem and it will also understand HTTPs.
My solution (vb.net):
Private Function ConvertToBoolean(p1 As Object) As Boolean
If p1 Is Nothing Then Return False
If IsDBNull(p1) Then Return False
If p1.ToString = "1" Then Return True
If p1.ToString.ToLower = "true" Then Return True
Return False
End Function
You can add a little syntax sugar to the above solution with the following:
class Time
def to_ms
(self.to_f * 1000.0).to_i
end
end
start_time = Time.now
sleep(3)
end_time = Time.now
elapsed_time = end_time.to_ms - start_time.to_ms # => 3004
I tried Noah's suggestion which leads to the best solution up to now.
Just insert \let\cleardoublepage\clearpage
before all the parts with the blank pages
Especially when you use \documentclass[12pt,a4paper]{book}
frederic snyers's advice \documentclass[oneside]{book}
is also very good and solves the problem, but if we just want to use the book.cls or article.cls, the one would make a big difference presenting your particles.
Hence, Big support to \let\cleardoublepage\clearpage
for the people who will ask the same question in the future.
Two ideas:
Just a slight addition to the above solution if you are having problem with downloaded file's name...
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
This will return the exact file name even if it contains spaces or other characters.
Yes. If you want to fetch a limited subset of objects, you can with the below code:
Example:
obj=emp.objects.all()[0:10]
The beginning 0 is optional, so
obj=emp.objects.all()[:10]
The above code returns the first 10 instances.
As a good example may be worth it to navigate to this project and see how to handle exiting processes grammatically or in this snippet from VM found in here
ConsoleOutputStream = new ObservableCollection<string>();
var startInfo = new ProcessStartInfo(FilePath)
{
WorkingDirectory = RootFolderPath,
Arguments = StartingArguments,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
ConsoleProcess = new Process {StartInfo = startInfo};
ConsoleProcess.EnableRaisingEvents = true;
ConsoleProcess.OutputDataReceived += (sender, args) =>
{
App.Current.Dispatcher.Invoke((System.Action) delegate
{
ConsoleOutputStream.Insert(0, args.Data);
//ConsoleOutputStream.Add(args.Data);
});
};
ConsoleProcess.Exited += (sender, args) =>
{
InProgress = false;
};
ConsoleProcess.Start();
ConsoleProcess.BeginOutputReadLine();
}
}
private void RegisterProcessWatcher()
{
startWatch = new ManagementEventWatcher(
new WqlEventQuery($"SELECT * FROM Win32_ProcessStartTrace where ProcessName = '{FileName}'"));
startWatch.EventArrived += new EventArrivedEventHandler(startProcessWatch_EventArrived);
stopWatch = new ManagementEventWatcher(
new WqlEventQuery($"SELECT * FROM Win32_ProcessStopTrace where ProcessName = '{FileName}'"));
stopWatch.EventArrived += new EventArrivedEventHandler(stopProcessWatch_EventArrived);
}
private void stopProcessWatch_EventArrived(object sender, EventArrivedEventArgs e)
{
InProgress = false;
}
private void startProcessWatch_EventArrived(object sender, EventArrivedEventArgs e)
{
InProgress = true;
}
Angular.js creates a watcher for every model we create in view. Whenever a model is changed, an "ng-dirty" class is appeneded to the model, so the watcher will observe all models which have the class "ng-dirty" & update their values in the controller & vice versa.
You could use the CSS calc
parameter to calculate the height dynamically like so:
.dynamic-height {_x000D_
color: #000;_x000D_
font-size: 12px;_x000D_
margin-top: calc(100% - 10px);_x000D_
text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
This is an old question but Oracle's latest installers are no improvement, so I recently found myself back in this swamp, thrashing around for several days ...
My scenario was SQL Server 2016 RTM. 32-bit Oracle 12c Open Client + ODAC was eventually working fine for Visual Studio Report Designer and Integration Services designer, and also SSIS packages run through SQL Server Agent (with 32-bit option). 64-bit was working fine for Report Portal when defining and Testing an Data Source, but running the reports always gave the dreaded "ORA-12154" error.
My final solution was to switch to an EZCONNECT connection string - this avoids the TNSNAMES mess altogether. Here's a link to a detailed description, but it's basically just: host:port/sid
In case it helps anyone in the future (or I get stuck on this again), here are my Oracle install steps (the full horror):
Install Oracle drivers: Oracle Client 12c (32-bit) plus ODAC.
a. Download and unzip the following files from http://www.oracle.com/technetwork/database/enterprise-edition/downloads/database12c-win64-download-2297732.html and http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html ):
i. winnt_12102_client32.zip
ii. ODAC112040Xcopy_32bit.zip
b. Run winnt_12102_client32\client32\setup.exe. For the Installation Type, choose Admin. For the installation location enter C:\Oracle\Oracle12. Accept other defaults.
c. Start a Command Prompt “As Administrator” and change directory (cd) to your ODAC112040Xcopy_32bit folder.
d. Enter the command: install.bat all C:\Oracle\Oracle12 odac
e. Copy the tnsnames.ora file from another machine to these folders: *
i. C:\Oracle\Oracle12\network\admin *
ii. C:\Oracle\Oracle12\product\12.1.0\client_1\network\admin *
Install Oracle Client 12c (x64) plus ODAC
a. Download and unzip the following files from http://www.oracle.com/technetwork/database/enterprise-edition/downloads/database12c-win64-download-2297732.html and http://www.oracle.com/technetwork/database/windows/downloads/index-090165.html ):
i. winx64_12102_client.zip
ii. ODAC121024Xcopy_x64.zip
b. Run winx64_12102_client\client\setup.exe. For the Installation Type, choose Admin. For the installation location enter C:\Oracle\Oracle12_x64. Accept other defaults.
c. Start a Command Prompt “As Administrator” and change directory (cd) to the C:\Software\Oracle Client\ODAC121024Xcopy_x64 folder.
d. Enter the command: install.bat all C:\Oracle\Oracle12_x64 odac
e. Copy the tnsnames.ora file from another machine to these folders: *
i. C:\Oracle\Oracle12_x64\network\admin *
ii. C:\Oracle\Oracle12_x64\product\12.1.0\client_1\network\admin *
* If you are going with the EZCONNECT method, then these steps are not required.
The ODAC installs are tricky and obscure - thanks to Dan English who gave me the method (detailed above) for that.
You can use Tikz/pgfplots for creating animations in beamer. http://www.texample.net/tikz/examples/tag/animations/
In sequence:
adb kill-server
in your DEVICE SETUP, go to developer-options end disable usb-debugging
press REVOKE USB debugging authorizations, click OK
enable usb-debugging
adb start-server
if you get "unexpected Character" error you should check if there is a BOM (Byte Order Marker saved into your utf-8 json. You can either remove the first character or save if without BOM.
I had the same error and SOLVED by removing the DB roles db_denydatawriter
and db_denydatreader
of the DB user. For that, select the appropriate DB user on logins >> properties >> user mappings >> find out DB and select it >> uncheck the mentioned Db user roles. Thats it !!
In App.config:
<add key="YOURKEY" value="a,b,c"/>
In C#:
string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);
Just to contribute with my approach. As already answered, RetryPolicy
is the way to go. But if you need a policy different the than default for all your requests, you can set it in a base Request class, so you don't need to set the policy for all the instances of your requests.
Something like this:
public class BaseRequest<T> extends Request<T> {
public BaseRequest(int method, String url, Response.ErrorListener listener) {
super(method, url, listener);
setRetryPolicy(getMyOwnDefaultRetryPolicy());
}
}
In my case I have a GsonRequest which extends from this BaseRequest, so I don't run the risk of forgetting to set the policy for an specific request and you can still override it if some specific request requires to.
Given a staging table with 70 columns and only 4 representing duplicates, this code will return the offending columns:
SELECT
COUNT(*)
,LTRIM(RTRIM(S.TransactionDate))
,LTRIM(RTRIM(S.TransactionTime))
,LTRIM(RTRIM(S.TransactionTicketNumber))
,LTRIM(RTRIM(GrossCost))
FROM Staging.dbo.Stage S
GROUP BY
LTRIM(RTRIM(S.TransactionDate))
,LTRIM(RTRIM(S.TransactionTime))
,LTRIM(RTRIM(S.TransactionTicketNumber))
,LTRIM(RTRIM(GrossCost))
HAVING COUNT(*) > 1
.
I guess you're using windows 7 with the Orwell Dev CPP
This version of Dev CPP is good for windows 8 only. However on Windows 7 you need the older version of it which is devcpp-4.9.9.2_setup.exe Download it from the link and use it. (Don't forget to uninstall any other version already installed on your pc) Also note that the older version does not work with windows 8.
Follow the other answer, and if it's still not working, restart your computer to effectively restart the SQL Server service on Windows.
If you want to run a script without modifying the default script execution policy, you can use the bypass switch when launching Windows PowerShell.
powershell [-noexit] -executionpolicy bypass -File <Filename>
if you are using width
and height
, you should try margin-right: 45%;
... it is 100% working for me.. so i can take it to anywhere with percentage!
Got a bit confused from the top answers so I've wrote a small gist with examples for better understanding.
Option #1 - socket.settimeout()
Will raise an exception in case the sock.recv()
waits for more than the defined timeout.
import socket
sock = socket.create_connection(('neverssl.com', 80))
timeout_seconds = 2
sock.settimeout(timeout_seconds)
sock.send(b'GET / HTTP/1.1\r\nHost: neverssl.com\r\n\r\n')
data = sock.recv(4096)
data = sock.recv(4096) # <- will raise a socket.timeout exception here
Option #2 - select.select()
Waits until data is sent until the timeout is reached. I've tweaked Daniel's answer so it will raise an exception
import select
import socket
def recv_timeout(sock, bytes_to_read, timeout_seconds):
sock.setblocking(0)
ready = select.select([sock], [], [], timeout_seconds)
if ready[0]:
return sock.recv(bytes_to_read)
raise socket.timeout()
sock = socket.create_connection(('neverssl.com', 80))
timeout_seconds = 2
sock.send(b'GET / HTTP/1.1\r\nHost: neverssl.com\r\n\r\n')
data = recv_timeout(sock, 4096, timeout_seconds)
data = recv_timeout(sock, 4096, timeout_seconds) # <- will raise a socket.timeout exception here
I use a variation of one of the answers here. I want to replace spaces with "-" so its SEO friendly and also make lower case. Also not reference system.web from my services layer.
private string MakeUrlString(string input)
{
var array = input.ToCharArray();
array = Array.FindAll<char>(array, c => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-');
var newString = new string(array).Replace(" ", "-").ToLower();
return newString;
}
Batch file for setting a new dns server
@echo off
rem usage: setdns <dnsserver> <interface>
rem default dsnserver is dhcp
rem default interface is Wi-Fi
set dnsserver="%1"
if %dnsserver%=="" set dnsserver="dhcp"
set interface="%2"
if %interface%=="" set interface="Wi-Fi"
echo Showing current DNS setting for interface a%interface%
netsh interface ipv4 show dnsserver %interface%
echo Changing dnsserver on interface %interface% to %dnsserver%
if %dnsserver% == "dhcp" netsh interface ipv4 set dnsserver %interface% %dnsserver%
if NOT %dnsserver% == "dhcp" netsh interface ipv4 add dnsserver %interface% address=%dnsserver% index=1
echo Showing new DNS setting for interface %interface%
netsh interface ipv4 show dnsserver %interface%
/*
* Thrown when a version number or timestamp check failed, indicating that the
* Session contained stale data (when using long transactions with versioning).
* Also occurs if we try delete or update a row that does not exist.
*
*/
if ( expectedRowCount > rowCount ) {
throw new StaleStateException(
"Batch update returned unexpected row count from update [" + batchPosition +"]; actual row count: " + rowCount +"; expected: " + expectedRowCount);
}
<property name="show_sql">true</property>
This should show you the SQL that is executed and causes the problem.
*The StaleStateException would be thrown only after we successfully deleted one object, and then tried to delete another. The reason for this is, while persisting the objects across sessions, objects must first be deleted from the Session before deleted. Otherwise, subsequent deletes will cause the StaleStateException
to be thrown.
Session.Remove(obj);
objectDAO.Delete(obj);
*The problem was that a table must have only one field that is primary key (I had a composite key and this is not a good idea, except for the many to many relation). I have solved using a new id table field auto incremental.
*It can be fix by using Hibernate session.update()
-- you need to have the table/view's primary key equal your corresponding bean property (eg. id).
*
#include <stdio.h>
#include <string.h>
int main ()
{
char buf[] ="abc/qwe/ccd";
int i = 0;
char *p = strtok (buf, "/");
char *array[3];
while (p != NULL)
{
array[i++] = p;
p = strtok (NULL, "/");
}
for (i = 0; i < 3; ++i)
printf("%s\n", array[i]);
return 0;
}
Here's what I found that worked for being able to get the deployed folder location of my clickonce application and that hasn't been mentioned anywhere I saw in my searches, for my similar, specific scenario:
Here is a visual of my use case:
I did not find any of the suggestions in this question or their comments to work in returning the folder that the clickonce application was deployed to (that I would then move relative to this folder to find the folder of interest). No other internet searching or related SO questions turned up an answer either.
All of the suggested properties either were failing due to the object (e.g. ActivationUri) being null, or were pointing to the local PC's cached installed app folder. Yes, I could gracefully handle null objects by a check for IsNetworkDeployed - that's not a problem - but surprisingly IsNetworkDeployed returns false even though I do in fact have a network deployed folder location for the clickonce application. This is because the application is running from the local, cached bits.
The solution is to look at:
AppDomain.CurrentDomain.BaseDirectory
when the application is being run within visual studio as I develop andSystem.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation
when it is executing normally.System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation
correctly returns the network directory that my clickonce application is deployed to, in all cases. That is, when it is launched via:
Here's the code I use at application startup to get the path of the WorkAccounts folder. Getting the deployed application folder is simple by just not marching up to parent directories:
string directoryOfInterest = "";
if (System.Diagnostics.Debugger.IsAttached)
{
directoryOfInterest = Directory.GetParent(Directory.GetParent(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).FullName).FullName).FullName;
}
else
{
try
{
string path = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation.ToString();
path = path.Replace("file:", "");
path = path.Replace("/", "\\");
directoryOfInterest = Directory.GetParent(Directory.GetParent(path).FullName).FullName;
}
catch (Exception ex)
{
directoryOfInterest = "Error getting update directory needed for relative base for finding WorkAccounts directory.\n" + ex.Message + "\n\nUpdate location directory is: " + System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation.ToString();
}
}
For those who want a "standard" text formatting of the hash, you can use something like the following:
static string Hash(string input)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
{
// can be "x2" if you want lowercase
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
}
This will produce a hash like 0C2E99D0949684278C30B9369B82638E1CEAD415
.
Or for a code golfed version:
static string Hash(string input)
{
var hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input));
return string.Concat(hash.Select(b => b.ToString("x2")));
}
go to cmd and enter the following command:
C:\Users{usernamehere}\Documents\Downloads\netbeans-{version}.exe –-javahome "C:\Program Files (x86)\Java\jdk{version}"
before it make sure you have properly set the environment variable. If it is not works than check compatibility of program or reinstall jdk appropriately and set environment again and do as above command.
You can use _.mapValues(users, function(o) { return o.age; });
in Lodash and _.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });
in Underscore.
Check out the cross-documentation here: http://jonathanpchen.com/underdash-api/#mapvalues-object-iteratee-identity
nbconvert allows you to run notebooks with the --execute
flag:
jupyter nbconvert --execute <notebook>
If you want to run a notebook and produce a new notebook, you can add --to notebook
:
jupyter nbconvert --execute --to notebook <notebook>
Or if you want to replace the existing notebook with the new output:
jupyter nbconvert --execute --to notebook --inplace <notebook>
Since that's a really long command, you can use an alias:
alias nbx="jupyter nbconvert --execute --to notebook"
nbx [--inplace] <notebook>
As firefox does not stringify some object as screen object ; if you want to have the same result such as : JSON.stringify(obj)
:
function objToString (obj) {
var tabjson=[];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
tabjson.push('"'+p +'"'+ ':' + obj[p]);
}
} tabjson.push()
return '{'+tabjson.join(',')+'}';
}
Jaminto did a great job of answering the question, but I recently went through the process myself and wanted to expand on Jaminto's answer.
I'm assuming that you already have an EC2 instance created and have associated an Elastic IP Address to it.
SSH to your EC2 server. Type:
> sudo yum install vsftpd
This should install vsftpd.
Next, you'll need to open up the FTP ports on your EC2 server. Log in to the AWS EC2 Management Console and select Security Groups from the navigation tree on the left. Select the security group assigned to your EC2 instance. Then select the Inbound tab, then click Edit:
Add two Custom TCP Rules with port ranges 20-21 and 1024-1048. For Source, you can select 'Anywhere'. If you decide to set Source to your own IP address, be aware that your IP address might change if it is being assigned via DHCP.
Edit your vsftpd conf file by typing:
> sudo vi /etc/vsftpd/vsftpd.conf
Disable anonymous FTP by changing this line:
anonymous_enable=YES
to
anonymous_enable=NO
Then add the following lines to the bottom of the vsftpd.conf file:
pasv_enable=YES
pasv_min_port=1024
pasv_max_port=1048
pasv_address=<Public IP of your instance>
Your vsftpd.conf file should look something like the following - except make sure to replace the pasv_address with your public facing IP address:
To save changes, press escape, then type :wq
, then hit enter.
Restart vsftpd by typing:
> sudo /etc/init.d/vsftpd restart
You should see a message that looks like:
If this doesn't work, try:
> sudo /sbin/service vsftpd restart
If you take a peek at /etc/vsftpd/user_list, you'll see the following:
# vsftpd userlist
# If userlist_deny=NO, only allow users in this file
# If userlist_deny=YES (default), never allow users in this file, and
# do not even prompt for a password.
# Note that the default vsftpd pam config also checks /etc/vsftpd/ftpusers
# for users that are denied.
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
news
uucp
operator
games
nobody
This is basically saying, "Don't allow these users FTP access." vsftpd will allow FTP access to any user not on this list.
So, in order to create a new FTP account, you may need to create a new user on your server. (Or, if you already have a user account that's not listed in /etc/vsftpd/user_list, you can skip to the next step.)
Creating a new user on an EC2 instance is pretty simple. For example, to create the user 'bret', type:
> sudo adduser bret
> sudo passwd bret
Here's what it will look like:
At this point, your FTP users are not restricted to their home directories. That's not very secure, but we can fix it pretty easily.
Edit your vsftpd conf file again by typing:
> sudo vi /etc/vsftpd/vsftpd.conf
Un-comment out the line:
chroot_local_user=YES
It should look like this once you're done:
Restart the vsftpd server again like so:
> sudo /etc/init.d/vsftpd restart
All done!
vsftpd doesn't automatically start when your server boots. If you're like me, that means that after rebooting your EC2 instance, you'll feel a moment of terror when FTP seems to be broken - but in reality, it's just not running!. Here's a handy way to fix that:
> sudo chkconfig --level 345 vsftpd on
Alternatively, if you are using redhat, another way to manage your services is by using this nifty graphic user interface to control which services should automatically start:
> sudo ntsysv
Now vsftpd will automatically start up when your server boots up.
* NOTE: Iman Sedighi has posted a more elegant solution for restricting users access to a specific directory. Please refer to his excellent solution posted as an answer *
You might want to create a user and restrict their FTP access to a specific folder, such as /var/www. In order to do this, you'll need to change the user's default home directory:
> sudo usermod -d /var/www/ username
In this specific example, it's typical to give the user permissions to the 'www' group, which is often associated with the /var/www folder:
> sudo usermod -a -G www username
Use env
.
For example, env FOO=BAR command
. Note that the environment variables will be restored/unchanged again when command
finishes executing.
Just be careful about about shell substitution happening, i.e. if you want to reference $FOO
explicitly on the same command line, you may need to escape it so that your shell interpreter doesn't perform the substitution before it runs env
.
$ export FOO=BAR
$ env FOO=FUBAR bash -c 'echo $FOO'
FUBAR
$ echo $FOO
BAR
remove_indices = [1,2,3]
somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
Example:
In [9]: remove_indices = [1,2,3]
In [10]: somelist = range(10)
In [11]: somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
In [12]: somelist
Out[12]: [0, 4, 5, 6, 7, 8, 9]
To add previous iOS simulator to Xcode 4.2, you need old xcode_3.2.6_and_ios_sdk_4.3.dmg (or similar version) installer file and do as following:
Now there are a list of your installed simulator.
example to uninstall package 'oauth2client' on MacOS:
pip uninstall oauth2client
One case when reinterpret_cast
is necessary is when interfacing with opaque data types. This occurs frequently in vendor APIs over which the programmer has no control. Here's a contrived example where a vendor provides an API for storing and retrieving arbitrary global data:
// vendor.hpp
typedef struct _Opaque * VendorGlobalUserData;
void VendorSetUserData(VendorGlobalUserData p);
VendorGlobalUserData VendorGetUserData();
To use this API, the programmer must cast their data to VendorGlobalUserData
and back again. static_cast
won't work, one must use reinterpret_cast
:
// main.cpp
#include "vendor.hpp"
#include <iostream>
using namespace std;
struct MyUserData {
MyUserData() : m(42) {}
int m;
};
int main() {
MyUserData u;
// store global data
VendorGlobalUserData d1;
// d1 = &u; // compile error
// d1 = static_cast<VendorGlobalUserData>(&u); // compile error
d1 = reinterpret_cast<VendorGlobalUserData>(&u); // ok
VendorSetUserData(d1);
// do other stuff...
// retrieve global data
VendorGlobalUserData d2 = VendorGetUserData();
MyUserData * p = 0;
// p = d2; // compile error
// p = static_cast<MyUserData *>(d2); // compile error
p = reinterpret_cast<MyUserData *>(d2); // ok
if (p) { cout << p->m << endl; }
return 0;
}
Below is a contrived implementation of the sample API:
// vendor.cpp
static VendorGlobalUserData g = 0;
void VendorSetUserData(VendorGlobalUserData p) { g = p; }
VendorGlobalUserData VendorGetUserData() { return g; }
Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.
If you make Dict
into an object, this will work:
var dict = {};
var addPair = function (myKey, myValue) {
dict[myKey] = myValue;
};
var giveValue = function (myKey) {
return dict[myKey];
};
The myKey
variable is already a string, so you don't need more quotes.
Just change your line of code to
<a href="~/Required/[email protected]">Edit</a>
from where you are calling this function that will pass corect id
something like this:
public int PowerRating
{
get { return base.PowerRating; } // if power inherits from meter...
}
Got into django recently and been looking into a solution to that and found a method that might be useful.
So for example, if using allouth the default redirect is accounts/profile. Make a view that solely redirects to a location of choice using the username field like so:
def profile(request):
name=request.user.username
return redirect('-----choose where-----' + name + '/')
Then create a view that captures it in one of your apps, for example:
def profile(request, name):
user = get_object_or_404(User, username=name)
return render(request, 'myproject/user.html', {'profile': user})
Where the urlpatterns capture would look like this:
url(r'^(?P<name>.+)/$', views.profile, name='user')
Works well for me.
At first install necessary PDO parts by running the command
`sudo apt-get install php*-mysql`
where * is a version name of php like 5.6, 7.0, 7.1, 7.2
After installation you need to mention these two statements
extension=pdo.so
extension=pdo_mysql.so
in your .ini file (uncomment if it is already there) and restart server by command
sudo service apache2 restart
You need to look for "waiting to lock" in /data/anr/traces.txt file
for more details: Engineer for High Performance with Tools from Android & Play (Google I/O '17)
The swoole extension. https://github.com/matyhtf/swoole Asynchronous & concurrent networking framework for PHP.
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function($cli) {
$cli->send("hello world\n");
});
$client->on("receive", function($cli, $data){
echo "Receive: $data\n";
});
$client->on("error", function($cli){
echo "connect fail\n";
});
$client->on("close", function($cli){
echo "close\n";
});
$client->connect('127.0.0.1', 9501, 0.5);
You can save the current scroll amount and then set it later:
var tempScrollTop = $(window).scrollTop();
..//Your code
$(window).scrollTop(tempScrollTop);
Chris Stewart wrote there:
Splash screens just waste your time, right? As an Android developer, when I see a splash screen, I know that some poor dev had to add a three-second delay to the code.
Then, I have to stare at some picture for three seconds until I can use the app. And I have to do this every time it’s launched. I know which app I opened. I know what it does. Just let me use it!
Splash Screens the Right Way
I believe that Google isn’t contradicting itself; the old advice and the new stand together. (That said, it’s still not a good idea to use a splash screen that wastes a user’s time. Please don’t do that.)
However, Android apps do take some amount of time to start up, especially on a cold start. There is a delay there that you may not be able to avoid. Instead of leaving a blank screen during this time, why not show the user something nice? This is the approach Google is advocating. Don’t waste the user’s time, but don’t show them a blank, unconfigured section of the app the first time they launch it, either.
If you look at recent updates to Google apps, you’ll see appropriate uses of the splash screen. Take a look at the YouTube app, for example.
I had a similar problem with wget to my own live web site returning errors after installing a new SSL certificate. I'd already checked several browsers and they didn't report any errors:
wget --no-cache -O - "https://example.com/..." ERROR: The certificate of ‘example.com’ is not trusted. ERROR: The certificate of ‘example.com’ hasn't got a known issuer.
The problem was I had installed the wrong certificate authority .pem/.crt file from the issuer. Usually they bundle the SSL certificate and CA file as a zip file, but DigiCert email you the certificate and you have to figure out the matching CA on your own. https://www.digicert.com/help/ has an SSL certificate checker which lists the SSL authority and the hopefully matching CA with a nice blue link graphic if they agree:
`SSL Cert: Issuer GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1
CA: Subject GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1 Valid from 16/Jul/2020 to 31/May/2023 Issuer DigiCert Global Root CA`
Input: 0 0.1 1000
=FIXED(E5,2)
Output: 0.00 0.10 1,000.00
=TEXT(E5,"0.00")
Output: 0.00 0.10 1000.00
Note: As you can see FIXED add a coma after a thousand, where TEXT does not.
The variable name you're looking for is ansible_ssh_private_key_file
.
You should set it at 'vars' level:
in the inventory file:
myHost ansible_ssh_private_key_file=~/.ssh/mykey1.pem
myOtherHost ansible_ssh_private_key_file=~/.ssh/mykey2.pem
in the host_vars
:
# hosts_vars/myHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey1.pem
# hosts_vars/myOtherHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey2.pem
in a group_vars
file if you use the same key for a group of hosts
in the vars
section of your play:
- hosts: myHost
remote_user: ubuntu
vars_files:
- vars.yml
vars:
ansible_ssh_private_key_file: "{{ key1 }}"
tasks:
- name: Echo a hello message
command: echo hello
I did it even simpler. Problem: A CSS file had url links to img folder. Gets 404.
I looked at url, http://tomcatfolder:port/img/blablah.png, which does not exist. But, that is really pointing to the ROOT app in Tomcat.
So I just copied the img folder from my webapp into that ROOT app. Works!
Not recommended for production, of course, but this is for an internal tool dev app.
This method work for me:
DELIMITER $$
DROP PROCEDURE IF EXISTS db.test $$
CREATE PROCEDURE db.test(IN id INT(12),IN NAME VARCHAR(255))
BEGIN
INSERT INTO USER VALUES(id,NAME);
END$$
DELIMITER ;
short answer, specific to OAuth2,
Are you sure you can't just run cl.exe without any input for it to report its version?
I've just tested running cl.exe in the command prompt for VS 2008, 2005, and .NET 2003 and they all reported its version.
For 2008:
d:\Program Files\Microsoft Visual Studio 9.0\VC>cl
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
For 2005, SP 1 (added Safe Standard C++ classes):
C:\Program Files\Microsoft Visual Studio 8\VC>cl
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86
For 2005:
C:\Program Files\Microsoft Visual Studio 8\VC>cl
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42 for 80x86
For .NET 2003:
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.6030 for 80x86
EDIT
For 2010, it will be along the line of:
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.XX.YYYYY.ZZ for 80x86
or depending on targeted platform
Microsoft (R) C/C++ Optimizing Compiler Version 16.XX.YYYYY.ZZ for x64
For 2012:
Microsoft (R) C/C++ Optimizing Compiler Version 17.XX.YYYYY.ZZ for $$$
where $$$ is the targeted platform (e.g. x86, x64, ARM), and XX, YYYYY, and ZZ are minor version numbers.
For 2013:
Microsoft (R) C/C++ Optimizing Compiler Version 18.XX.YYYYY.ZZ for $$$
where $$$ is the targeted platform (e.g. x86, x64, ARM), and XX, YYYYY, and ZZ are minor version numbers.
For 2015:
Microsoft (R) C/C++ Optimizing Compiler Version 19.XX.YYYYY for $$$
where $$$ is the targeted platform (e.g. x86, x64, ARM), and XX and YYYYY are minor version numbers.
If the goal is to seperate two elements, you can use CSS like below:
A<span style={{paddingLeft: '20px'}}>B</span>
A couple of issues
>
in -exec
without something like bash -c '... > ...'
. Though the >
will overwrite the file, so you want to redirect the entire find
anyway rather than each -exec
. +30
is older
than 30 days, -30
would be modified in last 30 days.-exec
really isn't needed, you could list everything with various -printf
options. Something like below should work
find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
Example with -printf
find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
This will list files in format "permissions owner group time date filename". -printf
is generally preferable to -exec
in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec
. Depending on the version of find
, you may also be able to use -ls
, which has a similar format to above.
You need to wrap the text in a div
element and include the absolutely positioned element inside of it.
<div class="container">
<div class="inner">
<div class="full-height"></div>
[Your text here]
</div>
</div>
Css:
.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }
Setting the inner div's position to relative
makes the absolutely position elements inside of it base their position and height on it rather than on the .container
div, which has a fixed height. Without the inner, relatively positioned div
, the .full-height
div will always calculate its dimensions and position based on .container
.
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
position: relative;_x000D_
border: solid 1px red;_x000D_
height: 256px;_x000D_
width: 256px;_x000D_
overflow: auto;_x000D_
float: left;_x000D_
margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
position: relative;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 128px;_x000D_
bottom: 0;_x000D_
height: 100%;_x000D_
background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
<div class="inner">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
quidem._x000D_
</div>_x000D_
</div>
_x000D_
If all the above methods are not working then change implementation 'com.google.firebase:firebase-core:12.0.0'
to implementation 'com.google.firebase:firebase-core:10.0.0'
in your app level build.gradle file.
This would surely work.
I think you may be looking for Jagged Arrays, which are different from multi-dimensional arrays (as you are using in your example) in C#. Converting the arrays in your declarations to jagged arrays should make it work. However, you'll still need to use two loops to iterate over all the items in the 2D jagged array.
This will definitely work. Orange outline won't show up anymore.. Common for all tags:
*:focus {
outline: none;
}
Specific to some tag, ex: input tag
input:focus{
outline:none;
}
A little bit off topic maybe, but for modern browsers (IE9 and newer) you can use the css odd/even selectors to achieve want you want.
tr:nth-child(even) { /* your alt-row stuff */}
tr:nth-child(odd) { /* the other rows */ }
or
tr { /* all table rows */ }
tr:nth-child(even) { /* your alt-row stuff */}
Everything in the g element is positioned relative to the current transform matrix.
To move the content, just put the transformation in the g element:
<g transform="translate(20,2.5) rotate(10)">
<rect x="0" y="0" width="60" height="10"/>
</g>
Links: Example from the SVG 1.1 spec
I tried this code, to retrieve shared preferences from an activity, and could not get it to work:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.getAll();
Log.d("AddNewRecord", "getAll: " + sharedPreferences.getAll());
Log.d("AddNewRecord", "Size: " + sharedPreferences.getAll().size());
Every time I tried, my preferences returned 0, even though I have 14 preferences saved by the preference activity. I finally found the answer. I added this to the preferences in the onCreate section.
getPreferenceManager().setSharedPreferencesName("defaultPreferences");
After I added this statement, my saved preferences returned as expected. I hope that this helps someone else who may experience the same issue that I did.
Are you possibly depending on development versions that obviously change a lot during development?
Instead of incrementing the version of development releases, you could just use a snapshot version that you overwrite when necessary, which means you wouldn't have to change the version tag on every minor change. Something like 1.0-SNAPSHOT...
But maybe you are trying to achieve something else ;)
To the response of James I will only change the sorting function to make it more universal. This way it will sort text alphabetical and numbers like numbers.
if( $.text([a]) == $.text([b]) )
return 0;
if(isNaN($.text([a])) && isNaN($.text([b]))){
return $.text([a]) > $.text([b]) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}
else{
return parseInt($.text([a])) > parseInt($.text([b])) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}
You're initialising your SSLContext
with a null
KeyManager
array.
The key manager is what handles the server certificate (on the server side), and this is what you're probably aiming to set when using javax.net.ssl.keyStore
.
However, as described in the JSSE Reference Guide, using null
for the first parameter doesn't do what you seem to think it does:
If the KeyManager[] parameter is null, then an empty KeyManager will be defined for this context. If the TrustManager[] parameter is null, the installed security providers will be searched for the highest-priority implementation of the TrustManagerFactory, from which an appropriate TrustManager will be obtained. Likewise, the SecureRandom parameter may be null, in which case a default implementation will be used.
An empty KeyManager
doesn't contain any RSA or DSA certificates. Therefore, all the default cipher suites that would rely on such a certificate are disabled. This is why you get all these "Ignoring unavailable cipher suite" messages, which ultimately result in a "no cipher suites in common" message.
If you want your keystore to be used as a keystore, you'll need to load it and initialise a KeyManagerFactory with it:
KeyStore ks = KeyStore.getInstance("JKS");
InputStream ksIs = new FileInputStream("...");
try {
ks.load(ksIs, "password".toCharArray());
} finally {
if (ksIs != null) {
ksIs.close();
}
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
kmf.init(ks, "keypassword".toCharArray());
The use kmf.getKeyManagers()
as the first parameter to SSLContext.init()
.
For the other two parameters, since you're visibly not requesting client-certificate authentication, you should leave the trust manager to its default value (null
) instead of copying/pasting a trust manager that's a potential cause of vulnerability, and you can also use the default null
SecureRandom
.
All the docker:
start | restart | stop | rm --force | kill
commands
may not work if the container is stuck. You can always restart the docker daemon. However, if you have other containers running, that may not be the option. What you can do is:
ps aux | grep <<container id>> | awk '{print $1 $2}'
The output contains:
<<user>><<process id>>
Then kill the process associated with the container like so:
sudo kill -9 <<process id from above command>>
That will kill the container and you can start a new container with the right image.
Same as accepted answer, But note that it works even with .crt
file and not just .pem
file, just in case if you are not able to find .pem
file location.
openssl x509 -enddate -noout -in e71c8ea7fa97ad6c.crt
Result:
notAfter=Mar 29 06:15:00 2020 GMT
You can use OnClientClick event to call a JavaScript function:
<asp:Button ID="Button1" runat="server" Text="Button" onclientclick='redirect()' />
JavaScript code:
function redirect() {
location.href = 'page.aspx';
}
But i think the best would be to style a hyperlink with css.
Example :
.button {
display: block;
height: 25px;
background: #f1f1f1;
padding: 10px;
text-align: center;
border-radius: 5px;
border: 1px solid #e1e1e2;
color: #000;
font-weight: bold;
}
If you want to set only one specific class, you might write a TypeScript function returning a boolean to determine when the class should be appended.
TypeScript
function hideThumbnail():boolean{
if (/* Your criteria here */)
return true;
}
CSS:
.request-card-hidden {
display: none;
}
HTML:
<ion-note [class.request-card-hidden]="hideThumbnail()"></ion-note>
This is OK for me. In Service project add to Installer.cs
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
protected override void OnAfterInstall(IDictionary savedState)
{
base.OnAfterInstall(savedState);
//The following code starts the services after it is installed.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
{
serviceController.Start();
}
}
}
Try this snippet of code:
String timeSettings = android.provider.Settings.System.getString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME);
if (timeSettings.contentEquals("0")) {
android.provider.Settings.System.putString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME, "1");
}
Date now = new Date(System.currentTimeMillis());
Log.d("Date", now.toString());
Make sure to add permission in Manifest
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
In your httpd.conf
make sure you have:
Listen *:80
And if you are using VirtualHosts then set them as given below:
NameVirtualHost *
<VirtualHost *>
...
</VirtualHost>
In usecase where you want to serialize/deserialize POCOs, Newtonsoft's JSON library is really good. I use it to persist POCOs within SQL Server as JSON strings in an nvarchar field. Caveat is that since its not true de/serialization, it will not preserve private/protected members and class hierarchy.
I would suggest 3 things:
The last one worked for me.
It's very simple. Just try:
start chrome https://www.google.co.in/
it will open the Google page in the Chrome browser.
If you wish to open the page in Firefox, try:
start firefox https://www.google.co.in/
Have Fun!
Have you tried using the stream_context_set_option()
method ?
$context = stream_context_create();
$result = stream_context_set_option($context, 'ssl', 'local_cert', '/etc/ssl/certs/cacert.pem');
$fp = fsockopen($host, $port, $errno, $errstr, 20, $context);
In addition, try file_get_contents()
for the pem file, to make sure you have permissions to access it, and make sure the host name matches the certificate.
I had similar problem . Two components communicating with each other was using a queue .
First component was not doing json.dumps before putting message to queue. So the JSON string generated by receiving component was in single quotes. This was causing error
Expecting property name enclosed in double quotes
Adding json.dumps started creating correctly formatted JSON & solved issue.
I'm using Styled Components and created a helper function for myself.
It takes the given Android elevation and creates a fairly equivalent iOS shadow.
import { css } from 'styled-components/native';
/*
REMINDER!!!!!!!!!!!!!
Shadows do not show up on iOS if `overflow: hidden` is used.
https://react-native.canny.io/feature-requests/p/shadow-does-not-appear-if-overflow-hidden-is-set-on-ios
*/
// eslint-disable-next-line import/prefer-default-export
export const crossPlatformElevation = (elevation: number = 0) => css`
/* Android - native default is 4, we're setting to 0 to match iOS. */
elevation: ${elevation};
/* iOS - default is no shadow. Only add if above zero */
${elevation > 0
&& css`
shadow-color: black;
shadow-offset: 0px ${0.5 * elevation}px;
shadow-opacity: 0.3;
shadow-radius: ${0.8 * elevation}px;
`}
`;
import styled from 'styled-components/native';
import { crossPlatformElevation } from "../../lib/stylingTools";
export const ContentContainer = styled.View`
background: white;
${crossPlatformElevation(10)};
`;
Sum of total_vm
is 847170 and sum of rss
is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.
Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.
rss
for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss
and file-rss
.
[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB
As many of the answers already state what these annotations are used for, we'll here focus on some minor differences among them.
First the Similarity
First point worth highlighting again is that with respect to scan-auto-detection and dependency injection for BeanDefinition all these annotations (viz., @Component, @Service, @Repository, @Controller) are the same. We can use one in place of another and can still get our way around.
@Component
This is a general-purpose stereotype annotation indicating that the class is a spring component.
What’s special about @Component
<context:component-scan>
only scans @Component
and does not look for @Controller
, @Service
and @Repository
in general. They are scanned because they themselves are annotated with @Component
.
Just take a look at @Controller
, @Service
and @Repository
annotation definitions:
@Component
public @interface Service {
….
}
@Component
public @interface Repository {
….
}
@Component
public @interface Controller {
…
}
Thus, it’s not wrong to say that @Controller
, @Service
and @Repository
are special types of @Component
annotation. <context:component-scan>
picks them up and registers their following classes as beans, just as if they were annotated with @Component
.
Special type annotations are also scanned, because they themselves are annotated with @Component
annotation, which means they are also @Component
s. If we define our own custom annotation and annotate it with @Component
, it will also get scanned with <context:component-scan>
@Repository
This is to indicate that the class defines a data repository.
What’s special about @Repository?
In addition to pointing out, that this is an Annotation based Configuration, @Repository
’s job is to catch platform specific exceptions and re-throw them as one of Spring’s unified unchecked exception. For this, we’re provided with PersistenceExceptionTranslationPostProcessor
, that we are required to add in our Spring’s application context like this:
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
This bean post processor adds an advisor to any bean that’s annotated with @Repository
so that any platform-specific exceptions are caught and then re-thrown as one of Spring’s unchecked data access exceptions.
@Controller
The @Controller
annotation indicates that a particular class serves the role of a controller. The @Controller
annotation acts as a stereotype for the annotated class, indicating its role.
What’s special about @Controller?
We cannot switch this annotation with any other like @Service
or @Repository
, even though they look same.
The dispatcher scans the classes annotated with @Controller
and detects methods annotated with @RequestMapping
annotations within them. We can use @RequestMapping
on/in only those methods whose classes are annotated with @Controller
and it will NOT work with @Component
, @Service
, @Repository
etc...
Note: If a class is already registered as a bean through any alternate method, like through @Bean
or through @Component
, @Service
etc... annotations, then @RequestMapping
can be picked if the class is also annotated with @RequestMapping
annotation. But that's a different scenario.
@Service
@Service
beans hold the business logic and call methods in the repository layer.
What’s special about @Service?
Apart from the fact that it's used to indicate, that it's holding the business logic, there’s nothing else noticeable in this annotation; but who knows, Spring may add some additional exceptional in future.
What else?
Similar to above, in the future Spring may add special functionalities for @Service
, @Controller
and @Repository
based on their layering conventions. Hence, it's always a good idea to respect the convention and use it in line with layers.
Now you can do in swift the following thing which allows you to regain a little bit of the objective-c if nil else
if textfieldDate.text?.isEmpty ?? true {
}
This will get you the PID of a process by name:
pidof name
Which you can then plug back in to ps for more detail:
ps -p $(pidof name)
According to the docs for v0.18.0, if you're running on a terminal (ie not iPython notebook, qtconsole or IDLE), it's a 2-liner to have Pandas auto-detect your screen width and adapt on the fly with how many columns it shows:
pd.set_option('display.large_repr', 'truncate')
pd.set_option('display.max_columns', 0)
This is due to Morphia jar not being part of your output war/jar. Eclipse or local build includes them as part of classpath, but remote builds or auto/scheduled build don't consider them part of classpath.
You can include dependent jars using plugin.
Add below snippet into your pom's plugins section
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
Just do
if (Attachment != null && Attachment.Length > 0)
From && Operator
The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.
Here is my modification of nrabinowitz' solution. I didn't use the size property, because it's not perfect with proportional fonts as @Mark noted. My solution place an element after your input and gets width counted by browser (using jQuery).
Although I don't test it, I suppose it will work only if all CSS properties affecting font are inherited.
The input width changes on focusout event, which works better for me. But you can use keyup/keypress to change input's width when typing as well.
function resizeInput() {
//Firstly take the content or placeholder if content is missing.
var content =
$(this).val().length > 0 ? $(this).val() : $(this).prop("placeholder");
//Create testing element with same content as input.
var widthTester = $("<span>"+content+"</span>").hide();
//Place testing element into DOM after input (so it inherits same formatting as input does).
widthTester.insertAfter($(this));
//Set inputs width; you may want to use outerWidth() or innerWidth()
//depending whether you want to count padding and border or not.
$(this).css("width",widthTester.width()+"px");
//Remove the element from the DOM
widthTester.remove();
}
$('.resizing-input').focusout(resizeInput).each(resizeInput);
Port 465: IANA has reassigned a new service to this port, and it should no longer be used for SMTP communications.
However, because it was once recognized by IANA as valid, there may be legacy systems that are only capable of using this connection method. Typically, you will use this port only if your application demands it. A quick Google search, and you'll find many consumer ISP articles that suggest port 465 as the recommended setup. Hopefully this ends soon! It is not RFC compliant.
Port 587: This is the default mail submission port. When a mail client or server is submitting an email to be routed by a proper mail server, it should always use this port.
Everyone should consider using this port as default, unless you're explicitly blocked by your upstream network or hosting provider. This port, coupled with TLS encryption, will ensure that email is submitted securely and following the guidelines set out by the IETF.
Port 25: This port continues to be used primarily for SMTP relaying. SMTP relaying is the transmittal of email from email server to email server.
In most cases, modern SMTP clients (Outlook, Mail, Thunderbird, etc) shouldn't use this port. It is traditionally blocked, by residential ISPs and Cloud Hosting Providers, to curb the amount of spam that is relayed from compromised computers or servers. Unless you're specifically managing a mail server, you should have no traffic traversing this port on your computer or server.
On all tables with foreign keys pointing to this one, use:
ALTER TABLE MyOtherTable NOCHECK CONSTRAINT fk_name
Dang, kids, let's crush this thing down, why don't we?
let uniqIds = {}, source = [{id:'a'},{id:'b'},{id:'c'},{id:'b'},{id:'a'},{id:'d'}];_x000D_
let filtered = source.filter(obj => !uniqIds[obj.id] && (uniqIds[obj.id] = true));_x000D_
console.log(filtered);_x000D_
// EXPECTED: [{id:'a'},{id:'b'},{id:'c'},{id:'d'}];
_x000D_
Just to quote Boot Docs:
You can set
spring.data.mongodb.uri
property to change the url, or alternatively specify ahost/port
. For example, you might declare the following in yourapplication.properties
:
spring.data.mongodb.host=mongoserver
spring.data.mongodb.port=27017
All available options for spring.data.mongodb
prefix are fields of MongoProperties
:
private String host;
private int port = DBPort.PORT;
private String uri = "mongodb://localhost/test";
private String database;
private String gridFsDatabase;
private String username;
private char[] password;
You can try this code (requires jQuery):
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#foo').keyup(function(e) {
var v = $('#foo').val();
$('#debug').val(v);
})
});
</script>
</head>
<body>
<form>
<input type="text" id="foo" value="bar"><br>
<textarea id="debug"></textarea>
</form>
</body>
</html>
Laravel raw sql – Insert query:
lets create a get link to insert data which is accessible through url . so our link name is ‘insertintodb’ and inside that function we use db class . db class helps us to interact with database . we us db class static function insert . Inside insert function we will write our PDO query to insert data in database . in below query we will insert ‘ my title ‘ and ‘my content’ as data in posts table .
put below code in your web.php file inside routes directory :
Route::get('/insertintodb',function(){
DB::insert('insert into posts(title,content) values (?,?)',['my title','my content']);
});
Now fire above insert query from browser link below :
localhost/yourprojectname/insertintodb
You can see output of above insert query by going into your database table .you will find a record with id 1 .
Laravel raw sql – Read query :
Now , lets create a get link to read data , which is accessible through url . so our link name is ‘readfromdb’. we us db class static function read . Inside read function we will write our PDO query to read data from database . in below query we will read data of id ‘1’ from posts table .
put below code in your web.php file inside routes directory :
Route::get('/readfromdb',function() {
$result = DB::select('select * from posts where id = ?', [1]);
var_dump($result);
});
now fire above read query from browser link below :
localhost/yourprojectname/readfromdb
Building on the other answers, I wanted to share an example of using the while loop construct to achieve a do-while behaviour. By using a simple boolean variable in the while condition (initialized to TRUE), and then checking our actual condition later in the if statement. One could also use a break keyword instead of the continue <- FALSE inside the if statement (probably more efficient).
df <- data.frame(X=c(), R=c())
x <- x0
continue <- TRUE
while(continue)
{
xi <- (11 * x) %% 16
df <- rbind(df, data.frame(X=x, R=xi))
x <- xi
if(xi == x0)
{
continue <- FALSE
}
}
You should consider (temporarily) disabling the constraint before you completely delete it.
If you look at the table creation TSQL you will see something like:
ALTER TABLE [dbo].[dbAccounting] CHECK CONSTRAINT [FK_some_FK_constraint]
You can run
ALTER TABLE [dbo].[dbAccounting] NOCHECK CONSTRAINT [FK_some_FK_constraint]
... then insert/update a bunch of values that violate the constraint, and then turn it back on by running the original CHECK
statement.
(I have had to do this to cleanup poorly designed systems I've inherited in the past.)
make input to block and float, Adjust margin top value.
HTML:
<div class="label">
<input type="checkbox" name="test" /> luke..
</div>
CSS:
/*
change margin-top, if your line-height is different.
*/
input[type=checkbox]{
height:18px;
width:18px;
padding:0;
margin-top:5px;
display:block;
float:left;
}
.label{
border:1px solid red;
}
Try:
123-(?:(apple|banana|)-|)456
That will match apple
, banana
, or a blank string, and following it there will be a 0 or 1 hyphens. I was wrong about not having a need for a capturing group. Silly me.
Using simply tr :
$ tr ':' $'\n' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5
If you really need sed :
$ sed 's/:/\n/g' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5
The easiest way is to use a StringContent
, with the JSON representation of your JSON object.
httpClient.Post(
"",
new StringContent(
myObject.ToString(),
Encoding.UTF8,
"application/json"));
Using an in
can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:
SELECT *
FROM (SELECT msisdn
,callid
,Change_color
,play_file_name
,date_played
FROM insert_log
WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
ORDER BY callid ASC) t1
JOIN (SELECT MAX(date_played) AS date_played
FROM insert_log GROUP BY callid) t2
ON t1.date_played = t2.date_played
You can send Email by Jquery just follow these steps
include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :
$( document ).ready(function() {
Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});
A very simple way to do it is:
list1=['']
j=0
for i in com_list:
if j==0:
list1[0]=(i['value'])
else:
list1.append(i['value'])
j+=1
Output:
['apple', 'banana', 'cars']
Here is a block to print out unicode chars between \u00c0
to \u00ff
:
char[] ca = {'\u00c0'};
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 16; j++) {
String sc = new String(ca);
System.out.print(sc + " ");
ca[0]++;
}
System.out.println();
}
This error can also show up if there are parts in your string that json.loads()
does not recognize. An in this example string, an error will be raised at character 27 (char 27)
.
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
My solution to this would be to use the string.replace()
to convert these items to a string:
import json
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
string = string.replace("False", '"False"')
dict_list = json.loads(string)
Arrays.fill works only with one-dimensional array
Source of java.util.Arrays:
public static void fill(Object[] a, Object val) {
int i = 0;
for(int len = a.length; i < len; ++i) {
a[i] = val;
}
Use own loops for initialization array
Sounds like you should stay with the defaults ;-)
Seriously: The number of maximum parallel connections you should set depends on your expected tomcat usage and also on the number of cores on your server. More cores on your processor => more parallel threads that can be executed.
See here how to configure...
Tomcat 9: https://tomcat.apache.org/tomcat-9.0-doc/config/executor.html
Tomcat 8: https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html
Tomcat 7: https://tomcat.apache.org/tomcat-7.0-doc/config/executor.html
Tomcat 6: https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html
Taken from the ReactKonvaCore.d.ts file:
onClick?(evt: Konva.KonvaEventObject<MouseEvent>): void;
So, I'd say your event type is Konva.KonvaEventObject<MouseEvent>
Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.
You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.
Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.
I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.
Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.
I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.
In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.
Good luck!
The 'best' way to do this would be to set a property on a view object once the update is successful. You can then access this property in the view and inform the user accordingly.
Having said that it would be possible to trigger an alert from the controller code by doing something like this -
public ActionResult ActionName(PostBackData postbackdata)
{
//your DB code
return new JavascriptResult { Script = "alert('Successfully registered');" };
}
You can find further info in this question - How to display "Message box" using MVC3 controller
Here is my version. Can be extended to accommodate more number of parameters and can extend formatting based on type. Currently only date and datetime types are formatted.
Example:
select dbo.FormatString('some string %s some int %s date %s','"abcd"',100,cast(getdate() as date),DEFAULT,DEFAULT)
select dbo.FormatString('some string %s some int %s date time %s','"abcd"',100,getdate(),DEFAULT,DEFAULT)
Output:
some string "abcd" some int 100 date 29-Apr-2017
some string "abcd" some int 100 date time 29-Apr-2017 19:40
Functions:
create function dbo.FormatValue(@param sql_variant)
returns nvarchar(100)
begin
/*
Tejasvi Hegde, 29-April-2017
Can extend formatting here.
*/
declare @result nvarchar(100)
if (SQL_VARIANT_PROPERTY(@param,'BaseType') in ('date'))
begin
select @result = REPLACE(CONVERT(CHAR(11), @param, 106), ' ', '-')
end
else if (SQL_VARIANT_PROPERTY(@param,'BaseType') in ('datetime','datetime2'))
begin
select @result = REPLACE(CONVERT(CHAR(11), @param, 106), ' ', '-')+' '+CONVERT(VARCHAR(5),@param,108)
end
else
begin
select @result = cast(@param as nvarchar(100))
end
return @result
/*
BaseType:
bigint
binary
char
date
datetime
datetime2
datetimeoffset
decimal
float
int
money
nchar
numeric
nvarchar
real
smalldatetime
smallint
smallmoney
time
tinyint
uniqueidentifier
varbinary
varchar
*/
end;
create function dbo.FormatString(
@format nvarchar(4000)
,@param1 sql_variant = null
,@param2 sql_variant = null
,@param3 sql_variant = null
,@param4 sql_variant = null
,@param5 sql_variant = null
)
returns nvarchar(4000)
begin
/*
Tejasvi Hegde, 29-April-2017
select dbo.FormatString('some string value %s some int %s date %s','"abcd"',100,cast(getdate() as date),DEFAULT,DEFAULT)
select dbo.FormatString('some string value %s some int %s date time %s','"abcd"',100,getdate(),DEFAULT,DEFAULT)
*/
declare @result nvarchar(4000)
select @param1 = dbo.formatValue(@param1)
,@param2 = dbo.formatValue(@param2)
,@param3 = dbo.formatValue(@param3)
,@param4 = dbo.formatValue(@param4)
,@param5 = dbo.formatValue(@param5)
select @param2 = cast(@param2 as nvarchar)
EXEC xp_sprintf @result OUTPUT,@format , @param1, @param2, @param3, @param4, @param5
return @result
end;
I profiled a few methods to move an item within the same list with timeit. Here are the ones to use if j>i:
+---------------------------------+ ¦ 14.4usec ¦ x[i:i]=x.pop(j), ¦ ¦ 14.5usec ¦ x[i:i]=[x.pop(j)] ¦ ¦ 15.2usec ¦ x.insert(i,x.pop(j)) ¦ +---------------------------------+
and here the ones to use if j<=i:
+--------------------------------------+ ¦ 14.4usec ¦ x[i:i]=x[j],;del x[j] ¦ ¦ 14.4usec ¦ x[i:i]=[x[j]];del x[j] ¦ ¦ 15.4usec ¦ x.insert(i,x[j]);del x[j] ¦ +--------------------------------------+
Not a huge difference if you only use it a few times, but if you do heavy stuff like manual sorting, it's important to take the fastest one. Otherwise, I'd recommend just taking the one that you think is most readable.
A sample - write multiple rows with boolean column (using example above by GaretJax and Eran?).
import csv
RESULT = [['IsBerry','FruitName'],
[False,'apple'],
[True, 'cherry'],
[False,'orange'],
[False,'pineapple'],
[True, 'strawberry']]
with open("../datasets/dashdb.csv", 'wb') as resultFile:
wr = csv.writer(resultFile, dialect='excel')
wr.writerows(RESULT)
Result:
df_data_4 = pd.read_csv('../datasets/dashdb.csv')
df_data_4.head()
Output:
IsBerry FruitName
0 False apple
1 True cherry
2 False orange
3 False pineapple
4 True strawberry
As mentioned by others the error may occur if the url is wrong.
However, the error may also occur if the repo is a private repo and you do not have access or wrong credentials.
Instead of
git clone https://github.com/NAME/repo.git
try
git clone https://username:[email protected]/NAME/repo.git
You can also use
git clone https://[email protected]/NAME/repo.git
and git will prompt for the password (thanks to leanne for providing this hint in the comments).
It worked using PSCP. Instructions:
set PATH=<path to the pscp.exe file>
pscp
use the following command to copy file form remote server to the local system
pscp [options] [user@]host:source target
So to copy the file /etc/hosts
from the server example.com
as user fred
to the file
c:\temp\example-hosts.txt
, you would type:
pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt
java.util.Arrays.asList(new String[]{"a", "b"})
import numpy as np
x=np.array([1,2,3])
y=np.multiply(np.ones((len(x),len(x))),x).T
print(y)
yields:
[[ 1. 1. 1.]
[ 2. 2. 2.]
[ 3. 3. 3.]]
The parser is expecting some HTML content, so it sees &
as the beginning of an entity, like è
.
Use this workaround:
<script type="text/javascript">
// <![CDATA[
Javascript code here
// ]]>
</script>
so you specify that the code is not HTML text but just data to be used as is.
I used this Unicode Decimal Code ‌
and worked. more details
Last one is not working now, take this one, it worked for me.
in WebApiConfig.cs at App_Start
public static string _WebApiExecutionPath = "api";
public static void Register(HttpConfiguration config)
{
var basicRouteTemplate = string.Format("{0}/{1}", _WebApiExecutionPath, "{controller}");
// Controller Only
// To handle routes like `/api/VTRouting`
config.Routes.MapHttpRoute(
name: "ControllerOnly",
routeTemplate: basicRouteTemplate//"{0}/{controller}"
);
// Controller with ID
// To handle routes like `/api/VTRouting/1`
config.Routes.MapHttpRoute(
name: "ControllerAndId",
routeTemplate: string.Format ("{0}/{1}", basicRouteTemplate, "{id}"),
defaults: null,
constraints: new { id = @"^\d+$" } // Only integers
);
Global.asax
protected void Application_PostAuthorizeRequest()
{
if (IsWebApiRequest())
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
private static bool IsWebApiRequest()
{
return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(_WebApiExecutionPath);
}
fournd here: http://forums.asp.net/t/1773026.aspx/1
Well, its an easy way of doing some registry changes: I tried this on 2008 r2 and 2016 servers.
Things need to be done:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0]
"GPO-ID"="LocalGPO"
"SOM-ID"="Local"
"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"
"DisplayName"="Local Group Policy"
"GPOName"="Local Group Policy"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0\0]
"Script"="terminate_script.bat"
"Parameters"=""
"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0]
"GPO-ID"="LocalGPO"
"SOM-ID"="Local"
"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"
"DisplayName"="Local Group Policy"
"GPOName"="Local Group Policy"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0\0]
"Script"="terminate_script.bat"
"Parameters"=""
"IsPowershell"=dword:00000000
"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
Save this file as regedit.reg extension
Run it on any command line using below command:
regedit.exe /s regedit.reg
This method uses regexp, it should work:
awk '$2 ~ /findtext/ {print $3}' <infile>
I've came up with this solution: https://calbertts.medium.com/unix-pipelines-with-curl-requests-and-serverless-functions-e21117ae4c65
# this in your bash profile
jsonprettify() {
curl -Ss -X POST -H "Content-Type: text/plain" --data-binary @- https://jsonprettify.vercel.app/api/server?indent=$@
}
echo '{"prop": true, "key": [1,2]}' | jsonprettify 4
# {
# "prop": true,
# "key": [
# 1,
# 2
# ]
# }
There's no need to install anything, if you have an internet connection and cURL installed, you can use this function.
Are you in another host where you can't install anything, this would be a perfect solution to that issue.
Lets see two efficient ways that deal with escaped quotes. These patterns are not designed to be concise nor aesthetic, but to be efficient.
These ways use the first character discrimination to quickly find quotes in the string without the cost of an alternation. (The idea is to discard quickly characters that are not quotes without to test the two branches of the alternation.)
Content between quotes is described with an unrolled loop (instead of a repeated alternation) to be more efficient too: [^"\\]*(?:\\.[^"\\]*)*
Obviously to deal with strings that haven't balanced quotes, you can use possessive quantifiers instead: [^"\\]*+(?:\\.[^"\\]*)*+
or a workaround to emulate them, to prevent too much backtracking. You can choose too that a quoted part can be an opening quote until the next (non-escaped) quote or the end of the string. In this case there is no need to use possessive quantifiers, you only need to make the last quote optional.
Notice: sometimes quotes are not escaped with a backslash but by repeating the quote. In this case the content subpattern looks like this: [^"]*(?:""[^"]*)*
The patterns avoid the use of a capture group and a backreference (I mean something like (["']).....\1
) and use a simple alternation but with ["']
at the beginning, in factor.
Perl like:
["'](?:(?<=")[^"\\]*(?s:\\.[^"\\]*)*"|(?<=')[^'\\]*(?s:\\.[^'\\]*)*')
(note that (?s:...)
is a syntactic sugar to switch on the dotall/singleline mode inside the non-capturing group. If this syntax is not supported you can easily switch this mode on for all the pattern or replace the dot with [\s\S]
)
(The way this pattern is written is totally "hand-driven" and doesn't take account of eventual engine internal optimizations)
ECMA script:
(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*')
POSIX extended:
"[^"\\]*(\\(.|\n)[^"\\]*)*"|'[^'\\]*(\\(.|\n)[^'\\]*)*'
or simply:
"([^"\\]|\\.|\\\n)*"|'([^'\\]|\\.|\\\n)*'
It looks like in the ECMAScript 6 proposal there are the Array
methods find()
and findIndex()
. MDN also offers polyfills which you can include to get the functionality of these across all browsers.
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log( [4, 6, 8, 12].find(isPrime) ); // undefined, not found
console.log( [4, 5, 8, 12].find(isPrime) ); // 5
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log( [4, 6, 8, 12].findIndex(isPrime) ); // -1, not found
console.log( [4, 6, 7, 12].findIndex(isPrime) ); // 2
Do install latest version instead of the recommended stable version. It will give you freedom to use latest ES6 Features on node.
Can be Found here Node JS.
sudo npm i -g npm@latest
All your projects will work fine.
Update: 2020 another good option is to use nvm
for node which can then support multiple versions.
use nvm install --lts
to always be able to update to latest node version use nvm ls-remote
command to to check new versions of node.
Other option for mac :: brew update && brew install node && npm -g npm
You can use the display property of style. Intialy set the result section style as
style = "display:none"
Then the div will not be visible and there won't be any white space.
Once the search results are being populated change the display property using the java script like
document.getElementById("someObj").style.display = "block"
Using java script you can make the div invisible
document.getElementById("someObj").style.display = "none"
In Java (or other languages), using Property/Attribute depends on usage:
Property used when value doesn't change very often (usually used at startup or for environment variable)
Attributes is a value (object child) of an Element (object) which can change very often/all the time and be or not persistent
You can try something like this, if you use jQuery.
$("form").bind("keydown", function(e) {
if (e.keyCode === 13) return false;
});
That will wait for a keydown, if it is Enter, it will do nothing.
Image upload using ajax and check image format and upload max size
<form class='form-horizontal' method="POST" id='document_form' enctype="multipart/form-data">
<div class='optionBox1'>
<div class='row inviteInputWrap1 block1'>
<div class='col-3'>
<label class='col-form-label'>Name</label>
<input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
</div>
<div class='col-3'>
<label class='col-form-label'>File</label>
<input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
</div>
<div class='col-3'>
<span class='deleteInviteWrap1 remove1 d-none'>
<i class='fas fa-trash'></i>
</span>
</div>
</div>
<div class='row'>
<div class='col-8 pl-3 pb-4 mt-4'>
<span class='btn btn-info add1 pr-3'>+ Add More</span>
<button class='btn btn-primary'>Submit</button>
</div>
</div>
</div>
</form>
</div>
$.validator.setDefaults({
submitHandler: function (form)
{
$.ajax({
url : "action1.php",
type : "POST",
data : new FormData(form),
mimeType: "multipart/form-data",
contentType: false,
cache: false,
dataType:'json',
processData: false,
success: function(data)
{
if(data.status =='success')
{
swal("Document has been successfully uploaded!", {
icon: "success",
});
setTimeout(function(){
window.location.reload();
},1200);
}
else
{
swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
}
},
error:function(data)
{
swal ( "Ops!" , "error in document upload." , "error" );
}
});
}
});
$('#document_form').validate({
rules: {
"name[]": {
required: true
},
"file[]": {
required: true,
extension: "jpg,jpeg,png,pdf,doc",
filesize :2000000
}
},
messages: {
"name[]": {
required: "Please enter name"
},
"file[]": {
required: "Please enter file",
extension :'Please upload only jpg,jpeg,png,pdf,doc'
}
},
errorElement: 'span',
errorPlacement: function (error, element) {
error.addClass('invalid-feedback');
element.closest('.col-3').append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
$.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than 2 MB');
If you are trying to do something similar to the Google search page when open in Chrome, (where certain events are triggered when you 'focus' on the page), then the hover() event may help.
$(window).hover(function() {
// code here...
});
Here is what I'm using on one of my projects, it's working great and it generates a UNIQUE RANDOM TOKEN:
$timestampz=time();
function generateRandomString($length = 60) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$tokenparta = generateRandomString();
$token = $timestampz*3 . $tokenparta;
echo $token;
Please note that I multiplied the timestamp by three to create a confusion for whoever user might be wondering how this token is generated ;)
I hope it helps :)
Here is sample usage using expect
:
#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }
Check: man expect
for further information.
Writing a null character to the first character does just that. If you treat it as a string, code obeying the null termination character will treat it as a null string, but that is not the same as clearing the data. If you want to actually clear the data you'll need to use memset.
The following program will add the python executable path and the subdir Scripts (which is where e.g. pip and easy_install are installed) to your environment. It finds the path to the python executable from the registry key binding the .py extension. It will remove old python paths in your environment. Works with XP (and probably Vista) as well. It only uses modules that come with the basic windows installer.
# coding: utf-8
import sys
import os
import time
import _winreg
import ctypes
def find_python():
"""
retrieves the commandline for .py extensions from the registry
"""
hKey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,
r'Python.File\shell\open\command')
# get the default value
value, typ = _winreg.QueryValueEx (hKey, None)
program = value.split('"')[1]
if not program.lower().endswith(r'\python.exe'):
return None
return os.path.dirname(program)
def extend_path(pypath, remove=False, verbose=0, remove_old=True,
script=False):
"""
extend(pypath) adds pypath to the PATH env. variable as defined in the
registry, and then notifies applications (e.g. the desktop) of this change.
!!! Already opened DOS-Command prompts are not updated. !!!
Newly opened prompts will have the new path (inherited from the
updated windows explorer desktop)
options:
remove (default unset), remove from PATH instead of extend PATH
remove_old (default set), removes any (old) python paths first
script (default unset), try to add/remove the Scripts subdirectory
of pypath (pip, easy_install) as well
"""
_sd = 'Scripts' # scripts subdir
hKey = _winreg.OpenKey (_winreg.HKEY_LOCAL_MACHINE,
r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
0, _winreg.KEY_READ | _winreg.KEY_SET_VALUE)
value, typ = _winreg.QueryValueEx (hKey, "PATH")
vals = value.split(';')
assert isinstance(vals, list)
if not remove and remove_old:
new_vals = []
for v in vals:
pyexe = os.path.join(v, 'python.exe')
if v != pypath and os.path.exists(pyexe):
if verbose > 0:
print 'removing from PATH:', v
continue
if script and v != os.path.join(pypath, _sd) and \
os.path.exists(v.replace(_sd, pyexe)):
if verbose > 0:
print 'removing from PATH:', v
continue
new_vals.append(v)
vals = new_vals
if remove:
try:
vals.remove(pypath)
except ValueError:
if verbose > 0:
print 'path element', pypath, 'not found'
return
if script:
try:
vals.remove(os.path.join(pypath, _sd))
except ValueError:
pass
print 'removing from PATH:', pypath
else:
if pypath in vals:
if verbose > 0:
print 'path element', pypath, 'already in PATH'
return
vals.append(pypath)
if verbose > 1:
print 'adding to PATH:', pypath
if script:
if not pypath + '\\Scripts' in vals:
vals.append(pypath + '\\Scripts')
if verbose > 1:
print 'adding to PATH:', pypath + '\\Scripts'
_winreg.SetValueEx(hKey, "PATH", 0, typ, ';'.join(vals) )
_winreg.SetValueEx(hKey, "OLDPATH", 0, typ, value )
_winreg.FlushKey(hKey)
# notify other programs
SendMessage = ctypes.windll.user32.SendMessageW
HWND_BROADCAST = 0xFFFF
WM_SETTINGCHANGE = 0x1A
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u'Environment')
if verbose > 1:
print 'Do not forget to restart any command prompts'
if __name__ == '__main__':
remove = '--remove' in sys.argv
script = '--noscripts' not in sys.argv
extend_path(find_python(), verbose=2, remove=remove, script=script)
If you take a look at the official docs, you'll see right below append
, extend
. That's what your looking for.
There's also itertools.chain
if you are more interested in efficient iteration than ending up with a fully populated data structure.
If you're using lodash:
_.endsWith('abc', 'c'); // true
If not using lodash, you can borrow from its source.
init = extendFunction(init, function(args) {
doSomethingHereToo();
});
But in your specific case, it's easier to extend the global onload function:
extendFunction('onload', function(args) {
doSomethingHereToo();
});
I actually really like your question, it's making me think about different use cases.
For javascript events, you really want to add and remove handlers - but for extendFunction, how could you later remove functionality? I could easily add a .revert method to extended functions, so init = init.revert()
would return the original function. Obviously this could lead to some pretty bad code, but perhaps it lets you get something done without touching a foreign part of the codebase.
String filepath="/tmp/employee.csv";
FileWriter sw = new FileWriter(new File(filepath));
CSVWriter writer = new CSVWriter(sw);
writer.writeAll(allRows);
String[] header= new String[]{"ErrorMessage"};
writer.writeNext(header);
List<String[]> errorData = new ArrayList<String[]>();
for(int i=0;i<1;i++){
String[] data = new String[]{"ErrorMessage"+i};
errorData.add(data);
}
writer.writeAll(errorData);
writer.close();
Go to your python package directory and remove your .egg file, e.g.: In python 2.5(ubuntu): /usr/lib/python2.5/site-packages/
In python 2.6(ubuntu): /usr/local/lib/python2.6/dist-packages/
In many case It is java facet problem ,jdk or jre or jsp version is difference than maven project face.
!== should match the value and data type
!= just match the value ignoring the data type
$num = '1';
$num2 = 1;
$num == $num2; // returns true
$num === $num2; // returns false because $num is a string and $num2 is an integer
the style is:
<style type="text/css">
.topcorner{
position:absolute;
top:0;
right:0;
}
</style>
hope it will work. Thanks
The WebKit Developer Console (found in Chrome, Safari, etc.) lets you view attached events for elements.
Your string is not valid. Double quots cannot be inside double quotes. You should escape them:
"{\"TeamList\" : [{\"teamid\" : \"1\",\"teamname\" : \"Barcelona\"}]}"
or use single quotes and double quotes
'{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}'
I had a similar issue with restoring using SQL Management Studio. I tried to restore a backup of the database to a new one with a different name. At first this failed and after fixing the new database's file names it was successfully performed - in any case the issue I'm describing re-occurred even if I got this right from the first time. So, after the restoration, the original database remained with a (Restoring...) next to its name. Considering the answers of the forum above (Bhusan's) I tried running in the query editor on the side the following:
RESTORE DATABASE "[NAME_OF_DATABASE_STUCK_IN_RESTORING_STATE]"
which fixed the issue. I was having trouble at first because of the database name which contained special characters. I resolved this by adding double quotes around - single quotes wouldn't work giving an "Incorrect syntax near ..." error.
This was the minimal solution I've tried to resolve this issue (stuck database in restoring state) and I hope it can be applied to more cases.
I had this issue and changing the Compilation Mode setting for the project from Incremental to Whole Module fixed it for me.
Diff between Finalize and Dispose methods in C#.
GC calls the finalize method to reclaim the unmanaged resources(such as file operarion, windows api, network connection, database connection) but time is not fixed when GC would call it. It is called implicitly by GC it means we do not have low level control on it.
Dispose Method: We have low level control on it as we call it from the code. we can reclaim the unmanaged resources whenever we feel it is not usable.We can achieve this by implementing IDisposal pattern.
I resolved problem by adding following to my build.gradle file
android {
useLibrary 'org.apache.http.legacy'}
However this only works if you are using gradle 1.3.0-beta2 or greater, so you will have to add this to buildscript dependencies if you are on a lower version:
classpath 'com.android.tools.build:gradle:1.3.0-beta2'
In Spring Boot 2 the property in e.g. application.properties
is server.servlet.context-path=/myWebApp
to set the context path.
You can use:
<asp:textbox id="textBox1" style="text-align:center"></asp:textbox>
Or this:
textbox.Style["text-align"] = "center"; //right, left
Run this as root permission otherwise this might not work
docker restart $(docker ps -a -q)
with root permissions
sudo docker restart $(sudo docker ps -a -q)
I had this issue with sites running on XAMPP with private hostnames. Not so private, it turns out! They were all domain.dev
, which Google has now registered as a private gTLD, and is forcing HSTS at the domain level. Changed every virtual host to .devel
(eugh), restarted Apache and all is now well.
You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public. Usually, JSP or facelets are found outside WEB-INF, but in this case they are easily accesssible for any user. In case you have some authorization restrictions, WEB-INF can be used for that.
WEB-INF/lib can contain 3rd party libraries which you do not want to pack at system level (JARs can be available for all the applications running on your server), but only for this particular applciation.
Generally speaking, many configurations files also go into WEB-INF.
As for WEB-INF/classes - it exists in any web-app, because that is the folder where all the compiled sources are placed (not JARS, but compiled .java files that you wrote yourself).
You can download and import all of Bootstrap, and Popper, with a single command using Fetch Injection:
fetchInject([
'https://npmcdn.com/[email protected]/dist/js/bootstrap.min.js',
'https://cdn.jsdelivr.net/popper.js/1.0.0-beta.3/popper.min.js'
], fetchInject([
'https://cdn.jsdelivr.net/jquery/3.1.1/jquery.slim.min.js',
'https://npmcdn.com/[email protected]/dist/js/tether.min.js'
]));
Add CSS files if you need those too. Adjust versions and external sources to meet your needs and consider using sub-resource integrity checking if you're not hosting the files on your own domain or don't trust the source.
You can do multiple condition logical tests within the while() check using the same rules as within any logical check.
while ( obj != null ) {
// do stuff
}
works, as does
while ( value > 5 && value < 10 ) {
// do stuff
}
are valid. The conditionals are checked on each iteration through the loop. As soon as one doesn't match, the while() loop is exited. You can also use break;
while ( value > 5 ) {
if ( value > 10 ) { break; }
...
}
if you have this problem and are on api level 21+ do this:
map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
.getMap();
this will get the map when used inside of a fragment.
From James Gosling in "The Java Programming Language":
"...There is exactly one parameter passing mode in Java - pass by value - and that keeps things simple. .."
I am python novice so this may not be the most efficient method but, if I understand the intent of the question correctly, steps listed below worked for me.
>>> import numpy as np
>>> Data = np.random.random((100, 100, 1000, 2))
>>> result = np.empty(Data.shape[:-1], dtype=complex)
>>> result.real = Data[...,0]; result.imag = Data[...,1]
>>> print Data[0,0,0,0], Data[0,0,0,1], result[0,0,0]
0.0782889873474 0.156087854837 (0.0782889873474+0.156087854837j)
You can try this cool app available in play store called Html Page Source https://play.google.com/store/apps/details?id=com.scintillar.hps
Here's a simple way
for (i in 1:10) {
skip_to_next <- FALSE
# Note that print(b) fails since b doesn't exist
tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
if(skip_to_next) { next }
}
Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b)
with any code you want. You can also wrap many lines of code in {
and }
if you have more than one line of code inside the tryCatch
I'd like to add complementary information: In postman app you may use the "request" object to see your subsituted input data. (refer to https://www.getpostman.com/docs/postman/scripts/postman_sandbox in paragraph "Request/response related properties", ie.
console.log("header : " + request.headers["Content-Type"]);
console.log("body : " + request.data);
console.log("url : " + request.url);
I didn't test for header substitution but it works for url and body.
Alex
you can't. foo-bar
is not an identifier. rename the file to foo_bar.py
Edit: If import
is not your goal (as in: you don't care what happens with sys.modules
, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile
# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>>
setRetaininstance
is only useful when your activity
is destroyed and recreated due to a configuration change because the instances are saved during a call to onRetainNonConfigurationInstance
. That is, if you rotate the device, the retained fragments will remain there(they're not destroyed and recreated.) but when the runtime kills the activity to reclaim resources, nothing is left. When you press back button and exit the activity, everything is destroyed.
Usually I use this function to saved orientation changing Time.Say I have download a bunch of Bitmaps from server and each one is 1MB, when the user accidentally rotate his device, I certainly don't want to do all the download work again.So I create a Fragment
holding my bitmaps and add it to the manager and call setRetainInstance
,all the Bitmaps are still there even if the screen orientation changes.
I used the following jQuery-based snippet to have a select
-element show a div
-element that has an id
that matches the value
of the option
-element while hiding the div
s that do not match. Not sure that it's the best way, but it is a way.
$('#sectionChooser').change(function(){_x000D_
var myID = $(this).val();_x000D_
$('.panel').each(function(){_x000D_
myID === $(this).attr('id') ? $(this).show() : $(this).hide();_x000D_
});_x000D_
});
_x000D_
.panel {display: none;}_x000D_
#one {display: block;}
_x000D_
<select id="sectionChooser">_x000D_
<option value="one" selected>Thing One</option>_x000D_
<option value="two">Thing Two</option>_x000D_
<option value="three">Thing Three</option>_x000D_
</select>_x000D_
_x000D_
<div class="panel" id="one">_x000D_
<p>Thing One</p>_x000D_
</div>_x000D_
<div class="panel" id="two">_x000D_
<p>Thing Two</p>_x000D_
</div>_x000D_
<div class="panel" id="three">_x000D_
<p>Thing Three</p>_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
A regex will probably be quite efficient, because you would specify ranges: [0-9a-zA-Z]
. Assuming the implementation code for regexes is efficient, this would simply require an upper and lower bound comparison for each range. Here's basically what a compiled regex should do:
boolean isAlphanumeric(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
return false;
}
return true;
}
I don't see how your code could be more efficient than this, because every character will need to be checked, and the comparisons couldn't really be any simpler.
sorry for answering in old thread but may my code helps other in future.i was in same scenario that when check box will be checked then few selected inputs fields will be enable other wise disabled.
$("[id*='chkAddressChange']").click(function () {
var checked = $(this).is(':checked');
if (checked) {
$('.DisabledInputs').removeAttr('disabled');
} else {
$('.DisabledInputs').attr('disabled', 'disabled');
}
});
Step : 1 Import webkit
in ViewController.swift
import WebKit
Step : 2 Declare variable of webView.
var webView : WKWebView!
Step : 3 Adding Delegate of WKNavigationDelegate
class ViewController: UIViewController , WKNavigationDelegate{
Step : 4 Adding code in ViewDidLoad
.
let myBlog = "https://iosdevcenters.blogspot.com/"
let url = NSURL(string: myBlog)
let request = NSURLRequest(URL: url!)
// init and load request in webview.
webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.loadRequest(request)
self.view.addSubview(webView)
self.view.sendSubviewToBack(webView)
Step : 5 Edit the info.plist
adding
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>google.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
If you are looping through a lot of cells, use the binary function, it is much faster. Using "<> 0" in place of "> 0" also makes it faster:
If InStrB(1, myString, "a", vbBinaryCompare) <> 0
See if this example provides any clarification. Basically you configure a set of routes and include partial templates based on the route. Setting ng-view in your main index.html allows you to inject those partial views.
The config portion looks like this:
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {controller:'ListCtrl', templateUrl:'list.html'})
.otherwise({redirectTo:'/'});
}])
The point of entry for injecting the partial view into your main template is:
<div class="container" ng-view=""></div>
I too got the same error, when I did this behind a proxy. But after I exported the following from a terminal and re-tried the same command, the problem got resolved:
export http_proxy="http://username:password@proxy_ip_addr:port/"
export https_proxy="https://username:password@proxy_ip_addr:port/"
I think your error was in calling the function.
In your HTML code, onclick
is calling the image()
function. However, in your script the function is named imgWindow()
. Try changing the onclick to imgWindow()
.
I don't do much JavaScript so if I have missed something, please let me know.
Good Luck!
I would do it like this:
dictionaryFrom.ToList().ForEach(x => dictionaryTo.Add(x.Key, x.Value));
Simple and easy. According to this blog post it's even faster than most loops as its underlying implementation accesses elements by index rather than enumerator (see this answer).
It will of course throw an exception if there are duplicates, so you'll have to check before merging.
const page_number = 3;
window.location.hash = page_number as string; // Error
"Conversion of type 'number' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first." -> You will get this error if you try to typecast number to string. So, first convert it to unknown and then to string.
window.location.hash = (page_number as unknown) as string; // Correct way
Very simple , using Alt fragment
Lets take an example of sequence diagram for an ATM machine.Let's say here you want
IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"
Then here is the sequence diagram for the same
Hope this helps!
Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html