Basically what others have already posted but IMHO a bit cleaner:
$('<iframe/>', {
src: 'https://example.com/',
load: function() {
alert("loaded")
}
}).appendTo('body');
this approach works on firefox, chrome and IE. hope it helps someone:
var comp = document.getElementById('yourCompId');
try { //in firefox
comp.click();
return;
} catch(ex) {}
try { // in chrome
if(document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent( 'click', true, true );
comp.dispatchEvent(e);
return;
}
} catch(ex) {}
try { // in IE
if(document.createEventObject) {
var evObj = document.createEventObject();
comp.fireEvent("onclick", evObj);
return;
}
} catch(ex) {}
If you had added some native C code in your project this answer could be helpful.
I had added some native C code in android project.
Now i was trying to access that code which was returning native string to me, before processing the the string i had set its default value as nullptr. Now upon retrieving its value in java code ran into this issue.
As our native C code is out from java directory so getting no clue of exact line of code which is creating the issue. So i would suggest you to check your .cpp file and try to find any clue there.
Hope so you will get rid of the issue soon. :)
I've just given TouchImageView a new update. It now includes Double Tap Zoom and Fling in addition to Panning and Pinch Zoom. The code below is very dated. You can check out the github project to get the latest code.
Place TouchImageView.java in your project. It can then be used the same as ImageView. Example:
TouchImageView img = (TouchImageView) findViewById(R.id.img);
If you are using TouchImageView in xml, then you must provide the full package name, because it is a custom view. Example:
<com.example.touch.TouchImageView
android:id="@+id/img”
android:layout_width="match_parent"
android:layout_height="match_parent" />
Note: I've removed my prior answer, which included some very old code and now link straight to the most updated code on github.
If you are interested in putting TouchImageView in a ViewPager, refer to this answer.
Check out Google Collections' Multimap
, e.g. page 28 of this presentation.
If you can't use that library for some reason, consider using ConcurrentHashMap
instead of SynchronizedHashMap
; it has a nifty putIfAbsent(K,V)
method with which you can atomically add the element list if it's not already there. Also, consider using CopyOnWriteArrayList
for the map values if your usage patterns warrant doing so.
Bear in mind, I've only experimented with MongoDB...
From what I've read, DynamoDB has come a long way in terms of features. It used to be a super-basic key-value store with extremely limited storage and querying capabilities. It has since grown, now supporting bigger document sizes + JSON support and global secondary indices. The gap between what DynamoDB and MongoDB offers in terms of features grows smaller with every month. The new features of DynamoDB are expanded on here.
Much of the MongoDB vs. DynamoDB comparisons are out of date due to the recent addition of DynamoDB features. However, this post offers some other convincing points to choose DynamoDB, namely that it's simple, low maintenance, and often low cost. Another discussion here of database choices was interesting to read, though slightly old.
My takeaway: if you're doing serious database queries or working in languages not supported by DynamoDB, use MongoDB. Otherwise, stick with DynamoDB.
Really fast comparison, to get count of differences. Using specific column name.
colname = "CreatedDate" # specify column name
index <- match(colname, names(source_df)) # get index name for column name
sel <- source_df[, index] == target_df[, index] # get differences, gives you dataframe with TRUE and FALSE values
table(sel)["FALSE"] # count of differences
table(sel)["TRUE"] # count of matches
For complete dataframe, do not provide column or index name
sel <- source_df[, ] == target_df[, ] # gives you dataframe with TRUE and FALSE values
table(sel)["FALSE"] # count of differences
table(sel)["TRUE"] # count of matches
In case you are working with seaborn plots, instead of Matplotlib, you can save a .png image like this:
Let's suppose you have a matrix
object (either Pandas or NumPy), and you want to take a heatmap:
import seaborn as sb
image = sb.heatmap(matrix) # This gets you the heatmap
image.figure.savefig("C:/Your/Path/ ... /your_image.png") # This saves it
This code is compatible with the latest version of Seaborn. Other code around Stack Overflow worked only for previous versions.
Another way I like is this. I set the size of the next image as follows:
plt.subplots(figsize=(15,15))
And then later I plot the output in the console, from which I can copy-paste it where I want. (Since Seaborn is built on top of Matplotlib, there will not be any problem.)
If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.
In your case, you might do better to have a generic draw()
method, and rely on the subclasses (Rectangle
, Ellipse
) to implement the draw()
method as what you had been thinking of as "drawEllipse" and "drawRectangle".
Try the following:
<a asp-controller="Users" asp-action="Index"></a>
(Valid for ASP.NET 5 and MVC 6)
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
Here is working code:
=QUERY(Sheet1!$A1:$B581, "select B where A = '"&A1&"'")
In this scenario I needed the interval to stay fixed and the reference value to change when I drag it.
You are mixing your business logic with your content. Instead, I'd recommend sending the data to your page and then using something like JQuery to place the data where you need it to go.
This has the advantage of keeping all your HTML in the HTML pages where it belongs so your web designers can modify the HTML later without having to pour through server side code.
Or if you're not wanting to use JavaScript, you could try this:
@str = "Hi"
<b><%= @str ></b>
At least this way your HTML is in the HTML page where it belongs.
Fromthe Javadoc of Method.invoke():
If the underlying method is static, then the specified obj argument is ignored. It may be null.
What happens when you
Class klass = ...; Method m = klass.getDeclaredMethod(methodName, paramtypes); m.invoke(null, args)
it's very simple how to replace with Fragment.
DataFromDb changeActivity = new DataFromDb();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.changeFrg, changeActivity);
transaction.commit();
Move Your log4j.properties file into the src folder. Open Windows explorer, browse to the directory where your project resides in. Browse to bin directory and delete all the folders with in it.
Now in eclipse click project---->clean---->OK
This would force it to build the project again,all the contents delete from bin directory will be recreated.
I took while to figure this out. At times directly clicking clean doesn't work
Several other answer give the solution using MAX. In some scenarios using an agregate function is either not possilbe, or not performant.
The alternative that I use a lot is to use a correlated sub-query in the join...
SELECT
`userName`,
`carPrice`
FROM `users`
LEFT JOIN `cars`
ON cars.id = (
SELECT id FROM `cars` WHERE BelongsToUser = users.id ORDER BY carPrice DESC LIMIT 1
)
WHERE `id`='4'
The <prev>
-tag might be an XML-tag.
Try this so you don't need to worry about where your logs are:
dmesg -T | egrep -i 'killed process'
-T
- readable timestamps
If, else and else if are all constructs to help 'branch' code. Basically, you employ them whenever you want to make a decision.
An example would be 'if it's sunny, I'll go outside. otherwise, I'll stay inside'
In code (ignoring the extra stuff)
if (sunny) {
goOutside();
}
else {
stayInside();
}
You CAN use 'else if' statements if you want to add 'additional' conditions. Extending the previous example, "if it's sunny, I'll go outside. If it's stormy, I'll go into the basement otherwise I'll stay inside"
In code
if (sunny) {
goOutside();
}
else if (stormy) {
goDownstairs();
}
else {
stayInside();
}
EDIT section:
Here is how you can write multiple ifs as and conditions. The following example can be written in at least two ways:
'If it's sunny and warm, go outside. If it's sunny and cold, do nothing'
if (sunny) {
if (warm) {
goOutside();
}
else if (cold) {
doNothing();
}
}
OR
if (sunny && warm) {
goOutside();
}
else if (sunny && cold) {
doNothing();
}
You can get cell value with JS even when click on the cell:
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp
. "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.
The example is working.I've seen.
I guess you mean this:
class Value:
def __init__(self, v=None):
self.v = v
v1 = Value(1)
v2 = Value(2)
d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1
d['b'].v == 2 # True
d['a']
and d['b']
to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict
, list
, set
).d['a']
, d['b']
changes at same time because they both point to same object.I'll add yet another solution to the problem using version 5.6 or later. Don't know if it's more efficient than the already great solutions (probably not), but to me it's just simpler to read:
$myArray = [
"key0" => 0,
"key1" => 1,
"key2" => 2
];
array_combine(
array_keys($myArray),
array_map(
function ($intVal) {
return strval($intVal);
},
$myArray
)
);
Using strval()
as an example function in the array_map
, this will generate:
array(3) {
["key0"]=>
string(1) "0"
["key1"]=>
string(1) "1"
["key2"]=>
string(1) "2"
}
Hopefully I'm not the only one who finds this pretty simple to grasp.
array_combine
creates a key => value
array from an array of keys and an array of values, the rest is pretty self explanatory.
What sort of button, neither a Forms Control nor an ActiveX control should affect the used range.
It is a known problem that excel does not keep track of the used range very well. Any reference to the used range via VBA will reset the value to the current used range. So try running this sub procedure:
Sub ResetUsedRng()
Application.ActiveSheet.UsedRange
End Sub
Failing that you may well have some formatting hanging round. Try clearing/deleting all the cells after your last row.
Regarding the above also see:
Another method to find the last used cell:
Dim rLastCell As Range
Set rLastCell = ActiveSheet.Cells.Find(What:="*", After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
Change the search direction to find the first used cell.
To convert XML File in to JSON include the following dependency
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
and you can Download Jar from Maven Repository here. Then implement as:
String soapmessageString = "<xml>yourStringURLorFILE</xml>";
JSONObject soapDatainJsonObject = XML.toJSONObject(soapmessageString);
System.out.println(soapDatainJsonObject);
You can use shuf
:
shuf -n 1 $FILE
There is also a utility called rl
. In Debian it's in the randomize-lines
package that does exactly what you want, though not available in all distros. On its home page it actually recommends the use of shuf
instead (which didn't exist when it was created, I believe). shuf
is part of the GNU coreutils, rl
is not.
rl -c 1 $FILE
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
For me the problem was, that I had used a query to that particular table while Django was initialized. Of course it will then throw an error, because those tables did not exist. In my case, it was a get_or_create
method within a admin.py file, that was executed whenever the software ran any kind of operation (in this case the migration). Hope that helps someone.
Check CAST and CONVERT syntax of t-sql:
Here is the same way as @Nera suggested to check the class first but instead of using .SD
is to use the fast loop of data.table with set
as @Matt Dowle solution with added class check.
for (j in seq_len(ncol(DT))){
if(class(DT[[j]]) == 'factor')
set(DT, j = j, value = as.character(DT[[j]]))
}
After @SedatKapanoglu comment, I am adding all my approach that works, because he was right, just using the fluent API does not work.
1- Create custom code generator and override Generate for a ColumnModel.
public class ExtendedMigrationCodeGenerator : CSharpMigrationCodeGenerator
{
protected override void Generate(ColumnModel column, IndentedTextWriter writer, bool emitName = false)
{
if (column.Annotations.Keys.Contains("Default"))
{
var value = Convert.ChangeType(column.Annotations["Default"].NewValue, column.ClrDefaultValue.GetType());
column.DefaultValue = value;
}
base.Generate(column, writer, emitName);
}
}
2- Assign the new code generator:
public sealed class Configuration : DbMigrationsConfiguration<Data.Context.EfSqlDbContext>
{
public Configuration()
{
CodeGenerator = new ExtendedMigrationCodeGenerator();
AutomaticMigrationsEnabled = false;
}
}
3- Use fluent api to created the Annotation:
public static void Configure(DbModelBuilder builder){
builder.Entity<Company>().Property(c => c.Status).HasColumnAnnotation("Default", 0);
}
Use next
:
(1..10).each do |a|
next if a.even?
puts a
end
prints:
1
3
5
7
9
For additional coolness check out also redo
and retry
.
Works also for friends like times
, upto
, downto
, each_with_index
, select
, map
and other iterators (and more generally blocks).
For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.
What happens in reality in case you pass string as a first parameter of function
setTimeout(
'string'
,number
)
is value of first param got evaluated when it is time to run (after number
of miliseconds passed).
Basically it is equal to
setTimeout(
eval('string')
,number
)
This is
an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.
So samples which you refer are not good samples, and may be given in different context or just simple typo.
If you invoke like this setTimeout(something, number)
, first parameter is not string, but pointer to a something called something
. And again if something
is string - then it will be evaluated. But if it is function, then function will be executed.
jsbin sample
One more thing to add to this list to check:
Make sure the element you are trying to focus is not itself nor is contained in an element with "display: none" at the time you are trying to focus it.
you can solve that problem in visual basic .net without concatenating your text, you can use this as a return type of your overloaded Tostring:
System.Text.RegularExpressions.Regex.Unescape(String.format("FirstName:{0} \r\n LastName: {1}", "Nordanne", "Isahac"))
Apache Spark does not support native CSV output on disk.
You have four available solutions though:
You can convert your Dataframe into an RDD :
def convertToReadableString(r : Row) = ???
df.rdd.map{ convertToReadableString }.saveAsTextFile(filepath)
This will create a folder filepath. Under the file path, you'll find partitions files (e.g part-000*)
What I usually do if I want to append all the partitions into a big CSV is
cat filePath/part* > mycsvfile.csv
Some will use coalesce(1,false)
to create one partition from the RDD. It's usually a bad practice, since it may overwhelm the driver by pulling all the data you are collecting to it.
Note that df.rdd
will return an RDD[Row]
.
With Spark <2, you can use databricks spark-csv library:
Spark 1.4+:
df.write.format("com.databricks.spark.csv").save(filepath)
Spark 1.3:
df.save(filepath,"com.databricks.spark.csv")
With Spark 2.x the spark-csv
package is not needed as it's included in Spark.
df.write.format("csv").save(filepath)
You can convert to local Pandas data frame and use to_csv
method (PySpark only).
Note: Solutions 1, 2 and 3 will result in CSV format files (part-*
) generated by the underlying Hadoop API that Spark calls when you invoke save
. You will have one part-
file per partition.
It seems to me you are using the wrong version...
TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!
You may get your answer here: Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
UPDATE
It might be due to various issues.I cant say which one is there in your case. It may be because:
Some WMI related services are:
For DCOM settings refer to registry key HKLM\Software\Microsoft\OLE
, value EnableDCOM
. The value should be set to 'Y'.
For result find: Click Here
Screen is a full-screen window manager that multiplexes a physical terminal between several processes, typically interactive shells. There is a scrollback history buffer for each virtual terminal and a copy-and-paste mechanism that allows the user to move text regions between windows.
There are all sorts of things which can do this. One possiblity is "Traffic Shaping". This is commonly done in office environments to reserve bandwidth for business critical activities. It may also be done by the web hosting company, or by your ISP, for very similar reasons.
You can also set it up at home very simply.
For example there may be a rule reserving minimum bandwidth for FTP, while SFTP might be falling under an "everything else" rule. Or there might be a rule capping bandwidth for SFTP, but someone else is also using SFTP at the same time as you.
So: Where are you tranferring the file from and to?
private readonly UserManager<AppUser> _userManager;
public AccountsController(UserManager<AppUser> userManager)
{
_userManager = userManager;
}
[Authorize(Policy = "ApiUser")]
[HttpGet("api/accounts/GetProfile", Name = "GetProfile")]
public async Task<IActionResult> GetProfile()
{
var userId = ((ClaimsIdentity)User.Identity).FindFirst("Id").Value;
var user = await _userManager.FindByIdAsync(userId);
ProfileUpdateModel model = new ProfileUpdateModel();
model.Email = user.Email;
model.FirstName = user.FirstName;
model.LastName = user.LastName;
model.PhoneNumber = user.PhoneNumber;
return new OkObjectResult(model);
}
IsEmpty()
would be the quickest way to check for that.
IsNull()
would seem like a similar solution, but keep in mind Null has to be assigned to the cell; it's not inherently created in the cell.
Also, you can check the cell by:
count()
counta()
Len(range("BCell").Value) = 0
You need to use a while loop. If you make a while loop, and there's no instruction after the loop, it'll become an infinite loop,and won't stop until you manually stop it.
“tools:context” is one of the Design Attributes that can facilitate layout creation in XML in the development framework. This attribute is used to show the development framework what activity class is picked for implementing the layout. Using “tools:context”, Android Studio chooses the necessary theme for the preview automatically.
If you’d like to know more about some other attributes and useful tools for Android app development, take a look at this review: http://cases.azoft.com/4-must-know-tools-for-effective-android-development/
Ok this helped a lot, I couldn't find a fix.
Simply, I already port forwarded the FTP port to my server. (The default is 14147, I'll use this as example)
Go to Edit > General settings, Listening port should be the one your using, in this case 14147.
Then go to Passive Mode Settings, I checked "Use Custom Port", and entered in the Range 50000 - 50100.
Then on your router, port forward 50000 - 50100 to the server IP locally.
IPv4 specific settings I left at default, reconnected my client, and bam now the file listing appears.
Ensure your servers firewall has an inbound rule set to accept 14147, and 50000-50100.
Basically what Evan stated. I can't attest to the security of opening these ports, but this is what finally got my Filezilla client and server to communicate and view files. Hope this helps someone.
The question mentions Windows, and the accepted answer also works for Ubuntu, but for those who found this question coming from a Redhat flavor of Linux, this did the trick:
sudo yum install -y python-setuptools
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
The below code may help you.
protected String getLocalizedBigDecimalValue(BigDecimal input, Locale locale) {
final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
numberFormat.setGroupingUsed(true);
numberFormat.setMaximumFractionDigits(2);
numberFormat.setMinimumFractionDigits(2);
return numberFormat.format(input);
}
If the question is about counting the number of keywords then would recommend something like
def countoccurrences(store, value):
try:
store[value] = store[value] + 1
except KeyError as e:
store[value] = 1
return
in the main function have something that loops through the data and pass the values to countoccurrences function
if __name__ == "__main__":
store = {}
list = ('a', 'a', 'b', 'c', 'c')
for data in list:
countoccurrences(store, data)
for k, v in store.iteritems():
print "Key " + k + " has occurred " + str(v) + " times"
The code outputs
Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times
SELECT DateAdded, COUNT(1) AS NUMBERADDBYDAY
FROM Responses
WHERE DateAdded >= dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded
Either
render partial: 'user', locals: {size: 30}
Or
render 'user', size: 30
To use locals
, you need partial
. Without the partial
argument, you can just list variables directly (not within locals
)
As I mentioned in my comment, I think the reason why this doesn't work is because the compiler can't infer types based on generic constraints.
Below is an alternative implementation that will compile. I've revised the IAccess interface to only have the T
generic type parameter.
interface ISignatur<T>
{
Type Type { get; }
}
interface IAccess<T>
{
ISignatur<T> Signature { get; }
T Value { get; set; }
}
class Signatur : ISignatur<bool>
{
public Type Type
{
get { return typeof(bool); }
}
}
class ServiceGate
{
public IAccess<T> Get<T>(ISignatur<T> sig)
{
throw new NotImplementedException();
}
}
static class Test
{
static void Main()
{
ServiceGate service = new ServiceGate();
var access = service.Get(new Signatur());
}
}
Only a teacher would ask you to do something silly like this. You could provide an expected answer. Or a unique solution, while the rest of the class will be (yawn) the same...
from operator import lt, gt
def ultimate (l,op,c=1,u=0):
try:
if op(l[c],l[u]):
u = c
c += 1
return ultimate(l,op,c,u)
except IndexError:
return l[u]
def minimum (l):
return ultimate(l,lt)
def maximum (l):
return ultimate(l,gt)
The solution is simple. Use this to set yourself apart from obvious choices.
Try this steps:
1) Resharper > Options
> Keyboard & Menus
Then point choose:
Hide overridden Visual Studio menu items
(Check)Visual Studio
(Check)Then click on Apply Scheme and Save
.
2) Tools
> Options
> Environment
> Keyboard
Reset
Ok
videoView can't open this video Online video
Create file res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
New in the AndroidManifest.xml file under application:
android:networkSecurityConfig="@xml/network_security_config"
https://techprogrammingideas.blogspot.com/2021/02/android-code-for-displaying-video-with.html
https://youtu.be/90hWWAqfdUU
yy
will yank the current line without deleting it
dd
will delete the current line
p
will put
a line grabbed by either of the previous methods
$('.tooltip').animate({ opacity: 1, top: "-10px" }, 'slow');
However, this doesn't appear to work on display: none
elements (as fadeIn
does). So, you might need to put this beforehand:
$('.tooltip').css('display', 'block');
$('.tooltip').animate({ opacity: 0 }, 0);
import os
folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)
for f in fileList:
filePath = folder + '/'+f
if os.path.isfile(filePath):
os.remove(filePath)
elif os.path.isdir(filePath):
newFileList = os.listdir(filePath)
for f1 in newFileList:
insideFilePath = filePath + '/' + f1
if os.path.isfile(insideFilePath):
os.remove(insideFilePath)
If you use YSlow with Firebug and analyse your page performance, YSlow will certainly tell you what artifacts on your page are not gzip'd!
Try something like this
jQuery
$('#toggle_icon').toggle(function() {
$('#toggle_icon').text('-');
$('#toggle_text').slideToggle();
}, function() {
$('#toggle_icon').text('+');
$('#toggle_text').slideToggle();
});
HTML
<a href="#" id="toggle_icon">+</a>
<div id="toggle_text" style="display: none">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
</div>
try this:
.test {
position:absolute;
background:blue;
width:200px;
height:200px;
top:40px;
transition:left 1s linear;
left: 0;
}
EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.
Here is a good table for printf
specifiers. So it should be %hu
for unsigned short int
.
And link to Wikipedia "C data types" too.
here is my implementation
public static byte[] intToByteArray(int a) {
return BigInteger.valueOf(a).toByteArray();
}
public static int byteArrayToInt(byte[] b) {
return new BigInteger(b).intValue();
}
This is all you need.
rsync -e ssh file host:/directory/.
var isValid = true;
$("#tabledata").find("#tablebody").find("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
}
else{
isValid = true;
}
});
console.log(isValid);
With SQL 2012 and later, you could use TRY_CAST
/TRY_CONVERT
to try converting to a numeric type, e.g. TRY_CAST(answer AS float) IS NOT NULL
-- note though that this will match scientific notation too (1+E34). (If you use decimal
, then scientific notation won't match)
You cannot create migration scripts for existing models.
Resources:
If going the classic way, you'll have to recreate the models via the CLI:
sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text
It will generate these files:
models/myuser.js:
"use strict";_x000D_
module.exports = function(sequelize, DataTypes) {_x000D_
var MyUser = sequelize.define("MyUser", {_x000D_
first_name: DataTypes.STRING,_x000D_
last_name: DataTypes.STRING,_x000D_
bio: DataTypes.TEXT_x000D_
}, {_x000D_
classMethods: {_x000D_
associate: function(models) {_x000D_
// associations can be defined here_x000D_
}_x000D_
}_x000D_
});_x000D_
return MyUser;_x000D_
};
_x000D_
migrations/20150210104840-create-my-user.js:
"use strict";_x000D_
module.exports = {_x000D_
up: function(migration, DataTypes, done) {_x000D_
migration.createTable("MyUsers", {_x000D_
id: {_x000D_
allowNull: false,_x000D_
autoIncrement: true,_x000D_
primaryKey: true,_x000D_
type: DataTypes.INTEGER_x000D_
},_x000D_
first_name: {_x000D_
type: DataTypes.STRING_x000D_
},_x000D_
last_name: {_x000D_
type: DataTypes.STRING_x000D_
},_x000D_
bio: {_x000D_
type: DataTypes.TEXT_x000D_
},_x000D_
createdAt: {_x000D_
allowNull: false,_x000D_
type: DataTypes.DATE_x000D_
},_x000D_
updatedAt: {_x000D_
allowNull: false,_x000D_
type: DataTypes.DATE_x000D_
}_x000D_
}).done(done);_x000D_
},_x000D_
down: function(migration, DataTypes, done) {_x000D_
migration.dropTable("MyUsers").done(done);_x000D_
}_x000D_
};
_x000D_
You can use hex colors:
your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)
Add an id column to the csv file and leave it blank:
id,Name,Address
,name1,addr test 1
,name2,addr test 2
Remove KEEPIDENTITY keyword from query:
BULK INSERT Employee FROM 'path\tempFile.csv '
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');
The id identity field will be auto-incremented.
If you assign values to the id field in the csv, they'll be ignored unless you use the KEEPIDENTITY keyword, then they'll be used instead of auto-increment.
Appending to the answer but using anonymous arrays and annotating:
Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]
Taking that answer apart, starting from the inside:
"a,b,c,d"
is actually a string.split
on commas into an array.zip
that together with the following array.[1,2,3,4]
is an actual array.The intermediate result is:
[[a,1],[b,2],[c,3],[d,4]]
flatten then transforms that to:
["a",1,"b",2,"c",3,"d",4]
and then:
*["a",1,"b",2,"c",3,"d",4]
unrolls that into
"a",1,"b",2,"c",3,"d",4
which we can use as the arguments to the Hash[]
method:
Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]
which yields:
{"a"=>1, "b"=>2, "c"=>3, "d"=>4}
This has been discussed on SO multiple times. Here are a few links to get you started:
SO: Capturing image from webcam in java?
openCVF applet: http://www.colorfulwolf.com/blog/2011/07/05/accessing-the-webcam-from-inside-a-java-applet/
config: http://ganeshtiwaridotcomdotnp.blogspot.in/2011/12/opencv-javacv-eclipse-project.html
Swift 4. If your array contains elements of type [String: AnyObject]. So to find the index of element use the below code
var array = [[String: AnyObject]]()// Save your data in array
let objectAtZero = array[0] // get first object
let index = (self.array as NSArray).index(of: objectAtZero)
Or If you want to found index on the basis of key from Dictionary. Here array contains Objects of Model class and I am matching id property.
let userId = 20
if let index = array.index(where: { (dict) -> Bool in
return dict.id == userId // Will found index of matched id
}) {
print("Index found")
}
OR
let storeId = Int(surveyCurrent.store_id) // Accessing model key value
indexArrUpTo = self.arrEarnUpTo.index { Int($0.store_id) == storeId }! // Array contains models and finding specific one
I fixed my pythonpath and everything was dandy when I imported stuff through the console, but all these previously unresolved imports were still marked as errors in my code, no matter how many times I restarted eclipse or refreshed/cleaned the project.
I right clicked the project->Pydev->Remove error markers and it got rid of that problem. Don't worry, if your code contains actual errors they will be re-marked.
For Jackson 2+ (com.fasterxml.jackson
), the methods are little bit different:
Iterator<Entry<String, JsonNode>> nodes = rootNode.get("foo").fields();
while (nodes.hasNext()) {
Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodes.next();
logger.info("key --> " + entry.getKey() + " value-->" + entry.getValue());
}
If your elements are glitching this is probably because when you change the position to relative
the Y position of the footer increases which tries to send the item back to fixed
which creates a loop. You can avoid this by setting two different cases when scrolling up and down. You don't even need to reference the fixed element, just the footer, and window size.
const footer = document.querySelector('footer');
document.addEventListener("scroll", checkScroll);
let prevY = window.scrollY + window.innerHeight;
function checkScroll() {
let footerTop = getRectTop(footer) + window.scrollY;
let windowBottomY = window.scrollY + window.innerHeight;
if (prevY < windowBottomY) { // Scroll Down
if (windowBottomY > footerTop)
setScrolledToFooter(true) // using React state. Change class or change style in JS.
} else { // Scroll Up
if (windowBottomY <= footerTop)
setScrolledToFooter(false)
}
prevY = windowBottomY
};
function getRectTop(el) {
var rect = el.getBoundingClientRect();
return rect.top;
}
and the position of the element in the style object as follows:
position: scrolledToFooter ? 'relative' : 'fixed'
You can add elements of a list
to a set
like this:
>>> foo = set(range(0, 4))
>>> foo
set([0, 1, 2, 3])
>>> foo.update(range(2, 6))
>>> foo
set([0, 1, 2, 3, 4, 5])
Based on Braden Rockwell Napier's answer, I made this BackgroundImage
component
BackgroundImage.js
import React, { Component } from 'react'
import { Image } from 'react-native'
class BackgroundImage extends Component {
render() {
const {source, children, style, ...props} = this.props
return (
<Image source={ source }
style={ { flex: 1, width: null, height: null, ...style } }
{...props}>
{ children }
</Image>
)
}
}
BackgroundImage.propTypes = {
source: React.PropTypes.object,
children: React.PropTypes.object,
style: React.PropTypes.object
}
export default BackgroundImage
someWhereInMyApp.js
import BackgroundImage from './backgroundImage'
....
<BackgroundImage source={ { uri: "https://facebook.github.io/react-native/img/header_logo.png" } }>
<Text>Test</Text>
</BackgroundImage>
As mentioned in "Shorthand for diff of git commit with its parent?", you can also use git diff
with:
git diff COMMIT^!
or
git diff-tree -p COMMIT
With git show, you would need (in order to focus on diff alone) to do:
git show --color --pretty=format:%b $COMMIT
The COMMIT
parameter is a commit-ish:
A commit object or an object that can be recursively dereferenced to a commit object. The following are all commit-ishes: a commit object, a tag object that points to a commit object, a tag object that points to a tag object that points to a commit object, etc.
See gitrevision "SPECIFYING REVISIONS" to reference a commit-ish.
See also "What does tree-ish mean in Git?".
'opts' is deprecated.
in ggplot2 >= 0.9.2
use
p + theme(legend.position = "none")
I would like to add a bit more to MadProgrammer's Answer.
In case of multiple line writing, when executing the command
writer.write(string);
one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,
System.out.println("\n");
Thus, the whole text comes as one big chunk of text which is undesirable in most cases. The newline character can be dependent on the platform, so it is better to get this character from the java system properties using
String newline = System.getProperty("line.separator");
and then using the newline variable instead of "\n". This will get the output in the way you want it.
Dim proc As New Process()
Dim psi As New ProcessStartInfo()
psi.CreateNoWindow = True
psi.FileName = "cmd.exe"
psi.Arguments = "/C net stop YOURSERVICENAMEHERE && net start YOURSERVICENAMEHERE"
psi.LoadUserProfile = False
psi.UseShellExecute = False
psi.WindowStyle = ProcessWindowStyle.Hidden
proc.StartInfo = psi
proc.Start()
Your question 1 has been already extensively discussed in several excellent answers here.
I thought to share with you a few lines of code that allow you to compute the autocorrelation of a signal based only on the mathematical properties of the autocorrelation. That is, the autocorrelation may be computed in the following way:
subtract the mean from the signal and obtain an unbiased signal
compute the Fourier transform of the unbiased signal
compute the power spectral density of the signal, by taking the square norm of each value of the Fourier transform of the unbiased signal
compute the inverse Fourier transform of the power spectral density
normalize the inverse Fourier transform of the power spectral density by the sum of the squares of the unbiased signal, and take only half of the resulting vector
The code to do this is the following:
def autocorrelation (x) :
"""
Compute the autocorrelation of the signal, based on the properties of the
power spectral density of the signal.
"""
xp = x-np.mean(x)
f = np.fft.fft(xp)
p = np.array([np.real(v)**2+np.imag(v)**2 for v in f])
pi = np.fft.ifft(p)
return np.real(pi)[:x.size/2]/np.sum(xp**2)
Cannot override constructor. Constructor can be regarded as static, subclass cannot override its super constructor.
Of course, you could call protected-method in super class constructor, then overide it in subclass to change super class constructor. However, many persons suggest not to use the trick, in order to protect super class constructor behavior. For instance, FindBugs will warn you that a constructor calls a non-final method.
Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:
Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.
In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.
Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.
It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath()
method. Using that method is in any case alarming.
The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location)
does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.
So, the path to the final storage location can be definied in either of the following ways:
Hardcoded:
File uploads = new File("/path/to/uploads");
Environment variable via SET UPLOAD_LOCATION=/path/to/uploads
:
File uploads = new File(System.getenv("UPLOAD_LOCATION"));
VM argument during server startup via -Dupload.location="/path/to/uploads"
:
File uploads = new File(System.getProperty("upload.location"));
*.properties
file entry as upload.location=/path/to/uploads
:
File uploads = new File(properties.getProperty("upload.location"));
web.xml
<context-param>
with name upload.location
and value /path/to/uploads
:
File uploads = new File(getServletContext().getInitParameter("upload.location"));
If any, use the server-provided location, e.g. in JBoss AS/WildFly:
File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
Either way, you can easily reference and save the file as follows:
File file = new File(uploads, "somefilename.ext");
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath());
}
Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:
File file = File.createTempFile("somefilename-", ".ext", uploads);
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
How to obtain part
in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part
in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?
Note: do not use Part#write()
as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location)
.
This task can be accomplished without blueprints and tricky imports using Centralized URL Map
app.py
import views
from flask import Flask
app = Flask(__name__)
app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/other', view_func=views.other)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
views.py
from flask import render_template
def index():
return render_template('index.html')
def other():
return render_template('other.html')
I tried this and things got weird for me. (css stopped working after the :after {content: "";}
part of this tutorial. I found you can color the bullets by just using color:#ddd;
on the li
item itself.
Here's an example.
li{
color:#ff0000;
list-style:square;
}
a {
text-decoration: none;
color:#00ff00;
}
a:hover {
background-color: #ddd;
}
The easiest way it to use a regular expression:
Regular Expression for alphanumeric and underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
What you actually created with:
MyType[] list = []
Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:
MyType[] array = new MyType[4]
But there's no add method of course.
If you create list with def
it's something like creating this instance with Object
(You can read more about def
here). And []
creates empty ArrayList
in this case.
So using def list = []
you can then append new items with add()
method of ArrayList
list.add(new MyType())
Or more groovy way with overloaded left shift operator:
list << new MyType()
Logical layers are merely a way of organizing your code. Typical layers include Presentation, Business and Data – the same as the traditional 3-tier model. But when we’re talking about layers, we’re only talking about logical organization of code. In no way is it implied that these layers might run on different computers or in different processes on a single computer or even in a single process on a single computer. All we are doing is discussing a way of organizing a code into a set of layers defined by specific function.
Physical tiers however, are only about where the code runs. Specifically, tiers are places where layers are deployed and where layers run. In other words, tiers are the physical deployment of layers.
Source: Rockford Lhotka, Should all apps be n-tier?
Some other options:
<object type="application/pdf" data="filename.pdf" width="100%" height="100%">
</object>
<object type="application/pdf" data="#request.localhost#_includes/filename.pdf"
width="100%" height="100%">
<param name="src" value="#request.localhost#_includes/filename.pdf">
</object>
I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.
Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div
is restored, forcing the animations to restart.
All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head>
section of your page:
<script>
setInterval(function(){
var container = document.getElementById('content');
var tmp = container.innerHTML;
container.innerHTML= tmp;
}, 35000 // length of the whole show in milliseconds
);
</script>
BTW, the closing </head>
in your code is misplaced: it must be before the starting <body>
.
IF this is only occurring on deployments, be sure that you have the dependency of the package you are referencing in the .war. For instance, this was working locally on my machine, with debug configurations working fine, but after deploying to Amazon's Elastic Beanstalk , I received this error and noticed one of the dependencies was not bundled in the .war package.
If you have Git
installed on windows you can use the GNU Bash
.... it's built in.
https://superuser.com/questions/134685/run-curl-commands-from-windows-console/#483964
This for the Api you could use
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
var multer = require('multer');
const port = 8000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(port, ()=>{
console.log('We are live on' + port);
});
var upload = multer({dest:'./upload/'});
app.post('/post', upload.single('file'), function(req, res) {
console.log(req.file);
res.send("file saved on server");
});
This also works fine used on Postman but the file doesn't comes with .jpg extension any Advice? As commented below
This is the default feature of multer if uploads file with no extension, however, provides you the the file object, using which you can update the extension of the file.
var filename = req.file.filename;
var mimetype = req.file.mimetype;
mimetype = mimetype.split("/");
var filetype = mimetype[1];
var old_file = configUploading.settings.rootPathTmp+filename;
var new_file = configUploading.settings.rootPathTmp+filename+'.'+filetype;
rname(old_file,new_file);
You have to add a ToolTip
control to your form first. Then you can set the text it should display for other controls.
Here's a screenshot showing the designer after adding a ToolTip
control which is named toolTip1
:
d2j-dex2jar.sh someApk.apk
Follow this guide: https://code.google.com/p/dex2jar/wiki/UserGuide
--Update 10/11/2016--
Found this ClassyShark from Google's github pretty easy to view code from APK.
https://github.com/google/android-classyshark
// make sure that you downloaded release https://github.com/pxb1988/dex2jar/releases (for the ppl who coldnt find this link in /dex2jar/downloads/list
To your secondary question
var elem1 = $('#elem1'),
elem2 = $('#elem2'),
elem3 = $('#elem3');
You can use the variable as the replacement of selector.
elem1.css({'display':'none'}); //will work
In the below case selector is already stored in a variable.
$(elem1,elem2,elem3).css({'display':'none'}); // will not work
I am adding this commands as reference for altering retention inside of InfluxDB container in kubernetes k8s. wget is used so as container doesn't have curl and influx CLI
wget 'localhost:8086/query?pretty=true' --post-data="db=k8s;q=ALTER RETENTION POLICY \"default\" on \"k8s\" duration 5h shard duration 4h default" -O-
Verification
wget 'localhost:8086/query?pretty=true' --post-data="db=k8s;q=SHOW RETENTION POLICIES" -O-
string appPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
Returns the directory information for the specified path string.
From Application.ExecutablePath
Gets the path for the executable file that started the application, including the executable name.
You can use functionality called Export Data-Tier Application which generates .bacpac
file consisting database schema and data.
On destination server, you can use Import Data-Tier Application option which creates and populates new database from pre-created .bacpac
file
If you want just to transfer database schema, you can use Extract Data-Tier Application for creating file and Deploy Data-Tier Application for deploying created database schema.
I've tried this process on different versions of SQL Server from SQL 2014 to SQL 2012 and from SQL 2014 to SQL 2008R2 and worked well.
Use 'needs-validation' apart from form-group, it will work.
Funtional efficiency is totally different. If you would like to select only "return value" except duplicate one, use distinct is better than group by. Because "group by" include ( sorting + removing ) , "distinct" include ( removing )
I resolved error copying the files class.phpmailer.php , class.smtp.php to the folder where the file is PHPMailerAutoload.php, of course there should be the file that we will use to send the email.
If not having a value has a meaning in your program (e.g. an optional value), you should use None. That's its purpose anyway.
If the value must be provided by the caller of __init__, I would recommend not to initialize it.
If "" makes sense as a default value, use it.
In Python the type is deduced from the usage. Hence, you can change the type by just assigning a value of another type.
>>> x = None
>>> print type(x)
<type 'NoneType'>
>>> x = "text"
>>> print type(x)
<type 'str'>
>>> x = 42
>>> print type(x)
<type 'int'>
The previous answers gave poor results when using rounded corners or stroke-width
that's >1 . For example, you would expect the following code to produce a rounded rectangle, but the corners are clipped by the parent svg
component:
<svg width="200" height="100">_x000D_
<!--this rect should have rounded corners-->_x000D_
<rect x="0" y="0" rx="5" ry="5" width="200" height="100" stroke="red" stroke-width="10px" fill="white"/>_x000D_
<text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle">CLIPPED BORDER</text> _x000D_
</svg>
_x000D_
Instead, I recommend wrapping the text
in a svg
and then nesting that new svg
and the rect
together inside a g
element, as in the following example:
<!--the outer svg here-->_x000D_
<svg width="400px" height="300px">_x000D_
_x000D_
<!--the rect/text group-->_x000D_
<g transform="translate(50,50)">_x000D_
<rect rx="5" ry="5" width="200" height="100" stroke="green" fill="none" stroke-width="10"/>_x000D_
<svg width="200px" height="100px">_x000D_
<text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle">CORRECT BORDER</text> _x000D_
</svg>_x000D_
</g>_x000D_
_x000D_
<!--rest of the image's code-->_x000D_
</svg>
_x000D_
This fixes the clipping problem that occurs in the answers above. I also translated the rect/text group using the transform="translate(x,y)"
attribute to demonstrate that this provides a more intuitive approach to positioning the rect/text on-screen.
If you have access to the delegate method you can do this:
[20] pry(main)> class Foo
[20] pry(main)* def self.bar
[20] pry(main)* "foo bar"
[20] pry(main)* end
[20] pry(main)* delegate :bar, to: 'self.class'
[20] pry(main)* end
=> [:bar]
[21] pry(main)> Foo.new.bar
=> "foo bar"
[22] pry(main)> Foo.bar
=> "foo bar"
Alternatively, and probably cleaner if you have more then a method or two you want to delegate to class & instance:
[1] pry(main)> class Foo
[1] pry(main)* module AvailableToClassAndInstance
[1] pry(main)* def bar
[1] pry(main)* "foo bar"
[1] pry(main)* end
[1] pry(main)* end
[1] pry(main)* include AvailableToClassAndInstance
[1] pry(main)* extend AvailableToClassAndInstance
[1] pry(main)* end
=> Foo
[2] pry(main)> Foo.new.bar
=> "foo bar"
[3] pry(main)> Foo.bar
=> "foo bar"
A word of caution:
Don't just randomly delegate
everything that doesn't change state to class and instance because you'll start running into strange name clash issues. Do this sparingly and only after you checked nothing else is squashed.
If you are running the correct class and the main is properly defined, also check if you have a class called String defined in the same package. This definition of String class will be considered and since it doesn't confirm to main(java.lang.String[] args)
, you will get the same exception.
Suggestion is to never hide library java classes in your package.
This is a solution that came up with for a similar issue
exit_status () {
if [ $? = 0 ]
then
true
else
false
fi
}
usage:
do-command exit_status && echo "worked" || echo "didnt work"
Just like you can password protect workbooks and worksheets, you can password protect a macro in Excel from being viewed (and executed).
Place a command button on your worksheet and add the following code lines:
First, create a simple macro that you want to protect.
Range("A1").Value = "This is secret code"
Next, click Tools, Then VBAProject Properties...
Click Tools, VBAProject Properties...
Enter a Password Twice
Click OK.
Save, close and reopen the Excel file. Try to view the code.
The following dialog box will appear:
Password Protected from being Viewed
You can still execute the code by clicking on the command button but you cannot view or edit the code anymore (unless you know the password). The password for the downloadable Excel file is "easy".
Dim password As Variant password = Application.InputBox("Enter Password", "Password Protected") Select Case password Case Is = False 'do nothing Case Is = "easy" Range("A1").Value = "This is secret code" Case Else MsgBox "Incorrect Password" End Select
Result when you click the command button on the sheet:
Password Protected from being Executed
Explanation: The macro uses the InputBox method of the Application object. If the users clicks Cancel, this method returns False and nothing happens (InputBox disappears). Only when the user knows the password ("easy" again), the secret code will be executed. If the entered password is incorrect, a MsgBox is displayed. Note that the user cannot take a look at the password in the Visual Basic Editor because the project is protected from being viewed
Case sensitive Tables (table names created with double-quotes) can throw this same error as well. See this answer for more information.
Simply wrap the table in double quotes:
INSERT INTO "customer" (c_id,name,surname) VALUES ('1','Micheal','Jackson')
try this
public static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
and in tne edit text
final String emailText = email.getText().toString();
EMAIL_ADDRESS_PATTERN.matcher(emailText).matches()
Or rather than to declare a function, simply:
setTimeout(() => {
console.log('hello');
}, 1000);
There are two ways I know of
1) Console.ReadLine()
at the end of the program. Disadvantage, you have to change your code and have to remember to take it out
2) Run outside of the debugger CONTROL-F5
this opens a console window outside of visual studio and that window won't close when finished. Advantage, you don't have to change your code. Disadvantage, if there is an exception, it won't drop into the debugger (however when you do get exceptions, you can simply just rerun it in the debugger)
In matplotlib 3.1, you can also use ticklabel_format. To prevents scientific notation without offsets:
plt.gca().ticklabel_format(axis='both', style='plain', useOffset=False)
So I'm myself new to React and I found a way to do it.
This solution does not require any extra packages.
In the above docs they mention export in Shell and other options, the one I'll attempt to explain is using .env file
1.1 create Root/.env
#.env file
REACT_APP_SECRET_NAME=secretvaluehere123
Important notes it MUST start with REACT_APP_
1.2 Access ENV variable
#App.js file or the file you need to access ENV
<p>print env secret to HTML</p>
<pre>{process.env.REACT_APP_SECRET_NAME}</pre>
handleFetchData() { // access in API call
fetch(`https://awesome.api.io?api-key=${process.env.REACT_APP_SECRET_NAME}`)
.then((res) => res.json())
.then((data) => console.log(data))
}
1.3 Build Env Issue
So after I did step 1.1|2 it was not working, then I found the above issue/solution. React read/creates env when is built so you need to npm run start every time you modify the .env file so the variables get updated.
You want the value set, not the key set:
for (TypeValue name: this.example.values()) {
System.out.println(name);
}
The code you give wouldn't even compile, which may be worth mentioning in future questions - "doesn't seem to work" is a bit vague!
array hash_algos(void)
echo hash('sha384', 'Message to be hashed'.'salt');
Here is a link to reference http://php.net/manual/en/function.hash.php
for the main question:
call sibling folder as module:
from .. import siblingfolder
call a_file.py from sibling folder as module:
from ..siblingfolder import a_file
call a_function inside a file in sibling folder as module:
from..siblingmodule.a_file import func_name_exists_in_a_file
The easiest way.
go to lib/site-packages folder.
if exists 'easy_install.pth' file, just edit it and add your directory that you have script that you want make it as module.
if not exists, just make it one...and put your folder that you want there
after you add it..., python will be automatically perceive that folder as similar like site-packages and you can call every script from that folder or subfolder as a module.
i wrote this by my phone, and hard to set it to make everyone comfortable to read.
You need to remove the object from your data array before you call deleteRowsAtIndexPaths:withRowAnimation:
. So, your code should look like this:
// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//when delete is tapped
[currentCart removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
You can also simplify your code a little by using the array creation shortcut @[]
:
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
It is better to parse the URL properly - this way you can handle http://.../file.doc?foo
and http://.../foo.doc/file.exe
correctly.
from urlparse import urlparse
import os
path = urlparse(url_string).path
ext = os.path.splitext(path)[1]
if ext in extensionsToCheck:
print(url_string)
In theory, there's nothing preventing you from sending a request body in a GET
request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET
payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.
However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.
The simple option is to use POST
instead of GET
as recommended by other answers. Since POST
is not standardized by HTTP, you'll have to document how exactly that's supposed to work.
Another option, which I prefer, is to implement your application assuming the GET
payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override
, which is a popular convention for clients to emulate HTTP methods with POST
. So, if a client has a broken implementation, it can write the GET
request as a POST
, sending the X-HTTP-Method-Override: GET
method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.
An alternative to javax.comm
is the rxtx
library which supports more platforms than javax.comm
.
Use
s.length()
The following was once suggested in one of the answers, but its very inefficient
textMessage.getText().toString().length()
I know that's an old question with good answers, but I believe I can add my 2 cents.
The simplest and most flexible way which works for me is just using an almost "Plain and Old Java Object" class2D to create each "row" of your array.
The below example has some explanations and is executable (you can copy and paste it, but remember to check the package name):
package my2darraylist;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
public class My2DArrayList
{
public static void main(String[] args)
{
// This is your "2D" ArrayList
//
List<Box> boxes = new ArrayList<>();
// Add your stuff
//
Box stuff = new Box();
stuff.setAString( "This is my stuff");
stuff.addString("My Stuff 01");
stuff.addInteger( 1 );
boxes.add( stuff );
// Add other stuff
//
Box otherStuff = new Box();
otherStuff.setAString( "This is my other stuff");
otherStuff.addString("My Other Stuff 01");
otherStuff.addInteger( 1 );
otherStuff.addString("My Other Stuff 02");
otherStuff.addInteger( 2 );
boxes.add( otherStuff );
// List the whole thing
for ( Box box : boxes)
{
System.out.println( box.getAString() );
System.out.println( box.getMyStrings().size() );
System.out.println( box.getMyIntegers().size() );
}
}
}
class Box
{
// Each attribute is a "Column" in you array
//
private String aString;
private List<String> myStrings = new ArrayList<>() ;
private List<Integer> myIntegers = new ArrayList<>();
// Use your imagination...
//
private JPanel jpanel;
public void addString( String s )
{
myStrings.add( s );
}
public void addInteger( int i )
{
myIntegers.add( i );
}
// Getters & Setters
public String getAString()
{
return aString;
}
public void setAString(String aString)
{
this.aString = aString;
}
public List<String> getMyStrings()
{
return myStrings;
}
public void setMyStrings(List<String> myStrings)
{
this.myStrings = myStrings;
}
public List<Integer> getMyIntegers()
{
return myIntegers;
}
public void setMyIntegers(List<Integer> myIntegers)
{
this.myIntegers = myIntegers;
}
public JPanel getJpanel()
{
return jpanel;
}
public void setJpanel(JPanel jpanel)
{
this.jpanel = jpanel;
}
}
UPDATE - To answer the question from @Mohammed Akhtar Zuberi, I've created the simplified version of the program, to make it easier to show the results.
import java.util.ArrayList;
public class My2DArrayListSimplified
{
public static void main(String[] args)
{
ArrayList<Row> rows = new ArrayList<>();
Row row;
// Insert the columns for each row
// First Name, Last Name, Age
row = new Row("John", "Doe", 30);
rows.add(row);
row = new Row("Jane", "Doe", 29);
rows.add(row);
row = new Row("Mary", "Doe", 1);
rows.add(row);
// Show the Array
//
System.out.println("First\t Last\tAge");
System.out.println("----------------------");
for (Row printRow : rows)
{
System.out.println(
printRow.getFirstName() + "\t " +
printRow.getLastName() + "\t" +
printRow.getAge());
}
}
}
class Row
{
// REMEMBER: each attribute is a column
//
private final String firstName;
private final String lastName;
private final int age;
public Row(String firstName, String lastName, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getAge()
{
return age;
}
}
The code above produces the following result (I ran it on NetBeans):
run:
First Last Age
----------------------
John Doe 30
Jane Doe 29
Mary Doe 1
BUILD SUCCESSFUL (total time: 0 seconds)
If your OS is using systemd
then you can view docker daemon log with:
sudo journalctl -fu docker.service
<p style="text-indent: 5em;">
The first line of this paragraph will be indented about five characters, similar to a tabbed indent.
</p>
The first line of this paragraph will be indented about five characters, similar to a tabbed indent.
See How to Use HTML and CSS to Create Tabs and Spacing for more information.
We do it that way: First add this script.
<script type="text/javascript">
function populateIframe(id,path)
{
var ifrm = document.getElementById(id);
ifrm.src = "download.php?path="+path;
}
</script>
Place this where you want the download button(here we use just a link):
<iframe id="frame1" style="display:none"></iframe>
<a href="javascript:populateIframe('frame1','<?php echo $path; ?>')">download</a>
The file 'download.php' (needs to be put on your server) simply contains:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter. We think this is the best solution!
It should be noted that the PHP part of this solution is a simple demonstration and potentially very, very insecure. It allows the user to download any file, not just a pre-defined set. That means they could download parts of the source code of the site itself, possibly containing API credentials etc.
You can access the first element adding the following code to the highlight
function
$(this).find(".selected td:first").html()
Working Code:JSFIDDLE
You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):
Sub Count_Selection()
Dim cell As Object
Dim count As Integer
count = 0
For Each cell In Selection
count = count + 1
Next cell
MsgBox count & " item(s) selected"
End Sub
//String to Date Convert
var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)
//CONVERT FROM NSDate to String
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
Here's how I succeeded in installing maatwebsite\excel package from composer in Laravel Framework:
composer update
from local command prompt (then wait until all the install process finished).composer install
on remote server (then wait until all process finished).I know this question has already been answered. However, for those using spring boot, this link helped me - https://smarterco.de/java-load-file-classpath-spring-boot/
However, the resourceLoader.getResource("classpath:file.txt").getFile();
was causing this problem and sbk's comment:
That's it. A java.io.File represents a file on the file system, in a directory structure. The Jar is a java.io.File. But anything within that file is beyond the reach of java.io.File. As far as java is concerned, until it is uncompressed, a class in jar file is no different than a word in a word document.
helped me understand why to use getInputStream()
instead. It works for me now!
Thanks!
Short answer is:
junk$nm[junk$nm %in% "B"] <- "b"
Take a look at Index vectors in R Introduction (if you don't read it yet).
EDIT. As noticed in comments this solution works for character vectors so fail on your data.
For factor best way is to change level:
levels(junk$nm)[levels(junk$nm)=="B"] <- "b"
I tried to work with all the suggested answers above but nothing seems to work for me. So i am trying to explain what worked for me here.
I believe if you are calling some method like the Main
below or even with a single parameter as in your question, you just have to change the type of parameter from string
to object
for this to work. I have a class like below
//Assembly.dll
namespace TestAssembly{
public class Main{
public void Hello()
{
var name = Console.ReadLine();
Console.WriteLine("Hello() called");
Console.WriteLine("Hello" + name + " at " + DateTime.Now);
}
public void Run(string parameters)
{
Console.WriteLine("Run() called");
Console.Write("You typed:" + parameters);
}
public string TestNoParameters()
{
Console.WriteLine("TestNoParameters() called");
return ("TestNoParameters() called");
}
public void Execute(object[] parameters)
{
Console.WriteLine("Execute() called");
Console.WriteLine("Number of parameters received: " + parameters.Length);
for(int i=0;i<parameters.Length;i++){
Console.WriteLine(parameters[i]);
}
}
}
}
Then you have to pass the parameterArray inside an object array like below while invoking it. The following method is what you need to work
private void ExecuteWithReflection(string methodName,object parameterObject = null)
{
Assembly assembly = Assembly.LoadFile("Assembly.dll");
Type typeInstance = assembly.GetType("TestAssembly.Main");
if (typeInstance != null)
{
MethodInfo methodInfo = typeInstance.GetMethod(methodName);
ParameterInfo[] parameterInfo = methodInfo.GetParameters();
object classInstance = Activator.CreateInstance(typeInstance, null);
if (parameterInfo.Length == 0)
{
// there is no parameter we can call with 'null'
var result = methodInfo.Invoke(classInstance, null);
}
else
{
var result = methodInfo.Invoke(classInstance,new object[] { parameterObject } );
}
}
}
This method makes it easy to invoke the method, it can be called as following
ExecuteWithReflection("Hello");
ExecuteWithReflection("Run","Vinod");
ExecuteWithReflection("TestNoParameters");
ExecuteWithReflection("Execute",new object[]{"Vinod","Srivastav"});
There is no built-in extension method to do this. Although defining one is fairly straight forward. At the bottom of the post is a method I defined called Iterate. It can be used like so
collection.Iterate(c => { c.PropertyToSet = value;} );
Iterate Source
public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T> callback)
{
if (enumerable == null)
{
throw new ArgumentNullException("enumerable");
}
IterateHelper(enumerable, (x, i) => callback(x));
}
public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
if (enumerable == null)
{
throw new ArgumentNullException("enumerable");
}
IterateHelper(enumerable, callback);
}
private static void IterateHelper<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
int count = 0;
foreach (var cur in enumerable)
{
callback(cur, count);
count++;
}
}
JonSkeet has a good answer but as an alternative if you wanted to keep the result more portable you could convert the date into an ISO 8601 format which could then be read into most other frameworks but this may fall outside your requirements.
value.ToUniversalTime().ToString("O");
Here's another approach based off Stephan Hoyer's solution
getRandomString (length) {
var chars = 'abcdefghkmnpqrstuvwxyz23456789';
return times(length, () => sample(chars)).join('');
}
You can use the open pragma.
For eg. below sets STDOUT, STDIN & STDERR to use UTF-8....
use open qw/:std :utf8/;
This may sometimes be caused by Chrome extensions you've installed. For example, AdBlock.
Unfortunately the best solution I could find was to disable the offending extension.
In the .css try
.jumbotron {_x000D_
background-color:red !important; _x000D_
}
_x000D_
Actually, the correct way of checking for 32 bit or 64 bit platform is to use the Win64 constant which is defined in all versions of VBA (16 bit, 32 bit, and 64 bit versions).
#If Win64 Then
' Win64=true, Win32=true, Win16= false
#ElseIf Win32 Then
' Win32=true, Win16=false
#Else
' Win16=true
#End If
Source: VBA help on compiler constants
You can just use the Select()
extension method:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());
Or in LINQ syntax:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
var strings = from i in integers
select i.ToString();
Slice can be used to find the substring. When we know the indexes we can use an alternative solution like index wise adder. Both are taking roughly the same time for execution.
const primitiveStringMember = "my name is Mate";
const objectStringMember = new String("my name is Mate");
console.log(typeof primitiveStringMember);//string
console.log(typeof objectStringMember);//object
/* However when we use . operator to string primitive type, JS will wrap up the string with object. That's why we can use the methods String object type for the primitive type string.
*/
//Slice method
const t0 = performance.now();
slicedString = primitiveStringMember.slice(-2);//te
const t1 = performance.now();
console.log(`Call to do slice took ${t1 - t0} milliseconds.`);
//index vise adder method
const t2 = performance.now();
length = primitiveStringMember.length
neededString = primitiveStringMember[length-2]+primitiveStringMember[length-1];//te
const t3 = performance.now();
console.log(`Call to do index adder took ${t3 - t2} milliseconds.`);
_x000D_
Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample
@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = {
ServiceMarker.class,
RepositoryMarker.class }
)
public class AppConfig {
}
@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};
@Autowired
private Environment env;
@Bean(destroyMethod = "close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
@Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
private HibernateJpaVendorAdapter vendorAdaptor() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());
return entityManagerFactoryBean;
}
private Properties jpaHibernateProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");
return properties;
}
}
public static void main(String[] args) {
try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
MyService myService = springContext.getBean(MyServiceImpl.class);
try {
myService.handleProcess(fromDate, toDate);
} catch (Exception e) {
logger.error("Exception occurs", e);
myService.handleException(fromDate, toDate, e);
}
} catch (Exception e) {
logger.error("Exception occurs in loading Spring context: ", e);
}
}
@Service
public class MyServiceImpl implements MyService {
@Inject
private MyDao myDao;
@Override
public void handleProcess(String fromDate, String toDate) {
List<Student> myList = myDao.select(fromDate, toDate);
}
}
@Repository
@Transactional
public class MyDaoImpl implements MyDao {
@PersistenceContext
private EntityManager entityManager;
public Student select(String fromDate, String toDate){
TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
List<Student> list = query.getResultList();
return CollectionUtils.isEmpty(list) ? null : list;
}
}
Assuming maven project:
Properties file should be in src/main/resources/database
folder
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password
hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true
ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.
Let's say you have package name a.b.c.service.impl
. MyServiceImpl is in this package and so is ServiceMarker.
public interface ServiceMarker {
}
Same for repository marker. Let's say you have a.b.c.repository.impl
or a.b.c.dao.impl
package name. Then MyDaoImpl is in this this package and also Repositorymarker
public interface RepositoryMarker {
}
//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {
private LocalDateTime fromDate;
private LocalDateTime toDate;
//getters setters
}
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {
if (dateTime == null) {
return null;
}
return Timestamp.valueOf(dateTime);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
return timestamp.toLocalDateTime();
}
}
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.2.1.RELEASE</org.springframework-version>
<hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
<mysql-connector-java.version>5.1.36</mysql-connector-java.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
Hope it helps. Thanks
The code commented works as well, just choose which do you prefer
import numpy as np
from PIL import Image
def convert_from_cv2_to_image(img: np.ndarray) -> Image:
# return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
return Image.fromarray(img)
def convert_from_image_to_cv2(img: Image) -> np.ndarray:
# return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
return np.asarray(img)
If you're using Bootstrap v3.0.1 or greater, you should use this solution instead. It doesn't override Bootstrap's styles with custom CSS, but instead uses a Bootstrap feature.
My original answer is shown below for posterity
This is a pleasantly easy fix. Because .img-responsive
from Bootstrap already sets display: block
, you can use margin: 0 auto
to center the image:
.product .img-responsive {
margin: 0 auto;
}
If you're not on java 1.8 yet and you don't mind to use commons-lang you can use org.apache.commons.lang3.ObjectUtils#defaultIfNull
Your code would be:
dinner = ObjectUtils.defaultIfNull(cage.getChicken(),getFreeRangeChicken())
If you are using Ubuntu server, you can use systemctl
systemctl reload apache2
import requests
site_request = requests.get("https://abhiunix.in")
site_response = str(site_request.content)
print(site_response)
function checkArrowKeys(e){
var arrs= ['left', 'up', 'right', 'down'],
key= window.event? event.keyCode: e.keyCode;
if(key && key>36 && key<41) alert(arrs[key-37]);
}
document.onkeydown= checkArrowKeys;
Player.cpp
require the definition of Ball
class. So simply add #include "Ball.h"
Player.cpp:
#include "Player.h"
#include "Ball.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
In this state:
The thread is reading and processing rows for a SELECT statement, and sending data to the client.
Because operations occurring during this this state tend to perform large amounts of disk access (reads).
That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.
I had this problem with git rebase -i origin/master
to a branch. I wanted to take master's version of the submodule ref, so I simply did:
git reset master path/to/submodule
and then
git rebase --continue
That solved the problem for me.
This simulates a tab through a form and gives focus to the next input when the enter key is pressed.
window.onkeypress = function(e) {
if (e.which == 13) {
e.preventDefault();
var inputs = document.getElementsByClassName('input');
for (var i = 0; i < inputs.length; i++) {
if (document.activeElement.id == inputs[i].id && i+1 < inputs.length ) {
inputs[i+1].focus();
break;
}
}
log4j.rootLogger=OFF
Math.floor(operation)
returns the rounded down value of the operation.
Example of 1st question:
var x = 5;
var y = 10.4;
var z = Math.floor(x + y);
console.log(z);
Console:
15
Example of 2nd question:
var x = 14;
var y = 5;
var z = Math.floor(x%y);
console.log(x);
Console:
4
I wanted to demonstrate what happens when a new random generator is used every time. Suppose you have two methods or two classes each requiring a random number. And naively you code them like:
public class A
{
public A()
{
var rnd=new Random();
ID=rnd.Next();
}
public int ID { get; private set; }
}
public class B
{
public B()
{
var rnd=new Random();
ID=rnd.Next();
}
public int ID { get; private set; }
}
Do you think you will get two different IDs? NOPE
class Program
{
static void Main(string[] args)
{
A a=new A();
B b=new B();
int ida=a.ID, idb=b.ID;
// ida = 1452879101
// idb = 1452879101
}
}
The solution is to always use a single static random generator. Like this:
public static class Utils
{
public static readonly Random random=new Random();
}
public class A
{
public A()
{
ID=Utils.random.Next();
}
public int ID { get; private set; }
}
public class B
{
public B()
{
ID=Utils.random.Next();
}
public int ID { get; private set; }
}
Code for one liner isFlashExists
variable:
<script type='text/javascript'
src='//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js'> </script>
<script type='text/javascript'>
var isFlashExists = swfobject.hasFlashPlayerVersion('1') ? true : false ;
if (isFlashExists) {
alert ('flash exists');
} else {
alert ('NO flash');
}
</script>
Note that there is an alternative like this: swfobject.getFlashPlayerVersion();
def pzip(c, seq):
result = []
for item in seq:
for i in range(len(item)+1):
result.append(item[i:]+c+item[:i])
return result
def perm(line):
seq = [c for c in line]
if len(seq) <=1 :
return seq
else:
return pzip(seq[0], perm(seq[1:]))
you may also like this
var Grp = Model.GroupBy(item => item.Order.Customer)
.Select(group => new
{
Customer = Model.First().Customer,
CustomerId= group.Key,
Orders= group.ToList()
})
.ToList();
I'm just wondering whether it is good practice to use multiple JFrames?
Bad (bad, bad) practice.
There are any number of ways of displaying many elements in one GUI, e.g.:
CardLayout
(short demo.). Good for:
JInternalFrame
/JDesktopPane
typically used for an MDI.JTabbedPane
for groups of components.JSplitPane
A way to display two components of which the importance between one or the other (the size) varies according to what the user is doing.JLayeredPane
far many well ..layered components.JToolBar
typically contains groups of actions or controls. Can be dragged around the GUI, or off it entirely according to user need. As mentioned above, will minimize/restore according to the parent doing so.JList
(simple example below).JTree
.But if those strategies do not work for a particular use-case, try the following. Establish a single main JFrame
, then have JDialog
or JOptionPane
instances appear for the rest of the free-floating elements, using the frame as the parent for the dialogs.
In this case where the multiple elements are images, it would be better to use either of the following instead:
JLabel
(centered in a scroll pane) to display whichever image the user is interested in at that moment. As seen in ImageViewer
.JList
. As seen in this answer. The 'single row' part of that only works if they are all the same dimensions. Alternately, if you are prepared to scale the images on the fly, and they are all the same aspect ratio (e.g. 4:3 or 16:9).This version is 26% shorter than yours but functions identically, even for redundant/ambiguous values (returns the first match, as yours does). However, it is probably twice as slow as yours, because it creates a list from the dict twice.
key = dict_obj.keys()[dict_obj.values().index(value)]
Or if you prefer brevity over readability you can save one more character with
key = list(dict_obj)[dict_obj.values().index(value)]
And if you prefer efficiency, @PaulMcGuire's approach is better. If there are lots of keys that share the same value it's more efficient not to instantiate that list of keys with a list comprehension and instead use use a generator:
key = (key for key, value in dict_obj.items() if value == 'value').next()
try this code ['12','34','35','231']*","
will give you result "12,34,35,231"
I hope this is the result you, let me know
Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.
The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:
e.g., given:
{
"store":
{
"book":
[
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle":
{
"color": "red",
"price": 19.95
}
}
}
And the expression: $.store.book[?(@.length-1)].title
, the tool returns a list of all titles.
You may have to perform a diff and put document.getElementById('name')
code inside a condition, in case your component is something like this:
// using the new hooks API
function Comp(props) {
const { isLoading, data } = props;
useEffect(() => {
if (data) {
var name = document.getElementById('name').value;
}
}, [data]) // this diff is necessary
if (isLoading) return <div>isLoading</div>
return (
<div id='name'>Comp</div>
);
}
If diff is not performed then, you will get null
.
Use dataType: "jsonp"
. I had the same error before. It fixed for me.
You can say word.strip(" ")
to remove any leading/trailing spaces from the string - you should do that before your if
statement. That way if someone enters input such as " test "
your program will still work.
That said, if " " in word:
will determine if a string contains any spaces. If that does not working, can you please provide more information?
You have to create a new property (ex:selectedCountry) and should use it in [(ngModel)]
and further in component file assign default
value to it.
In your_component_file.ts
this.selectedCountry = default;
In your_component_template.html
<select id="country" formControlName="country" [(ngModel)]="selectedCountry">
<option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>
If all your trying to do is fill the div this might help someone else, if aspect ratio is not important, is responsive.
.img-fill > img {
min-height: 100%;
min-width: 100%;
}
@eldar: I had the same issue with 3.6.7 running in 'normal mode'; and neither triggerSave or save() were working.
I changed to the jQuery TinyMCE plugin and without having to do anything else it's working now. I'm assuming somewhere along the line they implemented some kind of auto triggerSave for the jQuery version of TinyMCE.
The Externalizable interface was not actually provided to optimize the serialization process performance! but to provide means of implementing your own custom processing and offer complete control over the format and contents of the stream for an object and its super types!
Examples of this is the implementation of AMF (ActionScript Message Format) remoting to transfer native action script objects over the network.
Use the shell error handling for unset variables (note the double $
):
$ cat Makefile
foo:
echo "something is set to $${something:?}"
$ make foo
echo "something is set to ${something:?}"
/bin/sh: something: parameter null or not set
make: *** [foo] Error 127
$ make foo something=x
echo "something is set to ${something:?}"
something is set to x
If you need a custom error message, add it after the ?
:
$ cat Makefile
hello:
echo "hello $${name:?please tell me who you are via \$$name}"
$ make hello
echo "hello ${name:?please tell me who you are via \$name}"
/bin/sh: name: please tell me who you are via $name
make: *** [hello] Error 127
$ make hello name=jesus
echo "hello ${name:?please tell me who you are via \$name}"
hello jesus
This ScriptingGuy guest post links to a script by a Microsoft Powershell Expert can help you find this information, but to fully audit why it was locked and which machine triggered the lock you probably need to turn on additional levels of auditing via GPO.
https://gallery.technet.microsoft.com/scriptcenter/Get-LockedOutLocation-b2fd0cab#content
Use speccy. It shows the installation date in Operating System section. http://www.piriform.com/speccy
Oddly. but in my experience TeamViewer is not faster/more responsive than VNC, only easier to setup. I have a couple of win-boxen that I VNC over OpenVPN into (so there is another overhead layer) and that's on cheap Cable (512 up) and I find properly setup TightVNC to be much more responsive than TeamViewer to same boxen. RDP (naturally) even more so since by large part it sends GUI draw commands instead of bitmap tiles.
Which brings us to:
Why are you not using VNC? There are plethora of open source solutions, and Tight is probably on top of it's game right now.
Advanced VNC implementations use lossy compression and that seems to achieve better results than your choice of PNG. Also, IIRC the rest of the payload is also squashed using zlib. Bothj Tight and UltraVNC have very optimized algos, especially for windows. On top of that Tight is open-source.
If win boxen are your primary target RDP may be a better option, and has an opensource implementation (rdesktop)
If *nix boxen are your primary target NX may be a better option and has an open source implementation (FreeNX, albeit not as optimised as NoMachine's proprietary product).
If compressing JPEG is a performance issue for your algo, I'm pretty sure that image comparison would still take away some performance. I'd bet they use best-case compression for every specific situation ie lossy for large frames, some quick and dirty internall losless for smaller ones, compare bits of images and send only diffs of sort and bunch of other optimisation tricks.
And a lot of those tricks must be present in Tight > 2.0 since again, in my experience it beats the hell out of TeamViewer performance wyse, YMMV.
Also the choice of a JIT compiled runtime over something like C++ might take a slice from your performance edge, especially in memory constrained machines (a lot of performance tuning goes to the toilet when windows start using the pagefile intensively). And you will need memory to keep previous image states for internal comparison atop of what DF mirage gives you.
contentType
option to false
is used for multipart/form-data
forms that pass files.
When one sets the contentType
option to false
, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData
flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Use jQuery's .serialize()
method which creates a text string in standard URL-encoded notation.
You need to pass un-encoded data when using contentType: false
.
Try using new FormData
instead of .serialize():
var formData = new FormData($(this)[0]);
See for yourself the difference of how your formData is passed to your php page by using console.log()
.
var formData = new FormData($(this)[0]);
console.log(formData);
var formDataSerialized = $(this).serialize();
console.log(formDataSerialized);
Change Your Web.Config file as below
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV"/>
<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
<remove name="OPTIONSVerbHandler"/>
<remove name="TRACEVerbHandler"/>
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
If IsNull({TABLE.FIELD1}) then "NULL" +',' + {TABLE.FIELD2} else {TABLE.FIELD1} + ', ' + {TABLE.FIELD2}
Here I put NULL as string to display the string value NULL in place of the null value in the data field. Hope you understand.
This can happen when you are running IIS
and you run the html page through it, then the Local file system
will not be accessible.
To make your link work locally the run the calling html page directly from file browser not visual studio F5
or IIS
simply click it to open from the file system, and make sure you are using the link like this:
<a href="file:///F:/VS_2015_WorkSpace/Projects/xyz/Intro.html">Intro</a>
Note that if you installed RVM via apt-get, you have to run some further steps than rvm implode
or apt-get remove ruby-rvm
to get it to really uninstall.
See "Installing RVM on Ubuntu".
Bash alias for updating current active version:
alias nodeupdate='nvm install $(nvm current | sed -rn "s/v([[:digit:]]+).*/\1/p") --reinstall-packages-from=$(nvm current)'
The part sed -rn "s/v([[:digit:]]+).*/\1/p"
transforms output from nvm current
so that only a major version of node is returned, i.e.: v13.5.0
-> 13
.
Form1 frmnew = new Form1();
frmnew.ShowDialog();
source <(curl -s http://mywebsite.com/myscript.txt)
ought to do it. Alternately, leave off the initial redirection on yours, which is redirecting standard input; bash
takes a filename to execute just fine without redirection, and <(command)
syntax provides a path.
bash <(curl -s http://mywebsite.com/myscript.txt)
It may be clearer if you look at the output of echo <(cat /dev/null)
I've spoken to Tab Atkins (author of the flexbox spec) about this, and this is what we came up with:
HTML:
<div class="content">
<div class="box">
<div class="column">Column 1</div>
<div class="column">Column 2</div>
<div class="column">Column 3</div>
</div>
</div>
CSS:
.content {
flex: 1;
display: flex;
overflow: auto;
}
.box {
display: flex;
min-height: min-content; /* needs vendor prefixes */
}
Here are the pens:
The reason this works is because align-items: stretch
doesn't shrink its items if they have an intrinsic height, which is accomplished here by min-content
.
Just my 2 Cents here ..
Bootstrap.yml or Bootstrap.properties is used to fetch the config from Spring Cloud Server.
For Example, in My Bootstrap.properties file I have the following Config
spring.application.name=Calculation-service
spring.cloud.config.uri=http://localhost:8888
On starting the application , It tries to fetch the configuration for the service by connecting to http://localhost:8888 and looks at Calculation-service.properties present in Spring Cloud Config server
You can validate the same from logs of Calcuation-Service when you start it up
INFO 10988 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
You can also use Sugar.
Date.create().reset().set({seconds: 180}).format('{mm}:{ss}');
This example returns '03:00'.
Starting from Django 2.2, you can use request.headers
to access the HTTP headers. From the documentation on HttpRequest.headers:
A case insensitive, dict-like object that provides access to all HTTP-prefixed headers (plus Content-Length and Content-Type) from the request.
The name of each header is stylized with title-casing (e.g. User-Agent) when it’s displayed. You can access headers case-insensitively:
>>> request.headers {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...} >>> 'User-Agent' in request.headers True >>> 'user-agent' in request.headers True >>> request.headers['User-Agent'] Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) >>> request.headers['user-agent'] Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) >>> request.headers.get('User-Agent') Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) >>> request.headers.get('user-agent') Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
To get all headers, you can use request.headers.keys()
or request.headers.items()
.
No. The only you can do is to add content (and not an element) using :before
or :after
pseudo-element.
More information: http://www.w3.org/TR/CSS2/generate.html#before-after-content
Have you tried running npm config list
? And, if you want to see the defaults, run npm config ls -l
.
In Python 3.1+ you can specify multiple context expressions, and they will be processed as if multiple with
statements were nested:
with A() as a, B() as b:
suite
is equivalent to
with A() as a:
with B() as b:
suite
This also means that you can use the alias from the first expression in the second (useful when working with db connections/cursors):
with get_conn() as conn, conn.cursor() as cursor:
cursor.execute(sql)
Very simple -
npm config set registry https://path-to-your-registry/
It actually sets registry = "https://path-to-your-registry"
this line to /Users/<ur-machine-user-name>/.npmrc
All the value you have set explicitly or have been set by default can be seen by - npm config list
In my case I was modifying the request to append a header (using Fiddler) to an https
request, but I did not configure it to decrypt https traffic. You can export a manually-created certificate from Fiddler, so you can trust/import the certificate by your browsers. See above link for details, some steps include:
As with all good examples, you've simplified what you're actually trying to do. This is good, but it is worth noting that python has a lot of flexibility when it comes to class versus instance variables. The same can be said of methods. For a good list of possibilities, I recommend reading Michael Fötsch' new-style classes introduction, especially sections 2 through 6.
One thing that takes a lot of work to remember when getting started is that python is not java. More than just a cliche. In java, an entire class is compiled, making the namespace resolution real simple: any variables declared outside a method (anywhere) are instance (or, if static, class) variables and are implicitly accessible within methods.
With python, the grand rule of thumb is that there are three namespaces that are searched, in order, for variables:
{begin pedagogy}
There are limited exceptions to this. The main one that occurs to me is that, when a class definition is being loaded, the class definition is its own implicit namespace. But this lasts only as long as the module is being loaded, and is entirely bypassed when within a method. Thus:
>>> class A(object):
foo = 'foo'
bar = foo
>>> A.foo
'foo'
>>> A.bar
'foo'
but:
>>> class B(object):
foo = 'foo'
def get_foo():
return foo
bar = get_foo()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
class B(object):
File "<pyshell#11>", line 5, in B
bar = get_foo()
File "<pyshell#11>", line 4, in get_foo
return foo
NameError: global name 'foo' is not defined
{end pedagogy}
In the end, the thing to remember is that you do have access to any of the variables you want to access, but probably not implicitly. If your goals are simple and straightforward, then going for Foo.bar or self.bar will probably be sufficient. If your example is getting more complicated, or you want to do fancy things like inheritance (you can inherit static/class methods!), or the idea of referring to the name of your class within the class itself seems wrong to you, check out the intro I linked.
All of the examples here (with the exception of rockacola's) require that the user physically click on the window to define focus. This isn't ideal, so .hover()
is the better choice:
$(window).hover(function(event) {
if (event.fromElement) {
console.log("inactive");
} else {
console.log("active");
}
});
This'll tell you when the user has their mouse on the screen, though it still won't tell you if it's in the foreground with the user's mouse elsewhere.
you can go to the XML file
then focus your mouse cursor into your button, text view or whatever you choose for your layout, then press Alt + Enter
to fix it, after that the error will be gone.it works for me.
Try a different usb cable. My cable was bad. Charging was ok but did not attach the phone.
Facebook has a set of open-graph meta tags that it looks at to decide which image to show.
The keys one for the Facebook image are:
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
<meta property="og:image:secure_url" content="https://secure.example.com/ogp.jpg" />
and it should be present inside the <head></head>
tag at the top of your page.
If these tags are not present, it will look for their older method of specifying an image: <link rel="image_src" href="/myimage.jpg"/>
. If neither are present, Facebook will look at the content of your page and choose images from your page that meet its share image criteria: Image must be at least 200px by 200px, have a maximum aspect ratio of 3:1, and in PNG, JPEG or GIF format.
Can I specify multiple images to allow the user to select an image?
Yes, you just need to add multiple image meta tags in the order you want them to appear in. The user will then be presented with an image selector dialog:
I specified the appropriate image meta tags. Why isn't Facebook accepting the changes?
Once a url has been shared, Facebook's crawler, which has a user agent of facebookexternalhit/1.1 (+https://www.facebook.com/externalhit_uatext.php)
, will access your page and cache the meta information. To force Facebook servers to clear the cache, use the Facebook Url Debugger / Linter Tool that they launched in June 2010 to refresh the cache and troubleshoot any meta tag issues on your page.
Also, the images on the page must be publicly accessible to the Facebook crawler. You should specify absolute url's like http://example.com/yourimage.jpg instead of just /yourimage.jpg.
Can I update these meta tags with client side code like Javascript or jQuery? No. Much like search engine crawlers, the Facebook scraper does not execute scripts so whatever meta tags are present when the page is downloaded are the meta tags that are used for image selection.
Adding these tags causes my page to no longer validate. How can I fix this?
You can add the necessary Facebook namespaces to your tag and your page should then pass validation:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:og="http://ogp.me/ns#"
xmlns:fb="https://www.facebook.com/2008/fbml">
If anyone just wants to validate a bearer token in the authorize phase using the current security practices you can,
add this to your Startup/ConfigureServices
services.AddSingleton<IAuthorizationHandler, BearerAuthorizationHandler>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
services.AddAuthorization(options => options.AddPolicy("Bearer",
policy => policy.AddRequirements(new BearerRequirement())
)
);
and this in your codebase,
public class BearerRequirement : IAuthorizationRequirement
{
public async Task<bool> IsTokenValid(SomeValidationContext context, string token)
{
// here you can check if the token received is valid
return true;
}
}
public class BearerAuthorizationHandler : AuthorizationHandler<BearerRequirement>
{
public BearerAuthorizationHandler(SomeValidationContext thatYouCanInject)
{
...
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, BearerRequirement requirement)
{
var authFilterCtx = (Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)context.Resource;
string authHeader = authFilterCtx.HttpContext.Request.Headers["Authorization"];
if (authHeader != null && authHeader.Contains("Bearer"))
{
var token = authHeader.Replace("Bearer ", string.Empty);
if (await requirement.IsTokenValid(thatYouCanInject, token))
{
context.Succeed(requirement);
}
}
}
}
If the code doesn't reach context.Succeed(...)
it will Fail anyway (401).
And then in your controllers you can use
[Authorize(Policy = "Bearer", AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
may its so late but the response useful for others so :
Sometimes, when you don't specify a server or servlet container at the
creation of the project, NetBeans fails to create a context.xml
file.
META-INF
. Do this by right mouse button clicking on Web pages, and select:
New->Other->Other->File Folder
Name the folder META-INF
. Case is important, even on Windows.
context.xml
in the META-INF
folder. Do this by right mouse button clicking on the new META-INF
folder, and
select:
New->Other->XML->XML
Document
Name it context (NetBeans adds the .xml
)
Select Well-formed Document
Press Finish
Edit the new document (context.xml
), and add the following:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/app-name"/>
Replace app-name with the name of your application.
Now your in-place deployment should work. If not, make sure that the file can be read by everyone.
The context.xml
file is specific to Tomcat. For more information about
that file, see the Tomcat documentation at tomcat.apache.org
.
You can loop to create the String
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
}
String[] stringArray = list.toArray(new String[list.size()]);