Another solutions is - Backing Up and Restoring Database
Back Up the System Database
To back up the system database using Microsoft SQL Server Management Studio Express, follow the steps below:
Download and install Microsoft SQL Server 2008 Management Studio Express from the Microsoft web site: http://www.microsoft.com/en-us/download/details.aspx?id=7593
After Microsoft SQL Server Management Studio Express has been installed, launch the application to connect to the system database. The "Connect to Server" dialog box displays. In the "Server name:" field, enter the name of the Webtrends server on which the system database is installed. In the "Authentication:" field select "Windows Authentication" if logged into the Windows machine using the Webtrends service account or an account with rights to make changes to the system database. Otherwise, select "SQL Server Authentication" from the drop-down menu and enter the credentials for a SQL Server account which has the needed rights. Click "Connect" to connect to the database.
Select "OK" to complete the backup process.
Repeat the above steps for the "wtMaster" part of the database.
Restore the System Database
To restore the system database using Microsoft SQL Server Management Studio, follow the steps below:
If you haven't already, download and install Microsoft SQL Server 2008 Management Studio Express from the Microsoft web site: http://www.microsoft.com/en-us/download/details.aspx?id=7593
After Microsoft SQL Server Management Studio has been installed, launch the application to connect to the system database. The "Connect to Server" dialog box displays. In the "Server type:" field, select "Database Engine" (default). In the "Server name:" field, select "\WTSYSTEMDB" where is the name of the Webtrends server where the database is located. WTSYSTEMDB is the name of the database instance in a default installation. In the "Authentication:" field select "Windows Authentication" if logged into the Windows machine using the Webtrends service account or an account with rights to make changes to the system database. Otherwise, select "SQL Server Authentication" from the drop-down menu and enter the credentials for a SQL Server account which has the needed rights. Click "Connect" to connect to the database.
Expand "Databases", right-click on "wt_sched" and select "Delete" from the context menu. Make sure "Delete backup and restore history information for databases" check-box is checked.
Select "OK" to complete the deletion process.
Repeat the above steps for the "wtMaster" part of the database.
Right click on "Databases" and select "Restore Database..." from the context menu. In the "To database:" field type in "wt_sched". Select the "From device:" radio button. Click on the ellipse (...) to the right of the "From device:" text field. Click the "Add" button. Navigate to and select the backup file for "wt_sched". Select "OK" on the "Locate Backup File" form. Select "OK" on the "Specify Backup" form. Check the check-box in the restore column next to "wt_sched-Full Database Backup". Select "OK" on the "Restore Database" form.
Repeat step 6 for the "wtMaster" part of the database.
Had the same issue. It was resolved as described above.
In my index.js
var port = 1338,
express = require('express'),
app = express().use(express.static(__dirname + '/')),
http = require('http').Server(app),
io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(port, function(){
console.log("Node server listening on port " + port);
});
and in my index.html
<!doctype html>
<html>
<head>
<title>
My page
</title>
</head>
<body>
<script src = "lib/socket.io.js"></script>
<script src = "lib/three.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
the three.js was just in there for path testing. This will set all child files to start at the root directory of your app. Also socket.io.js can be called automatically using <script src = "/socket.io/socket.io.js">
through some dark magic (since there is physically a node_modules and lib directory in between) .
in fact there exists one trick:
create view view_test as
select
*
from
table
where id = (select convert(int, convert(binary(4), context_info)) from master.dbo.sysprocesses
where
spid = @@spid)
... in sql-query:
set context_info 2
select * from view_test
will be the same with
select * from table where id = 2
but using udf is more acceptable
What you put inside the </dependencies>
tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.
However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>
. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement>
tag.
You can also use the </dependencyManagement>
to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
This will need new var ttfixed
Then this under the tt
value slot and replace all pointers down below that are tt
to ttfixed
ttfixed = (tt.replace(",", "."));
In my case, I have Eclipse Maven project. I had the same issue and I posted detailed explanation of the issue and answer here Eclipse Maven - Code Completion fails "This compilation unit is not on the build path of a Java project" and "Failed to Download Index" Error
RENAME TABLE old_table_name TO new_table_name;
The main purpose of the interfaces is that it makes a contract between you and any other class that implement that interface which makes your code decoupled and allows expandability.
One possible solution is to open Android SDK Manager from
C:\Users\%user%\AppData\Local\Android\sdk
Check Android SDK build tool 21.1.1 download and install. Restart Android Studio
Sublime CodeFormatter has formatting support for PHP, JavaScript/JSON/JSONP, HTML, CSS, Python. Although I haven't used CodeFormatter for very long, I have been impressed with it's JS, HTML, and CSS "beautifying" capabilities. I haven't tried using it with PHP (I don't do any PHP development) or Python (which I have no experience with) but both languages have many options in the .sublime-settings
file.
One note however, the settings aren't very easy to find. On Windows you will need to go to your %AppData%\Roaming\Sublime Text #\Packages\CodeFormatter\CodeFormatter.sublime-settings
. As I don't have a Mac I'm not sure where the settings file is on OS X.
As for a shortcut key, I added this key binding to my "Key Bindings - User
" file:
{
"keys": ["ctrl+k", "ctrl+d"],
"command": "code_formatter"
}
I use Ctrl + K, Ctrl + D because that's what Visual Studio uses for formatting. You can change it, of course, just remember that what you choose might conflict with some other feature's keyboard shortcut.
Update:
It seems as if the developers of Sublime Text CodeFormatter have made it easier to access the .sublime-settings
file. If you install CodeFormatter with the Package Control plugin, you can access the settings via the Preferences -> Package Settings -> CodeFormatter -> Settings - Default
and override those settings using the Preferences -> Package Settings -> CodeFormatter -> Settings - User
menu item.
Updated 2x
Short answer: No, only the path and protocol field can be specified.
Longer answer:
There is no method in the JavaScript WebSockets API for specifying additional headers for the client/browser to send. The HTTP path ("GET /xyz") and protocol header ("Sec-WebSocket-Protocol") can be specified in the WebSocket constructor.
The Sec-WebSocket-Protocol header (which is sometimes extended to be used in websocket specific authentication) is generated from the optional second argument to the WebSocket constructor:
var ws = new WebSocket("ws://example.com/path", "protocol");
var ws = new WebSocket("ws://example.com/path", ["protocol1", "protocol2"]);
The above results in the following headers:
Sec-WebSocket-Protocol: protocol
and
Sec-WebSocket-Protocol: protocol1, protocol2
A common pattern for achieving WebSocket authentication/authorization is to implement a ticketing system where the page hosting the WebSocket client requests a ticket from the server and then passes this ticket during WebSocket connection setup either in the URL/query string, in the protocol field, or required as the first message after the connection is established. The server then only allows the connection to continue if the ticket is valid (exists, has not been already used, client IP encoded in ticket matches, timestamp in ticket is recent, etc). Here is a summary of WebSocket security information: https://devcenter.heroku.com/articles/websocket-security
Basic authentication was formerly an option but this has been deprecated and modern browsers don't send the header even if it is specified.
Basic Auth Info (Deprecated - No longer functional):
NOTE: the following information is no longer accurate in any modern browsers.
The Authorization header is generated from the username and password (or just username) field of the WebSocket URI:
var ws = new WebSocket("ws://username:[email protected]")
The above results in the following header with the string "username:password" base64 encoded:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
I have tested basic auth in Chrome 55 and Firefox 50 and verified that the basic auth info is indeed negotiated with the server (this may not work in Safari).
Thanks to Dmitry Frank's for the basic auth answer
Below worked for me:
When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/
Here's an alternative solution: if you have the date in PHP as a timestamp, bypass handling it with PHP and let the DB take care of transforming it by using the FROM_UNIXTIME
function.
mysql> insert into a_table values(FROM_UNIXTIME(1231634282));
Query OK, 1 row affected (0.00 sec)
mysql> select * from a_table;
+---------------------+
| a_date |
+---------------------+
| 2009-01-10 18:38:02 |
+---------------------+
Another way: The Iterator has an optional remove()-method, that is implemented for ArrayList. You can use it while iterating.
I don't know though, which variant is the most performant, you should measure it.
starblue commented, that the complexity isn't good, and that's true (for removeAll() too), because ArrayList has to copy all elements, if in the middle is an element added or removed. For that cases should a LinkedList work better. But, as we all don't know your real use-cases the best is too measure all variants, to pick the best solution.
You check if it's null
in C# like this:
if(MyObject != null) {
//do something
}
If you want to check against default (tough to understand the question on the info given) check:
if(MyObject != default(MyObject)) {
//do something
}
You can use unbind method to remove handler that has been attached...
if (current = 1){
$('li:eq(2)').unbind('click');
}
You can check what can unbind do ? Unbind manual
a=[100,200,300,400,500]
def search(b):
try:
k=a.index(b)
return a[k]
except ValueError:
return 'not found'
print(search(500))
it'll return the object if found else it'll return "not found"
I found a C preprocessor trick that is doing the same job without declaring a dedicated array string (Source: http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/c_preprocessor_applications_en).
Following the invention of Stefan Ram, sequential enums (without explicitely stating the index, e.g. enum {foo=-1, foo1 = 1}
) can be realized like this genius trick:
#include <stdio.h>
#define NAMES C(RED)C(GREEN)C(BLUE)
#define C(x) x,
enum color { NAMES TOP };
#undef C
#define C(x) #x,
const char * const color_name[] = { NAMES };
This gives the following result:
int main( void ) {
printf( "The color is %s.\n", color_name[ RED ]);
printf( "There are %d colors.\n", TOP );
}
The color is RED.
There are 3 colors.
Since I wanted to map error codes definitions to are array string, so that I can append the raw error definition to the error code (e.g. "The error is 3 (LC_FT_DEVICE_NOT_OPENED)."
), I extended the code in that way that you can easily determine the required index for the respective enum values:
#define LOOPN(n,a) LOOP##n(a)
#define LOOPF ,
#define LOOP2(a) a LOOPF a LOOPF
#define LOOP3(a) a LOOPF a LOOPF a LOOPF
#define LOOP4(a) a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP5(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP6(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP7(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP8(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP9(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LC_ERRORS_NAMES \
Cn(LC_RESPONSE_PLUGIN_OK, -10) \
Cw(8) \
Cn(LC_RESPONSE_GENERIC_ERROR, -1) \
Cn(LC_FT_OK, 0) \
Ci(LC_FT_INVALID_HANDLE) \
Ci(LC_FT_DEVICE_NOT_FOUND) \
Ci(LC_FT_DEVICE_NOT_OPENED) \
Ci(LC_FT_IO_ERROR) \
Ci(LC_FT_INSUFFICIENT_RESOURCES) \
Ci(LC_FT_INVALID_PARAMETER) \
Ci(LC_FT_INVALID_BAUD_RATE) \
Ci(LC_FT_DEVICE_NOT_OPENED_FOR_ERASE) \
Ci(LC_FT_DEVICE_NOT_OPENED_FOR_WRITE) \
Ci(LC_FT_FAILED_TO_WRITE_DEVICE) \
Ci(LC_FT_EEPROM_READ_FAILED) \
Ci(LC_FT_EEPROM_WRITE_FAILED) \
Ci(LC_FT_EEPROM_ERASE_FAILED) \
Ci(LC_FT_EEPROM_NOT_PRESENT) \
Ci(LC_FT_EEPROM_NOT_PROGRAMMED) \
Ci(LC_FT_INVALID_ARGS) \
Ci(LC_FT_NOT_SUPPORTED) \
Ci(LC_FT_OTHER_ERROR) \
Ci(LC_FT_DEVICE_LIST_NOT_READY)
#define Cn(x,y) x=y,
#define Ci(x) x,
#define Cw(x)
enum LC_errors { LC_ERRORS_NAMES TOP };
#undef Cn
#undef Ci
#undef Cw
#define Cn(x,y) #x,
#define Ci(x) #x,
#define Cw(x) LOOPN(x,"")
static const char* __LC_errors__strings[] = { LC_ERRORS_NAMES };
static const char** LC_errors__strings = &__LC_errors__strings[10];
In this example, the C preprocessor will generate the following code:
enum LC_errors { LC_RESPONSE_PLUGIN_OK=-10, LC_RESPONSE_GENERIC_ERROR=-1, LC_FT_OK=0, LC_FT_INVALID_HANDLE, LC_FT_DEVICE_NOT_FOUND, LC_FT_DEVICE_NOT_OPENED, LC_FT_IO_ERROR, LC_FT_INSUFFICIENT_RESOURCES, LC_FT_INVALID_PARAMETER, LC_FT_INVALID_BAUD_RATE, LC_FT_DEVICE_NOT_OPENED_FOR_ERASE, LC_FT_DEVICE_NOT_OPENED_FOR_WRITE, LC_FT_FAILED_TO_WRITE_DEVICE, LC_FT_EEPROM_READ_FAILED, LC_FT_EEPROM_WRITE_FAILED, LC_FT_EEPROM_ERASE_FAILED, LC_FT_EEPROM_NOT_PRESENT, LC_FT_EEPROM_NOT_PROGRAMMED, LC_FT_INVALID_ARGS, LC_FT_NOT_SUPPORTED, LC_FT_OTHER_ERROR, LC_FT_DEVICE_LIST_NOT_READY, TOP };
static const char* __LC_errors__strings[] = { "LC_RESPONSE_PLUGIN_OK", "" , "" , "" , "" , "" , "" , "" , "" "LC_RESPONSE_GENERIC_ERROR", "LC_FT_OK", "LC_FT_INVALID_HANDLE", "LC_FT_DEVICE_NOT_FOUND", "LC_FT_DEVICE_NOT_OPENED", "LC_FT_IO_ERROR", "LC_FT_INSUFFICIENT_RESOURCES", "LC_FT_INVALID_PARAMETER", "LC_FT_INVALID_BAUD_RATE", "LC_FT_DEVICE_NOT_OPENED_FOR_ERASE", "LC_FT_DEVICE_NOT_OPENED_FOR_WRITE", "LC_FT_FAILED_TO_WRITE_DEVICE", "LC_FT_EEPROM_READ_FAILED", "LC_FT_EEPROM_WRITE_FAILED", "LC_FT_EEPROM_ERASE_FAILED", "LC_FT_EEPROM_NOT_PRESENT", "LC_FT_EEPROM_NOT_PROGRAMMED", "LC_FT_INVALID_ARGS", "LC_FT_NOT_SUPPORTED", "LC_FT_OTHER_ERROR", "LC_FT_DEVICE_LIST_NOT_READY", };
This results to the following implementation capabilities:
LC_errors__strings[-1] ==> LC_errors__strings[LC_RESPONSE_GENERIC_ERROR] ==> "LC_RESPONSE_GENERIC_ERROR"
Remove the Newtonsoft.Json assembly from the project reference and add it again. You probably deleted or replaced the dll by accident.
Just a quick note. Be wary of using for..in
if you use a library (jQuery, Prototype, etc.), as most of them add methods to created Objects (including dictionaries).
This will mean that when you loop over them, method names will appear as keys. If you are using a library, look at the documentation and look for an enumerable section, where you will find the right methods for iteration of your objects.
There's no built-in command for it, so I usually just do something like this:
#!/bin/bash
# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs. The first revision of the file is emitted as
# full text since there's not previous version to compare it to.
function history_of_file() {
url=$1 # current url of file
svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {
# first revision as full text
echo
read r
svn log -r$r $url@HEAD
svn cat -r$r $url@HEAD
echo
# remaining revisions as differences to previous revision
while read r
do
echo
svn log -r$r $url@HEAD
svn diff -c$r $url@HEAD
echo
done
}
}
Then, you can call it with:
history_of_file $1
When I used --allow-unrelated-histories
, this command generated too many conflicts. There were conflicts in files which I didn't even work on. To get over the error " Refusing to merge unrelated histories"
, I used following rebase command:
git pull --rebase=preserve --allow-unrelated-histories
After this commit the uncommitted changes with a commit message. Finally, run the following command:
git rebase --continue
After this, my working copy was up-to-date with the remote copy and I was able to push my changes as before. No more unrelated histories error while pulling.
Came across this problem while upgrading projects across eclipse versions. For e.g. junits running well in Mars2.0 did not run on Neon. The following worked for me.
Illustration of the problem: (My code is computing delta in weeks, but same issue applies with delta in days)
Here is a very reasonable-looking implementation:
public static final long MILLIS_PER_WEEK = 7L * 24L * 60L * 60L * 1000L;
static public int getDeltaInWeeks(Date latterDate, Date earlierDate) {
long deltaInMillis = latterDate.getTime() - earlierDate.getTime();
int deltaInWeeks = (int)(deltaInMillis / MILLIS_PER_WEEK);
return deltaInWeeks;
}
But this test will fail:
public void testGetDeltaInWeeks() {
delta = AggregatedData.getDeltaInWeeks(dateMar09, dateFeb23);
assertEquals("weeks between Feb23 and Mar09", 2, delta);
}
The reason is:
Mon Mar 09 00:00:00 EDT 2009 = 1,236,571,200,000
Mon Feb 23 00:00:00 EST 2009 = 1,235,365,200,000
MillisPerWeek = 604,800,000
Thus,
(Mar09 - Feb23) / MillisPerWeek =
1,206,000,000 / 604,800,000 = 1.994...
but anyone looking at a calendar would agree that the answer is 2.
How do I select multiple columns by labels in pandas?
Multiple label-based range slicing is not easily supported with pandas, but position-based slicing is, so let's try that instead:
loc = df.columns.get_loc
df.iloc[:, np.r_[loc('A'):loc('C')+1, loc('E'), loc('G'):loc('I')+1]]
A B C E G H I
0 -1.666330 0.321260 -1.768185 -0.034774 0.023294 0.533451 -0.241990
1 0.911498 3.408758 0.419618 -0.462590 0.739092 1.103940 0.116119
2 1.243001 -0.867370 1.058194 0.314196 0.887469 0.471137 -1.361059
3 -0.525165 0.676371 0.325831 -1.152202 0.606079 1.002880 2.032663
4 0.706609 -0.424726 0.308808 1.994626 0.626522 -0.033057 1.725315
5 0.879802 -1.961398 0.131694 -0.931951 -0.242822 -1.056038 0.550346
6 0.199072 0.969283 0.347008 -2.611489 0.282920 -0.334618 0.243583
7 1.234059 1.000687 0.863572 0.412544 0.569687 -0.684413 -0.357968
8 -0.299185 0.566009 -0.859453 -0.564557 -0.562524 0.233489 -0.039145
9 0.937637 -2.171174 -1.940916 -1.553634 0.619965 -0.664284 -0.151388
Note that the +1
is added because when using iloc
the rightmost index is exclusive.
filter
is a nice and simple method for OP's headers, but this might not generalise well to arbitrary column names.
The "location-based" solution with loc
is a little closer to the ideal, but you cannot avoid creating intermediate DataFrames (that are eventually thrown out and garbage collected) to compute the final result range -- something that we would ideally like to avoid.
Lastly, "pick your columns directly" is good advice as long as you have a manageably small number of columns to pick. It will, however not be applicable in some cases where ranges span dozens (or possibly hundreds) of columns.
You should install PDO on your server.
Edit your php.ini (look at your phpinfo()
, "Loaded Configuration File" line, to find the php.ini file path).
Find and uncomment the following line (remove the ;
character):
;extension=pdo_mysql.so
Then, restart your Apache server. For more information, please read the documentation.
I resolved this problem this way:
In onCreateOptionsMenu
:
this.menu = menu;
this.menu.add("calendar");
ImageView imageView = new ImageView(getActivity());
imageView.setMinimumHeight(128);
imageView.setMinimumWidth(128);
imageView.setImageDrawable(yourDrawable);
MenuItem item = this.menu.getItem(0);
item.setActionView(imageView);
in onOptionsItemSelected
:
if (item.getOrder() == 0) {
//TODO
return true;
}
Compare every key in mapB against the counterpart in mapA. Then check if there is any key in mapA not existing in mapB
public boolean mapsAreEqual(Map<String, String> mapA, Map<String, String> mapB) {
try{
for (String k : mapB.keySet())
{
if (!mapA.get(k).equals(mapB.get(k))) {
return false;
}
}
for (String y : mapA.keySet())
{
if (!mapB.containsKey(y)) {
return false;
}
}
} catch (NullPointerException np) {
return false;
}
return true;
}
This rule
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o
is wrong. It says to create a file named producer.o (with -o producer.o
), but you want to create a file named main
. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o
As Shahbaz rightly points out, the gmake professionals would also use $^
which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ $^
Use map.panTo();
does not do anything if the point is in the current view. Use map.setView()
instead.
I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/
mymap.setView(point, 11, { animation: true });
BAD: https://jsfiddle.net/nstudor/Lgahv905/
mymap.panTo(point);
mymap.setZoom(11);
You've instantiated text2 as an Optional (e.g. var text2: String?). This is why you receive Optional("5") in your string. take away the ? and replace with:
var text2: String = ""
@Baba's answer is great. But you don't need to use explode
because fputcsv
takes an array as a parameter
For instance, if you have a three columns, four lines document, here's a more straight version:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$user_CSV[0] = array('first_name', 'last_name', 'age');
// very simple to increment with i++ if looping through a database result
$user_CSV[1] = array('Quentin', 'Del Viento', 34);
$user_CSV[2] = array('Antoine', 'Del Torro', 55);
$user_CSV[3] = array('Arthur', 'Vincente', 15);
$fp = fopen('php://output', 'wb');
foreach ($user_CSV as $line) {
// though CSV stands for "comma separated value"
// in many countries (including France) separator is ";"
fputcsv($fp, $line, ',');
}
fclose($fp);
As mentioned previously, compilers like to build lookup tables that optimize switch
statements to near O(1) timing whenever possible. Combine this with the fact that the C++ Language doesn't have a string type - std::string
is part of the Standard Library which is not part of the Language per se.
I will offer an alternative that you might want to consider, I've used it in the past to good effect. Instead of switching over the string itself, switch over the result of a hash function that uses the string as input. Your code will be almost as clear as switching over the string if you are using a predetermined set of strings:
enum string_code {
eFred,
eBarney,
eWilma,
eBetty,
...
};
string_code hashit (std::string const& inString) {
if (inString == "Fred") return eFred;
if (inString == "Barney") return eBarney;
...
}
void foo() {
switch (hashit(stringValue)) {
case eFred:
...
case eBarney:
...
}
}
There are a bunch of obvious optimizations that pretty much follow what the C compiler would do with a switch statement... funny how that happens.
You can't do that if USER is defined as a quoted string.
But you can do that if USER is just JACK or QUEEN or Joker or whatever.
There are two tricks to use:
#define JACK
to somethingSo let's start out with:
#define JACK_QUEEN_OTHER(u) EXPANSION1(ReSeRvEd_, u, 1, 2, 3)
Now, if I write JACK_QUEEN_OTHER(USER)
, and USER is JACK, the preprocessor
turns that into EXPANSION1(ReSeRvEd_, JACK, 1, 2, 3)
Step two is concatenation:
#define EXPANSION1(a, b, c, d, e) EXPANSION2(a##b, c, d, e)
Now JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(ReSeRvEd_JACK, 1, 2, 3)
This gives the opportunity to add a number of commas according to whether or not a string matches:
#define ReSeRvEd_JACK x,x,x
#define ReSeRvEd_QUEEN x,x
If USER is JACK, JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(x,x,x, 1, 2, 3)
If USER is QUEEN, JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(x,x, 1, 2, 3)
If USER is other, JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(ReSeRvEd_other, 1, 2, 3)
At this point, something critical has happened: the fourth argument to the EXPANSION2 macro is either 1, 2, or 3, depending on whether the original argument passed was jack, queen, or anything else. So all we have to do is pick it out. For long-winded reasons, we'll need two macros for the last step; they'll be EXPANSION2 and EXPANSION3, even though one seems unnecessary.
Putting it all together, we have these 6 macros:
#define JACK_QUEEN_OTHER(u) EXPANSION1(ReSeRvEd_, u, 1, 2, 3)
#define EXPANSION1(a, b, c, d, e) EXPANSION2(a##b, c, d, e)
#define EXPANSION2(a, b, c, d, ...) EXPANSION3(a, b, c, d)
#define EXPANSION3(a, b, c, d, ...) d
#define ReSeRvEd_JACK x,x,x
#define ReSeRvEd_QUEEN x,x
And you might use them like this:
int main() {
#if JACK_QUEEN_OTHER(USER) == 1
printf("Hello, Jack!\n");
#endif
#if JACK_QUEEN_OTHER(USER) == 2
printf("Hello, Queen!\n");
#endif
#if JACK_QUEEN_OTHER(USER) == 3
printf("Hello, who are you?\n");
#endif
}
Obligatory godbolt link: https://godbolt.org/z/8WGa19
MSVC Update: You have to parenthesize slightly differently to make things also work in MSVC. The EXPANSION* macros look like this:
#define EXPANSION1(a, b, c, d, e) EXPANSION2((a##b, c, d, e))
#define EXPANSION2(x) EXPANSION3 x
#define EXPANSION3(a, b, c, d, ...) d
Obligatory: https://godbolt.org/z/96Y8a1
jQuery.fn.extend
({
removeCss: function(cssName) {
return this.each(function() {
var curDom = $(this);
jQuery.grep(cssName.split(","),
function(cssToBeRemoved) {
curDom.css(cssToBeRemoved, '');
});
return curDom;
});
}
});
/*example code: I prefer JQuery extend so I can use it anywhere I want to use.
$('#searchJqueryObject').removeCss('background-color');
$('#searchJqueryObject').removeCss('background-color,height,width'); //supports comma separated css names.
*/
OR
//this parse style & remove style & rebuild style. I like the first one.. but anyway exploring..
jQuery.fn.extend
({
removeCSS: function(cssName) {
return this.each(function() {
return $(this).attr('style',
jQuery.grep($(this).attr('style').split(";"),
function(curCssName) {
if (curCssName.toUpperCase().indexOf(cssName.toUpperCase() + ':') <= 0)
return curCssName;
}).join(";"));
});
}
});
Simply my project wasn't in htdocs thats why it was showing me an this error make sure you put your project in HTdocs not in directory inside it
I composed this code as an example. Hope the idea works!
<?php
$friends = array('Robert', 'Louis', 'Ferdinand');
function greetings($friends){
echo "Greetings, $friends <br>";
}
foreach ($friends as $friend) {
greetings($friend);
}
?>
For portability, you really should do something like this:
public static final String NEW_LINE = System.getProperty("line.separator")
.
.
.
word.contains(NEW_LINE);
unless you're absolutely certain that "\n"
is what you want.
I had ran into this similar problem as well. In my case, my resolution is quite different. Here's my spring context xml file:
...
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
...
I'm not specifying any xsd version as I want spring to use the latest xsd version inside spring dependencies. The spring version my application used was spring-beans-4.3.1.RELEASE.jar:4.3.1.RELEASE and when I assembly my application into jar, all spring dependencies exist in my classpath. However, I received following error during startup of my spring application context:
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://www.springframework.org/schema/beans/spring-beans.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
After some hard time troubleshooting, I found the issue is due to the index.list inside the META-INF folder of my jar file. With index.list file, spring namespace handlers cannot be located to parse the spring application context xml correctly. You can read more about this spring issue SPR-5705
By removing indexing from my maven-jar-plugin, I manage to resolve the issue. Hope this will save some times for people having the same problem.
You can do something like this:
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings" inDirectory:nil forLocalization:@"es"];
NSBundle *spanishBundle = [[NSBundle alloc] initWithPath:[bundlePath stringByDeletingLastPathComponent]];
NSLocalizedStringFromTableInBundle(@"House", nil, spanishBundle, nil):
The popular Web Essentials plugin for Visual Studio offers a Markdown viewer and editor. It also supports the Github language syntax for adding code snippets.
Situation:
Solution:
I had the same issue when updating an older project. Here's what I did to resolve it:
The projects that used Entity Framework 5 and .NET 4 were installing the Entity Framework dll version 4.4. Once I switched the .NET version to 4.5 on the project, the dll version would be 5.
My problem came from older projects being on .NET 4 and a newer project running .NET 4.5 so there were 2 dll versions of EF in my solution.
Hope this helps someone...
From JDK8 on words it is as simple as
final String extension = ".java";
final File currentDir = new File(YOUR_DIRECTORY_PATH);
File[] files = currentDir.listFiles((File pathname) -> pathname.getName().endsWith(extension));
If you just want to remove "username1" you can use a simple replace.
name.replace("username1,", "")
or you could use split like you mentioned.
var name = "username1, username2 and username3 like this post.".split(",")[1];
$("h1").text(name);
jsfiddle example
You need to load your image as bitmap:
Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.your_image);
Then make the bitmap mutable and create a canvas over it:
Canvas canvas = new Canvas(bitmap.copy(Bitmap.Config.ARGB_8888, true));
You then can draw on the canvas.
Worth mentioning: you should download the x64 version!
From the main download page (https://www.iis.net/downloads/microsoft/url-rewrite) click "additional downloads" (under the main download button) and download the x64 version (because for some reason - the default download version is x86)
You are passing hello()
as a string, also hello()
means execute hello
immediately.
try
onClick={hello}
Use the Application Verifier (AppVerifier) tool from Microsoft.
In my case I need to simulate memory no longer being available so I did the following in the tool:
After 2 minutes my program could no longer allocate new memory and I was able to see how everything was handled.
Another solution, similar to Gerbus' solution, but this also works with relative font sizing.
ul {
letter-spacing: -1em; /* Effectively collapses white-space */
}
ul li {
display: inline;
letter-spacing: normal; /* Reset letter-spacing to normal value */
}
No need for extra software. Use the task scheduler -> create task -> hidden. The checkbox for hidden is in the bottom left corner. Set the task to trigger on login (or whatever condition you like) and choose the task in the actions tab. Running it hidden ensures that the task runs silently in the background like a service.
Note that you must also set the program to run "whether the user is logged in or not" or the program will still run in the foreground.
In the link you provided, thats not a loop in sql...
thats a loop in programming language
they are first getting list of all distinct districts, and then for each district executing query again.
Apache has 2 types of MPM (Multi-Processing Modules) defined:
1:Prefork 2: Worker
By default, Apacke is configured in preforked mode i.e. non-threaded pre-forking web server. That means that each Apache child process contains a single thread and handles one request at a time. Because of that, it consumes more resources.
Apache also has the worker MPM that turns Apache into a multi-process, multi-threaded web server. Worker MPM uses multiple child processes with many threads each.
I used the following code:
import urllib
def read_text():
quotes = urllib.urlopen("https://s3.amazonaws.com/udacity-hosted-downloads/ud036/movie_quotes.txt")
contents_file = quotes.read()
print contents_file
read_text()
Assuming these were datetime columns (if they're not apply to_datetime
) you can just subtract them:
df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])
In [11]: df.dtypes # if already datetime64 you don't need to use to_datetime
Out[11]:
A datetime64[ns]
B datetime64[ns]
dtype: object
In [12]: df['A'] - df['B']
Out[12]:
one -58 days
two -26 days
dtype: timedelta64[ns]
In [13]: df['C'] = df['A'] - df['B']
In [14]: df
Out[14]:
A B C
one 2014-01-01 2014-02-28 -58 days
two 2014-02-03 2014-03-01 -26 days
Note: ensure you're using a new of pandas (e.g. 0.13.1), this may not work in older versions.
The proper URL scheme is tel:[number] so you would do
<a href="tel:5551234567"><img src="callme.jpg" /></a>
_x000D_
The problem is likely to lie with the line:
window.onload = onPageLoad();
By including the brackets you are saying onload
should equal the return value of onPageLoad()
. For example:
/*Example function*/
function onPageLoad()
{
return "science";
}
/*Set on load*/
window.onload = onPageLoad()
If you print out the value of window.onload
to the console it will be:
science
The solution is remove the brackets:
window.onload = onPageLoad;
So, you're using onPageLoad
as a reference to the so-named function.
Finally, in order to get the response value you'll need a readystatechange
listener for your XMLHttpRequest
object, since it's asynchronous:
xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.
Here you add the listener:
xmlHttp.onreadystatechange = function() {
if(this.readyState == 4) {
// Do something
}
}
You can think of a static member function as one that exists without the need for an object to exist. For example, the Integer.parseInt() method from the Integer class is static. When you need to use it, you don't need to create a new Integer object, you simply call it. The same thing for main(). If you need to call a non-static member from it, simply put your main code in a class and then from main create a new object of your newly created class.
This question is old and things have evolved in JavaScript. You can now do this:
const params = {}
document.location.search.substr(1).split('&').forEach(pair => {
[key, value] = pair.split('=')
params[key] = value
})
and you get params.year
that contains 2008
.
You would also get other query params in your params
object.
Edit: a shorter/cleaner way to do this:
const params = new Map(location.search.slice(1).split('&').map(kv => kv.split('=')))
You can then test if the year
param exists with:
params.has('year') // true
Or retrieve it with:
params.get('year') // 2008
You can convert URL params to an Object:
const params = location.search.slice(1).split('&').reduce((acc, s) => {
const [k, v] = s.split('=')
return Object.assign(acc, {[k]: v})
}, {})
Then it can be used as a regular JS Object:
params.year // 2008
I had the same issue caused by two things:
So after I uninstalled the 32 bit Java 1.7, installed the correct one and added the javaw.exe path, eclipse fired up with no more errors
The curly braces mean concatenation, from most significant bit (MSB) on the left down to the least significant bit (LSB) on the right. You are creating a 32-bit bus (result) whose 16 most significant bits consist of 16 copies of bit 15 (the MSB) of the a bus, and whose 16 least significant bits consist of just the a bus (this particular construction is known as sign extension, which is needed e.g. to right-shift a negative number in two's complement form and keep it negative rather than introduce zeros into the MSBits).
There is a tutorial here*, but it doesn't explain too much more than the above paragraph.
For what it's worth, the nested curly braces around a[15:0]
are superfluous.
*Beware: the example within the tutorial link contains a typo when demonstrating multiple concatenations - the (2{C}}
should be a {2{2}}
.
I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:
dig @ns1.nameserver1.com domain.com txt
There are multiple classes that are grouped together as "numeric" classes, the 2 most common of which are double (for double precision floating point numbers) and integer. R will automatically convert between the numeric classes when needed, so for the most part it does not matter to the casual user whether the number 3 is currently stored as an integer or as a double. Most math is done using double precision, so that is often the default storage.
Sometimes you may want to specifically store a vector as integers if you know that they will never be converted to doubles (used as ID values or indexing) since integers require less storage space. But if they are going to be used in any math that will convert them to double, then it will probably be quickest to just store them as doubles to begin with.
Works for me.
<div ng-show="$scope.showme === true">Hello World</div>
<div ng-repeat="a in $scope.bigdata" ng-init="$scope.showme = true">{{ a.title }}</div>
First of all, remove component folder, which you have to delete and then remove its entries which you have made in "ts" files.
<table id="table_id" class="table table-hover">
<thead>
<tr>
...
...
</tr>
</thead>
</table>
use this command to clear the body of that table: $("#table_id tbody").empty()
I use jquery to load the table content dynamically, and use this command to clear the body when doing the refreshing.
hope this helps you.
The above answers missing a way to find the realm file in Android platform and believe me this way will save your lot's of time which we generally waste in other approaches to get the realm file. So let's start...
First open "Device File Explorer" in android studio(View -> Tools Windows -> Device File Explorer.
This will open your device explorer.
now open data -> data -> (your_app_package_name) -> files -> default.realm
default.realm is the file for which we are here. Now Save_as this file at your location and access the file from the realm_browser and you will get your database.
NOTE: Mentioned approach is tested on non-rooted phone(one+3).
You may use:
To create array of objects:
var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
Or if you wants to create a single object from values of arrays:
var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
I don't know about Windows (never used it), but on a Linux system you just have to create a build directory (in the top source directory)
mkdir build-dir
go inside it
cd build-dir
then run cmake
and point to the parent directory
cmake ..
and finally run make
make
Notice that make
and cmake
are different programs. cmake
is a Makefile
generator, and the make
utility is governed by a Makefile
textual file. See cmake & make wikipedia pages.
NB: On Windows, cmake
might operate so could need to be used differently. You'll need to read the documentation (like I did for Linux)
Short answer is you can't as above posts point out. But for my case, I simply didn't want to clutter the namespace but still have implicit conversions, so I just did:
#include <iostream>
using namespace std;
namespace Foo {
enum Foo { bar, baz };
}
int main() {
cout << Foo::bar << endl; // 0
cout << Foo::baz << endl; // 1
return 0;
}
The namespacing sort of adds a layer of type-safety while I don't have to static cast any enum values to the underlying type.
Using ng-selected for selected value. I Have successfully implemented code in AngularJS v1.3.2
<select ng-model="objBillingAddress.StateId" >_x000D_
<option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>_x000D_
</select>
_x000D_
Try this. It works for me:
yarn run lint --fix
or
npm run lint -- --fix
I did some test:
When it's running:
$ /usr/lib/zookeeper/bin/zkServer.sh status
JMX enabled by default
Using config: /usr/lib/zookeeper/bin/../conf/zoo.cfg
Mode: follower
When it's stopped:
$ zkServer status
JMX enabled by default
Using config: /usr/local/etc/zookeeper/zoo.cfg
Error contacting service. It is probably not running.
I'm not running on the same machine, but you get the idea.
I am in the process of developing a number of custom Plugins for CKEditor and here's my survival pack of bookmarks:
For your purpose, I would recommend look at one of the plugins in the _source/plugins
directory, for example the "print" button. Adding a simple Javascript function is quite easy to achieve. You should be able to duplicate the print plugin (take the directory from _source into the actual plugins/ directory, worry about minification later), rename it, rename every mention of "print" within it, give the button a proper name you use later in your toolbar setup to include the button, and add your function.
java 6
export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-amd64
or java 7
export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-amd64
I think it may be worth mentioning that [ConditionalAttribute]
is in the System.Diagnostics;
namespace. I stumbled a bit when I got:
Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)
after using it for the first time (I thought it would have been in System
).
Maybe: UPDATE test SET data = '"my-other-name"'::json WHERE id = 1;
It worked with my case, where data is a json type
Michael has given a very comprehensive answer, but I'd like to point out a few things which you can still do to be able to use grids in IE in a nearly painless way.
repeat
functionality is supportedYou can still use the repeat functionality, it's just hiding behind a different syntax. Instead of writing repeat(4, 1fr)
, you have to write (1fr)[4]
. That's it.
See this series of articles for the current state of affairs: https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/
Grid gaps are supported in all browsers except IE. So you can use the @supports
at-rule to set the grid-gaps conditionally for all new browsers:
Example:
.grid {
display: grid;
}
.item {
margin-right: 1rem;
margin-bottom: 1rem;
}
@supports (grid-gap: 1rem) {
.grid {
grid-gap: 1rem;
}
.item {
margin-right: 0;
margin-bottom: 0;
}
}
It's a little verbose, but on the plus side, you don't have to give up grids altogether just to support IE.
I can't stress this enough - half the pain of grids is solved just be using autoprefixer in your build step. Write your CSS in a standards-complaint way, and just let autoprefixer do it's job transforming all older spec properties automatically. When you decide you don't want to support IE, just change one line in the browserlist config and you'll have removed all IE-specific code from your built files.
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
How about importing the username and password from a file external to the script? That way even if someone got hold of the script, they wouldn't automatically get the password.
You can do it like this:
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="inputType" class="col-sm-2 control-label">Label</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="input" placeholder="Input text">
</div>
</div>
</form>
Branches in SVN are essentially directories; you don't name the branch so much as choose the name of the directory to branch into.
The common way of 'naming' a branch is to place it under a directory called branches
in your repository. In the "To URL:" portion of TortoiseSVN's Branch dialog, you would therefore enter something like:
(svn/http)://path-to-repo/branches/your-branch-name
The main branch of a project is referred to as the trunk, and is usually located in:
(svn/http)://path-to-repo/trunk
If someone would need a one liner:
iwr -Uri 'https://api.github.com/user' -Headers @{ Authorization = "Basic "+ [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("user:pass")) }
I actually have the same issue.
This link is probably my best guess:
nodejs vs node on ubuntu 12.04
I did that to resolve my problem:
sudo apt-get --purge remove node
sudo apt-get --purge remove nodejs
sudo apt-get install nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
Issue resolved.!!! Below are the solutions.
For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar
Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
Issue is that it is failed to decrypt 256 bits of encryption.
The following are totally acceptable in python:
int
float
float
int
float
But you get a ValueError
if you pass a string representation of a float into int
, or a string representation of anything but an integer (including empty string). If you do want to pass a string representation of a float to an int
, as @katyhuff points out above, you can convert to a float first, then to an integer:
>>> int('5')
5
>>> float('5.0')
5.0
>>> float('5')
5.0
>>> int(5.0)
5
>>> float(5)
5.0
>>> int('5.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
>>> int(float('5.0'))
5
you can remove the array content with passing the array index or you can remove all
var array = [String]()
print(array)
array.append("MY NAME")
print(array)
array.removeFirst()
print(array)
array.append("MY NAME")
array.removeLast()
array.append("MY NAME1")
array.append("MY NAME2")
print(array)
array.removeAll()
print(array)
For those using objects that are not an Array
or even array-like, you can build your own iterable easily so you can still use for of
for things like localStorage
which really only have a length
:
function indexerator(length) {
var output = new Object();
var index = 0;
output[Symbol.iterator] = function() {
return {next:function() {
return (index < length) ? {value:index++} : {done:true};
}};
};
return output;
}
Then just feed it a number:
for (let index of indexerator(localStorage.length))
console.log(localStorage.key(index))
You don't need to call json.getJSONArray()
at all, because the JSON you're working with already is an array. So, don't construct an instance of JSONObject
; use a JSONArray
. This should suffice:
// ...
JSONArray json = new JSONArray(result);
// ...
for(int i=0;i<json.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = json.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
You can't use exactly the same methods as in the tutorial, because the JSON you're dealing with needs to be parsed into a JSONArray
at the root, not a JSONObject
.
1.Go to My Computer Properties
2.Then click on Advance setting.
3.Go to Environment variable
4.Set the path to
F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3\lib;F:\oracle\product\10.2.0\db_2\sysman\admin\scripts;
change your drive and folder depending on your requirement...
SELECT * FROM table WHERE col >= '2010-10-01' AND col <= '2010-10-31'
Depends what you want to do.
If what you want is to retrieve the bytes that are remaining (between position and limit), then what you have will work. You could also just do:
ByteBuffer bb =..
byte[] b = new byte[bb.remaining()];
bb.get(b);
which is equivalent as per the ByteBuffer javadocs.
You can use a regular expresion to for example replace all non-alphanumeric characters with commas:
s = Regex.Replace(s, "[^0-9A-Za-z]+", ",");
Note: The +
after the set will make it replace each group of non-alphanumeric characters with a comma. If you want to replace each character with a comma, just remove the +
.
First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate
$('.swipeRight').click(function()
{
$('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});
$('.swipeLeft').click(function()
{
$('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});
The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.
For Oracle Java applications, add this after the ObjectMapper
instantiation:
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
While you can't kill all open connections with a single command, you can create a set of queries to do that for you if there are too many to do by hand.
This example will create a series of KILL <pid>;
queries for all some_user
's connections from 192.168.1.1
to my_db
.
SELECT
CONCAT('KILL ', id, ';')
FROM INFORMATION_SCHEMA.PROCESSLIST
WHERE `User` = 'some_user'
AND `Host` = '192.168.1.1';
AND `db` = 'my_db';
You can use charAt() function to find out spaces in string.
public class Test {
public static void main(String args[]) {
String fav="Hi Testing 12 3";
int counter=0;
for( int i=0; i<fav.length(); i++ ) {
if(fav.charAt(i) == ' ' ) {
counter++;
}
}
System.out.println("Number of spaces "+ counter);
//This will print Number of spaces 4
}
}
You can replace target-action with a closure (block in Objective-C) by adding a helper closure wrapper (ClosureSleeve) and adding it as an associated object to the control so it gets retained. That way you can pass any parameters.
class ClosureSleeve {
let closure: () -> ()
init(attachTo: AnyObject, closure: @escaping () -> ()) {
self.closure = closure
objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
}
@objc func invoke() {
closure()
}
}
extension UIControl {
func addAction(for controlEvents: UIControlEvents, action: @escaping () -> ()) {
let sleeve = ClosureSleeve(attachTo: self, closure: action)
addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
}
}
Usage:
button.addAction(for: .touchUpInside) {
self.switchToNewsDetails(parameter: i)
}
You can do this with a table value parameters.
Have a look at the following article:
http://www.codeproject.com/Articles/39161/C-and-Table-Value-Parameters
You can install the apk on your phone, then
connect using adb, you can launch adb shell and execute pm list packages -f, which shows the package name for each installed apk.
This taken from Find package name for Android apps to use Intent to launch Market app from web
I wanted to add this to the previous suggestions. If you are using a version of Linux that has SELinux enabled then you should also execute this in a shell:
chcon -R --type httpd_sys_rw_content_t /path/to/your/directory
Along with giving your web server user permissions either through group or changing of the owner of the directory.
The code snippet you gave does indeed load the entire set of data and then counts it client-side, which can be very slow for large amounts of data.
Firebase doesn't currently have a way to count children without loading data, but we do plan to add it.
For now, one solution would be to maintain a counter of the number of children and update it every time you add a new child. You could use a transaction to count items, like in this code tracking upvodes:
var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
return (current_value || 0) + 1;
});
For more info, see https://www.firebase.com/docs/transactions.html
UPDATE: Firebase recently released Cloud Functions. With Cloud Functions, you don't need to create your own Server. You can simply write JavaScript functions and upload it to Firebase. Firebase will be responsible for triggering functions whenever an event occurs.
If you want to count upvotes for example, you should create a structure similar to this one:
{
"posts" : {
"-JRHTHaIs-jNPLXOQivY" : {
"upvotes_count":5,
"upvotes" : {
"userX" : true,
"userY" : true,
"userZ" : true,
...
}
}
}
}
And then write a javascript function to increase the upvotes_count
when there is a new write to the upvotes
node.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.countlikes = functions.database.ref('/posts/$postid/upvotes').onWrite(event => {
return event.data.ref.parent.child('upvotes_count').set(event.data.numChildren());
});
You can read the Documentation to know how to Get Started with Cloud Functions.
Also, another example of counting posts is here: https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js
The firebase docs have changed so instead of event
we now have change
and context
.
The given example throws an error complaining that event.data
is undefined. This pattern seems to work better:
exports.countPrescriptions = functions.database.ref(`/prescriptions`).onWrite((change, context) => {
const data = change.after.val();
const count = Object.keys(data).length;
return change.after.ref.child('_count').set(count);
});
```
Here is how I did it. You can see how I convert the requestedURI to a filesystem path (what this SO question is about). Bonus: and also how to respond with the file.
@RequestMapping(value = "/file/{userId}/**", method = RequestMethod.GET)
public void serveFile(@PathVariable("userId") long userId, HttpServletRequest request, HttpServletResponse response) {
assert request != null;
assert response != null;
// requestURL: http://192.168.1.3:8080/file/54/documents/tutorial.pdf
// requestURI: /file/54/documents/tutorial.pdf
// servletPath: /file/54/documents/tutorial.pdf
// logger.debug("requestURL: " + request.getRequestURL());
// logger.debug("requestURI: " + request.getRequestURI());
// logger.debug("servletPath: " + request.getServletPath());
String requestURI = request.getRequestURI();
String relativePath = requestURI.replaceFirst("^/file/", "");
Path path = Paths.get("/user_files").resolve(relativePath);
try {
InputStream is = new FileInputStream(path.toFile());
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
logger.error("Error writing file to output stream. Path: '" + path + "', requestURI: '" + requestURI + "'");
throw new RuntimeException("IOError writing file to output stream");
}
}
None
is a singleton, therefore identity comparison will always work, whereas an object can fake the equality comparison via .__eq__()
.
In case it helps someone, I had a similar issue and the error was because of two reasons:
Not using the app's namespace before the url name
{% url 'app_name:url_name' %}
Missing single quotes around the url name (as pointed out here by Charlie)
Can also use:
find . -mindepth 1 -mtime +3 -delete
To not delete target directory
In css you can't set table-cells max height, and if you white-space nowrap then you can't break it with max width, so the solution is javascript working in all browsers.
So, this can work for you.
For Limiting max-height of all cells or rows in table with Javascript:
This script is good for horizontal overflow tables.
This script increase the table width 300px each time, maximum 4000px until rows shrinks to max-height(160px) , and you can also edit numbers as your need.
var i = 0, row, table = document.getElementsByTagName('table')[0], j = table.offsetWidth;
while (row = table.rows[i++]) {
while (row.offsetHeight > 160 && j < 4000) {
j += 300;
table.style.width = j + 'px';
}
}
Source: HTML Table Solution Max Height Limit For Rows Or Cells By Increasing Table Width, Javascript
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
class of my button is "input-addon btn btn-default fileinput-exists"
below code helped me
document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();
but I want to click second button, I have two buttons in my screen so I used querySelectorAll
var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
elem[1].click();
here elem[1] is the second button object that I want to click.
I think your co-worker is smart and you are also correct.
The useful things I found that putting everything into the headers is that:
No need for writing & sync headers and sources.
The structure is plain and no circular dependencies force the coder to make a "better" structure.
Portable, easy to embedded to a new project.
I do agree with the compiling time problem, but I think we should notice that:
The change of source file are very likely to change the header files which leads to the whole project be recompiled again.
Compiling speed is much faster than before. And if you have a project to be built with a long time and high frequency, it may indicates that your project design has flaws. Seperate the tasks into different projects and module can avoid this problem.
Lastly I just wanna support your co-worker, just in my personal view.
According to nginx documentation
there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else
So you could define something like
location ~ (dir1|file2\.php) {
# empty
}
location / {
rewrite ^/(.*) http://example.com/$1 permanent;
}
I investigate i knew that the jquery script need to load in order that why it not worked in your case. Because $ symbol mentioned in code not understand unless you load Jquery 1.9.1 at first. Load like follows
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
Then it will work fine
You can use the IAsyncResult and Action class/interface to achieve this.
public void TimeoutExample()
{
IAsyncResult result;
Action action = () =>
{
// Your code here
};
result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(10000))
Console.WriteLine("Method successful.");
else
Console.WriteLine("Method timed out.");
}
BigDecimal does not seem to respect Locale settings.
Locale.getDefault(); //returns sl_SI
Slovenian locale should have a decimal comma. Guess I had strange misconceptions regarding numbers.
a = new BigDecimal("1,2") //throws exception
a = new BigDecimal("1.2") //is ok
a.toPlainString() // returns "1.2" always
I have edited a part of my message that made no sense since it proved to be due the human error (forgot to commit data and was looking at the wrong thing).
Same as BigDecimal can be said for any Java .toString() functions. I guess that is good in some ways. Serialization for example or debugging. There is an unique string representation.
Also as others mentioned using formatters works OK. Just use formatters, same for the JSF frontend, formatters do the job properly and are aware of the locale.
You should definitely check out the MSDN on what Outlook will support in regards to css and html. The link is here: http://msdn.microsoft.com/en-us/library/aa338201(v=office.12).aspx. If you do not have at least office 2007 you really need to upgrade as there are major differences between 2007 and previous editions. Also try saving the resulting email to file and examine it with firefox you will see what is being changed by outlook and possibly have a more specific question to ask. You can use Word to view the email as a sort of preview as well (but you won't get info on what styles are/are not being applied.
You haven't really said much about what sort of random string you need. But in any case, you should look into the random
module.
A very simple solution is pasted below.
import random
def randstring(length=10):
valid_letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
return ''.join((random.choice(valid_letters) for i in xrange(length)))
print randstring()
print randstring(20)
You can get a vertical space even though you have NO WHITESPACE whatsoever between your inline-block elements.
For me, this was caused by line-height
. The simple fix was:
div.container {
line-height: 0;
}
div.container > * {
line-height: normal;
}
Could there be any problem if i replace Method-1 by Method-2?
No, just use map[key] = value
. The two options are equivalent.
Regarding Dictionary<>
vs. Hashtable
: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, add: false);
and the add
parameter is responsible for throwing an exception, when inserting a duplicate key. So the behavior is the same for both classes.
Because you send custom headers so your CORS request is not a simple request, so the browser first sends a preflight OPTIONS request to check that the server allows your request.
If you turn on CORS on the server then your code will work. You can also use JavaScript fetch instead (here)
let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=My-First-Header,My-Second-Header';_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
type: 'POST',_x000D_
url: url,_x000D_
headers: {_x000D_
"My-First-Header":"first value",_x000D_
"My-Second-Header":"second value"_x000D_
}_x000D_
}).done(function(data) {_x000D_
alert(data[0].request.httpMethod + ' was send - open chrome console> network to see it');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Here is an example configuration which turns on CORS on nginx (nginx.conf file):
location ~ ^/index\.php(/|$) {_x000D_
..._x000D_
add_header 'Access-Control-Allow-Origin' "$http_origin" always;_x000D_
add_header 'Access-Control-Allow-Credentials' 'true' always;_x000D_
if ($request_method = OPTIONS) {_x000D_
add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)_x000D_
add_header 'Access-Control-Allow-Credentials' 'true';_x000D_
add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days_x000D_
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';_x000D_
add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';_x000D_
add_header 'Content-Length' 0;_x000D_
add_header 'Content-Type' 'text/plain charset=UTF-8';_x000D_
return 204;_x000D_
}_x000D_
}
_x000D_
Here is an example configuration which turns on CORS on Apache (.htaccess file)
# ------------------------------------------------------------------------------_x000D_
# | Cross-domain Ajax requests |_x000D_
# ------------------------------------------------------------------------------_x000D_
_x000D_
# Enable cross-origin Ajax requests._x000D_
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity_x000D_
# http://enable-cors.org/_x000D_
_x000D_
# <IfModule mod_headers.c>_x000D_
# Header set Access-Control-Allow-Origin "*"_x000D_
# </IfModule>_x000D_
_x000D_
#Header set Access-Control-Allow-Origin "http://example.com:3000"_x000D_
#Header always set Access-Control-Allow-Credentials "true"_x000D_
_x000D_
Header set Access-Control-Allow-Origin "*"_x000D_
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"_x000D_
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"
_x000D_
New, simplified answer to an old, commonly asked question...
Always (90% important to remember)
Attribute Values (9% important to remember)
attr="
'
Single quotes'
are ok within double quotes."
attr='
"
Double quotes"
are ok within single quotes.'
"
as "
and '
as '
otherwise.Comments, CDATA, and Processing Instructions (0.9% important to remember)
Esoterica (0.1% important to remember)
]]>
as ]]>
unless ]]>
is ending a CDATA section. I'm on High Sierra MAC OS and just installed Anaconda3 via HomeBrew command. I had issue with running :
conda
It'd also give me:
-bash: conda: command not found
I tried running:
export PATH=~/anaconda3/bin:$PATH
but it needs ENTIRE path. so here are the correct steps:
$ nano ~/.bash_profile
Now export the ENTIRE path, in my case it was:
export PATH=/usr/local/anaconda3/bin:$PATH
Exit out and run:
$ source ~/.bash_profile
Then try:
$ conda
it'll output:
$ conda --version
conda 4.4.10
Use npm update
or,
Run `npm install --save-dev @angular-devkit/build-angular
`
I had the same problem but Dirk's solution didn't seem to work. I was getting this warning messege every time
"prob" is not a graphical parameter
I read through ?hist
and found about freq: a logical vector set TRUE by default.
the code that worked for me is
hist(x,freq=FALSE)
lines(density(x),na.rm=TRUE)
Looks like you need to use in_array function.
jQuery -> inArray
Prototype -> Array.indexOf
Or, see these examples if you are not using jQuery or Prototype:
Stylistic note: variables named thisthing thatthing, should be named to tell you something about what they contain (noun).
In kotlin, you can create extensions functions on resources (activities|fragments |context) that will convert your string to an html span
e.g.
fun Resources.getHtmlSpannedString(@StringRes id: Int): Spanned = getString(id).toHtmlSpan()
fun Resources.getHtmlSpannedString(@StringRes id: Int, vararg formatArgs: Any): Spanned = getString(id, *formatArgs).toHtmlSpan()
fun Resources.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int): Spanned = getQuantityString(id, quantity).toHtmlSpan()
fun Resources.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): Spanned = getQuantityString(id, quantity, *formatArgs).toHtmlSpan()
fun String.toHtmlSpan(): Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(this)
}
Usage
//your strings.xml
<string name="greeting"><![CDATA[<b>Hello %s!</b><br>]]>This is newline</string>
//in your fragment or activity
resources.getHtmlSpannedString(R.string.greeting, "World")
EDIT even more extensions
fun Context.getHtmlSpannedString(@StringRes id: Int): Spanned = getString(id).toHtmlSpan()
fun Context.getHtmlSpannedString(@StringRes id: Int, vararg formatArgs: Any): Spanned = getString(id, *formatArgs).toHtmlSpan()
fun Context.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int): Spanned = resources.getQuantityString(id, quantity).toHtmlSpan()
fun Context.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): Spanned = resources.getQuantityString(id, quantity, *formatArgs).toHtmlSpan()
fun Activity.getHtmlSpannedString(@StringRes id: Int): Spanned = getString(id).toHtmlSpan()
fun Activity.getHtmlSpannedString(@StringRes id: Int, vararg formatArgs: Any): Spanned = getString(id, *formatArgs).toHtmlSpan()
fun Activity.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int): Spanned = resources.getQuantityString(id, quantity).toHtmlSpan()
fun Activity.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): Spanned = resources.getQuantityString(id, quantity, *formatArgs).toHtmlSpan()
fun Fragment.getHtmlSpannedString(@StringRes id: Int): Spanned = getString(id).toHtmlSpan()
fun Fragment.getHtmlSpannedString(@StringRes id: Int, vararg formatArgs: Any): Spanned = getString(id, *formatArgs).toHtmlSpan()
fun Fragment.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int): Spanned = resources.getQuantityString(id, quantity).toHtmlSpan()
fun Fragment.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): Spanned = resources.getQuantityString(id, quantity, *formatArgs).toHtmlSpan()
If you need to re-use a string, then use StringBuffer:
String str = "hi";
StringBuffer sb = new StringBuffer(str);
while (...) {
sb.setCharAt(1, 'k');
}
EDIT:
Note that StringBuffer is thread-safe, while using StringBuilder is faster, but not thread-safe.
.list-wrap {
width: 355px;
height: 100%;
position: relative;
.list {
position: absolute;
top: 0;
bottom: 0;
overflow-y: auto;
width: 100%;
}
}
I usually use git on my linux machine, but at work I have to use Windows. I had the same problem when trying to commit the first commit in a Windows environment.
For those still facing this problem, I was able to resolve it as follows:
$ git commit --allow-empty -n -m "Initial commit".
I would like to improve on the accepted answer
Downsides of using .bashrc
with eval ssh-agent -s
:
Here is my .bashrc
that will eradicate above downsides
Put this .bashrc
into your home directory (Windows 10: C:\Users\[username]\.bashrc
) and it will be executed every time a new git-bash is opened
and ssh-add
will be working as a first class citizen
Read #comments to understand how it works
# Env vars used
# SSH_AUTH_SOCK - ssh-agent socket, should be set for ssh-add or git to be able to connect
# SSH_AGENT_PID - ssh-agent process id, should be set in order to check that it is running
# SSH_AGENT_ENV - env file path to share variable between instances of git-bash
SSH_AGENT_ENV=~/ssh-agent.env
# import env file and supress error message if it does not exist
. $SSH_AGENT_ENV 2> /dev/null
# if we know that ssh-agent was launched before ($SSH_AGENT_PID is set) and process with that pid is running
if [ -n "$SSH_AGENT_PID" ] && ps -p $SSH_AGENT_PID > /dev/null
then
# we don't need to do anything, ssh-add and git will properly connect since we've imported env variables required
echo "Connected to ssh-agent"
else
# start ssh-agent and save required vars for sharing in $SSH_AGENT_ENV file
eval $(ssh-agent) > /dev/null
echo export SSH_AUTH_SOCK=\"$SSH_AUTH_SOCK\" > $SSH_AGENT_ENV
echo export SSH_AGENT_PID=$SSH_AGENT_PID >> $SSH_AGENT_ENV
echo "Started ssh-agent"
fi
Also this script uses a little trick to ensure that provided environment variables are shared between git-bash instances by saving them into an .env
file.
in function
def handleUpload():
if 'photo' in request.files:
photo = request.files['photo']
if photo.filename != '':
image = request.files['photo']
image_string = base64.b64encode(image.read())
image_string = image_string.decode('utf-8')
#use this to remove b'...' to get raw string
return render_template('handleUpload.html',filestring = image_string)
return render_template('upload.html')
in html file
<html>
<head>
<title>Simple file upload using Python Flask</title>
</head>
<body>
{% if filestring %}
<h1>Raw image:</h1>
<h1>{{filestring}}</h1>
<img src="data:image/png;base64, {{filestring}}" alt="alternate" />.
{% else %}
<h1></h1>
{% endif %}
</body>
The first backslash in your string is being interpreted as a special character, in fact because it's followed by a "U" it's being interpreted as the start of a unicode code point.
To fix this you need to escape the backslashes in the string. I don't know Python specifically but I'd guess you do it by doubling the backslashes:
data = open("C:\\Users\\miche\\Documents\\school\\jaar2\\MIK\\2.6\\vektis_agb_zorgverlener")
Use:
:wq!
The exclamation mark is used for overriding read-only mode.
if($('jquery_selector').is(":checked")){_x000D_
//somecode_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Your second example does not work if you send the argument by reference. Did you mean
void copyVecFast(vec<int> original) // no reference
{
vector<int> new_;
new_.swap(original);
}
That would work, but an easier way is
vector<int> new_(original);
Example with mysql_fetch_assoc()
:
while ($row = mysql_fetch_assoc($result))
{
/* ... your stuff ...*/
}
In your case with foreach
, with the $result
array you get from select()
:
foreach ($result as $row)
{
/* ... your stuff ...*/
}
It's much like the same, with proper iteration.
You can use the following format to generate a tooltip for an image.
<div class="tooltip"><img src="joe.jpg" />
<span class="tooltiptext">Tooltip text</span>
</div>
Another way is to do the following in Visual Studio:
If you have the name of the remote, you will be able with git 2.7 (Q4 2015), to use the new git remote get-url
command:
git remote get-url origin
(nice pendant of git remote set-url origin <newurl>
)
See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf
).
(Merged by Junio C Hamano -- gitster
-- in commit e437cbd, 05 Oct 2015)
remote: add get-url subcommand
Expanding
insteadOf
is a part ofls-remote --url
and there is no way to expandpushInsteadOf
as well.
Add aget-url
subcommand to be able to query both as well as a way to get all configured urls.
iContribute: It's never too late for a right answer.
var form = $("form#myForm");
if($('form#myForm > :input[required]:visible').val() != ""){
form.submit();
}else{
console.log("Required field missing.");
}
This way the basic HTML5 validation for 'required' fields takes place without interfering with the standard submit using the form's 'name' values.
In addition to the aspects described in the other answers, append and +[] have very different behaviors when you're trying to build a list of lists.
>>> list1=[[1,2],[3,4]]
>>> list2=[5,6]
>>> list3=list1+list2
>>> list3
[[1, 2], [3, 4], 5, 6]
>>> list1.append(list2)
>>> list1
[[1, 2], [3, 4], [5, 6]]
list1+['5','6'] adds '5' and '6' to the list1 as individual elements. list1.append(['5','6']) adds the list ['5','6'] to the list1 as a single element.
If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test
rather than the default unittest
module.
Consider these two examples, which do the same thing:
Example 1 (unittest):
import unittest
class LearningCase(unittest.TestCase):
def test_starting_out(self):
self.assertEqual(1, 1)
def main():
unittest.main()
if __name__ == "__main__":
main()
Example 2 (pytest):
def test_starting_out():
assert 1 == 1
Assuming that both files are named test_unittesting.py
, how do we run the tests?
Example 1 (unittest):
cd /path/to/dir/
python test_unittesting.py
Example 2 (pytest):
cd /path/to/dir/
py.test
call initial methods inside self initialize function.
(function initController() {
// do your initialize here
})();
I use this solution to delete empty lines and join everything together as one line:
match_p = re.sub(r'\s{2}', '', my_txt) # my_txt is text above
Include sites-available/default
in sites-enabled/default
. It requires only one line.
In sites-enabled/default
(new config version?):
It seems that the include path is relative to the file that included it
include sites-available/default;
See the include
documentation.
I believe that certain versions of nginx allows including/linking to other files purely by having a single line with the relative path to the included file. (At least that's what it looked like in some "inherited" config files I've been using, until a new nginx version broke them.)
In sites-enabled/default
(old config version?):
It seems that the include path is relative to the current file
../sites-available/default
You need to download log4j and add in your classpath.
I use the following macro:
#define ENUM_FLAG_OPERATORS(T) \
inline T operator~ (T a) { return static_cast<T>( ~static_cast<std::underlying_type<T>::type>(a) ); } \
inline T operator| (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) | static_cast<std::underlying_type<T>::type>(b) ); } \
inline T operator& (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) & static_cast<std::underlying_type<T>::type>(b) ); } \
inline T operator^ (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) ^ static_cast<std::underlying_type<T>::type>(b) ); } \
inline T& operator|= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) |= static_cast<std::underlying_type<T>::type>(b) ); } \
inline T& operator&= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) &= static_cast<std::underlying_type<T>::type>(b) ); } \
inline T& operator^= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) ^= static_cast<std::underlying_type<T>::type>(b) ); }
It is similar to the ones mentioned above but has several improvements:
int
)It does need to include type_traits:
#include <type_traits>
The think best way to to it is using
Intent i = new Intent(this.myActivity, SecondActivity.class);
startActivityForResult(i, 1);
The Instant
class doesn't contain Zone information, it only stores timestamp in milliseconds from UNIX epoch, i.e. 1 Jan 1070 from UTC.
So, formatter can't print a date because date always printed for concrete time zone.
You should set time zone to formatter and all will be fine, like this :
Instant instant = Instant.ofEpochMilli(92554380000L);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.UK).withZone(ZoneOffset.UTC);
assert formatter.format(instant).equals("07/12/72 05:33");
assert instant.toString().equals("1972-12-07T05:33:00Z");
I would also highly recommend Adminer - http://www.adminer.org/
It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.
I made some big lists. One is a list and one is a numpy array.
import numpy as np
import random
arrayv=np.random.randint(0,10,(100000000,1))
listv=[]
for i in range(0,100000000):
listv.append(random.randint(0,9))
Using jupyter notebook's %%time function I can compare the speed of various things.
2 seconds:
%%time
listv.index(max(listv))
54.6 seconds:
%%time
listv.index(max(arrayv))
6.71 seconds:
%%time
np.argmax(listv)
103 ms:
%%time
np.argmax(arrayv)
numpy's arrays are crazy fast.
I'm using this Automator Shell Script to fix it after. It's showing up as contextual menu item (right clicking on any file showing up in Finder).
while read -r p; do
zip -d "$p" __MACOSX/\* || true
zip -d "$p" \*/.DS_Store || true
done
You should try
if (row.Table.Columns.Contains("US_OTHERFRIEND"))
I don't believe that row has a columns property itself.
Use PHP_EOL
which produces \r\n
or \n
$data = 'my data' . PHP_EOL . 'my data';
$fp = fopen('my_file', 'a');
fwrite($fp, $data);
fclose($fp);
// File output
my data
my data
I think you're getting confused about what can hold what in JSON.Net.
JToken
is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.JProperty
is a single JToken
value paired with a name. It can only be added to a JObject
, and its value cannot be another JProperty
.JObject
is a collection of JProperties
. It cannot hold any other kind of JToken
directly.In your code, you are attempting to add a JObject
(the one containing the "banana" data) to a JProperty
("orange") which already has a value (a JObject
containing {"colour":"orange","size":"large"}
). As you saw, this will result in an error.
What you really want to do is add a JProperty
called "banana" to the JObject
which contains the other fruit JProperties
. Here is the revised code:
JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));
The best way to accomplish this is to use the \r
character
Just try the below code:
import time
for n in range(500):
print(n, end='\r')
time.sleep(0.01)
print() # start new line so most recently printed number stays
An alternative approach if interested - with an extra intermediate class to use the normal OOO way. This simplifies the usage with parent::methodname
trait A {
function calc($v) {
return $v+1;
}
}
// an intermediate class that just uses the trait
class IntClass {
use A;
}
// an extended class from IntClass
class MyClass extends IntClass {
function calc($v) {
$v++;
return parent::calc($v);
}
}
Something along the lines of this?
<asp:TextBox id="txtUsername" runat="server" />
<asp:RegularExpressionValidator
id="RegularExpressionValidator1"
runat="server"
ErrorMessage="Field not valid!"
ControlToValidate="txtUsername"
ValidationExpression="[0-9a-zA-Z]{6,}" />
Why don't you check if text.trim() has a different length? :
if(text.length() == text.trim().length() || otherConditions){
//your code
}
You were right regarding how you want to generate salt i.e. its nothing but a random number. For this particular case it would protect your system from possible Dictionary attacks. Now, for the second problem what you could do is instead of using UTF-8 encoding you may want to use Base64. Here, is a sample for generating a hash. I am using Apache Common Codecs for doing the base64 encoding you may select one of your own
public byte[] generateSalt() {
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);
return bytes;
}
public String bytetoString(byte[] input) {
return org.apache.commons.codec.binary.Base64.encodeBase64String(input);
}
public byte[] getHashWithSalt(String input, HashingTechqniue technique, byte[] salt) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance(technique.value);
digest.reset();
digest.update(salt);
byte[] hashedBytes = digest.digest(stringToByte(input));
return hashedBytes;
}
public byte[] stringToByte(String input) {
if (Base64.isBase64(input)) {
return Base64.decodeBase64(input);
} else {
return Base64.encodeBase64(input.getBytes());
}
}
Here is some additional reference of the standard practice in password hashing directly from OWASP
It's simple to convert the Unix timestamp into the desired format. Lets suppose _ts is the Unix timestamp in long
let date = NSDate(timeIntervalSince1970: _ts)
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
let dateString = dayTimePeriodFormatter.stringFromDate(date)
print( " _ts value is \(_ts)")
print( " _ts value is \(dateString)")
Try Math.log(x) / Math.log(2)
Here is a variation of the previous examples. It takes care to filter out VMware interfaces, etc. If you don't pass an index it returns all addresses. Otherwise, you may want to set it default to 0 and then just pass null to get all, but you'll sort that out. You could also pass in another argument for the regex filter if so inclined to add.
function getAddress(idx) {
var addresses = [],
interfaces = os.networkInterfaces(),
name, ifaces, iface;
for (name in interfaces) {
if(interfaces.hasOwnProperty(name)){
ifaces = interfaces[name];
if(!/(loopback|vmware|internal)/gi.test(name)){
for (var i = 0; i < ifaces.length; i++) {
iface = ifaces[i];
if (iface.family === 'IPv4' && !iface.internal && iface.address !== '127.0.0.1') {
addresses.push(iface.address);
}
}
}
}
}
// If an index is passed only return it.
if(idx >= 0)
return addresses[idx];
return addresses;
}
public String substring(int beginIndex, int endIndex)
beginIndex
—the begin index, inclusive.
endIndex
—the end index, exclusive.
Example:
public class Test {
public static void main(String args[]) {
String Str = new String("Hello World");
System.out.println(Str.substring(3, 8));
}
}
Output: "lo Wo"
From 3 to 7 index.
Also there is another kind of substring()
method:
public String substring(int beginIndex)
beginIndex
—the begin index, inclusive.
Returns a sub string starting from beginIndex
to the end of the main String.
Example:
public class Test {
public static void main(String args[]) {
String Str = new String("Hello World");
System.out.println(Str.substring(3));
}
}
Output: "lo World"
From 3 to the last index.
At least in Python3 you also can do this:
import os, re, glob
path = '/home/my/path'
files = glob.glob(os.path.join(path, '*.png'))
files.sort(key=lambda x:[int(c) if c.isdigit() else c for c in re.split(r'(\d+)', x)])
for infile in files:
print(infile)
This should lexicographically order your input array of strings (e.g. respect numbers in strings while ordering).
You can also use the not operator. It will check if a variable is null, or, in the case of a string, is empty. It makes your code more compact and easier to read.
For example:
var pass = "";
if(!pass)
return false;
else
return true;
This would return false because the string is empty. It would also return false if the variable pass was null.
init
will be called everywhere uses its package(no matter blank import or import), but only one time.
this is a package:
package demo
import (
"some/logs"
)
var count int
func init() {
logs.Debug(count)
}
// Do do
func Do() {
logs.Debug("dd")
}
any package(main package or any test package) import it as blank :
_ "printfcoder.com/we/models/demo"
or import it using it func:
"printfcoder.com/we/models/demo"
func someFunc(){
demo.Do()
}
the init will log 0
only one time.
the first package using it, its init func will run before the package's init. So:
A calls B, B calls C, all of them have init func, the C's init will be run first before B's, B's before A's.
Follow these steps to run your application on the device connected.
1. Change directories to the root of your Android project and execute:
ant debug
2. Make sure the Android SDK platform-tools/
directory is included in your PATH
environment variable, then execute: adb install bin/<*your app name*>-debug.apk
On your device, locate <*your app name*>
and open it.
Refer Running App
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
When transmitting data or storing them in a file, the data are required to be byte strings, but complex objects are seldom in this format. Serialization can convert these complex objects into byte strings for such use. After the byte strings are transmitted, the receiver will have to recover the original object from the byte string. This is known as deserialization.
Say, you have an object:
{foo: [1, 4, 7, 10], bar: "baz"}
serializing into JSON will convert it into a string:
'{"foo":[1,4,7,10],"bar":"baz"}'
which can be stored or sent through wire to anywhere. The receiver can then deserialize this string to get back the original object. {foo: [1, 4, 7, 10], bar: "baz"}
.
I had the same issue. Turned out I used some external jars (apache poi 4.1.2) which were compiled with 1.8. Solved it by changing Java Build Path JRE to 1.8.
I was having the same issue today. And tried all the above solutions already given but nothing worked for me. Then I spent sometime and I found out the reason. I thought it could save some other developers time I am sharing here as well. The problem was with wrong package name. I was using MVP architecture, and I kept my activities in view package. And I copied the Main class from my other project. This was the catch. In the xml, Main Activity was referring to different Package that was just outer side. The package was not including my view directory (MVP hierarchy level). Then I checked back in manifest as well. The same problem I found there as well. So I provided full path(package name) of my activity(untill MVP' view directory/package there I kept my all activities). This solved my problem. Hope that helps others as well.
This is Web GUI of a GitHub repository:
Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:
Yowza, that’s a lot of files. Try again with fewer than 100 files.
and add commit message
And press button Commit changes is the last step.
Right-click an object in Chrome's console and select Store as Global Variable
from the context menu. It will return something like temp1
as the variable name.
Chrome also has a copy()
method, so copy(temp1)
in the console should copy that object to your clipboard.
Note on Recursive Objects: If you're trying to copy a recursive object, you will get [object Object]
. The way out is to copy(JSON.stringify(temp1))
, the object will be fully copied to your clipboard as a valid JSON, so you'd be able to format it as you wish, using one of many resources.
Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:
ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);
Use a backslash as such
"From time to \"time\"";
Backslashes are used in PHP to escape special characters within quotes. As PHP does not distinguish between strings and characters, you could also use this
'From time to "time"';
The difference between single and double quotes is that double quotes allows for string interpolation, meaning that you can reference variables inline in the string and their values will be evaluated in the string like such
$name = 'Chris';
$greeting = "Hello my name is $name"; //equals "Hello my name is Chris"
As per your last edit of your question I think the easiest thing you may be able to do that this point is to use a 'heredoc.' They aren't commonly used and honestly I wouldn't normally recommend it but if you want a fast way to get this wall of text in to a single string. The syntax can be found here: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc and here is an example:
$someVar = "hello";
$someOtherVar = "goodbye";
$heredoc = <<<term
This is a long line of text that include variables such as $someVar
and additionally some other variable $someOtherVar. It also supports having
'single quotes' and "double quotes" without terminating the string itself.
heredocs have additional functionality that most likely falls outside
the scope of what you aim to accomplish.
term;
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
Use the below css to solve your issue
#footer{ text-align:center; height:58px;}
#footer ul { font-size:11px;}
#footer ul li {display:inline-block;}
Note: Don't use float:left
in li. it will make your li to align left.
is
and ==
?==
and is
are different comparison! As others already said:
==
compares the values of the objects.is
compares the references of the objects.In Python names refer to objects, for example in this case value1
and value2
refer to an int
instance storing the value 1000
:
value1 = 1000
value2 = value1
Because value2
refers to the same object is
and ==
will give True
:
>>> value1 == value2
True
>>> value1 is value2
True
In the following example the names value1
and value2
refer to different int
instances, even if both store the same integer:
>>> value1 = 1000
>>> value2 = 1000
Because the same value (integer) is stored ==
will be True
, that's why it's often called "value comparison". However is
will return False
because these are different objects:
>>> value1 == value2
True
>>> value1 is value2
False
Generally is
is a much faster comparison. That's why CPython caches (or maybe reuses would be the better term) certain objects like small integers, some strings, etc. But this should be treated as implementation detail that could (even if unlikely) change at any point without warning.
You should only use is
if you:
want to check if two objects are really the same object (not just the same "value"). One example can be if you use a singleton object as constant.
want to compare a value to a Python constant. The constants in Python are:
None
True
1False
1NotImplemented
Ellipsis
__debug__
int is int
or int is float
)np.ma.masked
from the NumPy module)In every other case you should use ==
to check for equality.
There is some aspect to ==
that hasn't been mentioned already in the other answers: It's part of Pythons "Data model". That means its behavior can be customized using the __eq__
method. For example:
class MyClass(object):
def __init__(self, val):
self._value = val
def __eq__(self, other):
print('__eq__ method called')
try:
return self._value == other._value
except AttributeError:
raise TypeError('Cannot compare {0} to objects of type {1}'
.format(type(self), type(other)))
This is just an artificial example to illustrate that the method is really called:
>>> MyClass(10) == MyClass(10)
__eq__ method called
True
Note that by default (if no other implementation of __eq__
can be found in the class or the superclasses) __eq__
uses is
:
class AClass(object):
def __init__(self, value):
self._value = value
>>> a = AClass(10)
>>> b = AClass(10)
>>> a == b
False
>>> a == a
So it's actually important to implement __eq__
if you want "more" than just reference-comparison for custom classes!
On the other hand you cannot customize is
checks. It will always compare just if you have the same reference.
Because __eq__
can be re-implemented or overridden, it's not limited to return True
or False
. It could return anything (but in most cases it should return a boolean!).
For example with NumPy arrays the ==
will return an array:
>>> import numpy as np
>>> np.arange(10) == 2
array([False, False, True, False, False, False, False, False, False, False], dtype=bool)
But is
checks will always return True
or False
!
1 As Aaron Hall mentioned in the comments:
Generally you shouldn't do any is True
or is False
checks because one normally uses these "checks" in a context that implicitly converts the condition to a boolean (for example in an if
statement). So doing the is True
comparison and the implicit boolean cast is doing more work than just doing the boolean cast - and you limit yourself to booleans (which isn't considered pythonic).
Like PEP8 mentions:
Don't compare boolean values to
True
orFalse
using==
.Yes: if greeting: No: if greeting == True: Worse: if greeting is True:
No, it is not possible. You can use a custom javascript alert box.
Found a nice one using jQuery
jQuery Alert Dialogs (Alert, Confirm, & Prompt Replacements)
The same way you declare any other variable, just use the bit
type:
DECLARE @MyVar bit
Set @MyVar = 1 /* True */
Set @MyVar = 0 /* False */
SELECT * FROM [MyTable] WHERE MyBitColumn = @MyVar
Request.GetOwinContext().Authentication.User.Claims
However it is better to add the claims inside the "GenerateUserIdentityAsync" method, especially if regenerateIdentity in the Startup.Auth.cs is enabled.
Not that I know of, in pure C++. But a little modification of what you mentioned
string s = string(itoa(a));
should work, and it's pretty short.
for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){
double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT;
}
if you want to get around the + 1 issue
I needed to set the maximum size of my window application. This one could changed accordingly the application is is been showed in the primary screen or in the secondary. To overcome this problem e created a simple method that i show you next:
/// <summary>
/// Set the max size of the application window taking into account the current monitor
/// </summary>
public static void SetMaxSizeWindow(ioConnect _receiver)
{
Point absoluteScreenPos = _receiver.PointToScreen(Mouse.GetPosition(_receiver));
if (System.Windows.SystemParameters.VirtualScreenLeft == System.Windows.SystemParameters.WorkArea.Left)
{
//Primary Monitor is on the Left
if (absoluteScreenPos.X <= System.Windows.SystemParameters.PrimaryScreenWidth)
{
//Primary monitor
_receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;
_receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;
}
else
{
//Secondary monitor
_receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;
_receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;
}
}
if (System.Windows.SystemParameters.VirtualScreenLeft < 0)
{
//Primary Monitor is on the Right
if (absoluteScreenPos.X > 0)
{
//Primary monitor
_receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;
_receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;
}
else
{
//Secondary monitor
_receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;
_receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;
}
}
}
The simple answer is you should write code for rvalue references like you would regular references code, and you should treat them the same mentally 99% of the time. This includes all the old rules about returning references (i.e. never return a reference to a local variable).
Unless you are writing a template container class that needs to take advantage of std::forward and be able to write a generic function that takes either lvalue or rvalue references, this is more or less true.
One of the big advantages to the move constructor and move assignment is that if you define them, the compiler can use them in cases were the RVO (return value optimization) and NRVO (named return value optimization) fail to be invoked. This is pretty huge for returning expensive objects like containers & strings by value efficiently from methods.
Now where things get interesting with rvalue references, is that you can also use them as arguments to normal functions. This allows you to write containers that have overloads for both const reference (const foo& other) and rvalue reference (foo&& other). Even if the argument is too unwieldy to pass with a mere constructor call it can still be done:
std::vector vec;
for(int x=0; x<10; ++x)
{
// automatically uses rvalue reference constructor if available
// because MyCheapType is an unamed temporary variable
vec.push_back(MyCheapType(0.f));
}
std::vector vec;
for(int x=0; x<10; ++x)
{
MyExpensiveType temp(1.0, 3.0);
temp.initSomeOtherFields(malloc(5000));
// old way, passed via const reference, expensive copy
vec.push_back(temp);
// new way, passed via rvalue reference, cheap move
// just don't use temp again, not difficult in a loop like this though . . .
vec.push_back(std::move(temp));
}
The STL containers have been updated to have move overloads for nearly anything (hash key and values, vector insertion, etc), and is where you will see them the most.
You can also use them to normal functions, and if you only provide an rvalue reference argument you can force the caller to create the object and let the function do the move. This is more of an example than a really good use, but in my rendering library, I have assigned a string to all the loaded resources, so that it is easier to see what each object represents in the debugger. The interface is something like this:
TextureHandle CreateTexture(int width, int height, ETextureFormat fmt, string&& friendlyName)
{
std::unique_ptr<TextureObject> tex = D3DCreateTexture(width, height, fmt);
tex->friendlyName = std::move(friendlyName);
return tex;
}
It is a form of a 'leaky abstraction' but allows me to take advantage of the fact I had to create the string already most of the time, and avoid making yet another copying of it. This isn't exactly high-performance code but is a good example of the possibilities as people get the hang of this feature. This code actually requires that the variable either be a temporary to the call, or std::move invoked:
// move from temporary
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, string("Checkerboard"));
or
// explicit move (not going to use the variable 'str' after the create call)
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, std::move(str));
or
// explicitly make a copy and pass the temporary of the copy down
// since we need to use str again for some reason
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, string(str));
but this won't compile!
string str("Checkerboard");
TextureHandle htex = CreateTexture(128, 128, A8R8G8B8, str);
You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.*
function are thin wrappers that basically do gca().*
.
plt.subplot
returns an axes
object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.
import matplotlib.pyplot as plt
ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])
ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])
and so on for as many axes as you want.
or better, wrap it all up in a loop:
import matplotlib.pyplot as plt
DATA_x = ([1, 2],
[2, 3],
[3, 4])
DATA_y = DATA_x[::-1]
XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3
for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
ax = plt.subplot(1, 3, j + 1)
ax.scatter(x, y)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
You cannot style a variable such as $ip['countryName']
You can only style elements like p,div, etc, or classes and ids.
If you want to style $ip['countryName'] there are several ways.
You can echo it within an element:
echo '<p id="style">'.$ip['countryName'].'</p>';
echo '<span id="style">'.$ip['countryName'].'</span>';
echo '<div id="style">'.$ip['countryName'].'</div>';
If you want to style both the variables the same style, then set a class like:
echo '<p class="style">'.$ip['cityName'].'</p>';
echo '<p class="style">'.$ip['countryName'].'</p>';
You could also embed the variables within your actual html rather than echoing them out within the code.
$city = $ip['cityName'];
$country = $ip['countryName'];
?>
<div class="style"><?php echo $city ?></div>
<div class="style"><?php echo $country?></div>
var link=document.createElement('a');
document.body.appendChild(link);
link.href=url;
link.click();
I managed to do a portable, non-polling solution with 3 processes by abusing terminal control and sessions.
The trick is:
That way:
Shortcomings:
This is the code I developed to read all csv files into R. It will create a dataframe for each csv file individually and title that dataframe the file's original name (removing spaces and the .csv) I hope you find it useful!
path <- "C:/Users/cfees/My Box Files/Fitness/"
files <- list.files(path=path, pattern="*.csv")
for(file in files)
{
perpos <- which(strsplit(file, "")[[1]]==".")
assign(
gsub(" ","",substr(file, 1, perpos-1)),
read.csv(paste(path,file,sep="")))
}
To start only stopped containers:
docker start $(docker ps -a -q -f status=exited)
(On windows it works in Powershell).
First try to downgrade your angular version using "ng add @angular/material7.3..0" after that check if the error is gone in my case it is gone after that use this ng update @angular/material in case you are using angular 9 or 10 you have to write code like this import {MatInputModule} from 'angular/material/input' Hope it will work for you
You are trying to run bash
, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d
, but you can do this by adding -it
to the command line, which ensures that the container has a valid tty associated with it and that stdin
remains connected:
docker run -it -d -p 52022:22 basickarl/docker-git-test
You would more commonly run some sort of long-lived non-interactive process (like sshd
, or a web server, or a database server, or a process manager like systemd
or supervisor
) when starting detached containers.
If you are trying to run a service like sshd
, you cannot simply run service ssh start
. This will -- depending on the distribution you're running inside your container -- do one of two things:
It will try to contact a process manager like systemd
or upstart
to start the service. Because there is no service manager running, this will fail.
It will actually start sshd
, but it will be started in the background. This means that (a) the service sshd start
command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.
If you want to run just ssh in a container, consider an example like this.
If you want to run sshd
and other processes inside the container, you will need to investigate some sort of process supervisor.
UTF-8 is prepared for world domination, Latin1 isn't.
If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).
Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4
.
ansible-playbook release.yml -e "version=1.23.45 other_variable=foo"
This could be caused by the presence of ~/.gitconfig.lock It's possible this file could be an artifact of a previously running git that was aborted for some reason, e.g. ansible timed out or ^C
Take a look at Google Play Location Samples
Location Updates using a Foreground Service: Get updates about a device's location using a bound and started foreground service.
Location Updates using a PendingIntent: Get updates about a device's location using a PendingIntent
. Sample shows implementation using an IntentService
as well as a BroadcastReceiver
.
You're looking for TRIM.
UPDATE FOO set FIELD2 = TRIM(FIELD2);
Seems like it might be worth it to mention that TRIM can support multiple types of whitespace, but only one at a time and it will use a space by default. You can, however, nest TRIM
s.
TRIM(BOTH ' ' FROM TRIM(BOTH '\n' FROM column))
If you really want to get rid of all the whitespace in one call, you're better off using REGEXP_REPLACE
along with the [[:space:]]
notation. Here is an example:
SELECT
-- using concat to show that the whitespace is actually removed.
CONCAT(
'+',
REGEXP_REPLACE(
' ha ppy ',
-- This regexp matches 1 or more spaces at the beginning with ^[[:space:]]+
-- And 1 or more spaces at the end with [[:space:]]+$
-- By grouping them with `()` and splitting them with the `|`
-- we match all of the expected values.
'(^[[:space:]]+|[[:space:]]+$)',
-- Replace the above with nothing
''
),
'+')
as my_example;
-- outputs +ha ppy+
step1: show create table vendor_locations;
step2: ALTER TABLE vendor_locations drop foreign key vendor_locations_ibfk_1;
it worked for me.