Almost everything seems to be covered here already.. Adding just one more point on practical implementation of abstract
class:
abstract
keyword is also used just prevent a class from being instantiated. If you have a concrete class which you do not want to be instantiated - Make itabstract
.
Use usort:
usort($array, function($a1, $a2) {
$v1 = strtotime($a1['date']);
$v2 = strtotime($a2['date']);
return $v1 - $v2; // $v2 - $v1 to reverse direction
});
$("#availability option:selected").text();
This will give you the text value of your dropdown list. You can also use .val() instead of .text() depending on what you're looking to get. Follow the link to the jQuery documentation and examples.
The data URI format is:
data:<headers>;<encoding>,<data>
So, you need only append your data to the "data:image/jpeg;," string:
var your_binary_data = document.body.innerText.replace(/(..)/gim,'%$1'); // parse text data to URI format
window.open('data:image/jpeg;,'+your_binary_data);
You could use the ceiling
function; this portion of SQL code :
select ceiling(45.01), ceiling(45.49), ceiling(45.99);
will get you "46" each time.
For your update, so, I'd say :
Update product SET price = ceiling(45.01)
BTW : On MySQL, ceil
is an alias to ceiling
; not sure about other DB systems, so you might have to use one or the other, depending on the DB you are using...
Quoting the documentation :
CEILING(X)
Returns the smallest integer value not less than X.
And the given example :
mysql> SELECT CEILING(1.23);
-> 2
mysql> SELECT CEILING(-1.23);
-> -1
int x[] = { 10, 30, 15, 69, 52, 89, 5 };
int max, temp = 0, index = 0;
for (int i = 0; i < x.length; i++) {
int counter = 0;
max = x[i];
for (int j = i + 1; j < x.length; j++) {
if (x[j] > max) {
max = x[j];
index = j;
counter++;
}
}
if (counter > 0) {
temp = x[index];
x[index] = x[i];
x[i] = temp;
}
}
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
I found the solution. In the manifest file of the application I found the package name: com.package.address and the name of the main activity which I want to launch: MainActivity The following code starts this application:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.package.address","com.package.address.MainActivity"));
startActivity(intent);
The purpose of a view is to use the query over and over again. To that end, SQL Server, Oracle, etc. will typically provide a "cached" or "compiled" version of your view, thus improving its performance. In general, this should perform better than a "simple" query, though if the query is truly very simple, the benefits may be negligible.
Now, if you're doing a complex query, create the view.
There are a to of situations where the above CSS solutions do not work. For instance a transparent fixed header and a sticky footer on the same page. To prevent the top bounce in safari messing things and causing flashes on full screen sliders, you can use this.
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
$window.bind('mousewheel', function(e) {
if (e.originalEvent.wheelDelta / 120 > 0) {
if ($window.scrollTop() < 2) return false;
}
});
}
Here's some more detailed information on what Client, Resource, and Session are all about.
Client:
Here's an example of client-level access to an S3 bucket's objects (at most 1000**):
import boto3
client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
print(content['Key'], obj_dict['LastModified'])
** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.
Resource:
Here's the equivalent example using resource-level access to an S3 bucket's objects (all):
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
print(obj.key, obj.last_modified)
Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.
You can see that the Resource
version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client
version of the code would actually be more complicated than shown above if you wanted to include pagination.
Session:
A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.
It stands for Representational State Transfer and it can mean a lot of things, but usually when you are talking about APIs and applications, you are talking about REST as a way to do web services or get programs to talk over the web.
REST is basically a way of communicating between systems and does much of what SOAP RPC was designed to do, but while SOAP generally makes a connection, authenticates and then does stuff over that connection, REST works pretty much the same way that that the web works. You have a URL and when you request that URL you get something back. This is where things start getting confusing because people describe the web as a the largest REST application and while this is technically correct it doesn't really help explain what it is.
In a nutshell, REST allows you to get two applications talking over the Internet using tools that are similar to what a web browser uses. This is much simpler than SOAP and a lot of what REST does is says, "Hey, things don't have to be so complex."
Worth reading:
Olof's answer is good, but it needs one more thing before it's perfect. In the comments below his answer, dacwe (correctly) points out that his implementation violates the Compare/Equals contract for Sets. If you try to call contains or remove on an entry that's clearly in the set, the set won't recognize it because of the code that allows entries with equal values to be placed in the set. So, in order to fix this, we need to test for equality between the keys:
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
if (e1.getKey().equals(e2.getKey())) {
return res; // Code will now handle equality properly
} else {
return res != 0 ? res : 1; // While still adding all entries
}
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
"Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface... the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal." (http://docs.oracle.com/javase/6/docs/api/java/util/SortedSet.html)
Since we originally overlooked equality in order to force the set to add equal valued entries, now we have to test for equality in the keys in order for the set to actually return the entry you're looking for. This is kinda messy and definitely not how sets were intended to be used - but it works.
After verifying:
Still col-lg, col-md, and col-sm were not working. Finally I moved the references to bootstrap to be before the references to html5shiv.js and respond.js and it all worked.
Here is a snippet:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap Test for IE8</title>
<!-- Moved these two lines up -->
<link href="includes/css/bootstrap.css" type="text/css" rel="stylesheet" />
<script src="includes/js/bootstrap.js"></script>
<!--[if lt IE 9]>
<script src="includes/js/html5shiv.js"></script>
<script src="includes/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4" style="background-color:red;">col-md-4</div>
<div class="col-md-8" style="background-color:green;">col-md-8</div>
</div>
</div>
</body>
</html>
IMHO there is not a better explanation than the fact about How was the first compiler written?
These days the Operating System loading is the most common process referred as Bootstrapping
Check out std::isdigit()
function.
In your code:
while(fscanf(fp,"%s %c",item,&status) == 1)
why 1 and not 2? The scanf functions return the number of objects read.
Another way to encounter this error is from a dataset with unnamed columns. The error is thrown when the dataset is serialized into JSON.
This statement will result in error:
select @column1, @column2
Adding column names will prevent the error:
select @column1 as col1, @column2 as col2
Bootstrap 4:
<div class="w-100"></div>
Source: https://v4-alpha.getbootstrap.com/layout/grid/#equal-width-multi-row
using (var cmd = new SqlCommand("SELECT EmpName FROM [Employee] WHERE EmpID = @id", con))
put []
around table name ;)
No need to create overload methods, just use one single method with params as shown below
// Call params method with one to four integer constant parameters.
//
int sum0 = addTwoEach();
int sum1 = addTwoEach(1);
int sum2 = addTwoEach(1, 2);
int sum3 = addTwoEach(3, 3, 3);
int sum4 = addTwoEach(2, 2, 2, 2);
Example from the numpy documentation:
>>> a = numpy.array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> numpy.delete(a, numpy.s_[1:3], axis=0) # remove rows 1 and 2
array([[ 0, 1, 2, 3],
[12, 13, 14, 15]])
>>> numpy.delete(a, numpy.s_[1:3], axis=1) # remove columns 1 and 2
array([[ 0, 3],
[ 4, 7],
[ 8, 11],
[12, 15]])
There may be a problem with the video adapter. At least that's what I had. I picked up problems immediately after updating Windows 10 to the 2004 version. Disabling hardware graphics — solved the problem.
https://www.reddit.com/r/sysadmin/comments/gz6chp/rdp_issues_on_2004_update/
For posterity: you can also use classes to achieve something similar. For instance:
class Function_Wrapper():
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
def func(self):
return self.x + self.y + self.z # execute function
Button can then be simply created by:
instance1 = Function_Wrapper(x, y, z)
button1 = Button(master, text = "press", command = instance1.func)
This approach also allows you to change the function arguments by i.e. setting instance1.x = 3
.
Giving you the complete answer would have no point at all since this is homework, so here are a few pointers :
Even or Odd:
number % 2 == 0
definitely is a very good way to find whether your number is even.
In case you do not know %
, this does modulo which is here the remainder of the division of number
by 2
. http://en.wikipedia.org/wiki/Modulo_operation
Printing the pyramid:
First advice: In order to print *****
, you can do print "*" * 5
.
Second advice: In order to center the asterisks, you need to find out how many spaces to write before the asterisks. Then you can print a bunch of spaces and asterisks with print " "*1 + "*"*3
Put this in your html body (taken from the official angular.js website):
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
I believe that you were using some older angular.js files since you don't have any issues in plunker and therefore you got the specified error.
Open the Developer tools in your browser and just try the code shown in the below image.
Here is the official FAQ on installing Python Modules: http://docs.python.org/install/index.html
There are some tips which might help you.
Maybe it's a coincidence that the column order you want happens to have column names in descending alphabetical order. Since that's the case you could just do:
df<-df[,order(colnames(df),decreasing=TRUE)]
That's what I use when I have large files with many columns.
In Spark 2.0 (I didn't tested with earlier versions). Simply:
print myRDD.take(n)
Where n is the number of lines and myRDD is wc in your case.
I needed this same solution, but if you use the native ListObject.Add()
method then you avoid the risk of clashing with any data immediately below the table. The below routine checks the last row of the table, and adds the data in there if it's blank; otherwise it adds a new row to the end of the table:
Sub AddDataRow(tableName As String, values() As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = ActiveWorkbook.Worksheets("Sheet1")
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
For col = 1 To lastRow.Columns.Count
If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
table.ListRows.Add
Exit For
End If
Next col
Else
table.ListRows.Add
End If
'Iterate through the last row and populate it with the entries from values()
Set lastRow = table.ListRows(table.ListRows.Count).Range
For col = 1 To lastRow.Columns.Count
If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
Next col
End Sub
To call the function, pass the name of the table and an array of values, one value per column. You can get / set the name of the table from the Design
tab of the ribbon, in Excel 2013 at least:
Example code for a table with three columns:
Dim x(2)
x(0) = 1
x(1) = "apple"
x(2) = 2
AddDataRow "Table1", x
Adapted from this answer to a very similar question:
FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"
You should run this command from within your d:\study
folder. It will delete all subfolders which are older than 10 days.
The /S /Q
after the rd
makes it delete folders even if they are not empty, without prompting.
I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat
.
It seems you are hitting a UTF-8 byte order mark (BOM). Try using this unicode string with BOM extracted out:
import codecs
content = unicode(q.content.strip(codecs.BOM_UTF8), 'utf-8')
parser.parse(StringIO.StringIO(content))
I used strip
instead of lstrip
because in your case you had multiple occurences of BOM, possibly due to concatenated file contents.
You can add a watchpoint for each variable you're interested in.
A watchpoint is a special breakpoint that stops the execution of an application whenever the value of a given expression changes, without specifying where it might occur. Unlike breakpoints (which are line-specific), watchpoints are associated with files. They take effect whenever a specified condition is true, regardless of when or where it occurred. You can set a watchpoint on a global variable by highlighting the variable in the editor, or by selecting it in the Outline view.
Use a regular expression on a string:
def is_numeric?(obj)
obj.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
end
If you want to check if a variable is of certain type, you can simply use kind_of?
:
1.kind_of? Integer #true
(1.5).kind_of? Float #true
is_numeric? "545" #true
is_numeric? "2aa" #false
I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.
Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.
After this, Windows started prioritize Ethernet adapter.
exec is for statement and does not return anything. eval is for expression and returns value of expression.
expression means "something" while statement means "do something".
Try
adb root
adb remount
to start the adb demon as root and ensure partitions are mounted in read-write mode (the essential part is adb root
). After push
ing, revoke root permissions again using:
adb unroot
Amazing there is no '$0' type structure in R! You can do it with a system() call to a bash script written in R:
write.table(c("readlink -e $0"), file="scriptpath.sh",col=F, row=F, quote=F)
thisscript <- system("sh scriptpath.sh", intern = TRUE)
Then just split out the scriptpath.sh name for other.R
splitstr <- rev(strsplit(thisscript, "\\/")[[1]])
otherscript <- paste0(paste(rev(splitstr[2:length(splitstr)]),collapse="/"),"/other.R")
Worth mentioning
If you want to have a list of all classes under some package, you can use Reflection
the following way:
List<Class> myTypes = new ArrayList<>();
Reflections reflections = new Reflections("com.package");
for (String s : reflections.getStore().get(SubTypesScanner.class).values()) {
myTypes.add(Class.forName(s));
}
This will create a list of classes that later you can use them as you wish.
You can also have a look at FLTK (C++ and not plain C though)
FLTK (pronounced "fulltick") is a cross-platform C++ GUI toolkit for UNIX®/Linux® (X11), Microsoft® Windows®, and MacOS® X. FLTK provides modern GUI functionality without the bloat and supports 3D graphics via OpenGL® and its built-in GLUT emulation.
FLTK is designed to be small and modular enough to be statically linked, but works fine as a shared library. FLTK also includes an excellent UI builder called FLUID that can be used to create applications in minutes.
Here are some quickstart screencasts
[Happy New Year!]
I used apt-cache depends package
to get all required packages in any case if the are already installed on system or not.
So it will work always correct.
Because the command apt-cache works different, depending on language, you have to try this command on your system and adapt the command.
apt-cache depends yourpackage
On an englisch system you get:
$ apt-cache depends yourpackage
node
Depends: libax25
Depends: libc6
On an german system you get:
node
Hängt ab von: libax25
Hängt ab von: libc6
The englisch version with the term:
"Depends:
"
You have to change the term "yourpackage
" to your wish twice in this command, take care of this!
$ sudo apt-get --print-uris --yes -d --reinstall install yourpackage $(apt-cache depends yourpackage | grep " Depends:" | sed 's/ Depends://' | sed ':a;N;$!ba;s/\n//g') | grep ^\' | cut -d\' -f2 >downloads.list
And the german version with the term:
"Hängt ab von:
"
You have to change the term "yourpackage
" to your wish twice in this command, take care of this!
This text is used twice in this command, if you want to adapt it to your language take care of this!
$ sudo apt-get --print-uris --yes -d --reinstall install yourpackage $(apt-cache depends yourpackage | grep "Hängt ab von:" | sed 's/ Hängt ab von://' | sed ':a;N;$!ba;s/\n//g') | grep ^\' | cut -d\' -f2 >downloads.list
You get the list of links in downloads.list
Check the list, go to your folder and run the list:
$ cd yourpathToYourFolder
$ wget --input-file downloads.list
All your required packages are in:
$ ls yourpathToYourFolder
What about the ansicolors library? You can simple do:
from colors import color, red, blue
# common colors
print(red('This is red'))
print(blue('This is blue'))
# colors by name or code
print(color('Print colors by name or code', 'white', '#8a2be2'))
If you can re-structure your code so that you do not need to postback, then you can use this code in the PreRender event of the button:
protected void MyButton_OnPreRender(object sender, EventArgs e)
{
string URL = "~/MyPage.aspx";
URL = Page.ResolveClientUrl(URL);
MyButton.OnClientClick = "window.open('" + URL + "'); return false;";
}
I see this has been answered; however, I feel this link provides appropriate information for what formatting is supported in various email clients.
http://www.campaignmonitor.com/css/
It's worth noting that GMail and Outlook are two of the pickiest to format HTML email for.
Basically, the first model you are using is called as document-based storage. You should have a look at popular NoSQL document-based database like MongoDB and CouchDB. Basically, in document based db's, you store data in json files and then you can query on these json files.
The Second model is the popular relational database structure.
If you want to use relational database like MySql then i would suggest you to only use second model. There is no point in using MySql and storing data as in the first model.
To answer your second question, there is no way to query name like 'foo' if you use first model.
You can use file prefix to load the external application context file some thing like this
<context:property-placeholder location="file:///C:/Applications/external/external.properties"/>
Possible duplicate of Limit text length of EditText in Android
Use android:maxLength="140"
That should work. :)
Hope that helps
YAJSW (Yet Another Java Service Wrapper) looks like it has JNA-based implementations of its org.rzo.yajsw.os.TaskList interface for win32, linux, bsd and solaris and is under an LGPL license. I haven't tried calling this code directly, but YAJSW works really well when I've used it in the past, so you shouldn't have too many worries.
you can test a color by writing the CSS inline like <div style="color:red";>...</div>
use this one:
from django.urls import reverse
UPDATE: .NET Core 3.0 and .NET Standard 2.1 has shipped with this type.
Good news! A pull request adding System.Globalization.ISOWeek
to .NET Core was just merged and is currently slated for the 3.0 release. Hopefully it will propagate to the other .NET platforms in a not-too-distant future.
You should be able to use the ISOWeek.ToDateTime(int year, int week, DayOfWeek dayOfWeek)
method to calculate this.
You can find the source code here.
You can also generate source code from schema using jaxb2-maven-plugin plugin:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<sources>
<source>src/main/resources/your_schema.xsd</source>
</sources>
<xjbSources>
<xjbSource>src/main/resources/bindings.xjb</xjbSource>
</xjbSources>
<packageName>some_package</packageName>
<outputDirectory>src/main/java</outputDirectory>
<clearOutputDir>false</clearOutputDir>
<generateEpisode>false</generateEpisode>
<noGeneratedHeaderComments>true</noGeneratedHeaderComments>
</configuration>
</plugin>
As @pcans suggested you can do this overriding dispatchTouchEvent(MotionEvent event)
in your activity.
Here we get the touch coordinates and comparing them to view bounds. If touch is performed outside of a view then do something.
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View yourView = (View) findViewById(R.id.view_id);
if (yourView != null && yourView.getVisibility() == View.VISIBLE) {
// touch coordinates
int touchX = (int) event.getX();
int touchY = (int) event.getY();
// get your view coordinates
final int[] viewLocation = new int[2];
yourView.getLocationOnScreen(viewLocation);
// The left coordinate of the view
int viewX1 = viewLocation[0];
// The right coordinate of the view
int viewX2 = viewLocation[0] + yourView.getWidth();
// The top coordinate of the view
int viewY1 = viewLocation[1];
// The bottom coordinate of the view
int viewY2 = viewLocation[1] + yourView.getHeight();
if (!((touchX >= viewX1 && touchX <= viewX2) && (touchY >= viewY1 && touchY <= viewY2))) {
Do what you want...
// If you don't want allow touch outside (for example, only hide keyboard or dismiss popup)
return false;
}
}
}
return super.dispatchTouchEvent(event);
}
Also it's not necessary to check view existance and visibility if your activity's layout doesn't change during runtime (e.g. you don't add fragments or replace/remove views from the layout). But if you want to close (or do something similiar) custom context menu (like in the Google Play Store when using overflow menu of the item) it's necessary to check view existance. Otherwise you will get a NullPointerException
.
It took me ages to work this one out, so for the benefit of searchers:
I had a bizarre issue whereby the application worked in debug, but gave the XamlParseException
once released.
After fixing the x86/x64 issue as detailed by Katjoek, the issue remained.
The issue was that a CEF tutorial said to bring down System.Windows.Interactivity
from NuGet (even thought it's in the Extensions section of references in .NET) and bringing down from NuGet sets specific version
to true
.
Once deployed, a different version of System.Windows.Interactivity
was being packed by a different application.
It's refusal to use a different version of the dll caused the whole application to crash with XamlParseException
.
The META-INF folder is the home for the MANIFEST.MF file. This file contains meta data about the contents of the JAR. For example, there is an entry called Main-Class that specifies the name of the Java class with the static main() for executable JAR files.
Few Days ago i had the similar requirement of getting multiple return values from a function that i created.
From many return values , i needed it to return only specific value for a given condition and then other return value corresponding to other condition.
Here is the Example of how i did that :
Function:
function myTodayDate(){
var today = new Date();
var day = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var myTodayObj =
{
myDate : today.getDate(),
myDay : day[today.getDay()],
myMonth : month[today.getMonth()],
year : today.getFullYear()
}
return myTodayObj;
}
Getting Required return value from object returned by function :
var todayDate = myTodayDate().myDate;
var todayDay = myTodayDate().myDay;
var todayMonth = myTodayDate().myMonth;
var todayYear = myTodayDate().year;
The whole point of answering this question is to share this approach of getting Date in good format. Hope it helped you :)
My Solution is given below here searchDetail is an object..
<p-calendar [ngModel]="searchDetail.queryDate | date:'MM/dd/yyyy'" (ngModelChange)="searchDetail.queryDate=$event" [showIcon]="true" required name="queryDate" placeholder="Enter the Query Date"></p-calendar>
<input id="float-input" type="text" size="30" pInputText [ngModel]="searchDetail.systems | json" (ngModelChange)="searchDetail.systems=$event" required='true' name="systems"
placeholder="Enter the Systems">
You can do the following to learn/test the concept:
Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module
In newly added Module1 add the declaration; Public Global1 As String
in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:
Sub setMe() Global1 = "Hello" End Sub
Sub showMe() Debug.Print (Global1) End Sub
setMe()
and then Sub showMe()
to test the global visibility/accessibility of the var Global1
Hope this will help.
Tomcat can work in 2 modes:
Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol
parameter in the server.xml
file.
HTTP/1.1
or org.apache.coyote.http11.Http11Protocol
org.apache.coyote.http11.Http11NioProtocol
If you're using BIO then I believe they should be more or less the same.
If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.
Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/
It uses setSelectionRange if supported, else has a solid fallback.
jQuery.fn.putCursorAtEnd = function() {
return this.each(function() {
$(this).focus()
// If this function exists...
if (this.setSelectionRange) {
// ... then use it (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
} else {
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
Then you can just do:
input.putCursorAtEnd();
if you're looking for a simple column hide you can use the :nth-child selector as well.
#tableid tr td:nth-child(3),
#tableid tr th:nth-child(3) {
display: none;
}
I use this with the @media tag sometimes to condense wider tables when the screen is too narrow.
The select box arrow is a native ui element, it depends on the desktop theme or the web browser. Use a jQuery plugin (e.g. Select2, Chosen) or CSS.
http://closure-compiler.appspot.com/home will pick this error up with an accurate reference to the actual line number in the offending script.
Yes to your second and third questions -- that's what you need to do as you cannot have multiple 'lvalues' on the left of an assignment.
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
You need to import not only your secret key, but also the corresponding public key, or you'll get this error.
Don't really think there is some direct method to get the last day but you could do something like this:
var dateInst = new moment();
/**
* adding 1 month from the present month and then subtracting 1 day,
* So you would get the last day of this month
*/
dateInst.add(1, 'months').date(1).subtract(1, 'days');
/* printing the last day of this month's date */
console.log(dateInst.format('YYYY MM DD'));
The benefit of write-through to main memory is that it simplifies the design of the computer system. With write-through, the main memory always has an up-to-date copy of the line. So when a read is done, main memory can always reply with the requested data.
If write-back is used, sometimes the up-to-date data is in a processor cache, and sometimes it is in main memory. If the data is in a processor cache, then that processor must stop main memory from replying to the read request, because the main memory might have a stale copy of the data. This is more complicated than write-through.
Also, write-through can simplify the cache coherency protocol because it doesn't need the Modify state. The Modify state records that the cache must write back the cache line before it invalidates or evicts the line. In write-through a cache line can always be invalidated without writing back since memory already has an up-to-date copy of the line.
One more thing - on a write-back architecture software that writes to memory-mapped I/O registers must take extra steps to make sure that writes are immediately sent out of the cache. Otherwise writes are not visible outside the core until the line is read by another processor or the line is evicted.
I got this when I did composer update
instead of composer install
.
You can initialize it just like any list:
public List<ContactNumber> ContactNumbers { get; set; }
public Human(int id)
{
Id = id;
ContactNumbers = new List<ContactNumber>();
}
public Human(int id, string address, string name) :this(id)
{
Address = address;
Name = name;
// no need to initialize the list here since you're
// already calling the single parameter constructor
}
However, I would even go a step further and make the setter private since you often don't need to set the list, but just access/modify its contents:
public List<ContactNumber> ContactNumbers { get; private set; }
Primary key mainly prevent duplication and shows the uniqueness of columns Foreign key mainly shows relationship on two tables
It's running every minute of the hour 22 I guess. Try the following to run it every first minute of the hour 22:
0 22 * * * ....
if (navigator.geolocation) { //Checks if browser supports geolocation
navigator.geolocation.getCurrentPosition(function (position) {
var latitude = position.coords.latitude; //users current
var longitude = position.coords.longitude; //location
var coords = new google.maps.LatLng(latitude, longitude); //Creates variable for map coordinates
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = //Sets map options
{
zoom: 15, //Sets zoom level (0-21)
center: coords, //zoom in on users location
mapTypeControl: true, //allows you to select map type eg. map or satellite
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL //sets map controls size eg. zoom
},
mapTypeId: google.maps.MapTypeId.ROADMAP //sets type of map Options:ROADMAP, SATELLITE, HYBRID, TERRIAN
};
map = new google.maps.Map( /*creates Map variable*/ document.getElementById("map"), mapOptions /*Creates a new map using the passed optional parameters in the mapOptions parameter.*/);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
origin: coords,
destination: 'BT42 1FL',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
});
}
Assuming that you're looking for "numbers that start with 7" rather than "strings that start with 7," maybe something like
select * from books where convert(char(32), book_id) like '7%'
Or whatever the Postgres equivalent of convert is.
public static Date convertTimestampToDate(Timestamp timestamp) {
Instant ins=timestamp.toLocalDateTime().atZone(ZoneId.systemDefault()).toInstant();
return Date.from(ins);
}
Daemon threads are as everybody explained, will not constrain JVM to exit, so basically its a happy thread for Application from exit point of view.
Want to add that daemon threads can be used when say I'm providing an API like pushing data to a 3rd party server / or JMS, I might need to aggregate data at the client JVM level and then send to JMS in a separate thread. I can make this thread as daemon thread, if this is not a mandatory data to be pushed to server. This kind of data is like log push / aggregation.
Regards, Manish
This worked for me to get domain in intranet
https://gist.github.com/jrothmanshore/2656003
It's a powershell script. Run it in PowerShell
.\ip_lookup.ps1 <ip>
#!/usr/bin/env python
import inspect
import os
import sys
def get_script_dir(follow_symlinks=True):
if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze
path = os.path.abspath(sys.executable)
else:
path = inspect.getabsfile(get_script_dir)
if follow_symlinks:
path = os.path.realpath(path)
return os.path.dirname(path)
print(get_script_dir())
It works on CPython, Jython, Pypy. It works if the script is executed using execfile()
(sys.argv[0]
and __file__
-based solutions would fail here). It works if the script is inside an executable zip file (/an egg). It works if the script is "imported" (PYTHONPATH=/path/to/library.zip python -mscript_to_run
) from a zip file; it returns the archive path in this case. It works if the script is compiled into a standalone executable (sys.frozen
). It works for symlinks (realpath
eliminates symbolic links). It works in an interactive interpreter; it returns the current working directory in this case.
FOR WINDOWS:
In my case, I was working on Windows OS and I got the same error while running autoconf.
Then I converted the File with EOL conversion into Windows (CR LF) as follows:
EDIT -> EOL CONVERSION -> WINDOWS (CR LF)
In my case I use this
var key=dict.FirstOrDefault(m => m.Value == s).Key;
dict.Remove(key);
Sorry, but none of the previous solutions helped me. I need to check both sides: SecurityManager and SO permissions. I have learned a lot with Josh code and with iain answer, but I'm afraid I need to use Rakesh code (also thanks to him). Only one bug: I found that he only checks for Allow and not for Deny permissions. So my proposal is:
string folder;
AuthorizationRuleCollection rules;
try {
rules = Directory.GetAccessControl(folder)
.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
} catch(Exception ex) { //Posible UnauthorizedAccessException
throw new Exception("No permission", ex);
}
var rulesCast = rules.Cast<FileSystemAccessRule>();
if(rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Deny)
|| !rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Allow))
throw new Exception("No permission");
//Here I have permission, ole!
list(set(df[['Col1', 'Col2']].as_matrix().reshape((1,-1)).tolist()[0]))
The output will be ['Mary', 'Joe', 'Steve', 'Bob', 'Bill']
If you use same color for whole program , you can define printf()
function.
#include<stdio.h>
#define ah_red "\e[31m"
#define printf(X) printf(ah_red "%s",X);
#int main()
{
printf("Bangladesh");
printf("\n");
return 0;
}
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
Gathering solutions from multiple places here on StackOverflow, I think the next one sums it up:
If you don't need the keyboard to be shown anywhere on your activity, you can simply use the next flags which are used for dialogs (got from here) :
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
If you don't want it only for a specific EditText, you can use this (got from here) :
public static boolean disableKeyboardForEditText(@NonNull EditText editText) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
editText.setShowSoftInputOnFocus(false);
return true;
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
try {
final Method method = EditText.class.getMethod("setShowSoftInputOnFocus", new Class[]{boolean.class});
method.setAccessible(true);
method.invoke(editText, false);
return true;
} catch (Exception ignored) {
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
try {
Method method = TextView.class.getMethod("setSoftInputShownOnFocus", boolean.class);
method.setAccessible(true);
method.invoke(editText, false);
return true;
} catch (Exception ignored) {
}
return false;
}
Or this (taken from here) :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
editText.setShowSoftInputOnFocus(false);
else
editText.setTextIsSelectable(true);
You can use:
print df.columns[5:]
Index([u'2004', u'2005', u'2006', u'2007', u'2008', u'2009', u'2010', u'2011',
u'2012', u'2013', u'2014'],
dtype='object')
for col in df.columns[5:]:
df[col] = pd.to_numeric(df[col], errors='coerce')
print df
GeoName ComponentName IndustryId IndustryClassification \
37926 Alabama Real GDP by state 9 213
37951 Alabama Real GDP by state 34 42
37932 Alabama Real GDP by state 15 327
Description 2004 2005 2006 2007 \
37926 Support activities for mining 99 98 117 117
37951 Wholesale trade 9898 10613 10952 11034
37932 Nonmetallic mineral products manufacturing 980 968 940 1084
2008 2009 2010 2011 2012 2013 2014
37926 115 87 96 95 103 102 NaN
37951 11075 9722 9765 9703 9600 9884 10199.0
37932 861 724 714 701 589 641 NaN
Another solution with filter
:
print df.filter(like='20')
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
37926 99 98 117 117 115 87 96 95 103 102 (NA)
37951 9898 10613 10952 11034 11075 9722 9765 9703 9600 9884 10199
37932 980 968 940 1084 861 724 714 701 589 641 (NA)
for col in df.filter(like='20').columns:
df[col] = pd.to_numeric(df[col], errors='coerce')
print df
GeoName ComponentName IndustryId IndustryClassification \
37926 Alabama Real GDP by state 9 213
37951 Alabama Real GDP by state 34 42
37932 Alabama Real GDP by state 15 327
Description 2004 2005 2006 2007 \
37926 Support activities for mining 99 98 117 117
37951 Wholesale trade 9898 10613 10952 11034
37932 Nonmetallic mineral products manufacturing 980 968 940 1084
2008 2009 2010 2011 2012 2013 2014
37926 115 87 96 95 103 102 NaN
37951 11075 9722 9765 9703 9600 9884 10199.0
37932 861 724 714 701 589 641 NaN
A bit late, but for the record.
You can achieve smooth lines by using cardinal splines (aka canonical spline) to draw smooth curves that goes through the points.
I made this function for canvas - it's split into three function to increase versatility. The main wrapper function looks like this:
function drawCurve(ctx, ptsa, tension, isClosed, numOfSegments, showPoints) {
showPoints = showPoints ? showPoints : false;
ctx.beginPath();
drawLines(ctx, getCurvePoints(ptsa, tension, isClosed, numOfSegments));
if (showPoints) {
ctx.stroke();
ctx.beginPath();
for(var i=0;i<ptsa.length-1;i+=2)
ctx.rect(ptsa[i] - 2, ptsa[i+1] - 2, 4, 4);
}
}
To draw a curve have an array with x, y points in the order: x1,y1, x2,y2, ...xn,yn
.
Use it like this:
var myPoints = [10,10, 40,30, 100,10]; //minimum two points
var tension = 1;
drawCurve(ctx, myPoints); //default tension=0.5
drawCurve(ctx, myPoints, tension);
The function above calls two sub-functions, one to calculate the smoothed points. This returns an array with new points - this is the core function which calculates the smoothed points:
function getCurvePoints(pts, tension, isClosed, numOfSegments) {
// use input value if provided, or use a default value
tension = (typeof tension != 'undefined') ? tension : 0.5;
isClosed = isClosed ? isClosed : false;
numOfSegments = numOfSegments ? numOfSegments : 16;
var _pts = [], res = [], // clone array
x, y, // our x,y coords
t1x, t2x, t1y, t2y, // tension vectors
c1, c2, c3, c4, // cardinal points
st, t, i; // steps based on num. of segments
// clone array so we don't change the original
//
_pts = pts.slice(0);
// The algorithm require a previous and next point to the actual point array.
// Check if we will draw closed or open curve.
// If closed, copy end points to beginning and first points to end
// If open, duplicate first points to befinning, end points to end
if (isClosed) {
_pts.unshift(pts[pts.length - 1]);
_pts.unshift(pts[pts.length - 2]);
_pts.unshift(pts[pts.length - 1]);
_pts.unshift(pts[pts.length - 2]);
_pts.push(pts[0]);
_pts.push(pts[1]);
}
else {
_pts.unshift(pts[1]); //copy 1. point and insert at beginning
_pts.unshift(pts[0]);
_pts.push(pts[pts.length - 2]); //copy last point and append
_pts.push(pts[pts.length - 1]);
}
// ok, lets start..
// 1. loop goes through point array
// 2. loop goes through each segment between the 2 pts + 1e point before and after
for (i=2; i < (_pts.length - 4); i+=2) {
for (t=0; t <= numOfSegments; t++) {
// calc tension vectors
t1x = (_pts[i+2] - _pts[i-2]) * tension;
t2x = (_pts[i+4] - _pts[i]) * tension;
t1y = (_pts[i+3] - _pts[i-1]) * tension;
t2y = (_pts[i+5] - _pts[i+1]) * tension;
// calc step
st = t / numOfSegments;
// calc cardinals
c1 = 2 * Math.pow(st, 3) - 3 * Math.pow(st, 2) + 1;
c2 = -(2 * Math.pow(st, 3)) + 3 * Math.pow(st, 2);
c3 = Math.pow(st, 3) - 2 * Math.pow(st, 2) + st;
c4 = Math.pow(st, 3) - Math.pow(st, 2);
// calc x and y cords with common control vectors
x = c1 * _pts[i] + c2 * _pts[i+2] + c3 * t1x + c4 * t2x;
y = c1 * _pts[i+1] + c2 * _pts[i+3] + c3 * t1y + c4 * t2y;
//store points in array
res.push(x);
res.push(y);
}
}
return res;
}
And to actually draw the points as a smoothed curve (or any other segmented lines as long as you have an x,y array):
function drawLines(ctx, pts) {
ctx.moveTo(pts[0], pts[1]);
for(i=2;i<pts.length-1;i+=2) ctx.lineTo(pts[i], pts[i+1]);
}
var ctx = document.getElementById("c").getContext("2d");_x000D_
_x000D_
_x000D_
function drawCurve(ctx, ptsa, tension, isClosed, numOfSegments, showPoints) {_x000D_
_x000D_
ctx.beginPath();_x000D_
_x000D_
drawLines(ctx, getCurvePoints(ptsa, tension, isClosed, numOfSegments));_x000D_
_x000D_
if (showPoints) {_x000D_
ctx.beginPath();_x000D_
for(var i=0;i<ptsa.length-1;i+=2) _x000D_
ctx.rect(ptsa[i] - 2, ptsa[i+1] - 2, 4, 4);_x000D_
}_x000D_
_x000D_
ctx.stroke();_x000D_
}_x000D_
_x000D_
_x000D_
var myPoints = [10,10, 40,30, 100,10, 200, 100, 200, 50, 250, 120]; //minimum two points_x000D_
var tension = 1;_x000D_
_x000D_
drawCurve(ctx, myPoints); //default tension=0.5_x000D_
drawCurve(ctx, myPoints, tension);_x000D_
_x000D_
_x000D_
function getCurvePoints(pts, tension, isClosed, numOfSegments) {_x000D_
_x000D_
// use input value if provided, or use a default value _x000D_
tension = (typeof tension != 'undefined') ? tension : 0.5;_x000D_
isClosed = isClosed ? isClosed : false;_x000D_
numOfSegments = numOfSegments ? numOfSegments : 16;_x000D_
_x000D_
var _pts = [], res = [], // clone array_x000D_
x, y, // our x,y coords_x000D_
t1x, t2x, t1y, t2y, // tension vectors_x000D_
c1, c2, c3, c4, // cardinal points_x000D_
st, t, i; // steps based on num. of segments_x000D_
_x000D_
// clone array so we don't change the original_x000D_
//_x000D_
_pts = pts.slice(0);_x000D_
_x000D_
// The algorithm require a previous and next point to the actual point array._x000D_
// Check if we will draw closed or open curve._x000D_
// If closed, copy end points to beginning and first points to end_x000D_
// If open, duplicate first points to befinning, end points to end_x000D_
if (isClosed) {_x000D_
_pts.unshift(pts[pts.length - 1]);_x000D_
_pts.unshift(pts[pts.length - 2]);_x000D_
_pts.unshift(pts[pts.length - 1]);_x000D_
_pts.unshift(pts[pts.length - 2]);_x000D_
_pts.push(pts[0]);_x000D_
_pts.push(pts[1]);_x000D_
}_x000D_
else {_x000D_
_pts.unshift(pts[1]); //copy 1. point and insert at beginning_x000D_
_pts.unshift(pts[0]);_x000D_
_pts.push(pts[pts.length - 2]); //copy last point and append_x000D_
_pts.push(pts[pts.length - 1]);_x000D_
}_x000D_
_x000D_
// ok, lets start.._x000D_
_x000D_
// 1. loop goes through point array_x000D_
// 2. loop goes through each segment between the 2 pts + 1e point before and after_x000D_
for (i=2; i < (_pts.length - 4); i+=2) {_x000D_
for (t=0; t <= numOfSegments; t++) {_x000D_
_x000D_
// calc tension vectors_x000D_
t1x = (_pts[i+2] - _pts[i-2]) * tension;_x000D_
t2x = (_pts[i+4] - _pts[i]) * tension;_x000D_
_x000D_
t1y = (_pts[i+3] - _pts[i-1]) * tension;_x000D_
t2y = (_pts[i+5] - _pts[i+1]) * tension;_x000D_
_x000D_
// calc step_x000D_
st = t / numOfSegments;_x000D_
_x000D_
// calc cardinals_x000D_
c1 = 2 * Math.pow(st, 3) - 3 * Math.pow(st, 2) + 1; _x000D_
c2 = -(2 * Math.pow(st, 3)) + 3 * Math.pow(st, 2); _x000D_
c3 = Math.pow(st, 3) - 2 * Math.pow(st, 2) + st; _x000D_
c4 = Math.pow(st, 3) - Math.pow(st, 2);_x000D_
_x000D_
// calc x and y cords with common control vectors_x000D_
x = c1 * _pts[i] + c2 * _pts[i+2] + c3 * t1x + c4 * t2x;_x000D_
y = c1 * _pts[i+1] + c2 * _pts[i+3] + c3 * t1y + c4 * t2y;_x000D_
_x000D_
//store points in array_x000D_
res.push(x);_x000D_
res.push(y);_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
return res;_x000D_
}_x000D_
_x000D_
function drawLines(ctx, pts) {_x000D_
ctx.moveTo(pts[0], pts[1]);_x000D_
for(i=2;i<pts.length-1;i+=2) ctx.lineTo(pts[i], pts[i+1]);_x000D_
}
_x000D_
canvas { border: 1px solid red; }
_x000D_
<canvas id="c"><canvas>
_x000D_
This results in this:
You can easily extend the canvas so you can call it like this instead:
ctx.drawCurve(myPoints);
Add the following to the javascript:
if (CanvasRenderingContext2D != 'undefined') {
CanvasRenderingContext2D.prototype.drawCurve =
function(pts, tension, isClosed, numOfSegments, showPoints) {
drawCurve(this, pts, tension, isClosed, numOfSegments, showPoints)}
}
You can find a more optimized version of this on NPM (npm i cardinal-spline-js
) or on GitLab.
From here.
“Slug” is a newspaper term, but what it means here is the final bit of the URL. For example, a post with the title, “A bit about Django” would become, “bit-about-django” automatically (you can, of course, change it easily if you don’t like the auto-generated slug).
If your server certificated file is not trusted, (for example, you may generate the keystore by yourself with keytool command in java), you should add the extra option rejectUnauthorized
var socket = io.connect('https://localhost', {rejectUnauthorized: false});
Try:
select v.*, row_number() over (partition by id order by elem) rn from
(select
id,
unnest(string_to_array(elements, ',')) AS elem
from myTable) v
Well if they are both the same it doesn't matter. It implements both of them with a single concrete method per interface method.
After reviewing the other's answers above and finding Matt Gallagher's discussion here
I propose this:
NSMutableArray * reverseArray = [NSMutableArray arrayWithCapacity:[myArray count]];
for (id element in [myArray reverseObjectEnumerator]) {
[reverseArray addObject:element];
}
As Matt observes:
In the above case, you may wonder if -[NSArray reverseObjectEnumerator] would be run on every iteration of the loop — potentially slowing down the code. <...>
Shortly thereafter, he answers thus:
<...> The "collection" expression is only evaluated once, when the for loop begins. This is the best case, since you can safely put an expensive function in the "collection" expression without impacting upon the per-iteration performance of the loop.
Without having selected a language type for your file there are no styles defined. Comment and block comment are language specific style preferences. If that's a PITA...
To select for multi-line editing you can use
shift
+ alt
+ down arrow
You can use Vue event system
vm.$broadcast('event-name', args)
and
vm.$on('event-name', function())
Here is the fiddle: http://jsfiddle.net/hfalucas/wc1gg5v4/59/
Consider using the VC++ runtime Macros for Reporting _RPTN() and _RPTFN()
You can use the _RPTn, and _RPTFn macros, defined in CRTDBG.H, to replace the use of printf statements for debugging. These macros automatically disappear in your release build when _DEBUG is not defined, so there is no need to enclose them in #ifdefs.
Example...
if (someVar > MAX_SOMEVAR) {
_RPTF2(_CRT_WARN, "In NameOfThisFunc( ),"
" someVar= %d, otherVar= %d\n", someVar, otherVar );
}
Or you can use the VC++ runtime functions _CrtDbgReport, _CrtDbgReportW directly.
_CrtDbgReport and _CrtDbgReportW can send the debug report to three different destinations: a debug report file, a debug monitor (the Visual Studio debugger), or a debug message window.
_CrtDbgReport and _CrtDbgReportW create the user message for the debug report by substituting the argument[n] arguments into the format string, using the same rules defined by the printf or wprintf functions. These functions then generate the debug report and determine the destination or destinations, based on the current report modes and file defined for reportType. When the report is sent to a debug message window, the filename, lineNumber, and moduleName are included in the information displayed in the window.
It is likely a case of IIS 7 'handling' the HTTP OPTIONS response instead of your application specifying it. To determine this, in IIS7,
Go to your site's Handler Mappings.
Scroll down to 'OPTIONSVerbHandler'.
Change the 'ProtocolSupportModule' to 'IsapiHandler'
Set the executable: %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll
Now, your config entries above should kick in when an HTTP OPTIONS verb is sent.
Alternatively you can respond to the HTTP OPTIONS verb in your BeginRequest method.
protected void Application_BeginRequest(object sender,EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
HttpContext.Current.Response.End();
}
}
To answer the question without reading too much else into it i would
char str[2] = "\0"; /* gives {\0, \0} */
str[0] = fgetc(fp);
You could use the second line in a loop with what ever other string operations you want to keep using char's as strings.
This works too and you dont have to use join or anything:
DROP VIEW IF EXISTS yourview;
CREATE VIEW yourview AS
SELECT table1.column1,
table2.column2
FROM
table1, table2
WHERE table1.column1 = table2.column1;
There are a few unicode circles you could use:
* { font-size: 50px; }
_x000D_
○_x000D_
◌_x000D_
◍_x000D_
◎_x000D_
●
_x000D_
More shapes here.
You can overlay text on the circles if you want to:
#container {_x000D_
position: relative;_x000D_
}_x000D_
#circle {_x000D_
font-size: 50px;_x000D_
color: #58f;_x000D_
}_x000D_
#text {_x000D_
z-index: 1;_x000D_
position: absolute;_x000D_
top: 21px;_x000D_
left: 11px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="circle">●</div>_x000D_
<div id="text">a</div>_x000D_
</div>
_x000D_
You could also use a custom font (like this one) if you want to have a higher chance of it looking the same on different systems since not all computers/browsers have the same fonts installed.
None of these solutions worked for me.
Instead, I elaborate on @Martin v. Löwis 's mention of setting a config
file for SSH.
SSH will look for the user's ~/.ssh/config
file. I have mine setup as:
Host gitserv
Hostname remote.server.com
IdentityFile ~/.ssh/id_rsa.github
IdentitiesOnly yes # see NOTES below
And I add a remote git repository:
git remote add origin git@gitserv:myrepo.git
And then git commands work normally for me.
git push -v origin master
NOTES
IdentitiesOnly yes
is required to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol. If you have a file named ~/.ssh/id_rsa
that will get tried BEFORE your ~/.ssh/id_rsa.github
without this option.References
I had the same error because i had not installed mongoDB. Make sure that you have mongodb installed and if not, you can download it from here https://www.mongodb.com/download-center/community
I have a simple example here to display date and time with Millisecond......
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class MyClass{
public static void main(String[]args){
LocalDateTime myObj = LocalDateTime.now();
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS);
String forDate = myObj.format(myFormat);
System.out.println("The Date and Time are: " + forDate);
}
}
str = ""
if not str:
print "Empty String"
if(len(str)==0):
print "Empty String"
Nowadays C99 supports boolean types but you need to #include <stdbool.h>
.
Example:
#include <stdbool.h>
int main()
{
bool arr[2] = {true, false};
printf("%d\n", arr[0] && arr[1]);
printf("%d\n", arr[0] || arr[1]);
return 0;
}
Output:
0
1
You can run nodejs using pm2 if you want to manage each microservice means and run it. Node will be running in a port right just configure that port in nginx(/etc/nginx/sites-enabled/domain.com)
server{
listen 80;
server_name domain.com www.domain.com;
location / {
return 403;
}
location /url {
proxy_pass http://localhost:51967/info;
}
}
Check whether localhost is running or not by using ping.
And
Create one single Node.js server which handles all Node.js requests. This reads the requested files and evals their contents. So the files are interpreted on each request, but the server logic is much simpler.
This is best and as you said easier too
You can watch your container element using the useRef
hook.
Note that you need to watch the ref
's current
value specifically, otherwise it won't work.
Example:
const containerRef = useRef();
const { current } = containerRef;
useEffect(setLinksData, [current]);
return (
<div ref={containerRef}>
// your child elements...
</div>
)
Replacing CRLF with LF using Notepad++
Rebuild and run the docker image should solve your problem.
If someone looks for this…
I wanted to rsync only specific files and folders and managed to do it with this command: rsync --include-from=rsync-files
With rsync-files:
my-dir/
my-file.txt
- /*
Had the same problem. Came across an article from Zebra with the fix that worked for me:
Original article can be found here
Thought this is old question, I think I have better solution
To use pip for a python 2.x environment, use this command -
py -2 -m pip install -r requirements.txt
To use pip for python 3.x environment, use this command -
py -3 -m pip install -r requirements.txt
make sure you use the POST to insert the data. Actually you were using GET.
If you have made that request in your application already, and see it logged in Google Dev Tools, you can use the copy cURL command from the context menu when right-clicking on the request in the network tab. Copy -> Copy as cURL. It will contain all headers, cookies, etc..
I don't think you need/want the timeout.
onhover (hover) would be defined as the time period while "over" something. IMHO
onmouseover = start...
onmouseout = ...end
For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.
Hi everyone I found the solution regarding this github issue and it works for me no longer able to use private ssh key
Try following theses steps:
1 - Use HTTPS if possible. That will avoid SSH keys entirely.
2 - Manually add the SSH key to the running SSH agent. See manually generate ssh key
3 - If the two others doesn't work, delete all your ssh keys and generate some new one thats what I did after weeks of issues.
Hope it will help you..
To calculate a z-score for an entire column quickly, do as follows:
from scipy.stats import zscore
import pandas as pd
df = pd.DataFrame({'num_1': [1,2,3,4,5,6,7,8,9,3,4,6,5,7,3,2,9]})
df['num_1_zscore'] = zscore(df['num_1'])
display(df)
You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.
Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.
In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.)
You can format the x-axis options with this menu. (Chart->Design->Layout)
Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"
Set up the options you wish. (Fix the starting and ending points.)
And you will get a graph such as the one below.
You can then tweak many of the options, label the axes better etc, but this should get you started.
Hope this helps you move forward.
It may happen, e.g. after an interrupted download, that Maven cached a broken version of the referenced package in your local repository.
Solution: Manually delete the folder of this plugin from cache (i.e. your local repository), and repeat maven install
.
How to find the right folder? Folders in Maven repository follow the structure:
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.4</version>
</dependency>
is cached in ${USER_HOME}\.m2\repository\org\apache\maven\plugins\maven-source-plugin\2.4
please try this bash script. it uses curl command with no need for any external dependencies
bucket=<bucket_name>
region=<region_name>
awsAccess=<access_key>
awsSecret=<secret_key>
awsRegion="${region}"
baseUrl="s3.${awsRegion}.amazonaws.com"
m_sed() {
if which gsed > /dev/null 2>&1; then
gsed "$@"
else
sed "$@"
fi
}
awsStringSign4() {
kSecret="AWS4$1"
kDate=$(printf '%s' "$2" | openssl dgst -sha256 -hex -mac HMAC -macopt "key:${kSecret}" 2>/dev/null | m_sed 's/^.* //')
kRegion=$(printf '%s' "$3" | openssl dgst -sha256 -hex -mac HMAC -macopt "hexkey:${kDate}" 2>/dev/null | m_sed 's/^.* //')
kService=$(printf '%s' "$4" | openssl dgst -sha256 -hex -mac HMAC -macopt "hexkey:${kRegion}" 2>/dev/null | m_sed 's/^.* //')
kSigning=$(printf 'aws4_request' | openssl dgst -sha256 -hex -mac HMAC -macopt "hexkey:${kService}" 2>/dev/null | m_sed 's/^.* //')
signedString=$(printf '%s' "$5" | openssl dgst -sha256 -hex -mac HMAC -macopt "hexkey:${kSigning}" 2>/dev/null | m_sed 's/^.* //')
printf '%s' "${signedString}"
}
if [ -z "${region}" ]; then
region="${awsRegion}"
fi
# Initialize helper variables
authType='AWS4-HMAC-SHA256'
service="s3"
dateValueS=$(date -u +'%Y%m%d')
dateValueL=$(date -u +'%Y%m%dT%H%M%SZ')
# 0. Hash the file to be uploaded
# 1. Create canonical request
# NOTE: order significant in ${signedHeaders} and ${canonicalRequest}
signedHeaders='host;x-amz-content-sha256;x-amz-date'
canonicalRequest="\
GET
/
host:${bucket}.s3.amazonaws.com
x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
x-amz-date:${dateValueL}
${signedHeaders}
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
# Hash it
canonicalRequestHash=$(printf '%s' "${canonicalRequest}" | openssl dgst -sha256 -hex 2>/dev/null | m_sed 's/^.* //')
# 2. Create string to sign
stringToSign="\
${authType}
${dateValueL}
${dateValueS}/${region}/${service}/aws4_request
${canonicalRequestHash}"
# 3. Sign the string
signature=$(awsStringSign4 "${awsSecret}" "${dateValueS}" "${region}" "${service}" "${stringToSign}")
# Upload
curl -g -k "https://${baseUrl}/${bucket}" \
-H "x-amz-content-sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" \
-H "x-amz-Date: ${dateValueL}" \
-H "Authorization: ${authType} Credential=${awsAccess}/${dateValueS}/${region}/${service}/aws4_request,SignedHeaders=${signedHeaders},Signature=${signature}"
This is what I've been using for development:
<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
This is a very liberal approach, but is fine for my application.
As others have pointed out below, beware the risks of this.
For impatient:
Without passing argument, persist()
and cache()
are the same, with default settings:
RDD
: MEMORY_ONLYDataset
: MEMORY_AND_DISKUnlike cache()
, persist()
allows you to pass argument inside the bracket, in order to specify the level:
persist(MEMORY_ONLY)
persist(MEMORY_ONLY_SER)
persist(MEMORY_AND_DISK)
persist(MEMORY_AND_DISK_SER )
persist(DISK_ONLY )
Voilà!
Additional Solution: use Restul api wrapper libraries written in Java
/ python
/ Ruby
- An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.
For documentation and links: Remote Access API
I needed to change by defaultConnectionFactory to be SqlConnectionFactory instead of the default
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="<My Connection String>" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
Using a list comprehension:
from datetime import date, timedelta
d1 = date(2008,8,15)
d2 = date(2008,9,15)
# this will give you a list containing all of the dates
dd = [d1 + timedelta(days=x) for x in range((d2-d1).days + 1)]
for d in dd:
print d
# you can't join dates, so if you want to use join, you need to
# cast to a string in the list comprehension:
ddd = [str(d1 + timedelta(days=x)) for x in range((d2-d1).days + 1)]
# now you can join
print "\n".join(ddd)
I like to do the same thing for different projects without firing up a new shell.
In your case:
cd /home/artemb
Save the_script as:
echo cd /home/artemb
Then fire it up with:
\`./the_script\`
Then you get to the directory using the same shell.
To be honest I still think the best explanation is the one about future and promises on the Wikipedia: http://en.wikipedia.org/wiki/Futures_and_promises
The basic idea is that you have a separate pool of threads that execute tasks asynchronously. When using it. The object does however make the promise that it will execute the operation at some time and give you the result when you request it. This means that it will block when you request the result and hasn't finished, but execute in the thread pool otherwise.
From there you can optimize things: some operations can be implemented async and you can optimize things like file IO and network communication by batching together subsequent requests and/or reordering them. I'm not sure if this is already in the task framework of Microsoft - but if it isn't that would be one of the first things I would add.
You can actually implement the future pattern sort-of with yields in C# 4.0. If you want to know how it works exactly, I can recommend this link that does a decent job: http://code.google.com/p/fracture/source/browse/trunk/Squared/TaskLib/ . However, if you start toying with it yourself, you will notice that you really need language support if you want to do all the cool things -- which is exactly what Microsoft did.
I never liked the key code validation. My approach was to see if the input have text (any character), confirming that the user is entering text and no other characters
$('#input').on('keyup', function() {_x000D_
var words = $(this).val();_x000D_
// if input is empty, remove the word count data and return_x000D_
if(!words.length) {_x000D_
$(this).removeData('wcount');_x000D_
return true;_x000D_
}_x000D_
// if word count data equals the count of the input, return_x000D_
if(typeof $(this).data('wcount') !== "undefined" && ($(this).data('wcount') == words.length)){_x000D_
return true;_x000D_
}_x000D_
// update or initialize the word count data_x000D_
$(this).data('wcount', words.length);_x000D_
console.log('user tiped ' + words);_x000D_
// do you stuff..._x000D_
});
_x000D_
<html lang="en">_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<input type="text" name="input" id="input">_x000D_
</body>_x000D_
</html>
_x000D_
Same can be achieved by using stdout
.
>>> from sys import stdout
>>> for i in range(1,11):
... stdout.write(str(i)+' ')
...
1 2 3 4 5 6 7 8 9 10
Alternatively, same can be done by using reduce()
:
>>> xrange = range(1,11)
>>> print reduce(lambda x, y: str(x) + ' '+str(y), xrange)
1 2 3 4 5 6 7 8 9 10
>>>
Let's assume you want to concatenate string and integer in a situation like this:
for i in range(1,11):
string="string"+i
and you are getting type or concatenation error
The best way to go about it is to do something like this:
for i in range(1,11):
print("string",i)
This will give you concatenated results like string 1, string 2, string 3 ...etc
Steps are below:
In package.json add:
"bin":{
"script1": "bin/script1.js"
}
Create a bin
folder in the project directory and add file runScript1.js
with the code:
#! /usr/bin/env node
var shell = require("shelljs");
shell.exec("node step1script.js");
Run npm install shelljs
in terminal
Run npm link
in terminal
From terminal you can now run script1
which will run node script1.js
Reference: http://blog.npmjs.org/post/118810260230/building-a-simple-command-line-tool-with-npm
To cherry pick from a commit id up to the tip of the branch, you can use:
git cherry-pick commit_id^..branch_name
To check the database connection state you can just simple do the following
if(con.State == ConnectionState.Open){}
On linux distributions (@least on Debian with plasma) the default shortcut is
Ctrl + 0
You can not "attach" a SASS/SCSS file to an HTML document.
SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.
There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.
It's as simple as adding 2 lines of code to your HTML file.
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>
Anyone here looking for Knockout JS integration.
Given the following HTML (Standard Bootstrap dropdown button):
<div class="dropdown">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Select an item
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>
<a href="javascript:;" data-bind="click: clickTest">Click 1</a>
</li>
<li>
<a href="javascript:;" data-bind="click: clickTest">Click 2</a>
</li>
<li>
<a href="javascript:;" data-bind="click: clickTest">Click 3</a>
</li>
</ul>
</div>
Use the following JS:
var viewModel = function(){
var self = this;
self.clickTest = function(){
alert("I've been clicked!");
}
};
For those looking to generate dropdown options based on knockout observable array, the code would look something like:
var viewModel = function(){
var self = this;
self.dropdownOptions = ko.observableArray([
{ id: 1, label: "Click 1" },
{ id: 2, label: "Click 2" },
{ id: 3, label: "Click 3" }
])
self.clickTest = function(item){
alert("Item with id:" + item.id + " was clicked!");
}
};
<!-- REST OF DD CODE -->
<ul class="dropdown-menu" role="menu">
<!-- ko foreach: { data: dropdownOptions, as: 'option' } -->
<li>
<a href="javascript:;" data-bind="click: $parent.clickTest, text: option.clickTest"></a>
</li>
<!-- /ko -->
</ul>
<!-- REST OF DD CODE -->
Note, that the observable array item is implicitly passed into the click function handler for use in the view model code.
From LDAP, there is not a query method to determine an empty string.
The best practice would be to scrub your data inputs to LDAP as an empty or null value in LDAP is no value at all.
To determine this you would need to query for all with a value (manager=*) and then use code to determine the ones that were a "space" or null value.
And as Terry said, storing an empty or null value in an attribute of DN syntax is wrong.
Some LDAP server implementations will not permit entering a DN where the DN entry does not exist.
Perhaps, you could, if your DN's are consistent, use something like:
(&(!(manager=cn*))(manager=*))
This should return any value of manager where there was a value for manager and it did not start with "cn".
However, some LDAP implementations will not allow sub-string searches on DN syntax attributes.
-jim
You are looking for the command scandir.
$path = '/tmp';
$files = scandir($path);
Following code will remove .
and ..
from the returned array from scandir
:
$files = array_diff(scandir($path), array('.', '..'));
A short answer is to add the following options when the JVM is started.
JAVA_OPTS=" $JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8080"
I stumbled upon another solution, which is quite nice.
Basically, only do step 2 from the blog posted mentioned, and define a custom ObjectMapper as a Spring @Component
. (Things started working when I just removed all the AnnotationMethodHandlerAdapter stuff from step 3.)
@Component
@Primary
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
setSerializationInclusion(JsonInclude.Include.NON_NULL);
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
}
Works as long as the component is in a package scanned by Spring. (Using @Primary
is not mandatory in my case, but why not make things explicit.)
For me there are two benefits compared to the other approach:
Jackson2ObjectMapperBuilder
.new CustomObjectMapper()
instead of new ObjectMapper()
.in my main script detectiveROB.py
file i need call passGen
function which generate password hash and that functions is under modules\passwordGen.py
The quickest and easiest solution for me is
Below is my directory structure
So in detectiveROB.py
i have import my function with below syntax
from modules.passwordGen import passGen
You can't do this: {this.state.arrayFromJson}
As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map
to do that.
I am pasting a link from where you can learn how to render elements from an array with React.
http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/
Hope it helps!
This is the way to execute a program quietly, and hide all its output.
/dev/null
is a special filesystem object that discards everything written into it. Redirecting a stream into it means hiding your program's output.
The 2>&1
part means "redirect the error stream into the output stream", so when you redirect the output stream, error stream gets redirected as well. Even if your program writes to stderr
now, that output would be discarded as well.
This answer shows how to write "normal/easily understandable" pythonic code.
I suggest not using zip
as not really everyone knows about it.
The solutions use list comprehensions and common built-in functions.
a = [2, 2, 2]
b = [1, 1, 1]
result = [a[i] - b[i] for i in range(len(a))]
Recommended as it only uses the most basic functions in Python
a = [2, 2, 2]
b = [1, 1, 1]
result = [x - b[i] for i, x in enumerate(a)]
a = [2, 2, 2]
b = [1, 1, 1]
result = list(map(lambda x, y: x - y, a, b))
I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.
So, for hiding the sheet:
Sub try()
Worksheets("Sheet1").Visible = xlSheetHidden
End Sub
There are other methods also if you want to learn all Methods Click here
This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.
Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:
http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/
Import:
You must write columns in INSERT
statement
INSERT INTO TABLE
SELECT * FROM
Is not correct.
Insert into Table(Field1,...)
Select (Field1,...) from TABLE
Is correct
Although GitHub removed the private messaging feature, there's still an alternative.
GitHub host git repositories. If the user you're willing to communicate with has ever committed some code, there are good chances you may reach your goal. Indeed, within each commit is stored some information about the author of the change or the one who accepted it.
Provided you're really dying to exchange with user user_test
git clone https://github.com/..../repository.git
git checkout [branch]
git log -50
As a committer/author, an email should be displayed along with the commit data.
Note: Every warning related to unsolicited email should apply there. Do not spam.
None of the answers work for all output types the same way and others focus on figures plottet within the code chunk and not external images.
The include_graphics()
function provides an easy solution. The only argument is the name of the file (with the relative path if it's in a subfolder). By setting echo
to FALSE
and fig.align=center
you get the wished result.
```{r, echo=FALSE, fig.align='center'}
include_graphics("image.jpg")
```
You can fix your example with the iterator pattern by changing the parametrization of the class:
List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Iterator<Room> i = rooms.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
or much simpler way:
List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Room room : rooms) {
System.out.println(room);
}
Unless your do_something
function actually does something with any given arguments, you can just pass it as the event handler.
var first = document.getElementById('first');
first.addEventListener('touchstart', do_something, false);
first.addEventListener('click', do_something, false);
You missed the *
in front of NgIf (like we all have, dozens of times):
<div *ngIf="answer.accepted">✔</div>
Without the *
, Angular sees that the ngIf
directive is being applied to the div
element, but since there is no *
or <template>
tag, it is unable to locate a template, hence the error.
If you get this error with Angular v5:
Error: StaticInjectorError[TemplateRef]:
StaticInjectorError[TemplateRef]:
NullInjectorError: No provider for TemplateRef!
You may have <template>...</template>
in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>
.
One thing that you'll want to watch out for (it's a stupid mistake on my part, but it happens), is that the email address attached to the CSR needs to be the same as the email connected to your Apple Dev account. Once I used a new CSR and rebuilt all the certs and provisioning profiles, all was well in applesville.
Focus might be what your looking for. With tabbing or clicking I think u mean giving the element the focus. Same code as Russ (Sorry i stole it :P) but firing an other event.
// this must be done after input1 exists in the DOM
var element = document.getElementById("input1");
if (element) element.focus();
foreach (var f in Directory.GetFiles(".", "*.dll"))
Assembly.LoadFrom(f);
That loads all the DLLs present in your executable's folder.
In my case I was trying to use Reflection
to find all subclasses of a class, even in other DLLs. This worked, but I'm not sure if it's the best way to do it.
EDIT: I timed it, and it only seems to load them the first time.
Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 4; i++)
{
stopwatch.Restart();
foreach (var f in Directory.GetFiles(".", "*.dll"))
Assembly.LoadFrom(f);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
Output: 34 0 0 0
So one could potentially run that code before any Reflection searches just in case.
Maybe look at the WooCommerce Order class? For example, to get the customer's email address:
$order = new WC_Order($order_id);
echo $order->get_billing_email();
Just a thought...
I have a very good approach mixing https://stackoverflow.com/a/13982508/2516436 and https://stackoverflow.com/a/17578272/2516436
-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
NSUInteger orientations = UIInterfaceOrientationMaskAllButUpsideDown;
if(self.window.rootViewController){
UIViewController *presentedViewController = [self topViewControllerWithRootViewController:self.window.rootViewController];
orientations = [presentedViewController supportedInterfaceOrientations];
}
return orientations;
}
- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
if ([rootViewController isKindOfClass:[UITabBarController class]]) {
UITabBarController* tabBarController = (UITabBarController*)rootViewController;
return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
} else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController*)rootViewController;
return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
} else if (rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return [self topViewControllerWithRootViewController:presentedViewController];
} else {
return rootViewController;
}
}
and return whatever orientations you want to support for each UIViewController
- (NSUInteger)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskPortrait;
}
In iOS 8.3 (perhaps earlier) with Swift, it's as simple as overriding the motionBegan
or motionEnded
methods in your view controller:
class ViewController: UIViewController {
override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {
println("started shaking!")
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
println("ended shaking!")
}
}
Sometimes, converting string to Date in swift can result to return nil so that you should add "!" mark to format.date function!
let dateFormatterUK = DateFormatter()
dateFormatterUK.dateFormat = "dd-MM-yyyy"
let stringDate = "11-03-2018"
let date = dateFormatterUK.date(from: stringDate)!
Thanks to Mayur for knowing me about withFileTypes
. I written following code for getting files of particular folder recursively. It can be easily modified to get only directories.
const getFiles = (dir, base = '') => readdirSync(dir, {withFileTypes: true}).reduce((files, file) => {
const filePath = path.join(dir, file.name)
const relativePath = path.join(base, file.name)
if(file.isDirectory()) {
return files.concat(getFiles(filePath, relativePath))
} else if(file.isFile()) {
file.__fullPath = filePath
file.__relateivePath = relativePath
return files.concat(file)
}
}, [])
Try:
git add -A
Warning: Starting with git 2.0 (mid 2013), this will always stage files on the whole working tree.
If you want to stage files under the current path of your working tree, you need to use:
git add -A .
Also see: Difference of git add -A
and git add .
The latest solution for passing data between fragments can be implemented by using android architectural components such as ViewModel and LiveData. With this solution, you don't need to define interface for communication and can get the advantages of using viewmodel like data survival due to configuration changes.
In this solution, the fragments involved in the communication share the same viewmodel object which is tied to their activity lifecycle. The view model object contains livedata object. One fragment sets data to be passed on livedata object and second fragment observers livedata changes and received the data.
Here is the complete example http://www.zoftino.com/passing-data-between-android-fragments-using-viewmodel
As environments are inherited from the parent process, you could write an add-in for Visual Studio that modifies its environment variables before you perform the start. I am not sure how easy that would be to put into your process.
If you are not sharing develop branch with anybody, then I would just rebase it every time master updated, that way you will not have merge commits all over your history once you will merge develop back into master. Workflow in this case would be as follows:
> git clone git://<remote_repo_path>/ <local_repo>
> cd <local_repo>
> git checkout -b develop
....do a lot of work on develop
....do all the commits
> git pull origin master
> git rebase master develop
Above steps will ensure that your develop branch will be always on top of the latest changes from the master branch. Once you are done with develop branch and it's rebased to the latest changes on master you can just merge it back:
> git checkout -b master
> git merge develop
> git branch -d develop
There is already an extension to do this.
namespace System.Reflection
{
// Summary:
// Contains static methods for retrieving custom attributes.
public static class CustomAttributeExtensions
{
public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute;
}
}
So:
var attr = typeof(MyClass).GetCustomAttribute<DomainNameAttribute>(false);
return attr != null ? attr.DomainName : "";
from flask import request
request.headers.get('your-header-name')
request.headers
behaves like a dictionary, so you can also get your header like you would with any dictionary:
request.headers['your-header-name']
I use this and it works great for me for setting any color I want.
public static final int MY_COLOR = Color.rgb(255, 102, 153);
Set the colors using 0-255 for each red, green and blue then anywhere you want that color used just put MY_COLOR instead of Color.BLUE or Color.RED or any of the other static colors the Color class offers.
Just do a Google search for color chart and it you can find a chart with the correct RGB codes using 0-255.
For sending get request with parameter i use
$http.get('urlPartOne\\'+parameter+'\\urlPartTwo')
By this you can use your own url string
yes I often need to have 3 or more JVM's installed. For example, I've noticed that sometimes the JRE is slightly different to the JDK version of the JRE.
My go to solution on Windows for a bit of 'packaging' is something like this:
@echo off
setlocal
@rem _________________________
@rem
@set JAVA_HOME=b:\lang\java\jdk\v1.6\u45\x64\jre
@rem
@set JAVA_EXE=%JAVA_HOME%\bin\java
@set VER=test
@set WRK=%~d0%~p0%VER%
@rem
@pushd %WRK%
cd
@echo.
@echo %JAVA_EXE% -jar %WRK%\openmrs-standalone.jar
%JAVA_EXE% -jar %WRK%\openmrs-standalone.jar
@rem
@rem _________________________
popd
endlocal
@exit /b
I think it is straightforward. The main thing is the setlocal and endlocal give your app a "personal environment" for what ever it does -- even if there's other programs to run.
The mail server on CentOS 6 and other IPv6 capable server platforms may be bound to IPv6 localhost (::1) instead of IPv4 localhost (127.0.0.1).
Typical symptoms:
[root@host /]# telnet 127.0.0.1 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100
[root@host /]# netstat -plant | grep 25
tcp 0 0 :::25 :::* LISTEN 1082/exim
If this happens, make sure that you don't have two entries for localhost
in /etc/hosts
with different IP addresses, like this (bad) example:
[root@host /]# cat /etc/hosts
127.0.0.1 localhost.localdomain localhost localhost4.localdomain4 localhost4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
To avoid confusion, make sure you only have one entry for localhost
, preferably an IPv4 address, like this:
[root@host /]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4.localdomain4 localhost4
::1 localhost6 localhost6.localdomain6
Please don't use any library for this effect instead use the recommended way of doing it according to Google I/O. In your recyclerView's onBindViewHolder method do this:
final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
TransitionManager.beginDelayedTransition(recyclerView);
notifyDataSetChanged();
}
});
And for the cool effects that you wanted, use these as your list_item attributes:
android:background="@drawable/comment_background"
android:stateListAnimator="@animator/comment_selection"
where comment_background is:
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize="true"
android:enterFadeDuration="@android:integer/config_shortAnimTime"
android:exitFadeDuration="@android:integer/config_shortAnimTime">
<item android:state_activated="true" android:drawable="@color/selected_comment_background" />
<item android:drawable="@color/comment_background" />
</selector>
and comment_selection is:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true">
<objectAnimator
android:propertyName="translationZ"
android:valueTo="@dimen/z_card"
android:duration="2000"
android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>
<item>
<objectAnimator
android:propertyName="translationZ"
android:valueTo="0dp"
android:duration="2000"
android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>
</selector>
Finally I found the solution, that works for me:
jQuery.ajax ({
url: myurl,
type: "POST",
data: JSON.stringify({data:"test"}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(){
//
}
});
You can use this: [None] * 10
. But this won't be "fixed size" you can still append, remove ... This is how lists are made.
You could make it a tuple (tuple([None] * 10)
) to fix its width, but again, you won't be able to change it (not in all cases, only if the items stored are mutable).
Another option, closer to your requirement, is not a list, but a collections.deque
with a maximum length. It's the maximum size, but it could be smaller.
import collections
max_4_items = collections.deque([None] * 4, maxlen=4)
But, just use a list, and get used to the "pythonic" way of doing things.
From the notebook menu you can save the file directly as a python script. Go to the 'File' option of the menu, then select 'Download as' and there you would see a 'Python (.py)' option.
Another option would be to use nbconvert from the command line:
jupyter nbconvert --to script 'my-notebook.ipynb'
Have a look here.
Instructions to run node server
along apache2(v2.4.xx) server
:
In order to pipe all requests on a particular URL to your Node.JS application create CUSTOM.conf
file inside /etc/apache2/conf-available
directory, and add following line to the created file:
ProxyPass /node http://localhost:8000/
Change 8000 to the prefered port number for node server
.
Enable custom configurations with following command:
$> sudo a2enconf CUSTOM
CUSTOM is your newly created filename without extension, then enable proxy_http
with the command:
$> sudo a2enmod proxy_http
it should enable both proxy
and proxy_http
modules. You can check whether module is enabled or not with:
$> sudo a2query -m MODULE_NAME
After configuration and modules enabled, you will need to restart apache server:
$> sudo service apache2 restart
Now you can execute node server. All requests to the URL/node
will be handled by node server.
Correct way of doing this would be to use Python's format syntax as described in the official documentation
For this case it would simply be:
'{:10}'.format('hi')
which outputs:
'hi '
Explanation:
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Pretty much all you need to know is there ^.
Update: as of python 3.6 it's even more convenient with literal string interpolation!
foo = 'foobar'
print(f'{foo:10} is great!')
# foobar is great!
I got the same error message. In my case, it was due to not using quotes.
Although the column was supposed to have only numbers, it was a Varchar column, and one of the rows had a letter in it.
So I was doing this:
select * from mytable where myid = 1234
While I should be doing this:
select * from mytable where myid = '1234'
If the column had all numbers, the conversion would have worked, but not in this case.
You can write:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView= inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
Button button = (Button)dialogView.findViewById(R.id.btnName);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Commond here......
}
});
EditText editText = (EditText)
dialogView.findViewById(R.id.label_field);
editText.setText("test label");
dialogBuilder.create().show();
You could also tell MySQL to execute the commands in the given file, like so:
mysql --user=root --password=sa casemanager < CaseManager.sql
It took me quite a while to figure out, how to not get a false
when using openssl_decrypt()
and get encrypt and decrypt working.
// cryptographic key of a binary string 16 bytes long (because AES-128 has a key size of 16 bytes)
$encryption_key = '58adf8c78efef9570c447295008e2e6e'; // example
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encrypted = openssl_encrypt($plaintext, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);
$encrypted = $encrypted . ':' . base64_encode($iv);
// decrypt to get again $plaintext
$parts = explode(':', $encrypted);
$decrypted = openssl_decrypt($parts[0], 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, base64_decode($parts[1]));
If you want to pass the encrypted string via a URL, you need to urlencode the string:
$encrypted = urlencode($encrypted);
To better understand what is going on, read:
To generate 16 bytes long keys you can use:
$bytes = openssl_random_pseudo_bytes(16);
$hex = bin2hex($bytes);
To see error messages of openssl you can use: echo openssl_error_string();
Hope that helps.
Check to see if the user is suspended in GitHub. Access their user page and if a banner is across the top of the page that says, "This user is suspended." that is probably your issue.
I would use du
's --threshold
for this. Not sure if this option is available in all versions of du
but it is implemented in GNU's version.
Quoting from du(1)'s manual:
-t, --threshold=SIZE
exclude entries smaller than SIZE if positive, or entries greater
than SIZE if negative
Here's my solution, using du --threshold=
for OP's use case:
THRESHOLD=90k
if [[ -z "$(du --threshold=${THRESHOLD} file.txt)" ]]; then
mail -s "file.txt size is below ${THRESHOLD}, please fix. " [email protected] < /dev/null
mv -f /root/tmp/file.txt /var/www/file.txt
fi
The advantage of that, is that du
can accept an argument to that option in a known format - either human as in 10K
, 10MiB
or what ever you feel comfortable with - you don't need to manually convert between formats / units since du
handles that.
For reference, here's the explanation on this SIZE
argument from the man page:
The SIZE argument is an integer and optional unit (example: 10K is
10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers
of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on.
Quick and Easy way:
tasks
In SSMS 2017 you need to ignore step 2 - the generate scripts options is at the top level of the context menu
Thanks to Daniel for the comment to update.generate scripts
Types of data to script
- Called types of data to script
in SMSS 2014 Thanks to Ellesedil for commentingdata only
I usually in cases like this generate to a new query editor window and then just do any modifications where needed.
You can use awk, sort & uniq to do this, for example to list all the unique values in the first column
awk < test.txt '{print $1}' | sort | uniq
As posted elsewhere, if you want to count the number of instances of something you can pipe the unique list into wc -l
$http methods return a promise, which can't be iterated, so you have to attach the results to the scope variable through the callbacks:
$scope.documents = [];
$http.get('/Documents/DocumentsList/' + caseId)
.then(function(result) {
$scope.documents = result.data;
});
Now, since this defines the documents
variable only after the results are fetched, you need to initialise the documents
variable on scope beforehand: $scope.documents = []
. Otherwise, your ng-repeat will choke.
This way, ng-repeat will first return an empty list, because documents
array is empty at first, but as soon as results are received, ng-repeat will run again because the `documents``have changed in the success callback.
Also, you might want to alter you ng-repeat expression to:
<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
because if your DisplayDocuments()
function is making a call to the server, than this call will be executed many times over, due to the $digest cycles.
You can do this with JSON in more recent MySQL versions. It's a blast. We will have a quick preparation to create a numbers table. Then first we create an intermediary table to convert the comma delimited strings into a json array then we will use json_extract
to blast them apart. I am encapsulating the strings in quotes carefully escaping existing quotes because I had semicolon separated strings containing commas.
So to create the numbers table, hopefully you have more clients than courses, choose an adequately big table if not.
CREATE TABLE numbers (n int PRIMARY KEY);
INSERT INTO numbers
SELECT @row := @row + 1
FROM clients JOIN (select @row:=0) t2;
Add LIMIT 50 if you know you only have 50 courses. Now, that was easy, wasn't it? Now on to the real work, honestly it's the quotes that make it uglier but at least it's more generic that way:
CREATE TABLE json_coursenames
SELECT clientId,clientName,CONCAT('["', REPLACE(REPLACE(courseName,'"','\\"'), ',', '","'), '"]') AS a
FROM clients;
CREATE TABLE extracted
SELECT clientId,clientName,REPLACE(TRIM(TRIM('"' FROM JSON_EXTRACT(a, concat('$[', n, ']')))), '\\"', '"')
FROM json_coursenames
INNER JOIN numbers ON n < JSON_LENGTH(a);
Wheee!
The meat here are these two: the CONCAT('["', REPLACE(coursename, ',', '","'), '"]')
(I dropped the second REPLACE
to make it more visible) will convert foo,bar,bar
into "foo","bar","baz"
. The other trick is JSON_EXTRACT(a, concat('$[', n, ']')
will become JSON_EXTRACT(a, $[12])
and that's the 13th element in the array, see JSON Path syntax.
Maybe this example listed here can help you out. Statement from the author
about 24 lines of code to encrypt, 23 to decrypt
Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)
/*
Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
#region Usings
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
#endregion
namespace Utilities.Encryption
{
/// <summary>
/// Utility class that handles encryption
/// </summary>
public static class AESEncryption
{
#region Static Functions
/// <summary>
/// Encrypts a string
/// </summary>
/// <param name="PlainText">Text to be encrypted</param>
/// <param name="Password">Password to encrypt with</param>
/// <param name="Salt">Salt to encrypt with</param>
/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="PasswordIterations">Number of iterations to do</param>
/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
/// <param name="KeySize">Can be 128, 192, or 256</param>
/// <returns>An encrypted string</returns>
public static string Encrypt(string PlainText, string Password,
string Salt = "Kosher", string HashAlgorithm = "SHA1",
int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
int KeySize = 256)
{
if (string.IsNullOrEmpty(PlainText))
return "";
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] CipherTextBytes = null;
using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream())
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
{
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
CryptoStream.FlushFinalBlock();
CipherTextBytes = MemStream.ToArray();
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
return Convert.ToBase64String(CipherTextBytes);
}
/// <summary>
/// Decrypts a string
/// </summary>
/// <param name="CipherText">Text to be decrypted</param>
/// <param name="Password">Password to decrypt with</param>
/// <param name="Salt">Salt to decrypt with</param>
/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="PasswordIterations">Number of iterations to do</param>
/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
/// <param name="KeySize">Can be 128, 192, or 256</param>
/// <returns>A decrypted string</returns>
public static string Decrypt(string CipherText, string Password,
string Salt = "Kosher", string HashAlgorithm = "SHA1",
int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
int KeySize = 256)
{
if (string.IsNullOrEmpty(CipherText))
return "";
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
int ByteCount = 0;
using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
{
ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
}
#endregion
}
}
try
with open(f"{os.path.dirname(sys.argv[0])}/data/test.csv", newline='') as f:
findAny
& orElse
By using findAny()
and orElse()
:
Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);
Stops looking after finding an occurrence.
findAny
Optional<T> findAny()
Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)
It worked to me:
String javaHome = System.getProperty("java.home");
File f = new File(javaHome);
f = new File(f, "bin");
f = new File(f, "javaw.exe"); //or f = new File(f, "javaws.exe"); //work too
System.out.println(f + " exists: " + f.exists());
You are getting this error because the parameter required is Activity and you are passing it the Application.
So, either you cast application to the Activity like: (Activity)getApplicationContext();
Or you can just type the Activity like: MyActivity.this
There are two differences:
We can use Iterator to traverse Set and List and also Map type of Objects. While a ListIterator can be used to traverse for List-type Objects, but not for Set-type of Objects.
That is, we can get a Iterator object by using Set and List, see here:
By using Iterator we can retrieve the elements from Collection Object in forward direction only.
Methods in Iterator:
hasNext()
next()
remove()
Iterator iterator = Set.iterator();
Iterator iterator = List.iterator();
But we get ListIterator object only from the List interface, see here:
where as a ListIterator allows you to traverse in either directions (Both forward and backward). So it has two more methods like hasPrevious()
and previous()
other than those of Iterator. Also, we can get indexes of the next or previous elements (using nextIndex()
and previousIndex()
respectively )
Methods in ListIterator:
ListIterator listiterator = List.listIterator();
i.e., we can't get ListIterator object from Set interface.
Reference : - What is the difference between Iterator and ListIterator ?
Here is some good overview of .NET impersonation concepts.
Basically you will be leveraging these classes that are out of the box in the .NET framework:
The code can often get lengthy though and that is why you see many examples like the one you reference that try to simplify the process.
If you don't have a modifiable lvalue of an iterator, or it is desired to get a copy of a given iterator (leaving the original one unchanged), then C++11 comes with new helper functions - std::next
/ std::prev
:
std::next(iter, 2); // returns a copy of iter incremented by 2
std::next(std::begin(v), 2); // returns a copy of begin(v) incremented by 2
std::prev(iter, 2); // returns a copy of iter decremented by 2
INSERT INTO mt_magazine_subscription (
magazine_subscription_id,
subscription_name,
magazine_id,
status )
VALUES (
(SELECT magazine_subscription_id,
subscription_name,
magazine_id,'1' as status
FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC))
@Sheridan thx.. if I try your example with "DisplayedImagePath" on both sides, it works with absolute path as you show.
As for the relative paths, this is how I always connect relative paths, I first include the subdirectory (!) and the image file in my project.. then I use ~ character to denote the bin-path..
public string DisplayedImagePath
{
get { return @"~\..\images\osc.png"; }
}
This was tested, see below my Solution Explorer in VS2015..
Note: if you want a Click event, use the Button tag around the image,
<Button Click="image_Click" Width="128" Height="128" Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left">_x000D_
<Image x:Name="image" Source="{Binding DisplayedImagePath}" Margin="0,0,0,0" />_x000D_
</Button>
_x000D_
Try these:
window.location.href = 'http://www.google.com';
window.location.assign("http://www.w3schools.com");
window.location = 'http://www.google.com';
For more see this link: other ways to reload the page with JavaScript
This one is useful as well when you want to implement a functional interface
Runnable r = ()-> System.out.print("Run method");
is equivalent to
Runnable r = new Runnable() {
@Override
public void run() {
System.out.print("Run method");
}
};
You would want to use ->forget()
$collection->forget($key);
Link to the forget method documentation
Margin is the spacing outside your element, just as padding is the spacing inside your element.
Setting the bottom margin indicates what distance you want below the current block. Setting a negative top margin indicates that you want negative spacing above your block. Negative spacing may in itself be a confusing concept, but just the way positive top margin pushes content down, a negative top margin pulls content up.