As no one is talking about the why part, I'm gonna answer it.
Why this JSON.stringify
returns an empty object?
> JSON.stringify(error);
'{}'
Answer
From the document of JSON.stringify(),
For all the other Object instances (including Map, Set, WeakMap and WeakSet), only their enumerable properties will be serialized.
and Error
object doesn't have its enumerable properties, that's why it prints an empty object.
Here is what I did to find out the key that was being added twice. I downloaded the source code from http://referencesource.microsoft.com/DotNetReferenceSource.zip and setup VS to debug framework source. Opened up Dictionary.cs in VS ran the project, once page loads, added a debug at the line ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
and was able to see the 'key' value. I realized that in the JSON one letter of a variable was in upper case but in my model it was lowercase. I fixed the model and now the same code works.
You can get annotations on the getter method:
propertyDescriptor.getReadMethod().getDeclaredAnnotations();
Getting the annotations of a private field seems like a bad idea... what if the property isn't even backed by a field, or is backed by a field with a different name? Even ignoring those cases, you're breaking abstraction by looking at private stuff.
Document Object Model (DOM), a programming interface specification being developed by the World Wide Web Consortium (W3C), lets a programmer create and modify HTML pages and XML documents as full-fledged program objects.
Try this.
Does not require any options to change.
Does not require any command line activity.
Just run software and you will done the job.
www.vhghorecha.in/unhide-all-files-folders-virus/
Happy Knowledge Sharing
You don't need to pass this
, there already is the event
object passed by default automatically, which contains event.target
which has the object it's coming from. You can lighten your syntax:
This:
<p onclick="doSomething()">
Will work with this:
function doSomething(){
console.log(event);
console.log(event.target);
}
You don't need to instantiate the event
object, it's already there. Try it out. And event.target
will contain the entire object calling it, which you were referencing as "this" before.
Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event
is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent
:
document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));
Then doSomething()
will see event
and event.target
as per usual!
No need to pass this
everywhere, and you can keep your function signatures free from wiring information and simplify things.
If you have lots of columns and only one is different you could do:
In[1]: grouper = df.groupby('Company Name')
In[2]: res = grouper.count()
In[3]: res['Amount'] = grouper.Amount.sum()
In[4]: res
Out[4]:
Organisation Name Amount
Company Name
Vifor Pharma UK Ltd 5 4207.93
Note you can then rename the Organisation Name column as you wish.
You are copying all files to a single file called TEST_BACKUP_FOLDER
try this:
md TEST_BACKUP_FOLDER
copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER
SELECT * FROM table
where Date(col) = 'date'
Have you tried this:
import java.io.*;
import java.util.*;
import java.net.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
public class cat{
public static void main (String [] args) throws Exception{
try{
FileSystem fs = FileSystem.get(new Configuration());
FileStatus[] status = fs.listStatus(new Path("hdfs://test.com:9000/user/test/in")); // you need to pass in your hdfs path
for (int i=0;i<status.length;i++){
BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(status[i].getPath())));
String line;
line=br.readLine();
while (line != null){
System.out.println(line);
line=br.readLine();
}
}
}catch(Exception e){
System.out.println("File not found");
}
}
}
There are special cases where arrow functions
just won't do the trick:
If we're changing a method of an external API, and need the object's reference.
If we need to use special keywords that are exclusive to the function
expression: arguments
, yield
, bind
etc.
For more information:
Arrow function expression limitations
Example:
I assigned this function as an event handler in the Highcharts
API.
It's fired by the library, so the this
keyword should match a specific object.
export const handleCrosshairHover = function (proceed, e) {
const axis = this; // axis object
proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // method arguments
};
With an arrow function, this
would match the declaration scope, and we won't have access to the API obj:
export const handleCrosshairHover = (proceed, e) => {
const axis = this; // this = undefined
proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // compilation error
};
First execute python3
then type the command import pygame
,now you can see the output
You can revert only one file to a specified revision.
First you can check on which commits the file was changed.
git log path/to/file.txt
Then you can checkout the file with the revision number.
git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /path/to/file.txt
After that you can commit and push it again.
To 301 redirect all requests made directly to the domain to www you can use:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^([^.]+\.[^.]+){2,}$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
The benefit of this is that this will work if you have any valid subdomains, e.g.
example.com REDIRECTED TO www.example.com
foo.example.com NO REDIRECT
bar.example.com NO REDIRECT
This Perl code removes commas at the end of the line:
perl -pe 's/,$//' file > file.nocomma
This variation still works if there is whitespace after the comma:
perl -lpe 's/,\s*$//' file > file.nocomma
This variation edits the file in-place:
perl -i -lpe 's/,\s*$//' file
This variation edits the file in-place, and makes a backup file.bak
:
perl -i.bak -lpe 's/,\s*$//' file
You can try to load the child component with history. to do so, pass 'history' through props. Something like that:
return (
<div>
<Login history={this.props.history} />
<br/>
<Register/>
</div>
)
Try uninstalling Python and then install it again, but this time make sure that the option Add Python to Path is marked as checked during the installation process.
If injecting multiple script tags in the head like this with mix of local and remote script files a situation may arise where the local scripts that are dependent on external scripts (such as loading jQuery from googleapis) will have errors because the external scripts may not be loaded before the local ones are.
So something like this would have a problem: ("jQuery is not defined" in jquery.some-plugin.js).
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js";
head.appendChild(script);
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "/jquery.some-plugin.js";
head.appendChild(script);
Of course this situation is what the .onload() is for, but if multiple scripts are being loaded that can be cumbersome.
As a resolution to this situation, I put together this function that will keep a queue of scripts to be loaded, loading each subsequent item after the previous finishes, and returns a Promise that resolves when the script (or the last script in the queue if no parameter) is done loading.
load_script = function(src) {
// Initialize scripts queue
if( load_script.scripts === undefined ) {
load_script.scripts = [];
load_script.index = -1;
load_script.loading = false;
load_script.next = function() {
if( load_script.loading ) return;
// Load the next queue item
load_script.loading = true;
var item = load_script.scripts[++load_script.index];
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = item.src;
// When complete, start next item in queue and resolve this item's promise
script.onload = () => {
load_script.loading = false;
if( load_script.index < load_script.scripts.length - 1 ) load_script.next();
item.resolve();
};
head.appendChild(script);
};
};
// Adding a script to the queue
if( src ) {
// Check if already added
for(var i=0; i < load_script.scripts.length; i++) {
if( load_script.scripts[i].src == src ) return load_script.scripts[i].promise;
}
// Add to the queue
var item = { src: src };
item.promise = new Promise(resolve => {item.resolve = resolve;});
load_script.scripts.push(item);
load_script.next();
}
// Return the promise of the last queue item
return load_script.scripts[ load_script.scripts.length - 1 ].promise;
};
With this adding scripts in order ensuring the previous are done before staring the next can be done like...
["https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js",
"/jquery.some-plugin.js",
"/dependant-on-plugin.js",
].forEach(load_script);
Or load the script and use the return Promise to do work when it's complete...
load_script("some-script.js")
.then(function() {
/* some-script.js is done loading */
});
Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:
EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")
After that you can do this:
EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )
R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.
def get_clients():
first_run = True
startMainMenu = False
while True:
if first_run:
global done
done = False
Thread(target=animate, args=("Waiting For Connection",)).start()
Client, address = objSocket.accept()
global menuIsOn
if menuIsOn:
menuIsOn = False # will stop main menu
startMainMenu = True
done = True
# Get Current Directory in Client Machine
current_client_directory = Client.recv(1024).decode("utf-8", errors="ignore")
# beep on connection
beep()
print(f"{bcolors.OKBLUE}\n***** Incoming Connection *****{bcolors.OKGREEN}")
print('* Connected to: ' + address[0] + ':' + str(address[1]))
try:
get_client_info(Client, first_run)
except Exception as e:
print("Error data received is not a json!")
print(e)
now = datetime.now()
current_time = now.strftime("%D %H:%M:%S")
print("* Current Time =", current_time)
print("* Current Folder in Client: " + current_client_directory + bcolors.WARNING)
connections.append(Client)
addresses.append(address)
if first_run:
Thread(target=threaded_main_menu, daemon=True).start()
first_run = False
else:
print(f"{bcolors.OKBLUE}* Hit Enter To Continue.{bcolors.WARNING}\n#>", end="")
if startMainMenu == True:
Thread(target=threaded_main_menu, daemon=True).start()
startMainMenu = False
Download java jdk<version>-linux-x64.tar.gz
file from https://www.oracle.com/technetwork/java/javase/downloads/index.html.
Extract this file where you want. like: /home/java
(Folder name created by user in home directory).
Now open terminal.
Set path JAVA_HOME=path
of your jdk folder(open jdk folder then right click on any folder, go to properties then copy the path using select all)
and paste here.
Like: JAVA_HOME=/home/xxxx/java/JDK1.8.0_201
Let Ubuntu know where our JDK/JRE is located.
sudo update-alternatives --install /usr/bin/java java /home/xxxx/java/jdk1.8.0_201/bin/java 20000
sudo update-alternatives --install /usr/bin/javac javac /home/xxxx/java/jdk1.8.0_201/bin/javac 20000
sudo update-alternatives --install /usr/bin/javaws javaws /home/xxxx/java/jdk1.8.0_201/bin/javaws 20000
Tell Ubuntu that our installation i.e., jdk1.8.0_05 must be the default Java.
sudo update-alternatives --set java /home/xxxx/sipTest/jdk1.8.0_201/bin/java
sudo update-alternatives --set javac /home/xxxx/java/sipTest/jdk1.8.0_201/bin/javac
sudo update-alternatives --set javaws /home/xxxxx/sipTest/jdk1.8.0_201/bin/javaws
Now try:
$ sudo update-alternatives --config java
There are 3 choices for the alternative java (providing /usr/bin/java
).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/lib/jvm/java-6-oracle1/bin/java 1047 auto mode
1 /usr/bin/gij-4.6 1046 manual mode
2 /usr/lib/jvm/java-6-oracle1/bin/java 1047 manual mode
3 /usr/lib/jvm/jdk1.7.0_75/bin/java 1 manual mode
Press enter to keep the current choice [*
], or type selection number: 3
update-alternatives: using /usr/lib/jvm/jdk1.7.0_75/bin/java to provide /usr/bin/java (java) in manual mode
Repeat the above for:
sudo update-alternatives --config javac
sudo update-alternatives --config javaws
To use information_schema and not collide with other sessions:
select *
from tempdb.INFORMATION_SCHEMA.COLUMNS
where table_name =
object_name(
object_id('tempdb..#test'),
(select database_id from sys.databases where name = 'tempdb'))
jQuery would be the easiest way if you want to use it, but this should work.
function showHide(){
var e = document.getElementById('e');
if ( e.style.display !== 'none' ) {
e.style.display = 'none';
} else {
e.style.display = '';
}
}
if(isset($_GET['content'])){
$content = $_GET['content'];
$dir = $_GET['dir'];
header("Content-type:".$content);
@readfile($dir);
}
$directory = (file_exists("mydir/"))?"mydir/":die("file/directory doesn't exists");// checks directory if existing.
//the line above is just a one-line if statement (syntax: (conditon)?code here if true : code if false; )
if($handle = opendir($directory)){ //opens directory if existing.
while ($file = readdir($handle)) { //assign each file with link <a> tag with GET params
echo '<a target="_blank" href="?content=application/pdf&dir='.$directory.'">'.$file.'</a>';
}
}
if you click the link a new window will appear with the pdf file
It is perfectly fine if you want to go with the display: table-cell
solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;
. flex
is something which has a decent support.
.wrap {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
border: 1px solid #aaa;_x000D_
margin: 10px;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
<span>Align me to the bottom</span>_x000D_
</div>
_x000D_
In the above example, we first set the parent element to display: flex;
and later, we use align-self
to flex-end
. This helps you push the item to the end of the flex
parent.
flex
)If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell;
with vertical-align: bottom;
is enough
div {_x000D_
display: table-cell;_x000D_
vertical-align: bottom;_x000D_
border: 1px solid #f00;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
Try creating a handler for select event on those elements and in the handler you can clear the selection.
Take a look at this:
Clear Text Selection with JavaScript
It's an example of clearing the selection. You'd only need to modify it to work only on the specific element that you need.
I would like to do this without attaching a class to every td
Personally, I would go with the the class-on-each-td/th/col approach. Then you can switch columns on and off using a single write to className on the container, assuming style rules like:
table.hide1 .col1 { display: none; }
table.hide2 .col2 { display: none; }
...
This is going to be faster than any JS loop approach; for really long tables it can make a significant difference to responsiveness.
If you can get away with not supporting IE6, you could use adjacency selectors to avoid having to add the class attributes to tds. Or alternatively, if your concern is making the markup cleaner, you could add them from JavaScript automatically in an initialisation step.
I will show you some examples:
const string &dontDoThis(const string &s)
{
string local = s;
return local;
}
You can't return local
by reference, because local
is destroyed at the end of the body of dontDoThis
.
const string &shorterString(const string &s1, const string &s2)
{
return (s1.size() < s2.size()) ? s1 : s2;
}
Here, you can return by reference both s1
and s2
because they were defined before shorterString
was called.
char &get_val(string &str, string::size_type ix)
{
return str[ix];
}
usage code as below:
string s("123456");
cout << s << endl;
char &ch = get_val(s, 0);
ch = 'A';
cout << s << endl; // A23456
get_val
can return elements of s
by reference because s
still exists after the call.
class Student
{
public:
string m_name;
int age;
string &getName();
};
string &Student::getName()
{
// you can return by reference
return m_name;
}
string& Test(Student &student)
{
// we can return `m_name` by reference here because `student` still exists after the call
return stu.m_name;
}
usage example:
Student student;
student.m_name = 'jack';
string name = student.getName();
// or
string name2 = Test(student);
class String
{
private:
char *str_;
public:
String &operator=(const String &str);
};
String &String::operator=(const String &str)
{
if (this == &str)
{
return *this;
}
delete [] str_;
int length = strlen(str.str_);
str_ = new char[length + 1];
strcpy(str_, str.str_);
return *this;
}
You could then use the operator=
above like this:
String a;
String b;
String c = b = a;
I agree with "Is Nothing". As stated above, it's easy to negate with "IsNot Nothing".
I find this easier to read...
If printDialog IsNot Nothing Then
'blah
End If
than this...
If Not obj Is Nothing Then
'blah
End If
Try this:
<meta http-equiv="refresh" content="5;URL= your url">
or
<meta http-equiv="refresh" content="5">
I had problem to catch "shown.bs.modal" event.. And this is my solution which works perfect..
Instead simple on():
$('#modal').on 'shown.bs.modal', ->
Use on() with delegated element:
$('body').on 'shown.bs.modal', '#modal', ->
I know how to generate random number in C++ without using any headers, compiler intrinsics or whatever.
#include <cstdio> // Just for printf
int main() {
auto val = new char[0x10000];
auto num = reinterpret_cast<unsigned long long>(val);
delete[] val;
num = num / 0x1000 % 10;
printf("%llu\n", num);
}
I got the following stats after run for some period of time:
0: 5268
1: 5284
2: 5279
3: 5242
4: 5191
5: 5135
6: 5183
7: 5236
8: 5372
9: 5343
Looks random.
How it works:
UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id
That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read
As for running slow, how large are the tables? You should have indexes on tobeupdated.value
and original.value
EDIT: we can also simplify the query
UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id
USING
is shorthand when both tables of a join have an identical named key
such as id
. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join
UIView.transition(with: title3Label, duration: 0.4,
options: .transitionCrossDissolve,
animations: {
self.title3Label.isHidden = !self.title3Label.isHidden
})
Applying transition on View with some delay gives hide and show effect
Difference between “@+id/”
and “@id/”
in Android
The first one is used for to create the ID
of the particular ui component and the another one is used for to refer the particular component
Simple one
Reference - http://www.php.net/manual/en/function.date.php
<?php
echo 'First Date = ' . date('Y-m-01') . '<br />';
echo 'Last Date = ' . date('Y-m-t') . '<br />';
?>
You can have great success and great performance either way. MSDN runs off of ASP.NET so you know it can perform well. PHP runs a lot of the top websites in the world. The same can be said of the databases as well. You really need to choose based upon your skills, the skills of your team, possible specific features that you need/want that one does better than the other, and even the servers that you want to run this site.
If I were building it, I would lean towards PHP because probably everything you want to do has been done before (with code examples how) and because hosting is so much easier to get (and cheaper because you don't have the licensing issues to deal with compared to Windows hosting). For the same reason, I would choose MySQL as well. It is a great database platform and the price is right.
If you intend to use the default VB6 Collection
, then the easiest you can do is:
col1.add array("first key", "first string"), "first key"
col1.add array("second key", "second string"), "second key"
col1.add array("third key", "third string"), "third key"
Then you can list all values:
Dim i As Variant
For Each i In col1
Debug.Print i(1)
Next
Or all keys:
Dim i As Variant
For Each i In col1
Debug.Print i(0)
Next
You inherit class attributes, not class constructors .This is how it goes :
If no constructor is added in the super class, if no then the compiler adds a no argument contructor. This default constructor is invoked implicitly whenever a new instance of the sub class is created . Here the sub class may or may not have constructor, all is ok .
if a constructor is provided in the super class, the compiler will see if it is a no arg constructor or a constructor with parameters.
if no args, then the compiler will invoke it for any sub class instanciation . Here also the sub class may or may not have constructor, all is ok .
if 1 or more contructors in the parent class have parameters and no args constructor is absent, then the subclass has to have at least 1 constructor where an implicit call for the parent class construct is made via super (parent_contractor params) .
this way you are sure that the inherited class attributes are always instanciated .
If you use form.close() in your form and set the FormClosing Event of your form and either use form.close() in this Event ,you fall in unlimited loop and Argument out of range happened and the solution is that change the form.close() with form.dispose() in Event of FormClosing. I hope this little tip help you!!!
With Python 2, this doesn't work for non-English words in UTF-8. In this case decode('utf-8')
can help:
>>> s='????????'
>>> print s.lower()
????????
>>> print s.decode('utf-8').lower()
????????
It sounds like you should be clearer about your RNG requirements. The strongest cryptographic RNG requirement (as I understand it) would be that even if you know the algorithm used to generate them, and you know all previously generated random numbers, you could not get any useful information about any of the random numbers generated in the future, without spending an impractical amount of computing power.
If you don't need this full guarantee of randomness then there are probably appropriate performance tradeoffs. I would tend to agree with Dan Dyer's response about AESCounterRNG from Uncommons-Maths, or Fortuna (one of its authors is Bruce Schneier, an expert in cryptography). I've never used either but the ideas appear reputable at first glance.
I would think that if you could generate an initial random seed periodically (e.g. once per day or hour or whatever), you could use a fast stream cipher to generate random numbers from successive chunks of the stream (if the stream cipher uses XOR then just pass in a stream of nulls or grab the XOR bits directly). ECRYPT's eStream project has lots of good information including performance benchmarks. This wouldn't maintain entropy between the points in time that you replenish it, so if someone knew one of the random numbers and the algorithm you used, technically it might be possible, with a lot of computing power, to break the stream cipher and guess its internal state to be able to predict future random numbers. But you'd have to decide whether that risk and its consequences are sufficient to justify the cost of maintaining entropy.
Edit: here's some cryptographic course notes on RNG I found on the 'net that look very relevant to this topic.
StringComparison.InvariantCultureIgnoreCase just do the job for me:
.Where(fi => fi.DESCRIPTION.Contains(description, StringComparison.InvariantCultureIgnoreCase));
For me it worked like I had images in icons
folder under src
and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));
You may want to use something like this:
NSDateComponents *components;
NSInteger days;
components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit
fromDate: startDate toDate: endDate options: 0];
days = [components day];
I believe this method accounts for situations such as dates that span a change in daylight savings.
As far as I know you can only join this way:
var query = from obj_i in set1
join obj_j in set2 on
new {
JoinProperty1 = obj_i.SomeField1,
JoinProperty2 = obj_i.SomeField2,
JoinProperty3 = obj_i.SomeField3,
JoinProperty4 = obj_i.SomeField4
}
equals
new {
JoinProperty1 = obj_j.SomeOtherField1,
JoinProperty2 = obj_j.SomeOtherField2,
JoinProperty3 = obj_j.SomeOtherField3,
JoinProperty4 = obj_j.SomeOtherField4
}
The main requirements are: Property names, types and order in the anonymous objects you're joining on must match.
You CAN'T use ANDs, ORs, etc. in joins. Just object1 equals object2.
More advanced stuff in this LinqPad example:
class c1
{
public int someIntField;
public string someStringField;
}
class c2
{
public Int64 someInt64Property {get;set;}
private object someField;
public string someStringFunction(){return someField.ToString();}
}
void Main()
{
var set1 = new List<c1>();
var set2 = new List<c2>();
var query = from obj_i in set1
join obj_j in set2 on
new {
JoinProperty1 = (Int64) obj_i.someIntField,
JoinProperty2 = obj_i.someStringField
}
equals
new {
JoinProperty1 = obj_j.someInt64Property,
JoinProperty2 = obj_j.someStringFunction()
}
select new {obj1 = obj_i, obj2 = obj_j};
}
Addressing names and property order is straightforward, addressing types can be achieved via casting/converting/parsing/calling methods etc. This might not always work with LINQ to EF or SQL or NHibernate, most method calls definitely won't work and will fail at run-time, so YMMV (Your Mileage May Vary). This is because they are copied to public read-only properties in the anonymous objects, so as long as your expression produces values of correct type the join property - you should be fine.
assign
is good, but I have not found a function for referring back to the variable you've created in an automated script. (as.name
seems to work the opposite way). More experienced coders will doubtless have a better solution, but this solution works and is slightly humorous perhaps, in that it gets R to write code for itself to execute.
Say I have just assigned value 5 to x
(var.name <- "x"; assign(var.name, 5)
) and I want to change the value to 6. If I am writing a script and don't know in advance what the variable name (var.name
) will be (which seems to be the point of the assign
function), I can't simply put x <- 6
because var.name
might have been "y"
. So I do:
var.name <- "x"
#some other code...
assign(var.name, 5)
#some more code...
#write a script file (1 line in this case) that works with whatever variable name
write(paste0(var.name, " <- 6"), "tmp.R")
#source that script file
source("tmp.R")
#remove the script file for tidiness
file.remove("tmp.R")
x
will be changed to 6, and if the variable name was anything other than "x"
, that variable will similarly have been changed to 6.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
notification = (ImageView)v.findViewById(R.id.notification);
notification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container,new NotificationFragment());
fr.commit();
}
});
return v;
}
Looks like you're a little bit confused about all that stuff.
operator
is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n)
constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.
So, you can't use key=a[x][1]
there, because python has no idea what x
is. Instead, you could use a lambda
function (elem
is just a variable name, no magic there):
a.sort(key=lambda elem: elem[1])
Or just an ordinary function:
def get_second_elem(iterable):
return iterable[1]
a.sort(key=get_second_elem)
So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.
Other questions:
reverse=True
: a.sort(key=..., reverse=True)
itemgetter
with multiple indices: operator.itemgetter(1,2)
, or with lambda: lambda elem: (elem[1], elem[2])
. This way, iterables are constructed on the fly for each item in list, which are than compared against each other in lexicographic(?) order (first elements compared, if equal - second elements compared, etc)a[2,1]
(indices are zero-based). Using operator... It's possible, but not as clean as just indexing.Refer to the documentation for details:
Depends what you mean by "post data". You can use the HTML target=""
attribute on a <form />
tag, so it could be as simple as:
<form action="do_stuff.aspx" method="post" target="my_iframe">
<input type="submit" value="Do Stuff!">
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>
If that's not it, or you're after something more complex, please edit your question to include more detail.
There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a work-around here), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3.
I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself.
default.asp
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Form Iframe Demo</title>
</head>
<body>
<form action="do_stuff.asp" method="post" target="my_frame">
<input type="text" name="someText" value="Some Text">
<input type="submit">
</form>
<iframe name="my_frame" src="do_stuff.asp">
</iframe>
</body>
</html>
do_stuff.asp
<%@Language="JScript"%><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Form Iframe Demo</title>
</head>
<body>
<% if (Request.Form.Count) { %>
You typed: <%=Request.Form("someText").Item%>
<% } else { %>
(not submitted)
<% } %>
</body>
</html>
I would be very interested to hear of any browser that doesn't run these examples correctly.
You can use Streams In Java 8 (this is exmaple of Set):
@Test
public void whenInitializeUnmodifiableSetWithDoubleBrace_containsElements() {
Set<String> countries = Stream.of("India", "USSR", "USA")
.collect(collectingAndThen(toSet(), Collections::unmodifiableSet));
assertTrue(countries.contains("India"));
}
Ref: https://www.baeldung.com/java-double-brace-initialization
Ian put this in the comment, but I think it's a good answer:
if (exists("aVariable"))
{
do whatever
}
note that the variable name is quoted.
Using CodeIgniter OAuth2/0.4.0 sparks,
in Auth.php file,
$user = $provider->get_user_info($token);
$friends = $provider->get_friends_list($token);
print_r($friends);
and in Facebook.php file under Provider, add the following function,
public function get_friends_list(OAuth2_Token_Access $token)
{
$url = 'https://graph.facebook.com/me/friends?'.http_build_query(array(
'access_token' => $token->access_token,
));
$friends = json_decode(file_get_contents($url),TRUE);
return $friends;
}
prints the facebenter code hereook friends.
An alternative solution, in case you are needing to do this on an ajax file upload:
var data = new FormData( $('#form')[0] ).append( 'name' , value );
OR even simpler.
$('form').on('submit',function(e){
e.preventDefault();
var data = new FormData( this ).append('name', value );
// ... your ajax code here ...
return false;
});
USE [mydb1]
SELECT *
INTO mytable1
FROM OPENDATASOURCE (
'SQLNCLI'
,'Data Source=XXX.XX.XX.XXX;Initial Catalog=mydb2;User ID=XXX;Password=XXXX'
).[mydb2].dbo.mytable2
/* steps -
1- [mydb1] means our opend connection database
2- mytable1 means create copy table in mydb1 database where we want insert record
3- XXX.XX.XX.XXX - another server name.
4- mydb2 another server database.
5- write User id and Password of another server credential
6- mytable2 is another server table where u fetch record from it. */
A callback function in C is the equivalent of a function parameter / variable assigned to be used within another function.Wiki Example
In the code below,
#include <stdio.h>
#include <stdlib.h>
/* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void)) {
printf("%d and %d\n", numberSource(), numberSource());
}
/* A possible callback */
int overNineThousand(void) {
return (rand() % 1000) + 9001;
}
/* Another possible callback. */
int meaningOfLife(void) {
return 42;
}
/* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void) {
PrintTwoNumbers(&rand);
PrintTwoNumbers(&overNineThousand);
PrintTwoNumbers(&meaningOfLife);
return 0;
}
The function (*numberSource) inside the function call PrintTwoNumbers is a function to "call back" / execute from inside PrintTwoNumbers as dictated by the code as it runs.
So if you had something like a pthread function you could assign another function to run inside the loop from its instantiation.
The first constructor in the header should not end with a semicolon. #include <string>
is missing in the header. string
is not qualified with std::
in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream
is broken. I suggest learning C++ before trying to use it.
Let's fix this up:
//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__
#include <iostream>
#include <string>
class Polygone {
public:
// declarations have to end with a semicolon, definitions do not
Polygone(){} // why would we needs this?
Polygone(const std::string& fichier);
};
# endif
and
//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>
Polygone::Polygone(const std::string& nom)
{
std::ifstream fichier (nom, ios::in);
if (fichier.is_open())
{
// keep the scope as tiny as possible
std::string line;
// getline returns the stream and streams convert to booleans
while ( std::getline(fichier, line) )
{
std::cout << line << std::endl;
}
}
else
{
std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
}
}
You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]
My 'random' library provide a high convenient wrapper around C++11 random classes. You can do almost all things with a simple 'get' method.
Examples:
Random number in a range
auto val = Random::get(-10, 10); // Integer
auto val = Random::get(10.f, -10.f); // Float point
Random boolean
auto val = Random::get<bool>( ) // 50% to generate true
auto val = Random::get<bool>( 0.7 ) // 70% to generate true
Random value from a std::initilizer_list
auto val = Random::get( { 1, 3, 5, 7, 9 } ); // val = 1 or 3 or...
Random iterator from iterator range or all container
auto it = Random::get( vec.begin(), vec.end() ); // it = random iterator
auto it = Random::get( vec ); // return random iterator
And even more things ! Check out the github page:
.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following
Example :
var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
Google now has a documentation page dedicated to Maps URLs:
https://developers.google.com/maps/documentation/urls/guide
An API key is not required.
Manipulating one of the examples, I came up with this URL scheme that fits your question:
https://www.google.com/maps/search/<search term>/@<coordinates>,<zoom level>z
A valid example of this would be:
https://www.google.com/maps/search/pizza/@41.089988,-81.542901,12z
This should show you all of the pizza places around Akron, Ohio.
I use these two commands and I can see the files to change.
First executing git fetch, it gives output like this (part of output):
... 72f8433..c8af041 develop -> origin/develop ...
This operation gives us two commit IDs, first is the old one, and second will be the new.
Then compare these two commits using git diff
git diff 72f8433..c8af041 | grep "diff --git"
This command will list the files that will be updated:
diff --git a/app/controller/xxxx.php b/app/controller/xxxx.php
diff --git a/app/view/yyyy.php b/app/view/yyyy.php
For example app/controller/xxxx.php and app/view/yyyy.php will be updated.
Comparing two commits using git diff prints all updated files with changed lines, but with grep it searches and gets only the lines contains diff --git from output.
I have tried to measure speed of Android Studio 3.1.4 on the same hardware: Macbook Pro 2011, RAM 4Gb, SSD 240GB Samsung, Core i5 2.4Ghz. I have installed on this machine 3 different OS: Windows 10, MacOS Hight Sierra 10.13, Ubuntu 18.04. Avarage build time (running command: gradlew clean build, gradlew clean assembleRelease) on MacOS/Ubuntu was around 30% faster than on Windows.
On my another working machine: Core i5 3.0 Ghz 7400, RAM 16Gb, SSD 250Gb. Build time takes 4.34min on Windows 10 machine. The same project on a little bit slower processor, but with the same RAM and SSD and it is running Ubuntu 16.04 build time takes two times faster!! Well I was shocked with results, but still I choose Windows as development machine, because it's much more comfortable for me to use comfortable and usable keyboard and sotfware than on Unix like systems. And even if I had to choose between MacOS and Ubuntu - mac is really much easier to setup everything, and Ubuntu is too complex to use for usual people. Choise is up to you.
Just wrap your WebElement into Select Object as shown below
Select dropdown = new Select(driver.findElement(By.id("identifier")));
Once this is done you can select the required value in 3 ways. Consider an HTML file like this
<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>
Now to identify dropdown do
Select dropdown = new Select(driver.findElement(By.id("designation")));
To select its option say 'Programmer' you can do
dropdown.selectByVisibleText("Programmer ");
or
dropdown.selectByIndex(1);
or
dropdown.selectByValue("prog");
I tried the above answer - using page.html#ID_name
it gave me a 404 page doesn't exist error.
Then instead of using .html
, I simply put a slash /
before the #
and that worked fine. So my example on the sending page between the link tags looks like:
<a href= "http://my website.com/target-page/#El_Chorro">El Chorro</a>
Just use /
instead of .html
.
If your List
is sorted and has good random access (as ArrayList
does), you should look into Collections.binarySearch
. Otherwise, you should use List.indexOf
, as others have pointed out.
But your algorithm is sound, fwiw (other than the ==
others have pointed out).
You're looking for $(this).attr("href");
There is a function is the math library called signnum.
http://www.tutorialspoint.com/java/lang/math_signum_float.htm http://www.tutorialspoint.com/java/lang/math_signum_double.htm
Just to help those in a similar situation to myself...
This can be caused when a dependent library has accidentally bundled an old version of slf4j. In my case, it was tika-0.8. See https://issues.apache.org/jira/browse/TIKA-556
The workaround is exclude the component and then manually depends on the correct, or patched version.
EG.
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-parsers</artifactId>
<version>0.8</version>
<exclusions>
<exclusion>
<!-- NOTE: Version 4.2 has bundled slf4j -->
<groupId>edu.ucar</groupId>
<artifactId>netcdf</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<!-- Patched version 4.2-min does not bundle slf4j -->
<groupId>edu.ucar</groupId>
<artifactId>netcdf</artifactId>
<version>4.2-min</version>
</dependency>
Here's an extension that will do it all, on as many elements in as many ways...
Example usage:
keep existing class and attributes:
$('div#change').replaceTag('<span>', true);
or
Discard existing class and attributes:
$('div#change').replaceTag('<span class=newclass>', false);
or even
replace all divs with spans, copy classes and attributes, add extra class name
$('div').replaceTag($('<span>').addClass('wasDiv'), true);
Plugin Source:
$.extend({
replaceTag: function (currentElem, newTagObj, keepProps) {
var $currentElem = $(currentElem);
var i, $newTag = $(newTagObj).clone();
if (keepProps) {//{{{
newTag = $newTag[0];
newTag.className = currentElem.className;
$.extend(newTag.classList, currentElem.classList);
$.extend(newTag.attributes, currentElem.attributes);
}//}}}
$currentElem.wrapAll($newTag);
$currentElem.contents().unwrap();
// return node; (Error spotted by Frank van Luijn)
return this; // Suggested by ColeLawrence
}
});
$.fn.extend({
replaceTag: function (newTagObj, keepProps) {
// "return" suggested by ColeLawrence
return this.each(function() {
jQuery.replaceTag(this, newTagObj, keepProps);
});
}
});
If you're on Mac OS X, you can install the ca-cert-bundle via homebrew
:
$ brew install curl-ca-bundle
$ git config --system http.sslcainfo /usr/local/share/ca-bundle.crt
The formula installs the cert bundle to your share via:
share.install 'ca-bundle.crt'
The share
method is just an alias to /usr/local/share
, and the curl-ca-bundle is provided by Mozilla
. It's what you see being referenced in a lot of issues. Hope this helps as it's not very straightforward about how to approach this on Mac OS X. brew install curl
isn't going to get you much either as it's keg only and will not be linked (running which curl
will always output /usr/bin/curl
, which is the default that ships with your OS). This post may also be of some value.
You'll of course need to disable SSL before you install homebrew
since it's a git repo. Just do what curl says when it errors out during SSL verification and:
$ echo insecure >> ~/.curlrc
Once you get homebrew
installed along with the curl-ca-bundle
, delete .curlrc
and try cloning a repo out on github. Ensure that there are no errors and you'll be good to go.
NOTE: If you do resort to .curlrc
, please remove it from your system the moment you're done testing. This file can cause major issues, so use it for temporary purposes and with caution. brew doctor
will complain in case you forget to purge it from your system).
NOTE: If you update your version of git, you'll need to rerun this command since your system settings will be wiped out (they're stored relative to the git binary based on version).
So after running:
$ brew update
$ brew upgrade
If you get a new version of git, then just rerun:
$ git config --system http.sslcainfo /usr/local/share/ca-bundle.crt
And you'll be all set.
Lastly if you have a new version of git, running:
$ git config -l --system
should give you an error along the lines of
fatal: unable to read config file '/usr/local/Cellar/git/1.8.2.2/etc/gitconfig'
that's your tip that you need to tell git where the Mozilla ca-bundle is.
UPDATE:
.curlrc
may or may not be the remedy to your problem. In any case, just get the Mozilla ca-bundle installed on your machine whether you have to manually download it or not. That's what's important here. Once you get the ca-bundle, you're good to go. Just run the git config command and point git to the the ca-bundle.
UPDATE
I recently had to add:
export CURL_CA_BUNDLE=/usr/local/share/ca-bundle.crt
to my .zshenv
dot file since I'm using zsh
. the git config
option worked for most cases, but when hitting github over SSL (rvm get stable
for example), I still ran into certificate issues. @Maverick pointed this out in his comment, but just in case someone misses it or assumes they don't necessarily need to export this environment variable in addition to running the git config --system....
command. Thanks and hope this helps.
UPDATE
It looks like the curl-ca-bundle was recently removed from homebrew. There is a recommendation here.
You will want to drop some files into:
$(brew --prefix)/etc/openssl/certs
You could use the ExcelStorage Class of the FileHelpers library, it's very easy and simple... you will need Excel 2000 or later installed on the machine.
The FileHelpers is a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.
scp -r [email protected]:/path/to/foo /home/user/Desktop/
By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory.
From man scp
(See online manual)
-r Recursively copy entire directories
For those who are using it first time and have no information regarding what the password is they can follow the below steps(assuming you are on ubuntu):
You might want to check HTML frames, which can do pretty much exactly what you are looking for. They are considered outdated however.
The answer of JasonW is fine. But since apache httpd 2.4.6 there is a alternative: mod_remoteip
All what you must do is:
Enable the module:
LoadModule remoteip_module modules/mod_remoteip.so
Add the following to your apache httpd config. Note that you must add this line not into the configuration of the proxy server. You must add this to the configuration of the proxy target httpd server (the server behind the proxy):
RemoteIPHeader X-Forwarded-For
See at http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html for more informations and more options.
An inner class, by definition, cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?"
A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
Check your appid and make sure you have updated your Site URL Mobile Site URL in https://developers.facebook.com/
Material example is using the wrong table tags. Change
<table mat-table></table>
<th mat-header-cell></th>
<td mat-cell></td>
<tr mat-header-row></tr>
<tr mat-row></tr>
to
<mat-table></mat-table>
<mat-header-cell></mat-header-cell>
<mat-cell></mat-cell>
<mat-header-row></<mat-header-row>
<mat-row></<mat-row>
Using dynamic variable for search in array
/* https://ideone.com/Pfb0Ou */
$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');
/* variable search */
$search = 'living_room';
if (in_array($search, $array)) {
echo "this array contains $search";
} else
echo "this array NOT contains $search";
add 0.5 before casting (if x > 0) or subtract 0.5 (if x < 0), because the compiler will always truncate.
float x = 55; // stored as 54.999999...
x = x + 0.5 - (x<0); // x is now 55.499999...
int y = (int)x; // truncated to 55
C++11 also introduces std::round, which likely uses a similar logic of adding 0.5 to |x| under the hood (see the link if interested) but is obviously more robust.
A follow up question might be why the float isn't stored as exactly 55. For an explanation, see this stackoverflow answer.
Please check the compatibility. I struggled with mvn 3.2.1
and jdk 1.6.0_37
for many hours. All variables were set but was not working. Finally I upgraded jdk to 1.8.0_60
and mvn 3.3.3
and that worked. Environment Variables as following:
JAVA_HOME=C:\ProgramFiles\Java\jdk1.8.0_60
MVN_HOME=C:\ProgramFiles\apache-maven\apache-maven-3.3.3
M2=%MVN_HOME%\bin extend system level Path- ;%M2%;%JAVA_HOME%\bin;
Notes:
git status --ignored
.gitignore
files?")git clean -ndX
works on older gits, displaying a preview of what ignored files could be removed (without removing anything)Also interesting (mentioned in qwertymk's answer), you can also use the git check-ignore -v
command, at least on Unix (doesn't work in a CMD Windows session)
git check-ignore *
git check-ignore -v *
The second one displays the actual rule of the .gitignore
which makes a file to be ignored in your git repo.
On Unix, using "What expands to all files in current directory recursively?" and a bash4+:
git check-ignore **/*
(or a find -exec
command)
Note: https://stackoverflow.com/users/351947/Rafi B. suggests in the comments to avoid the (risky) globstar:
git check-ignore -v $(find . -type f -print)
Make sure to exclude the files from the .git/
subfolder though.
Original answer 42009)
git ls-files -i
should work, except its source code indicates:
if (show_ignored && !exc_given) {
fprintf(stderr, "%s: --ignored needs some exclude pattern\n",
argv[0]);
exc_given
?
It turns out it need one more parameter after the -i
to actually list anything:
Try:
git ls-files -i --exclude-from=[Path_To_Your_Global].gitignore
(but that would only list your cached (non-ignored) object, with a filter, so that is not quite what you want)
Example:
$ cat .git/ignore
# ignore objects and archives, anywhere in the tree.
*.[oa]
$ cat Documentation/.gitignore
# ignore generated html files,
*.html
# except foo.html which is maintained by hand
!foo.html
$ git ls-files --ignored \
--exclude='Documentation/*.[0-9]' \
--exclude-from=.git/ignore \
--exclude-per-directory=.gitignore
Actually, in my 'gitignore' file (called 'exclude'), I find a command line that could help you:
F:\prog\git\test\.git\info>type exclude
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~
So....
git ls-files --ignored --exclude-from=.git/info/exclude
git ls-files -i --exclude-from=.git/info/exclude
git ls-files --others --ignored --exclude-standard
git ls-files -o -i --exclude-standard
should do the trick.
(Thanks to honzajde pointing out in the comments that git ls-files -o -i --exclude-from...
does not include cached files: only git ls-files -i --exclude-from...
(without -o
) does.)
As mentioned in the ls-files man page, --others
is the important part, in order to show you non-cached, non-committed, normally-ignored files.
--exclude_standard
is not just a shortcut, but a way to include all standard "ignored patterns" settings.
exclude-standard
Add the standard git exclusions:.git/info/exclude
,.gitignore
in each directory, and theuser's global exclusion file
.
You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.
If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form.
Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg
public void DoSomethingWithText(string formText)
{
// do something text in here
}
or exposing properties on your form class and setting the form text in there - eg
string SomeProperty
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}
I merely created a div class using various heights i.e.
<div class="divider-10"></div>
The CSS is:
.divider-10 {
width:100%;
min-height:1px;
margin-top:10px;
margin-bottom:10px;
display:inline-block;
position:relative;
}
Just create a divider class for what ever heights are needed.
On behalf of the Visual Studio tool, we can easily generate C# properties using an online tool called C# property generator.
You should also be careful with your case. Let me explain: doing Blah.valueOf("A")
works, but Blah.valueOf("a")
will not work. Then again Blah.valueOf("a".toUpperCase(Locale.ENGLISH))
would work.
edit
Changed toUpperCase
to toUpperCase(Locale.ENGLISH)
based on tc. comment and the java docs
edit2
On android you should use Locale.US
, as sulai points out.
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
// ...
Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});
Replace
if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged
with
if (obj === undefined) { return undefined;} // return undefined for undefined
if (obj === null) { return null;} // null unchanged
The Address()
worksheet function does exactly that. As it's not available through Application.WorksheetFunction
, I came up with a solution using the Evaluate()
method.
This solution let Excel deals with spaces and other funny characters in the sheet name, which is a nice advantage over the previous answers.
Example:
Evaluate("ADDRESS(" & rng.Row & "," & rng.Column & ",1,1,""" & _
rng.Worksheet.Name & """)")
returns exactly "Sheet1!$A$1", with a Range
object named rng
referring the A1 cell in the Sheet1 worksheet.
This solution returns only the address of the first cell of a range, not the address of the whole range ("Sheet1!$A$1" vs "Sheet1!$A$1:$B$2"). So I use it in a custom function:
Public Function AddressEx(rng As Range) As String
Dim strTmp As String
strTmp = Evaluate("ADDRESS(" & rng.Row & "," & _
rng.Column & ",1,1,""" & rng.Worksheet.Name & """)")
If (rng.Count > 1) Then
strTmp = strTmp & ":" & rng.Cells(rng.Count) _
.Address(RowAbsolute:=True, ColumnAbsolute:=True)
End If
AddressEx = strTmp
End Function
The full documentation of the Address() worksheet function is available on the Office website: https://support.office.com/en-us/article/ADDRESS-function-D0C26C0D-3991-446B-8DE4-AB46431D4F89
SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')
Switch off compatibility view if you use IE9.
Go to My Computer>Properties>Advance System Settings>Environment Variables>
Under the variables of Administrator edit the PATH variable & change its value to "C:\Users\Username\AppData\Roaming\npm"
. Note: The username in the path will be the current Admin user's name that you have logged in with.
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator.
Alternate Key:
All Candidate Keys excluding the Primary Key are known as Alternate Keys.
Artificial Key:
If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key, by assigning a unique number to each record or occurrence. Then this is known as developing an artificial key.
Compound Key:
If no single data element uniquely identifies occurrences within a construct, then combining multiple elements to create a unique identifier for the construct is known as creating a compound key.
Natural Key:
When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key.
from item in db.vw_Dropship_OrderItems
where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
(listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
select item;
Might give strange behavior if both listMerchants and listStatus are both null.
If you want to list folders and files like graphical directory tree, you should use tree command.
tree /f
There are various options for display format or ordering.
Check example output.
Answering late. Hope it help someone.
It doesn't really matter. "".equals(str)
is more clear in my opinion.
isEmpty()
returns count == 0
;
onblur
is the opposite of onfocus
.
Found an XML transform stylesheet here (wayback machine link, site itself is in german)
The stylesheet added here could be helpful:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>
<xsl:strip-space elements="*" />
<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>", </xsl:if>
<xsl:if test="position() = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>
</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.
I have written a quick guide on how to install the latest versions of Python 2 and Python 3 on CentOS 6 and CentOS 7. It currently covers Python 2.7.13 and Python 3.6.0:
# Start by making sure your system is up-to-date:
yum update
# Compilers and related tools:
yum groupinstall -y "development tools"
# Libraries needed during compilation to enable all features of Python:
yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel expat-devel
# If you are on a clean "minimal" install of CentOS you also need the wget tool:
yum install -y wget
The next steps depend on the version of Python you're installing.
For Python 2.7.14:
wget http://python.org/ftp/python/2.7.14/Python-2.7.14.tar.xz
tar xf Python-2.7.14.tar.xz
cd Python-2.7.14
./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall
# Strip the Python 2.7 binary:
strip /usr/local/lib/libpython2.7.so.1.0
For Python 3.6.3:
wget http://python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
tar xf Python-3.6.3.tar.xz
cd Python-3.6.3
./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall
# Strip the Python 3.6 binary:
strip /usr/local/lib/libpython3.6m.so.1.0
To install Pip:
# First get the script:
wget https://bootstrap.pypa.io/get-pip.py
# Then execute it using Python 2.7 and/or Python 3.6:
python2.7 get-pip.py
python3.6 get-pip.py
# With pip installed you can now do things like this:
pip2.7 install [packagename]
pip2.7 install --upgrade [packagename]
pip2.7 uninstall [packagename]
You are not supposed to change the system version of Python because it will break the system (as you found out). Installing other versions works fine as long as you leave the original system version alone. This can be accomplished by using a custom prefix (for example /usr/local
) when running configure, and using make altinstall
(instead of the normal make install
) when installing your build of Python.
Having multiple versions of Python available is usually not a big problem as long as you remember to type the full name including the version number (for example "python2.7" or "pip2.7"). If you do all your Python work from a virtualenv the versioning is handled for you, so make sure you install and use virtualenv!
I was able to go around the whole thing by replacing the context reference from this
or Context.this
to getapplicationcontext
.
Using update directly is more efficient and could also prevent integrity problems.
From the official documentation https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.update
If you’re just updating a record and don’t need to do anything with the model object, the most efficient approach is to call update(), rather than loading the model object into memory. For example, instead of doing this:
e = Entry.objects.get(id=10) e.comments_on = False e.save()
…do this:
Entry.objects.filter(id=10).update(comments_on=False)
Using update() also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save().
Using nodejs natively
var fs = require('fs')
var oldPath = 'old/path/file.txt'
var newPath = 'new/path/file.txt'
fs.rename(oldPath, newPath, function (err) {
if (err) throw err
console.log('Successfully renamed - AKA moved!')
})
(NOTE: "This will not work if you are crossing partitions or using a virtual filesystem not supporting moving files. [...]" – Flavien Volken Sep 2 '15 at 12:50")
the World Wide Web Consortium HTML Validator is great at catching HTML errors.
I am using Angular 5 with Boostrap 4. It works for me in this way.
$(document).on('click', '.navbar-nav>li>a, .navbar-brand, .dropdown-menu>a', function (e) {_x000D_
if ( $(e.target).is('a') && $(e.target).attr('class') != 'nav-link dropdown-toggle' ) {_x000D_
$('.navbar-collapse').collapse('hide');_x000D_
}_x000D_
});_x000D_
}
_x000D_
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">_x000D_
<a class="navbar-brand" [routerLink]="['/home']">FbShareTool</a>_x000D_
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation" style="">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
_x000D_
<div class="collapse navbar-collapse" id="navbarColor01">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
<li class="nav-item active" *ngIf="_myAuthService.isAuthenticated()">_x000D_
<a class="nav-link" [routerLink]="['/dashboard']">Dashboard <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item dropdown" *ngIf="_myAuthService.isAuthenticated()">_x000D_
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
Manage_x000D_
</a>_x000D_
<div class="dropdown-menu" aria-labelledby="navbarDropdown">_x000D_
<a class="dropdown-item" [routerLink]="['/fbgroup']">Facebook Group</a>_x000D_
<div class="dropdown-divider"></div>_x000D_
<a class="dropdown-item" href="#">Fetch Data</a>_x000D_
</div>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
<ul class="navbar-nav navbar-right navbar-right-link">_x000D_
<li class="nav-item" *ngIf="!_myAuthService.isAuthenticated()" >_x000D_
<a class="nav-link" (click)="logIn()">Login</a>_x000D_
</li>_x000D_
<li class="nav-item" *ngIf="_myAuthService.isAuthenticated()">_x000D_
<a class="nav-link">{{ _myAuthService.userDetails.displayName }}</a>_x000D_
</li>_x000D_
<li class="nav-item" *ngIf="_myAuthService.isAuthenticated() && _myAuthService.userDetails.photoURL">_x000D_
<a>_x000D_
<img [src]="_myAuthService.userDetails.photoURL" alt="profile-photo" class="img-fluid rounded" width="40px;">_x000D_
</a>_x000D_
</li>_x000D_
<li class="nav-item" *ngIf="_myAuthService.isAuthenticated()">_x000D_
<a class="nav-link" (click)="logOut()">Logout</a>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
</div>_x000D_
</nav>
_x000D_
Make sure not to miss the explanation of :host-context
which is directly above ::ng-deep
in the angular guide : https://angular.io/guide/component-styles. I missed it up until now and wish I'd seen it sooner.
::ng-deep
is often necessary when you didn't write the component and don't have access to its source, but :host-context
can be a very useful option when you do.
For example I have a black <h1>
header inside a component I designed, and I want the ability to change it to white when it's displayed on a dark themed background.
If I didn't have access to the source I may have to do this in the css for the parent:
.theme-dark widget-box ::ng-deep h1 { color: white; }
But instead with :host-context
you can do this inside the component.
h1
{
color: black; // default color
:host-context(.theme-dark) &
{
color: white; // color for dark-theme
}
// OR set an attribute 'outside' with [attr.theme]="'dark'"
:host-context([theme='dark']) &
{
color: white; // color for dark-theme
}
}
This will look anywhere in the component chain for .theme-dark
and apply the css to the h1 if found. This is a good alternative to relying too much on ::ng-deep
which while often necessary is somewhat of an anti-pattern.
In this case the &
is replaced by the h1
(that's how sass/scss works) so you can define your 'normal' and themed/alternative css right next to each other which is very handy.
Be careful to get the correct number of :
. For ::ng-deep
there are two and for :host-context
only one.
Check this out! There is a clear definition of smoothing of a 1D signal.
http://scipy-cookbook.readthedocs.io/items/SignalSmooth.html
Shortcut:
import numpy
def smooth(x,window_len=11,window='hanning'):
"""smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introducing reflected copies of the signal
(with the window size) in both ends so that transient parts are minimized
in the begining and end part of the output signal.
input:
x: the input signal
window_len: the dimension of the smoothing window; should be an odd integer
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window will produce a moving average smoothing.
output:
the smoothed signal
example:
t=linspace(-2,2,0.1)
x=sin(t)+randn(len(t))*0.1
y=smooth(x)
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
scipy.signal.lfilter
TODO: the window parameter could be the window itself if an array instead of a string
NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
"""
if x.ndim != 1:
raise ValueError, "smooth only accepts 1 dimension arrays."
if x.size < window_len:
raise ValueError, "Input vector needs to be bigger than window size."
if window_len<3:
return x
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"
s=numpy.r_[x[window_len-1:0:-1],x,x[-2:-window_len-1:-1]]
#print(len(s))
if window == 'flat': #moving average
w=numpy.ones(window_len,'d')
else:
w=eval('numpy.'+window+'(window_len)')
y=numpy.convolve(w/w.sum(),s,mode='valid')
return y
from numpy import *
from pylab import *
def smooth_demo():
t=linspace(-4,4,100)
x=sin(t)
xn=x+randn(len(t))*0.1
y=smooth(x)
ws=31
subplot(211)
plot(ones(ws))
windows=['flat', 'hanning', 'hamming', 'bartlett', 'blackman']
hold(True)
for w in windows[1:]:
eval('plot('+w+'(ws) )')
axis([0,30,0,1.1])
legend(windows)
title("The smoothing windows")
subplot(212)
plot(x)
plot(xn)
for w in windows:
plot(smooth(xn,10,w))
l=['original signal', 'signal with noise']
l.extend(windows)
legend(l)
title("Smoothing a noisy signal")
show()
if __name__=='__main__':
smooth_demo()
In newer versions, the shortcut for the document-wide formatting is: Shift + Alt + F
The data contained therein will not be parsed as XML, and as such does not need to be valid XML or can contain elements that may appear to be XML but are not.
With the introduction of C# 6 (in VS 2015), you can now have get
-only automatic properties, in which the implicit backing field is readonly
(i.e. values can be assigned in the constructor but not elsewhere):
public string Name { get; }
public Customer(string name) // Constructor
{
Name = name;
}
private void SomeFunction()
{
Name = "Something Else"; // Compile-time error
}
And you can now also initialise properties (with or without a setter) inline:
public string Name { get; } = "Boris";
Referring back to the question, this gives you the advantages of option 2 (public member is a property, not a field) with the brevity of option 1.
Unfortunately, it doesn't provide a guarantee of immutability at the level of the public interface (as in @CodesInChaos's point about self-documentation), because to a consumer of the class, having no setter is indistinguishable from having a private setter.
try{
Integer.parseInt(string);
return true;
}catch (Exception e){
return false;
}
or you can do it himself:
for ( int i = 0; i < string.length; ++i ) {
if ( !( string[i] >= '0' || string[i] <= '9' ) )
return false;
}
return true;
Of course is also function isDigit
If you want a simple one liner that will do it all for you (assuming by no value you mean a blank cell):
=(ROWS(A:A) + ROWS(B:B) + ROWS(C:C)) - COUNTIF(A:C, "")
If by no value you mean the cell contains a 0
=(ROWS(A:A) + ROWS(B:B) + ROWS(C:C)) - COUNTIF(A:C, 0)
The formula works by first summing up all the rows that are in columns A, B, and C (if you need to count more rows, just increase the columns in the range. E.g. ROWS(A:A) + ROWS(B:B) + ROWS(C:C) + ROWS(D:D) + ... + ROWS(Z:Z)
).
Then the formula counts the number of values in the same range that are blank (or 0 in the second example).
Last, the formula subtracts the total number of cells with no value from the total number of rows. This leaves you with the number of cells in each row that contain a value
Ok, based on ndpu's code heres an improved (I think) version of ajax_download;-
function ajax_download(url, data) {
var $iframe,
iframe_doc,
iframe_html;
if (($iframe = $('#download_iframe')).length === 0) {
$iframe = $("<iframe id='download_iframe'" +
" style='display: none' src='about:blank'></iframe>"
).appendTo("body");
}
iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
if (iframe_doc.document) {
iframe_doc = iframe_doc.document;
}
iframe_html = "<html><head></head><body><form method='POST' action='" +
url +"'>"
Object.keys(data).forEach(function(key){
iframe_html += "<input type='hidden' name='"+key+"' value='"+data[key]+"'>";
});
iframe_html +="</form></body></html>";
iframe_doc.open();
iframe_doc.write(iframe_html);
$(iframe_doc).find('form').submit();
}
Use this like this;-
$('#someid').on('click', function() {
ajax_download('/download.action', {'para1': 1, 'para2': 2});
});
The params are sent as proper post params as if coming from an input rather than as a json encoded string as per the previous example.
CAVEAT: Be wary about the potential for variable injection on those forms. There might be a safer way to encode those variables. Alternatively contemplate escaping them.
This works fine too:
@Autowired
ApplicationContext context;
internal is for assembly scope (i.e. only accessible from code in the same .exe or .dll)
private is for class scope (i.e. accessible only from code in the same class).
I noticed something else about your coding.... look
INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')
in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be
'0',
you put
0,
lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)
UPDATE.....
I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol
Similarly, if you wanted to redirect to a sub-folder instead of a sub-domain, do the following:
Working off of Kevin's great solution you can add this to the .htaccess file in your site's root directory:
<IfModule mod_rewrite.c>
RewriteBase /
RewriteEngine On
# Check if mobile=1 is set and set cookie 'mobile' equal to 1
RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$)
RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}]
# Check if mobile=0 is set and set cookie 'mobile' equal to 0
RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}]
# cookie can't be set and read in the same request so check
RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
RewriteRule ^ - [S=1]
# Check if this looks like a mobile device
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
RewriteCond %{HTTP:Profile} !^$
# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST} !^m\.
# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP:Cookie} !\mobile=0(;|$)
# Now redirect to the mobile site
RewriteRule ^ http://www.mysite.com/m/ [R]
</IfModule>
Then, in the /m/
folder, add or create an .htaccess with the following:
#Begin user agent loop fix
RewriteEngine Off
RewriteBase /
#End user agent loop fix
I know it's not a direct answer to the question, but somebody (like me) might stumble upon this question and wonder how that method would be accomplished as well.
When we use == , the Reference of object is compared not the actual objects. We need to override equals method to compare Java Objects.
Some additional information C++ has operator over loading & Java does not provide operator over loading. Also other possibilities in java are implement Compare Interface .which defines a compareTo method.
Comparator interface is also used compare two objects
#form{
position:fixed;
top:50%;
left:50%;
width:250px;
}
You can adjust top & left depending on form size.
Yes, but not how you would imagine. According to caniuse (a very good resource) there is no support and no polyfill available for adding text-shadow
support to IE9. However, IE has their own proprietary text shadow (detailed here).
Example implementation, taken from their website (works in IE5.5 through IE9):
p.shadow {
filter: progid:DXImageTransform.Microsoft.Shadow(color=#0000FF,direction=45);
}
For cross-browser compatibility and future-proofing of code, remember to also use the CSS3 standard text-shadow
property (detailed here). This is especially important considering that IE10 has officially announced their intent to drop support for legacy dx filters. Going forward, IE10+ will only support the CSS3 standard text-shadow
.
Add namespace
using System.Configuration;
and in place of
ConfigurationSettings.AppSettings
you should use
ConfigurationManager.AppSettings
String path = ConfigurationManager.AppSettings["configFile"];
Your root logger definition is a bit confused. See the log4j documentation.
This is a standard Java properties file, which means that lines are treated as key=value pairs. Your second log4j.rootLogger
line is overwriting the first, which explains why you aren't seeing anything on the console
appender.
You need to merge your two rootLogger
definitions into one. It looks like you're trying to have DEBUG
messages go to the console and INFO
messages to the file. The root logger can only have one level, so you need to change your configuration so that the appenders have appropriate levels.
While I haven't verified that this is correct, I'd guess it'll look something like this:
log4j.rootLogger=DEBUG,console,file
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender
Note that you also have an error in casing - you have console lowercase in one place and in CAPS in another.
Were your tests performed on your personal computer, or on a web server? It is a blank page, or is it a complex online system with images, databases, etc.? Are your scripts performing a simple hover event action, or are they a core component to how your website renders and interacts with the user? There are several things to consider here, and the relevance of these recommendations almost always become rules when you venture into high-caliber web development.
The purpose of the "put stylesheets at the top and scripts at the bottom" rule is that, in general, it's the best way to achieve optimal progressive rendering, which is critical to the user experience.
All else aside: assuming your test is valid, and you really are producing results contrary to the popular rules, it'd come as no surprise, really. Every website (and everything it takes to make the whole thing appear on a user's screen) is different and the Internet is constantly evolving.
First, I acknowledge that this is an Android thread but it is the first search result for this issue in general.
To open the most recently created Xcode Simulator Realm db in Realm Browser you can use this script in Automator or type it all in at the terminal. By using Automator, I have one-click access to my current realm.
cd ~/Library/Developer/CoreSimulator/Devices/
cd `ls -t | head -n 1`/data/Containers/Data/Application
cd `ls -t | head -n 1`/Documents
open -a 'Realm Browser' ./default.realm
Install Realm Browser. In Automator, click New, select Run Shell Script, paste in code, change Realm Db name, Click Run to test, save file somewhere convenient for quick click access.
I don't know where I found this tip the first time but this thread reminded me how I was accessing my live data in the past.
Nothing in the example says that the "classes implementing the same interface". MovieCatalog
is a type and CustomerPreferenceDao
is another type. Spring can easily tell them apart.
In Spring 2.x, wiring of beans mostly happened via bean IDs or names. This is still supported by Spring 3.x but often, you will have one instance of a bean with a certain type - most services are singletons. Creating names for those is tedious. So Spring started to support "autowire by type".
What the examples show is various ways that you can use to inject beans into fields, methods and constructors.
The XML already contains all the information that Spring needs since you have to specify the fully qualified class name in each bean. You need to be a bit careful with interfaces, though:
This autowiring will fail:
@Autowired
public void prepare( Interface1 bean1, Interface1 bean2 ) { ... }
Since Java doesn't keep the parameter names in the byte code, Spring can't distinguish between the two beans anymore. The fix is to use @Qualifier
:
@Autowired
public void prepare( @Qualifier("bean1") Interface1 bean1,
@Qualifier("bean2") Interface1 bean2 ) { ... }
Use the two argument for of Collections.sort
. You will want a suitable Comparator
that treats case appropriate (i.e. does lexical, not UTF16 ordering), such as that obtainable through java.text.Collator.getInstance
.
You can check your respone content, just console.log it and you will see whitch property have a status code. If you do not understand jsons, please refer to the video: https://www.youtube.com/watch?v=Bv_5Zv5c-Ts
It explains very basic knowledge that let you feel more comfortable with javascript.
You can do it with shorter version of ajax request, please see code above:
$.get("example.url.com", function(data) {
console.log(data);
}).done(function() {
// TO DO ON DONE
}).fail(function(data, textStatus, xhr) {
//This shows status code eg. 403
console.log("error", data.status);
//This shows status message eg. Forbidden
console.log("STATUS: "+xhr);
}).always(function() {
//TO-DO after fail/done request.
console.log("ended");
});
Example console output:
error 403
STATUS: Forbidden
ended
Kotlin
mapOf(
"param1" to 12,
"param2" to "cat"
).map { "${it.key}=${it.value}" }
.joinToString("&")
The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.
Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.
<input type="hidden" name="TrackingID"
<input type="text" name="FirstName" id="firstnametext" />
<input type="checkbox" name="IsLegal" value="Do you accept terms and conditions?" />
Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string
is nullable)) otherwise the AJAX or POST back will fail.
[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}
You can also post back a model without using any razor helpers. I have come across that this is needed some times.
public Class HomeModel
{
public int HouseNumber { get; set; }
public string StreetAddress { get; set; }
}
The HTML markup will simply be ...
<input type="text" name="variableName.HouseNumber" id="whateverid" >
and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.
[HttpPost]
public ActionResult PostBack(HomeModel variableName){
postBack.HouseNumber; //The value user entered
postBack.StreetAddress; //the default value of NULL.
}
When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.
TIP: The name of the parameter in the controller is the name defined in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !
Using List<>
is bit more complex in its mark-up.
<input type="text" name="variableNameHere[0].HouseNumber" id="id" value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber" value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">
Index on List<> MUST always be zero based and sequential. 0,1,2,3.
[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
int counter = MyHomes.Count()
foreach(var home in MyHomes)
{ ... }
}
Using IEnumerable<>
for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.
<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id" value="3">
<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3" value="4">
<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23" value="5">
And the code just needs to use IEnumerable and call ToList()
[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
int counter = variableNameHere.ToList().Count()
foreach(var home in variableNameHere)
{ ... }
}
It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.
So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.
There is indeed no such thing as a forward declaration of enum. As an enum's definition doesn't contain any code that could depend on other code using the enum, it's usually not a problem to define the enum completely when you're first declaring it.
If the only use of your enum is by private member functions, you can implement encapsulation by having the enum itself as a private member of that class. The enum still has to be fully defined at the point of declaration, that is, within the class definition. However, this is not a bigger problem as declaring private member functions there, and is not a worse exposal of implementation internals than that.
If you need a deeper degree of concealment for your implementation details, you can break it into an abstract interface, only consisting of pure virtual functions, and a concrete, completely concealed, class implementing (inheriting) the interface. Creation of class instances can be handled by a factory or a static member function of the interface. That way, even the real class name, let alone its private functions, won't be exposed.
Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.
The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch'
ref using any Git client tool".
The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>
. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>
; it lies to the git client.
Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH>
refs.
When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].
After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>
. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository
.
Its actually very simple: simply Rotate the list view to lay on its side
mlistView.setRotation(-90);
Then upon inflating the children, that should be inside the getView method. you rotate the children to stand up straight:
mylistViewchild.setRotation(90);
Edit: if your ListView doesnt fit properly after rotation, place the ListView inside this RotateLayout like this:
<com.github.rongi.rotate_layout.layout.RotateLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:angle="90"> <!-- Specify rotate angle here -->
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</com.github.rongi.rotate_layout.layout.RotateLayout>
An additional alternative is: responsivevoice.org a simple example JsFiddle is Here
HTML
<div id="container">
<input type="text" name="text">
<button id="gspeech" class="say">Say It</button>
<audio id="player1" src="" class="speech" hidden></audio>
</div>
JQuery
$(document).ready(function(){
$('#gspeech').on('click', function(){
var text = $('input[name="text"]').val();
responsiveVoice.speak("" + text +"");
<!-- http://responsivevoice.org/ -->
});
});
External Resource:
Compile the program with:
g++ -Wall -Wextra -Werror -c main.cpp -o main.o
^^^^^^^^^^^^^^^^^^^^ <- For listing all warnings when your code is compiled.
as cout
is present in the C++ standard library, which would need explicit linking with -lstdc++
when using gcc
; g++
links the standard library by default.
With gcc
, (g++
should be preferred over gcc
)
gcc main.cpp -lstdc++ -o main.o
First check with dmesg | grep tty
if system recognize your adapter.
Then try to run minicom with sudo minicom -s
, go to "Serial port setup" and change the first line to /dev/ttyUSB0
.
Don't forget to save config as default with "Save setup as dfl". It works for me on Ubuntu 11.04 on VirtualBox.
Even though @JamesMcNellis answer is a valid one I would like to explain something about error handling and also the fact that there is another way of doing what you want.
You have four ways of accessing a specific item in a vector:
[]
operatorat(...)
std::for_each
from the algorithm
header of the standard C++ library. This is another way which I can recommend (it uses internally an iterator). You can read more about it for example here.In the following examples I will be using the following vector as a lab rat and explaining the first three methods:
static const int arr[] = {1, 2, 3, 4};
std::vector<int> v(arr, arr+sizeof(arr)/sizeof(arr[0]));
This creates a vector as seen below:
1 2 3 4
First let's look at the []
way of doing things. It works in pretty much the same way as you expect when working with a normal array. You give an index and possibly you access the item you want. I say possibly because the []
operator doesn't check whether the vector actually has that many items. This leads to a silent invalid memory access. Example:
v[10] = 9;
This may or may not lead to an instant crash. Worst case is of course is if it doesn't and you actually get what seems to be a valid value. Similar to arrays this may lead to wasted time in trying to find the reason why for example 1000 lines of code later you get a value of 100
instead of 234
, which is somewhat connected to that very location where you retrieve an item from you vector.
A much better way is to use at(...)
. This will automatically check for out of bounds
behaviour and break throwing an std::out_of_range
. So in the case when we have
v.at(10) = 9;
We will get:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 4)
The third way is similar to the []
operator in the sense you can screw things up. A vector just like an array is a sequence of continuous memory blocks containing data of the same type. This means that you can use your starting address by assigning it to an iterator and then just add an offset to this iterator. The offset simply stands for how many items after the first item you want to traverse:
std::vector<int>::iterator it = v.begin(); // First element of your vector
*(it+0) = 9; // offest = 0 basically means accessing v.begin()
// Now we have 9 2 3 4 instead of 1 2 3 4
*(it+1) = -1; // offset = 1 means first item of v plus an additional one
// Now we have 9 -1 3 4 instead of 9 2 3 4
// ...
As you can see we can also do
*(it+10) = 9;
which is again an invalid memory access. This is basically the same as using at(0 + offset)
but without the out of bounds error checking.
I would advice using at(...)
whenever possible not only because it's more readable compared to the iterator access but because of the error checking for invalid index that I have mentioned above for both the iterator with offset combination and the []
operator.
The comment in your code is wrong. INADDR_ANY
doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.
Just to contribute with my approach. As already answered, RetryPolicy
is the way to go. But if you need a policy different the than default for all your requests, you can set it in a base Request class, so you don't need to set the policy for all the instances of your requests.
Something like this:
public class BaseRequest<T> extends Request<T> {
public BaseRequest(int method, String url, Response.ErrorListener listener) {
super(method, url, listener);
setRetryPolicy(getMyOwnDefaultRetryPolicy());
}
}
In my case I have a GsonRequest which extends from this BaseRequest, so I don't run the risk of forgetting to set the policy for an specific request and you can still override it if some specific request requires to.
namedtuples are a great feature, they are perfect container for data. When you have to "store" data you would use tuples or dictionaries, like:
user = dict(name="John", age=20)
or:
user = ("John", 20)
The dictionary approach is overwhelming, since dict are mutable and slower than tuples. On the other hand, the tuples are immutable and lightweight but lack readability for a great number of entries in the data fields.
namedtuples are the perfect compromise for the two approaches, the have great readability, lightweightness and immutability (plus they are polymorphic!).
It means that trackDAO
should not be serialized.
If you get an error 1044 (42000) when you try to run SQL commands in MySQL (which installed along XAMPP server) cmd prompt, then here's the solution:
Close your MySQL command prompt.
Open your cmd prompt (from Start menu -> run -> cmd) which will show: C:\Users\User>_
Go to MySQL.exe by Typing the following commands:
C:\Users\User>cd\
C:\>cd xampp
C:\xampp>cd mysql
C:\xxampp\mysql>cd bin
C:\xampp\mysql\bin>mysql -u root
Now try creating a new database by typing:
mysql> create database employee;
if it shows:
Query OK, 1 row affected (0.00 sec)
mysql>
Then congrats ! You are good to go...
I know this is a little old, but for anyone stumbling across this page should know there is a difference between \n and \r\n.
The \r\n gives a CRLF end of line and the \n gives an LF end of line character. There is very little difference to the eye in general.
Create a .txt from the string and then try and open in notepad (normal not notepad++) and you will notice the difference
SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIOD
Q44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901
Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901
The above is using 'CRLF' and the below is what 'LF only' would look like (There is a character that cant be seen where the LF shows).
SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIODQ44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901
If the Line Ends need to be corrected and the file is small enough in size, you can change the line endings in NotePad++ (or paste into word then back into Notepad - although this will make CRLF only).
This may cause some functions that read these files to potenitially no longer function (The example lines given are from GP Prescribing data - England. The file has changed from a CRLF Line end to an LF line end). This stopped an SSIS job from running and failed as couldn't read the LF line endings.
Source of Line Ending Information: https://en.wikipedia.org/wiki/Newline#Representations_in_different_character_encoding_specifications
Hope this helps someone in future :) CRLF = Windows based, LF or CF are from Unix based systems (Linux, MacOS etc.)
You can use string.punctuation with built-in NLTK stopwords list:
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from string import punctuation
words = tokenize(text)
wordsWOStopwords = removeStopWords(words)
def tokenize(text):
sents = sent_tokenize(text)
return [word_tokenize(sent) for sent in sents]
def removeStopWords(words):
customStopWords = set(stopwords.words('english')+list(punctuation))
return [word for word in words if word not in customStopWords]
NLTK stopwords complete list
You could use Matcher#start(group)
and Matcher#end(group)
to build a generic replacement method:
public static String replaceGroup(String regex, String source, int groupToReplace, String replacement) {
return replaceGroup(regex, source, groupToReplace, 1, replacement);
}
public static String replaceGroup(String regex, String source, int groupToReplace, int groupOccurrence, String replacement) {
Matcher m = Pattern.compile(regex).matcher(source);
for (int i = 0; i < groupOccurrence; i++)
if (!m.find()) return source; // pattern not met, may also throw an exception here
return new StringBuilder(source).replace(m.start(groupToReplace), m.end(groupToReplace), replacement).toString();
}
public static void main(String[] args) {
// replace with "%" what was matched by group 1
// input: aaa123ccc
// output: %123ccc
System.out.println(replaceGroup("([a-z]+)([0-9]+)([a-z]+)", "aaa123ccc", 1, "%"));
// replace with "!!!" what was matched the 4th time by the group 2
// input: a1b2c3d4e5
// output: a1b2c3d!!!e5
System.out.println(replaceGroup("([a-z])(\\d)", "a1b2c3d4e5", 2, 4, "!!!"));
}
Check online demo here.
Depending on your project, you might want to consider using EditorConfig (https://editorconfig.org/). There's a Notepad++ plugin which will load an .editorconfig where you can specify "lf" as the mandatory line ending.
I've only started using it, but it's nice so far, and open source projects I've worked on have included .editorconfig files for years. The "EOL Conversion" setting isn't changed, so it can be a bit confusing, but if you "View > Show Symbol > Show End of Line", you can see that it's adding LF instead of CRLF, even when "EOL Conversion" and the lower bottom corner shows something else (e.g. Windows (CR LF)).
This will work like a charm.
background-image:url("http://assets.toptal.io/uploads/blog/category/logo/4/php.png");
background-repeat: no-repeat;
background-size: contain;
make an example:
var body = document.body,
btn = document.getElementById( 'id' );
body.addEventListener( 'click', function( event ) {
console.log( event.currentTarget === body );
console.log( event.target === btn );
}, false );
when you click 'btn', and 'true' and 'true' will be appeared!
What's happening is that since the the TextView is filling the whole width of the inner LinearLayout it is already in the horizontal center of the layout. When you use android:layout_gravity
it places the widget, as a whole, in the gravity specified. Instead of placing the whole widget center what you're really trying to do is place the content in the center which can be accomplished with android:gravity="center_horizontal"
and the android:layout_gravity
attribute can be removed.
You need to call GetResponse().
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();
Use:
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
int minutes = c.get(Calendar.MINUTE);
int hour = c.get(Calendar.HOUR);
String time = hour + ":" + minutes + ":" + seconds;
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
String date = day + "/" + month + "/" + year;
// Assuming that you need date and time in a separate
// textview named txt_date and txt_time.
txt_date.setText(date);
txt_time.setText(time);
Since the question on how to convert from ISO-8859-1 to UTF-8 is closed because of this one I'm going to post my solution here.
The problem is when you try to GET anything by using XMLHttpRequest, if the XMLHttpRequest.responseType is "text" or empty, the XMLHttpRequest.response is transformed to a DOMString and that's were things break up. After, it's almost impossible to reliably work with that string.
Now, if the content from the server is ISO-8859-1 you'll have to force the response to be of type "Blob" and later convert this to DOMSTring. For example:
var ajax = new XMLHttpRequest();
ajax.open('GET', url, true);
ajax.responseType = 'blob';
ajax.onreadystatechange = function(){
...
if(ajax.responseType === 'blob'){
// Convert the blob to a string
var reader = new window.FileReader();
reader.addEventListener('loadend', function() {
// For ISO-8859-1 there's no further conversion required
Promise.resolve(reader.result);
});
reader.readAsBinaryString(ajax.response);
}
}
Seems like the magic is happening on readAsBinaryString so maybe someone can shed some light on why this works.
//In the Application_OnBeginRequest method in GLOBAL.ASX add the following:-
var res = HttpContext.Current.Response;
var req = HttpContext.Current.Request;
res.AppendHeader("Access-Control-Allow-Origin", "*");
res.AppendHeader("Access-Control-Allow-Credentials", "true");
res.AppendHeader("Access-Control-Allow-Headers", "Authorization");
res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
// ==== Respond to the OPTIONS verb =====
if (req.HttpMethod == "OPTIONS")
{
res.StatusCode = 200;
res.End();
}
//Remove any entries in the custom headers as this will throw an error that there's to
//many values in the header.
<httpProtocol>
<customHeaders>
</customHeaders>
</httpProtocol>
based on Sam Holder's answer, you could make an extension method for that
namespace adonet.extensions
{
public static class AdonetExt
{
public static int GetInt32(this SqlDataReader reader, string columnName)
{
return reader.GetInt32(reader.GetOrdinal(columnName));
}
}
}
and use it like this
using adonet.extensions;
//...
int farmsize = reader.GetInt32("farmsize");
assuming there is no GetInt32(string) already in SqlDataReader - if there is any, just use some other method name instead
This is an excerpt from method of mine, which converts a DataTable
(the dt
variable) into an array and then writes the array into a Range
on a worksheet (wsh
var). You can also change the topRow
variable to whatever row you want the array of strings to be placed at.
object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];
for (int r = 0; r < dt.Rows.Count; r++)
{
DataRow dr = dt.Rows[r];
for (int c = 0; c < dt.Columns.Count; c++)
{
arr[r, c] = dr[c];
}
}
Excel.Range c1 = (Excel.Range)wsh.Cells[topRow, 1];
Excel.Range c2 = (Excel.Range)wsh.Cells[topRow + dt.Rows.Count - 1, dt.Columns.Count];
Excel.Range range = wsh.get_Range(c1, c2);
range.Value = arr;
Of course you do not need to use an intermediate DataTable
like I did, the code excerpt is just to demonstrate how an array can be written to worksheet in single call.
With -Raw
you should get what you expect
The switch method (as mentioned by Guffa) works very nicely indeed. However, the default warning settings in most linters will alert you about the use of fall-through. It's one of the main reasons I use switches at all, so I pretty much ignore this warning, but you should be aware that the using the fall-through feature of the switch statement can be tricky. In cases like this, though - I'd go for it.
To make the code more clear that Kahia wrote in (it is clear but gets tricky when you want to add more text to it)...try this simple solution.
if (Math.Round((decimal)user.CurrentPoints) == user.CurrentPoints)
ViewBag.MyCurrentPoints = String.Format("Your current Points: {0:0}",user.CurrentPoints);
else
ViewBag.MyCurrentPoints = String.Format("Your current Points: {0:0.0}",user.CurrentPoints);
I had to add the extra cast (decimal) to have Math.Round compare the two decimal variables.
Thanks for the help everyone, rejecting the promise in .catch()
solved my issue:
export function fetchVehicle(id) {
return dispatch => {
return dispatch({
type: 'FETCH_VEHICLE',
payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
.then(status)
.then(res => res.json())
.catch(error => {
return Promise.reject()
})
});
};
}
function status(res) {
if (!res.ok) {
throw new Error(res.statusText);
}
return res;
}
Try binaryjs. Its just like socket.io but only thing it do well is that it stream audio video. Binaryjs google it
Method 4 is best.
if(foo != null && foo.bar()) {
someStuff();
}
will use short-circuit evaluation, meaning it ends if the first condition of a logical AND
is false.
public class StringEqualityTest extends TestCase {
public void testEquality() throws Exception {
String a = "abcde";
String b = new String(a);
assertTrue(a.equals(b));
assertFalse(a == b);
assertEquals(a, b);
}
}
You just need to put [(ngModel)]
on your select element:
<select class="form-control col-lg-8" #corporation required [(ngModel)]="selectedValue">
Try running the command
brew doctor
and let us know what sort of output you get
edit: And to answer the title question, this is from their FAQ :
Homebrew doesn’t write files outside its prefix. So generally you can just
rm -rf
the folder you installed it in.
So following that up with a clean re-install (following their latest recommended steps) should be your best bet.
the correct syntax is -
with t1
as
(select * from tab1
where conditions...
),
t2
as
(select * from tab2
where conditions...
(you can access columns of t1 here as well)
)
select * from t1, t2
where t1.col1=t2.col2;
Java Advanced Imaging is now open source, and provides the operations you need.
This is a great post. I like Waleed's solution. I haven't run it through patridge's test but it seems to be quite fast. I also needed the reverse process, converting a hex string to a byte array, so I wrote it as a reversal of Waleed's solution. Not sure if it's any faster than Tomalak's original solution. Again, I did not run the reverse process through patridge's test either.
private byte[] HexStringToByteArray(string hexString)
{
int hexStringLength = hexString.Length;
byte[] b = new byte[hexStringLength / 2];
for (int i = 0; i < hexStringLength; i += 2)
{
int topChar = (hexString[i] > 0x40 ? hexString[i] - 0x37 : hexString[i] - 0x30) << 4;
int bottomChar = hexString[i + 1] > 0x40 ? hexString[i + 1] - 0x37 : hexString[i + 1] - 0x30;
b[i / 2] = Convert.ToByte(topChar + bottomChar);
}
return b;
}
You could use the XMLParser that I have been working on.
$xml = XMLParser::encode(array(
'bla' => 'blub',
'foo' => 'bar',
'another_array' => array (
'stack' => 'overflow',
)
));
// @$xml instanceof SimpleXMLElement
echo $xml->asXML();
Would result in:
<?xml version="1.0"?>
<root>
<bla>blub</bla>
<foo>bar</foo>
<another_array>
<stack>overflow</stack>
</another_array>
</root>
Let’s look at how to filter a built-in JDK List and a MutableList using Eclipse Collections.
List<Integer> jdkList = Arrays.asList(1, 2, 3, 4, 5);
MutableList<Integer> ecList = Lists.mutable.with(1, 2, 3, 4, 5);
If you wanted to filter the numbers less than 3, you would expect the following outputs.
List<Integer> selected = Lists.mutable.with(1, 2);
List<Integer> rejected = Lists.mutable.with(3, 4, 5);
Here’s how you can filter using a Java 8 lambda as the Predicate
.
Assert.assertEquals(selected, Iterate.select(jdkList, each -> each < 3));
Assert.assertEquals(rejected, Iterate.reject(jdkList, each -> each < 3));
Assert.assertEquals(selected, ecList.select(each -> each < 3));
Assert.assertEquals(rejected, ecList.reject(each -> each < 3));
Here’s how you can filter using an anonymous inner class as the Predicate
.
Predicate<Integer> lessThan3 = new Predicate<Integer>()
{
public boolean accept(Integer each)
{
return each < 3;
}
};
Assert.assertEquals(selected, Iterate.select(jdkList, lessThan3));
Assert.assertEquals(selected, ecList.select(lessThan3));
Here are some alternatives to filtering JDK lists and Eclipse Collections MutableLists using the Predicates factory.
Assert.assertEquals(selected, Iterate.select(jdkList, Predicates.lessThan(3)));
Assert.assertEquals(selected, ecList.select(Predicates.lessThan(3)));
Here is a version that doesn't allocate an object for the predicate, by using the Predicates2 factory instead with the selectWith
method that takes a Predicate2
.
Assert.assertEquals(
selected, ecList.selectWith(Predicates2.<Integer>lessThan(), 3));
Sometimes you want to filter on a negative condition. There is a special method in Eclipse Collections for that called reject
.
Assert.assertEquals(rejected, Iterate.reject(jdkList, lessThan3));
Assert.assertEquals(rejected, ecList.reject(lessThan3));
The method partition
will return two collections, containing the elements selected by and rejected by the Predicate
.
PartitionIterable<Integer> jdkPartitioned = Iterate.partition(jdkList, lessThan3);
Assert.assertEquals(selected, jdkPartitioned.getSelected());
Assert.assertEquals(rejected, jdkPartitioned.getRejected());
PartitionList<Integer> ecPartitioned = gscList.partition(lessThan3);
Assert.assertEquals(selected, ecPartitioned.getSelected());
Assert.assertEquals(rejected, ecPartitioned.getRejected());
Note: I am a committer for Eclipse Collections.
Assuming C++11, here is a one-liner loop body, if this is consistent with your programming style:
using Map = std::map<K,V>;
Map map;
// Erase members that satisfy needs_removing(itr)
for (Map::const_iterator itr = map.cbegin() ; itr != map.cend() ; )
itr = needs_removing(itr) ? map.erase(itr) : std::next(itr);
A couple of other minor style changes:
Map::const_iterator
) when possible/convenient, over using auto
.using
for template types, to make ancillary types (Map::const_iterator
) easier to read/maintain.Recommendation. Do not use user-added REM statements to block batch steps. Use conditional GOTO instead. That way you can predefine and test the steps and options. The users also get much simpler changes and better confidence.
@Echo on
rem Using flags to control command execution
SET ExecuteSection1=0
SET ExecuteSection2=1
@echo off
IF %ExecuteSection1%==0 GOTO EndSection1
ECHO Section 1 Here
:EndSection1
IF %ExecuteSection2%==0 GOTO EndSection2
ECHO Section 2 Here
:EndSection2
exponent
is a 1D array. This means that exponent[0]
is a scalar, and exponent[0][i]
is trying to access it as if it were an array.
Did you mean to say:
L = identity(len(l))
for i in xrange(len(l)):
L[i][i] = exponent[i]
or even
L = diag(exponent)
?
I wrote a jQuery plugin, which catches keystrokes. It can be used to enable multiple language script input in html forms without the OS (except the fonts). Its about 300 lines of code, maybe you like to take a look:
Generally, be careful with such kind of alterations. I wrote the plugin for a client because other solutions weren't available.
You can also use template matching to detect shapes inside an image.
I had similar error: "Expecting value: line 1 column 1 (char 0)"
It helped for me to add "myfile.seek(0)", move the pointer to the 0 character
with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
myfile.seek(0)
Bank_0 = json.load(myfile)
Use facebook feed dialog instead of share dialog.
Example:
You could register to the KeyDown-Event of the Textbox, look if the pressed key is Enter and then execute the EventHandler of the button:
private void buttonTest_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello World");
}
private void textBoxTest_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
buttonTest_Click(this, new EventArgs());
}
}
Use this snippet
import os
import requests
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
name_img= os.path.basename(path_img)
files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
with requests.Session() as s:
r = s.post(url,files=files)
print(r.status_code)
I had the same issue. It seems the easiest solution is to just remove the remote, readd it, and fetch.
It can done easy by just using html draggable attribute
<textarea name="mytextarea" draggable="false"></textarea>
Default value is true.
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
In your connection string replace server=localhost
with "server = Paul-PC\\SQLEXPRESS;
"
I've compared the different options for speed and found that – much to my surprise – all options (except diag
) are equally fast. I personally use
A * b[:, None]
(or (A.T * b).T
) because it's short.
Code to reproduce the plot:
import numpy
import perfplot
def newaxis(data):
A, b = data
return A * b[:, numpy.newaxis]
def none(data):
A, b = data
return A * b[:, None]
def double_transpose(data):
A, b = data
return (A.T * b).T
def double_transpose_contiguous(data):
A, b = data
return numpy.ascontiguousarray((A.T * b).T)
def diag_dot(data):
A, b = data
return numpy.dot(numpy.diag(b), A)
def einsum(data):
A, b = data
return numpy.einsum("ij,i->ij", A, b)
perfplot.save(
"p.png",
setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n)),
kernels=[
newaxis,
none,
double_transpose,
double_transpose_contiguous,
diag_dot,
einsum,
],
n_range=[2 ** k for k in range(13)],
xlabel="len(A), len(b)",
)
As everyone else has mentioned it is better to use the "in" operator, it can also act on lists:
line = "This,is,a,sample,string"
lst = ['This', 'sample']
for i in lst:
i in line
>> True
>> True
You are going to have to come back to your main thread (also called UI thread
) in order to update
the UI.
Any other thread trying to update your UI will just cause exceptions
to be thrown all over the place.
So because you are in WPF, you can use the Dispatcher
and more specifically a beginInvoke
on this dispatcher
. This will allow you to execute what needs done (typically Update the UI) in the UI thread.
You migh also want to "register" the UI
in your business
, by maintaining a reference to a control/form, so you can use its dispatcher
.
A nice practical use of this is if you want to make your own HtmlHelper
extensions. For example, I hate trying to remember the <link>
tag syntax, so I've created my own extension method to make a <link>
tag:
<Extension()> _
Public Function CssBlock(ByVal html As HtmlHelper, ByVal src As String, ByVal Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
Dim tag = New TagBuilder("link")
tag.MergeAttribute("type", "text/css")
tag.MergeAttribute("rel", "stylesheet")
tag.MergeAttribute("href", src)
tag.MergeAttributes(New RouteValueDictionary(htmlAttributes))
Dim result = tag.ToString(TagRenderMode.Normal)
Return MvcHtmlString.Create(result)
End Function
I could have returned String
from this method, but if I had the following would break:
<%: Html.CssBlock(Url.Content("~/sytles/mysite.css")) %>
With MvcHtmlString
, using either <%: ... %>
or <%= ... %>
will both work correctly.
crypto-js is a rich javascript library containing many cryptography algorithms.
All you have to do is just call CryptoJS.MD5(password)
$.post(
'includes/login.php',
{ user: username, pass: CryptoJS.MD5(password) },
onLogin,
'json' );
See http://dev.mysql.com/doc/refman/8.0/en/numeric-types.html
INT
is a four-byte signed integer.
BIGINT
is an eight-byte signed integer.
They each accept no more and no fewer values than can be stored in their respective number of bytes. That means 232 values in an INT
and 264 values in a BIGINT
.
The 20 in INT(20)
and BIGINT(20)
means almost nothing. It's a hint for display width. It has nothing to do with storage, nor the range of values that column will accept.
Practically, it affects only the ZEROFILL
option:
CREATE TABLE foo ( bar INT(20) ZEROFILL );
INSERT INTO foo (bar) VALUES (1234);
SELECT bar from foo;
+----------------------+
| bar |
+----------------------+
| 00000000000000001234 |
+----------------------+
It's a common source of confusion for MySQL users to see INT(20)
and assume it's a size limit, something analogous to CHAR(20)
. This is not the case.
Use
git cherry-pick <commit>
to apply <commit>
to your current branch.
I myself would probably cross-check the commits I pick in gitk
and cherry-pick them with right-clicks on the commit entry there instead.
If you want to go more automatic (with all its dangers) and assuming all commits since yesterday happened on wss you could generate the list of commits using git log
(with --pretty
suggested by Jefromi)
git log --reverse --since=yesterday --pretty=%H
so everything together assuming you use bash
for commit in $(git log --reverse --since=yesterday --pretty=%H);
do
git cherry-pick $commit
done
If something goes wrong here (there is a lot of potential) you are in trouble since this works on the live checkout, so either do manual cherry-picks or use rebase like suggested by Jefromi.
Another possibility would be the use of REGEXP_SUBSTR.
The issue could be that your deployed files are not updated with the correct RMI methods. Check to see that your RMI interface has updated parameters, or updated data structures that your client does not have. Or that your RMI client has no parameters that differ from what your server version has.
This is just an educated guess. After re-deploying my server application's class files and re-testing, the problem of "Broken pipe" went away.
The main difference is that SurfaceView
can be drawn on by background theads but Views
can't.
SurfaceViews
use more resources though so you don't want to use them unless you have to.
This post is right from SAP on Sep 20, 2012.
In short, they are still working on a release of Crystal Reports that will support VS2012 (including support for Windows 8) It will come in the form of a service pack release that updates the version currently supporting VS2010. At that time they will drop 2010/2012 from the name and simply call it Crystal Reports Developer.
If you want to download that version you can find it here.
Further, service packs etc. when released can be found here.
I would also add that I am currently using Visual Studio 2012. As long as you don't edit existing reports they continue to compile and work fine. Even on Windows 8. When I need to modify a report I can still open the project with VS2010, do my work, save my changes, and then switch back to 2012. It's a little bit of a pain but the ability for VS2010 and VS2012 to co-exist is nice in this regard. I'm also using TFS2012 and so far it hasn't had a problem with me modifying files in 2010 on a "2012" solution.
Bootstrap 4
Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu
Bootstrap 3
I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/
The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..
http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook
Working in GIT 1.7.2.2
For example you have a remote some_remote with branches branch1, branch32
so to checkout a specific file you call this commands:
git checkout remote/branch path/to/file
as an example it will be something like this
git checkout some_remote/branch32 conf/en/myscript.conf
git checkout some_remote/branch1 conf/fr/load.wav
This checkout command will copy the whole file structure conf/en and conf/fr into the current directory where you call these commands (of course I assume you ran git init at some point before)
The termination of an array of characters with a null character is just a convention that is specifically for strings in C. You are dealing with something completely different -- an array of character pointers -- so it really has no relation to the convention for C strings. Sure, you could choose to terminate it with a null pointer; that perhaps could be your convention for arrays of pointers. There are other ways to do it. You can't ask people how it "should" work, because you're assuming some convention that isn't there.
Use the following JS:
$(document).ready(function () {
$("#btnsubmit").click(function () {
$.ajax({
type: "POST",
url: '/Plan/PlanManage', //your action
data: $('#PlanForm').serialize(), //your form name.it takes all the values of model
dataType: 'json',
success: function (result) {
console.log(result);
}
})
return false;
});
});
and the following code on your controller:
[HttpPost]
public string PlanManage(Plan objplan) //model plan
{
}
Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:
TypeError: 'numpy.float64' object cannot be interpreted as an integer
or
TypeError: 'numpy.float64' object is not iterable
The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:
def MinMax(x, mini=0, maxi=1)
return max(min(x,mini), maxi)
The solution was avoid numpy
or math
:
def MinMax(x, mini=0, maxi=1)
x = [x_aux if x_aux > mini else mini for x_aux in x]
x = [x_aux if x_aux < maxi else maxi for x_aux in x]
return max(min(x,mini), maxi)
Then, everything calm again. It was like one library possessed max
and min
!