I used the plugin Smooth Scroll, at http://plugins.jquery.com/smooth-scroll/. With this plugin all you need to include is a link to jQuery and to the plugin code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/smoothscroll.js"></script>
(the links need to have the class smoothScroll
to work).
Another feature of Smooth Scroll is that the ancor name is not displayed in the URL!
sys.executable
contains full path of the currently running Python interpreter.
import sys
print(sys.executable)
which is now documented here
Set a default value for people
with ngInit
<div ng-app>
<div ng-init="people=1" />
<input type="radio" ng-model="people" value="1"><label>1</label>
<input type="radio" ng-model="people" value="2"><label>2</label>
<input type="radio" ng-model="people" value="3"><label>3</label>
<ul>
<li>{{10*people}}€</li>
<li>{{8*people}}€</li>
<li>{{30*people}}€</li>
</ul>
</div>
Demo: Fiddle
The whole code in the document will be:
graph = {'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']}
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
After writing it, save the document and press F 5
After that, the code you will run in the Python IDLE shell will be:
find_path(graph, 'A','D')
The answer you should receive in IDLE is
['A', 'B', 'C', 'D']
if you have an iframe using Google map embedded API like this :
<iframe width="320" height="400" frameborder="0" src="https://www.google.com/maps/embed/v1/place?q=Cagli ... "></iframe>
you can add this css style: pointer-event:none; ES.
<iframe width="320" height="400" frameborder="0" style="pointer-event:none;" src="https://www.google.com/maps/embed/v1/place?q=Cagli ... "></iframe>
If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):
>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])
There are a couple of important things to know about bash's [[ ]]
construction. The first:
Word splitting and pathname expansion are not performed on the words between the
[[
and]]
; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.
The second thing:
An additional binary operator, ‘=~’, is available,... the string to the right of the operator is considered an extended regular expression and matched accordingly... Any part of the pattern may be quoted to force it to be matched as a string.
Consequently, $v
on either side of the =~
will be expanded to the value of that variable, but the result will not be word-split or pathname-expanded. In other words, it's perfectly safe to leave variable expansions unquoted on the left-hand side, but you need to know that variable expansions will happen on the right-hand side.
So if you write: [[ $x =~ [$0-9a-zA-Z] ]]
, the $0
inside the regex on the right will be expanded before the regex is interpreted, which will probably cause the regex to fail to compile (unless the expansion of $0
ends with a digit or punctuation symbol whose ascii value is less than a digit). If you quote the right-hand side like-so [[ $x =~ "[$0-9a-zA-Z]" ]]
, then the right-hand side will be treated as an ordinary string, not a regex (and $0
will still be expanded). What you really want in this case is [[ $x =~ [\$0-9a-zA-Z] ]]
Similarly, the expression between the [[
and ]]
is split into words before the regex is interpreted. So spaces in the regex need to be escaped or quoted. If you wanted to match letters, digits or spaces you could use: [[ $x =~ [0-9a-zA-Z\ ] ]]
. Other characters similarly need to be escaped, like #
, which would start a comment if not quoted. Of course, you can put the pattern into a variable:
pat="[0-9a-zA-Z ]"
if [[ $x =~ $pat ]]; then ...
For regexes which contain lots of characters which would need to be escaped or quoted to pass through bash's lexer, many people prefer this style. But beware: In this case, you cannot quote the variable expansion:
# This doesn't work:
if [[ $x =~ "$pat" ]]; then ...
Finally, I think what you are trying to do is to verify that the variable only contains valid characters. The easiest way to do this check is to make sure that it does not contain an invalid character. In other words, an expression like this:
valid='0-9a-zA-Z $%&#' # add almost whatever else you want to allow to the list
if [[ ! $x =~ [^$valid] ]]; then ...
!
negates the test, turning it into a "does not match" operator, and a [^...]
regex character class means "any character other than ...
".
The combination of parameter expansion and regex operators can make bash regular expression syntax "almost readable", but there are still some gotchas. (Aren't there always?) One is that you could not put ]
into $valid
, even if $valid
were quoted, except at the very beginning. (That's a Posix regex rule: if you want to include ]
in a character class, it needs to go at the beginning. -
can go at the beginning or the end, so if you need both ]
and -
, you need to start with ]
and end with -
, leading to the regex "I know what I'm doing" emoticon: [][-]
)
When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.
But there are more important differences on the receiving side of things. When the receiver does a recv
(or read
) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.
Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.
I think that there is a more simple approach to all given here, and is the method Number.toFixed()
already implemented in JavaScript.
simply write:
var myNumber = 2;
myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"
etc...
df = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],'rating': [3., 4., 5., np.nan, np.nan, np.nan],'name': ['John','James', np.nan, np.nan, np.nan,np.nan]})
for col in df.columns:
df = df[~pd.isnull(df[col])]
Another alternative with .lastIndexOf
:
haystack.lastIndexOf(needle, 0) === 0
This looks backwards through haystack
for an occurrence of needle
starting from index 0
of haystack
. In other words, it only checks if haystack
starts with needle
.
In principle, this should have performance advantages over some other approaches:
haystack
.When using Python 2.4, try
inf = float("9e999")
nan = inf - inf
I am facing the issue when I was porting the simplejson to an embedded device which running the Python 2.4, float("9e999")
fixed it. Don't use inf = 9e999
, you need convert it from string.
-inf
gives the -Infinity
.
For cmake version 3.1.0-rc2
to pick up boost 1.57
specify -D_boost_TEST_VERSIONS=1.57
cmake version 3.1.0-rc2
defaults to boost<=1.56.0
as is seen using -DBoost_DEBUG=ON
cmake -D_boost_TEST_VERSIONS=1.57 -DBoost_DEBUG=ON -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++
May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.
var obj = [];
var elems = $("input[class=email]");
for (i = 0; i < elems.length; i += 1) {
var id = this.getAttribute('title');
var email = this.value;
tmp = {
'title': id,
'email': email
};
obj.push(tmp);
}
Sample function is used for sample data in ORACLE. So you can try like this:-
SELECT * FROM TABLE_NAME SAMPLE(50);
Here 50 is the percentage of data contained by the table. So if you want 1000 rows from 100000. You can execute a query like:
SELECT * FROM TABLE_NAME SAMPLE(1);
Hope this can help you.
A primitive quick fix that works.
If you only use OpenFileDialog
, you can capture the FileName
, SafeFileName
, then subtract to get folder path:
exampleFileName = ofd.SafeFileName;
exampleFileNameFull = ofd.FileName;
exampleFileNameFolder = ofd.FileNameFull.Replace(ofd.FileName, "");
You have two options:
Either use:
sb.setLength(0); // It will just discard the previous data, which will be garbage collected later.
Or use:
sb.delete(0, sb.length()); // A bit slower as it is used to delete sub sequence.
Avoid declaring StringBuffer
or StringBuilder
objects within the loop else it will create new objects with each iteration. Creating of objects requires system resources, space and also takes time. So for long run, avoid declaring them within a loop if possible.
If you want to remove the column completely (i.e. not just the button) from the table then use a suitable event handler, e.g. for the OnDataBound
event, and then hide the appropriate column on the target GridView
. Pick an event that will only fire once for this control, i.e. not OnRowDataBound
.
<asp:GridView ID="grdUsers" runat="server" DataSourceID="dsProjectUsers" OnDataBound="grdUsers_DataBound">
<Columns>
<asp:TemplateField HeaderText="Admin Actions">
<ItemTemplate><asp:Button ID="btnEdit" runat="server" text="Edit" /></ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="Telephone" HeaderText="Telephone" />
</Columns>
</asp:GridView>
protected void grdUsers_DataBound(object sender, EventArgs e)
{
try
{
// in this case hiding the first col if not admin
if (!User.IsInRole(Constants.Role_Name_Admin))
grdUsers.Columns[0].Visible = false;
}
catch (Exception ex)
{
// deal with ex
}
}
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
I will give here my opinion based on experience:
For shell:
For python:
I usually choose bash for most of the things, but when I have something that must cross windows boundaries, I just use python.
There is a simpler way, sql timestamp string:
2018-07-19 00:00:00
The closest format to timestamp for Date() to receive is the following, so replace blank space for "T":
var dateString = media.intervention.replace(/\s/g, "T");
"2011-10-10T14:48:00"
Then, create the date object:
var date = new Date(dateString);
result would be the date object:
Thu Jul 19 2018 00:00:00 GMT-0300 (Horário Padrão de Brasília)
Google Closure has a nice function for this... goog.object.getCount(obj)
We can say like DispatcherServlet
taking care of everything in Spring MVC.
At web container start up:
DispatcherServlet
will be loaded and initialized by calling
init()
methodinit()
of DispatcherServlet
will try to identify the Spring
Configuration Document with naming conventions like
"servlet_name-servlet.xml"
then all beans can be identified.Example:
public class DispatcherServlet extends HttpServlet {
ApplicationContext ctx = null;
public void init(ServletConfig cfg){
// 1. try to get the spring configuration document with default naming conventions
String xml = "servlet_name" + "-servlet.xml";
//if it was found then creates the ApplicationContext object
ctx = new XmlWebApplicationContext(xml);
}
...
}
So, in generally DispatcherServlet
capture request URI and hand over to HandlerMapping
. HandlerMapping
search mapping bean with method of controller, where controller returning logical name(view). Then this logical name is send to DispatcherServlet
by HandlerMapping
. Then DispatcherServlet
tell ViewResolver
to give full location of view by appending prefix and suffix, then DispatcherServlet
give view to the client.
Ok, this is actually four different question. I'll address them one by one:
are both equals for the compiler? (speed, perf...)
Yes. The pointer dereferenciation and decay from type int (*)[100][280]
to int (*)[280]
is always a noop to your CPU. I wouldn't put it past a bad compiler to generate bogus code anyways, but a good optimizing compiler should compile both examples to the exact same code.
is one of these solutions eating more memory than the other?
As a corollary to my first answer, no.
what is the more frequently used by developers?
Definitely the variant without the extra (*pointer)
dereferenciation. For C programmers it is second nature to assume that any pointer may actually be a pointer to the first element of an array.
what is the best way, the 1st or the 2nd?
That depends on what you optimize for:
Idiomatic code uses variant 1. The declaration is missing the outer dimension, but all uses are exactly as a C programmer expects them to be.
If you want to make it explicit that you are pointing to an array, you can use variant 2. However, many seasoned C programmers will think that there's a third dimension hidden behind the innermost *
. Having no array dimension there will feel weird to most programmers.
You can invoke reflections and also, set order of sequence for getter for values through annotations
public class Student {
private String grade;
private String name;
private String id;
private String gender;
private Method[] methods;
@Retention(RetentionPolicy.RUNTIME)
public @interface Order {
int value();
}
/**
* Sort methods as per Order Annotations
*
* @return
*/
private void sortMethods() {
methods = Student.class.getMethods();
Arrays.sort(methods, new Comparator<Method>() {
public int compare(Method o1, Method o2) {
Order or1 = o1.getAnnotation(Order.class);
Order or2 = o2.getAnnotation(Order.class);
if (or1 != null && or2 != null) {
return or1.value() - or2.value();
}
else if (or1 != null && or2 == null) {
return -1;
}
else if (or1 == null && or2 != null) {
return 1;
}
return o1.getName().compareTo(o2.getName());
}
});
}
/**
* Read Elements
*
* @return
*/
public void readElements() {
int pos = 0;
/**
* Sort Methods
*/
if (methods == null) {
sortMethods();
}
for (Method method : methods) {
String name = method.getName();
if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
pos++;
String value = "";
try {
value = (String) method.invoke(this);
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(name + " Pos: " + pos + " Value: " + value);
}
}
}
// /////////////////////// Getter and Setter Methods
/**
* @param grade
* @param name
* @param id
* @param gender
*/
public Student(String grade, String name, String id, String gender) {
super();
this.grade = grade;
this.name = name;
this.id = id;
this.gender = gender;
}
/**
* @return the grade
*/
@Order(value = 4)
public String getGrade() {
return grade;
}
/**
* @param grade the grade to set
*/
public void setGrade(String grade) {
this.grade = grade;
}
/**
* @return the name
*/
@Order(value = 2)
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the id
*/
@Order(value = 1)
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the gender
*/
@Order(value = 3)
public String getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* Main
*
* @param args
* @throws IOException
* @throws SQLException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void main(String args[]) throws IOException, SQLException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Student student = new Student("A", "Anand", "001", "Male");
student.readElements();
}
}
Output when sorted
getId Pos: 1 Value: 001
getName Pos: 2 Value: Anand
getGender Pos: 3 Value: Male
getGrade Pos: 4 Value: A
Open AndroidManifest.xml
(located at android/app/src/main
)
<application
android:label="App Name" ...> // Your app name here
Open info.plist
(located at ios/Runner
)
<key>CFBundleName</key>
<string>App Name</string> // Your app name here
Don't forget to run
flutter clean
For me what worked is, as this error may occur for memory requirement of git. I have added these lines to my global git configuration file .gitconfig which is present in $USER_HOME i.e C:\Users\<USER_NAME>\.gitconfig
[core]
packedGitLimit = 512m
packedGitWindowSize = 512m
[pack]
deltaCacheSize = 2047m
packSizeLimit = 2047m
windowMemory = 2047m
Mladen's basic idea worked (thanks), but needed a few changes to be robust, so I contributed them here.
The only place where this type of solution should be used is if you want to clone the object, but can't because it is a managed object. If you are lucky enough to have objects that all have 100% side-effect free setters for all fields, you should definitely use the BeanUtils option instead.
Here, I use lang3's utility methods to simplify the code, so if you paste it, you must first import Apache's lang3 library.
Copy code
static public <X extends Object> X copy(X object, String... skipFields) {
Constructor constructorToUse = null;
for (Constructor constructor : object.getClass().getConstructors()) {
if (constructor.getParameterTypes().length == 0) {
constructorToUse = constructor;
constructorToUse.setAccessible(true);
break;
}
}
if (constructorToUse == null) {
throw new IllegalStateException(object + " must have a zero arg constructor in order to be copied");
}
X copy;
try {
copy = (X) constructorToUse.newInstance();
for (Field field : FieldUtils.getAllFields(object.getClass())) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
//Avoid the fields that you don't want to copy. Note, if you pass in "id", it will skip any field with "id" in it. So be careful.
if (StringUtils.containsAny(field.getName(), skipFields)) {
continue;
}
field.setAccessible(true);
Object valueToCopy = field.get(object);
//TODO add here other special types of fields, like Maps, Lists, etc.
field.set(copy, valueToCopy);
}
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new IllegalStateException("Could not copy " + object, e);
}
return copy;
}
That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:
(4 :: List(1,2,3).reverse).reverse
or that:
List(1,2,3) ::: List(4)
There is a new official design library, just add this to your build.gradle: for details visit android developers page
compile 'com.android.support:design:27.0.0'
This might be caused by HHH-10876 which got fixed so make sure you update to:
The easiest way to do it is leaving action blank action=""
or omitting it completely from the form tag, however it is bad practice (if at all you care about it).
Incase you do care about it, the best you can do is:
<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="<?php echo($_SERVER['PHP_SELF'] . http_build_query($_GET));?>">
The best thing about using this is that even arrays are converted so no need to do anything else for any kind of data.
You can user UIBezierPath Class for this:
And can draw as many lines as you want:
I have subclassed UIView :
@interface MyLineDrawingView()
{
NSMutableArray *pathArray;
NSMutableDictionary *dict_path;
CGPoint startPoint, endPoint;
}
@property (nonatomic,retain) UIBezierPath *myPath;
@end
And initialized the pathArray and dictPAth objects which will be used for line drawing. I am writing the main portion of the code from my own project:
- (void)drawRect:(CGRect)rect
{
for(NSDictionary *_pathDict in pathArray)
{
[((UIColor *)[_pathDict valueForKey:@"color"]) setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
[[_pathDict valueForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}
[[dict_path objectForKey:@"color"] setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
[[dict_path objectForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}
touchesBegin method :
UITouch *touch = [touches anyObject];
startPoint = [touch locationInView:self];
myPath=[[UIBezierPath alloc]init];
myPath.lineWidth = currentSliderValue*2;
dict_path = [[NSMutableDictionary alloc] init];
touchesMoved Method:
UITouch *touch = [touches anyObject];
endPoint = [touch locationInView:self];
[myPath removeAllPoints];
[dict_path removeAllObjects];// remove prev object in dict (this dict is used for current drawing, All past drawings are managed by pathArry)
// actual drawing
[myPath moveToPoint:startPoint];
[myPath addLineToPoint:endPoint];
[dict_path setValue:myPath forKey:@"path"];
[dict_path setValue:strokeColor forKey:@"color"];
// NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
// [pathArray addObject:tempDict];
// [dict_path removeAllObjects];
[self setNeedsDisplay];
touchesEnded Method:
NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
[pathArray addObject:tempDict];
[dict_path removeAllObjects];
[self setNeedsDisplay];
i think better to do this
if ( $request->hasFile('file')){
if ($request->file('file')->isValid()){
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('images' , $name);
$inputs = $request->all();
$inputs['path'] = $name;
}
}
Post::create($inputs);
actually images is folder that laravel make it automatic and file is name of the input and here we store name of the image in our path column in the table and store image in public/images directory
Let me give you a working example to understand the hashable objects in python. I am taking 2 Tuples for this example.Each value in a tuple has a unique Hash Value which never changes during its lifetime. So based on this has value, the comparison between two tuples is done. We can get the hash value of a tuple element using the Id().
I hope my late answer can be of some help.
This will go to rails database console.
rails db
pretty print your query output
.headers on
.mode columns
(turn headers on and show database data in column mode )
Show the tables
.table
'.help' to see help.
Or use SQL statements like 'Select * from cars'
I saw some answers at this post and it's possible to be considered completed base knowledge, because have a several approaches in C# Programming to resolve the same problem. Only one thing that is necessary to be considered is about a difference between Pure UTF-8 and UTF-8 with B.O.M..
In last week, at my job, I need to develop one functionality that outputs CSV files with B.O.M. and other CSVs with pure UTF-8 (without B.O.M.), each CSV file Encoding type will be consumed by different non-standardized APIs, that one API read UTF-8 with B.O.M. and the other API read without B.O.M.. I need to research the references about this concept, reading "What's the difference between UTF-8 and UTF-8 without B.O.M.?" Stack Overflow discussion and this Wikipedia link "Byte order mark" to build my approach.
Finally, my C# Programming for the both UTF-8 encoding types (with B.O.M. and pure) needed to be similar like this example bellow:
//for UTF-8 with B.O.M., equals shared by Zanoni (at top)
string result = System.Text.Encoding.UTF8.GetString(byteArray);
//for Pure UTF-8 (without B.O.M.)
string result = (new UTF8Encoding(false)).GetString(byteArray);
0 values of basic types (1)(2)map to false
.
Other values map to true
.
This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.
It's a common error to assume that as function return values, false
indicates failure. But in particular from main
it's false
that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.
There's no need to cast to bool
for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x
, works nicely. One can read !!
as a “convert to bool
” operator, much as -->
can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)
1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false
; any other value is converted to true
. For direct-initialization (8.5), a prvalue of type std::nullptr_t
can be converted to a prvalue of type bool
; the resulting value is false
.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool
, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”
Try this, it worked for me.
<td><a href="Docs/Chapter 1_ORG.pdf" target="pdf-frame">Chapter-1 Organizational</a></td>
Try:
#your_div_id {
width: 855px;
margin:0 auto;
text-align: center;
}
The Verilog code compiler you use will dictate what you have to do. If you use illegal syntax, you will get a compile error.
An output
must also be declared as a reg
only if it is assigned using a "procedural assignment". For example:
output reg a;
always @* a = b;
There is no need to declare an output
as a wire
.
There is no need to declare an input
as a wire
or reg
.
If you are extending from an AppCompatActivity and are trying to get the ActionBar from the Fragment, you can do this:
ActionBar mActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
If you are using jQuery, you can do it with jQuery.trigger
http://api.jquery.com/trigger/
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
<a id="foo" onclick="action()"></a>
<script type="text/javascript">
function action(){
window.location.replace("http://stackoverflow.com/q/9081426/5526354")
}
$("#foo").trigger("click");
</script>
</body>
</html>
Single quotes delimit a string constant or a date/time constant.
Double quotes delimit identifiers for e.g. table names or column names. This is generally only necessary when your identifier doesn't fit the rules for simple identifiers.
See also:
You can make MySQL use double-quotes per the ANSI standard:
SET GLOBAL SQL_MODE=ANSI_QUOTES
You can make Microsoft SQL Server use double-quotes per the ANSI standard:
SET QUOTED_IDENTIFIER ON
You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.
If you don't use the onLocationChanged it always will be the old location.
Java SE refers to the standard version of Java and its libraries. Java EE refers to the Enterprise edition of Java which is used to deploy web applications.
When compiling your program, you need to include dict.c as well, eg:
gcc -o test1 test1.c dict.c
Plus you have a typo in dict.c definition of CreateDictionary
, it says CreateDectionary
(e
instead of i
)
Using the idea of totem and zlangner, I have created a KnownTypeConverter
that will be able to determine the most appropriate inheritor, while taking into account that json data may not have optional elements.
So, the service sends a JSON response that contains an array of documents (incoming and outgoing). Documents have both a common set of elements and different ones. In this case, the elements related to the outgoing documents are optional and may be absent.
In this regard, a base class Document
was created that includes a common set of properties.
Two inheritor classes are also created:
- OutgoingDocument
adds two optional elements "device_id"
and "msg_id"
;
- IncomingDocument
adds one mandatory element "sender_id"
;
The task was to create a converter that based on json data and information from KnownTypeAttribute will be able to determine the most appropriate class that allows you to save the largest amount of information received. It should also be taken into account that json data may not have optional elements. To reduce the number of comparisons of json elements and properties of data models, I decided not to take into account the properties of the base class and to correlate with json elements only the properties of the inheritor classes.
{
"documents": [
{
"document_id": "76b7be75-f4dc-44cd-90d2-0d1959922852",
"date": "2019-12-10 11:32:49",
"processed_date": "2019-12-10 11:32:49",
"sender_id": "9dedee17-e43a-47f1-910e-3a88ff6bc258",
},
{
"document_id": "5044a9ac-0314-4e9a-9e0c-817531120753",
"date": "2019-12-10 11:32:44",
"processed_date": "2019-12-10 11:32:44",
}
],
"total": 2
}
/// <summary>
/// Service response model
/// </summary>
public class DocumentsRequestIdResponse
{
[JsonProperty("documents")]
public Document[] Documents { get; set; }
[JsonProperty("total")]
public int Total { get; set; }
}
// <summary>
/// Base document
/// </summary>
[JsonConverter(typeof(KnownTypeConverter))]
[KnownType(typeof(OutgoingDocument))]
[KnownType(typeof(IncomingDocument))]
public class Document
{
[JsonProperty("document_id")]
public Guid DocumentId { get; set; }
[JsonProperty("date")]
public DateTime Date { get; set; }
[JsonProperty("processed_date")]
public DateTime ProcessedDate { get; set; }
}
/// <summary>
/// Outgoing document
/// </summary>
public class OutgoingDocument : Document
{
// this property is optional and may not be present in the service's json response
[JsonProperty("device_id")]
public string DeviceId { get; set; }
// this property is optional and may not be present in the service's json response
[JsonProperty("msg_id")]
public string MsgId { get; set; }
}
/// <summary>
/// Incoming document
/// </summary>
public class IncomingDocument : Document
{
// this property is mandatory and is always populated by the service
[JsonProperty("sender_sys_id")]
public Guid SenderSysId { get; set; }
}
public class KnownTypeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return System.Attribute.GetCustomAttributes(objectType).Any(v => v is KnownTypeAttribute);
}
public override bool CanWrite => false;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// load the object
JObject jObject = JObject.Load(reader);
// take custom attributes on the type
Attribute[] attrs = Attribute.GetCustomAttributes(objectType);
Type mostSuitableType = null;
int countOfMaxMatchingProperties = -1;
// take the names of elements from json data
HashSet<string> jObjectKeys = GetKeys(jObject);
// take the properties of the parent class (in our case, from the Document class, which is specified in DocumentsRequestIdResponse)
HashSet<string> objectTypeProps = objectType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Select(p => p.Name)
.ToHashSet();
// trying to find the right "KnownType"
foreach (var attr in attrs.OfType<KnownTypeAttribute>())
{
Type knownType = attr.Type;
if(!objectType.IsAssignableFrom(knownType))
continue;
// select properties of the inheritor, except properties from the parent class and properties with "ignore" attributes (in our case JsonIgnoreAttribute and XmlIgnoreAttribute)
var notIgnoreProps = knownType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => !objectTypeProps.Contains(p.Name)
&& p.CustomAttributes.All(a => a.AttributeType != typeof(JsonIgnoreAttribute) && a.AttributeType != typeof(System.Xml.Serialization.XmlIgnoreAttribute)));
// get serializable property names
var jsonNameFields = notIgnoreProps.Select(prop =>
{
string jsonFieldName = null;
CustomAttributeData jsonPropertyAttribute = prop.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(JsonPropertyAttribute));
if (jsonPropertyAttribute != null)
{
// take the name of the json element from the attribute constructor
CustomAttributeTypedArgument argument = jsonPropertyAttribute.ConstructorArguments.FirstOrDefault();
if(argument != null && argument.ArgumentType == typeof(string) && !string.IsNullOrEmpty((string)argument.Value))
jsonFieldName = (string)argument.Value;
}
// otherwise, take the name of the property
if (string.IsNullOrEmpty(jsonFieldName))
{
jsonFieldName = prop.Name;
}
return jsonFieldName;
});
HashSet<string> jKnownTypeKeys = new HashSet<string>(jsonNameFields);
// by intersecting the sets of names we determine the most suitable inheritor
int count = jObjectKeys.Intersect(jKnownTypeKeys).Count();
if (count == jKnownTypeKeys.Count)
{
mostSuitableType = knownType;
break;
}
if (count > countOfMaxMatchingProperties)
{
countOfMaxMatchingProperties = count;
mostSuitableType = knownType;
}
}
if (mostSuitableType != null)
{
object target = Activator.CreateInstance(mostSuitableType);
using (JsonReader jObjectReader = CopyReaderForObject(reader, jObject))
{
serializer.Populate(jObjectReader, target);
}
return target;
}
throw new SerializationException($"Could not serialize to KnownTypes and assign to base class {objectType} reference");
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
private HashSet<string> GetKeys(JObject obj)
{
return new HashSet<string>(((IEnumerable<KeyValuePair<string, JToken>>) obj).Select(k => k.Key));
}
public static JsonReader CopyReaderForObject(JsonReader reader, JObject jObject)
{
JsonReader jObjectReader = jObject.CreateReader();
jObjectReader.Culture = reader.Culture;
jObjectReader.DateFormatString = reader.DateFormatString;
jObjectReader.DateParseHandling = reader.DateParseHandling;
jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
jObjectReader.FloatParseHandling = reader.FloatParseHandling;
jObjectReader.MaxDepth = reader.MaxDepth;
jObjectReader.SupportMultipleContent = reader.SupportMultipleContent;
return jObjectReader;
}
}
PS: In my case, if no one inheritor has not been selected by converter (this can happen if the JSON data contains information only from the base class or the JSON data does not contain optional elements from the OutgoingDocument
), then an object of the OutgoingDocument
class will be created, since it is listed first in the list of KnownTypeAttribute
attributes. At your request, you can vary the implementation of the KnownTypeConverter
in this situation.
In my opinion, a dynamic PL/SQL block is somewhat obscure. While is very flexible, is also hard to tune, hard to debug and hard to figure out what's up. My vote goes to your first option,
EXECUTE IMMEDIATE v_query_str INTO v_num_of_employees USING p_job;
Both uses bind variables, but first, for me, is more redeable and tuneable than @jonearles option.
use agent detector and then with your web language create program to create css
for example in python
csscreator()
useragent = detector()
if useragent == "Firefox":
css = "your css"
...
return css
The .cpp file is the compilation unit : it's the real source code file that will be compiled (in C++).
The .h (header) files are files that will be virtually copy/pasted in the .cpp files where the #include precompiler instruction appears. Once the headers code is inserted in the .cpp code, the compilation of the .cpp can start.
I personally use prepared statements.
Why is it important?
Well it's important because of security. It's very easy to do an SQL injection on someone who use variables in the query.
Instead of using this code:
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
You should use this
$stmt = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password); //You need the variables to do something as well.
$stmt->execute();
Learn more about prepared statements on:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php MySQLI
You can use split function.
SELECT
(select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
(select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
(select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
(select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
FROM MyTbl
Build two foreach loops and iterate through your array. Print out the value and add HTML table tags around that.
As the error messages stated, ngFor
only supports Iterables such as Array
, so you cannot use it for Object
.
change
private extractData(res: Response) {
let body = <Afdelingen[]>res.json();
return body || {}; // here you are return an object
}
to
private extractData(res: Response) {
let body = <Afdelingen[]>res.json().afdelingen; // return array from json file
return body || []; // also return empty array if there is no data
}
I solve my problem just adding @AutoConfigureTestDatabase(replace=Replace.NONE)
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class TestClienteRepository {
}
I got the same error, and fixed it with the following PHP in my back-end script:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
you shoult try this one :
java -cp youJarName.jar your.package.your.MainClass
Here's generally how to select multiple columns from a subquery:
SELECT
A.SalesOrderID,
A.OrderDate,
SQ.Max_Foo,
SQ.Max_Foo2
FROM
A
LEFT OUTER JOIN
(
SELECT
B.SalesOrderID,
MAX(B.Foo) AS Max_Foo,
MAX(B.Foo2) AS Max_Foo2
FROM
B
GROUP BY
B.SalesOrderID
) AS SQ ON SQ.SalesOrderID = A.SalesOrderID
If what you're ultimately trying to do is get the values from the row with the highest value for Foo (rather than the max of Foo and the max of Foo2 - which is NOT the same thing) then the following will usually work better than a subquery:
SELECT
A.SalesOrderID,
A.OrderDate,
B1.Foo,
B1.Foo2
FROM
A
LEFT OUTER JOIN B AS B1 ON
B1.SalesOrderID = A.SalesOrderID
LEFT OUTER JOIN B AS B2 ON
B2.SalesOrderID = A.SalesOrderID AND
B2.Foo > B1.Foo
WHERE
B2.SalesOrderID IS NULL
You're basically saying, give me the row from B where I can't find any other row from B with the same SalesOrderID and a greater Foo.
To remove the optional you only should do this
println("\(text2!)")
cause if you dont use "!" it takes the optional value of text2
And to remove "" from 5 you have to convert it to NSInteger or NSNumber easy peasy. It has "" cause its an string.
You could always switch out the first and third examples with a while loop and a little more code. This gives you the advantage of being able to use the do-while:
int i = 0;
do{
E element = list.get(i);
i++;
}
while (i < list.size());
Of course, this kind of thing might cause a NullPointerException if the list.size() returns 0, becuase it always gets executed at least once. This can be fixed by testing if element is null before using its attributes / methods tho. Still, it's a lot simpler and easier to use the for loop
Maybe you can use measure
:
measureProgressBar() {
this.refs.welcome.measure(this.logProgressBarLayout);
},
logProgressBarLayout(ox, oy, width, height, px, py) {
console.log("ox: " + ox);
console.log("oy: " + oy);
console.log("width: " + width);
console.log("height: " + height);
console.log("px: " + px);
console.log("py: " + py);
}
Compile
configuration was deprecated and should be replaced by implementation
or api
.
You can read the docs at https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_separation.
The brief part being-
The key difference between the standard Java plugin and the Java Library plugin is that the latter introduces the concept of an API exposed to consumers. A library is a Java component meant to be consumed by other components. It's a very common use case in multi-project builds, but also as soon as you have external dependencies.
The plugin exposes two configurations that can be used to declare dependencies: api and implementation. The api configuration should be used to declare dependencies which are exported by the library API, whereas the implementation configuration should be used to declare dependencies which are internal to the component.
I think the following should work. I'm not sure about win32
though.
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
# ...
elif [[ "$OSTYPE" == "darwin"* ]]; then
# Mac OSX
elif [[ "$OSTYPE" == "cygwin" ]]; then
# POSIX compatibility layer and Linux environment emulation for Windows
elif [[ "$OSTYPE" == "msys" ]]; then
# Lightweight shell and GNU utilities compiled for Windows (part of MinGW)
elif [[ "$OSTYPE" == "win32" ]]; then
# I'm not sure this can happen.
elif [[ "$OSTYPE" == "freebsd"* ]]; then
# ...
else
# Unknown.
fi
Clearly you aren't sending the data with ObjectOutputStream:
you are just writing the bytes.
readObject()
you must write with writeObject().
readUTF()
you must write with writeUTF().
readXXX()
you must write with writeXXX(),
for most values of XXX.Below is the PowerShell code that I use for basic web URL testing. It includes the ability to accept invalid certs and get detailed information about the results of checking the certificate.
$CertificateValidatorClass = @'
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace CertificateValidation
{
public class CertificateValidationResult
{
public string Subject { get; internal set; }
public string Thumbprint { get; internal set; }
public DateTime Expiration { get; internal set; }
public DateTime ValidationTime { get; internal set; }
public bool IsValid { get; internal set; }
public bool Accepted { get; internal set; }
public string Message { get; internal set; }
public CertificateValidationResult()
{
ValidationTime = DateTime.UtcNow;
}
}
public static class CertificateValidator
{
private static ConcurrentStack<CertificateValidationResult> certificateValidationResults = new ConcurrentStack<CertificateValidationResult>();
public static CertificateValidationResult[] CertificateValidationResults
{
get
{
return certificateValidationResults.ToArray();
}
}
public static CertificateValidationResult LastCertificateValidationResult
{
get
{
CertificateValidationResult lastCertificateValidationResult = null;
certificateValidationResults.TryPeek(out lastCertificateValidationResult);
return lastCertificateValidationResult;
}
}
public static bool ServicePointManager_ServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
StringBuilder certificateValidationMessage = new StringBuilder();
bool allowCertificate = true;
if (sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
{
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) == System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch)
{
certificateValidationMessage.AppendFormat("The remote certificate name does not match.\r\n", certificate.Subject);
}
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) == System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors)
{
certificateValidationMessage.AppendLine("The certificate chain has the following errors:");
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus chainStatus in chain.ChainStatus)
{
certificateValidationMessage.AppendFormat("\t{0}", chainStatus.StatusInformation);
if (chainStatus.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.Revoked)
{
allowCertificate = false;
}
}
}
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable) == System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable)
{
certificateValidationMessage.AppendLine("The remote certificate was not available.");
allowCertificate = false;
}
System.Console.WriteLine();
}
else
{
certificateValidationMessage.AppendLine("The remote certificate is valid.");
}
CertificateValidationResult certificateValidationResult = new CertificateValidationResult
{
Subject = certificate.Subject,
Thumbprint = certificate.GetCertHashString(),
Expiration = DateTime.Parse(certificate.GetExpirationDateString()),
IsValid = (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None),
Accepted = allowCertificate,
Message = certificateValidationMessage.ToString()
};
certificateValidationResults.Push(certificateValidationResult);
return allowCertificate;
}
public static void SetDebugCertificateValidation()
{
ServicePointManager.ServerCertificateValidationCallback = ServicePointManager_ServerCertificateValidationCallback;
}
public static void SetDefaultCertificateValidation()
{
ServicePointManager.ServerCertificateValidationCallback = null;
}
public static void ClearCertificateValidationResults()
{
certificateValidationResults.Clear();
}
}
}
'@
function Set-CertificateValidationMode
{
<#
.SYNOPSIS
Sets the certificate validation mode.
.DESCRIPTION
Set the certificate validation mode to one of three modes with the following behaviors:
Default -- Performs the .NET default validation of certificates. Certificates are not checked for revocation and will be rejected if invalid.
CheckRevocationList -- Cerftificate Revocation Lists are checked and certificate will be rejected if revoked or invalid.
Debug -- Certificate Revocation Lists are checked and revocation will result in rejection. Invalid certificates will be accepted. Certificate validation
information is logged and can be retrieved from the certificate handler.
.EXAMPLE
Set-CertificateValidationMode Debug
.PARAMETER Mode
The mode for certificate validation.
#>
[CmdletBinding(SupportsShouldProcess = $false)]
param
(
[Parameter()]
[ValidateSet('Default', 'CheckRevocationList', 'Debug')]
[string] $Mode
)
begin
{
$isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null
if ($isValidatorClassLoaded -eq $false)
{
Add-Type -TypeDefinition $CertificateValidatorClass
}
}
process
{
switch ($Mode)
{
'Debug'
{
[System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
[CertificateValidation.CertificateValidator]::SetDebugCertificateValidation()
}
'CheckRevocationList'
{
[System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
[CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
}
'Default'
{
[System.Net.ServicePointManager]::CheckCertificateRevocationList = $false
[CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
}
}
}
}
function Clear-CertificateValidationResults
{
<#
.SYNOPSIS
Clears the collection of certificate validation results.
.DESCRIPTION
Clears the collection of certificate validation results.
.EXAMPLE
Get-CertificateValidationResults
#>
[CmdletBinding(SupportsShouldProcess = $false)]
param()
begin
{
$isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null
if ($isValidatorClassLoaded -eq $false)
{
Add-Type -TypeDefinition $CertificateValidatorClass
}
}
process
{
[CertificateValidation.CertificateValidator]::ClearCertificateValidationResults()
Sleep -Milliseconds 20
}
}
function Get-CertificateValidationResults
{
<#
.SYNOPSIS
Gets the certificate validation results for all operations performed in the PowerShell session since the Debug cerificate validation mode was enabled.
.DESCRIPTION
Gets the certificate validation results for all operations performed in the PowerShell session since the Debug certificate validation mode was enabled in reverse chronological order.
.EXAMPLE
Get-CertificateValidationResults
#>
[CmdletBinding(SupportsShouldProcess = $false)]
param()
begin
{
$isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null
if ($isValidatorClassLoaded -eq $false)
{
Add-Type -TypeDefinition $CertificateValidatorClass
}
}
process
{
return [CertificateValidation.CertificateValidator]::CertificateValidationResults
}
}
function Test-WebUrl
{
<#
.SYNOPSIS
Tests and reports information about the provided web URL.
.DESCRIPTION
Tests a web URL and reports the time taken to get and process the request and response, the HTTP status, and the error message if an error occurred.
.EXAMPLE
Test-WebUrl 'http://websitetotest.com/'
.EXAMPLE
'https://websitetotest.com/' | Test-WebUrl
.PARAMETER HostName
The Hostname to add to the back connection hostnames list.
.PARAMETER UseDefaultCredentials
If present the default Windows credential will be used to attempt to authenticate to the URL; otherwise, no credentials will be presented.
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Uri] $Url,
[Parameter()]
[Microsoft.PowerShell.Commands.WebRequestMethod] $Method = 'Get',
[Parameter()]
[switch] $UseDefaultCredentials
)
process
{
[bool] $succeeded = $false
[string] $statusCode = $null
[string] $statusDescription = $null
[string] $message = $null
[int] $bytesReceived = 0
[Timespan] $timeTaken = [Timespan]::Zero
$timeTaken = Measure-Command `
{
try
{
[Microsoft.PowerShell.Commands.HtmlWebResponseObject] $response = Invoke-WebRequest -UseDefaultCredentials:$UseDefaultCredentials -Method $Method -Uri $Url
$succeeded = $true
$statusCode = $response.StatusCode.ToString('D')
$statusDescription = $response.StatusDescription
$bytesReceived = $response.RawContent.Length
Write-Verbose "$($Url.ToString()): $($statusCode) $($statusDescription) $($message)"
}
catch [System.Net.WebException]
{
$message = $Error[0].Exception.Message
[System.Net.HttpWebResponse] $exceptionResponse = $Error[0].Exception.GetBaseException().Response
if ($exceptionResponse -ne $null)
{
$statusCode = $exceptionResponse.StatusCode.ToString('D')
$statusDescription = $exceptionResponse.StatusDescription
$bytesReceived = $exceptionResponse.ContentLength
if ($statusCode -in '401', '403', '404')
{
$succeeded = $true
}
}
else
{
Write-Warning "$($Url.ToString()): $($message)"
}
}
}
return [PSCustomObject] @{ Url = $Url; Succeeded = $succeeded; BytesReceived = $bytesReceived; TimeTaken = $timeTaken.TotalMilliseconds; StatusCode = $statusCode; StatusDescription = $statusDescription; Message = $message; }
}
}
Set-CertificateValidationMode Debug
Clear-CertificateValidationResults
Write-Host 'Testing web sites:'
'https://expired.badssl.com/', 'https://wrong.host.badssl.com/', 'https://self-signed.badssl.com/', 'https://untrusted-root.badssl.com/', 'https://revoked.badssl.com/', 'https://pinning-test.badssl.com/', 'https://sha1-intermediate.badssl.com/' | Test-WebUrl | ft -AutoSize
Write-Host 'Certificate validation results (most recent first):'
Get-CertificateValidationResults | ft -AutoSize
I found this question and none of the solutions here worked for me. I found another solution that got rid of the gaps below images in Chrome. I had to add line-height:0;
to the img selector in my CSS and the gaps below images went away.
Crazy that this problem persists in browsers in 2013.
You can actually compile and run C code even without the use of nppexec plugins. If you use MingW32 C compiler, use g++ for C++ language and gcc for C language.
Paste this code into the notepad++ run section
cmd /k cd $(CURRENT_DIRECTORY) && gcc $(FILE_NAME) -o $(NAME_PART).exe && $(NAME_PART).exe && pause
It will compile your C code into exe and run it immediately. It's like a build and run feature in CodeBlock. All these are done with some cmd knowledge.
Explanation:
For more info on notepad++ commands, go to
http://docs.notepad-plus-plus.org/index.php/External_Programs
Here is a stripped down example, using as little HTML markup as possible.
The overlay is provided by the :before
pseudo element on the .content
container.
No z-index is required, :before
is naturally layered over the video element.
The .content
container is position: relative
so that the position: absolute
overlay is positioned in relation to it.
The overlay is stretched to cover the entire .content
div width with left / right / bottom
and left
set to 0
.
The width of the video is controlled by the width of its container with width: 100%
.content {
position: relative;
width: 500px;
margin: 0 auto;
padding: 20px;
}
.content video {
width: 100%;
display: block;
}
.content:before {
content: '';
position: absolute;
background: rgba(0, 0, 0, 0.5);
border-radius: 5px;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
_x000D_
<div class="content">
<video id="player" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.360p.vp9.webm" autoplay loop muted></video>
</div>
_x000D_
it's like this :)
window.addEventListener("scroll", (event) => {
let scroll = this.scrollY;
console.log(scroll)
});
WOW!!!
It's pretty long time ago
Now, In python 3.x it will be pretty easy
code:
for i in range(20):
print('a',end='') # here end variable will clarify what you want in
# end of the code
output:
aaaaaaaaaaaaaaaaaaaa
More about print() function
print(value1,value2,value3,sep='-',end='\n',file=sys.stdout,flush=False)
Here:
value1,value2,value3
you can print multiple values using commas
sep = '-'
3 values will be separated by '-' character
you can use any character instead of that even string like sep='@' or sep='good'
end='\n'
by default print function put '\n' charater at the end of output
but you can use any character or string by changing end variale value
like end='$' or end='.' or end='Hello'
file=sys.stdout
this is a default value, system standard output
using this argument you can create a output file stream like
print("I am a Programmer", file=open("output.txt", "w"))
by this code you will create a file named output.txt where your output I am a Programmer will be stored
flush = False
It's a default value using flush=True you can forcibly flush the stream
View the source of the login page. Look for the form
HTML tag. Within that tag is something that will look like action=
Use that value as $url
, not the URL of the form itself.
Also, while you are there, verify the input boxes are named what you have them listed as.
For example, a basic login form will look similar to:
<form method='post' action='postlogin.php'>
Email Address: <input type='text' name='email'>
Password: <input type='password' name='password'>
</form>
Using the above form as an example, change your value of $url
to:
$url="http://www.myremotesite.com/postlogin.php";
Verify the values you have listed in $postdata
:
$postdata = "email=".$username."&password=".$password;
and it should work just fine.
If you are looking for converting Large integers i.e. Numbers greater than Number.MAX_SAFE_INTEGER -- 9007199254740991, then you can use the following code
const hugeNumber = "9007199254740991873839" // Make sure its in String_x000D_
const hexOfHugeNumber = BigInt(hugeNumber).toString(16);_x000D_
console.log(hexOfHugeNumber)
_x000D_
Try this:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(1220227200 * 1000);
System.out.println(cal.getTime());
Here is what you are looking for:
Service hangs up at WaitForExit after calling batch file
It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.
The Why
java.util.logging has a root logger that defaults to Level.INFO
, and a ConsoleHandler attached to it that also defaults to Level.INFO
.
FINE
is lower than INFO
, so fine messages are not displayed by default.
Solution 1
Create a logger for your whole application, e.g. from your package name or use Logger.getGlobal()
, and hook your own ConsoleLogger to it.
Then either ask root logger to shut up (to avoid duplicate output of higher level messages), or ask your logger to not forward logs to root.
public static final Logger applog = Logger.getGlobal();
...
// Create and set handler
Handler systemOut = new ConsoleHandler();
systemOut.setLevel( Level.ALL );
applog.addHandler( systemOut );
applog.setLevel( Level.ALL );
// Prevent logs from processed by default Console handler.
applog.setUseParentHandlers( false ); // Solution 1
Logger.getLogger("").setLevel( Level.OFF ); // Solution 2
Solution 2
Alternatively, you may lower the root logger's bar.
You can set them by code:
Logger rootLog = Logger.getLogger("");
rootLog.setLevel( Level.FINE );
rootLog.getHandlers()[0].setLevel( Level.FINE ); // Default console handler
Or with logging configuration file, if you are using it:
.level = FINE
java.util.logging.ConsoleHandler.level = FINE
By lowering the global level, you may start seeing messages from core libraries, such as from some Swing or JavaFX components. In this case you may set a Filter on the root logger to filter out messages not from your program.
We can use a separate function for performing a continue statement work. suppose you have following problem:
for i=1 to 10
if(condition) then 'for loop body'
contionue
End If
Next
Here we will use a function call for for loop body:
for i=1 to 10
Call loopbody()
next
function loopbody()
if(condition) then 'for loop body'
Exit Function
End If
End Function
loop will continue for function exit statement....
InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
imm.ShowSoftInput(_enterPin.FindFocus(), 0);
*This is for Android.xamarin and FindFocus()-it searches for the view in hierarchy rooted at this view that currently has focus,as i have _enterPin.RequestFocus() before the above code thus it shows keyboard for _enterPin EditText *
Usefetch
and innerHTML
to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
_x000D_
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
_x000D_
I'd say you are right, in my own words;
Architecture is the allocation of system requirements to system elements. Four statements about an architecture:
Architecture is an essential engineering step when a complexity of the system is subdivided.
Example: Think about your house, you don't need an architect for your kitchen (only one element involved) but the complete building needs some interaction definitions, like doors, and a roof.
Design is a informative representation of the (proposed) implementation of the function. It is intended to elicit feedback and to discuss with stakeholders. It might be good practice but is not an essential engineering step.
It would be nice to see the kitchen design see before the kitchen is installed but it is not essential for the cooking requirement:
If I think about it you can state:
I finally created a workaround around this frustrating issue. I'm not completely happy with the workaround, but it's better than nothing.
Basically, after you paste the source code and unambigous imports are fixed, just press F2
to highlight the next compiler error. If the current error is an import-missing error, press Alt+Enter
, then Enter
to select the Import
option, then pick the correct import. Then, press F2
again.
**To avoid XSS security threat in spring application**
solution to the XSS issue is to filter all the textfields in the form at the time of submitting the form.
It needs XML entry in the web.xml file & two simple classes.
java code :-
The code for the first class named CrossScriptingFilter.java is :
package com.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
public class CrossScriptingFilter implements Filter {
private static Logger logger = Logger.getLogger(CrossScriptingFilter.class);
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logger.info("Inlter CrossScriptingFilter ...............");
chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);
logger.info("Outlter CrossScriptingFilter ...............");
}
}
The code second class named RequestWrapper.java is :
package com.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.log4j.Logger;
public final class RequestWrapper extends HttpServletRequestWrapper {
private static Logger logger = Logger.getLogger(RequestWrapper.class);
public RequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
}
public String[] getParameterValues(String parameter) {
logger.info("InarameterValues .. parameter .......");
String[] values = super.getParameterValues(parameter);
if (values == null) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = cleanXSS(values[i]);
}
return encodedValues;
}
public String getParameter(String parameter) {
logger.info("Inarameter .. parameter .......");
String value = super.getParameter(parameter);
if (value == null) {
return null;
}
logger.info("Inarameter RequestWrapper ........ value .......");
return cleanXSS(value);
}
public String getHeader(String name) {
logger.info("Ineader .. parameter .......");
String value = super.getHeader(name);
if (value == null)
return null;
logger.info("Ineader RequestWrapper ........... value ....");
return cleanXSS(value);
}
private String cleanXSS(String value) {
// You'll need to remove the spaces from the html entities below
logger.info("InnXSS RequestWrapper ..............." + value);
//value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
//value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
//value = value.replaceAll("'", "& #39;");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("(?i)<script.*?>.*?<script.*?>", "");
value = value.replaceAll("(?i)<script.*?>.*?</script.*?>", "");
value = value.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", "");
value = value.replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", "");
//value = value.replaceAll("<script>", "");
//value = value.replaceAll("</script>", "");
logger.info("OutnXSS RequestWrapper ........ value ......." + value);
return value;
}
The only thing remained is the XML entry in the web.xml file:
<filter>
<filter-name>XSS</filter-name>
<display-name>XSS</display-name>
<description></description>
<filter-class>com.filter.CrossScriptingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>XSS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The /* indicates that for every request made from browser, it will call CrossScriptingFilter class. Which will parse all the components/elements came from the request & will replace all the javascript tags put by hacker with empty string i.e
Seeing that this is marked as gcc you can use the command line switch Wno-unused-parameter
.
For example:
gcc -Wno-unused-parameter test.c
Of course this effects the whole file (and maybe project depending where you set the switch) but you don't have to change any code.
type
%matplotlib qt
when you want graphs in a separate window and
%matplotlib inline
when you want an inline plot
According to the LanguageManual, you can use unix_timestamp()
to get the "current time stamp using the default time zone." If you need to convert that to something more human-readable, you can use from_unixtime(unix_timestamp())
.
Hope that helps.
Unfortunately, the DateTime.to_time, Time.to_datetime
and Time.parse
functions don't retain the timezone info. Everything is converted to local timezone during conversion. Date arithmetics still work but you won't be able to display the dates with their original timezones. That context information is often important. For example, if I want to see transactions performed during business hours in New York I probably prefer to see them displayed in their original timezones, not my local timezone in Australia (which 12 hrs ahead of New York).
The conversion methods below do keep that tz info.
For Ruby 1.8, look at Gordon Wilson's answer. It's from the good old reliable Ruby Cookbook.
For Ruby 1.9, it's slightly easier.
require 'date'
# Create a date in some foreign time zone (middle of the Atlantic)
d = DateTime.new(2010,01,01, 10,00,00, Rational(-2, 24))
puts d
# Convert DateTime to Time, keeping the original timezone
t = Time.new(d.year, d.month, d.day, d.hour, d.min, d.sec, d.zone)
puts t
# Convert Time to DateTime, keeping the original timezone
d = DateTime.new(t.year, t.month, t.day, t.hour, t.min, t.sec, Rational(t.gmt_offset / 3600, 24))
puts d
This prints the following
2010-01-01T10:00:00-02:00
2010-01-01 10:00:00 -0200
2010-01-01T10:00:00-02:00
The full original DateTime info including timezone is kept.
As something of an aside, MAXDOP can apparently be used as a workaround to a potentially nasty bug:
** -> "xampp->mysql->data" cut all files from data folder and paste to another folder
-> now restart mysql
-> paste all folders from your folder to myslq->data folder
and also paste ib_logfile0.ib_logfile1 , ibdata1 into data folder from your folder.
your database and your data is now available in phpmyadmin..**
It looks like body-parser
did support uploading files in Express 3, but support was dropped for Express 4 when it no longer included Connect as a dependency
After looking through some of the modules in mscdex's answer, I found that express-busboy
was a far better alternative and the closest thing to a drop-in replacement. The only differences I noticed were in the properties of the uploaded file.
console.log(req.files)
using body-parser (Express 3) output an object that looked like this:
{ file:
{ fieldName: 'file',
originalFilename: '360px-Cute_Monkey_cropped.jpg',
name: '360px-Cute_Monkey_cropped.jpg'
path: 'uploads/6323-16v7rc.jpg',
type: 'image/jpeg',
headers:
{ 'content-disposition': 'form-data; name="file"; filename="360px-Cute_Monkey_cropped.jpg"',
'content-type': 'image/jpeg' },
ws:
WriteStream { /* ... */ },
size: 48614 } }
compared to console.log(req.files)
using express-busboy (Express 4):
{ file:
{ field: 'file',
filename: '360px-Cute_Monkey_cropped.jpg',
file: 'uploads/9749a8b6-f9cc-40a9-86f1-337a46e16e44/file/360px-Cute_Monkey_cropped.jpg',
mimetype: 'image/jpeg',
encoding: '7bit',
truncated: false
uuid: '9749a8b6-f9cc-40a9-86f1-337a46e16e44' } }
From a comment:
I want to sort each set.
That's easy. For any set s
(or anything else iterable), sorted(s)
returns a list of the elements of s
in sorted order:
>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']
Note that sorted
is giving you a list
, not a set
. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2}
and {2, 1}
are the same set.
You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).
The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key
function:
>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']
For more information, see the Sorting HOWTO in the official docs.
* See the comments for exceptions.
For myself, using Jquery lib 2.1.1 the following did NOT work the way I expected:
Set element data attribute value:
$('.my-class').data('num', 'myValue');
console.log($('#myElem').data('num'));// as expected = 'myValue'
BUT the element itself remains without the attribute:
<div class="my-class"></div>
I needed the DOM updated so I could later do $('.my-class[data-num="myValue"]') //current length is 0
So I had to do
$('.my-class').attr('data-num', 'myValue');
To get the DOM to update:
<div class="my-class" data-num="myValue"></div>
Whether the attribute exists or not $.attr will overwrite.
No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.
You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.
Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto
is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100%
like this fiddle.
img {
width: 100%;
height: auto;
}
You'll need to reload the table on the UI
thread via:
//swift 2.3
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
//swift 5
DispatchQueue.main.async{
self.tableView.reloadData()
}
Follow up:
An easier alternative to the connection.start()
approach is to instead use NSURLConnection.sendAsynchronousRequest(...)
//NSOperationQueue.mainQueue() is the main thread
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url), queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
//check error
var jsonError: NSError?
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &jsonError)
//check jsonError
self.collectionView?.reloadData()
}
This doesn't allow you the flexibility of tracking the bytes though, for example you might want to calculate the progress of the download via bytesDownloaded/bytesNeeded
Swift 4 way to check for substrings, including the necessary Foundation
(or UIKit
) framework import:
import Foundation // or UIKit
let str = "Oh Canada!"
str.contains("Can") // returns true
str.contains("can") // returns false
str.lowercased().contains("can") // case-insensitive, returns true
Unless Foundation
(or UIKit
) framework is imported, str.contains("Can")
will give a compiler error.
This answer is regurgitating manojlds's answer, which is completely correct. I have no idea why so many answers go through so much trouble to recreate Foundation
's String.contains(subString: String)
method.
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
Step 1: Go to the download site from Gradle: https://gradle.org/releases/
Step 2: Extract the downloaded zip file into a directory.
Step 2: Hit Ctrl + Alt + S (mac: ? + ,) in Android studio/Intellij IDEA
Step 3: Goto: Build, Execution, Deployment >> Build Tools >> Gradle (Or just type in the searchbar Gradle)
Step 4: Select: (X) Use local gradle distribution and set Gradle home to your extracted Gradle directory. Click on apply.
Step 5: Get rid of your unnecessary gradle files delete:
- MyApp/gradle/
- gradlew
- gradlew.bat
Just to add to the accepted answer, as all the answers seem to talk about android.graphics.Color
only: what if the color I want is defined in res/values/colors.xml
?
For example, consider Material Design colors defined in colors.xml
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="md_blue_500">#2196F3</color>
</resources>
(android_material_design_colours.xml
is your best friend)
Then use ContextCompat.getColor(getContext(), R.color.md_blue_500)
where you would use Color.BLUE
, so that:
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
becomes:
wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.md_blue_500)), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Where I found that:
Closing a window that was opened by the user through JavaScript is considered to be a security risk, thus not all browsers will allow this (which is why all solutions are hacks/workarounds). Browsers that are steadily maintained remove these types of hacks, and solutions that work one day may be broken the next.
This was addressed here by rvighne in a similar question on the subject.
If you want to record video from within a web browser, I think your only option is Flash. We are looking to do the same thing. We are also primarily a .NET house and I don't see a way to use .NET to capture the webcam _from_within_the_browser_. All of the other solutions mentioned here would probably work great if you are happy to settle for a desktop app
_.toArray(obj);
Outputs as:
[
{
"name": "Ivan",
"id": 12,
"friends": [
2,
44,
12
],
"works": {
"books": [],
"films": []
}
},
{
"name": "John",
"id": 22,
"friends": [
5,
31,
55
],
"works": {
"books": [],
"films": []
}
}
]"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(string.length > 0)
{
NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];
BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
return stringIsValid;
}
return YES;
}
PL/SQL: numeric or value error: character string buffer too small
is due to the fact that you declare a string to be of a fixed length (say 20), and at some point in your code you assign it a value whose length exceeds what you declared.
for example:
myString VARCHAR2(20);
myString :='abcdefghijklmnopqrstuvwxyz'; --length 26
will fire such an error
contentCompressionResistancePriority – The view with the lowest value gets truncated when there is not enough space to fit everything’s intrinsicContentSize
contentHuggingPriority – The view with the lowest value gets expanded beyond its intrinsicContentSize
when there is leftover space to fill
In case anyone is still wondering...
I did it like this:
<a href="data:application/xml;charset=utf-8,your code here" download="filename.html">Save</a>
cant remember my source but it uses the following techniques\features:
Found the reference:
http://paxcel.net/blog/savedownload-file-using-html5-javascript-the-download-attribute-2/
EDIT: As you can gather from the comments this does NOT work in
--Find and drop the constraints
DECLARE @dynamicSQL VARCHAR(MAX)
DECLARE MY_CURSOR CURSOR
LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT dynamicSQL = 'ALTER TABLE [' + OBJECT_SCHEMA_NAME(parent_object_id) + '].[' + OBJECT_NAME(parent_object_id) + '] DROP CONSTRAINT [' + name + ']'
FROM sys.foreign_keys
WHERE object_name(referenced_object_id) in ('table1', 'table2', 'table3')
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @dynamicSQL
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @dynamicSQL
EXEC (@dynamicSQL)
FETCH NEXT FROM MY_CURSOR INTO @dynamicSQL
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
-- Drop tables
DROP 'table1'
DROP 'table2'
DROP 'table3'
server {
server_name example.com;
root /path/to/root;
location / {
# bla bla
}
location /demo {
alias /path/to/root/production/folder/here;
}
}
If you need to use try_files
inside /demo
you'll need to replace alias
with a root
and do a rewrite because of the bug explained here
In Eclipse Ganymede (3.4.0):
Use Advanced BAT to EXE Converter from http://www.battoexeconverter.com
This will allow you to embed any additional binaries with your batch file in to one stand alone completely silent EXE and its freeware
Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html
I've had the same issue before. After analyzing my code, I realized that attempting to reset the iterator inside of loops slightly increases the time complexity and it also makes the code a bit ugly.
Open the file and save the rows to a variable in memory.
# initialize list of rows
rows = []
# open the file and temporarily name it as 'my_file'
with open('myfile.csv', 'rb') as my_file:
# set up the reader using the opened file
myfilereader = csv.DictReader(my_file)
# loop through each row of the reader
for row in myfilereader:
# add the row to the list of rows
rows.append(row)
Now you can loop through rows anywhere in your scope without dealing with an iterator.
Performance wise, this should be comparable. Use Select statement and Sort to get a list and then pick the first or last (depending on your sort order).
var col = dt.Select("AccountLevel", "AccountLevel ASC");
var min = col.First();
var max = col.Last();
As suggested on the python-dev mailinglist recently, the runpy module might be a viable alternative. Quoting from that message:
https://docs.python.org/3/library/runpy.html#runpy.run_path
import runpy file_globals = runpy.run_path("file.py")
There are subtle differences to execfile
:
run_path
always creates a new namespace. It executes the code as a module, so there is no difference between globals and locals (which is why there is only a init_globals
argument). The globals are returned.
execfile
executed in the current namespace or the given namespace. The semantics of locals
and globals
, if given, were similar to locals and globals inside a class definition.
run_path
can not only execute files, but also eggs and directories (refer to its documentation for details).
You could use this function:
function RefreshTable(tableId, urlData)
{
//Retrieve the new data with $.getJSON. You could use it ajax too
$.getJSON(urlData, null, function( json )
{
table = $(tableId).dataTable();
oSettings = table.fnSettings();
table.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
table.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
});
}
Dont' forget to call it after your delete function has succeded.
String extends Object, which means an Object. Object o = a;
If you really want to get as Object, you may do like below.
String s = "Hi";
Object a =s;
Place your widget.js after core.js, but before any other jquery that calls the widget.js file. (Example: draggable.js) Precedence (order) matters in what javascript/jquery can 'see'. Always position helper code before the code that uses the helper code.
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('10544175A')
UNION
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('10328189B')
UNION
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('103498732H')
No, but you could cast the whole expression rather than the sub-components of that expression. Actually, that probably makes it less readable in this case.
Click on wampserver icon then -> Apache -> httpd.conf -> search listen here you will find port number like this #Listen 12.34.56.78:80
Listen 80 change this port number with any other number like Listen 12.34.56.78:81
save this and now restart all servers it gets green to orange.
about 3 years ago i needed cctv. I found zoneminder, tried to edit it to my liking, but found i was fixing it more than editing it.
Not to mention mp4 recording feature isn't actually part of the master branch (which is kind of lol, since its a cctv program and its already been about 3 years or more since it was suggested). Its literally just adapting the ffmpeg command lol.
So i found the solution!
If you want something done right, do it yourself.
I present to you Shinobi! Shinobi : The Open Source CCTV Platform
Use $('ul#menu').children('li').length
.size() instead of .length will also work
To answer your question as it was posed I would have to say, "No, mathematics is not necessary for programming". However, as other people have suggested in this thread, I believe there is a correlation between understanding mathematics and being able to "think algorithmically". That is, to be able to think abstractly about quantity, processes, relationships and proof.
I started programming when I was about 9 years old and it would be a stretch to say I had learnt much mathematics by that stage. However, with a bit of effort I was able to understand variables, for loops, goto statements (forgive me, I was Vic 20 BASIC and I hadn't read any Dijkstra yet) and basic co-ordinate geometry to put graphics on the screen.
I eventually went on to complete an honours degree in Pure Mathematics with a minor in Computer Science. Although I focused mainly on analysis, I also studied quite a bit of discrete maths, number theory, logic and computability theory. Apart from being able to apply a few ideas from statistics, probability theory, vector analysis and linear algebra to programming, there was little maths I studied that was directly applicable to my programming during my undergraduate degree and the commercial and research programming I did afterwards.
However, I strongly believe the formal methods of thinking that mathematics demands — careful reasoning, searching for counter-examples, building axiomatic foundations, spotting connections between concepts — has been a tremendous help when I have tackled large and complex programming projects.
Consider the way athletes train for their sport. For example, footballers no doubt spend much of their training time on basic football skills. However, to improve their general fitness they might also spend time at the gym on bicycle or rowing machines, doing weights, etc.
Studying mathematics can be likened to weight-training or cross-training to improve your mental strength and stamina for programming. It is absolutely essential that you practice your basic programming skills but studying mathematics is an incredible mental work-out that improves your core analytic ability.
This was driving me crazy, but it seems that aularon's edit was missing the colon after "Vary"
. So changing "Vary Accept-Encoding"
to "Vary: Accept-Encoding"
fixed the issue for me.
I would have commented below the post, but it doesn't seem like it will let me.
Anyhow, I hope this saves someone the same trouble I was having.
So, let's say you have this table:
CREATE TABLE YourTable(Col1 VARCHAR(10))
And you want to change Col1
to VARCHAR(20)
. What you need to do is this:
ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)
That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5)
, then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE
will fail.
I would suggest using conda. Conda is an anconda specific package manager. If you want to know more about conda, read the conda docs.
Using conda in the command line, the command below would install scipy 0.17.
conda install scipy=0.17.0
PS> Get-CimInstance -ComputerName bobPC win32_logicaldisk | where caption -eq "C:" | foreach-object {write " $($_.caption) $('{0:N2}' -f ($_.Size/1gb)) GB total, $('{0:N2}' -f ($_.FreeSpace/1gb)) GB free "}
C: 117.99 GB total, 16.72 GB free
PS>
In my case, the problem was solved by adding this line to the module build.gradle:
// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'
I would try the following syntax - it works for me.
msiexec /x filename.msi /q
I think a better approach will be to set app:tabMode="auto"
and app:tabGravity="fill"
because setting tabMode to fixed can make headings congested and cause headings to occupy multiple lines on the other side setting it to scrollable could make them leave spaces at the end in some screen sizes. manually setting tabMode would give a problem when dealing with multiple screen sizes
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
app:tabGravity="fill"
android:textAlignment="center"
app:tabMode="auto"
/>
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
listagg
got recently covered by the ISO SQL standard (SQL:2016). As part of that, it also got an on overflow
clause, which is supported by Oracle 12cR2.
LISTAGG(<expression>, <separator> ON OVERFLOW …)
The on overflow
clause supports a truncate
option (as alternative to the default on overflow error
behavior).
ON OVERFLOW TRUNCATE [<filler>] WITH[OUT] COUNT
The optional defaults to three periods (...) and will be added as last element if truncation happens.
If with count is specified and truncation happens, the number of omitted values is put in brackets and appended to the result.
More about listagg
's on overflow
clause: http://modern-sql.com/feature/listagg
Basically, the problem lies in block12. for the block1/2 to take up the total height of the block12, it must have a defined height. This stack overflow post explains that in really good detail.
So setting a defined height for block12 will allow you to set a proper height. I have created an example on JSfiddle that will show you the the blocks can be floated next to one another if the block12 div is set to a standard height through out the page.
Here is an example including a header and block3 div with some content in for examples.
#header{
position:absolute;
top:0;
left:0;
width:100%;
height:20%;
}
#block12{
position:absolute;
top:20%;
width:100%;
left:0;
height:40%;
}
#block1,#block2{
float:left;
overflow-y: scroll;
text-align:center;
color:red;
width:50%;
height:100%;
}
#clear{clear:both;}
#block3{
position:absolute;
bottom:0;
color:blue;
height:40%;
}
When we have to use inbuilt procedures or packages we have to use "EXECUTE" command then it will work.
EX:
EXECUTE exec DBMS_MVIEW.REFRESH('v_materialized_foo_tbl');
The preflight is being triggered by your Content-Type of application/json
. The simplest way to prevent this is to set the Content-Type to be text/plain
in your case. application/x-www-form-urlencoded
& multipart/form-data
Content-Types are also acceptable, but you'll of course need to format your request payload appropriately.
If you are still seeing a preflight after making this change, then Angular may be adding an X-header to the request as well.
Or you might have headers (Authorization, Cache-Control...) that will trigger it, see:
Well, i guess M represent the mantissa. Decimal can be used to save money, but it doesn't mean, decimal only used for money.
If you want to have your code os-unspecific you should use println for each word
System.out.println("I");
System.out.println("am");
System.out.println("a");
System.out.println("boy");
because Windows uses "\r\n" as newline and unixoid systems use just "\n"
println always uses the correct one
summary:
df = pd.DataFrame({'money': [100.456, 200.789], 'share': ['100,000', '200,000']})
print(df)
print(df.to_string(formatters={'money': '${:,.2f}'.format}))
for col_name in ('share',):
df[col_name] = df[col_name].map(lambda p: int(p.replace(',', '')))
print(df)
"""
money share
0 100.456 100,000
1 200.789 200,000
money share
0 $100.46 100,000
1 $200.79 200,000
money share
0 100.456 100000
1 200.789 200000
"""
As you said:
if you are adding conditions dynamically you don't have to worry about stripping the initial AND that's the only reason could be, you are right.
For Node.js users:
const myBuffer = Buffer.from(someBase64String, 'base64');
myBuffer will be of type Buffer which is a subclass of Uint8Array. Unfortunately, Uint8Array is NOT an ArrayBuffer as the OP was asking for. But when manipulating an ArrayBuffer I almost always wrap it with Uint8Array or something similar, so it should be close to what's being asked for.
Use this function:
function getDatetimeNow() {
$tz_object = new DateTimeZone('Brazil/East');
//date_default_timezone_set('Brazil/East');
$datetime = new DateTime();
$datetime->setTimezone($tz_object);
return $datetime->format('Y\-m\-d\ h:i:s');
}
Typescript distinguishes two different kinds of modules: Internal modules are used to structure your code internally. At compile-time, you have to bring internal modules into scope using reference paths:
/// <reference path='moo.ts'/>
class bar extends moo.foo {
}
On the other hand, external modules are used to refernence external source files that are to be loaded at runtime using CommonJS or AMD. In your case, to use external module loading you have to do the following:
moo.ts
export class foo {
test: number;
}
app.ts
import moo = module('moo');
class bar extends moo.foo {
test2: number;
}
Note the different way of brining the code into scope. With external modules, you have to use module
with the name of the source file that contains the module definition. If you want to use AMD modules, you have to call the compiler as follows:
tsc --module amd app.ts
This then gets compiled to
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
}
define(["require", "exports", 'moo'], function(require, exports, __moo__) {
var moo = __moo__;
var bar = (function (_super) {
__extends(bar, _super);
function bar() {
_super.apply(this, arguments);
}
return bar;
})(moo.foo);
})
I'd go with the following:
Select max(start_ts)
from db
where trunc(start_ts) = date'13-may-2016'
HTML5 has several goals which differentiate it from HTML4.
The primary one is consistent, defined error handling. As you know, HTML purposely supports 'tag soup', or the ability to write malformed code and have it corrected into a valid document. The problem is that the rules for doing this aren't written down anywhere. When a new browser vendor wants to enter the market, they just have to test malformed documents in various browsers (especially IE) and reverse-engineer their error handling. If they don't, then many pages won't display correctly (estimates place roughly 90% of pages on the net as being at least somewhat malformed).
So, HTML5 is attempting to discover and codify this error handling, so that browser developers can all standardize and greatly reduce the time and money required to display things consistently. As well, long in the future after HTML has died as a document format, historians may still want to read our documents, and having a completely defined parsing algorithm will greatly aid this.
The secondary goal of HTML5 is to develop the ability of the browser to be an application platform, via HTML, CSS, and Javascript. Many elements have been added directly to the language that are currently (in HTML4) Flash or JS-based hacks, such as <canvas>
, <video>
, and <audio>
. Useful things such as Local Storage (a js-accessible browser-built-in key-value database, for storing information beyond what cookies can hold), new input types such as date for which the browser can expose easy user interface (so that we don't have to use our js-based calendar date-pickers), and browser-supported form validation will make developing web applications much simpler for the developers, and make them much faster for the users (since many things will be supported natively, rather than hacked in via javascript).
There are many other smaller efforts taking place in HTML5, such as better-defined semantic roles for existing elements (<strong>
and <em>
now actually mean something different, and even <b>
and <i>
have vague semantics that should work well when parsing legacy documents) and adding new elements with useful semantics - <article>
, <section>
, <header>
, <aside>
, and <nav>
should replace the majority of <div>
s used on a web page, making your pages a bit more semantic, but more importantly, easier to read. No more painful scanning to see just what that random </div>
is closing - instead you'll have an obvious </header>
, or </article>
, making the structure of your document much more intuitive.
This one worked for me
var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});
The documentation for Environment.UserName seems to be a bit conflicting:
On the same page it says:
Gets the user name of the person who is currently logged on to the Windows operating system.
AND
displays the user name of the person who started the current thread
If you test Environment.UserName using RunAs, it will give you the RunAs user account name, not the user originally logged on to Windows.
This should make it work in both cases
function onDateChange() {
// Do something here
}
$('#dpd1').bind('changeDate', onDateChange);
$('#dpd1').bind('input', onDateChange);
I've had multenum for "Multi-column enumerated lists" recommended to me, but I've never actually used it myself, yet.
Edit: The syntax doesn't exactly look like you could easily copy+paste lists into the LaTeX code. So, it may not be the best solution for your use case!
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
Something that sometimes crops up you may/maynot be aware of
Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE
As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?
If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?
No need to use jquery for any major browser to swap elements at the moment. Native dom method, insertAdjacentElement
does the trick no matter how they are located:
var el1 = $("el1");
var el2 = $("el2");
el1[0].insertAdjacentElement("afterend", el2[0]);
Here is a python3 method using str.translate
and str.maketrans
:
s = "abc&def#ghi"
print(s.translate(str.maketrans({'&': '\&', '#': '\#'})))
The printed string is abc\&def\#ghi
.
Update December 2012 (19 months later):
The blog post "Jin Mingjian: Eclipse Darker Theme" mentions this GitHub repo "eclipse themes - darker":
The big fun is that, the codes are minimized by using Eclipse4 platform technologies like dependency injection.
It proves that again, the concise codes and advanced features could be achieved by contributing or extending with the external form (like library, framework).
New language is not necessary just for this kind of purpose.
Update July 2012 (14 months later):
With the latest Eclipse4.2 (June 2012, "Juno") release, you can implement what I originally described below: a CSS-based fully dark theme for Eclipse.
See the article by Lars Vogel in "Eclipse 4 is beautiful – Create your own Eclipse 4 theme":
If you want to play with it, you only need to write a plug-in, create a CSS file and use the
org.eclipse.e4.ui.css.swt.theme
extension point to point to your file.
If you export your plug-in, place it in the “dropins” folder of your Eclipse installation and your styling is available.
Original answer: August 2011
With Eclipse 3.x, theme is only for the editors, as you can see in the site "Eclipse Color Themes".
Anything around that is managed by windows system colors.
That is what you need to change to have any influence on Eclipse global colors around editors.
Eclipse 4 will provide much advance theme options: See "Eclipse 4.0 – So you can theme me Part 1" and "Eclipse 4.0 RCP: Dynamic CSS Theme Switching".
You could take any of the answers above that use the string.length method and replace it with string.size.
They both work the same way.
if string.size <= 25
puts "No problem here!"
else
puts "Sorry too long!"
end
For the once who receive this error while requesting large JSON data it is, as mentioned by Blauhirn, not a solution to just open the request in new tab if you are using authentication headers and suchlike.
Forturnatly chrome does have other options such as Copy -> Copy as curl. Running this call from the commandoline through cURL will be a exact replicate of the original call.
I added > ~/result.json
to the last part of the commando to save the result to a file.
Otherwise it will be outputted to the console.
q <- c(1,1,2,2,3,3,3,4,4,5,5,7,7)
rm <- q[11]
remove(rm)
q
q[13] = NaN
q
q %in% 7
This sets the 13 in a vector to not a number(NAN) it shows false remove(q[c(11,12,13)]) if you try this you will see that remove function don't work on vector number. you remove entire vector but maybe not a single element.
You can write your own Extension method for type String :-
public static string NonBlankValueOf(this string source)
{
return (string.IsNullOrEmpty(source)) ? "0" : source;
}
Now you can use it like with any string type
FooTextBox.Text = strFoo.NonBlankValueOf();
The substring starts at, and includes the character at the location of the first number given and goes to, but does not include the character at the last number given.
You can set the width in pixels via inline styling:
<input type="text" name="text" style="width: 195px;">
You can also set the width with a visible character length:
<input type="text" name="text" size="35">
Option 1: Discard tracked and untracked file changes
Discard changes made to both staged and unstaged files.
$ git reset --hard [HEAD]
Then discard (or remove) untracked files altogether.
$ git clean [-f]
Option 2: Stash
You can first stash your changes
$ git stash
And then either drop or pop it depending on what you want to do. See https://git-scm.com/docs/git-stash#_synopsis.
Option 3: Manually restore files to original state
First we switch to the target branch
$ git checkout <branch-name>
List all files that have changes
$ git status
Restore each file to its original state manually
$ git restore <file-path>
Note: Because this post's answer sometimes gets upvoted, I came back here to kindly ask people not to upvote it anymore. My answer is ancient, not technically correct, and there are several better approaches right here. I'm only keeping it here for historical purposes.
Although the documentation poorly describes the strtotime function, @rjmunro correctly addressed the issue in his comment: it's in ISO format date "YYYY-MM-DD".
Also, even though my Date_Converter function might still work, I'd like to warn that there may be imprecise statements below, so please do disregard them.
The most voted answer is actually incorrect!
The PHP strtotime manual here states that "The function expects to be given a string containing an English date format". What it actually means is that it expects an American US date format, such as "m-d-Y" or "m/d/Y".
That means that a date provided as "Y-m-d" may get misinterpreted by strtotime
. You should provide the date in the expected format.
I wrote a little function to return dates in several formats. Use and modify at will. If anyone does turn that into a class, I'd be glad if that would be shared.
function Date_Converter($date, $locale = "br") {
# Exception
if (is_null($date))
$date = date("m/d/Y H:i:s");
# Let's go ahead and get a string date in case we've
# been given a Unix Time Stamp
if ($locale == "unix")
$date = date("m/d/Y H:i:s", $date);
# Separate Date from Time
$date = explode(" ", $date);
if ($locale == "br") {
# Separate d/m/Y from Date
$date[0] = explode("/", $date[0]);
# Rearrange Date into m/d/Y
$date[0] = $date[0][1] . "/" . $date[0][0] . "/" . $date[0][2];
}
# Return date in all formats
# US
$Return["datetime"]["us"] = implode(" ", $date);
$Return["date"]["us"] = $date[0];
# Universal
$Return["time"] = $date[1];
$Return["unix_datetime"] = strtotime($Return["datetime"]["us"]);
$Return["unix_date"] = strtotime($Return["date"]["us"]);
$Return["getdate"] = getdate($Return["unix_datetime"]);
# BR
$Return["datetime"]["br"] = date("d/m/Y H:i:s", $Return["unix_datetime"]);
$Return["date"]["br"] = date("d/m/Y", $Return["unix_date"]);
# Return
return $Return;
} # End Function
For the following HTML (from Bootstrap 3 examples):
.panel-heading .accordion-toggle:after {_x000D_
/* symbol for "opening" panels */_x000D_
font-family: 'Glyphicons Halflings'; /* essential for enabling glyphicon */_x000D_
content: "\e114"; /* adjust as needed, taken from bootstrap.css */_x000D_
float: right; /* adjust as needed */_x000D_
color: grey; /* adjust as needed */_x000D_
}_x000D_
.panel-heading .accordion-toggle.collapsed:after {_x000D_
/* symbol for "collapsed" panels */_x000D_
content: "\e080"; /* adjust as needed, taken from bootstrap.css */_x000D_
}
_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript" ></script>_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript" ></script>_x000D_
_x000D_
<div class="panel-group" id="accordion">_x000D_
<div class="panel panel-default">_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">_x000D_
Collapsible Group Item #1_x000D_
</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div id="collapseOne" class="panel-collapse collapse in">_x000D_
<div class="panel-body">_x000D_
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS._x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">_x000D_
Collapsible Group Item #2_x000D_
</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div id="collapseTwo" class="panel-collapse collapse">_x000D_
<div class="panel-body">_x000D_
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS._x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">_x000D_
Collapsible Group Item #3_x000D_
</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div id="collapseThree" class="panel-collapse collapse">_x000D_
<div class="panel-body">_x000D_
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS._x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Visual effect:
Your vector<string> userString
has size 0
, so the loop is never entered. You could start with a vector of a given size:
vector<string> userString(10);
string word;
string sentence;
for (decltype(userString.size()) i = 0; i < userString.size(); ++i)
{
cin >> word;
userString[i] = word;
sentence += userString[i] + " ";
}
although it is not clear why you need the vector at all:
string word;
string sentence;
for (int i = 0; i < 10; ++i)
{
cin >> word;
sentence += word + " ";
}
If you don't want to have a fixed limit on the number of input words, you can use std::getline
in a while
loop, checking against a certain input, e.g. "q"
:
while (std::getline(std::cin, word) && word != "q")
{
sentence += word + " ";
}
This will add words to sentence
until you type "q".
I have created this jquery that solved my problem.
public void ChangeClassIntoSelected(String name,String div) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("Array.from($(\"div." + div +" ul[name=" + name + "]\")[0].children).forEach((element, index) => {\n" +
" $(element).addClass('ui-selected');\n" +
"});");
}
With this script you are able to change the actual class name into some other thing.
Another way based on amadan:
SELECT * FROM [Purchasing].[Vendor] WHERE
( (@url IS null OR @url = '' OR @url = 'ALL') and PurchasingWebServiceURL LIKE '%')
or
( @url = 'blank' and PurchasingWebServiceURL = '')
or
(@url = 'fail' and PurchasingWebServiceURL NOT LIKE '%treyresearch%')
or( (@url not in ('fail','blank','','ALL') and @url is not null and
PurchasingWebServiceUrl Like '%'+@ur+'%')
END
Laravel 6 or on the top: Write the table name, then give where clause condition for instance where('id', $request->id)
public function store(Request $request)
{
$target = DB:: table('categories')
->where('title', $request->name)
->get()->first();
if ($target === null) { // do what ever you need to do
$cat = new Category();
$cat->title = $request->input('name');
$cat->parent_id = $request->input('parent_id');
$cat->user_id=auth()->user()->id;
$cat->save();
return redirect(route('cats.app'))->with('success', 'App created successfully.');
}else{ // match found
return redirect(route('cats.app'))->with('error', 'App already exists.');
}
}
Use the css "rotate()" method:
div {
width: 100px;
height: 100px;
background-color: yellow;
border: 1px solid black;
}
div#rotate{
transform: rotate(90deg);
}
_x000D_
<div>
normal div
</div>
<br>
<div id="rotate">
This div is rotated 90 degrees
</div>
_x000D_
Multiple statements are to be separated by a new line:
If SkyIsBlue Then
StartEngines
Pollute
ElseIf SkyIsRed Then
StopAttack
Vent
ElseIf SkyIsYellow Then
If Sunset Then
Sleep
ElseIf Sunrise or IsMorning Then
Smoke
GetCoffee
Else
Error
End If
Else
Joke
Laugh
End If
Restart your IDE and everything will be fine
1. Generalized Substring
To generalise the question and the answer of gniourf_gniourf (as this is what I was searching for), if you want to cut a range of characters from, say, 7th from the end to 3rd from the end, you can use this syntax:
${string: -7:4}
Where 4 is the length of course (7-3).
2. Alternative using cut
In addition, while the solution of gniourf_gniourf is obviously the best and neatest, I just wanted to add an alternative solution using cut:
echo $string | cut -c $((${#string}-2))-
Here, ${#string}
is the length of the string, and the "-" means cut to the end.
3. Alternative using awk
This solution instead uses the substring function of awk to select a substring which has the syntax substr(string, start, length)
going to the end if the length is omitted. length($string)-2)
thus picks up the last three characters.
echo $string | awk '{print substr($1,length($1)-2) }'
use centered class with offset-6 like below sample.
<body class="container">
<div class="col-lg-1 col-offset-6 centered">
<img data-src="holder.js/100x100" alt="" />
</div>
I am not sure how this happened but I started to get this error in my internal submit form pages. So when ever I submit something I'm getting this error. But the problem is this website is almost working 5-6 years. I don't remember I made an important change.
None of the solutions worked for me.
I have setup a machine key with the Microsoft script and copied into my web.config
I have executed asp.net regiis script.
aspnet_regiis -ga "IIS APPPOOL\My App Pool"
Also tried to add this code into the page:
enableViewStateMac="false"
still no luck.
Any other idea to solve this issue?
UPDATE:
Finally I solved the issue. I had integrated my angular 4 component into my asp.net website. So I had added base href into my master page. So I removed that code and it is working fine now.
<base href="/" />
Add this to your Activity class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
// some your code
}
If you are sure there are no commas in your input, other than to separate the category, you can read the file line by line and split on ,
, then push the result to List
That said, it looks like you are looking at a CSV file, so you might consider using the modules for it
When you override the init you have also to call the init of the parent class
super(Num2, self).__init__(num)
If your using embedded Derby you need Derby.jar in your classpath.
If you dont want to mess around with path variables (e.g. if you are no admin) and if you are working on windows, you can do the following which solved the problem for me.
Open graphviz.py
(likely located in ...Anaconda\pkgs\graphviz***\Library\bin
) in an editor. If you cant find it you might be able to open it via the error message.
Go to the fuction __find_executables
and replace:
elif os.path.exists(os.path.join(path, prg + '.exe')):
if was_quoted:
progs[prg] = '"' + os.path.join(path, prg + '.exe') + '"'
else:
progs[prg] = os.path.join(path, prg + '.exe')
with
elif os.path.exists(os.path.join(path, prg + '.bat')):
if was_quoted:
progs[prg] = '"' + os.path.join(path, prg + '.bat') + '"'
else:
progs[prg] = os.path.join(path, prg + '.bat')
Another option:
Advantages:
Disadvantages:
If you're running a single node cluster for some reason, you might simply need to do avoid replicas, like this:
curl -XPUT -H 'Content-Type: application/json' 'localhost:9200/_settings' -d '
{
"index" : {
"number_of_replicas" : 0
}
}'
Doing this you'll force to use es without replicas
After a quality time I have found, theme option is the main problem in my code And following is the proper way to show the toolbar for me
In AndroidManifest file first you have to change your theme style
Theme.AppCompat.Light.DarkActionBar
to
Theme.AppCompat.Light.NoActionBar
then at your activity xml you need to call your own Toolbar like
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:id="@+id/toolbar"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:elevation="4dp"/>
And then this toolbar should be called in your Java file by
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
And for toolbar showing U should check the null to avoid NullPointerException
if(getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
For Home activity back add this
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
OR for your desired activity back
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), YourActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
Try putting a background color on a block div with width and height. You'll see that padding increases the size of the element, whereas margin just moves it within the flow of the document.
Margin is specifically for shifting the element around.
That won't work if the string contains more than one match... try this:
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo " $0) }'
or better (if the echo
isn't a placeholder for something else):
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'
In your case you want to make a copy of the value before changing it:
echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
The above options do not work for maps created with sf
and geom_sf()
. Hence, I want to add the relevant ndiscr
parameter here. This will create a nice clean map showing only the features.
library(sf)
library(ggplot2)
ggplot() +
geom_sf(data = some_shp) +
theme_minimal() + # white background
theme(axis.text = element_blank(), # remove geographic coordinates
axis.ticks = element_blank()) + # remove ticks
coord_sf(ndiscr = 0) # remove grid in the background
I had trouble binding a value with any of the symbols in AngularJS 1.6. I did not get any value at all, only undefined
, even though I did it the exact same way as other bindings in the same file that did work.
Problem was: my variable name had an underscore.
This fails:
bindings: { import_nr: '='}
This works:
bindings: { importnr: '='}
(Not completely related to the original question, but that was one of the top search results when I looked, so hopefully this helps someone with the same problem.)
The problem is that your <label>
is inside of an <h2>
tag, and header tags have a margin
set by the default stylesheet.
If the result is for humans to read and the elements of the array have a proper toString()
defined...
outputString.write(Arrays.toString(array));
select *
from sys.configurations
where name = 'clr enabled'
The simplest way is to convert Date to POSIXlt format. Then perform the arithmetic operation as follows:
date_1m_fwd <- as.POSIXlt("2010-01-01")
date_1m_fwd$mon <- date_1m_fwd$mon +1
Moreover, incase you want to deal with Date columns in data.table, unfortunately, POSIXlt format is not supported.
Still you can perform the add month using basic R codes as follows:
library(data.table)
dt <- as.data.table(seq(as.Date("2010-01-01"), length.out=5, by="month"))
dt[,shifted_month:=tail(seq(V1[1], length.out=length(V1)+3, by="month"),length(V1))]
Hope it helps.
Bearer tokens look like this:
curl -H "Authorization: Bearer <ACCESS_TOKEN>" http://www.example.com
The cvWaitKey
simply provides something of a delay. For example:
char c = cvWaitKey(33);
if( c == 27 ) break;
Tis was apart of my code in which a video was loaded into openCV and the frames outputted. The 33
number in the code means that after 33ms
, a new frame would be shown. Hence, the was a dely or time interval of 33ms
between each frame being shown on the screen.
Hope this helps.
This is a peculiar question because it's not supposed to be a matter of choice.
When you launch the JVM, you specify a class to run, and it is the main()
of this class where your program starts.
By init()
, I assume you mean the JApplet method. When an applet is launched in the browser, the init()
method of the specified applet is executed as the first order of business.
By run()
, I assume you mean the method of Runnable. This is the method invoked when a new thread is started.
If Eclipse is running your run()
method even though you have no main()
, then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.
This is an easy way to add an underline, while maintaining other settings:
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Use attribute binding syntax instead
<ol class="viewer-nav"><li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value">{{ section.text }}</li>
</ol>
or
<ol class="viewer-nav"><li *ngFor="let section of sections"
attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>
</ol>
My example code was correct and the issue was something else in my actual code. Still, I know it was difficult to find examples of this so I'm answering it in case someone else is looking.
<div ng-repeat="f in foos">
<div>
<div ng-repeat="b in foos.bars">
<a ng-click="addSomething($parent.$index)">Add Something</a>
</div>
</div>
</div>
Use this
<script>
$(document).ready(function(){
$( '.expand' ).click(function() {
$( '.img_display_content' ).show();
});
});
</script>
Event assigning always after Document Object Model loaded
export CFLAGS=-m32
As GvS said, but I also find it useful to use strongly typed views so that I can write something like
@Html.Partial(MVC.Student.Index(), model)
without magic strings.
Use break;
to escape the first loop:
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
break;
}
If you want to also escape the second loop, you might need to use a flag and check in the out loop's guard:
boolean breakFlag = false;
while (!breakFlag)
{
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
breakFlag = true;
break;
}
}
}
Or, if you want to just exit the function completely from within the nested loop, put in a return;
instead of a break;
.
But these aren't really considered best practices. You should find some way to add the necessary Boolean logic into your while
guards.