For our application, we had a client server architecture and we only allowed decrypting/encrypting data in the server level. Hence the JCE files are only needed there.
We had another problem where we needed to update a security jar on the client machines, through JNLP, it overwrites the libraries in${java.home}/lib/security/
and the JVM on first run.
That made it work.
C#: try this
Use some delimeter,like this:
For my Qt 5.7, open QtCreator, go to Tools -> Options -> Build & Run -> Qt Versions gave me the location of qmake.
Invisible: The widget takes physical space on the screen but not visible to user.
Gone: The widget doesn't take any physical space and is completely gone.
Invisible example
Visibility(
child: Text("Invisible"),
maintainSize: true,
maintainAnimation: true,
maintainState: true,
visible: false,
),
Gone example
Visibility(
child: Text("Gone"),
visible: false,
),
Alternatively, you can use if
condition for both invisible and gone.
Column(
children: <Widget>[
if (show) Text("This can be visible/not depending on condition"),
Text("This is always visible"),
],
)
I was also stuck on this problem then I saw that the ids of the modal are the same. You need different ids of modals if you want multiple modals. I used dynamic id. Here is my code in haml
:
.modal.hide.fade{"id"=> discount.id,"aria-hidden" => "true", "aria-labelledby" => "myModalLabel", :role => "dialog", :tabindex => "-1"}
you can do this
<div id="<%= some.id %>" class="modal hide fade in">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save" />
</div>
</div>
and your links to modal will be
<a data-toggle="modal" data-target="#" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>
I hope this will work for you.
My solution would be to use filter after the map.
This should support every JS data type.
example:
const notUndefined = anyValue => typeof anyValue !== 'undefined'
const noUndefinedList = someList
.map(// mapping condition)
.filter(notUndefined); // by doing this,
//you can ensure what's returned is not undefined
Essentially it means you don't have the index you are trying to reference. For example:
df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)
will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:
df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)
Hope that answers your question!
Lazy exceptions occur when you fetch an object typically containing a collection which is lazily loaded, and try to access that collection.
You can avoid this problem by
Hibernate.initialize(obj);
Fetch profiles
to select lazy/non-lazy fetching runtimeFurther I would recommend looking at the related
links to your right where this question has been answered many times before. Also see Hibernate lazy-load application design.
try this out:
SELECT
`userName`,
`carPrice`
FROM `users`
LEFT JOIN `cars`
ON cars.belongsToUser=users.id
WHERE `id`='4'
ORDER BY `carPrice` DESC
LIMIT 1
Felix
These two schools are not really excluding.
Here is the scenario where you simply have to use
Task.Run(() => AsyncOperation()).Wait();
or something like
AsyncContext.Run(AsyncOperation);
I have a MVC action that is under database transaction attribute. The idea was (probably) to roll back everything done in the action if something goes wrong. This does not allow context switching, otherwise transaction rollback or commit is going to fail itself.
The library I need is async as it is expected to run async.
The only option. Run it as a normal sync call.
I am just saying to each its own.
For Swift 3.0 you can use following
button.addTarget(self, action: #selector(YourViewController.YourMethodName(_:)), for:.touchUpInside)
func YourMethodName(_ sender : UIButton) {
print(sender.tag)
}
* {
-ms-touch-action: manipulation;
touch-action: manipulation;
}
Disable double tap to zoom on touch screens. Internet explorer included.
This is the XML optional preamble.
version="1.0"
means that this is the XML standard this file conforms toencoding="utf-8"
means that the file is encoded using the UTF-8 Unicode encodingImplement the Serializable
interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable
object might reference an instance of your class.
Serializable
classes are useful when you want to persist instances of them or send them over a wire.
Instances of Serializable
classes can be easily transmitted. Serialization does have some security consequences, however. Read Joshua Bloch's Effective Java.
An expression is something, while a statement does something.
An expression is a statement as well, but it must have a return.
>>> 2 * 2 #expression
>>> print(2 * 2) #statement
PS:The interpreter always prints out the values of all expressions.
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
Here's my method to install git on centos 6.
sudo yum groupinstall "Development Tools"
sudo yum install zlib-devel perl-ExtUtils-MakeMaker asciidoc xmlto openssl-devel curl-devel
sudo yum install wget
cd ~
wget -O git.zip https://github.com/git/git/archive/v2.7.2.zip
unzip git.zip
cd git-2.7.2
make configure
./configure --prefix=/usr/local
make all doc
sudo make install install-doc install-html
I wrote helper to add attributes easily:
- (void)addColor:(UIColor *)color substring:(NSString *)substring;
- (void)addBackgroundColor:(UIColor *)color substring:(NSString *)substring;
- (void)addUnderlineForSubstring:(NSString *)substring;
- (void)addStrikeThrough:(int)thickness substring:(NSString *)substring;
- (void)addShadowColor:(UIColor *)color width:(int)width height:(int)height radius:(int)radius substring:(NSString *)substring;
- (void)addFontWithName:(NSString *)fontName size:(int)fontSize substring:(NSString *)substring;
- (void)addAlignment:(NSTextAlignment)alignment substring:(NSString *)substring;
- (void)addColorToRussianText:(UIColor *)color;
- (void)addStrokeColor:(UIColor *)color thickness:(int)thickness substring:(NSString *)substring;
- (void)addVerticalGlyph:(BOOL)glyph substring:(NSString *)substring;
https://github.com/shmidt/MASAttributes
You can install through CocoaPods also : pod 'MASAttributes', '~> 1.0.0'
Swift 2.0:
Get a count: yourString.text.characters.count
Fun example of how this is useful would be to show a character countdown from some number (150 for example) in a UITextView:
func textViewDidChange(textView: UITextView) {
yourStringLabel.text = String(150 - yourStringTextView.text.characters.count)
}
Just download and install openSSH for windows. It is open source, and it makes your cmd ssh ready. A quick google search will give you a tutorial on how to install it, should you need it.
After it is installed you can just go ahead and generate your public key if you want to put in on a server. You generate it by running:
ssh-keygen -t rsa
After that you can just can just press enter, it will automatically assign a name for the key (example: id_rsa.pub)
Date and time as String to Long (millis):
String dateTimeString = "2020-12-12T14:34:18.000Z";
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDateTime localDateTime = LocalDateTime
.parse(dateTimeString, formatter);
Long dateTimeMillis = localDateTime
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
You can't rely on order of dictionaries, but you may try this:
mydict['Apple'].items()[0][0]
If you want the order to be preserved you may want to use this: http://www.python.org/dev/peps/pep-0372/#ordered-dict-api
Just installed git using the following instructions:
Install EPEL V5
#rpm -Uvh http://archives.fedoraproject.org/pub/archive/epel/5/x86_64/epel-release-5-4.noarch.rpm
Install Git
# yum install git git-daemon
Check
# git --version
git version 1.8.2.3
Optionally install Git GUI
# yum install git-gui
For i386 substitute x86_64 by i386 in the URL at step #1.
#rpm -Uvh http://archives.fedoraproject.org/pub/archive/epel/5/i386/epel-release-5-4.noarch.rpm
you can try with
Process process = new Process();
process.StartInfo.FileName = "yourProgram.exe";
process.StartInfo.Arguments = ..... //your parameters
process.Start();
terminal output:
ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}'
file output:
ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' > test.txt
terminal + file output:
ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' | tee test.txt
file output background:
nohup ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' > test.txt &
From the JVM™ Tool Interface documentation…
Since the command-line cannot always be accessed or modified, for example in embedded VMs or simply VMs launched deep within scripts, a
JAVA_TOOL_OPTIONS
variable is provided so that agents may be launched in these cases.
By setting the (Windows) environment variable JAVA_TOOL_OPTIONS
to -Dfile.encoding=UTF8
, the (Java) System
property will be set automatically every time a JVM is started. You will know that the parameter has been picked up because the following message will be posted to System.err
:
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
The right query:
drop table #tmp_table
select new_acc_no, count(new_acc_no) as count1
into #tmp_table
from table
where unit_id = '0007'
group by unit_id, new_acc_no
having count(new_acc_no) > 1
Using this JavaScript will help you a lot. Some explanations are given within the code.
<script type="text/javascript">
<!--
function Blank_TextField_Validator()
{
// Check whether the value of the element
// text_name from the form named text_form is null
if (!text_form.text_name.value)
{
// If it is display and alert box
alert("Please fill in the text field.");
// Place the cursor on the field for revision
text_form.text_name.focus();
// return false to stop further processing
return (false);
}
// If text_name is not null continue processing
return (true);
}
-->
</script>
<form name="text_form" method="get" action="#"
onsubmit="return Blank_TextField_Validator()">
<input type="text" name="text_name" >
<input type="submit" value="Submit">
</form>
Updating @Dario's code approach for Xcode 8.2.2, Swift 3.x. Noting that in storyboard, set the Background color to "clear" to avoid a black background in the square UIView:
import UIKit
@IBDesignable
class Dot:UIView
{
@IBInspectable var mainColor: UIColor = UIColor.clear
{
didSet { print("mainColor was set here") }
}
@IBInspectable var ringColor: UIColor = UIColor.clear
{
didSet { print("bColor was set here") }
}
@IBInspectable var ringThickness: CGFloat = 4
{
didSet { print("ringThickness was set here") }
}
@IBInspectable var isSelected: Bool = true
override func draw(_ rect: CGRect)
{
let dotPath = UIBezierPath(ovalIn: rect)
let shapeLayer = CAShapeLayer()
shapeLayer.path = dotPath.cgPath
shapeLayer.fillColor = mainColor.cgColor
layer.addSublayer(shapeLayer)
if (isSelected) { drawRingFittingInsideView(rect: rect) }
}
internal func drawRingFittingInsideView(rect: CGRect)->()
{
let hw:CGFloat = ringThickness/2
let circlePath = UIBezierPath(ovalIn: rect.insetBy(dx: hw,dy: hw) )
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = ringColor.cgColor
shapeLayer.lineWidth = ringThickness
layer.addSublayer(shapeLayer)
}
}
And if you want to control the start and end angles:
import UIKit
@IBDesignable
class Dot:UIView
{
@IBInspectable var mainColor: UIColor = UIColor.clear
{
didSet { print("mainColor was set here") }
}
@IBInspectable var ringColor: UIColor = UIColor.clear
{
didSet { print("bColor was set here") }
}
@IBInspectable var ringThickness: CGFloat = 4
{
didSet { print("ringThickness was set here") }
}
@IBInspectable var isSelected: Bool = true
override func draw(_ rect: CGRect)
{
let dotPath = UIBezierPath(ovalIn: rect)
let shapeLayer = CAShapeLayer()
shapeLayer.path = dotPath.cgPath
shapeLayer.fillColor = mainColor.cgColor
layer.addSublayer(shapeLayer)
if (isSelected) { drawRingFittingInsideView(rect: rect) }
}
internal func drawRingFittingInsideView(rect: CGRect)->()
{
let halfSize:CGFloat = min( bounds.size.width/2, bounds.size.height/2)
let desiredLineWidth:CGFloat = ringThickness // your desired value
let circlePath = UIBezierPath(
arcCenter: CGPoint(x: halfSize, y: halfSize),
radius: CGFloat( halfSize - (desiredLineWidth/2) ),
startAngle: CGFloat(0),
endAngle:CGFloat(Double.pi),
clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = ringColor.cgColor
shapeLayer.lineWidth = ringThickness
layer.addSublayer(shapeLayer)
}
}
You can use ::after
to create a 0px
-height block after the <h4>
, which effectively moves anything after the <h4>
to the next line:
h4 {_x000D_
display: inline;_x000D_
}_x000D_
h4::after {_x000D_
content: "";_x000D_
display: block;_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
Text, text, text, text, text. <h4>Sub header</h4>_x000D_
Text, text, text, text, text._x000D_
</li>_x000D_
</ul>
_x000D_
When using JavaScript to access an HTML element, there is a good chance that the element is not on the page and therefore not in the dom as far as JavaScript is concerned, when the code to access that element runs.
This problem can occur even though you can visually see the HTML element in the browser window or have the code set to be called in the onload method.
I ran into this problem after writing code to repopulate specific div elements on a page after retrieving the cookies.
What is apparently happening is that even though the HTML has loaded and is outputted by the browser, the JavaScript code is running before the page has completed loading.
The solution to this problem which just may be a JavaScript bug, is to place the code you want to run within a timer that delays the code run by 400 milliseconds or so. You will need to test it to determine how quick you can run the code.
I also made a point to test for the element before attempting to assign values to it.
window.setTimeout(function() {
if( document.getElementById("book") )
{ // Code goes here }, 400 /* but after 400 ms */);
This may or may not help you solve your problem, but keep this in mind and understand that browsers do not always function as expected.
You can't close sockets without shutting down the process that owns those sockets. Sockets are owned by the process that opened them. So to find out the process ID (PID) for Unix/Linux. Use netstat like so:
netstat -a -n -p -l
That will print something like:
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1879/sendmail: acce
tcp 0 0 0.0.0.0:21 0.0.0.0:* LISTEN 1860/xinetd
Where -a prints all sockets, -n shows the port number, -p shows the PID, -l shows only what's listening (this is optional depending on what you're after).
The real info you want is PID. Now we can shutdown that process by doing:
kill 1879
If you are shutting down a service it's better to use:
service sendmail stop
Kill literally kills just that process and any children it owns. Using the service command runs the shutdown script registered in the init.d directory. If you use kill on a service it might not properly start back up because you didn't shut it down properly. It just depends on the service.
Unfortunately, Mac is different from Linux/Unix in this respect. You can't use netstat. Read this tutorial if you're interested in Mac:
http://www.tech-recipes.com/rx/227/find-out-which-process-is-holding-which-socket-open/
And if you're on Windows use TaskManager to kill processes, and services UI to shutdown services. You can use netstat on Windows just like Linux/Unix to identify the PID.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/netstat.mspx?mfr=true
Try this:
<style>
#wrapper { position: relative; }
#over_map { position: absolute; top: 10px; left: 10px; z-index: 99; }
</style>
<div id="wrapper">
<div id="google_map">
</div>
<div id="over_map">
</div>
</div>
Set conn.setAutoCommit(false) to conn.setAutoCommit(true)
Commit the transactions before initiating a new one.
jquery:
$('div.animalcontent').hide();
$('div').hide();
$('p.animal').bind('mouseover', function() {
$('div.animalcontent').fadeOut();
$('#'+$(this).attr('id')+'content').fadeIn();
});
html:
<p class='animal' id='dog'>dog url</p><div id='dogcontent' class='animalcontent'>Doggiecontent!</div>
<p class='animal' id='cat'>cat url</p><div id='catcontent' class='animalcontent'>Pussiecontent!</div>
<p class='animal' id='snake'>snake url</p><div id='snakecontent'class='animalcontent'>Snakecontent!</div>
-edit-
yeah sure, here you go -- JSFiddle
NULL has no value, and so cannot be compared using the scalar value operators.
In other words, no value can ever be equal to (or not equal to) NULL because NULL has no value.
Hence, SQL has special IS NULL and IS NOT NULL predicates for dealing with NULL.
Let me propose an improved method when the values of the dictionnary are lists with the same lenght :
import numpy
def dctToNdarray (dd, szFormat = 'f8'):
'''
Convert a 'rectangular' dictionnary to numpy NdArray
entry
dd : dictionnary (same len of list
retrun
data : numpy NdArray
'''
names = dd.keys()
firstKey = dd.keys()[0]
formats = [szFormat]*len(names)
dtype = dict(names = names, formats=formats)
values = [tuple(dd[k][0] for k in dd.keys())]
data = numpy.array(values, dtype=dtype)
for i in range(1,len(dd[firstKey])) :
values = [tuple(dd[k][i] for k in dd.keys())]
data_tmp = numpy.array(values, dtype=dtype)
data = numpy.concatenate((data,data_tmp))
return data
dd = {'a':[1,2.05,25.48],'b':[2,1.07,9],'c':[3,3.01,6.14]}
data = dctToNdarray(dd)
print data.dtype.names
print data
Localization support in legacy browsers is poor. Originally, this was due to phrases in the ECMAScript
language spec that look like this:
Number.prototype.toLocaleString()
Produces a string value that represents the value of the Number formatted according to the conventions of the host environment’s current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.
Every localization method defined in the spec is defined as "implementation-dependent", which results in a lot of inconsistencies. In this instance, Chrome Opera and Safari would return the same thing as .toString()
. Firefox and IE will return locale formatted strings, and IE even includes a thousand separator (perfect for currency strings). Chrome was recently updated to return a thousands-separated string, though with no fixed decimal.
For modern environments, the ECMAScript Internationalization API spec, a new standard that complements the ECMAScript Language spec, provides much better support for string comparison, number formatting, and the date and time formatting; it also fixes the corresponding functions in the Language Spec. An introduction can be found here. Implementations are available in:
There is also a compatibility implementation, Intl.js, which will provide the API in environments where it doesn't already exist.
Determining the user's preferred language remains a problem since there's no specification for obtaining the current language. Each browser implements a method to obtain a language string, but this could be based on the user's operating system language or just the language of the browser:
// navigator.userLanguage for IE, navigator.language for others
var lang = navigator.language || navigator.userLanguage;
A good workaround for this is to dump the Accept-Language header from the server to the client. If formatted as a JavaScript, it can be passed to the Internationalization API constructors, which will automatically pick the best (or first-supported) locale.
In short, you have to put in a lot of the work yourself, or use a framework/library, because you cannot rely on the browser to do it for you.
Various libraries and plugins for localization:
Feel free to add/edit.
Height of Binary Tree
public static int height(Node root)
{
// Base case: empty tree has height 0
if (root == null) {
return 0;
}
// recursively for left and right subtree and consider maximum depth
return 1 + Math.max(height(root.left), height(root.right));
}
To read characters try
scan("/PathTo/file.csv", "")
If you're reading numeric values, then just use
scan("/PathTo/file.csv")
scan
by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).
A possibility is to have an iframe inside the outer form. The iframe contains the inner form. Make sure to use the <base target="_parent" />
tag inside the head tag of the iframe to make the form behave as part of the main page.
Just an another way:
public static class ApplicationExitCodes
{
public static readonly int Failure = 1;
public static readonly int Success = 0;
}
I used a slightly modified version:
with open(file_name, 'w', encoding = 'utf-8') as f:
for rec_index, rec in df.iterrows():
f.write(rec['<field>'] + '\n')
I had to write the contents of a dataframe field (that was delimited) as a text file.
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
You can update your jquery typings version like so
npm install --save @types/jquery@latest
I had this same error and I've been at if for 5 days surfing the net for a solution.it worked for me and it should work for you
In JavaScript everything is an object
console.log(type of({})) //Object
console.log(type of([])) //Object
To get Real type , use this
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
Hope this helps
Strictly speaking, the difference between Database and Schema is inexisting in MySql.
However, this is not the case in other database engines such as SQL Server. In SQL server:,
Every table belongs to a grouping of objects in the database called database schema. It's a container or namespace (Querying Microsoft SQL Server 2012)
By default, all the tables in SQL Server belong to a default schema called dbo. When you query a table that hasn't been allocated to any particular schema, you can do something like:
SELECT *
FROM your_table
which is equivalent to:
SELECT *
FROM dbo.your_table
Now, SQL server allows the creation of different schema, which gives you the possibility of grouping tables that share a similar purpose. That helps to organize the database.
For example, you can create an schema called sales, with tables such as invoices, creditorders (and any other related with sales), and another schema called lookup, with tables such as countries, currencies, subscriptiontypes (and any other table used as look up table).
The tables that are allocated to a specific domain are displayed in SQL Server Studio Manager with the schema name prepended to the table name (exactly the same as the tables that belong to the default dbo schema).
There are special schemas in SQL Server. To quote the same book:
There are several built-in database schemas, and they can't be dropped or altered:
1) dbo, the default schema.
2) guest contains objects available to a guest user ("guest user" is a special role in SQL Server lingo, with some default and highly restricted permissions). Rarely used.
3) INFORMATION_SCHEMA, used by the Information Schema Views
4) sys, reserved for SQL Server internal use exclusively
Schemas are not only for grouping. It is actually possible to give different permissions for each schema to different users, as described MSDN.
Doing this way, the schema lookup mentioned above could be made available to any standard user in the database (e.g. SELECT
permissions only), whereas a table called supplierbankaccountdetails may be allocated in a different schema called financial, and to give only access to the users in the group accounts
(just an example, you get the idea).
Finally, and quoting the same book again:
It isn't the same Database Schema and Table Schema. The former is the namespace of a table, whereas the latter refers to the table definition
Similar question has been asked in stackoverflow before.
See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?
Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host
Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:
- no DNS support
- misconfigured
- behind load balancing software
From Android's Developer Documentation on Managing Projects from Eclipse with ADT:
Next, set the project's Properties to indicate that it is a library project:
- In the Package Explorer, right-click the library project and select Properties.
- In the Properties window, select the "Android" properties group at left and locate the Library properties at right.
- Select the "is Library" checkbox and click Apply.
- Click OK to close the Properties window.
So, open your project properties, un-select the "Is Library" checkbox, and click Apply to make your project a normal Android project (not a library project).
I have solved this issue by adding below in my package.json for killing active PORT - 4000 (in my case) Running on WSL2/Linux/Mac
"scripts": {
"dev": "nodemon app.js",
"predev":"fuser -k 4000/tcp && echo 'Terminated' || echo 'Nothing was running on the PORT'",
}
I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!
This is my working example:
Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
' in duplicated formatting rules that in turn will significantly slow down
' the spreadsheet.
' This macro is designed to reset all formatting rules to default.
' ----------------------------------------------------------------------------------------
On Error GoTo ErrHandler
' Make sure we are positioned in the correct sheet
WS_PROMO.Select
' Disable Events
Application.EnableEvents = False
' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete
' CREATE ALL THE CONDITIONAL FORMATTING RULES:
' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
.Font.Color = -16776961
.StopIfTrue = False
End With
' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
.Font.Color = -16744448
.StopIfTrue = False
End With
' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
.Font.Bold = True
.Font.Color = -16776961
.StopIfTrue = False
End With
' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
.Font.Bold = True
.Font.Color = -10092544
.StopIfTrue = False
End With
' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
.DupeUnique = xlDuplicate
.Font.Color = -16383844
.Interior.Color = 13551615
.StopIfTrue = False
End With
' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
.Font.Bold = True
.Interior.Color = 13434879
.StopIfTrue = False
End With
' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")
ErrHandler:
Application.EnableEvents = False
End Sub
$(this).css({'text-align':'center'});
You can use class name and id in place of this
$('.classname').css({'text-align':'center'});
or
$('#id').css({'text-align':'center'});
You can mount files or directories/folders it all depends on Source file or directory. And also you need to provide full path or if you are not sure you can use PWD. Here is a simple working example.
In this example, I am mounting env-commands file which already exists in my working directory
$ docker run --rm -it -v ${PWD}/env-commands:/env-commands aravindgv/eosdt:1.0.5 /bin/bash -c "cat /env-commands"
Changing the casing to all lowercases worked for me.
From Java 9 there is some optimizations in replace method.
In Java 8 it uses a regex.
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
From Java 9 and on.
And Stringlatin implementation.
Which perform way better.
I solve it!
First off all, you should add these:
defaultConfig {
multiDexEnabled true
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
After, you should click Build in top bar of Android Studio:
Build > Build Bundle(s) / APK(s) > Build APK(s)
Finally, you have an app-debug.apk file in:
app > build > outputs > apk > debug > app-debug.apk
Note: apk, debug, app-debug.apk files created automatically in outputs file by Android Studio.
(Under Linux), I wanted to use the posts here suggesting the ls-files --ignored --exclude-standard | xargs git rm -r --cached
approach. However, (some of) the files to be removed had an embedded newline/LF/\n
in their names. Neither of the solutions:
git ls-files --ignored --exclude-standard | xargs -d"\n" git rm --cached
git ls-files --ignored --exclude-standard | sed 's/.*/"&"/' | xargs git rm -r --cached
cope with this situation (get errors about files not found).
git ls-files -z --ignored --exclude-standard | xargs -0 git rm -r --cached
git commit -am "Remove ignored files"
This uses the -z
argument to ls-files, and the -0
argument to xargs to cater safely/correctly for "nasty" characters in filenames.
In the manual page git-ls-files(1), it states:
When -z option is not used, TAB, LF, and backslash characters in pathnames are represented as \t, \n, and \\, respectively.
so I think my solution is needed if filenames have any of these characters in them.
bbox_to_anchor
)A legend is positioned inside the bounding box of the axes using the loc
argument to plt.legend
.
E.g. loc="upper right"
places the legend in the upper right corner of the bounding box, which by default extents from (0,0)
to (1,1)
in axes coordinates (or in bounding box notation (x0,y0, width, height)=(0,0,1,1)
).
To place the legend outside of the axes bounding box, one may specify a tuple (x0,y0)
of axes coordinates of the lower left corner of the legend.
plt.legend(loc=(1.04,0))
A more versatile approach is to manually specify the bounding box into which the legend should be placed, using the bbox_to_anchor
argument. One can restrict oneself to supply only the (x0, y0)
part of the bbox. This creates a zero span box, out of which the legend will expand in the direction given by the loc
argument. E.g.
plt.legend(bbox_to_anchor=(1.04,1), loc="upper left")
places the legend outside the axes, such that the upper left corner of the legend is at position (1.04,1)
in axes coordinates.
Further examples are given below, where additionally the interplay between different arguments like mode
and ncols
are shown.
l1 = plt.legend(bbox_to_anchor=(1.04,1), borderaxespad=0)
l2 = plt.legend(bbox_to_anchor=(1.04,0), loc="lower left", borderaxespad=0)
l3 = plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)
l4 = plt.legend(bbox_to_anchor=(0,1.02,1,0.2), loc="lower left",
mode="expand", borderaxespad=0, ncol=3)
l5 = plt.legend(bbox_to_anchor=(1,0), loc="lower right",
bbox_transform=fig.transFigure, ncol=3)
l6 = plt.legend(bbox_to_anchor=(0.4,0.8), loc="upper right")
Details about how to interpret the 4-tuple argument to bbox_to_anchor
, as in l4
, can be found in this question. The mode="expand"
expands the legend horizontally inside the bounding box given by the 4-tuple. For a vertically expanded legend, see this question.
Sometimes it may be useful to specify the bounding box in figure coordinates instead of axes coordinates. This is shown in the example l5
from above, where the bbox_transform
argument is used to put the legend in the lower left corner of the figure.
Having placed the legend outside the axes often leads to the undesired situation that it is completely or partially outside the figure canvas.
Solutions to this problem are:
Adjust the subplot parameters
One can adjust the subplot parameters such, that the axes take less space inside the figure (and thereby leave more space to the legend) by using plt.subplots_adjust
. E.g.
plt.subplots_adjust(right=0.7)
leaves 30% space on the right-hand side of the figure, where one could place the legend.
Tight layout
Using plt.tight_layout
Allows to automatically adjust the subplot parameters such that the elements in the figure sit tight against the figure edges. Unfortunately, the legend is not taken into account in this automatism, but we can supply a rectangle box that the whole subplots area (including labels) will fit into.
plt.tight_layout(rect=[0,0,0.75,1])
Saving the figure with bbox_inches = "tight"
The argument bbox_inches = "tight"
to plt.savefig
can be used to save the figure such that all artist on the canvas (including the legend) are fit into the saved area. If needed, the figure size is automatically adjusted.
plt.savefig("output.png", bbox_inches="tight")
automatically adjusting the subplot params
A way to automatically adjust the subplot position such that the legend fits inside the canvas without changing the figure size can be found in this answer: Creating figure with exact size and no padding (and legend outside the axes)
Comparison between the cases discussed above:
A figure legend
One may use a legend to the figure instead of the axes, matplotlib.figure.Figure.legend
. This has become especially useful for matplotlib version >=2.1, where no special arguments are needed
fig.legend(loc=7)
to create a legend for all artists in the different axes of the figure. The legend is placed using the loc
argument, similar to how it is placed inside an axes, but in reference to the whole figure - hence it will be outside the axes somewhat automatically. What remains is to adjust the subplots such that there is no overlap between the legend and the axes. Here the point "Adjust the subplot parameters" from above will be helpful. An example:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,2*np.pi)
colors=["#7aa0c4","#ca82e1" ,"#8bcd50","#e18882"]
fig, axes = plt.subplots(ncols=2)
for i in range(4):
axes[i//2].plot(x,np.sin(x+i), color=colors[i],label="y=sin(x+{})".format(i))
fig.legend(loc=7)
fig.tight_layout()
fig.subplots_adjust(right=0.75)
plt.show()
Legend inside dedicated subplot axes
An alternative to using bbox_to_anchor
would be to place the legend in its dedicated subplot axes (lax
).
Since the legend subplot should be smaller than the plot, we may use gridspec_kw={"width_ratios":[4,1]}
at axes creation.
We can hide the axes lax.axis("off")
but still put a legend in. The legend handles and labels need to obtained from the real plot via h,l = ax.get_legend_handles_labels()
, and can then be supplied to the legend in the lax
subplot, lax.legend(h,l)
. A complete example is below.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6,2
fig, (ax,lax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios":[4,1]})
ax.plot(x,y, label="y=sin(x)")
....
h,l = ax.get_legend_handles_labels()
lax.legend(h,l, borderaxespad=0)
lax.axis("off")
plt.tight_layout()
plt.show()
This produces a plot, which is visually pretty similar to the plot from above:
We could also use the first axes to place the legend, but use the bbox_transform
of the legend axes,
ax.legend(bbox_to_anchor=(0,0,1,1), bbox_transform=lax.transAxes)
lax.axis("off")
In this approach, we do not need to obtain the legend handles externally, but we need to specify the bbox_to_anchor
argument.
loc
argument can take numbers instead of strings, which make calls shorter, however, they are not very intuitively mapped to each other. Here is the mapping for reference:raise SystemExit
this worked on the first try, where
self.destroy()
root.destroy()
did not
If you're using Python 3, raw_input
has changed to input
Python 3 example:
line = input('Enter a sentence:')
In TortoiseHg, right-click on the revision you want to modify. Choose Modify History->Import MQ. That will convert all the revisions up to and including the selected revision from Mercurial changesets into Mercurial Queue patches. Select the Patch you want to modify the message for, and it should automatically change the screen to the MQ editor. Edit the message which is in the middle of the screen, then click QRefresh. Finally, right click on the patch and choose Modify History->Finish Patch, which will convert it from a patch back into a change set.
Oh, this assumes that MQ is an active extension for TortoiseHG on this repository. If not, you should be able to click File->Settings, click Extensions, and click the mq checkbox. It should warn you that you have to close TortoiseHg before the extension is active, so close and reopen.
Int[] number ={1,2,3,4,5,6,7,8,9,10};
Int? Result = null;
foreach(Int i in number)
{
If(!Result.HasValue || i< Result)
{
Result =i;
}
}
Console.WriteLine(Result);
}
Another alternative, using the rgr
package:
> library(rgr)
> gx.sort.df(dd, ~ -z+b)
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1
Trying to think in tableless design does not mean that you can not use tables :)
It is only that you can think of it that tabular data can be presented in a table, and that other elements (mostly div's) are used to create the layout of the page.
So I should say that you have to read some information on styling with div-elements, or use this page as a good example page!
Good luck ;)
For a single style attribute, you can use the following syntax:
<div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">
I assumed that the background color should not be set if neither style1
nor style2
is true
.
Since the question title mentions ngStyle
, here is the equivalent syntax with that directive:
<div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">
The following will give you the hex encoding for the low byte of each character, which looks like what you're asking for:
StringBuilder sb = new StringBuilder();
foreach (char c in asciiString)
{
uint i = (uint)c;
sb.AppendFormat("{0:X2}", (i & 0xff));
}
return sb.ToString();
I would like to add to this, there are somethings to consider during the import calls:
I have the following structure:
mod/
__init__.py
main.py
a.py
b.py
c.py
d.py
main.py:
import mod.a
import mod.b as b
from mod import c
import d
dis.dis shows the difference:
1 0 LOAD_CONST 0 (-1)
3 LOAD_CONST 1 (None)
6 IMPORT_NAME 0 (mod.a)
9 STORE_NAME 1 (mod)
2 12 LOAD_CONST 0 (-1)
15 LOAD_CONST 1 (None)
18 IMPORT_NAME 2 (b)
21 STORE_NAME 2 (b)
3 24 LOAD_CONST 0 (-1)
27 LOAD_CONST 2 (('c',))
30 IMPORT_NAME 1 (mod)
33 IMPORT_FROM 3 (c)
36 STORE_NAME 3 (c)
39 POP_TOP
4 40 LOAD_CONST 0 (-1)
43 LOAD_CONST 1 (None)
46 IMPORT_NAME 4 (mod.d)
49 LOAD_ATTR 5 (d)
52 STORE_NAME 5 (d)
55 LOAD_CONST 1 (None)
In the end they look the same (STORE_NAME is result in each example), but this is worth noting if you need to consider the following four circular imports:
foo/
__init__.py
a.py
b.py
a.py:
import foo.b
b.py:
import foo.a
>>> import foo.a
>>>
This works
bar/
__init__.py
a.py
b.py
a.py:
import bar.b as b
b.py:
import bar.a as a
>>> import bar.a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bar\a.py", line 1, in <module>
import bar.b as b
File "bar\b.py", line 1, in <module>
import bar.a as a
AttributeError: 'module' object has no attribute 'a'
No dice
baz/
__init__.py
a.py
b.py
a.py:
from baz import b
b.py:
from baz import a
>>> import baz.a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "baz\a.py", line 1, in <module>
from baz import b
File "baz\b.py", line 1, in <module>
from baz import a
ImportError: cannot import name a
Similar issue... but clearly from x import y is not the same as import import x.y as y
qux/
__init__.py
a.py
b.py
a.py:
import b
b.py:
import a
>>> import qux.a
>>>
This one also works
The answer mentioned by @HaNdTriX is a great, but we are not sure if DOM is completely loaded in the below code:
var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
This works perfectly when used with onload as:
window.onload = function () {
var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart;
console.log('Page load time is '+ loadTime);
}
Edit 1: Added some context to answer
Note: loadTime
is in milliseconds, you can divide by 1000 to get seconds as mentioned by @nycynik
I've finally worked it out. The biggest issue is how they managed to work out what Wireless networks were around me and how do they know where these networks are.
It "seems" to be something similar to this:
Reference: Slashdot
From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning
the following
Excessive GC Time and OutOfMemoryError
The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.
The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).
in conjunction with a passage further down
One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,
java -Dsun.rmi.dgc.client.gcInterval=3600000
-Dsun.rmi.dgc.server.gcInterval=3600000
specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.
Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.
Of course, other interpretations are possible.
This is a quite confusing way of using Apache configuration directives.
Technically, the first bit is equivalent to
Allow From All
This is because Order Deny,Allow
makes the Deny directive evaluated before the Allow Directives.
In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.
Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.
The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.
Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.
It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.
The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
which forbids access to any file beginning by ".ht".
The equivalent Apache 2.4 configuration should look like:
<Files ~ "^\.ht">
Require all denied
</Files>
cmd
Tunnel all your internet traffic through a socks proxy:
netsh winhttp set proxy proxy-server="socks=localhost:9090" bypass-list="localhost"
View the current proxy settings:
netsh winhttp show proxy
Clear all proxy settings:
netsh winhttp reset proxy
Use either of the Map
implementations bundled with Java 6 and later that implement NavigableMap
(the successor to SortedMap
):
TreeMap
if running single-threaded, or if the map is to be read-only across threads after first being populated. ConcurrentSkipListMap
if manipulating the map across threads.NavigableMap
FYI, the SortedMap
interface was succeeded by the NavigableMap
interface.
You would only need to use SortedMap
if using 3rd-party implementations that have not yet declared their support of NavigableMap
. Of the maps bundled with Java, both of the implementations that implement SortedMap
also implement NavigableMap
.
s SortedMap the best answer? TreeMap?
As others mentioned, SortedMap
is an interface while TreeMap
is one of multiple implementations of that interface (and of the more recent NavigableMap
.
Having an interface allows you to write code that uses the map without breaking if you later decide to switch between implementations.
NavigableMap< Employee , Project > currentAssignments = new TreeSet<>() ;
currentAssignments.put( alice , writeAdCopyProject ) ;
currentAssignments.put( bob , setUpNewVendorsProject ) ;
This code still works if later change implementations. Perhaps you later need a map that supports concurrency for use across threads. Change that declaration to:
NavigableMap< Employee , Project > currentAssignments = new ConcurrentSkipListMap<>() ;
…and the rest of your code using that map continues to work.
There are ten implementations of Map
bundled with Java 11. And more implementations provided by 3rd parties such as Google Guava.
Here is a graphic table I made highlighting the various features of each. Notice that two of the bundled implementations keep the keys in sorted order by examining the key’s content. Also, EnumMap
keeps its keys in the order of the objects defined on that enum. Lastly, the LinkedHashMap
remembers original insertion order.
You cannot undo the latest git add, but you can undo all add
s since the last commit. git reset
without a commit argument resets the index (unstages staged changes):
git reset
I updated the SDK version in app.json to match with the react native SDK version in package.json to fix this issue
In app.json
"sdkVersion": "37.0.0",
In package.json
"react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",
If you have a wamp setup that won't send emails, there is only a couple of things to do. 1. find out what the smtp server name is for your isp. The gmail thing is most likely unnecessary complication 2. create a phpsetup.php file in your 'www' folder and edit like this:
<?php
phpinfo();
?>
this will give you a handle on what wamp is using. 3. search for the php.ini file. there may be serveral. The one you want is the one that effects the output of the file above. 4. find the smtp address in the most likely php.ini. 5. Type in your browser localhost/phpsetup.php and scroll down to smtp setting. it should say 'localhost' 6. edit the php.ini file smtp setting to the name of your ISPs smtp server. check if it changes for you phpsetup.php. if it works your done, if not you are working the wrong file.
this issue should be on the Wordpress site but they are way too up-them-selves or trying to get clients.;)
If one only cares about whitespace at the beginning and end of the string (but not in the middle), then another option is to use String.trim():
" your string contents ".trim();
// => "your string contents"
You can open the PDF file and extract its contents using the Adobe library (which I believe you can download from Adobe as part of the SDK, but it comes with certain versions of Acrobat as well)
Make sure to add the Library to your references too (On my machine it is the Adobe Acrobat 10.0 Type Library, but not sure if that is the newest version)
Even with the Adobe library it is not trivial (you'll need to add your own error-trapping etc):
Function getTextFromPDF(ByVal strFilename As String) As String
Dim objAVDoc As New AcroAVDoc
Dim objPDDoc As New AcroPDDoc
Dim objPage As AcroPDPage
Dim objSelection As AcroPDTextSelect
Dim objHighlight As AcroHiliteList
Dim pageNum As Long
Dim strText As String
strText = ""
If (objAvDoc.Open(strFilename, "") Then
Set objPDDoc = objAVDoc.GetPDDoc
For pageNum = 0 To objPDDoc.GetNumPages() - 1
Set objPage = objPDDoc.AcquirePage(pageNum)
Set objHighlight = New AcroHiliteList
objHighlight.Add 0, 10000 ' Adjust this up if it's not getting all the text on the page
Set objSelection = objPage.CreatePageHilite(objHighlight)
If Not objSelection Is Nothing Then
For tCount = 0 To objSelection.GetNumText - 1
strText = strText & objSelection.GetText(tCount)
Next tCount
End If
Next pageNum
objAVDoc.Close 1
End If
getTextFromPDF = strText
End Function
What this does is essentially the same thing you are trying to do - only using Adobe's own library. It's going through the PDF one page at a time, highlighting all of the text on the page, then dropping it (one text element at a time) into a string.
Keep in mind what you get from this could be full of all kinds of non-printing characters (line feeds, newlines, etc) that could even end up in the middle of what look like contiguous blocks of text, so you may need additional code to clean it up before you can use it.
Hope that helps!
It depends on whether you process IDNs before or after the IDN toASCII
algorithm (that is, do you see the domain name pa??de??µa.d???µ?
in Greek or as xn--hxajbheg2az3al.xn--jxalpdlp
?).
In the latter case—where you are handling IDNs through the punycode—the old RFC 1123 rules apply:
U+0041 through U+005A (A-Z), U+0061 through U+007A (a-z) case folded as each other, U+0030 through U+0039 (0-9) and U+002D (-).
and U+002E (.) of course; the rules for labels allow the others, with dots between labels.
If you are seeing it in IDN form, the allowed characters are much varied, see http://unicode.org/reports/tr36/idn-chars.html for a handy chart of all valid characters.
Chances are your network code will deal with the punycode, but your display code (or even just passing strings to and from other layers) with the more human-readable form as nobody running a server on the ????????. domain wants to see their server listed as being on .xn--mgberp4a5d4ar
.
Try this "one-liner" from Delta's Blog, String To MemoryStream (C#).
MemoryStream stringInMemoryStream =
new MemoryStream(ASCIIEncoding.Default.GetBytes("Your string here"));
The string will be loaded into the MemoryStream
, and you can read from it. See Encoding.GetBytes(...), which has also been implemented for a few other encodings.
Try this one IntentChooser. Just add some lines of code, I did the rest for you.
private void startImageChooserActivity() {
Intent intent = ImageChooserMaker.newChooser(MainActivity.this)
.add(new ImageChooser(true))
.create("Select Image");
startActivityForResult(intent, REQUEST_IMAGE_CHOOSER);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CHOOSER && resultCode == RESULT_OK) {
List<Uri> imageUris = ImageChooserMaker.getPickMultipleImageResultUris(this, data);
}
}
PS: as mentioned at the answers above, EXTRA_ALLOW_MULTIPLE is only available for API >= 18. And some gallery apps don't make this feature available (Google Photos and Documents (com.android.documentsui
) work.
I don't use commands. You should be able to do this using the GUI:
Visual Studio\Projects\{your project}
folder. Select OK.Unfortunately, no. Not with HTML and CSS. You need an a
element to make a link, and you can't wrap an entire table row in one.
The closest you can get is linking every table cell. Personally I'd just link one cell and use JavaScript to make the rest clickable. It's good to have at least one cell that really looks like a link, underlined and all, for clarity anyways.
Here's a simple jQuery snippet to make all table rows with links clickable (it looks for the first link and "clicks" it)
$("table").on("click", "tr", function(e) {
if ($(e.target).is("a,input")) // anything else you don't want to trigger the click
return;
location.href = $(this).find("a").attr("href");
});
The reason for the exception is that and
implicitly calls bool
. First on the left operand and (if the left operand is True
) then on the right operand. So x and y
is equivalent to bool(x) and bool(y)
.
However the bool
on a numpy.ndarray
(if it contains more than one element) will throw the exception you have seen:
>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The bool()
call is implicit in and
, but also in if
, while
, or
, so any of the following examples will also fail:
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
There are more functions and statements in Python that hide bool
calls, for example 2 < x < 10
is just another way of writing 2 < x and x < 10
. And the and
will call bool
: bool(2 < x) and bool(x < 10)
.
The element-wise equivalent for and
would be the np.logical_and
function, similarly you could use np.logical_or
as equivalent for or
.
For boolean arrays - and comparisons like <
, <=
, ==
, !=
, >=
and >
on NumPy arrays return boolean NumPy arrays - you can also use the element-wise bitwise functions (and operators): np.bitwise_and
(&
operator)
>>> np.logical_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> np.bitwise_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> (arr > 1) & (arr < 3)
array([False, True, False], dtype=bool)
and bitwise_or
(|
operator):
>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> (arr <= 1) | (arr >= 3)
array([ True, False, True], dtype=bool)
A complete list of logical and binary functions can be found in the NumPy documentation:
Try:
git submodule init
git submodule update
if variable is defined and you want to check if it has value you can just a or b
def test(myvar=None):
# shorter than: print myvar if myvar else "no Input"
print myvar or "no Input"
test()
test([])
test(False)
test('hello')
test(['Hello'])
test(True)
will output
no Input
no Input
no Input
hello
['Hello']
True
I use this way:
String[] array={
"man","for","think"
}; int j;
then below the onCreate
TextView t = findViewById(R.id.textView);
new CountDownTimer(5000,1000) {
@Override
public void onTick(long millisUntilFinished) {}
@Override
public void onFinish() {
t.setText("I "+array[j] +" You");
j++;
if(j== array.length-1) j=0;
start();
}
}.start();
it's easy way to solve this problem.
This method work when you are using a class: In this example you will receive a array, so the only method that worked for me was these one:
template <typename T, size_t n, size_t m>
Matrix& operator= (T (&a)[n][m])
{
int arows = n;
int acols = m;
p = new double*[arows];
for (register int r = 0; r < arows; r++)
{
p[r] = new double[acols];
for (register int c = 0; c < acols; c++)
{
p[r][c] = a[r][c]; //A[rows][columns]
}
}
https://www.geeksforgeeks.org/how-to-print-size-of-an-array-in-a-function-in-c/
I solved this problem through the following:
string userId="";
for example: in C#
userId= "5,44,72,81,126";
and Send to SQL-Server
SqlParameter param = cmd.Parameters.AddWithValue("@user_id_list",userId);
NVARCHAR(Max)
) to Table.CREATE FUNCTION dbo.SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.') ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y WHERE Item IS NOT NULL );
SELECT user_id = Item FROM dbo.SplitInts(@user_id_list, ',');
From the jQuery.each() documentation:
.each( function(index, Element) )
function(index, Element)A function to execute for each matched element.
So you'll want to use:
$('#list option').each(function(i,e){
//do stuff
});
...where index will be the index and element will be the option element in list
Swift 5.0, with generics:
func hideViewWithAnimation<T: UIView>(shouldHidden: Bool, objView: T) {
if shouldHidden == true {
UIView.animate(withDuration: 0.3, animations: {
objView.alpha = 0
}) { (finished) in
objView.isHidden = shouldHidden
}
} else {
objView.alpha = 0
objView.isHidden = shouldHidden
UIView.animate(withDuration: 0.3) {
objView.alpha = 1
}
}
}
Use:
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountLabelBGView)
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountLabel)
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountButton)
Here itemCountLabelBGView
is a UIView
, itemCountLabel
is a UILabel
& itemCountButton
is a UIButton
, So it will work for every view object whose parent class is UIView
.
From the manual:
require()
is identical toinclude()
except upon failure it will also produce a fatalE_COMPILE_ERROR
level error. In other words, it will halt the script whereasinclude()
only emits a warning (E_WARNING
) which allows the script to continue.
The same is true for the _once()
variants.
Best and Simple solution to follow:
Select the range of the columns you want to be copied to single column
Copy the range of cells (multiple columns)
Open Notepad++
Paste the selected range of cells
Press Ctrl+H, replace \t by \n and click on replace all
all the multiple columns fall under one single column
now copy the same and paste in excel
Simple and effective solution for those who dont want to waste time coding in VBA
Don't match an email with a regex. It's extremely ugly and long and complicated and your regex parser probably can't handle it anyway. Try to find a library routine for matching them. If you only want to solve the practical problem of matching an email address (that is, if you want wrong code that happens to (usually) work), use the regular-expressions.info link someone else submitted.
As for the empty string, ^$
is mentioned by multiple people and will work fine.
I'm not sure there's a way to hide that information. No matter what you do to obfuscate or hide whatever you're doing in JavaScript, it still comes down to the fact that your browser needs to load it in order to use it. Modern browsers have web debugging/analysis tools out of the box that make extracting and viewing scripts trivial (just hit F12 in Chrome, for example).
If you're worried about exposing some kind of trade secret or algorithm, then your only recourse is to encapsulate that logic in a web service call and have your page invoke that functionality via AJAX.
As of Android P, the support libraries have been moved to AndroidX
Please do a refactor for your libs from this page.
https://developer.android.com/topic/libraries/support-library/refactor
If you don't mind hardcoding it you can do this ~> android:background="#eeeeee" and drop any hex color # you wish.
Looks like this....
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:text="@string/ClickMe"
android:background="#fff"/>
Please note: for Bootstrap 4+ users, please consider Christophe's solution (Bootstrap 4 introduced flexbox, which provides for a more elegant CSS-only solution). The following will work for earlier versions of Bootstrap...
See http://jsfiddle.net/jhfrench/bAHfj/ for a working solution.
//for each element that is classed as 'pull-down', set its margin-top to the difference between its own height and the height of its parent
$('.pull-down').each(function() {
var $this = $(this);
$this.css('margin-top', $this.parent().height() - $this.height())
});
On the plus side:
pull-down
.Now the bad news:
If I had to guess, I'd say you installed the PPA 7.1.8 as CLI only (php7-cli). You're getting your version info from that, but your libapache2-mod-php package is still 14.04 main which is 5.6. Check your phpinfo in your browser to confirm the version. You might also consider migrating to Ubuntu 16.04 to get PHP 7.0 in main.
For a hybrid dictionary, I use this:
List<string> keys = new List<string>(dictionary.Count);
keys.AddRange(dictionary.Keys.Cast<string>());
You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:
-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
k NUMBER:= 0;
BEGIN
FOR i IN 1..10 LOOP
k:= k+1;
dbms_output.put_line(i||' '||k);
END LOOP;
END;
/
-- Cursor FOR loop --
set serveroutput on
DECLARE
CURSOR c1 IS SELECT * FROM scott.emp;
i NUMBER:= 0;
BEGIN
FOR e_rec IN c1 LOOP
i:= i+1;
dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
END LOOP;
END;
/
-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
FROM dual
CONNECT BY LEVEL <= 10
/
simply run
virtualenv -p python3 envname
Update after OP's edit:
There was a bug in the OP's version of virtualenv, as described here. The problem was fixed by running:
pip install --upgrade virtualenv
This is microsoft's page on the location
tag: http://msdn.microsoft.com/en-us/library/b6x6shw7%28v=vs.100%29.aspx
It may be helpful to some folks.
After my previous answer was deleted for failing to include the code, on the basis the Ansi characters used can not be displayed by stack overflow rendering the presence of the code somewhat pointless given it was based on them, I have redesigned the code to include the method of populating the Escape character detailed by @Sam Hasler
In the process, I've also taken out all the subroutines in favor of macro's, and adapted my approach to passing parameters to the macro's.
All macro's balance the Setlocal / Endlocal pairings to prevent exceeding recursion level's through use of ^&^& endlocal
after completeing their handling of the Args.
The std.out macro also demonstrates how to adapt the macros to store output into variables that survive past the Endlocal barrier.
@Echo off & Mode 1000
::: / Creates two variables with one character DEL=Ascii-08 and /AE=Ascii-27 escape code. only /AE is used
::: - http://www.dostips.com/forum/viewtopic.php?t=1733
::: - https://stackoverflow.com/a/34923514/12343998
:::
::: - DEL and ESC can be used with and without DelayedExpansion, except during Macro Definition
Setlocal
For /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
Endlocal
Set "DEL=%%a"
Set "/AE=%%b"
)
::: \
::: / Establish Environment for macro Definition
Setlocal DisableDelayedExpansion
(Set LF=^
%= NewLine =%)
Set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
::: \
::: / Ascii code variable assignment
::: - Variables used for cursor Positiong Ascii codes in the form of bookends to prevent ansi escape code disrupting macro definition
Set "[=%/AE%["
Set "]=H"
::: - define Variables for Ascii color code values
Set "Red=%/AE%[31m"
Set "Green=%/AE%[32m"
Set "Yellow=%/AE%[33m"
Set "Blue=%/AE%[34m"
Set "Purple=%/AE%[35m"
Set "Cyan=%/AE%[36m"
Set "White=%/AE%[37m"
Set "Grey=%/AE%[90m"
Set "Pink=%/AE%[91m"
Set "BrightGreen=%/AE%[92m"
Set "Beige=%/AE%[93m"
Set "Aqua=%/AE%[94m"
Set "Magenta=%/AE%[95m"
Set "Teal=%/AE%[96m"
Set "BrightWhite=%/AE%[97m"
Set "Off=%/AE%[0m"
::: \
::: / mini-Macro to Pseudo pipe complex strings into Macros.
Set "Param|=Set Arg-Output="
::: \
::: / Macro for outputing to cursor position Arg1 in color Arg2
Set Pos.Color=^&for /L %%n in (1 1 2) do if %%n==2 (%\n%
For /F "tokens=1,2 delims=, " %%G in ("!argv!") do (%\n%
Echo(![!%%G!]!!%%H!!Arg-Output!!Off!^&^&Endlocal%\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
::: \
::: / Macro variable for creating a Colored prompt with pause at Cursor pos Arg1 in Color Arg2
Set Prompt.Pause=^&for /L %%n in (1 1 2) do if %%n==2 (%\n%
For /F "tokens=1,2 delims=, " %%G in ("!argv!") do (%\n%
Echo.!/AE![%%G!]!!/AE![%%Hm!Arg-Output!!Off!%\n%
pause^>nul ^&^& Endlocal%\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
::: \
::: / Macro variable for outputing to stdout on a new line with selected color Arg1 and store output to VarName Arg2
Set std.out=^&for /L %%n in (1 1 2) do if %%n==2 (%\n%
For /F "tokens=1,2 delims=, " %%G in ("!argv!") do (%\n%
Echo.!/AE![%%Gm!Arg-Output!!Off!^&^& Endlocal ^&(Set %%H=!Arg-Output!)%\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
::: \
::: / Stringlength Macro. Not utilized in this example.
::: Usage: %Param|%string or expanded variable%get.strLen% ResultVar
Set get.strLen=^&for /L %%n in (1 1 2) do if %%n==2 (%\n%
For /F "tokens=1,* delims=, " %%G in ("!argv!") do (%\n%
Set tmpLen=!Arg-Output!%\n%
Set LenTrim=Start%\n%
For /L %%a in (1,1,250) Do (%\n%
IF NOT "!LenTrim!"=="" (%\n%
Set LenTrim=!tmpLen:~0,-%%a!%\n%
If "!LenTrim!"=="" Echo.>nul ^&^& Endlocal ^&(Set %%G=%%a)%\n%
)%\n%
) %\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
::: \
::: / Create Script break for Subroutines. Subroutines not utilized in this example
Goto :main
::: \
::: / Subroutines
::: \
::: / Script main Body
:::::: - Example usage
:main
Setlocal EnableDelayedExpansion
For %%A in ("31,1,37" "41,1,47" "90,1,97" "100,1,107") do For /L %%B in (%%~A) Do %Param|%[Color Code = %%B.]%std.out% %%B AssignVar
Set "XP=20"
For %%A in (red aqua white brightwhite brightgreen beige blue magenta green pink cyan grey yellow purple teal) do (
Set /A XP+=1
Set /A YP+=1
Set "output=%%A !YP!;!XP!"
%Param|%Cursor Pos: !YP!;!XP!, %%A %Pos.Color% !YP!;!XP! %%A
)
%Param|%Example %green%Complete.%prompt.pause% 32;10 31
Endlocal
Exit /B
::: \ End Script
My thanks to @Martijn Pieters for deleting my previous answer. In rewriting my code I also discovered for myself some new ways to manipulate macro's.
The reason is that in your second example i
is the word itself, not the index of the word. So
for w1 in words:
if w1[0] == w1[len(w1) - 1]:
c += 1
print c
would the equivalent of your code.
I looked at several of the options. Here are my two favorites, because I needed to round the value.
,DataSizeKB = replace(convert(varchar,Cast(Round(SUM(BigNbr / 0.128),0)as money),1), '.00','')
,DataSizeKB2 = format(Round(SUM(BigNbr / 0.128),0),'##,##0')
-----------------
--- below if the full script where I left DataSizeKB in both methods -----------
--- enjoy ---------
--- Hank Freeman : [email protected]
-----------------------------------
--- Scritp to get rowcounts and Memory size of index and Primary Keys
SELECT
FileGroupName = DS.name
,FileGroupType =
CASE DS.[type]
WHEN 'FG' THEN 'Filegroup'
WHEN 'FD' THEN 'Filestream'
WHEN 'FX' THEN 'Memory-optimized'
WHEN 'PS' THEN 'Partition Scheme'
ELSE 'Unknown'
END
,SchemaName = SCH.name
,TableName = OBJ.name
,IndexType =
CASE IDX.[type]
WHEN 0 THEN 'Heap'
WHEN 1 THEN 'Clustered'
WHEN 2 THEN 'Nonclustered'
WHEN 3 THEN 'XML'
WHEN 4 THEN 'Spatial'
WHEN 5 THEN 'Clustered columnstore'
WHEN 6 THEN 'Nonclustered columnstore'
WHEN 7 THEN 'Nonclustered hash'
END
,IndexName = IDX.name
,RowCounts = replace(convert(varchar,Cast(p.rows as money),1), '.00','') --- MUST show for all types when no Primary key
--,( Case WHEN IDX.[type] IN (2,6,7) then 0 else p.rows end )as Rowcounts_T
,AllocationDesc = AU.type_desc
/*
,RowCounts = p.rows --- MUST show for all types when no Primary key
,TotalSizeKB2 = Cast(Round(SUM(AU.total_pages / 0.128),0)as int) -- 128 pages per megabyte
,UsedSizeKB = Cast(Round(SUM(AU.used_pages / 0.128),0)as int)
,DataSizeKB = Cast(Round(SUM(AU.data_pages / 0.128),0)as int)
--replace(convert(varchar,cast(1234567 as money),1), '.00','')
*/
,TotalSizeKB = replace(convert(varchar,Cast(Round(SUM(AU.total_pages / 0.128),0)as money),1), '.00','') -- 128 pages per megabyte
,UsedSizeKB = replace(convert(varchar,Cast(Round(SUM(AU.used_pages / 0.128),0)as money),1), '.00','')
,DataSizeKB = replace(convert(varchar,Cast(Round(SUM(AU.data_pages / 0.128),0)as money),1), '.00','')
,DataSizeKB2 = format(Round(SUM(AU.data_pages / 0.128),0),'##,##0')
,DataSizeKB3 = format(SUM(AU.data_pages / 0.128),'##,##0')
--SELECT Format(1234567.8, '##,##0.00')
---
,is_default = CONVERT(INT,DS.is_default)
,is_read_only = CONVERT(INT,DS.is_read_only)
FROM
sys.filegroups DS -- you could also use sys.data_spaces
LEFT JOIN sys.allocation_units AU ON DS.data_space_id = AU.data_space_id
LEFT JOIN sys.partitions PA
ON (AU.[type] IN (1,3) AND
AU.container_id = PA.hobt_id) OR
(AU.[type] = 2 AND
AU.container_id = PA.[partition_id])
LEFT JOIN sys.objects OBJ ON PA.[object_id] = OBJ.[object_id]
LEFT JOIN sys.schemas SCH ON OBJ.[schema_id] = SCH.[schema_id]
LEFT JOIN sys.indexes IDX
ON PA.[object_id] = IDX.[object_id] AND
PA.index_id = IDX.index_id
-----
INNER JOIN
sys.partitions p ON obj.object_id = p.OBJECT_ID AND IDX.index_id = p.index_id
WHERE
OBJ.type_desc = 'USER_TABLE' -- only include user tables
OR
DS.[type] = 'FD' -- or the filestream filegroup
GROUP BY
DS.name ,SCH.name ,OBJ.name ,IDX.[type] ,IDX.name ,DS.[type] ,DS.is_default ,DS.is_read_only -- discard different allocation units
,p.rows ,AU.type_desc ---
ORDER BY
DS.name ,SCH.name ,OBJ.name ,IDX.name
---
;
//javascript
//teams.Table does not exist
function OnSuccessJSON(data, status) {
var teams = eval('(' + data.d + ')');
var listItems = "";
for (var i = 0; i < teams.length; i++) {
listItems += "<option value='" + teams[i][0]+ "'>" + teams[i][1] + "</option>";
}
$("#<%=ddlTeams.ClientID%>").html(listItems);
}
Install ASP.NET Core module
Download the installer using the following link: https://www.microsoft.com/net/permalink/dotnetcore-current-windows-runtime-bundle-installer
The top answer, by jondavidjohn is good but I'd like to tweak it to address a couple of points:
http
to a page on https
.jquery.com
's protocol to https
results in a warning if you try it straight from the browser's URL bar: This is probably not the site you are looking for!
My only issue is that I have to include a version number where in the console I really always want the latest.
var jq = document.createElement('script');
jq.src = "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
jQuery.noConflict();
The reason why your full-width-div doesn't stretch 100% to your screen it's because of its parent "container" which occupies only about 80% of the screen.
If you want to make it stretch 100% to the screen either you make the "full-width-div" position fixed or use the "container-fluid" class instead of "container".
see Bootstrap 3 docs: http://getbootstrap.com/css/#grid
datetime.replace() will provide the best options. Also, it provides facility for replacing day, year, and month.
Suppose we have a datetime
object and date is represented as:
"2017-05-04"
>>> from datetime import datetime
>>> date = datetime.strptime('2017-05-04',"%Y-%m-%d")
>>> print(date)
2017-05-04 00:00:00
>>> date = date.replace(minute=59, hour=23, second=59, year=2018, month=6, day=1)
>>> print(date)
2018-06-01 23:59:59
You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a style
attribute. Apparently, it has to be one using the !important
specifier, which generally indicates poor logic and structure in styling.
Primarily, modify the style.css file so that it does not use !important
. Failing this, add !important
to the rule in style
attribute. But you should aim at reducing the use of !important
, not increasing it.
You could just use list comprehension:
property_asel = [val for is_good, val in zip(good_objects, property_a) if is_good]
or
property_asel = [property_a[i] for i in good_indices]
The latter one is faster because there are fewer good_indices
than the length of property_a
, assuming good_indices
are precomputed instead of generated on-the-fly.
Edit: The first option is equivalent to itertools.compress
available since Python 2.7/3.1. See @Gary Kerr's answer.
property_asel = list(itertools.compress(property_a, good_objects))
As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView
.
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"
I had this same issue.
The solution for me was found in the Microsoft KB Article 2452723:
Basically, edit your scheduled task and take the Quotes out of the Start In field:
To get the relevant error message:
1) Convert 2147942667 to hex: 8007010B
2) Take last 4 digits (010B) and convert to decimal: 267
3) Run: net helpmsg 267
4) Result: "The directory name is invalid."
Had to look it up in the specs:
Class's getResource() - documentation states the difference:
This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.
I would solve it by doing:
private void button1_Click(object sender, EventArgs e)
{
Form2 m = new Form2();
m.Show();
Form1 f = new Form1();
this.Visible = false;
this.Hide();
}
▲
is the Unicode black up-pointing triangle (?) while ▼
is the black down-pointing triangle (?).
You can just plug the characters (copied from the web) into this site for a lookup.
sort()
. This will give a new array with numeric keys starting from 0
.asort()
.See also the comparison table of sorting functions in PHP.
You can think of a MySQL "database" as a schema/user in Oracle. If you have the privileges, you can query the DBA_USERS
view to see the list of schemas:
SELECT * FROM DBA_USERS;
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
Are you searching for this:
int c = some_ascii_character;
Or just converting without assignment:
(int)some_aschii_character;
Another way to get non-blocking keyboard input is to open the device file and read it!
You have to know the device file you are looking for, one of /dev/input/event*. You can run cat /proc/bus/input/devices to find the device you want.
This code works for me (run as an administrator).
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
int main(int argc, char** argv)
{
int fd, bytes;
struct input_event data;
const char *pDevice = "/dev/input/event2";
// Open Keyboard
fd = open(pDevice, O_RDONLY | O_NONBLOCK);
if(fd == -1)
{
printf("ERROR Opening %s\n", pDevice);
return -1;
}
while(1)
{
// Read Keyboard Data
bytes = read(fd, &data, sizeof(data));
if(bytes > 0)
{
printf("Keypress value=%x, type=%x, code=%x\n", data.value, data.type, data.code);
}
else
{
// Nothing read
sleep(1);
}
}
return 0;
}
use
sudo find / -name file.txt
It's stupid (because you elevate the search) and nonsecure, but far shorter to write.
The JavaScript Object()
constructor makes an Object that you can assign members to.
myObj = new Object()
myObj.key = value;
myObj[key2] = value2; // Alternative
One difference to keep in mind, though.
Let's say you want to build some URL using the current URL. The following code will in fact redirect you, because it's not calling String.replace
but Location.replace
:
nextUrl = window.location.replace('/step1', '/step2');
The following codes work:
// cast to string
nextUrl = (window.location+'').replace('/step1', '/step2');
// href property
nextUrl = window.location.href.replace('/step1', '/step2');
I did this for a <div>
on Chrome.
element.scrollTop - is the pixels hidden in top due to the scroll. With no scroll its value is 0.
element.scrollHeight - is the pixels of the whole div.
element.clientHeight - is the pixels that you see in your browser.
var a = element.scrollTop;
will be the position.
var b = element.scrollHeight - element.clientHeight;
will be the maximum value for scrollTop.
var c = a / b;
will be the percent of scroll [from 0 to 1].
If you are adding options to the dropdown one by one without a dataset and you want to sort it later after adding items, here's a solution:
DataTable dtOptions = new DataTable();
DataColumn[] dcColumns = { new DataColumn("Text", Type.GetType("System.String")),
new DataColumn("Value", Type.GetType("System.String"))};
dtOptions.Columns.AddRange(dcColumns);
foreach (ListItem li in ddlOperation.Items)
{
DataRow dr = dtOptions.NewRow();
dr["Text"] = li.Text;
dr["Value"] = li.Value;
dtOptions.Rows.Add(dr);
}
DataView dv = dtOptions.DefaultView;
dv.Sort = "Text";
ddlOperation.Items.Clear();
ddlOperation.DataSource = dv;
ddlOperation.DataTextField = "Text";
ddlOperation.DataValueField = "Value";
ddlOperation.DataBind();
This would sort the dropdown items in alphabetical order.
<p>
<img style="float: right; margin: 0px 15px 15px 0px;" src="files/styles/large_hero_desktop_1x/public/headers/Kids%20on%20iPad%20 %202400x880.jpg?itok=PFa-MXyQ" width="100" />
Nunc pulvinar lacus id purus ultrices id sagittis neque convallis. Nunc vel libero orci.
<br style="clear: both;" />
</p>
You should checkout Junit-ext
project. They have RunIf
annotation that performs conditional tests, like:
@Test
@RunIf(DatabaseIsConnected.class)
public void calculateTotalSalary() {
//your code there
}
class DatabaseIsConnected implements Checker {
public boolean satisify() {
return Database.connect() != null;
}
}
[Code sample taken from their tutorial]
Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:
char (*orderedIds)[ID_LEN+1]
= malloc(variableNumberOfElements * sizeof(*orderedIds));
// Clear-up
free(orderedIds);
A more cumbersome, but more general, solution, is to assign an array of pointers, and psuedo-initialising them to point at elements of a raw backing array:
char *raw = malloc(variableNumberOfElements * (ID_LEN + 1));
char **orderedIds = malloc(sizeof(*orderedIds) * variableNumberOfElements);
// Set each pointer to the start of its corresponding section of the raw buffer.
for (i = 0; i < variableNumberOfElements; i++)
{
orderedIds[i] = &raw[i * (ID_LEN+1)];
}
...
// Clear-up pointer array
free(orderedIds);
// Clear-up raw array
free(raw);
As I understand your question, you want to write some function y = interpolate(x_values, y_values, x)
, which will give you the y
value at some x
? The basic idea then follows these steps:
x_values
which define an interval containing x
. For instance, for x=3
with your example lists, the containing interval would be [x1,x2]=[2.5,3.4]
, and the indices would be i1=1
, i2=2
(y_values[i2]-y_values[i1])/(x_values[i2]-x_values[i1])
(ie dy/dx
).x
is now the value at x1
plus the slope multiplied by the distance from x1
.You will additionally need to decide what happens if x
is outside the interval of x_values
, either it's an error, or you could interpolate "backwards", assuming the slope is the same as the first/last interval.
Did this help, or did you need more specific advice?
IndexError: invalid index to scalar variable
happens when you try to index a numpy
scalar such as numpy.int64
or numpy.float64
. It is very similar to TypeError: 'int' object has no attribute '__getitem__'
when you try to index an int
.
>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'
Maybe you can filter rows by possible columns like this :
DataRow[] filteredRows =
datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
enter the below command to verify if zookeeper is running :
echo "ruok" | nc localhost 2181 ; echo
expected response: imok
Aside from the obvious licensing difference, the major difference between OpenJDK and OracleJDK 11 are stability and performance updates.
Source: https://www.youtube.com/watch?v=Adv9--6IcQI&t=385
Every 6 months the two codebases will be in-sync. But during the 6 month window OpenJDK will only receive security updates while OracleJDK will receive additional stability and performance updates.
Given that update releases only occur every 3 months for both OpenJDK and OracleJDK this means that you are missing out on (at most) 3 months worth of fixes until the next major release comes out and you upgrade. However, if you choose to stick to LTS releases then a commercial license begins to make more sense.
maybe you benefit from converting it to JSON string
String jsonString = new com.google.gson.Gson().toJson(myObject);
in my case, I wanted to add an object to the response headers but you cant add objects to the headers,
so to solve this I convert my object to JSON string and in the client side I will return that string to JSON again
Make sure you die()
after your redirection, and make sure you do your redirect AS SOON AS POSSIBLE while your script executes. It makes sure that no more database queries (if some) are not wasted for nothing. That's the one tip I can give you
For search engines, 301 is the best response code
It's document.getElementById()
and not document.getElementByID()
. Check the casing for Id
.
Either return;
from the method early, or throw
an exception.
There is no other way to prevent further code from being executed short of exiting the process completely.
This method does the trick.
boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
Example of usage:
class Main {
static boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
public static void main(String[] a) {
char[] charArray = new char[] {'h','e','l','l','o'};
if (!contains('q', charArray)) {
// Do something...
System.out.println("Hello world!");
}
}
}
Alternative way:
if (!String.valueOf(charArray).contains("q")) {
// do something...
}
.bak
is a backup file generated in SQL Server.
Backup files importing means restoring a database, you can restore on a database created in SQL Server 2012 but the backup file should be from SQL Server 2005, 2008, 2008 R2, 2012 database.
You restore database by using following command...
RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH Recovery
You want to learn about how to restore .bak
file follow the below link:
http://msdn.microsoft.com/en-us/library/ms186858(v=sql.90).aspx
public static boolean isNumeric(String string) {
if (string == null || string.isEmpty()) {
return false;
}
int i = 0;
int stringLength = string.length();
if (string.charAt(0) == '-') {
if (stringLength > 1) {
i++;
} else {
return false;
}
}
if (!Character.isDigit(string.charAt(i))
|| !Character.isDigit(string.charAt(stringLength - 1))) {
return false;
}
i++;
stringLength--;
if (i >= stringLength) {
return true;
}
for (; i < stringLength; i++) {
if (!Character.isDigit(string.charAt(i))
&& string.charAt(i) != '.') {
return false;
}
}
return true;
}
It hides the intention of the code.
It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.
Some use it as a faster alternative to Math.floor
, but the speed difference is not that dramatic, and in most cases it's just micro optimisation. Unless you have a piece of code that really needs to be optimised, you should use code that descibes what it does instead of code that uses a side effect of a non-operation.
With optimisation of the JavaScript engine in browsers, the performance for operators and functions change. With current browsers, using ~~
instead of Math.floor
is somewhat faster in some browsers, and not faster at all in some browsers. If you really need that extra bit of performance, you would need to write different optimised code for each browser.
See: tilde vs floor
Here is a list of python packages that implement Trie:
There are so many Answers. My solution for this was:
globalNamespace.globalArray = new Array();
if (typeof console === "undefined" || typeof console.log === "undefined") {
console = {};
console.log = function(message) {globalNamespace.globalArray.push(message)};
}
In short, if console.log doesn't exists (or in this case, isn't opened) then store the log in a global namespace Array. This way, you're not pestered with millions of alerts and you can still view your logs with the developer console opened or closed.
To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.
A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.
I prefer to use <script>console.log({$varname|@json_encode})</script>
to log to the console.
If you want to retrieve POST data:
first_name = request.form.get("firstname")
If you want to retrieve GET (query string) data:
first_name = request.args.get("firstname")
Or if you don't care/know whether the value is in the query string or in the post data:
first_name = request.values.get("firstname")
request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.
I'm expanding upon a comment that I posted here as most people won't notice the comment.
https://lifeboat.com/programs/console.exe is a compiled version of the Visual Basic program described at https://stackoverflow.com/a/4694566/1752929. My version simply sets the buffer height to 32766 which is the maximum buffer height available. It does not adjust anything else. If there is a lot of demand, I could create a more flexible program but generally you can just set other variables in your shortcut layout tab.
Following is the target I use in my shortcut where I wish to start in the f directory. (I have to set the directory this way as Windows won't let you set it any other way if you wish to run the command prompt as administrator.)
C:\Windows\System32\cmd.exe /k "console & cd /d c:\f"
I faced similar issue with Spring MVC application. I used < mvc:resources >
tag to resolve this issue.
Please find the following link having more details.
http://www.mkyong.com/spring-mvc/spring-mvc-how-to-include-js-or-css-files-in-a-jsp-page/
Make two interfaces IA
and IB
:
public interface IA
{
public void methodA(int value);
}
public interface IB
{
public void methodB(int value);
}
Next make A
implement IA
and B
implement IB
.
public class A : IA
{
public int fooA { get; set; }
public void methodA(int value) { fooA = value; }
}
public class B : IB
{
public int fooB { get; set; }
public void methodB(int value) { fooB = value; }
}
Then implement your C class as follows:
public class C : IA, IB
{
private A _a;
private B _b;
public C(A _a, B _b)
{
this._a = _a;
this._b = _b;
}
public void methodA(int value) { _a.methodA(value); }
public void methodB(int value) { _b.methodB(value); }
}
Generally this is a poor design overall because you can have both A
and B
implement a method with the same name and variable types such as foo(int bar)
and you will need to decide how to implement it, or if you just call foo(bar)
on both _a
and _b
. As suggested elsewhere you should consider a .A
and .B
properties instead of combining the two classes.
I wrote this function to solve this problem:
// this is for adding the ordinal suffix, turning 1, 2 and 3 into 1st, 2nd and 3rd
Number.prototype.addSuffix=function(){
var n=this.toString().split('.')[0];
var lastDigits=n.substring(n.length-2);
//add exception just for 11, 12 and 13
if(lastDigits==='11' || lastDigits==='12' || lastDigits==='13'){
return this+'th';
}
switch(n.substring(n.length-1)){
case '1': return this+'st';
case '2': return this+'nd';
case '3': return this+'rd';
default : return this+'th';
}
};
With this you can just put .addSuffix()
to any number and it will result in what you want. For example:
var number=1234;
console.log(number.addSuffix());
// console will show: 1234th
Query params are used like this:
use Illuminate\Http\Request;
class MyController extends BaseController{
public function index(Request $request){
$param = $request->query('param');
}
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
You can use gson.jar to store class objects into SharedPreferences. You can download this jar from google-gson
Or add the GSON dependency in your Gradle file:
implementation 'com.google.code.gson:gson:2.8.5'
Creating a shared preference:
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
To save:
MyObject myObject = new MyObject;
//set variables of 'myObject', etc.
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
To retrieve:
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
You can find your Firebase Web API Key in the follwing way .
Go To project overview -> general -> web API key
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
ul {
list-style-type: none;
}
ul li:before {
content:'*'; /* Change this to unicode as needed*/
width: 1em !important;
margin-left: -1em;
display: inline-block;
}
I decided I didn't want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing. Therefore, I did this:
score = [1,2,3,4,5]
with open("file.txt", "w") as f:
for s in score:
f.write(str(s) +"\n")
score = []
with open("file.txt", "r") as f:
for line in f:
score.append(int(line.strip()))
So the items in the file are read as integers, despite being stored to the file as strings.
I modified @Vlad_Spays answer so that the back button acts normally unless it's the last item in the stack, then it prompts the user before exiting the app.
@Override
public void onBackPressed(){
if (isTaskRoot()){
if (backButtonCount >= 1){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}else{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}else{
super.onBackPressed();
}
}
env\Scripts\activate worked for me on windows
A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.
If you want to control the width of your data, then you could use the width
sub-specifiers in the printf
format string. Eg. :
printf("%5d", 2);
It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.
If you want complete control, you'll probably have to implement it yourself.
How do I obtain a function pointer for a class member function, and later call that member function with a specific object?
It's easiest to start with a typedef
. For a member function, you add the classname in the type declaration:
typedef void(Dog::*BarkFunction)(void);
Then to invoke the method, you use the ->*
operator:
(pDog->*pBark)();
Also, if possible, I’d like to invoke the constructor via a pointer as well. Is this possible, and if so, what is the preferred way to do this?
I don't believe you can work with constructors like this - ctors and dtors are special. The normal way to achieve that sort of thing would be using a factory method, which is basically just a static function that calls the constructor for you. See the code below for an example.
I have modified your code to do basically what you describe. There's some caveats below.
#include <iostream>
class Animal
{
public:
typedef Animal*(*NewAnimalFunction)(void);
virtual void makeNoise()
{
std::cout << "M00f!" << std::endl;
}
};
class Dog : public Animal
{
public:
typedef void(Dog::*BarkFunction)(void);
typedef Dog*(*NewDogFunction)(void);
Dog () {}
static Dog* newDog()
{
return new Dog;
}
virtual void makeNoise ()
{
std::cout << "Woof!" << std::endl;
}
};
int main(int argc, char* argv[])
{
// Call member function via method pointer
Dog* pDog = new Dog ();
Dog::BarkFunction pBark = &Dog::makeNoise;
(pDog->*pBark)();
// Construct instance via factory method
Dog::NewDogFunction pNew = &Dog::newDog;
Animal* pAnimal = (*pNew)();
pAnimal->makeNoise();
return 0;
}
Now although you can normally use a Dog*
in the place of an Animal*
thanks to the magic of polymorphism, the type of a function pointer does not follow the lookup rules of class hierarchy. So an Animal method pointer is not compatible with a Dog method pointer, in other words you can't assign a Dog* (*)()
to a variable of type Animal* (*)()
.
The static newDog
method is a simple example of a factory, which simply creates and returns new instances. Being a static function, it has a regular typedef
(with no class qualifier).
Having answered the above, I do wonder if there's not a better way of achieving what you need. There's a few specific scenarios where you would do this sort of thing, but you might find there's other patterns that work better for your problem. If you describe in more general terms what you are trying to achieve, the hive-mind may prove even more useful!
Related to the above, you will no doubt find the Boost bind library and other related modules very useful.
Note that git checkout --ours|--theirs
will overwrite the files entirely, by choosing either theirs
or ours
version, which might be or might not be what you want to do (if you have any non-conflicted changes coming from the other side, they will be lost).
If instead you want to perform a three-way merge on the file, and only resolve the conflicted hunks using --ours|--theirs
, while keeping non-conflicted hunks from both sides in place, you may want to resort to git merge-file
; see details in this answer.
In 3 words: inline-block
is better.
Inline Block
The only drawback to the display: inline-block
approach is that in IE7 and below an element can only be displayed inline-block
if it was already inline
by default. What this means is that instead of using a <div>
element you have to use a <span>
element. It's not really a huge drawback at all because semantically a <div>
is for dividing the page while a <span>
is just for covering a span of a page, so there's not a huge semantic difference. A huge benefit of display:inline-block
is that when other developers are maintaining your code at a later point, it is much more obvious what display:inline-block
and text-align:right
is trying to accomplish than a float:left
or float:right
statement. My favorite benefit of the inline-block
approach is that it's easy to use vertical-align: middle
, line-height
and text-align: center
to perfectly center the elements, in a way that is intuitive. I found a great blog post on how to implement cross-browser inline-block, on the Mozilla blog. Here is the browser compatibility.
Float
The reason that using the float
method is not suited for layout of your page is because the float
CSS property was originally intended only to have text wrap around an image (magazine style) and is, by design, not best suited for general page layout purposes. When changing floated elements later, sometimes you will have positioning issues because they are not in the page flow. Another disadvantage is that it generally requires a clearfix otherwise it may break aspects of the page. The clearfix requires adding an element after the floated elements to stop their parent from collapsing around them which crosses the semantic line between separating style from content and is thus an anti-pattern in web development.
Any white space problems mentioned in the link above could easily be fixed with the white-space
CSS property.
SitePoint is a very credible source for web design advice and they seem to have the same opinion that I do:
If you’re new to CSS layouts, you’d be forgiven for thinking that using CSS floats in imaginative ways is the height of skill. If you have consumed as many CSS layout tutorials as you can find, you might suppose that mastering floats is a rite of passage. You’ll be dazzled by the ingenuity, astounded by the complexity, and you’ll gain a sense of achievement when you finally understand how floats work.
Don’t be fooled. You’re being brainwashed.
http://www.sitepoint.com/give-floats-the-flick-in-css-layouts/
2015 Update - Flexbox is a good alternative for modern browsers:
.container {
display: flex; /* or inline-flex */
}
.item {
flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
}
Dec 21, 2016 Update
Bootstrap 4 is removing support for IE9, and thus is getting rid of floats from rows and going full Flexbox.
Just two more things I found helpful to know, even if they are not part of the question, really.
You can use the relayEvents
method to tell a component to listen for certain events of another component and then fire them again as if they originate from the first component. The API docs give the example of a grid relaying the store load
event. It is quite handy when writing custom components that encapsulate several sub-components.
The other way around, i.e. passing on events received by an encapsulating component mycmp
to one of its sub-components subcmp
, can be done like this
mycmp.on('show' function (mycmp, eOpts)
{
mycmp.subcmp.fireEvent('show', mycmp.subcmp, eOpts);
});
Create a wrapper class. Something like this:
public class Date:IEquatable<Date>,IEquatable<DateTime>
{
public Date(DateTime date)
{
value = date.Date;
}
public bool Equals(Date other)
{
return other != null && value.Equals(other.value);
}
public bool Equals(DateTime other)
{
return value.Equals(other);
}
public override string ToString()
{
return value.ToString();
}
public static implicit operator DateTime(Date date)
{
return date.value;
}
public static explicit operator Date(DateTime dateTime)
{
return new Date(dateTime);
}
private DateTime value;
}
And expose whatever of value
you want.
Java does not support Switch-case with String. I guess this link can help you. :)
I found that the following folder structure makes a very insightful context for understanding what runtime
is:
You can see that there is the 'source', there is the 'SDK' or 'Software Development Kit' and then there is the Runtime
, eg. the stuff that gets run - at runtime. It's contents are like:
The win32 zip contains .exe -s and .dll -s.
So eg. the C runtime would be the files like this -- C runtime libraries, .so-s or .dll -s -- you run at runtime, made special by their (or their contents' or purposes') inclusion in the definition of the C language (on 'paper'), then implemented by your C implementation of choice. And then you get the runtime of that implementation, to use it and to build upon it.
That is, with a little polarisation, the runnable files that the users of your new C-based program will need. As a developer of a C-based program, so do you, but you need the C compiler and the C library headers, too; the users don't need those.
This code- (sets currency to GB(Britain/UK/England/£) then prints a line. Then sets currency to US/$ and prints a line)
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB",false);
Console.WriteLine("bbbbbbb {0:c}",4321.2);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US",false);
Console.WriteLine("bbbbbbb {0:c}",4321.2);
Will display-
bbbbbbb £4,321.20
bbbbbbb $4,321.20
For a list of culture names e.g. en-GB en-US e.t.c.
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.80).aspx
there is a better way.
View.performClick();
http://developer.android.com/reference/android/view/View.html#performClick()
this should answer all your problems. every View inherits this function, including Button, Spinner, etc.
Just to clarify, View does not have a static performClick() method. You must call performClick() on an instance of View. For example, you can't just call
View.performClick();
Instead, do something like:
View myView = findViewById(R.id.myview);
myView.performClick();
This solution fixed my problem while replacing br tag to '\n' .
alert(content.replace(/<br\/\>/g,'\n'));
Check the contents of SpringExample/target/classes. Is spring-config.xml there? If not, try manually removing the SpringExample/target/ directory, and force a rebuild with Project=>Clean... in Eclipse.
Here is the solution that worked for me; I did it this way as the content in the carousel was dynamically generated from user-submitted content (so we could not use a static height in the stylesheet) - This solution should also work with different sized screens:
function updateCarouselSizes(){
jQuery(".carousel").each(function(){
// I wanted an absolute minimum of 10 pixels
var maxheight=10;
if(jQuery(this).find('.item,.carousel-item').length) {
// We've found one or more item within the Carousel...
jQuery(this).carousel(); // Initialise the carousel (include options as appropriate)
// Now we iterate through each item within the carousel...
jQuery(this).find('.item,.carousel-item').each(function(k,v){
if(jQuery(this).outerHeight()>maxheight) {
// This item is the tallest we've found so far, so store the result...
maxheight=jQuery(this).outerHeight();
}
});
// Finally we set the carousel's min-height to the value we've found to be the tallest...
jQuery(this).css("min-height",maxheight+"px");
}
});
}
jQuery(function(){
jQuery(window).on("resize",updateCarouselSizes);
updateCarouselSizes();
}
Technically this is not responsive, but for my purposes the on window resize
makes this behave responsively.
I had the same issue using webpack4, i was missing the file .babelrc in the root folder:
{
"presets":["env", "react"],
"plugins": [
"syntax-dynamic-import"
]
}
From package.json :
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.
NSInteger SelectedRow;
SelectedRow = [yourPickerView selectedRowInComponent:0];
selectedPickerString = [YourPickerArray objectAtIndex:SelectedRow];
self.YourTextField.text= selectedPickerString;
// if you want to move pickerview to selected row then
for (int i = 0; I<YourPickerArray.count; i++) {
if ([[YourPickerArray objectAtIndex:i] isEqualToString:self.YourTextField.text]) {
[yourPickerView selectRow:i inComponent:0 animated:NO];
}
}
There are some special types of whitespace in the form of tags. You need to use
$str=strip_tags($str);
to remove redundant tags, error tags, to get to a normal string first.
And use
$str=preg_replace('/\s+/', '', $str);
It's work for me.
<button disabled=true>text here</button>
You can still use an attribute. Just use the 'disabled' attribute instead of 'value'.
In Linux the graphical user interface is not a part of the operating system. The graphical user interface found on most Linux desktops is provided by software called the X Window System, which defines a device independent way of dealing with screens, keyboards and pointer devices.
X Window defines a network protocol for communication, and any program that knows how to "speak" this protocol can use it. There is a C library called Xlib that makes it easier to use this protocol, so Xlib is kind of the native GUI API. Xlib is not the only way to access an X Window server; there is also XCB.
Toolkit libraries such as GTK+ (used by GNOME) and Qt (used by KDE), built on top of Xlib, are used because they are easier to program with. For example they give you a consistent look and feel across applications, make it easier to use drag-and-drop, provide components standard to a modern desktop environment, and so on.
How X draws on the screen internally depends on the implementation. X.org has a device independent part and a device dependent part. The former manages screen resources such as windows, while the latter communicates with the graphics card driver, usually a kernel module. The communication may happen over direct memory access or through system calls to the kernel. The driver translates the commands into a form that the hardware on the card understands.
As of 2013, a new window system called Wayland is starting to become usable, and many distributions have said they will at some point migrate to it, though there is still no clear schedule. This system is based on OpenGL/ES API, which means that in the future OpenGL will be the "native GUI API" in Linux. Work is being done to port GTK+ and QT to Wayland, so that current popular applications and desktop systems would need minimal changes. The applications that cannot be ported will be supported through an X11 server, much like OS X supports X11 apps through Xquartz. The GTK+ port is expected to be finished within a year, while Qt 5 already has complete Wayland support.
To further complicate matters, Ubuntu has announced they are developing a new system called Mir because of problems they perceive with Wayland. This window system is also based on the OpenGL/ES API.
With the following code, you can simulate a click on the 'close' button of the dialog (change the string 'MY_DIALOG' for the name of your own dialog)
$("div[aria-labelledby='ui-dialog-title-MY_DIALOG'] div.ui-helper-clearfix a.ui-dialog-titlebar-close")[0].click();
This error occurs when the client URL and server URL don't match, including the port number. In this case you need to enable your service for CORS which is cross origin resource sharing.
If you are hosting a Spring REST service then you can find it in the blog post CORS support in Spring Framework.
If you are hosting a service using a Node.js server then
npm install cors --save
Add following lines to your server.js
var cors = require('cors')
app.use(cors()) // Use this after the variable declaration
This happens sometimes when I'm trying to open my old projects, what helps me is to change projects target framework. Go to Project -> projectname Properties... and change the Target framework to the one that you have installed.
Since I could not run the C
executable that way, I wrote a simple shell script
that does the following
cd /..path_to_shell_script
./c_executable_name
In the cron jobs list, I call the shell script.
div {
display: flex;
flex-direction: row-reverse;
}
The following also works:
select dump(a,1016), a from (
SELECT REGEXP_REPLACE (
CONVERT (
'3735844533120%$03 ',
'US7ASCII',
'WE8ISO8859P1'),
'[^!@/\.,;:<>#$%&()_=[:alnum:][:blank:]]') a
FROM DUAL);
The solution of Judah Himango and Hans Passant is available in the Designer (I am currently using VS2015):
I had a similar problem, when I wanted to automatically remove temp files I had created. The solution I came up with was not to use command substitution, but rather to pass the name of the variable, that should take the final result, into the function. E.g.
#! /bin/bash
remove_later=""
new_tmp_file() {
file=$(mktemp)
remove_later="$remove_later $file"
eval $1=$file
}
remove_tmp_files() {
rm $remove_later
}
trap remove_tmp_files EXIT
new_tmp_file tmpfile1
new_tmp_file tmpfile2
So, in your case that would be:
#!/bin/bash
e=2
function test1() {
e=4
eval $1="hello"
}
test1 ret
echo "$ret"
echo "$e"
Works and has no restrictions on the "return value".
What about using CSS3 transform
property and use scale
which ill give a zoom like effect, this can be done like so,
HTML
<div class="thumbnail">
<div class="image">
<img src="http://placehold.it/320x240" alt="Some awesome text"/>
</div>
</div>
CSS
.thumbnail {
width: 320px;
height: 240px;
}
.image {
width: 100%;
height: 100%;
}
.image img {
-webkit-transition: all 1s ease; /* Safari and Chrome */
-moz-transition: all 1s ease; /* Firefox */
-ms-transition: all 1s ease; /* IE 9 */
-o-transition: all 1s ease; /* Opera */
transition: all 1s ease;
}
.image:hover img {
-webkit-transform:scale(1.25); /* Safari and Chrome */
-moz-transform:scale(1.25); /* Firefox */
-ms-transform:scale(1.25); /* IE 9 */
-o-transform:scale(1.25); /* Opera */
transform:scale(1.25);
}
Here's a demo fiddle. I removed some of the element to make it simpler, you can always add overflow hidden to the .image
to hide the overflow of the scaled image.
zoom
property only works in IE
I am getting similar errors recently because recent JDKs (and browsers, and the Linux TLS stack, etc.) refuse to communicate with some servers in my customer's corporate network. The reason of this is that some servers in this network still have SHA-1 certificates.
Please see: https://www.entrust.com/understanding-sha-1-vulnerabilities-ssl-longer-secure/ https://blog.qualys.com/ssllabs/2014/09/09/sha1-deprecation-what-you-need-to-know
If this would be your current case (recent JDK vs deprecated certificate encription) then your best move is to update your network to the proper encription technology.
In case that you should provide a temporal solution for that, please see another answers to have an idea about how to make your JDK trust or distrust certain encription algorithms:
How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections
Anyway I insist that, in case that I have guessed properly your problem, this is not a good solution to the problem and that your network admin should consider removing these deprecated certificates and get a new one.
Adding android:keepScreenOn="true"
in the XML of the activity(s) you want to keep the screen on is the best option. Add that line to the main layout of the activity(s).
Something like this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:keepScreenOn="true">
...
</LinearLayout>
Why not just using
<div [ngClass]="classes"> </div>
https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html
A notice about IList:
MSDN IList Remarks:
"IList implementations fall into three categories: read-only, fixed-size, and variable-size. (...). For the generic version of this interface, see
System.Collections.Generic.IList<T>
."
IList<T>
does NOT inherits from IList
(but List<T>
does implement both IList<T>
and IList
), but is always variable-size.
Since .NET 4.5, we have also IReadOnlyList<T>
but AFAIK, there is no fixed-size generic List which would be what you are looking for.
Here is how to do it in the last version of ChartJs:
setInterval(function(){
chart.data.datasets[0].data[5] = 80;
chart.data.labels[5] = "Newly Added";
chart.update();
}
Look at this clear video
or test it in jsfiddle
Try \r\n
where \r
is carriage return. Also ensure that your output do not have new line, because debugger can show you special characters in form of \n
, \r
, \t
etc.