Why didn't anyone mentioned the method LocalDateTime.toEpochSecond()
:
LocalDateTime localDateTime = ... // whatever e.g. LocalDateTime.now()
long time2epoch = localDateTime.toEpochSecond(ZoneOffset.UTC);
This seems way shorter that many suggested answers above...
Update On 18-Dec-2017
You can update Google Play Services via the Play Store app in your emulator just as you would on a physical Android device from API 24.
check Emulator new features added with stable update from Android Studio v 3.0
Google Play Support - From Google : We know that many app developers use Google Play Services, and it can be difficult to keep the service up to date in the Android Emulator system images. To solve this problem, we now offer versions of Android System Images that include the Play Store app. The Google Play images are available starting with Android Nougat (API 24). With these new emulator images, you can update Google Play Services via the Play Store app in your emulator just as you would on a physical Android device. Plus, you can now test end-to-end install, update, and purchase flows with the Google Play Store.
Quick Boot - Quick Boot allows you to resume your Android Emulator session in under 6 seconds
Android CTS Compatibility
Performance Improvements - With the latest versions of the Android Emulator, we now allocate RAM on demand, instead of allocating and pinning the memory to the max RAM size defined in your AVD.
Virtual sensors
Wi-Fi support
GPS location and Many more...
OR
Update this SDK Build-Tools and Android Emulator to latest and this alert message will not come again,
Settings --> Android SDK --> SDK Tools(tab) --> Android SDK Build-Tools
@echo off
Set filename=C:\Documents and Settings\All Users\Desktop\Dostips.cmd
For %%A in ("%filename%") do (
Set Folder=%%~dpA
Set Name=%%~nxA
)
echo.Folder is: %Folder%
echo.Name is: %Name%
But I can't take credit for this; Google found this at http://www.dostips.com/forum/viewtopic.php?f=3&t=409
From the man read:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
Input parameters:
int fd
file descriptor is an integer and not a file pointer. The file descriptor for stdin
is 0
void *buf
pointer to buffer to store characters read by the read
function
size_t count
maximum number of characters to read
So you can read character by character with the following code:
char buf[1];
while(read(0, buf, sizeof(buf))>0) {
// read() here read from stdin charachter by character
// the buf[0] contains the character got by read()
....
}
DateTime.Now
returns a DateTime
value that consists of the local date and time of the computer where the code is running. It has DateTimeKind.Local
assigned to its Kind
property. It is equivalent to calling any of the following:
DateTime.UtcNow.ToLocalTime()
DateTimeOffset.UtcNow.LocalDateTime
DateTimeOffset.Now.LocalDateTime
TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Local)
TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Local)
DateTime.Today
returns a DateTime
value that has the same year, month, and day components as any of the above expressions, but with the time components set to zero. It also has DateTimeKind.Local
in its Kind
property. It is equivalent to any of the following:
DateTime.Now.Date
DateTime.UtcNow.ToLocalTime().Date
DateTimeOffset.UtcNow.LocalDateTime.Date
DateTimeOffset.Now.LocalDateTime.Date
TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Local).Date
TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Local).Date
Note that internally, the system clock is in terms of UTC, so when you call DateTime.Now
it first gets the UTC time (via the GetSystemTimeAsFileTime
function in the Win32 API) and then it converts the value to the local time zone. (Therefore DateTime.Now.ToUniversalTime()
is more expensive than DateTime.UtcNow
.)
Also note that DateTimeOffset.Now.DateTime
will have similar values to DateTime.Now
, but it will have DateTimeKind.Unspecified
rather than DateTimeKind.Local
- which could lead to other errors depending on what you do with it.
So, the simple answer is that DateTime.Today
is equivalent to DateTime.Now.Date
.
But IMHO - You shouldn't use either one of these, or any of the above equivalents.
When you ask for DateTime.Now
, you are asking for the value of the local calendar clock of the computer that the code is running on. But what you get back does not have any information about that clock! The best that you get is that DateTime.Now.Kind == DateTimeKind.Local
. But whose local is it? That information gets lost as soon as you do anything with the value, such as store it in a database, display it on screen, or transmit it using a web service.
If your local time zone follows any daylight savings rules, you do not get that information back from DateTime.Now
. In ambiguous times, such as during a "fall-back" transition, you won't know which of the two possible moments correspond to the value you retrieved with DateTime.Now
. For example, say your system time zone is set to Mountain Time (US & Canada)
and you ask for DateTime.Now
in the early hours of November 3rd, 2013. What does the result 2013-11-03 01:00:00
mean? There are two moments of instantaneous time represented by this same calendar datetime. If I were to send this value to someone else, they would have no idea which one I meant. Especially if they are in a time zone where the rules are different.
The best thing you could do would be to use DateTimeOffset
instead:
// This will always be unambiguous.
DateTimeOffset now = DateTimeOffset.Now;
Now for the same scenario I described above, I get the value 2013-11-03 01:00:00 -0600
before the transition, or 2013-11-03 01:00:00 -0700
after the transition. Anyone looking at these values can tell what I meant.
I wrote a blog post on this very subject. Please read - The Case Against DateTime.Now.
Also, there are some places in this world (such as Brazil) where the "spring-forward" transition happens exactly at Midnight. The clocks go from 23:59 to 01:00. This means that the value you get for DateTime.Today
on that date, does not exist! Even if you use DateTimeOffset.Now.Date
, you are getting the same result, and you still have this problem. It is because traditionally, there has been no such thing as a Date
object in .Net. So regardless of how you obtain the value, once you strip off the time - you have to remember that it doesn't really represent "midnight", even though that's the value you're working with.
If you really want a fully correct solution to this problem, the best approach is to use NodaTime. The LocalDate
class properly represents a date without a time. You can get the current date for any time zone, including the local system time zone:
using NodaTime;
...
Instant now = SystemClock.Instance.Now;
DateTimeZone zone1 = DateTimeZoneProviders.Tzdb.GetSystemDefault();
LocalDate todayInTheSystemZone = now.InZone(zone1).Date;
DateTimeZone zone2 = DateTimeZoneProviders.Tzdb["America/New_York"];
LocalDate todayInTheOtherZone = now.InZone(zone2).Date;
If you don't want to use Noda Time, there is now another option. I've contributed an implementation of a date-only object to the .Net CoreFX Lab project. You can find the System.Time
package object in their MyGet feed. Once added to your project, you will find you can do any of the following:
using System;
...
Date localDate = Date.Today;
Date utcDate = Date.UtcToday;
Date tzSpecificDate = Date.TodayInTimeZone(anyTimeZoneInfoObject);
Since java 8 there is easy way to do it with Lambda:
yourMap.keySet().forEach(key -> {
Object obj = yourMap.get(key);
System.out.println( obj);
}
Here is the step by step process to include php code in html file ( Tested )
If PHP is working there is only one step left to use PHP scripts in files with *.html or *.htm extensions as well. The magic word is ".htaccess". Please see the Wikipedia definition of .htaccess to learn more about it. According to Wikipedia it is "a directory-level configuration file that allows for decentralized management of web server configuration."
You can probably use such a .htaccess configuration file for your purpose. In our case you want the webserver to parse HTML files like PHP files.
First, create a blank text file and name it ".htaccess". You might ask yourself why the file name starts with a dot. On Unix-like systems this means it is a dot-file is a hidden file. (Note: If your operating system does not allow file names starting with a dot just name the file "xyz.htaccess" temporarily. As soon as you have uploaded it to your webserver in a later step you can rename the file online to ".htaccess") Next, open the file with a simple text editor like the "Editor" in MS Windows. Paste the following line into the file: AddType application/x-httpd-php .html .htm If this does not work, please remove the line above from your file and paste this alternative line into it, for PHP5: AddType application/x-httpd-php5 .html .htm Now upload the .htaccess file to the root directory of your webserver. Make sure that the name of the file is ".htaccess". Your webserver should now parse *.htm and *.html files like PHP files.
You can try if it works by creating a HTML-File like the following. Name it "php-in-html-test.htm", paste the following code into it and upload it to the root directory of your webserver:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Use PHP in HTML files</TITLE>
</HEAD>
<BODY>
<h1>
<?php echo "It works!"; ?>
</h1>
</BODY>
</HTML>
Try to open the file in your browser by typing in: http://www.your-domain.com/php-in-html-test.htm (once again, please replace your-domain.com by your own domain...) If your browser shows the phrase "It works!" everything works fine and you can use PHP in .*html and *.htm files from now on. However, if not, please try to use the alternative line in the .htaccess file as we showed above. If is still does not work please contact your hosting provider.
There are various ways of changing the status bar color.
1) Using the styles.xml. You can use the android:statusBarColor attribute to do this the easy but static way.
Note: You can also use this attribute with the Material theme.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="AppTheme.Base">
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
</resources>
2) You can get it done dynamically using the setStatusBarColor(int) method in the Window class. But remember that this method is only available for API 21 or higher. So be sure to check that, or your app will surely crash in lower devices.
Here is a working example of this method.
if (Build.VERSION.SDK_INT >= 21) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.primaryDark));
}
where primaryDark is the 700 tint of the primary color I am using in my app. You can define this color in the colors.xml file.
Do give it a try and let me know if you have any questions. Hope it helps.
When you change the name of your Cookies, you may also want to delete all Cookies but preserve one:
if (isset($_COOKIE)) {
foreach($_COOKIE as $name => $value) {
if ($name != "preservecookie") // Name of the cookie you want to preserve
{
setcookie($name, '', 1); // Better use 1 to avoid time problems, like timezones
setcookie($name, '', 1, '/');
}
}
}
Also based on this PHP-Answer
To print the name of the fields in a struct:
fmt.Printf("%+v\n", yourProject)
From the fmt
package:
when printing structs, the plus flag (
%+v
) adds field names
That supposes you have an instance of Project (in 'yourProject
')
The article JSON and Go will give more details on how to retrieve the values from a JSON struct.
This Go by example page provides another technique:
type Response2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
res2D := &Response2{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))
That would print:
{"page":1,"fruits":["apple","peach","pear"]}
If you don't have any instance, then you need to use reflection to display the name of the field of a given struct, as in this example.
type T struct {
A int
B string
}
t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Printf("%d: %s %s = %v\n", i,
typeOfT.Field(i).Name, f.Type(), f.Interface())
}
pg_get_serial_sequence
can be used to avoid any incorrect assumptions about the sequence name. This resets the sequence in one shot:
SELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), (SELECT MAX(id) FROM table_name)+1);
Or more concisely:
SELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;
However this form can't handle empty tables correctly, since max(id) is null, and neither can you setval 0 because it would be out of range of the sequence. One workaround for this is to resort to the ALTER SEQUENCE
syntax i.e.
ALTER SEQUENCE table_name_id_seq RESTART WITH 1;
ALTER SEQUENCE table_name_id_seq RESTART; -- 8.4 or higher
But ALTER SEQUENCE
is of limited use because the sequence name and restart value cannot be expressions.
It seems the best all-purpose solution is to call setval
with false as the 3rd parameter, allowing us to specify the "next value to use":
SELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1;
This ticks all my boxes:
Finally, note that pg_get_serial_sequence
only works if the sequence is owned by the column. This will be the case if the incrementing column was defined as a serial
type, however if the sequence was added manually it is necessary to ensure ALTER SEQUENCE .. OWNED BY
is also performed.
i.e. if serial
type was used for table creation, this should all work:
CREATE TABLE t1 (
id serial,
name varchar(20)
);
SELECT pg_get_serial_sequence('t1', 'id'); -- returns 't1_id_seq'
-- reset the sequence, regardless whether table has rows or not:
SELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1;
But if sequences were added manually:
CREATE TABLE t2 (
id integer NOT NULL,
name varchar(20)
);
CREATE SEQUENCE t2_custom_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE t2 ALTER COLUMN id SET DEFAULT nextval('t2_custom_id_seq'::regclass);
ALTER SEQUENCE t2_custom_id_seq OWNED BY t2.id; -- required for pg_get_serial_sequence
SELECT pg_get_serial_sequence('t2', 'id'); -- returns 't2_custom_id_seq'
-- reset the sequence, regardless whether table has rows or not:
SELECT setval(pg_get_serial_sequence('t2', 'id'), coalesce(max(id),0) + 1, false) FROM t1;
Your Box
class is attempting to define multiple constructor implementations.
Only the last constructor overload signature is used as the class constructor implementation.
In the below example, note the constructor implementation is defined such that it does not contradict either of the preceding overload signatures.
interface IBox = {
x: number;
y: number;
width: number;
height: number;
}
class Box {
public x: number;
public y: number;
public width: number;
public height: number;
constructor() /* Overload Signature */
constructor(obj: IBox) /* Overload Signature */
constructor(obj?: IBox) /* Implementation Constructor */ {
if (obj) {
this.x = obj.x;
this.y = obj.y;
this.width = obj.width;
this.height = obj.height;
} else {
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0
}
}
get frame(): string {
console.log(this.x, this.y, this.width, this.height);
}
}
new Box().frame; // 0 0 0 0
new Box({ x:10, y:10, width: 70, height: 120 }).frame; // 10 10 70 120
// You could also write the Box class like so;
class Box {
public x: number = 0;
public y: number = 0;
public width: number = 0;
public height: number = 0;
constructor() /* Overload Signature */
constructor(obj: IBox) /* Overload Signature */
constructor(obj?: IBox) /* Implementation Constructor */ {
if (obj) {
this.x = obj.x;
this.y = obj.y;
this.width = obj.width;
this.height = obj.height;
}
}
get frame(): string { ... }
}
You just need to use single quotes:
$ echo "$TEST"
test
$ echo '$TEST'
$TEST
Inside single quotes special characters are not special any more, they are just normal characters.
You may see the same schematic explanations for both, but these are totally confusing.
For UNION:
For JOIN:
I had this, and it was the create syntax, changed to --create-options and life was better
mysqldump -u [user] -p -create-options [DBNAME] >[DumpFile].sql
And that restored nicely.
jQuery's data()
method will give you access to data-*
attributes, BUT, it clobbers the case of the attribute name. You can either use this:
$('#myButton').data("x10") // note the lower case
Or, you can use the attr()
method, which preserves your case:
$('#myButton').attr("data-X10")
Try both methods here: http://jsfiddle.net/q5rbL/
Be aware that these approaches are not completely equivalent. If you will change the data-*
attribute of an element, you should use attr()
. data()
will read the value once initially, then continue to return a cached copy, whereas attr()
will re-read the attribute each time.
Note that jQuery will also convert hyphens in the attribute name to camel case (source -- i.e. data-some-data == $(ele).data('someData')
). Both of these conversions are in conformance with the HTML specification, which dictates that custom data attributes should contain no uppercase letters, and that hyphens will be camel-cased in the dataset
property (source). jQuery's data
method is merely mimicking/conforming to this standard behavior.
Documentation
data
- http://api.jquery.com/data/attr
- http://api.jquery.com/attr/Apache's commons.collections library has a CollectionUtils class that provides easy-to-use methods for Collection manipulation/checking, such as intersection, difference, and union.
The org.apache.commons.collections.CollectionUtils API docs are here.
If python -m pip install --upgrade pip==9.0.3
doesn't work, and you're using Windows,
Close your IDE if you have it open.
Press 'Repair' on Python 3.
Go to your Microsoft SDKs directory. A path like this:
C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools
Open the WCF Configuration Editor (Microsoft Service Configuration Editor) from that directory:
SvcConfigEditor.exe
(another option to open this tool is by navigating in Visual Studio 2017 to "Tools" > "WCF Service Configuration Editor")
Open your .config file or create a new one using the editor and navigate to Diagnostics.
There you can click the "Enable MessageLogging".
More info: https://msdn.microsoft.com/en-us/library/ms732009(v=vs.110).aspx
With the trace viewer from the same directory you can open the trace log files:
SvcTraceViewer.exe
You can also enable tracing using WMI. More info: https://msdn.microsoft.com/en-us/library/ms730064(v=vs.110).aspx
This should fix it...
Scanner in=new Scanner(System.in);
int rounds = 0;
while (rounds < 1 || rounds > 3) {
System.out.print("How many rounds? ");
if (in.hasNextInt()) {
rounds = in.nextInt();
} else {
System.out.println("Invalid input. Please try again.");
in.next(); // -->important
System.out.println();
}
// Clear buffer
}
System.out.print(rounds+" rounds.");
setTimeout
is not an async
function, so you can't use it with ES7 async-await. But you could implement your sleep
function using ES6 Promise:
function sleep (fn, par) {
return new Promise((resolve) => {
// wait 3s before calling fn(par)
setTimeout(() => resolve(fn(par)), 3000)
})
}
Then you'll be able to use this new sleep
function with ES7 async-await:
var fileList = await sleep(listFiles, nextPageToken)
Please, note that I'm only answering your question about combining ES7 async/await with setTimeout
, though it may not help solve your problem with sending too many requests per second.
Update: Modern node.js versions has a buid-in async timeout implementation, accessible via util.promisify helper:
const {promisify} = require('util');
const setTimeoutAsync = promisify(setTimeout);
If you are using RABL you can configure it as described here to use JSON.pretty_generate:
class PrettyJson
def self.dump(object)
JSON.pretty_generate(object, {:indent => " "})
end
end
Rabl.configure do |config|
...
config.json_engine = PrettyJson if Rails.env.development?
...
end
A problem with using JSON.pretty_generate is that JSON schema validators will no longer be happy with your datetime strings. You can fix those in your config/initializers/rabl_config.rb with:
ActiveSupport::TimeWithZone.class_eval do
alias_method :orig_to_s, :to_s
def to_s(format = :default)
format == :default ? iso8601 : orig_to_s(format)
end
end
Sample code block for strong password:
(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?=\\S+$).{6,18}
In the toolbar search for press the arrow and select Customize... It will open project properties.In the categories select RUN. Look for Main Class. Clear all the Main Class character and type your class name. Click on OK. And run again. The problem is solved.
On window
import os
os.system("start \"\" https://example.com")
On macOS
import os
os.system("open \"\" https://example.com")
On Linux
import os
os.system("xdg-open \"\" https://example.com")
Cross-Platform
import webbrowser
webbrowser.open('https://example.com')
While you can't directly recover a MySQL password without bruteforcing, there might be another way - if you've used MySQL Workbench to connect to the database, and have saved the credentials to the "vault", you're golden.
On Windows, the credentials are stored in %APPDATA%\MySQL\Workbench\workbench_user_data.dat - encrypted with CryptProtectData (without any additional entropy). Decrypting is easy peasy:
std::vector<unsigned char> decrypt(BYTE *input, size_t length) {
DATA_BLOB inblob { length, input };
DATA_BLOB outblob;
if (!CryptUnprotectData(&inblob, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &outblob)) {
throw std::runtime_error("Couldn't decrypt");
}
std::vector<unsigned char> output(length);
memcpy(&output[0], outblob.pbData, outblob.cbData);
return output;
}
Or you can check out this DonationCoder thread for source + executable of a quick-and-dirty implementation.
url : www.mydomain.com/user1/1234
$.params = window.location.href.split("/"); $.params[$.params.length-1];
You can split based on your query string separator
bind focusin after using datepicker change css of datepicker`s widget wish help
$('input.date').datepicker();
$('input.date').focusin(function(){
$('input.date').datepicker('widget').css({left:"-=127"});
});
The normal layout for a maven multi module project is:
parent
+-- pom.xml
+-- module
+-- pom.xml
Check that you use this layout.
Additionally:
the relativePath
looks strange. Instead of '..'
<relativePath>..</relativePath>
try '../' instead:
<relativePath>../</relativePath>
You can also remove relativePath
if you use the standard layout. This is what I always do, and on the command line I can build as well the parent (and all modules) or only a single module.
The module path may be wrong. In the parent you define the module as:
<module>junitcategorizer.cutdetection</module>
You must specify the name of the folder of the child module, not an artifact identifier. If junitcategorizer.cutdetection
is not the name of the folder than change it accordingly.
Hope that helps..
EDIT have a look at the other post, I answered there.
What about providing a custom N-Factor authentication mechanism?
Before combining available methods, let's assume we can perform the following:
1) Hard-code inside the Java program
2) Store in a .properties file
3) Ask user to type password from command line
4) Ask user to type password from a form
5) Ask user to load a password-file from command line or a form
6) Provide the password through network
7) many alternatives (eg Draw A Secret, Fingerprint, IP-specific, bla bla bla)
1st option: We could make things more complicated for an attacker by using obfuscation, but this is not considered a good countermeasure. A good coder can easily understand how it works if he/she can access the file. We could even export a per-user binary (or just the obfuscation part or key-part), so an attacker must have access to this user-specific file, not another distro. Again, we should find a way to change passwords, eg by recompiling or using reflection to on-the-fly change class behavior.
2nd option: We can store the password in the .properties file in an encrypted format, so it's not directly visible from an attacker (just like jasypt does). If we need a password manager we'll need a master password too which again should be stored somewhere - inside a .class file, the keystore, kernel, another file or even in memory - all have their pros and cons.
But, now users will just edit the .properties file for password change.
3rd option: type the password when running from command line e.g. java -jar /myprogram.jar -p sdflhjkiweHIUHIU8976hyd
.
This doesn't require the password to be stored and will stay in memory. However, history
commands and OS logs, may be your worst enemy here.
To change passwords on-the-fly, you will need to implement some methods (eg listen for console inputs, RMI, sockets, REST bla bla bla), but the password will always stay in memory.
One can even temporarily decrypt it only when required -> then delete the decrypted, but always keep the encrypted password in memory. Unfortunately, the aforementioned method does not increase security against unauthorized in-memory access, because the person who achieves that, will probably have access to the algorithm, salt and any other secrets being used.
4th option: provide the password from a custom form, rather than the command line. This will circumvent the problem of logging exposure.
5th option: provide a file as a password stored previously on a another medium -> then hard delete file. This will again circumvent the problem of logging exposure, plus no typing is required that could be shoulder-surfing stolen. When a change is required, provide another file, then delete again.
6th option: again to avoid shoulder-surfing, one can implement an RMI method call, to provide the password (through an encrypted channel) from another device, eg via a mobile phone. However, you now need to protect your network channel and access to the other device.
I would choose a combination of the above methods to achieve maximum security so one would have to access the .class files, the property file, logs, network channel, shoulder surfing, man in the middle, other files bla bla bla. This can be easily implemented using a XOR operation between all sub_passwords to produce the actual password.
We can't be protected from unauthorized in-memory access though, this can only be achieved by using some access-restricted hardware (eg smartcards, HSMs, SGX), where everything is computed into them, without anyone, even the legitimate owner being able to access decryption keys or algorithms. Again, one can steal this hardware too, there are reported side-channel attacks that may help attackers in key extraction and in some cases you need to trust another party (eg with SGX you trust Intel). Of course, situation may worsen when secure-enclave cloning (de-assembling) will be possible, but I guess this will take some years to be practical.
Also, one may consider a key sharing solution where the full key is split between different servers. However, upon reconstruction, the full key can be stolen. The only way to mitigate the aforementioned issue is by secure multiparty computation.
We should always keep in mind that whatever the input method, we need to ensure we are not vulnerable from network sniffing (MITM attacks) and/or key-loggers.
In the click event "this" is the a tag that was clicked
jQuery('.class1 a').click( function() {
var divToSlide = $(this).parent().find(".class2");
if (divToSlide.is(":hidden")) {
divToSlide.slideDown("slow");
} else {
divToSlide.slideUp();
}
});
There's multiple ways to get to the div though you could also use .siblings, .next etc
Steps:
Use Mach-OView for viewing all the Symbols in dylib
You can have your React development server proxy your requests to that server. Simply send your requests to your local server like this: url: "/"
And add the following line to your package.json
file
"proxy": "https://awww.api.com"
Though if you are sending CORS requests to multiple sources, you'll have to manually configure the proxy yourself This link will help you set that up Create React App Proxying API requests
4 decimal places would give you the accuracy to store the world's smallest currency sub-units. You can take it down further if you need micropayment (nanopayment?!) accuracy.
I too prefer DECIMAL
to DBMS-specific money types, you're safer keeping that kind of logic in the application IMO. Another approach along the same lines is simply to use a [long] integer, with formatting into ¤unit.subunit for human readability (¤ = currency symbol) done at the application level.
A really simple implementation is:
out = "".join(c for c in asking if c not in ('!','.',':'))
and keep adding any other types of punctuation.
A more efficient way would be
import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)
Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python
For your convenience, below is a small shellscript that has to be executed with two parameters: db-name and new db-name.
You might need to add login-parameters to the mysql-lines if you don't use the .my.cnf-file in your home-directory. Please make a backup before executing this script.
#!/usr/bin/env bash
mysql -e "CREATE DATABASE $2 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;"
for i in $(mysql -Ns $1 -e "show tables");do
echo "$1.$i -> $2.$i"
mysql -e "rename TABLE $1.$i to $2.$i"
done
mysql -e "DROP DATABASE $1"
I had the same problem.
I had to print the color of the nodes where the color was: enum col { WHITE, GRAY, BLACK };
and the node: typedef struct Node { col color; };
I tried to print node->color
with printf("%s\n", node->color);
but all I got on the screen was (null)\n
.
The answer bmargulies gave almost solved the problem.
So my final solution is:
static char *enumStrings[] = {"WHITE", "GRAY", "BLACK"};
printf("%s\n", enumStrings[node->color]);
Replace whatever is in the address bar with this:
javascript:document.getElementById('serverTime').innerHTML='[text here]';
/*$mpdf = new mPDF('', // mode - default ''
'', // format - A4, for example, default ''
0, // font size - default 0
'', // default font family
15, // margin_left
15, // margin right
16, // margin top
16, // margin bottom
9, // margin header
9, // margin footer
'L'); // L - landscape, P - portrait*/
Regarding the comment of Andrew Mairose - Although a fine solution, I would just like to add that this solution will not work on fixed size lists.
You could attempt doing like so:
Arrays.asList(new String[]{"a", "b", null, "c", " "})
.removeIf(item -> item == null || "".equals(item));
But you'll encounter an UnsupportedOperationException at java.util.AbstractList.remove
(since asList
returns a non-resizable List).
A different solution might be this:
List<String> collect =
Stream.of(new String[]{"a", "b", "c", null, ""})
.filter(item -> item != null && !"".equals(item))
.collect(Collectors.toList());
Which will produce a nice list of strings :-)
I have just made a solution for it. I made a library for this to do that in a reusable way that's why you don't need to recode in your XML. Here is documentation on how to use it in Java and Kotlin. First, initialize it from an activity from where you want to show the overlay-
AppWaterMarkBuilder.doConfigure()
.setAppCompatActivity(MainActivity.this)
.setWatermarkProperty(R.layout.layout_water_mark)
.showWatermarkAfterConfig();
Then you can hide and show it from anywhere in your app -
/* For hiding the watermark*/
AppWaterMarkBuilder.hideWatermark()
/* For showing the watermark*/
AppWaterMarkBuilder.showWatermark()
Gif preview -
Spring Boot automatically loads src/test/resources/application.properties
, if following annotations are used
@RunWith(SpringRunner.class)
@SpringBootTest
So, rename test.properties
to application.properties
to utilize auto configuration.
If you only need to load the properties file (into the Environment) you can also use the following, as explained here
@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
[Update: Overriding certain properties for testing]
src/main/resources/application-test.properties
.@ActiveProfiles("test")
.This loads application.properties
and then application-test.properties
properties into application context for the test case, as per rules defined here.
Demo - https://github.com/mohnish82/so-spring-boot-testprops
Already answered above but wanted to share.
Will not work in IE though. thanks for mentioning it @Mahmoud
var array1 = [1, 2, 3];_x000D_
_x000D_
console.log(array1.includes(2));_x000D_
// expected output: true_x000D_
_x000D_
var pets = ['cat', 'dog', 'bat'];_x000D_
_x000D_
console.log(pets.includes('cat'));_x000D_
// expected output: true_x000D_
_x000D_
console.log(pets.includes('at'));_x000D_
// expected output: false
_x000D_
got some reference Here. they also have Polyfill for above.
Add the following line on the top of your file
require 'json'
Then you can use:
car = {:make => "bmw", :year => "2003"}
car.to_json
Alternatively, you can use:
JSON.generate({:make => "bmw", :year => "2003"})
The coding standards I've worked with have had the following for most of class declarations.
// coding standard: disallow when not used
T(void) = delete; // default ctor (1)
~T(void) = delete; // default dtor (2)
T(const T&) = delete; // copy ctor (3)
T(const T&&) = delete; // move ctor (4)
T& operator= (const T&) = delete; // copy assignment (5)
T& operator= (const T&&) = delete; // move assignment (6)
If you use any of these 6, you simply comment out the corresponding line.
Example: class FizzBus require only dtor, and thus do not use the other 5.
// coding standard: disallow when not used
FizzBuzz(void) = delete; // default ctor (1)
// ~FizzBuzz(void); // dtor (2)
FizzBuzz(const FizzBuzz&) = delete; // copy ctor (3)
FizzBuzz& operator= (const FizzBuzz&) = delete; // copy assig (4)
FizzBuzz(const FizzBuzz&&) = delete; // move ctor (5)
FizzBuzz& operator= (const FizzBuzz&&) = delete; // move assign (6)
We comment out only 1 here, and install the implementation of it else where (probably where the coding standard suggests). The other 5 (of 6) are disallowed with delete.
You can also use '= delete' to disallow implicit promotions of different sized values ... example
// disallow implicit promotions
template <class T> operator T(void) = delete;
template <class T> Vuint64& operator= (const T) = delete;
template <class T> Vuint64& operator|= (const T) = delete;
template <class T> Vuint64& operator&= (const T) = delete;
I could happen that if your array contains the string "hello", and if you are searching for "he", grep returns true, although, "he" may not be an array element.
Perhaps,
if (grep(/^$match$/, @array))
more apt.
SELECT last_value, increment_by from "other_schema".id_seq;
for adding a seq to a column where the schema is not public try this.
nextval('"other_schema".id_seq'::regclass)
a simple line , after that you can see also a doted line
import java.awt.*;
import javax.swing.*;
import java.awt.Graphics.*;
import java.awt.Graphics2D.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BasicStroke;
import java.awt.Event.*;
import java.awt.Component.*;
import javax.swing.SwingUtilities;
/**
*
* @author junaid
*/
public class JunaidLine extends JPanel{
//private Graphics Graphics;
private void doDrawing(Graphics g){
Graphics2D g2d=(Graphics2D) g;
float[] dash1 = {2f,0f,2f};
g2d.drawLine(20, 40, 250, 40);
BasicStroke bs1 = new BasicStroke(1,BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND,1.0f,dash1,2f);
g2d.setStroke(bs1);
g2d.drawLine(20, 80, 250, 80);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent( g);
doDrawing(g);
}
}
class BasicStrokes extends JFrame{
public BasicStrokes(){
initUI();
}
private void initUI(){
setTitle("line");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
add(new JunaidLine());
setSize(280,270);
setLocationRelativeTo(null);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
BasicStrokes bs = new BasicStrokes();
bs.setVisible(true);
}
});
}
}
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
I had to read subtitles files and split them into sentences. After pre-processing (like removing time information etc in the .srt files), the variable fullFile contained the full text of the subtitle file. The below crude way neatly split them into sentences. Probably I was lucky that the sentences always ended (correctly) with a space. Try this first and if it has any exceptions, add more checks and balances.
# Very approximate way to split the text into sentences - Break after ? . and !
fullFile = re.sub("(\!|\?|\.) ","\\1<BRK>",fullFile)
sentences = fullFile.split("<BRK>");
sentFile = open("./sentences.out", "w+");
for line in sentences:
sentFile.write (line);
sentFile.write ("\n");
sentFile.close;
Oh! well. I now realize that since my content was Spanish, I did not have the issues of dealing with "Mr. Smith" etc. Still, if someone wants a quick and dirty parser...
you can use zscore to analyze the data in column C and D for outliers, where zscore is the series - series.mean / series.std(). Use apply too create a user defined function for difference between C and D creating a new resulting dataframe. Apply uses the group result set.
from scipy.stats import zscore
columns = ['A', 'B', 'C', 'D']
records = [
['foo', 'one', 0.162003, 0.087469],
['bar', 'one', -1.156319, -1.5262719999999999],
['foo', 'two', 0.833892, -1.666304],
['bar', 'three', -2.026673, -0.32205700000000004],
['foo', 'two', 0.41145200000000004, -0.9543709999999999],
['bar', 'two', 0.765878, -0.095968],
['foo', 'one', -0.65489, 0.678091],
['foo', 'three', -1.789842, -1.130922]
]
df = pd.DataFrame.from_records(records, columns=columns)
print(df)
standardize=df.groupby('A')['C','D'].transform(zscore)
print(standardize)
outliersC= (standardize['C'] <-1.1) | (standardize['C']>1.1)
outliersD= (standardize['D'] <-1.1) | (standardize['D']>1.1)
results=df[outliersC | outliersD]
print(results)
#Dataframe results
A B C D
0 foo one 0.162003 0.087469
1 bar one -1.156319 -1.526272
2 foo two 0.833892 -1.666304
3 bar three -2.026673 -0.322057
4 foo two 0.411452 -0.954371
5 bar two 0.765878 -0.095968
6 foo one -0.654890 0.678091
7 foo three -1.789842 -1.130922
#C and D transformed Z score
C D
0 0.398046 0.801292
1 -0.300518 -1.398845
2 1.121882 -1.251188
3 -1.046514 0.519353
4 0.666781 -0.417997
5 1.347032 0.879491
6 -0.482004 1.492511
7 -1.704704 -0.624618
#filtering using arbitrary ranges -1 and 1 for the z-score
A B C D
1 bar one -1.156319 -1.526272
2 foo two 0.833892 -1.666304
5 bar two 0.765878 -0.095968
6 foo one -0.654890 0.678091
7 foo three -1.789842 -1.130922
>>>>>>>>>>>>> Part 2
splitting = df.groupby('A')
#look at how the data is grouped
for group_name, group in splitting:
print(group_name)
def column_difference(gr):
return gr['C']-gr['D']
grouped=splitting.apply(column_difference)
print(grouped)
A
bar 1 0.369953
3 -1.704616
5 0.861846
foo 0 0.074534
2 2.500196
4 1.365823
6 -1.332981
7 -0.658920
I've got that error when the controller name was not the same (case sensitivity!):
.controller('mainCOntroller', ... // notice CO
and in view
<div class="container" ng-controller="mainController"> <!-- notice Co -->
If you just want to check the value is in Range, use this:
MIN_VALUE = 1;
MAX_VALUE = 100;
$customValue = min(MAX_VALUE,max(MIN_VALUE,$customValue)));
When you have a certificate with both CN and Subject Alternative Names (SAN), if you make your request based on the CN content, then that particular content must also be present under SAN, otherwise it will fail with the error in question.
In my case CN had something, SAN had something else. I had to use SAN URL, and then it worked just fine.
See if this example provides any clarification. Basically you configure a set of routes and include partial templates based on the route. Setting ng-view in your main index.html allows you to inject those partial views.
The config portion looks like this:
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {controller:'ListCtrl', templateUrl:'list.html'})
.otherwise({redirectTo:'/'});
}])
The point of entry for injecting the partial view into your main template is:
<div class="container" ng-view=""></div>
Try this CSS:
body {
margin: 0;
padding: 0;
}
.logo {
float: left;
}
/* ~~ Top Navigation Bar ~~ */
#navigation-container {
width: 1200px;
margin: 0 auto;
height: 70px;
}
.navigation-bar {
background-color: #352d2f;
height: 70px;
width: 100%;
}
#navigation-container img {
float: left;
}
#navigation-container ul {
padding: 0px;
margin: 0px;
text-align: center;
display:inline-block;
}
#navigation-container li {
list-style-type: none;
padding: 0px;
height: 24px;
margin-top: 4px;
margin-bottom: 4px;
display: inline;
}
#navigation-container li a {
color: white;
font-size: 16px;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
text-decoration: none;
line-height: 70px;
padding: 5px 15px;
opacity: 0.7;
}
#menu {
float: right;
}
Summarized: INSTALL 32 bit version of Microsoft Access Database Engine 2010 Redistributable. Uninstall 64 bit version if previously installed. http://www.microsoft.com/en-us/download/details.aspx?id=13255
The Excel connection manager is trying to use the ACE OLE DB provider in order to access the Excel file when the version is above 2007 (xlsx). Although your box is 64-bit, you’re using SQL Server Data Tools, which is a 32-bit application. There is no 64-bit version for SSDT. When you design your package within SSDT, you’re using a 32-bit process, which can only use 32-bit providers. When you try to choose the table in the Excel file, the connection manager needs to access the 32-bit version of the ACE OLE DB provider, but this provider is not registered on your machine, only the 64-bit version is installed.
You should download the 32-bit version of the “Microsoft Access Database Engine 2010 Redistributable”. When you try to install it, you might get an error message. You should first uninstall only the 64-bit version of the “Microsoft Access Database Engine 2010 Redistributable”, which you probably installed previously. The 64-bit version and the 32-bit version can’t live together on the same host, so you’ll have to uninstall (through “Program and Features”) and install the other one if you wish to switch between them.
Once you finish uninstalling the 64-bit version and installing the 32-bit version of the provider, the problem is solved, and you can finally choose the table within the Excel file. The Excel connection manager is now able to use the ACE OLE DB provider (32-bit version) in order to access the Excel file.
Andrew had a great response but I wanted to tweek it a little. The way this is different is that I like my ModelViews to not have overhead data in them. Just the data for the object. It seem that ViewData fits the bill for over head data, but of course I'm new at this. I suggest doing something like this.
Controller
virtual public ActionResult DisplaySomeWidget(int id)
{
SomeModelView returnData = someDataMapper.getbyid(1);
var serializer = new JavaScriptSerializer();
ViewData["JSON"] = serializer.Serialize(returnData);
return View(myview, returnData);
}
View
//create base js object;
var myWidget= new Widget(); //Widget is a class with a public member variable called data.
myWidget.data= <%= ViewData["JSON"] %>;
What This does for you is it gives you the same data in your JSON as in your ModelView so you can potentially return the JSON back to your controller and it would have all the parts. This is similar to just requesting it via a JSONRequest however it requires one less call so it saves you that overhead. BTW this is funky for Dates but that seems like another thread.
This is the code I have for moving an item down one place in a list:
if (this.folderImages.SelectedIndex > -1 && this.folderImages.SelectedIndex < this.folderImages.Items.Count - 1)
{
string imageName = this.folderImages.SelectedItem as string;
int index = this.folderImages.SelectedIndex;
this.folderImages.Items.RemoveAt(index);
this.folderImages.Items.Insert(index + 1, imageName);
this.folderImages.SelectedIndex = index + 1;
}
and this for moving it one place up:
if (this.folderImages.SelectedIndex > 0)
{
string imageName = this.folderImages.SelectedItem as string;
int index = this.folderImages.SelectedIndex;
this.folderImages.Items.RemoveAt(index);
this.folderImages.Items.Insert(index - 1, imageName);
this.folderImages.SelectedIndex = index - 1;
}
folderImages
is a ListBox
of course so the list is a ListBox.ObjectCollection
, not a List<T>
, but it does inherit from IList
so it should behave the same. Does this help?
Of course the former only works if the selected item is not the last item in the list and the latter if the selected item is not the first item.
Give the parent z-index: -1, or opacity: 0.99
In cryptography there are two types of algorithms used:
Symmetric algorithms
A single key is used to encrypt data. When encrypted with the key, the data can be decrypted using the same key. If, for example, Mary encrypts a message using the key "my-secret" and sends it to John, he will be able to decrypt the message correctly with the same key "my-secret".
Asymmetric algorithms
Two keys are used to encrypt and decrypt messages. While one key(public) is used to encrypt the message, the other key(private) can only be used to decrypt it. So, John can generate both public and private keys, then send only the public key to Mary to encrypt her message. The message can only be decrypted using the private key.
HS256 and RS256 Scenario
These algorithms are NOT used to encrypt/decryt data. Rather they are used to verify the origin or the authenticity of the data. When Mary needs to send an open message to Jhon and he needs to verify that the message is surely from Mary, HS256 or RS256 can be used.
HS256 can create a signature for a given sample of data using a single key. When the message is transmitted along with the signature, the receiving party can use the same key to verify that the signature matches the message.
RS256 uses pair of keys to do the same. A signature can only be generated using the private key. And the public key has to be used to verify the signature. In this scenario, even if Jack finds the public key, he cannot create a spoof message with a signature to impersonate Mary.
Another way is to use CONCAT
and CAST
, be aware, that you need to use DATETIME2(x)
to make it work. You can set x
to anything between 0-7
7
meaning no precision loss.
DECLARE @date date = '2018-03-12'
DECLARE @time time = '07:00:00.0000000'
SELECT CAST(CONCAT(@date, ' ', @time) AS DATETIME2(7))
Returns 2018-03-12 07:00:00.0000000
Tested on SQL Server 14
3 syntax (nasm, tasm, gas ) in 1 assembler, yasm.
Make sure "html_files" is a directory in your app's main bundle, and not just a group in Xcode.
If you use yum search you can find the python dev package for your version of python.
For me I was using python 3.5. I ran the following
yum search python | grep devel
Which returned the following
I was then able to install the correct package for my version of python with the following cmd.
sudo yum install python35u-devel.x86_64
This works on centos for ubuntu or debian you would need to use apt-get
The following IP address ranges belong to Google:
64.233.160.0 - 64.233.191.255
66.102.0.0 - 66.102.15.255
66.249.64.0 - 66.249.95.255
72.14.192.0 - 72.14.255.255
74.125.0.0 - 74.125.255.255
209.85.128.0 - 209.85.255.255
216.239.32.0 - 216.239.63.255
Like many popular Web sites, Google utilizes multiple Internet servers to handle incoming requests to its Web site. Instead of entering http://www.google.com/ into the browser, a person can enter http:// followed by one of the above addresses, for example:
http://74.125.224.72/
A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.
It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)
select
sone_field collate DATABASE_DEFAULT
from
table_1
inner join
table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever
You can use redial package for prefetching data on the server before attempting to render
<asp:LinkButton ID="mybutton" Text="Link Button" runat="server"></asp:LinkButton>
With Hover effects :
#mybutton
{
background-color: #000;
color: #fff;
font-size: 20px;
width: 150px;
font-weight: bold;
}
#mybutton:hover
{
background-color: #fff;
color: #000;
}
In order to reset the value in angular 2 use:
this.rootNode.findNode("objectname").resetValue();
I know this is ancient but what about...
4x4 example (actually 4x<anything>)
:
var matrix = [ [],[],[],[] ]
which can filled by:
for (var i=0; i<4; i++) {
for (var j=0; j<4; j++) {
matrix[i][j] = i*j;
}
}
No there is not : But I have created one easy class to help :
public class PropertiesUtility
{
private static Hashtable ht = new Hashtable();
public void loadProperties(string path)
{
string[] lines = System.IO.File.ReadAllLines(path);
bool readFlag = false;
foreach (string line in lines)
{
string text = Regex.Replace(line, @"\s+", "");
readFlag = checkSyntax(text);
if (readFlag)
{
string[] splitText = text.Split('=');
ht.Add(splitText[0].ToLower(), splitText[1]);
}
}
}
private bool checkSyntax(string line)
{
if (String.IsNullOrEmpty(line) || line[0].Equals('['))
{
return false;
}
if (line.Contains("=") && !String.IsNullOrEmpty(line.Split('=')[0]) && !String.IsNullOrEmpty(line.Split('=')[1]))
{
return true;
}
else
{
throw new Exception("Can not Parse Properties file please verify the syntax");
}
}
public string getProperty(string key)
{
if (ht.Contains(key))
{
return ht[key].ToString();
}
else
{
throw new Exception("Property:" + key + "Does not exist");
}
}
}
Hope this helps.
The value
attribute on submit
-type <input>
elements controls the text displayed.
<input type="submit" class="like" value="Like" />
For a very simple solution, you could use PHPMyAdmin to export the row as a CSV file then simply import the amended CSV file. Editing the ID/primarykey column to show a 0 for the primarykey value before you import it.
SELECT * FROM table where primarykey=1
Then at the bottom of the page:
Where is says "Export" simply export, then edit the csv file to remove the primarykey value, so it's empty, and then just import it into the database, a new primarykey will be assigned on import.
The previous answers explain type parameters (T, E, etc.), but don't explain the wildcard, "?", or the differences between them, so I'll address that.
First, just to be clear: the wildcard and type parameters are not the same. Where type parameters define a sort of variable (e.g., T) that represents the type for a scope, the wildcard does not: the wildcard just defines a set of allowable types that you can use for a generic type. Without any bounding (extends
or super
), the wildcard means "use any type here".
The wildcard always come between angle brackets, and it only has meaning in the context of a generic type:
public void foo(List<?> listOfAnyType) {...} // pass a List of any type
never
public <?> ? bar(? someType) {...} // error. Must use type params here
or
public class MyGeneric ? { // error
public ? getFoo() { ... } // error
...
}
It gets more confusing where they overlap. For example:
List<T> fooList; // A list which will be of type T, when T is chosen.
// Requires T was defined above in this scope
List<?> barList; // A list of some type, decided elsewhere. You can do
// this anywhere, no T required.
There's a lot of overlap in what's possible with method definitions. The following are, functionally, identical:
public <T> void foo(List<T> listOfT) {...}
public void bar(List<?> listOfSomething) {...}
So, if there's overlap, why use one or the other? Sometimes, it's honestly just style: some people say that if you don't need a type param, you should use a wildcard just to make the code simpler/more readable. One main difference I explained above: type params define a type variable (e.g., T) which you can use elsewhere in the scope; the wildcard doesn't. Otherwise, there are two big differences between type params and the wildcard:
Type params can have multiple bounding classes; the wildcard cannot:
public class Foo <T extends Comparable<T> & Cloneable> {...}
The wildcard can have lower bounds; type params cannot:
public void bar(List<? super Integer> list) {...}
In the above the List<? super Integer>
defines Integer
as a lower bound on the wildcard, meaning that the List type must be Integer or a super-type of Integer. Generic type bounding is beyond what I want to cover in detail. In short, it allows you to define which types a generic type can be. This makes it possible to treat generics polymorphically. E.g. with:
public void foo(List<? extends Number> numbers) {...}
You can pass a List<Integer>
, List<Float>
, List<Byte>
, etc. for numbers
. Without type bounding, this won't work -- that's just how generics are.
Finally, here's a method definition which uses the wildcard to do something that I don't think you can do any other way:
public static <T extends Number> void adder(T elem, List<? super Number> numberSuper) {
numberSuper.add(elem);
}
numberSuper
can be a List of Number or any supertype of Number (e.g., List<Object>
), and elem
must be Number or any subtype. With all the bounding, the compiler can be certain that the .add()
is typesafe.
I came upon PIL's ImageSequence module, which offers for a better (and more standard) GIF aninmation. I also use Tk's after() method this time, which is better than time.sleep().
from Tkinter import *
from PIL import Image, ImageTk, ImageSequence
def stop(event):
global play
play = False
exit()
root = Tk()
root.bind("<Key>", stop) # Press any key to stop
GIFfile = {path_to_your_GIF_file}
im = Image.open(GIFfile); img = ImageTk.PhotoImage(im)
delay = im.info['duration'] # Delay used in the GIF file
lbl = Label(image=img); lbl.pack() # Create a label where to display images
play = True;
while play:
for frame in ImageSequence.Iterator(im):
if not play: break
root.after(delay);
img = ImageTk.PhotoImage(frame)
lbl.config(image=img); root.update() # Show the new frame/image
root.mainloop()
About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :
Basically, flatMap
is the equivalent of Promise.then
.
For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay
operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)
static bool FileInUse(string path)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
fs.CanWrite
}
return false;
}
catch (IOException ex)
{
return true;
}
}
string filePath = "C:\\Documents And Settings\\yourfilename";
bool isFileInUse;
isFileInUse = FileInUse(filePath);
// Then you can do some checking
if (isFileInUse)
Console.WriteLine("File is in use");
else
Console.WriteLine("File is not in use");
Hope this helps!
I found that when I was reading strings in from a .plist
file, occurrences of "\n"
were parsed as "\\n"
. The solution for me was to replace occurrences of "\\n"
with "\n"
. For example, given an instance of NSString
named myString
read in from my .plist
file, I had to call...
myString = [myString stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
... before assigning it to my UILabel
instance...
myLabel.text = myString;
Use a custom ID if possible if you would like to apply the action to only that button.
<button class="pushDontpush">PUSH ME</button>
$("#pushDontpush").click(function() {
if ($(this).text() == "PUSH ME") {
$(this).text("DON'T PUSH ME");
} else {
$(this).text("PUSH ME");
};
});
Working CodePen: Toggle text in button
A quick step-by-step guide how to configure NetBeans default encoding UTF-8. In result NetBeans will create all new files in UTF-8 encoding.
NetBeans default encoding UTF-8 step-by-step guide
Go to etc folder in NetBeans installation directory
Edit netbeans.conf file
Find netbeans_default_options line
Add -J-Dfile.encoding=UTF-8 inside quotation marks inside that line
(example: netbeans_default_options="-J-Dfile.encoding=UTF-8"
)
Restart NetBeans
You set NetBeans default encoding UTF-8.
Your netbeans_default_options may contain additional parameters inside the quotation marks. In such case, add -J-Dfile.encoding=UTF-8 at the end of the string. Separate it with space from other parameters.
Example:
netbeans_default_options="-J-client -J-Xss128m -J-Xms256m -J-XX:PermSize=32m -J-Dapple.laf.useScreenMenuBar=true -J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true -J-Dsun.java2d.dpiaware=true -J-Dsun.zip.disableMemoryMapping=true -J-Dfile.encoding=UTF-8"
here is link for Further Details
I've used py2exe in the past and have been very happy with it. I didn't particularly enjoy using cx-freeze as much, though
Leaving this here for myself,
If I get this error, I probably used const char*
when I should be using char* const
.
This makes the pointer constant, and not the contents of the string.
const char* const
makes it so the value and the pointer is constant also.
Well, the most efficient way, presuming you know the size of the integer, would be a lookup. Should be faster than the much shorter logarithm based approach. If you don't care about counting the '-', remove the + 1.
// generic solution
template <class T>
int numDigits(T number)
{
int digits = 0;
if (number < 0) digits = 1; // remove this line if '-' counts as a digit
while (number) {
number /= 10;
digits++;
}
return digits;
}
// partial specialization optimization for 32-bit numbers
template<>
int numDigits(int32_t x)
{
if (x == MIN_INT) return 10 + 1;
if (x < 0) return numDigits(-x) + 1;
if (x >= 10000) {
if (x >= 10000000) {
if (x >= 100000000) {
if (x >= 1000000000)
return 10;
return 9;
}
return 8;
}
if (x >= 100000) {
if (x >= 1000000)
return 7;
return 6;
}
return 5;
}
if (x >= 100) {
if (x >= 1000)
return 4;
return 3;
}
if (x >= 10)
return 2;
return 1;
}
// partial-specialization optimization for 8-bit numbers
template <>
int numDigits(char n)
{
// if you have the time, replace this with a static initialization to avoid
// the initial overhead & unnecessary branch
static char x[256] = {0};
if (x[0] == 0) {
for (char c = 1; c != 0; c++)
x[c] = numDigits((int32_t)c);
x[0] = 1;
}
return x[n];
}
document.getElementById('username').value = 'foo';
document.getElementById('login_form').submit();
Main Class:
public class AndroidLocationActivity extends Activity {
Button btnGPSShowLocation;
Button btnNWShowLocation;
AppLocationService appLocationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appLocationService = new AppLocationService(
AndroidLocationActivity.this);
btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (GPS): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("GPS");
}
}
});
btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("NETWORK");
}
}
});
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
AndroidLocationActivity.this);
alertDialog.setTitle(provider + " SETTINGS");
alertDialog.setMessage(provider
+ " is not enabled! Want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
AndroidLocationActivity.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Next Class:
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Don't forget to add in your manifest.
<!-- to get location using GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- to get location using NetworkProvider -->
<uses-permission android:name="android.permission.INTERNET" />
Using only virtualenv (without virtualenvwrapper), setting environment variables is easy through the activate
script you sourcing in order to activate the virtualenv.
Run:
nano YOUR_ENV/bin/activate
Add the environment variables to the end of the file like this:
export KEY=VALUE
You can also set a similar hook to unset the environment variable as suggested by Danilo Bargen in his great answer above if you need.
Create a file called config
inside ~/.ssh
. Inside the file you can add:
Host *
User buck
Or add
Host example
HostName example.net
User buck
The second example will set a username and is hostname specific, while the first example sets a username only. And when you use the second one you don't need to use ssh example.net
; ssh example
will be enough.
In our case, we struggled with this error for quite some days. It turns out that in control panel, programs, turn windows features on or off.
We selected Internet Information Services, world wide web services, Application development features and there we check the set of features associated with our development environment. For example: ASP.NET 4.6. .NET Extensibility 4.6, etc.
It works!
os.system ('/home/user1/exportPath.ksh')
exportPath.ksh:
export PATH=MY_DATA="my_export"
List does not implement IBindingList
so the grid does not know about your new items.
Bind your DataGridView to a BindingList<T>
instead.
var list = new BindingList<Person>(persons);
myGrid.DataSource = list;
But I would even go further and bind your grid to a BindingSource
var list = new List<Person>()
{
new Person { Name = "Joe", },
new Person { Name = "Misha", },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;
If you need to list all rows where all the column values are NULL
, then i'd use the COLLATE
function. This takes a list of values and returns the first non-null value. If you add all the column names to the list, then use IS NULL
, you should get all the rows containing only nulls.
SELECT * FROM MyTable WHERE COLLATE(Col1, Col2, Col3, Col4......) IS NULL
You shouldn't really have any tables with ALL the columns
null, as this means you don't have a primary key
(not allowed to be null
). Not having a primary key is something to be avoided; this breaks the first normal form.
For those using the Symfony framework, the phpseclib can also be used to connect via SSH. It can be installed using composer:
composer require phpseclib/phpseclib
Next, simply use it as follows:
use phpseclib\Net\SSH2;
// Within a controller for example:
$ssh = new SSH2('hostname or ip');
if (!$ssh->login('username', 'password')) {
// Login failed, do something
}
$return_value = $ssh->exec('command');
Here is a solution which requires no additional libraries and is very fast. This was found from: https://nedbatchelder.com/blog/200712/extracting_jpgs_from_pdfs.html# I have added the code in a function to make it more convenient.
def convert(filepath):
with open(filepath, "rb") as file:
pdf = file.read()
startmark = b"\xff\xd8"
startfix = 0
endmark = b"\xff\xd9"
endfix = 2
i = 0
njpg = 0
while True:
istream = pdf.find(b"stream", i)
if istream < 0:
break
istart = pdf.find(startmark, istream, istream + 20)
if istart < 0:
i = istream + 20
continue
iend = pdf.find(b"endstream", istart)
if iend < 0:
raise Exception("Didn't find end of stream!")
iend = pdf.find(endmark, iend - 20)
if iend < 0:
raise Exception("Didn't find end of JPG!")
istart += startfix
iend += endfix
jpg = pdf[istart:iend]
newfile = "{}jpg".format(filepath[:-3])
with open(newfile, "wb") as jpgfile:
jpgfile.write(jpg)
njpg += 1
i = iend
return newfile
Call convert with the pdf path as the argument and the function will create a .jpg file in the same directory
using which.min
and which.max
:
library(dplyr, warn.conflicts = F)
df %>%
group_by(id) %>%
slice(c(which.min(stopSequence), which.max(stopSequence)))
#> # A tibble: 6 x 3
#> # Groups: id [3]
#> id stopId stopSequence
#> <dbl> <fct> <dbl>
#> 1 1 a 1
#> 2 1 c 3
#> 3 2 b 1
#> 4 2 c 4
#> 5 3 b 1
#> 6 3 a 3
benchmark
It is also much faster than the current accepted answer because we find the min and max value by group, instead of sorting the whole stopSequence column.
# create a 100k times longer data frame
df2 <- bind_rows(replicate(1e5, df, F))
bench::mark(
mm =df2 %>%
group_by(id) %>%
slice(c(which.min(stopSequence), which.max(stopSequence))),
jeremy = df2 %>%
group_by(id) %>%
arrange(stopSequence) %>%
filter(row_number()==1 | row_number()==n()))
#> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
#> # A tibble: 2 x 6
#> expression min median `itr/sec` mem_alloc `gc/sec`
#> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
#> 1 mm 22.6ms 27ms 34.9 14.2MB 21.3
#> 2 jeremy 254.3ms 273ms 3.66 58.4MB 11.0
File >> New Project >> Java Project With Existing Source>Next >> Project Name(add a name for your project) >> Next>>Add Folder >> select your existing project source code from your Directory>>Next >> Finish
Java Project With Existing Source
svn log -r {2009-09-17}:HEAD
where 2009-09-17
is the date you went on holiday. To see the changed files as well as the summary, add a -v
option:
svn log -r {2009-09-17}:HEAD -v
I haven't used WebSVN but there will be a log viewer somewhere that does the equivalent of these commands under the hood.
The way to do this in .NET Core is (at the time of writing) as follows:
public async Task<IActionResult> YourAction(YourModel model)
{
if (ModelState.IsValid)
{
return StatusCode(200);
}
return StatusCode(400);
}
The StatusCode method returns a type of StatusCodeResult which implements IActionResult and can thus be used as a return type of your action.
As a refactor, you could improve readability by using a cast of the HTTP status codes enum like:
return StatusCode((int)HttpStatusCode.OK);
Furthermore, you could also use some of the built in result types. For example:
return Ok(); // returns a 200
return BadRequest(ModelState); // returns a 400 with the ModelState as JSON
Ref. StatusCodeResult - https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-2.1
If the timestamp considered is a UNIX timestamp You need to first convert UNIX timestamp (e.g 1462567865) to mysql timestamp or data
SELECT * FROM `orders` WHERE FROM_UNIXTIME(order_ts) > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
As c-smile mentioned: Just need to remove the apostrophes in the url()
:
<div style="background-image: url(http://i54.tinypic.com/4zuxif.jpg)"></div>
You're looking for Select
which can be used to transform\project the input sequence:
IEnumerable<string> strings = integers.Select(i => i.ToString());
[email protected] also fixed this bug, just update it:
npm i --save react-router@latest
I see that everybody missed the most important flaw in your code:
strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
should be:
strs = {'HA' 'KU' 'NA' 'MA' 'TATA'}
or
strs = {'HAKUNA' 'MATATA'}
Now if you stick to using
ind=find(ismember(strs,'KU'))
You'll have no worries :).
Your code should look like:
<?php
if ( that_happened ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
if ( something_else_happened ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
// Your function should return FALSE if something goes wrong
if ( !update_database() ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
// the script can also fail on the above line
// e.g. a mysql error occurred
header('HTTP/1.1 200 OK');
?>
I assume you stop execution if something goes wrong.
Another nice package which I used for migrating form a beta version of Angular2 to Angular2 2.0.0 final
is npm-check-updates
It shows the latest available version of all packages specified within your package.json. In contrast to npm outdated
it is also capable to edit your package.json, enabling you to do a npm upgrade
later.
Install
sudo npm install -g npm-check-updates
Usage
ncu
for display
ncu -u
for re-writing your package.json
Yes, it's true. Why do you doubt the php faq on the function? :)
The result of running password_hash()
has has four parts:
So as you can see, the hash is a part of it.
Sure, you could have an additional salt for an added layer of security, but I honestly think that's overkill in a regular php application. The default bcrypt algorithm is good, and the optional blowfish one is arguably even better.
I have created a working CodePen example to demonstrate how you might accomplish your goals.
I added ng-click
to the <form>
and removed the logic from your button:
<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />
Here's the updated template:
<section ng-app="app" ng-controller="MainCtrl">
<form class="well" name="addRelation" data-ng-click="save(model)">
<label>First Name</label>
<input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
<label>Last Name</label>
<input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
<label>Email</label>
<input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
<input class="btn" type="submit" value="SAVE" />
</form>
</section>
and controller code:
app.controller('MainCtrl', function($scope) {
$scope.save = function(model) {
$scope.addRelation.submitted = true;
if($scope.addRelation.$valid) {
// submit to db
console.log(model);
} else {
console.log('Errors in form data');
}
};
});
I hope this helps.
This is a guess at best, but perhaps your development team is building and deploying the application in debug mode, in stead of release mode. This will cause the occurrence of .pdb files. The implication of this is that your application will take up additional resources to collect system state and debugging information during the execution of your system, causing more processor utilization.
So, it would be simple enough to ensure that they are building and deploying in release mode.
Just provide the jQuery val function with an array of values:
var values = "Test,Prof,Off";
$('#strings').val(values.split(','));
And to get the selected values in the same format:
values = $('#strings').val();
As others have noted, most likely you don't have .html
set up to handle php code.
Having said that, if all you're doing is using index.html
to include index.php
, your question should probably be 'how do I use index.php
as index document?
In which case, for Apache (httpd.conf), search for DirectoryIndex
and replace the line with this (will only work if you have dir_module
enabled, but that's default on most installs):
DirectoryIndex index.php
If you use other directory indexes, list them in order of preference i.e.
DirectoryIndex index.php index.phtml index.html index.htm
How does the server know that it should pull image.png from the /pictures folder when you visit the website and browse to the /system/files/images folder in your web browser? A so-called symbolic link is the guy that is responsible for this behavior. Somewhere in your system, there is a symlink that tells your server "If a visitor requests /system/files/images/image.png then show him /pictures/image.png."
And what is the role of the FollowSymLinks setting in this?
FollowSymLinks relates to server security. When dealing with web servers, you can't just leave things undefined. You have to tell who has access to what. The FollowSymLinks setting tells your server whether it should or should not follow symlinks. In other words, if FollowSymLinks was disabled in our case, browsing to the /system/files/images/image.png file would return depending on other settings either the 403 (access forbidden) or 404 (not found) error.
The other way around, if you have problems ADDING the lines to your panel dont forget to add the to your TABLE. By default (http://getbootstrap.com/components/#panels), it is suppose to add the line but It helped me to add the tag so now the row lines are shown.
The following example "probably" wont display the lines between rows:
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Panel heading</div>
<!-- Table -->
<table class="table">
<tr><td> Hi 1! </td></tr>
<tr><td> Hi 2! </td></tr>
</table>
</div>
The following example WILL display the lines between rows:
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Panel heading</div>
<!-- Table -->
<table class="table">
<thead></thead>
<tr><td> Hi 1! </td></tr>
<tr><td> Hi 2! </td></tr>
</table>
</div>
The preceding 0 is used to indicate a number in base 2, 8, or 16.
In my opinion, 0x was chosen to indicate hex because 'x' sounds like hex.
Just my opinion, but I think it makes sense.
Good Day!
jQuery inArray() method is use to search a value in an array and return its index not a Boolean value. And if the value was not found it’ll return -1.
So, to check if a value is present in an array, follow the below practice:
myArray = new Array("php", "tutor");
if( $.inArray("php", myArray) !== -1 ) {
alert("found");
}
create environment variable like in the screenshot and make sure to replace with your sdk path in my case it was C:\Users\zeesh\AppData\Local\Android\sdk replace zeesh with your username and make sure to restart android studio to take effect.
For me, I encountered this error many times,
Error inflating class android.support.design.widget.NavigationView #28 and #29
The solution that works for me is that you must match your support design library and your support appcompat library.
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
For me they must match. :) It works for me!
To state the obvious, the cup represents outerScopeVar
.
Asynchronous functions be like...
You can either wrap the argument in your own class, or wrap the method call in a method that doesn't need to be passed in the primitive type. Then call that method after your delay, and within that method perform the selector you wish to perform.
Your regular expression should be \btrue\b
to get around the 'miscontrue' issue Casper brings up. The full solution would look like this:
string searchText = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
string regexPattern = @"\btrue\b";
int numberOfTrues = Regex.Matches(searchText, regexPattern).Count;
Make sure the System.Text.RegularExpressions namespace is included at the top of the file.
could also happen when your local time is off (e.g. before certificate validation time), this was the case in my error...
Update JQuery for version 1.9.1 link for deletion is here $("#div1").find('button').click(function(){...}
VBA is not VB/VB.NET
The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:
Do While counter < 20
counter = counter + 1
Loop
(But a For..Next might be more appropriate here.)
Happy coding.
If the other answers don't work you can check if something else is using the port with netstat:
netstat -ano | findstr <your port number>
If nothing is already using it, the port might be excluded, try this command to see if the range is blocked by something else:
netsh interface ipv4 show excludedportrange protocol=tcp
In my case build 1 was installed correctly in my mobile using the signed APK (also from Google Play Store). But when I update the application with build 2 for first time, I had an issue installing it with the signed APK as I got "There was a problem parsing the package".
I tried several methods as specified above. But did not work.
After some time, I rerun the commands
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-key.keystore app-release-unsigned.apk myappkeyalias
zipalign -v 4 app-release-unsigned.apk MyApp.apk
and surprisingly, it worked.
It seems sometimes the APK built might be corrupt. So, Re-running jarsigner and zipalign commands resolved my issue.
If you use Kotlin (which works seamlessly with Java), you can make such an enum:
enum class AnsiColor(private val colorNumber: Byte) {
BLACK(0), RED(1), GREEN(2), YELLOW(3), BLUE(4), MAGENTA(5), CYAN(6), WHITE(7);
companion object {
private const val prefix = "\u001B"
const val RESET = "$prefix[0m"
private val isCompatible = "win" !in System.getProperty("os.name").toLowerCase()
}
val regular get() = if (isCompatible) "$prefix[0;3${colorNumber}m" else ""
val bold get() = if (isCompatible) "$prefix[1;3${colorNumber}m" else ""
val underline get() = if (isCompatible) "$prefix[4;3${colorNumber}m" else ""
val background get() = if (isCompatible) "$prefix[4${colorNumber}m" else ""
val highIntensity get() = if (isCompatible) "$prefix[0;9${colorNumber}m" else ""
val boldHighIntensity get() = if (isCompatible) "$prefix[1;9${colorNumber}m" else ""
val backgroundHighIntensity get() = if (isCompatible) "$prefix[0;10${colorNumber}m" else ""
}
And then use is as such: (code below showcases the different styles for all colors)
val sampleText = "This is a sample text"
enumValues<AnsiColor>().forEach { ansiColor ->
println("${ansiColor.regular}$sampleText${AnsiColor.RESET}")
println("${ansiColor.bold}$sampleText${AnsiColor.RESET}")
println("${ansiColor.underline}$sampleText${AnsiColor.RESET}")
println("${ansiColor.background}$sampleText${AnsiColor.RESET}")
println("${ansiColor.highIntensity}$sampleText${AnsiColor.RESET}")
println("${ansiColor.boldHighIntensity}$sampleText${AnsiColor.RESET}")
println("${ansiColor.backgroundHighIntensity}$sampleText${AnsiColor.RESET}")
}
If running on Windows where these ANSI codes are not supported, the isCompatible
check avoids issues by replacing the codes with empty string.
Using bash:
if [ "`mysql -u'USER' -p'PASSWORD' -se'USE $DATABASE_NAME;' 2>&1`" == "" ]; then
echo $DATABASE_NAME exist
else
echo $DATABASE_NAME doesn't exist
fi
If you want to exclude the sub-directories, you can use
git diff <ref1>..<ref2> -- $(git diff <ref1>..<ref2> --name-only | grep -v /)
-- My default settings (this is basically a single-session machine, so work_mem is pretty high)
SET effective_cache_size='2048MB';
SET work_mem='16MB';
\echo original
EXPLAIN ANALYZE
SELECT
COUNT (distinct val) as aantal
FROM one
;
\echo group by+count(*)
EXPLAIN ANALYZE
SELECT
distinct val
-- , COUNT(*)
FROM one
GROUP BY val;
\echo with CTE
EXPLAIN ANALYZE
WITH agg AS (
SELECT distinct val
FROM one
GROUP BY val
)
SELECT COUNT (*) as aantal
FROM agg
;
Results:
original QUERY PLAN
----------------------------------------------------------------------------------------------------------------------
Aggregate (cost=36448.06..36448.07 rows=1 width=4) (actual time=1766.472..1766.472 rows=1 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=31.371..185.914 rows=1499845 loops=1)
Total runtime: 1766.642 ms
(3 rows)
group by+count(*)
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------
HashAggregate (cost=36464.31..36477.31 rows=1300 width=4) (actual time=412.470..412.598 rows=1300 loops=1)
-> HashAggregate (cost=36448.06..36461.06 rows=1300 width=4) (actual time=412.066..412.203 rows=1300 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=26.134..166.846 rows=1499845 loops=1)
Total runtime: 412.686 ms
(4 rows)
with CTE
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------
Aggregate (cost=36506.56..36506.57 rows=1 width=0) (actual time=408.239..408.239 rows=1 loops=1)
CTE agg
-> HashAggregate (cost=36464.31..36477.31 rows=1300 width=4) (actual time=407.704..407.847 rows=1300 loops=1)
-> HashAggregate (cost=36448.06..36461.06 rows=1300 width=4) (actual time=407.320..407.467 rows=1300 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=24.321..165.256 rows=1499845 loops=1)
-> CTE Scan on agg (cost=0.00..26.00 rows=1300 width=0) (actual time=407.707..408.154 rows=1300 loops=1)
Total runtime: 408.300 ms
(7 rows)
The same plan as for the CTE could probably also be produced by other methods (window functions)
Instead of window
use global
it('correct url is called', () => {
global.open = jest.fn();
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
you could also try
const open = jest.fn()
Object.defineProperty(window, 'open', open);
You must first convert your timestamps to Python datetime
objects (use datetime.strptime
). Then use date2num
to convert the dates to matplotlib format.
Plot the dates and values using plot_date
:
dates = matplotlib.dates.date2num(list_of_datetimes)
matplotlib.pyplot.plot_date(dates, values)
First you need to create the config file, using cmd :
jupyter notebook --generate-config
Then, search for C:\Users\your_username\.jupyter folder (Search for that folder), and right click edit the jupyter_notebook_config.py.
Then, Ctrl+F: #c.NotebookApp.notebook_dir ='' . Note that the quotes are single quotes. Select your directory you want to have as home for your jupyter, and copy it with Ctrl+C, for example: C:\Users\username\Python Projects.
Then on that line, paste it like this : c.NotebookApp.notebook_dir = 'C:\\Users\\username\\Python Projects'
Make sure to remove #, as it is as comment.
Make sure to double slash \\ on each name of your path. Ctrl+S to save the config.py file !!!
Go back to your cmd and run jupyter notebook.
It should be in your directory of choice. Test it by making a folder and watch your directory from your computer.
Test-Path
can be used with a special syntax:
Test-Path variable:global:foo
This also works for environment variables ($env:foo
):
Test-Path env:foo
And for non-global variables (just $foo
inline):
Test-Path variable:foo
You are on share environment and cannot find error log, always check if cPanel has option Errors on your cPanel dashboard. If you are not being able to find error log, then you can find it there .
On cPanel search bar, search Error, it will show Error Pages which are basically lists of different http error pages and other Error is where the error logs are displayed.
Other places to look on shared environment: /home/yourusername/logs /home/yourusername/public_html/error_log
This ORA error is occurred because of violation of unique constraint.
ORA-00001: unique constraint (constraint_name) violated
This is caused because of trying to execute an INSERT
or UPDATE
statement that has created a duplicate value in a field restricted by a unique index.
You can resolve this either by
You should not trust $_FILES['upfile']['mime']
, check MIME type by yourself. For that purpose, you may use fileinfo
extension, enabled by default as of PHP 5.3.0.
$fileInfo = new finfo(FILEINFO_MIME_TYPE);
$fileMime = $fileInfo->file($_FILES['upfile']['tmp_name']);
$validMimes = array(
'zip' => 'application/zip',
'rar' => 'application/x-rar',
);
$fileExt = array_search($fileMime, $validMimes, true);
if($fileExt != 'zip' && $fileExt != 'rar')
throw new RuntimeException('Invalid file format.');
NOTE: Don't forget to enable the extension in your php.ini
and restart your server:
extension=php_fileinfo.dll
Java SE = Standard Edition. This is the core Java programming platform. It contains all of the libraries and APIs that any Java programmer should learn (java.lang, java.io, java.math, java.net, java.util, etc...).
Java EE = Enterprise Edition. From Wikipedia:
The Java platform (Enterprise Edition) differs from the Java Standard Edition Platform (Java SE) in that it adds libraries which provide functionality to deploy fault-tolerant, distributed, multi-tier Java software, based largely on modular components running on an application server.
In other words, if your application demands a very large scale, distributed system, then you should consider using Java EE. Built on top of Java SE, it provides libraries for database access (JDBC, JPA), remote method invocation (RMI), messaging (JMS), web services, XML processing, and defines standard APIs for Enterprise JavaBeans, servlets, portlets, Java Server Pages, etc...
Java ME = Micro Edition. This is the platform for developing applications for mobile devices and embedded systems such as set-top boxes. Java ME provides a subset of the functionality of Java SE, but also introduces libraries specific to mobile devices. Because Java ME is based on an earlier version of Java SE, some of the new language features introduced in Java 1.5 (e.g. generics) are not available.
If you are new to Java, definitely start with Java SE.
This prints all elements that contain sub:
for s in filter (lambda x: sub in x, list): print (s)
proceed = "y", "Y"
if answer in proceed:
Also, you don't want
answer = str(input("Is the information correct? Enter Y for yes or N for no"))
You want
answer = raw_input("Is the information correct? Enter Y for yes or N for no")
input()
evaluates whatever is entered as a Python expression, raw_input()
returns a string.
Edit: That is only true on Python 2. On Python 3, input
is fine, although str()
wrapping is still redundant.
@Stephen Bailey
To complete your answer, you can also delegate the user rights to the project manager, through a plain text file in your repository.
To do that, you set up your SVN database with a default authz
file containing the following:
###########################################################################
# The content of this file always precedes the content of the
# $REPOS/admin/acl_descriptions.txt file.
# It describes the immutable permissions on main folders.
###########################################################################
[groups]
svnadmins = xxx,yyy,....
[/]
@svnadmins = rw
* = r
[/admin]
@svnadmins = rw
@projadmins = r
* =
[/admin/acl_descriptions.txt]
@projadmins = rw
This default authz
file authorizes the SVN administrators to modify a visible plain text file within your SVN repository, called '/admin/acl_descriptions.txt', in which the SVN administrators or project managers will modify and register the users.
Then you set up a pre-commit hook which will detect if the revision is composed of that file (and only that file).
If it is, this hook's script will validate the content of your plain text file and check if each line is compliant with the SVN syntax.
Then a post-commit hook will update the \conf\authz
file with the concatenation of:
authz
file presented above/admin/acl_descriptions.txt
The first iteration is done by the SVN administrator, who adds:
[groups]
projadmins = zzzz
He commits his modification, and that updates the authz
file.
Then the project manager 'zzzz' can add, remove or declare any group of users and any users he wants.
He commits the file and the authz
file is updated.
That way, the SVN administrator does not have to individually manage any and all users for all SVN repositories.
In VB.NET, you need to use the GetType
method to retrieve the type of an instance of an object, and the GetType()
operator to retrieve the type of another known type.
Once you have the two types, you can simply compare them using the Is
operator.
So your code should actually be written like this:
Sub FillCategories(ByVal Obj As Object)
Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
cmd.CommandType = CommandType.StoredProcedure
Obj.DataSource = cmd.ExecuteReader
If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then
End If
Obj.DataBind()
End Sub
You can also use the TypeOf
operator instead of the GetType
method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:
If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then
End If
Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.
Why nobody mentioned docker-compose
! I 've just been using it for one week, and I cannot survive without it. All you need is writing a yml which takes only several minutes of studying, and then you are ready to go. It can boot images, containers (which are needed in so-called services) and let you review logs just like you use with docker native commands. Git it a try:
docker-compose up -d
docker-compose down --rmi 'local'
Before I used docker-compose, I wrote my own shell script, then I had to customize the script whenever needed especially when application architecture changed. Now I don't have to do this anymore, thanks to docker-compose.
The to_yaml
method seems to be useful sometimes:
$foo = {:name => "Clem", :age => 43}
puts $foo.to_yaml
returns
---
:age: 43
:name: Clem
(Does this depend on some YAML
module being loaded? Or would that typically be available?)
The recent openssh version deprecated DSA keys by default. You should suggest to your GIT provider to add some reasonable host key. Relying only on DSA is not a good idea.
As a workaround, you need to tell your ssh
client that you want to accept DSA host keys, as described in the official documentation for legacy usage. You have few possibilities, but I recommend to add these lines into your ~/.ssh/config
file:
Host your-remote-host
HostkeyAlgorithms +ssh-dss
Other possibility is to use environment variable GIT_SSH
to specify these options:
GIT_SSH_COMMAND="ssh -oHostKeyAlgorithms=+ssh-dss" git clone ssh://user@host/path-to-repository
Since the hosts is blocked. try connect it from other host and execute the mysqladmin flush-hosts command.
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
It is an "INEQUALITY" operator. Get a list of comparison operators in VBA
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
Shows all the stored procedures:
SHOW PROCEDURE STATUS;
Shows all the functions:
SHOW FUNCTION STATUS;
Shows the definition of the specified procedure:
SHOW CREATE PROCEDURE [PROC_NAME];
Shows you all the procedures of the given database:
SHOW PROCEDURE STATUS WHERE Db = '[db_name]';
I faced this same issue on CentOS 7 years later
Posting hoping that it may help others...
Steps:
FIRST, configure the php-fpm settings:
-> systemctl stop php-fpm.service
-> cd /etc/php-fpm.d
-> ls -hal
(should see a www.conf file)
-> cp www.conf www.conf.backup
(back file up just in case)
-> vi www.conf
-> :/listen =
(to get to the line we need to change)
-> i
(to enter VI's text insertion mode)
-> change from listen = 127.0.0.1:9000
TO listen = /var/run/php-fpm/php-fpm.sock
-> Esc
then :/listen.owner
(to find it) then i
(to change)
-> UNCOMMENT the listen.owner = nobody
AND listen.group = nobody
lines
-> Hit Esc
then type :/user =
then i
-> change user = apache
TO user = nginx
-> AND change group = apache
TO group = nginx
-> Hit Esc
then :wq
(to save and quit)
-> systemctl start php-fpm.service
(now you will have a php-fpm.sock file)
SECOND, you configure your server {}
block in your /etc/nginx/nginx.conf
file. Then run:systemctl restart nginx.service
FINALLY, create a new .php file in your /usr/share/nginx/html directory for your Nginx server to serve up via the internet browser as a test.
-> vi /usr/share/nginx/html/mytest.php
-> type o
-> <?php echo date("Y/m/d-l"); ?>
(PHP page will print date and day in browser)
-> Hit Esc
-> type :wq
(to save and quite VI editor)
-> open up a browser and go to: http://yourDomainOrIPAddress/mytest.php
(you should see the date and day printed)
Here is the way I look at COALESCE...and hopefully it makes sense...
In a simplistic form….
Coalesce(FieldName, 'Empty')
So this translates to…If "FieldName" is NULL, populate the field value with the word "EMPTY".
Now for mutliple values...
Coalesce(FieldName1, FieldName2, Value2, Value3)
If the value in Fieldname1 is null, fill it with the value in Fieldname2, if FieldName2 is NULL, fill it with Value2, etc.
This piece of test code for the AdventureWorks2012 sample database works perfectly & gives a good visual explanation of how COALESCE works:
SELECT Name, Class, Color, ProductNumber,
COALESCE(Class, Color, ProductNumber) AS FirstNotNull
FROM Production.Product
Here's a simple one that worked for me. It checks whether the path exists, and if it doesn't, it will create not only the root path, but all sub-directories also:
$rptpath = "C:\temp\reports\exchange"
if (!(test-path -path $rptpath)) {new-item -path $rptpath -itemtype directory}
com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to finalize session : INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package [MY REACT NATIVE APP NAME HERE] signatures do not match the previously installed version; ignoring!
I got this error when trying to install my React Native Android app on a connected device using this command:
react-native run-android --variant=release
I also had an emulator running on my computer.
Once I quit the emulator, running this command succeeded.
setval('sequence_name', sequence_value)
You can see a detailed description here.
ini_set('display_errors', 1);
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
Changelog
5.4.0 E_STRICT became part of E_ALL
5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.
5.2.0 E_RECOVERABLE_ERROR introduced.
5.0.0 E_STRICT introduced (not part of E_ALL).
Here's my understanding (non-authoritative):
ODBC is a technology-agnostic open standard supported by most software vendors. OLEDB is a technology-specific Microsoft's API from the COM-era (COM was a component and interoperability technology before .NET)
At some point various datasouce vendors (e.g. Oracle etc.), willing to be compatible with Microsoft data consumers, developed OLEDB providers for their products, but for the most part OLEDB remains a Microsoft-only standard. Now, most Microsoft data sources allow both ODBC and OLEDB access, mainly for compatibility with legacy ODBC data consumers. Also, there exists OLEDB provider (wrapper) for ODBC which allows one to use OLEDB to access ODBC data sources if one so wishes.
In terms of the features OLEDB is substantially richer than ODBC but suffers from one-ring-to-rule-them-all syndrome (overly generic, overcomplicated, non-opinionated).
In non-Microsoft world ODBC-based data providers and clients are widely used and not going anywhere.
Inside Microsoft bubble OLEDB is being phased out in favor of native .NET APIs build on top of whatever the native transport layer for that data source is (e.g. TDS for MS SQL Server).
You must have either disabled
, froze
or uninstalled
FaceProvider in settings>applications>all
This will only happen if it's frozen
, either uninstall
it, or enable
it.
function alertWithoutNotice(message){
setTimeout(function(){
alert(message);
}, 1000);
}
I do it this way:
https://en.wikipedia.org/w/api.php?action=opensearch&search=bee&limit=1&format=json
The response you get is an array with the data, easy to parse:
[
"bee",
[
"Bee"
],
[
"Bees are flying insects closely related to wasps and ants, known for their role in pollination and, in the case of the best-known bee species, the European honey bee, for producing honey and beeswax."
],
[
"https://en.wikipedia.org/wiki/Bee"
]
]
To get just the first paragraph limit=1
is what you need.
You can also do this with Pandas:
Using a 2356-long array:
import numpy as np
xs = np.array([...])
Using scipy:
from scipy.ndimage.interpolation import shift
%timeit shift(xs, 1, cval=np.nan)
# 956 µs ± 77.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Using Pandas:
import pandas as pd
%timeit pd.Series(xs).shift(1).values
# 377 µs ± 9.42 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In this example, using Pandas was about ~8 times faster than Scipy
int arr[] = new int[15];
The variable arr
holds a memory address. At the memory address, there are 15 consecutive ints in a row. They can be referenced with index 0 to 14 inclusive.
In php i can just do this arr[]=22; this will automatically add 22 to the next empty index of array.
There is no concept of 'next' when dealing with arrays.
One important thing that I think you are missing is that as soon as the array is created, all elements of the array already exist. They are uninitialized, but they all do exist already. So you aren't 'filling' the elements of the array as you go, they are already filled, just with uninitialized values. There is no way to test for an uninitialized element in an array.
It sounds like you want to use a data structure such as a queue or stack or vector.
This is what I would do:
#include <cmath>
int roundUp(int numToRound, int multiple)
{
// if our number is zero, return immediately
if (numToRound == 0)
return multiple;
// if multiplier is zero, return immediately
if (multiple == 0)
return numToRound;
// how many times are number greater than multiple
float rounds = static_cast<float>(numToRound) / static_cast<float>(multiple);
// determine, whether if number is multiplier of multiple
int floorRounds = static_cast<int>(floor(rounds));
if (rounds - floorRounds > 0)
// multiple is not multiplier of number -> advance to the next multiplier
return (floorRounds+1) * multiple;
else
// multiple is multiplier of number -> return actual multiplier
return (floorRounds) * multiple;
}
The code might not be optimal, but I prefer clean code than dry performance.
A derived class is not the the same class as its base class and you may or may not care whether any members of the base class are initialized at the time of the construction of the derived class. That is a determination made by the programmer not by the compiler.
Try the JavaScriptSerializer instead of the DataContractJsonSerializer
JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);
You can combine the two functions; coerce to characters thence to numerics:
> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2
Use the HTML
<div id="full-size">
<div id="wrapper">
Your content goes here.
</div>
</div>
and use the CSS:
html, body {margin:0;padding:0;height:100%;}
#full-size {
height:100%;
width:100%;
position:absolute;
top:0;
left:0;
overflow:hidden;
}
#wrapper {
/*You can add padding and margins here.*/
padding:0;
margin:0;
}
Make sure that the HTML is in the root element.
Hope this helps!
jQuery now has a CDN access:
code.jquery.com/ui/[version]/themes/[theme name]/jquery-ui.css
And to make this a little more easy, Here you go:
I'd this issue on Linux Mint (Maya) 13, And I fixed it by Installing postgresql and postgresql-server :
apt-get install postgresql-9.1
sudo apt-get install postgresql-server-dev-9.1
Practically speaking, if the keys were of type NaN, the browser will not change the order.
The following script will output "One", "Two", "Three":
var foo={"3":"Three", "1":"One", "2":"Two"};
for(bar in foo) {
alert(foo[bar]);
}
Whereas the following script will output "Three", "One", "Two":
var foo={"@3":"Three", "@1":"One", "@2":"Two"};
for(bar in foo) {
alert(foo[bar]);
}
theharshest answered the question but here is another way to do the same thing. Also, In your example you have NAME in caps and in your code you have name in lowercase.
s = '<div class="question" id="get attrs" name="python" x="something">Hello World</div>'
soup = BeautifulSoup(s)
attributes_dictionary = soup.find('div').attrs
print attributes_dictionary
# prints: {'id': 'get attrs', 'x': 'something', 'class': ['question'], 'name': 'python'}
print attributes_dictionary['class'][0]
# prints: question
print soup.find('div').get_text()
# prints: Hello World
break
and continue
breaks the readability for the reader, although it's often useful.
Not as much as "goto" concept, but almost.
Besides, if you take some new languages like Scala (inspired by Java and functional programming languages like Ocaml), you will notice that break
and continue
simply disappeared.
Especially in functional programming, this style of code is avoided:
Why scala doesn't support break and continue?
To sum up: break
and continue
are widely used in Java for an imperative style, but for any coders that used to practice functional programming, it might be.. weird.
I liked galloglas's code, and I changed the main function so that it shows a sorted list of total size by application:
verbose = True
if __name__ == '__main__':
mbdb = process_mbdb_file("Manifest.mbdb")
mbdx = process_mbdx_file("Manifest.mbdx")
sizes = {}
for offset, fileinfo in mbdb.items():
if offset in mbdx:
fileinfo['fileID'] = mbdx[offset]
else:
fileinfo['fileID'] = "<nofileID>"
print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
print fileinfo_str(fileinfo, verbose)
if (fileinfo['mode'] & 0xE000) == 0x8000:
sizes[fileinfo['domain']]= sizes.get(fileinfo['domain'],0) + fileinfo['filelen']
for domain in sorted(sizes, key=sizes.get):
print "%-60s %11d (%dMB)" % (domain, sizes[domain], int(sizes[domain]/1024/1024))
That way you can figure out what application is eating all that space.
The following is something I used that worked for me across browsers so I hope it helps someone in the future:
#contentblock th:first-child {
-moz-border-radius: 6px 0 0 0;
-webkit-border-radius: 6px 0 0 0;
border-radius: 6px 0 0 0;
behavior: url(/images/border-radius.htc);
border-radius: 6px 0 0 0;
}
#contentblock th:last-child {
-moz-border-radius: 0 6px 0 0;
-webkit-border-radius: 0 6px 0 0;
border-radius: 0 6px 0 0;
behavior: url(/images/border-radius.htc);
border-radius: 0 6px 0 0;
}
#contentblock tr:last-child td:last-child {
border-radius: 0 0 6px 0;
-moz-border-radius: 0 0 6px 0;
-webkit-border-radius: 0 0 6px 0;
behavior: url(/images/border-radius.htc);
border-radius: 0 0 6px 0;
}
#contentblock tr:last-child td:first-child {
-moz-border-radius: 0 0 0 6px;
-webkit-border-radius: 0 0 0 6px;
border-radius: 0 0 0 6px;
behavior: url(/images/border-radius.htc);
border-radius: 0 0 0 6px;
}
Obviously the #contentblock
portion can be replaced/edited as needed and you can find the border-radius.htc
file by doing a search in Google or your favorite web browser.
you can use a generator:
li = [1,2,3,4,5,6]
len_li = len(li)
gen = (len_li-1-i for i in range(len_li))
finally:
for i in gen:
print(li[i])
hope this help you.
Check out this screenshot (Toogle Word Wrap):
I followed all of those instructions including the instructions from Android. What finally fixed it for me was changing Project Build Target from API level to API level 21 in my project.
I am using API 22 (Android 5.1.1), which is newer than when these other answers were written. So you cannot set target=21 in the support library as you could 6 months ago.
My usual trick is to simply print sys.path
in the actual context where the import problem happens. In your case it'd seem that the place for the print is in /home/hughdbrown/.local/bin/pserve
. Then check dirs & files in the places that path shows..
You do that by first having:
import sys
and in python 2 with print expression:
print sys.path
or in python 3 with the print function:
print(sys.path)
I was facing this issue in Grafana and all I had to do was go to the config file and change allow_embedding to true and restart the server :)
Counting the number of lines can be done by following codes:
<?php
$fp= fopen("myfile.txt", "r");
$count=0;
while($line = fgetss($fp)) // fgetss() is used to get a line from a file ignoring html tags
$count++;
echo "Total number of lines are ".$count;
fclose($fp);
?>
In case someone else is brought here by google because they were trying to use a variable for a method within a class, the below is a code sample which will actually work. None of the above worked for my situation. The key difference is the &
in the declaration of $c = & new...
and &$c
being passed in call_user_func
.
My specific case is when implementing someone's code having to do with colors and two member methods lighten()
and darken()
from the csscolor.php class. For whatever reason, I wanted to have the same code be able to call lighten or darken rather than select it out with logic. This may be the result of my stubbornness to not just use if-else or to change the code calling this method.
$lightdark="lighten"; // or optionally can be darken
$color="fcc"; // a hex color
$percent=0.15;
include_once("csscolor.php");
$c = & new CSS_Color($color);
$rtn=call_user_func( array(&$c,$lightdark),$color,$percent);
Note that trying anything with $c->{...}
didn't work. Upon perusing the reader-contributed content at the bottom of php.net's page on call_user_func
, I was able to piece together the above. Also, note that $params
as an array didn't work for me:
// This doesn't work:
$params=Array($color,$percent);
$rtn=call_user_func( array(&$c,$lightdark),$params);
This above attempt would give a warning about the method expecting a 2nd argument (percent).
Thanks to your comments. I've made a function that give an error message when it happens:
/**
* Replaces a string in a file
*
* @param string $FilePath
* @param string $OldText text to be replaced
* @param string $NewText new text
* @return array $Result status (success | error) & message (file exist, file permissions)
*/
function replace_in_file($FilePath, $OldText, $NewText)
{
$Result = array('status' => 'error', 'message' => '');
if(file_exists($FilePath)===TRUE)
{
if(is_writeable($FilePath))
{
try
{
$FileContent = file_get_contents($FilePath);
$FileContent = str_replace($OldText, $NewText, $FileContent);
if(file_put_contents($FilePath, $FileContent) > 0)
{
$Result["status"] = 'success';
}
else
{
$Result["message"] = 'Error while writing file';
}
}
catch(Exception $e)
{
$Result["message"] = 'Error : '.$e;
}
}
else
{
$Result["message"] = 'File '.$FilePath.' is not writable !';
}
}
else
{
$Result["message"] = 'File '.$FilePath.' does not exist !';
}
return $Result;
}
I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)
I've tested this on Twenty Fifteen and it's working, so it should be working for you.
In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 8
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<div id="more_posts">Load More</div>
This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with
$cat_id = get_query_var('cat');
This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like
<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>
And pull the category with
var cat = $('#more_posts').data('category');
But for now, you can leave this out.
Next in functions.php I added
wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'twentyfifteen'),
));
Right after the existing wp_localize_script
. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.
At the end of the functions.php file I added the function that will load your posts:
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-12 large-4 columns">
<h1>'.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.
If you've added your category in the loader, you'd add:
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';
And instead of 8, you'd put $cat
. This will be in the $_POST
array, and you'll be able to use it in ajax.
Last part is the ajax itself. In functions.js I put inside the $(document).ready();
enviroment
var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
Saved it, tested it, and it works :)
Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD
UPDATE
For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;
) you can try with
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
This should run the load_posts()
function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer
$(window).on('scroll', function(){
if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
load_posts();
}
}
});
Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100
or $('footer').offset().top
for some reason. If that should happen, just increase the number where the scroll goes to.
You can easily check it by putting console.log
s in your code and see in the inspector what they throw out
$(window).on('scroll', function () {
console.log($(window).scrollTop() + $(window).height());
console.log($(document).height() - 100);
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
And just adjust accordingly ;)
Hope this helps :) If you have any questions just ask.
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
What you are doing is to look for (0) or (1) results.
(cnt >= 10 && cnt <= 20) returns either true or false.
--edit-- you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length. --edit--
If the command contains some special characters such as pipes and quotes, the command needs to be padded with quotes. For example, to repeat ls -l | grep "txt"
, the watch command should be:
watch -n 5 'ls -l | grep "txt"'
String localFormat = android.text.format.DateFormat.getBestDateTimePattern(Locale.getDefault(), "EEEE MMMM d");
return new SimpleDateFormat(localFormat, Locale.getDefault()).format(localMidnight);
will return a format based on device's language. Note that getBestDateTimePattern() returns "the best possible localized form of the given skeleton for the given locale"
As others have said, a functional interface is an interface which exposes one method. It may have more than one method, but all of the others must have a default implementation. The reason it's called a "functional interface" is because it effectively acts as a function. Since you can pass interfaces as parameters, it means that functions are now "first-class citizens" like in functional programming languages. This has many benefits, and you'll see them quite a lot when using the Stream API. Of course, lambda expressions are the main obvious use for them.
You can also do like this:
private void button2_Click(object sender, EventArgs e)
{
System.Windows.Forms.Application.ExitThread();
}
open your adt and open preferences, then modify directory with your sdk dir, it may help you follow the pic link indication
I believe the main (only?) different is inheritance:
class T < S
end
p T.k
=> 23
S.k = 24
p T.k
=> 24
p T.s
=> nil
Class variables are shared by all "class instances" (i.e. subclasses), whereas class instance variables are specific to only that class. But if you never intend to extend your class, the difference is purely academic.
I found the answer to use double and triple quotation marks unsatisfactory. I used a nested DO...LOOP to write an ASP segment of code. There are repeated quotation marks within the string. When I ran the code:
thestring = "<asp:RectangleHotSpot Bottom=""" & bottom & """ HotSpotMode=""PostBack"" Left="""& left & """ PostBackValue=""" &xx & "." & yy & """ Right=""" & right & """ Top=""" & top & """/>"
the output was: <`asp:RectangleHotSpot Bottom="28
'Changing the code to the explicit chr() call worked:
thestring = "<asp:RectangleHotSpot Bottom=""" & bottom & chr(34) & " HotSpotMode=""PostBack"" Left="""& left & chr(34) & " PostBackValue=""" &xx & "." & yy & chr(34) & " Right=""" & right & chr(34) & " Top=""" & top & chr(34) &"/>"
The output:
<asp:RectangleHotSpot Bottom="28" HotSpotMode="PostBack" Left="0" PostBackValue="0.0" Right="29" Top="0"/>
Simply save it with a .pyw
extension. This will prevent the console window from opening.
On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.
a couple years down the road, I'd vote for three.js because
ie 11 supports webgl (to what extent I can't assure you since i'm usually in chrome)
and, as far as importing external models into three.js, here's a link to mrdoob's updated loaders (so many!)
UPDATE nov 2019: the THREE.js loaders are now far more and it makes little sense to post them all: just go to this link
http://threejs.org/examples and review the loaders - at least 20 of them
I make moving the files and then do
git add -A
which put in the sataging area all deleted/new files. Here git realizes that the file is moved.
git commit -m "my message"
git push
I do not know why but this works for me.
What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient
request.
At worst, it won't work.
You can try
//ios
shadowOpacity: 0.3,
shadowRadius: 3,
shadowOffset: {
height: 0,
width: 0
},
//android
elevation: 1
"return" does exit the function but if you want to return large sums of data, you can store it in an array and then return it instead of trying to returning each piece of data 1 by 1 in the loop.
str
in Python is represented in Unicode
.UTF-8
is an encoding standard to encode Unicode
string to bytes
. There are many encoding standards out there (e.g. UTF-16
, ASCII
, SHIFT-JIS
, etc.).When the client sends data to your server and they are using UTF-8
, they are sending a bunch of bytes
not str
.
You received a str
because the "library" or "framework" that you are using, has implicitly converted some random bytes
to str
.
Under the hood, there is just a bunch of bytes
. You just need ask the "library" to give you the request content in bytes
and you will handle the decoding yourself (if library can't give you then it is trying to do black magic then you shouldn't use it).
UTF-8
encoded bytes
to str
: bs.decode('utf-8')
str
to UTF-8
bytes
: s.encode('utf-8')
Actually, even that didn't work for me. When I executed "select dbms_metadata.get_ddl('TABLESPACE','TABLESPACE_NAME') from dual;" I again got only the first three lines, but this time each line was padded out to 15,000 characters. I was able to work around this with:
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),80) from dual;
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),160) from dual;
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),240) from dual;
It sure seemed like there ought to be an easier way, but I couldn't seem to find it.